OpenAI ChatKit (Python SDK)

1.6.3 · active · verified Sun Apr 12

OpenAI ChatKit is a Python SDK designed for building custom backend servers for OpenAI's ChatKit, enabling developers to integrate advanced AI-powered chat experiences into their applications. It is a key component of the broader OpenAI AgentKit suite, facilitating the creation of conversational AI agents with features like response streaming, tool invocation, and thread management. The library is currently at version 1.6.3 and is actively maintained, with recent updates suggesting ongoing development and integration with OpenAI's evolving agent capabilities.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up a basic FastAPI backend that uses `openai-chatkit` to handle chat interactions. It includes creating a ChatKit session (which provides a client secret for frontend authentication) and a response endpoint where your defined AI agent processes user messages. Remember to replace placeholder IDs and ensure your `OPENAI_API_KEY` and `CHATKIT_WORKFLOW_ID` are set as environment variables. A frontend (e.g., using `@openai/chatkit-react`) would then connect to these endpoints.

import os
from fastapi import FastAPI, Request
from openai import OpenAI
from openai_chatkit.server import ChatKitServer, UserMessageItem
from openai.lib.chatkit import Agent

app = FastAPI()
openai_client = OpenAI(api_key=os.environ.get('OPENAI_API_KEY', ''))

# Define your AI agent
assistant_agent = Agent(
    model="gpt-4o",
    name="Assistant",
    instructions="You are a helpful assistant."
)

# Implement your ChatKit server
class MyChatKitServer(ChatKitServer):
    def __init__(self):
        super().__init__()
        self.agent = assistant_agent

    async def respond(
        self, thread_id: str, input: UserMessageItem, request: Request
    ):
        # Example: Process user input with your agent
        # In a real application, you would manage state and agent context here
        response_content = f"Echoing: {input.text}"
        yield {"type": "text", "text": response_content}

chatkit_server = MyChatKitServer()

@app.post("/api/chatkit/session")
async def create_chat_session(request: Request):
    # In a real app, authenticate the user and provide a unique user_id
    user_id = "user_123"
    # Workflow ID would come from your OpenAI Agent Builder workflow
    workflow_id = os.environ.get('CHATKIT_WORKFLOW_ID', 'wf-YOUR_WORKFLOW_ID')

    # The client secret should be generated on the server-side only
    session = openai_client.beta.chatkit.sessions.create(
        workflow_id=workflow_id,
        user_id=user_id
    )
    return {"client_secret": session.client_secret}

@app.post("/api/chatkit/respond")
async def chatkit_respond(request: Request):
    return await chatkit_server.handle_request(request)

view raw JSON →