Go SDK

The ChatBotKit Go SDK is a powerful, production-ready library for building conversational AI applications in Go. It provides full type safety with auto-generated types, streaming capabilities, and a comprehensive agent package for building autonomous AI agents.

Key Features

  • Full Type Safety: Auto-generated types from the OpenAPI specification
  • Streaming by Default: Optimized for real-time responses
  • Comprehensive API Coverage: Access to all ChatBotKit resources and operations
  • Agent Package: High-level functionality for running autonomous AI agents
  • Tool Support: Define custom tools with handlers for function calling
  • Default Tools: Built-in tools for file and shell operations
  • Production Ready: Battle-tested with proper error handling

Installation

Install the SDK using Go modules:

go get github.com/chatbotkit/go-sdk

bash

Requirements:

  • Go 1.21 or higher
  • A ChatBotKit API secret key

Quick Start

The simplest way to get started is with stateless conversation completion:

package main import ( "context" "fmt" "log" "github.com/chatbotkit/go-sdk/agent" "github.com/chatbotkit/go-sdk/sdk" ) func main() { client := sdk.New(sdk.Options{ Secret: "your-api-key", }) result, err := agent.Complete(context.Background(), client, agent.CompleteOptions{ Model: "gpt-4o", Messages: []agent.Message{ {Type: "user", Text: "Hello! How are you?"}, }, }) if err != nil { log.Fatal(err) } fmt.Println(result.Text) }

go

Client Architecture

The SDK is organized into specialized packages, each handling specific functionality.

SDK Structure Maps to API Routes

Important: The SDK follows the exact structure of the API routes. This means that every API endpoint has a direct corresponding method in the SDK.

The mapping pattern is straightforward:

  • API route: /api/v1/bot/list → SDK method: client.Bot.List()
  • API route: /api/v1/bot/create → SDK method: client.Bot.Create()
  • API route: /api/v1/dataset/fetch → SDK method: client.Dataset.Fetch()
  • API route: /api/v1/conversation/complete → SDK method: client.Conversation.Complete()

Main Client

import "github.com/chatbotkit/go-sdk/sdk" client := sdk.New(sdk.Options{ Secret: "your-api-key", }) // Access all resources through the main client bots, err := client.Bot.List(ctx, nil) datasets, err := client.Dataset.List(ctx, nil) conversations, err := client.Conversation.List(ctx, nil)

go

Available Resources

The SDK provides clients for all ChatBotKit resources:

  • Bots: client.Bot - Bot creation and management
  • Conversations: client.Conversation - Conversation management with messages
  • Datasets: client.Dataset - Knowledge base management with records and files
  • Skillsets: client.Skillset - Skillset management with abilities
  • Files: client.File - File upload and download
  • Contacts: client.Contact - Contact management
  • Secrets: client.Secret - Secure credential storage
  • Blueprints: client.Blueprint - Template management
  • Integrations: client.Integration - Third-party service integrations
  • Teams: client.Team - Team collaboration features
  • Tasks: client.Task - Task automation
  • Spaces: client.Space - Organizational spaces
  • Events: client.Event - Event log access
  • Magic: client.Magic - Magic AI generation

Configuration Options

All clients accept the same configuration options:

