Python SDK

The ChatBotKit Python SDK is the official async Python library for building conversational AI applications on ChatBotKit. It provides typed access to the platform API, streaming responses, generated request and response types, and optional agent helpers for tool-using workflows.

Key Features

  • Async by Default: Built on httpx and designed for modern async Python applications
  • Comprehensive API Coverage: Access bots, conversations, datasets, integrations, tasks, partners, usage, and platform resources
  • Streaming Support: Iterate over JSONL stream events as they arrive
  • Generated Types: Use chatbotkit.types for request, response, and stream item models
  • Agent Helpers: Install the optional agent extra to run tool-using agents with Python handlers
  • Production Ready: Supports custom base URLs, timeouts, headers, transports, and partner run-as options

Installation

Install the SDK from PyPI:

pip install chatbotkit

bash

To use the optional agent helpers, install the agent extra:

pip install "chatbotkit[agent]"

bash

You can also install directly from the source repository:

pip install "chatbotkit @ git+https://github.com/chatbotkit/python-sdk.git"

bash

Requirements:

  • Python 3.10 or higher
  • A ChatBotKit API secret key

Quick Start

The simplest way to get started is with a stateless conversation completion. The SDK is async, so use it inside an event loop:

import asyncio import os from chatbotkit import ChatBotKit from chatbotkit.types import ConversationCompleteStreamItemType async def main(): async with ChatBotKit(secret=os.environ["CHATBOTKIT_API_SECRET"]) as cbk: completion = cbk.conversation.complete( None, { "messages": [ {"type": "user", "text": "Hello! Tell me a joke."}, ], }, ) async for event in completion.stream(): if event.type == ConversationCompleteStreamItemType.TOKEN: print(event.data.token, end="", flush=True) asyncio.run(main())

python

Passing None as the conversation ID uses the stateless completion endpoint. Pass an existing conversation ID when you want ChatBotKit to continue a stored conversation.

Client Architecture

Create a ChatBotKit client with your API key and access platform resources as attributes:

from chatbotkit import ChatBotKit cbk = ChatBotKit( secret="your-api-key", base_url="https://api.chatbotkit.com", run_as_user_id="user-id", timezone="America/New_York", ) cbk.bot cbk.conversation cbk.dataset cbk.skillset cbk.file cbk.contact cbk.secret cbk.memory cbk.blueprint cbk.task cbk.team cbk.space cbk.partner cbk.policy cbk.portal cbk.usage cbk.magic cbk.event cbk.graphql cbk.channel cbk.platform cbk.integration

python

The client manages an underlying httpx.AsyncClient. Use async with ChatBotKit(...) as cbk when possible, or call await cbk.aclose() when you are done.

API Route Mapping

The Python SDK follows the same shape as the ChatBotKit API:

  • API route: /api/v1/bot/list -> SDK method: cbk.bot.list()
  • API route: /api/v1/bot/create -> SDK method: cbk.bot.create()
  • API route: /api/v1/dataset/record/create -> SDK method: cbk.dataset.record.create()
  • API route: /api/v1/conversation/complete -> SDK method: cbk.conversation.complete()

This makes it straightforward to move between the API reference, examples, and SDK calls.

Responses and Streaming

Every resource method returns an awaitable response. Await it to parse the JSON body into a typed object:

bots = await cbk.bot.list({"take": 10}) for bot in bots.items: print(bot.id, bot.name)

python

Call .stream() to iterate over stream items as they arrive:

from chatbotkit.types import ConversationCompleteStreamItemType completion = cbk.conversation.complete( None, { "messages": [ {"type": "user", "text": "Write a short poem."}, ], }, ) async for event in completion.stream(): if event.type == ConversationCompleteStreamItemType.TOKEN: print(event.data.token, end="", flush=True) elif event.type == ConversationCompleteStreamItemType.RESULT: print("\nDone!")

python

Working with Bots

Bots are AI agents configured with backstory, model settings, datasets, skillsets, and integrations.

