Go SDK
ChatBotKit Go SDK is the official Go software development kit for building conversational AI interfaces and chatbots. It provides a comprehensive set of tools, libraries, and APIs to help developers create AI-powered applications using the Go programming language.
Installation
To install ChatBotKit Go SDK, simply run the following command:
go get github.com/chatbotkit/go-sdk
Requirements
- Go 1.21 or later
- A ChatBotKit API key from the Dashboard
Quick Start
package main
import (
"context"
"fmt"
"log"
"github.com/chatbotkit/go-sdk/agent"
"github.com/chatbotkit/go-sdk/sdk"
)
func main() {
// Create a client with your API key
client := sdk.New(sdk.Options{
Secret: "your-api-key",
})
// Run a simple conversation
result, err := agent.Complete(context.Background(), client, agent.CompleteOptions{
Model: "glm-5.2",
Messages: []agent.Message{
{Type: "user", Text: "Hello! Tell me a joke."},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Text)
}
SDK Structure
The Go SDK is organized into focused packages:
| Package | Description |
|---|---|
sdk | Main SDK client with access to all ChatBotKit API resources |
agent | High-level agent execution functionality with tool support |
types | Auto-generated API request and response types |
sdk/integration | Integration clients (Widget, Slack, Discord, WhatsApp, Telegram, Messenger, Instagram, Notion, Sitemap, Support, Extract, Trigger, Twilio, Email, McpServer, Teams, GoogleChat) |
SDK Client
The main sdk package provides access to all ChatBotKit API resources:
client := sdk.New(sdk.Options{
Secret: "your-api-key",
BaseURL: "https://api.chatbotkit.com", // optional
RunAsUserID: "user-id", // optional
Timezone: "America/New_York", // optional
})
// Access resources
client.Bot // Bot management
client.Conversation // Conversation management
client.Dataset // Dataset management
client.Skillset // Skillset management
client.File // File management
client.Contact // Contact management
client.Secret // Secret management
client.Channel // Channel operations
client.Blueprint // Blueprint management
client.Graphql // GraphQL operations
client.Integration // Integration management
client.Integration.Widget // Widget integrations
client.Integration.Slack // Slack integrations
client.Integration.Discord // Discord integrations
client.Integration.WhatsApp // WhatsApp integrations
client.Integration.Telegram // Telegram integrations
client.Integration.Messenger // Messenger integrations
client.Integration.Instagram // Instagram integrations
client.Integration.Notion // Notion integrations
client.Integration.Sitemap // Sitemap integrations
client.Integration.Support // Support integrations
client.Integration.Extract // Extract integrations
client.Integration.Trigger // Trigger integrations
client.Integration.Twilio // Twilio integrations
client.Integration.Email // Email integrations
client.Integration.McpServer // MCP server integrations
client.Integration.Teams // Teams integrations
client.Integration.GoogleChat // Google Chat integrations
client.Memory // Memory management
client.Partner // Partner operations
client.Platform // Platform content and catalogue access
client.Policy // Policy management
client.Portal // Portal management
client.Team // Team management
client.Task // Task management
client.Usage // Usage reporting
client.Space // Space management
client.Event // Event log access
client.Event.Log // Event log operations
client.Magic // Magic AI generation
client.Magic.Prompt // Magic prompt templates
Resource Operations
Bots
// List bots
bots, err := client.Bot.List(ctx, nil)
// Fetch a bot
bot, err := client.Bot.Fetch(ctx, "bot-id")
// Create a bot
bot, err := client.Bot.Create(ctx, types.BotCreateRequest{
Name: "My Bot",
Description: "A helpful assistant",
Backstory: "You are a friendly AI assistant.",
})
// Update a bot
bot, err := client.Bot.Update(ctx, "bot-id", types.BotUpdateRequest{
Name: "Updated Bot Name",
})
// Delete a bot
resp, err := client.Bot.Delete(ctx, "bot-id")
Conversations
// Create a conversation
conv, err := client.Conversation.Create(ctx, types.ConversationCreateRequest{})
// List conversations
convs, err := client.Conversation.List(ctx, nil)
// Stateless completion (no conversation ID - server does not persist state)
resp, err := client.Conversation.Complete(ctx, types.ConversationCompleteRequest{
Text: "Hello!",
})
// Continue an existing conversation (stateful)
resp, err := client.Conversation.CompleteMessage(ctx, "conversation-id", types.ConversationMessageCompleteRequest{
Text: "Follow-up question",
})
// Send a user message to an existing conversation
resp, err := client.Conversation.Send(ctx, "conversation-id", types.ConversationMessageSendRequest{
Text: "Hello!",
})
// Receive the latest bot response from an existing conversation
resp, err := client.Conversation.Receive(ctx, "conversation-id", types.ConversationMessageReceiveRequest{})
Datasets
// Create a dataset
dataset, err := client.Dataset.Create(ctx, types.DatasetCreateRequest{
Name: "Knowledge Base",
})
// Add a record
record, err := client.Dataset.Record.Create(ctx, "dataset-id", types.DatasetRecordCreateRequest{
Text: "Important information...",
})
// Search the dataset
results, err := client.Dataset.Search(ctx, "dataset-id", types.DatasetSearchRequest{
Text: "search query",
})
Agent Package
The agent package provides high-level functionality for running AI agents.
Complete
Run a single conversation completion:
result, err := agent.Complete(ctx, client, agent.CompleteOptions{
Model: "glm-5.2",
Backstory: "You are a helpful assistant.",
Messages: []agent.Message{
{Type: "user", Text: "What is 2+2?"},
},
})
Execute
Run a multi-turn agent execution:
result, err := agent.Execute(ctx, client, agent.ExecuteOptions{
Model: "glm-5.2",
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)
Complete with Tools
Run a conversation with custom tool handlers:
// Define your tools
tools := agent.Tools{
"get_weather": {
Description: "Get the current weather for a location",
Parameters: agent.FunctionParameters{
"properties": map[string]any{
"location": map[string]any{"type": "string", "description": "The city name"},
},
"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
},
},
}
// Provide backstory via Extensions (CompleteWithToolsOptions has no Backstory field)
backstory := "You are a helpful assistant with access to tools."
// Stream with tool support
events, errs := agent.CompleteWithTools(ctx, client, agent.CompleteWithToolsOptions{
Model: "glm-5.2",
Messages: messages,
Tools: tools,
Extensions: &types.ConversationCompleteRequestExtensions{
Backstory: &backstory,
},
})
// Process events including tool calls
for event := range events {
switch e := event.(type) {
case agent.TokenAgentEvent:
fmt.Print(e.Token)
case agent.ResultAgentEvent:
fmt.Printf("\nDone: %s\n", e.EndReason)
case agent.ToolCallStartEvent:
fmt.Printf("[Calling %s...]\n", e.Name)
case agent.ToolCallEndEvent:
fmt.Printf("[%s returned: %v]\n", e.Name, e.Result)
case agent.ToolCallErrorEvent:
fmt.Printf("[%s failed: %s]\n", e.Name, e.Error)
case agent.MessageAgentEvent:
fmt.Printf("[Message (%s): %s]\n", e.Type, e.Text)
case agent.IterationEvent:
fmt.Printf("[Iteration %d]\n", e.Iteration)
case agent.AgentExitEvent:
fmt.Printf("[Exit %d: %s]\n", e.Code, e.Message)
}
}
Default Tools
The SDK provides default tools for common file and shell operations:
// Get the default tools
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
events, errs := agent.ExecuteWithTools(ctx, client, agent.ExecuteWithToolsOptions{
Model: "glm-5.2",
Backstory: "You are an autonomous agent.",
Messages: []agent.Message{
{Type: "user", Text: "Create a file called hello.txt with 'Hello World'"},
},
Tools: tools,
MaxIterations: 20,
})
Stateful Mode
All agent functions support stateful mode by setting ConversationID. The server manages conversation history; local Messages must be empty when using a remote conversation.
On the first call, pass the initial user message via Text. On subsequent iterations, omit Text to continue from the server-side state.
// Create a conversation first
model := "glm-5.2"
conv, err := client.Conversation.Create(ctx, types.ConversationCreateRequest{
Model: &model,
})
userPrompt := "What is the weather in San Francisco?"
backstory := "You are a helpful assistant."
events, errs := agent.CompleteWithTools(ctx, client, agent.CompleteWithToolsOptions{
ConversationID: conv.ID,
Text: &userPrompt, // omit on later iterations
Tools: tools,
Extensions: &types.ConversationCompleteRequestExtensions{
Backstory: &backstory,
},
})
Agent Options Reference
The following options are supported across agent functions:
| Option | CompleteOptions | ExecuteOptions | CompleteWithToolsOptions | ExecuteWithToolsOptions |
|---|---|---|---|---|
Model | Yes | Yes | Yes | Yes |
Messages | Yes | Yes | Yes | Yes |
Backstory | Yes | Yes | - | Yes |
ConversationID | Yes | Yes | Yes | Yes |
Text | Yes | Yes | Yes | Yes |
BotID | Yes | - | Yes | Yes |
DatasetID | Yes | - | Yes | Yes |
SkillsetID | Yes | - | Yes | Yes |
Tools | - | - | Yes | Yes |
Extensions | - | - | Yes | Yes |
MaxIterations | - | Yes | - | Yes |
Inbox | - | - | - | Yes |
BotID, DatasetID, and SkillsetID attach existing ChatBotKit resources to the completion. Extensions allows passing an inline backstory, datasets, skillsets, and features directly without requiring pre-created resources.
Inbox Channel
ExecuteWithToolsOptions.Inbox is an optional <-chan string for injecting messages while the agent is running. Messages are drained between iterations and appended to the conversation so the model sees them on the next API call.
inbox := make(chan string, 10)
events, errs := agent.ExecuteWithTools(ctx, client, agent.ExecuteWithToolsOptions{
Model: "glm-5.2",
Backstory: "You are a long-running assistant.",
Messages: []agent.Message{
{Type: "user", Text: "Start the process."},
},
Tools: tools,
MaxIterations: 50,
Inbox: inbox,
})
// Inject a message from another goroutine
inbox <- "Please also summarize the results."
Skills
The agent package provides utilities for loading skill definitions from local directories. Skills describe capabilities available to the agent and are passed to the API via the Extensions.Features field.
Each skill directory must contain a SKILL.md file with YAML front matter defining the skill name and description.
// Load skills from one or more directories
skillsResult, err := agent.LoadSkills([]string{"./skills", "./custom-skills"})
// Reload skills on demand (e.g. after files change)
if err := skillsResult.Reload(); err != nil {
log.Printf("reload failed: %v", err)
}
// Convert loaded skills to a features entry for the Extensions field
skillsFeature := agent.CreateSkillsFeature(skillsResult.GetSkills())
events, errs := agent.ExecuteWithTools(ctx, client, agent.ExecuteWithToolsOptions{
Model: "glm-5.2",
Backstory: "You are an assistant that uses local skills.",
Messages: messages,
Tools: tools,
MaxIterations: 20,
Extensions: &types.ConversationCompleteRequestExtensions{
Features: []interface{}{skillsFeature},
},
})
SKILL.md front matter format:
---
name: My Skill
description: A brief description of what this skill does.
---
Streaming
The SDK supports streaming responses for real-time processing:
// Stateless streaming completion
events, errs := client.Conversation.CompleteStream(ctx, types.ConversationCompleteRequest{
Text: "Tell me a story",
})
// Process events as they arrive
for event := range events {
switch event.Type {
case "token":
fmt.Print(".")
case "result":
fmt.Println("\nDone!")
}
}
// Check for errors
if err := <-errs; err != nil {
log.Fatal(err)
}
// Stateful streaming - continue an existing conversation
events, errs = client.Conversation.CompleteMessageStream(ctx, "conversation-id", types.ConversationMessageCompleteRequest{
Text: "What about the ending?",
})
Available Streaming Methods
| Method | Description |
|---|---|
Conversation.CompleteStream | Stream a stateless conversation completion |
Conversation.CompleteMessageStream | Stream a continuation of an existing conversation |
Conversation.SendStream | Stream a send message operation |
Conversation.ReceiveStream | Stream a receive message operation |
agent.CompleteStream | Stream agent completion |
agent.CompleteWithTools | Stream agent completion with tool execution |
agent.ExecuteWithTools | Stream autonomous agent execution with tools |
Agent Events
When using CompleteWithTools or ExecuteWithTools, the event channel emits typed events implementing the AgentEvent interface:
| Event Type | Fields | Description |
|---|---|---|
TokenAgentEvent | Token string | A streaming token from the model |
ResultAgentEvent | Text string, EndReason string | Final completion result. EndReason values: stop, activity, iteration, length, error |
ToolCallStartEvent | Name string, Args map[string]interface{} | A tool call is starting |
ToolCallEndEvent | Name string, Result interface{} | A tool call completed successfully |
ToolCallErrorEvent | Name string, Error string | A tool call failed |
MessageAgentEvent | Type string, Text string, Meta map[string]interface{} | Server appended a message to the conversation |
IterationEvent | Iteration int | An execution iteration started (emitted by ExecuteWithTools) |
AgentExitEvent | Code int, Message string | Agent exited. Code 0 means success |
OtherAgentEvent | Type string, Data json.RawMessage | Unrecognized event type |
Configuration Options
| Option | Description |
|---|---|
Secret | API authentication token (required) |
BaseURL | Custom API base URL |
RunAsUserID | Execute requests within a specific user |
Timezone | Timezone for timestamp handling |
Error Handling
API errors are returned with a message and code:
bot, err := client.Bot.Fetch(ctx, "invalid-id")
if err != nil {
fmt.Printf("Error: %v\n", err)
}
Types Package
The types package contains all API request and response types:
import "github.com/chatbotkit/go-sdk/types"
// Request types
req := types.BotCreateRequest{
Name: "My Bot",
Description: "Description",
}
// Response types
var resp types.BotCreateResponse
Conclusion
This concludes the documentation for ChatBotKit Go SDK. For more information on how to use the SDK, please refer to the official repository at https://github.com/chatbotkit/go-sdk.