The Einstein Bots Platform API is a new REST API that allows you to interact with your Einstein Bots from any client. In this blog post, we will explore how to use this new API to talk to your bot, and in later posts in this series, we’ll discuss specific cases in detail.

What are Einstein Bots?

A bot is an autonomous program that can interact with systems or users. Common use cases include: placing orders, providing customer support, showing FAQs, and more. Bots minimize the need for human interaction when providing services to the end customer.

Bots can be made smarter and more proficient with artificial intelligence (AI). Backed by the power of data, a bot can help solve more complex tasks for the end-user, thus reducing the need for a human agent. This, in turn, saves a lot of money for the companies that employ such AI-powered bots.

Einstein Bots are exactly the above — and more. Einstein Bots are fully integrated into the vast cloud ecosystem of Salesforce, and therefore can directly harness the power of all the great tools and technologies that Salesforce offers, both currently and in the future. You can read more about their awesomeness in the Einstein Bots documentation.

How to define and use Einstein Bots?

To set the context of this blog post, we first need to understand how to define and use Einstein Bots in a customer’s org. The following steps provide a high-level overview:

  1. Build the Bot: Define your Einstein Bot in the Bot Builder. This step includes creating all the bot dialogs, elements, rules, etc. for your new bot to be functional. This is also where you will define/train your Einstein NLP model for using the bot’s NLP capabilities. You can find all the necessary details in the getting started documentation. The bot that you defined in Step 1 is channel-agnostic.

  1. Test the Bot: Once you have completed the bot building phase, you can now activate and test your Einstein Bot in the Bot Preview. The Bot Preview is a playground for you to interact with the bot just like an end-user would.
  2. Add Channels: Once your Einstein Bot is ready, it’s time to bring it to your customers for actual production usage. Salesforce provides out-of-the-box channels, such as web, SMS, WhatsApp, and Facebook, and Einstein Bots are available to end-users only via these Salesforce channels.

The following system diagram depicts how the various systems interact when building and deploying Einstein Bots.

But what happens if, as a bot admin, you need to leverage bots beyond these Salesforce channels/connections? This is where the Einstein Bots Platform API comes in!

More ways to integrate with the Einstein Bot

As discussed in the previous section, the only way to integrate your Einstein Bot into your customer engagement infrastructure is via the various Salesforce channels. This was a limitation with previously released versions of Einstein Bots. But now, we have released the new Einstein Bots Platform API, which completely removes this limitation. Your Einstein Bots will continue to do their awesome work on your current channels, but now you can add your custom channels and client implementations.

What is the Einstein Bots Platform API?

The Einstein Bots Platform API is a REST API that allows interaction with your Einstein Bots from any client. It is a true platform solution for exposing your Einstein Bot in any customer engagement environment. For example, imagine a use case in which the end-user engagement client is a React Native mobile app. Without the Einstein Bots Platform API, it wouldn’t have been possible to integrate Einstein Bots with such a custom-built client. But with the Einstein Bots Platform API, you can now easily integrate Einstein Bots with the above custom client. You can find more details about this in the Developer Guide.

The following system diagram depicts how the various components, including the new Einstein Bots Platform API, interact to help Salesforce customers deliver their Einstein Bots to their customers.

How to use the API

Let’s get started with an introductory code sample. To use the API, Steps 1 and 2 described in the “How to define and use Einstein Bots” section above remain the same. But when you get to Step 3 (i.e., adding connections/channels), choose the API option as depicted below:


When you choose the API connection, you will be prompted to fill in the integration details and a Salesforce Connected App name, as shown below. The Integration Name can be any string you like.

A few words about Salesforce Connected Apps

A Salesforce Connected App is a framework used to authorize external systems that interact with any Salesforce API. With the Einstein Bots Platform API, a connected app will be used to generate OAuth access tokens that should be included in the external request as authorization headers. The Einstein Bots API, upon receipt of such authorization header, will inspect the incoming OAuth access token and determine if the request is valid or not. You can find more in the connected apps documentation. To set up a connected app for the Einstein Bots API specifically, you can refer to the Prerequisites section of the Bot API Developer Guide. Also, this blog post talks in detail about how to set up a connected app for the JWT bearer flow and obtain an OAuth access token that can be used to talk to the Einstein Bots Platform API.