client := sdk.New(sdk.Options{ // Required: Your API secret key Secret: "your-api-key", // Optional: Custom API base URL BaseURL: "https://api.chatbotkit.com", // Optional: Run operations as a child user (Partner API) RunAsUserID: "user-id", // Optional: Timezone for timestamp handling Timezone: "America/New_York", })

go

Working with Bots

Bots are AI agents configured with specific behaviors, models, and capabilities.

Creating and Managing Bots

import "github.com/chatbotkit/go-sdk/types" // Create a bot bot, err := client.Bot.Create(ctx, types.BotCreateRequest{ Name: "Support Assistant", Description: "Helpful customer support bot", Backstory: "You are a friendly and knowledgeable support agent.", Model: "gpt-4o", }) // List bots bots, err := client.Bot.List(ctx, nil) // Fetch a specific bot bot, err := client.Bot.Fetch(ctx, "bot-id") // Update a bot bot, err := client.Bot.Update(ctx, "bot-id", types.BotUpdateRequest{ Name: "Updated Name", }) // Delete a bot resp, err := client.Bot.Delete(ctx, "bot-id")

go

Conversations

Conversations are the core of chat interactions, supporting both stateless and stateful patterns.

Stateless Conversations

Perfect for one-off interactions without persistent storage:

resp, err := client.Conversation.Complete(ctx, "", types.ConversationCompleteRequest{ Model: "gpt-4o", Messages: []types.Message{ {Type: "user", Text: "What is the weather in Tokyo?"}, }, }) fmt.Println(resp.Text)

go

Stateful Conversations

Create persistent conversation records:

// Create a conversation conv, err := client.Conversation.Create(ctx, types.ConversationCreateRequest{ BotID: "bot-id", Model: "gpt-4o", }) // Send a message and get a response resp, err := client.Conversation.Complete(ctx, conv.ID, types.ConversationCompleteRequest{ Text: "I need help with my order", })

go

Agent Package

The agent package provides high-level functionality for running AI agents.

Complete

Run a single conversation completion:

import "github.com/chatbotkit/go-sdk/agent" result, err := agent.Complete(ctx, client, agent.CompleteOptions{ Model: "gpt-4o", Backstory: "You are a helpful assistant.", Messages: []agent.Message{ {Type: "user", Text: "What is 2+2?"}, }, }) fmt.Println(result.Text)

go

Execute

Run a multi-turn agent execution with automatic planning:

result, err := agent.Execute(ctx, client, agent.ExecuteOptions{ Model: "gpt-4o", Backstory: "You are a task completion agent.", MaxIterations: 10, Messages: []agent.Message{ {Type: "user", Text: "Write a haiku about programming."}, }, }) for _, response := range result.Responses { fmt.Println(response) } fmt.Printf("Exit: %d - %s\n", result.Exit.Code, result.Exit.Message)

go

Complete with Tools

Run a conversation with custom tool handlers:

tools := agent.Tools{ "get_weather": { Description: "Get the current weather for a location", Parameters: &agent.Parameters{ Properties: map[string]agent.Property{ "location": {Type: "string", Description: "The city name"}, "unit": { Type: "string", Description: "Temperature unit", Enum: []string{"celsius", "fahrenheit"}, }, }, Required: []string{"location"}, }, Handler: func(ctx context.Context, args map[string]interface{}) (interface{}, error) { location := args["location"].(string) return map[string]interface{}{ "temperature": 72, "location": location, }, nil }, }, } events, errs := agent.CompleteWithTools(ctx, client, agent.CompleteWithToolsOptions{ Model: "gpt-4o", Backstory: "You are a helpful assistant with access to tools.", Messages: messages, Tools: tools, }) for event := range events { switch e := event.(type) { case agent.TokenAgentEvent: fmt.Print(e.Token) case agent.ToolCallStartEvent: fmt.Printf("[Calling %s...]\n", e.Name) case agent.ToolCallEndEvent: fmt.Printf("[%s returned: %v]\n", e.Name, e.Result) } }

go

Execute with Tools

Run an autonomous agent task with built-in planning and progress tracking:

events, errs := agent.ExecuteWithTools(ctx, client, agent.ExecuteWithToolsOptions{ Model: "gpt-4o", Backstory: "You are an autonomous task executor.", MaxIterations: 20, Messages: []agent.Message{ {Type: "user", Text: "Research and summarize the topic..."}, }, Tools: tools, }) for event := range events { switch e := event.(type) { case agent.IterationEvent: fmt.Printf("=== Iteration %d ===\n", e.Iteration) case agent.TokenAgentEvent: fmt.Print(e.Token) case agent.AgentExitEvent: fmt.Printf("Exit: code=%d, message=%s\n", e.Code, e.Message) } }

go

The ExecuteWithTools function automatically includes three system tools:

  • plan: Create or update a task execution plan
  • progress: Track completed steps and current status
  • exit: Exit the execution with a status code

Default Tools

The SDK provides default tools for common file and shell operations:

tools := agent.DefaultTools() // Available tools: // - read: Read file contents with optional line ranges // - write: Write or modify file contents // - edit: Replace exact string occurrences in files // - exec: Execute shell commands with timeout // Combine with custom tools tools["my_custom_tool"] = agent.ToolDefinition{ Description: "My custom tool", Parameters: &agent.Parameters{...}, Handler: myHandler, }

go

Streaming Responses

The SDK supports streaming for real-time processing of AI responses.

Streaming with Conversation Client

events, errs := client.Conversation.CompleteStream(ctx, conversationID, types.ConversationCompleteRequest{ Text: "Tell me a story", }) for event := range events { switch event.Type { case "token": fmt.Print(".") case "result": fmt.Println("\nDone!") } } if err := <-errs; err != nil { log.Fatal(err) }

go

Available Streaming Methods

MethodDescription
Conversation.CompleteStreamStream a conversation completion
Conversation.SendStreamStream a send message operation
Conversation.ReceiveStreamStream a receive message operation
agent.CompleteStreamStream agent completion
agent.CompleteWithToolsStream agent completion with tool execution
agent.ExecuteWithToolsStream autonomous agent execution with tools

Error Handling

API errors are returned with structured information:

bot, err := client.Bot.Fetch(ctx, "invalid-id") if err != nil { fmt.Printf("Error: %v\n", err) }

go

Best Practices

Security

  • Never commit API secrets: Use environment variables
  • Rotate credentials regularly: Change API keys periodically
  • Use separate keys per environment: Different keys for development and production

Performance

  • Use streaming for interactive applications: Provides better user experience
  • Implement proper context handling: Use context for cancellation and timeouts
  • Monitor API usage: Track consumption to optimize costs

Architecture

  • Use stateless conversations for simple use cases: Reduces overhead
  • Use stateful conversations for complex flows: Enables history tracking
  • Implement proper error handling: Handle API errors gracefully

Additional Resources

Support