# List bots bots = await cbk.bot.list({"take": 10}) # Fetch a bot bot = await cbk.bot.fetch("bot-id") # Create a bot bot = await cbk.bot.create( { "name": "Support Assistant", "description": "Helpful customer support bot", "backstory": "You are a friendly and knowledgeable support agent.", } ) # Update a bot bot = await cbk.bot.update("bot-id", {"name": "Updated Support Assistant"}) # Delete a bot result = await cbk.bot.delete("bot-id")

python

Conversations

Use conversations for chat interactions. You can run stateless completions or create persistent conversation records.

# Create a conversation conversation = await cbk.conversation.create({}) # Continue a stored conversation result = await cbk.conversation.complete( conversation.id, { "messages": [ {"type": "user", "text": "I need help with my order."}, ], }, ) print(result.text)

python

For one-off completions, pass None as the conversation ID:

result = await cbk.conversation.complete( None, { "messages": [ {"type": "user", "text": "Summarize this in one sentence."}, ], }, )

python

Datasets

Datasets store knowledge that bots and agents can search.

# Create a dataset dataset = await cbk.dataset.create( { "name": "Knowledge Base", "description": "Product and support information", } ) # Add a record record = await cbk.dataset.record.create( dataset.id, { "text": "ChatBotKit helps teams build conversational AI applications.", "source": "python-sdk-example", }, ) # Search records results = await cbk.dataset.search( dataset.id, {"search": "conversational AI applications"}, )

python

Integrations

Integrations are available under cbk.integration and follow the same list, create, fetch, update, and delete patterns. Some integrations also expose operations such as setup, initiate, or sync.

# List Slack integrations slack_integrations = await cbk.integration.slack.list({"take": 10}) # Create a widget integration widget = await cbk.integration.widget.create({"name": "Website Widget"}) # Trigger a sitemap sync await cbk.integration.sitemap.sync("integration-id")

python

Agent Helpers

Install chatbotkit[agent] to use the optional agent helpers. They let you define Python tools, validate tool inputs with Pydantic models, and stream agent execution events.

import asyncio import os from pydantic import BaseModel, Field from chatbotkit import ChatBotKit from chatbotkit.agent import Tool, execute class WeatherInput(BaseModel): location: str = Field(description="The city and state, e.g. San Francisco, CA") async def get_weather(input: WeatherInput) -> dict[str, object]: return { "location": input.location, "temperature": 72, "conditions": "sunny", } async def main() -> None: async with ChatBotKit(secret=os.environ["CHATBOTKIT_API_SECRET"]) as cbk: async for event in execute( client=cbk, model="gpt-4o", messages=[ { "type": "user", "text": "What is the weather in San Francisco?", } ], tools={ "get_weather": Tool( description="Get the current weather for a location", input_model=WeatherInput, handler=get_weather, ) }, max_iterations=10, ): if event.get("type") == "token": print(event["data"]["token"], end="", flush=True) asyncio.run(main())

python

Configuration Options

Options can be passed as keyword arguments or with ClientOptions:

from chatbotkit import ChatBotKit, ClientOptions cbk = ChatBotKit( ClientOptions( secret="your-api-key", timezone="UTC", timeout=30, ) )

python

OptionDescription
secretAPI authentication token
base_urlCustom API base URL
run_as_user_idExecute requests as a specific user
run_as_child_user_emailExecute requests as a specific child user
timezoneTimezone for timestamp handling
headersExtra headers to send with every request
timeoutRequest timeout in seconds
transportCustom httpx transport for tests or advanced networking

Error Handling

Failed requests raise APIError, which includes the API message, code, status, and URL.

from chatbotkit import APIError try: bot = await cbk.bot.fetch("invalid-id") except APIError as error: print(error.status_code, error.code, error.message)

python

Types

The chatbotkit.types module contains generated request, response, and stream item types. Each type provides from_dict and to_dict helpers, and resource methods accept either generated objects or plain dictionaries.

from chatbotkit.types import BotCreateRequest bot = await cbk.bot.create( BotCreateRequest.from_dict( { "name": "My Bot", "description": "Created with the Python SDK", } ) )

python

Resources