Git Product home page Git Product logo

cloud-sdk-ios-cai's Introduction

The SAPCAI Swift Package is a module to connect to a bot on the end-to-end chatbot platform SAP Conversational AI (CAI). It provides a pluggable SwiftUI AssistantView to initiate a conversation and render the various message types of a bot.

This Swift Package is an open-source addition to the SAP BTP SDK for iOS.

SwiftUI AssistantView

Requirements

Latest version

  • iOS 14 or higher
  • Xcode 12 (Swift 5.3) or higher
Previous versions

Version 1.0.x

  • iOS 13 or higher
  • Xcode 12 (Swift 5.3) or higher

Prerequisites

  • You have existing bot(s) on the SAP Conversational AI platform
  • You have created an OAuth client for Designtime API for your bot (Settings > Tokens)
  • Your bot(s) are connected to a mobile channel

Create a Mobile Channel

In SAP Conversational AI you create a mobile channel via the "Connect" tab of your bot.

CreateMobileChannel

CreateMobileChannelResults

Dependencies

  • SAPCommon for Logging
  • SAPFoundation for Network Connectivity and Authentication
  • SDWebImage for asynchronous image loading and gif animation in SwiftUI
  • Down for Markdown / CommonMark rendering in Swift

Installation

The package is intended for consumption via Swift Package Manager. To add SAPCAI to your application target, navigate to the File > Add Packages... >. Use the Search or Enter Package URL field to find the package using the repository URL https://github.com/SAP/cloud-sdk-ios-cai.

You can choose one of the following package products to be added to your application/framework target.

Package Product When to Use
SAPCAI You did not already embed binary frameworks from SAP BTP SDK for iOS
SAPCAI-requiresToEmbedXCFrameworks You already embedded SAPCommon and SAPFoundation binary frameworks to your target

Getting Started

The code snippet below illustrates setting up the CAIConversation Combine publisher to initialize the MessagingViewModel for the AssistantView. For prototyping you can connect the iOS client directly with SAP Conversational AI Community Edition. You have to replace variable values in angle brackets (e.g. <channelId>) with your bot-specific values.

See the Enterprise Configuration guide for the required configuration steps to use SAPCAI Swift package and connect indirectly with SAP Conversational AI Enterprise Edition through SAP Mobile Services.

Setting up the Data Publisher

import SAPCAI
import SAPFoundation
import SwiftUI

/*
  Create the `CAIChannel` object by providing the channel id, channel token, and channel slug of your mobile channel. Values can be looked up in CAI platform.

  If you do not want to hardcode channel information on the client, you can retrieve a list of channels for a given Application ID with `CAIChannelService`.
*/
let caiChannel = CAIChannel(id: "<channelId>", token: "<channelToken>", slug: "<channelSlug>")

// Create CAI service config for a SAPURLSession and URL pointing to CAI API endpoint
let serviceConfig = CAIServiceConfig(urlSession: SAPURLSession(), host: URL(string:"<Example: https://api.cai.tools.sap>")!)
     
// Provide the message delivery object for polling
let polling: MessageDelivering = PollMessageDelivery(channelId: "<channelId>", serviceConfig: serviceConfig)
   
// Create CAIConversation object and use it as publisher
let dataPublisher = CAIConversation(config: serviceConfig, channel: caiChannel, messageDelivery: polling)

// Create view model for `AssistantView`
let viewModel = MessagingViewModel(publisher: dataPublisher)

User Interface

Using the SwiftUI implementation is the preferred approach.

// `NavigationView` must be present in your view hierachy as `AssistantView` makes use of `NavigationLink`
AssistantView()
  .navigationTitle(Text("Chat")) // if you are in navigation controller
  .environmentObject(viewModel)
  .environmentObject(ThemeManager.shared)
  .onDisappear {
    // you cannot rely on the fact that onDisappear will be called only
    // once because `AssistantView` might trigger further navigations
    // causing the `AssistantView` to disappear and re-appear.
    // Therefore cleanup logic should be handled elsewhere.
  })

but SAPCAI also provides a UIKit wrapper

let vc = MessagingViewController(MessagingViewModel(publisher: dataPublisher))

self.navigationController?.pushViewController(vc, animated: true)

Cleanup