Time to code!

Once you have defined your Einstein Bot, set up the OAuth-enabled Salesforce Connected App, and connected it to the bot, you are ready to consume the Einstein Bots Platform API. The following code snippet shows an example of using a Python Flask server to talk to the Einstein Bots API.

import logging
import requests
import json
from app import app
from flask import request
from app.auth import get_oauth_access_token
from app.constants import INIT_CHAT_URI, SEND_MESSAGES_URI, END_CHAT_URI, ORG_ID_HEADER_KEY, END_SESSION_HEADER_KEY

@app.route("/start/<bot_id>", methods=["POST"])
def init(bot_id):
    request_url = get_request_url(INIT_CHAT_URI.format(bot_id))
    response = send(request.json, request_url)
    return response

@app.route("/chat/<session_id>", methods=["POST"])
def chat(session_id):
    request_url = get_request_url(SEND_MESSAGES_URI.format(session_id))
    return send(request.json, request_url)

@app.route("/end/<session_id>", methods=["DELETE"])
def end(session_id):
    request_url = get_request_url(END_CHAT_URI.format(session_id))
    headers = get_headers()
    headers[END_SESSION_HEADER_KEY] = request.headers.get(END_SESSION_HEADER_KEY)
    response = requests.delete(request_url, headers=headers)
    validate_response(response)
    return json.loads(response.text)

def send(data, url):
    headers = get_headers()
    response = requests.post(url, headers=headers, data=json.dumps(data))
    validate_response(response)
    return json.loads(response.text)

def validate_response(response):
    # check status code
    if response.status_code != 200:
        raise ValueError("Invalid response code from Bot server. Error=" + response.text)    

def get_request_url(uri):
    return app.config.get("BOTS_SERVER_URL") + uri

def get_headers():
    token = get_oauth_access_token()
    orgId = app.config.get("ORG_ID")
    return {
        "Authorization": "Bearer " + token,
        "Content-Type":"application/json",
        "Accept": "application/json",
        ORG_ID_HEADER_KEY: orgId 
    }

if __name__ == "__main__":
    app.run()

NOTE: In each route implementation, we explicitly add the authorization header. For this header, we need the OAuth access token which is retrieved in the get_oauth_access_token function. Please refer to the code repository for the complete implementation of this function.

The functions init, chat, and end correspond to the three Einstein Bot APIs. The request and response structures for each of these calls are very well documented in the API Client Guide, and the same can be used with the above Python Flask server. Here are some sample requests made to the Python Flask server:

Initiate a chat session:

curl --location --request POST 'http://127.0.0.1:5000/start/<bot-id>' \
--header 'Content-Type: application/json' \
--data-raw '{
    "forceConfig": {
        "endpoint": "<ForceConfig Endpoint shown in the Add Connection Dialog>"
    },
    "externalSessionKey": "UUID"
}'

Send messages on an existing chat session:

curl --location --request POST 'http://127.0.0.1:5000/chat/<sessionId from the response of the Initiate Chat Session request>' \
--header 'Content-Type: application/json' \
--data-raw '{
    "message": {
        "type": "text",
        "text": "Hellow",
        "sequenceId":1
    }
}'

End a chat session:

curl --location --request DELETE 'http://127.0.0.1:5000/end/<sessionId from the response of the Initiate Chat Session request>' \
--header 'Content-Type: application/json' \
--header 'X-Session-End-Reason: UserRequest'

And that’s it! You just spoke to your Einstein Bot via a custom Python client!

What’s next?

In upcoming posts in this series, we will discuss specific cases in detail, including how to handle initializing a bot session with custom parameters, as well as escalation scenarios, such as a bot-to-case with the Einstein Bots Platform API.

References

About the author

Makarand Bhonsle is a Lead Software Engineer at Salesforce. He is the lead developer for the Einstein Bots Platform API.

Get the latest Salesforce Developer blog posts and podcast episodes via Slack or RSS.

Add to Slack Subscribe to RSS