Context memory

Every conversation in Kindly, has their own key-value store named context that serves as the bot's memory for that conversation.

Saving values

The bot can collect information from the user via pattern dialogues. In addition, if the bot sends a webhook to another service, the response from the webhook service can contain new context as well.

Keep in mind that the context memory is a simple key-value storage. If you insert a key-value pair where the key already exists in the memory, the value will be overwritten and the old value will be lost.

Retrieving values

When defining bot replies, you may insert placeholders that look like {key}. If key is found in the chat context, the value will be inserted. If key is not available, the bot will not use that reply, but try to find something else to reply with, or go to a fallback reply.

The full context is also sent with every webhook, allowing you to perform any operation you'd like on the context data in your own service.

Managing context via API

If you're using the Application API, you can also read read and write to the context storage with your API requests.

Writing to context

When you send data, you can send new_context which will be merged with any existing context for the chat. If you send a key-value pair where the key already exists, the value will be overwritten. If the key does not exist the key-value pair will be inserted (upsert strategy).

Example:

```shell script curl -H 'Content-Type: application/json' -H "Authorization: YOUR_API_KEY" -d '{"user_id": "UNIQUE USER ID", "message": "Hello world!", "new_context": {"key": "value"}}' https://bot.kindly.ai/api/v1/send

### Reading context
When you receive a message from the bot, you will also find the `context` is attached as part of the JSON payload.
Example:
```json
{
"message": "Hello world!",
"context": {
"key": "value"
}
}

Set context in Kindly Chat

In some cases you might want to add data to the chat context on Kindly Chat initialization, for instance to know on which page the chat client is loaded or the email of a logged in user.

You can set chat context when initializing the chat client by populating window.kindlyOptions.context before loading the Kindly Chat HTML snippet:

<script>
window.kindlyOptions = {
context: {
email: "user@example.com",
url_path: "/interesting-product-slug"
}
};
</script>
<script
id="kindly-chat"
src="https://chat.kindlycdn.com/kindly-chat.js"
data-bot-key="YOUR-BOT-KEY"
async
></script>

Read more about the available options on the Kindly Chat page.