Once a conversation has ended you need to call the following functions to avoid memory leaks and unnecessary network requests. Also MessagingViewModel cannot be deallocated otherwise.

viewModel.cancelSubscriptions()
dataPublisher.resetConversation()

SAPCAI uses SDWebImage and its image caching capabilities but it is the app developers responsibility to clear the cache if that is desired. Example:

SDImageCache.shared.clearMemory()
SDImageCache.shared.clearDisk(onCompletion: nil)

Theming

SAPCAI will provide two standard themes

  • a Fiori theme and
  • a Casual theme (no longer maintained)

Themes

Each theme will come with a color palette that supports both light and dark modes.

Fiori Theme

ThemeManager.shared.setCurrentTheme( .fiori(FioriColorPalette()) )

Casual Theme

No longer maintained and therefore marked as deprecated. Do not use!

ThemeManager.shared.setCurrentTheme( .casual(CasualColorPalette()) )

Create Your Own Custom Theme

You can also provide an alternative color palette or provide a custom theme.

Persistent Static Menu

In SAP Conversational AI you can add persistent static menu options to your chatbot enabling your users to quickly trigger links or skills at any point during the conversation.

Persistent Static Menu In Bot Builder

Use CAIChannelService.loadPreferences to fetch your channel's preferences (incl. the persistent static menu) asynchronously, then set MessagingViewModel.menu.

service.loadPreferences(channel: channel) { result in
  DispatchQueue.main.async {
    switch result {
      case .success(let data):
        viewModel.menu = data?.menu
      case .failure:
        break
    }
  }
}

Persistent Static Menu Rendered by SAP CAI SDK for iOS

Limitations

Markdown Related

Trigger Skill Button Related

  • Trigger Skill buttons are still enabled after execution / next interaction. This behavior differs from the SAP CAI Web Client. Once you click the button or type an utterance, the corresponding skill can't be triggered anymore at a later point in time since the context in which it was created might not be valid anymore.

Image Related

  • Not being able to save, copy, or share an image as part of a bot response. Currently, there is no gesture handler attached to an image view which could allow opening a contextual menu offering such features (similar to iMessage or WhatsApp).

How to Obtain Support

Please raise an issue on GitHub. SAP customers can continue to report issues through OSS for SLA tracking.

Raise questions around CAI in the SAP CAI Answers forum.

Contributing

If you want to contribute, please check the Contribution Guidelines.

Examples

The CAITestApp in this repository allows you to

  • choose a theme
  • view static mock data or
  • connect against a live system by either
    • letting the user choose the mobile channel from the list of available mobile channels for given Application ID (a.k.a targetSystem); note: this illustrates the use of CAIChannelService and how to build a simple SwiftUI view on top of it
    • loading the AssistantView for a specific mobile channel

See here on how to maintain connection settings for the test application.

cloud-sdk-ios-cai's People

Contributors

ajinkyapatil8190 avatar jyguyomarch avatar kevinriedelsheimer avatar marcoeidinger avatar service-tip-git avatar shadowtourist avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

cloud-sdk-ios-cai's Issues

Persistent Static Menu shows postback/link value as subtitle

SAP Conversational AI SDK for iOS renders not only the display text but also the postback/link value in the persistent static menu

Issue

This is a different behavior than the SAP CAI Web Client.

Also this behavior is problematic as the postback/link value may contain non-user friendly text or (even worse) sensitive information

The goal is to render only the display text.

Fixed

ScrollView contentSize and offset incorrect when loading existing conversation with images

Loading a conversation with multiple images may lead to the effect that scroll view size and offset is incorrect and that the user cannot scroll to and see content at the very top or very bottom.

Simulator.Screen.Recording.-.iPhone.11.-.2021-06-03.at.15.24.52.mp4

As a manual workaround, the user can click on the input field (i.e setting its focus and retriggering view updates) which will correct the scroll view size and offset.

Persistent Static Menu is not rendered

Using CAIChannelService.loadPreferences to fetch information about Persistent Static Menu fails due to serialization error

        // load preferences for this channel
        service.loadPreferences(channel: channel) { result in
            DispatchQueue.main.async {
                switch result {
                case .success(let data):
                    viewModel.menu = data?.menu
                case .failure:
                    break
                }
            }
        }

Hence, Persistent Static Menu will not be rendered

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.