### Minimal Runnable Example in Go Source: https://github.com/cexll/agentsdk-go/blob/main/docs/getting-started.md This Go code demonstrates the minimal setup to run the agentsdk-go. It initializes the Anthropic provider, creates an API runtime, and executes a simple prompt. It requires the ANTHROPIC_API_KEY environment variable to be set. ```go package main import ( "context" "log" "os" "github.com/cexll/agentsdk-go/pkg/api" "github.com/cexll/agentsdk-go/pkg/model" ) func main() { ctx := context.Background() // 创建模型提供者 provider := model.NewAnthropicProvider( model.WithAPIKey(os.Getenv("ANTHROPIC_API_KEY")), model.WithModel("claude-sonnet-4-5"), ) // 初始化运行时 runtime, err := api.New(ctx, api.Options{ ProjectRoot: ".", ModelFactory: provider, }) if err != nil { log.Fatal(err) } defer runtime.Close() // 执行任务 result, err := runtime.Run(ctx, api.Request{ Prompt: "列出当前目录下的文件", SessionID: "demo", }) if err != nil { log.Fatal(err) } log.Printf("输出: %s", result.Output) } ``` -------------------------------- ### Run HTTP Server Example in Bash Source: https://github.com/cexll/agentsdk-go/blob/main/docs/getting-started.md This bash script shows how to start the HTTP server example for agentsdk-go. It requires setting the ANTHROPIC_API_KEY environment variable and navigating to the example directory before running the Go program. The server exposes health, sync run, and streaming endpoints. ```bash export ANTHROPIC_API_KEY=sk-ant-... cd examples/03-http go run . ``` -------------------------------- ### Run Minimal Go Example Source: https://github.com/cexll/agentsdk-go/blob/main/docs/getting-started.md This command executes the minimal Go example code. Ensure you have set the ANTHROPIC_API_KEY environment variable and saved the code as 'main.go'. ```bash go run main.go ``` -------------------------------- ### CLI Example Source: https://github.com/cexll/agentsdk-go/blob/main/docs/getting-started.md Demonstrates how to run the Agent SDK via the command-line interface. It supports session IDs and loading settings from a file for tool configuration. ```APIDOC ## CLI Example ### Description Demonstrates how to run the Agent SDK via the command-line interface. It supports session IDs and loading settings from a file for tool configuration. ### Method CLI Command ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```bash export ANTHROPIC_API_KEY=sk-ant-... cd examples/02-cli go run . --session-id demo --settings-path .claude/settings.json ``` ### Flags - `--session-id` — session ID (defaults to `SESSION_ID` env or `demo-session`) - `--settings-path` — path to `.claude/settings.json` to enable sandbox/tool config ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### MCP Client Example Source: https://github.com/cexll/agentsdk-go/blob/main/docs/getting-started.md Demonstrates how to use the Agent SDK with an MCP (Message Communication Protocol) client. This example shows a basic integration scenario. ```APIDOC ## MCP Client Example ### Description Demonstrates how to use the Agent SDK with an MCP (Message Communication Protocol) client. This example shows a basic integration scenario. ### Method CLI Command ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```bash export ANTHROPIC_API_KEY=sk-ant-... cd examples/mcp go run . ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Verify Go Version Source: https://github.com/cexll/agentsdk-go/blob/main/docs/getting-started.md This command verifies that the installed Go version meets the minimum requirement of Go 1.24 or later. It's a crucial first step in environment setup. ```bash go version # should show go1.24 or later ``` -------------------------------- ### Run MCP Client Example in Bash Source: https://github.com/cexll/agentsdk-go/blob/main/docs/getting-started.md This bash script demonstrates how to execute the MCP client example for agentsdk-go. It involves setting the ANTHROPIC_API_KEY environment variable, changing to the example directory, and then running the Go program. This example is typically used for interacting with a Message Queue. ```bash export ANTHROPIC_API_KEY=sk-ant-... cd examples/mcp go run . ``` -------------------------------- ### HTTP Server Examples Source: https://github.com/cexll/agentsdk-go/blob/main/docs/getting-started.md Provides examples for running the Agent SDK as an HTTP server. It exposes endpoints for health checks, synchronous runs, and streaming responses. ```APIDOC ## HTTP Server Examples ### Description Provides examples for running the Agent SDK as an HTTP server. It exposes endpoints for health checks, synchronous runs, and streaming responses. ### Method HTTP Server ### Endpoint - `http://localhost:8080/health` (GET) - `POST /v1/run` - `POST /v1/run/stream` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body (For POST requests, refer to specific endpoint documentation not provided here) ### Request Example ```bash export ANTHROPIC_API_KEY=sk-ant-... cd examples/03-http go run . ``` ### Response #### Success Response (200) N/A (Depends on endpoint) #### Response Example N/A (Depends on endpoint) ``` -------------------------------- ### Basic Example Setup Source: https://github.com/cexll/agentsdk-go/blob/main/README.md Steps to set up the environment for the basic example, including copying the environment file and setting the Anthropic API key. ```bash # 1. Set up environment cp .env.example .env # Edit .env: ANTHROPIC_API_KEY=sk-ant-your-key-here source .env ``` -------------------------------- ### Run CLI Example with Environment Variables in Bash Source: https://github.com/cexll/agentsdk-go/blob/main/docs/getting-started.md This bash script demonstrates how to run the CLI example for agentsdk-go. It requires setting the ANTHROPIC_API_KEY environment variable and navigating to the example directory. The script then executes the Go program with specific flags for session ID and settings path. ```bash export ANTHROPIC_API_KEY=sk-ant-... cd examples/02-cli go run . --session-id demo --settings-path .claude/settings.json ``` -------------------------------- ### Settings JSON Example Source: https://github.com/cexll/agentsdk-go/blob/main/docs/getting-started.md An example of a `settings.json` file used for agent configuration. It specifies permissions for tool usage (allowing Bash commands and denying file reads) and environment variables. ```json { "permissions": { "allow": ["Bash(ls:*)", "Bash(pwd:*)"], "deny": ["Read(.env)", "Read(secrets/**)"] }, "env": { "MY_VAR": "value" }, "sandbox": { "enabled": false } } ``` -------------------------------- ### State Sharing Middleware (Go) Source: https://github.com/cexll/agentsdk-go/blob/main/docs/getting-started.md An example of middleware that shares state between hooks using the `Meta` map. It records the start time before the agent runs and logs the execution duration after the agent completes. ```go timingMiddleware := middleware.Middleware{ BeforeAgent: func(ctx context.Context, req *middleware.AgentRequest) (*middleware.AgentRequest, error) { req.Meta["start_time"] = time.Now() return req, nil }, AfterAgent: func(ctx context.Context, resp *middleware.AgentResponse) (*middleware.AgentResponse, error) { startTime := resp.Meta["start_time"].(time.Time) duration := time.Since(startTime) log.Printf("执行时间: %v", duration) return resp, nil }, } ``` -------------------------------- ### Load Agent Configuration (Go) Source: https://github.com/cexll/agentsdk-go/blob/main/docs/getting-started.md Demonstrates how to load agent configuration using the SDK. It initializes a configuration loader, specifying the base directory and the Claude configuration directory, then loads the configuration. Error handling for loader and load operations is included. ```go import "github.com/cexll/agentsdk-go/pkg/config" loader, err := config.NewLoader(".", config.WithClaudeDir(".claude")) if err != nil { log.Fatal(err) } cfg, err := loader.Load() if err != nil { log.Fatal(err) } ``` -------------------------------- ### Run Advanced Integrated Example with Go Source: https://github.com/cexll/agentsdk-go/blob/main/examples/04-advanced/README.md Executes the advanced integrated example using the Go CLI. This command navigates to the example directory, sets up necessary API keys (if using a real provider), and runs the main binary with specific flags to control features like MCP and prompt input. ```bash cd examples/04-advanced # set ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN only if you swap in a real provider; demo model is offline-safe go run . --prompt "生成一份安全巡检摘要" --enable-mcp=false ``` -------------------------------- ### Running Go Examples with API Key Source: https://github.com/cexll/agentsdk-go/blob/main/CLAUDE.md Instructions on how to set up and run the example applications within the agentsdk-go project. Emphasizes the requirement for the ANTHROPIC_API_KEY environment variable and provides methods for setting it via a .env file or direct export. ```bash # Recommended: Use .env file cp .env.example .env # Edit .env and set ANTHROPIC_API_KEY=sk-ant-your-key-here source .env # Run examples go run ./examples/01-basic go run ./examples/02-cli --session-id demo go run ./examples/03-http go run ./examples/04-advanced --prompt "安全巡检" --enable-mcp=false Alternative (direct export): export ANTHROPIC_API_KEY=sk-ant-... go run ./examples/01-basic ``` -------------------------------- ### Build and Test agentsdk-go Project Source: https://github.com/cexll/agentsdk-go/blob/main/docs/getting-started.md This command builds the agentsdk-go project and then runs core module tests. It ensures the project is compiled correctly and that essential functionalities are working as expected. ```bash # Build the project make build # Run core module tests go test ./pkg/agent ./pkg/middleware ``` -------------------------------- ### MCP Server Configuration Example Source: https://github.com/cexll/agentsdk-go/blob/main/CLAUDE.md A JSON configuration example for setting up Model Context Protocol (MCP) servers. This includes specifying the command and arguments for external tools that communicate via stdio. ```json { "mcp": { "servers": [ { "name": "my-server", "command": "node", "args": ["server.js"] } ] } } ``` -------------------------------- ### Clone agentsdk-go Repository Source: https://github.com/cexll/agentsdk-go/blob/main/docs/getting-started.md These commands clone the agentsdk-go repository from GitHub and navigate into the project directory. This is necessary to access the source code and build the project. ```bash git clone https://github.com/cexll/agentsdk-go.git cd agentsdk-go ``` -------------------------------- ### Using Middleware in Go Source: https://github.com/cexll/agentsdk-go/blob/main/docs/getting-started.md This Go code demonstrates how to integrate middleware with agentsdk-go. It defines a logging middleware to track request and response times and injects it into the API runtime. It requires the ANTHROPIC_API_KEY environment variable. ```go package main import ( "context" "log" "os" "time" "github.com/cexll/agentsdk-go/pkg/api" "github.com/cexll/agentsdk-go/pkg/middleware" "github.com/cexll/agentsdk-go/pkg/model" ) func main() { ctx := context.Background() provider := model.NewAnthropicProvider( model.WithAPIKey(os.Getenv("ANTHROPIC_API_KEY")), model.WithModel("claude-sonnet-4-5"), ) // 定义日志 Middleware loggingMiddleware := middleware.Middleware{ BeforeAgent: func(ctx context.Context, req *middleware.AgentRequest) (*middleware.AgentRequest, error) { log.Printf("[请求] %s", req.Input) req.Meta["start_time"] = time.Now() return req, nil }, AfterAgent: func(ctx context.Context, resp *middleware.AgentResponse) (*middleware.AgentResponse, error) { duration := time.Since(resp.Meta["start_time"].(time.Time)) log.Printf("[响应] 耗时: %v", duration) return resp, nil }, } // 注入 Middleware runtime, err := api.New(ctx, api.Options{ ProjectRoot: ".", ModelFactory: provider, Middleware: []middleware.Middleware{loggingMiddleware}, }) if err != nil { log.Fatal(err) } defer runtime.Close() result, err := runtime.Run(ctx, api.Request{ Prompt: "计算 1+1", SessionID: "math", }) if err != nil { log.Fatal(err) } log.Printf("结果: %s", result.Output) } ``` -------------------------------- ### Go SDK Async Bash Execution Example Source: https://github.com/cexll/agentsdk-go/blob/main/README.md Shows how to execute bash commands asynchronously using the Go SDK. The first call starts a background task, and a subsequent call retrieves its output. This is useful for long-running operations that should not block the main execution flow. ```go // Start background task result, _ := runtime.Run(ctx, api.Request{ Prompt: "Run 'sleep 10 && echo done' in background", SessionID: "demo", }) // Later, check task output result, _ = runtime.Run(ctx, api.Request{ Prompt: "Get output of background task", SessionID: "demo", }) ``` -------------------------------- ### Run Custom Tools Example (Bash) Source: https://github.com/cexll/agentsdk-go/blob/main/examples/05-custom-tools/README.md Executes the custom tools example using the Go CLI. Requires setting the ANTHROPIC_API_KEY environment variable. ```bash export ANTHROPIC_API_KEY=sk-ant-... go run ./examples/05-custom-tools ``` -------------------------------- ### Run the Minimal HTTP API Example (Bash) Source: https://github.com/cexll/agentsdk-go/blob/main/examples/03-http/README.md Instructions to run the minimal HTTP API example using Go. It requires setting the ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN environment variable. The API defaults to port 8080, which can be overridden by AGENTSDK_HTTP_ADDR. The model can be selected using AGENTSDK_MODEL, and custom endpoints can be specified with ANTHROPIC_BASE_URL. ```bash export ANTHROPIC_API_KEY=sk-ant-... # OR use ANTHROPIC_AUTH_TOKEN (takes precedence) # export ANTHROPIC_AUTH_TOKEN=your-token go run ./examples/03-http ``` -------------------------------- ### Install and Clean Build Artifacts with Make Source: https://github.com/cexll/agentsdk-go/blob/main/README.md These make commands are used for managing the build process of the Go Agent SDK. 'make install' is used to install the SDK, typically into the GOPATH, making it available for use in other Go projects. 'make clean' removes any previously generated build artifacts, ensuring a fresh build environment. ```bash make install ``` ```bash make clean ``` -------------------------------- ### HTTP API Endpoints for Streaming Source: https://github.com/cexll/agentsdk-go/blob/main/CLAUDE.md Details the HTTP API endpoints available when running the HTTP example, specifically focusing on the streaming endpoint for real-time progress. Includes an example cURL command for making a streaming request. ```bash # Example streaming request: curl -N -X POST http://localhost:8080/v1/run/stream \ -H 'Content-Type: application/json' \ -d '{"prompt": "列出当前目录", "session_id": "demo"}' ``` -------------------------------- ### Go SDK Configuration and Token Usage Example Source: https://github.com/cexll/agentsdk-go/blob/main/README.md Demonstrates how to initialize the Go SDK with custom options, including a callback for token usage statistics and settings for auto-compaction. This helps in monitoring token consumption and managing costs by automatically summarizing conversations. ```go runtime, err := api.New(ctx, api.Options{ ProjectRoot: ".", ModelFactory: provider, // Token tracking callback OnTokenUsage: func(stats api.TokenStats) { log.Printf("Tokens: input=%d, output=%d, cache_read=%d", stats.InputTokens, stats.OutputTokens, stats.CacheReadTokens) }, // Auto compact settings CompactThreshold: 100000, // Trigger compact at 100k tokens CompactModel: "claude-haiku-4-5", // Use cheaper model for summarization }) ``` -------------------------------- ### Run Basic Agent SDK Example in Go Source: https://github.com/cexll/agentsdk-go/blob/main/README.md This Go program demonstrates a basic interaction with the Agent SDK. It initializes a runtime with an Anthropic model provider and executes a simple prompt to list files in the current directory. The output from the model is then logged. ```go package main import ( "context" "log" "os" "github.com/cexll/agentsdk-go/pkg/api" "github.com/cexll/agentsdk-go/pkg/model" ) func main() { ctx := context.Background() // Create the model provider provider := model.NewAnthropicProvider( model.WithAPIKey(os.Getenv("ANTHROPIC_API_KEY")), model.WithModel("claude-sonnet-4-5"), ) // Initialize the runtime runtime, err := api.New(ctx, api.Options{ ProjectRoot: ".", ModelFactory: provider, }) if err != nil { log.Fatal(err) } defer runtime.Close() // Execute a task result, err := runtime.Run(ctx, api.Request{ Prompt: "List files in the current directory", SessionID: "demo", }) if err != nil { log.Fatal(err) } log.Printf("Output: %s", result.Output) } ``` -------------------------------- ### Error Handling Middleware (Go) Source: https://github.com/cexll/agentsdk-go/blob/main/docs/getting-started.md A middleware example that demonstrates error handling by validating the agent's input. If the input is empty, it returns an error, stopping the execution chain. ```go validationMiddleware := middleware.Middleware{ BeforeAgent: func(ctx context.Context, req *middleware.AgentRequest) (*middleware.AgentRequest, error) { if req.Input == "" { return nil, errors.New("输入不能为空") } return req, nil }, } ``` -------------------------------- ### Initialize and Run Agent with Go Source: https://github.com/cexll/agentsdk-go/blob/main/docs/api-reference.md Demonstrates how to initialize an agent with a mock model, tool registry, and tool executor, then run the agent with a context and print the output. It highlights the use of agent.New, agent.NewContext, and the agent.Run method. ```go mdl := &mockModel{} // implements agent.Model registry := tool.NewRegistry() _ = registry.Register(&EchoTool{}) toolExec := tool.NewExecutor(registry, nil) a, err := agent.New(mdl, toolExec, agent.Options{Timeout: 30 * time.Second}) ctx := agent.NewContext() ctx.Values["session"] = "demo-1" out, err := a.Run(context.Background(), ctx) if err != nil { log.Fatal(err) } fmt.Printf("final output: %s (tools=%d)\n", out.Content, len(out.ToolCalls)) ``` -------------------------------- ### Monitoring Middleware Source: https://github.com/cexll/agentsdk-go/blob/main/docs/getting-started.md Provides middleware for monitoring agent and tool execution. It logs the start and end of model calls, tool calls, and tool results, including any errors. ```APIDOC ## Monitoring Middleware ### Description Provides middleware for monitoring agent and tool execution. It logs the start and end of model calls, tool calls, and tool results, including any errors. ### Method Middleware (BeforeModel, AfterModel, BeforeTool, AfterTool) ### Endpoint N/A (Middleware) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go // Example of creating the middleware middleware := createMonitoringMiddleware() // This middleware would be applied to monitor model and tool interactions. ``` ### Response #### Success Response (200) N/A (Middleware) #### Response Example N/A (Middleware) ``` -------------------------------- ### Rate Limiting Middleware Source: https://github.com/cexll/agentsdk-go/blob/main/docs/getting-started.md Implements a token bucket rate limiter to control the frequency of agent requests. It replenishes tokens over time and denies requests when the limit is exceeded. ```APIDOC ## Rate Limiting Middleware ### Description Implements a token bucket rate limiter to control the frequency of agent requests. It replenishes tokens over time and denies requests when the limit is exceeded. ### Method Middleware (BeforeAgent) ### Endpoint N/A (Middleware) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go // Example of creating the middleware middleware := createRateLimitMiddleware(10) // Max 10 tokens // This middleware would be applied before agent requests. ``` ### Response #### Success Response (200) N/A (Middleware) #### Response Example N/A (Middleware) ``` -------------------------------- ### Go SDK Configuration and Runtime Initialization Source: https://context7.com/cexll/agentsdk-go/llms.txt This Go code demonstrates how to initialize the agentsdk-go runtime, loading configuration from the .claude directory. It shows how to set up a model provider, a settings loader, and apply programmatic overrides to the configuration. The code then runs a prompt and prints the output and loaded environment variables. ```go package main import ( "context" "fmt" "log" "github.com/cexll/agentsdk-go/pkg/api" "github.com/cexll/agentsdk-go/pkg/config" "github.com/cexll/agentsdk-go/pkg/model" ) func main() { ctx := context.Background() provider := &model.AnthropicProvider{ModelName: "claude-sonnet-4-5"} // Load configuration from .claude directory loader := &config.SettingsLoader{ProjectRoot: "."} runtime, err := api.New(ctx, api.Options{ ProjectRoot: ".", ModelFactory: provider, SettingsLoader: loader, // Override specific settings programmatically SettingsOverrides: &config.Settings{ Env: map[string]string{"RUNTIME_OVERRIDE": "true"}, }, }) if err != nil { log.Fatal(err) } defer runtime.Close() resp, err := runtime.Run(ctx, api.Request{ Prompt: "Show project configuration", SessionID: "config-demo", }) if err != nil { log.Fatal(err) } fmt.Println(resp.Result.Output) // Access loaded settings if resp.Settings != nil { fmt.Printf("Loaded env vars: %v\n", resp.Settings.Env) } } ``` -------------------------------- ### Configure Anthropic API Key Source: https://github.com/cexll/agentsdk-go/blob/main/docs/getting-started.md This command sets the ANTHROPIC_API_KEY environment variable, which is required for the agentsdk-go to authenticate with the Anthropic API. Ensure you replace 'sk-ant-...' with your actual API key. ```bash export ANTHROPIC_API_KEY=sk-ant-... ``` -------------------------------- ### Basic Logging Middleware (Go) Source: https://github.com/cexll/agentsdk-go/blob/main/docs/getting-started.md Implements a basic middleware for agent execution that logs the incoming request before the agent runs and the outgoing response after the agent finishes. It uses the `BeforeAgent` and `AfterAgent` hooks. ```go loggingMiddleware := middleware.Middleware{ BeforeAgent: func(ctx context.Context, req *middleware.AgentRequest) (*middleware.AgentRequest, error) { log.Printf("收到请求: %s", req.Input) return req, nil }, AfterAgent: func(ctx context.Context, resp *middleware.AgentResponse) (*middleware.AgentResponse, error) { log.Printf("返回响应: %s", resp.Output) return resp, nil }, } ``` -------------------------------- ### Model Interface Definition Source: https://github.com/cexll/agentsdk-go/blob/main/docs/getting-started.md This Go code snippet defines the `Model` interface, which is the core abstraction for interacting with different language models. Any model provider must implement this interface, specifically the `Generate` method. ```go type Model interface { Generate(ctx context.Context, c *Context) (*ModelOutput, error) } ``` -------------------------------- ### Streaming Output in Go Source: https://github.com/cexll/agentsdk-go/blob/main/docs/getting-started.md This Go code demonstrates how to handle streaming output from the agentsdk-go. It uses the `RunStream` method to receive events as they are generated, allowing for real-time display of content deltas and tool execution information. Requires ANTHROPIC_API_KEY. ```go package main import ( "context" "fmt" "log" "os" "github.com/cexll/agentsdk-go/pkg/api" "github.com/cexll/agentsdk-go/pkg/model" ) func main() { ctx := context.Background() provider := model.NewAnthropicProvider( model.WithAPIKey(os.Getenv("ANTHROPIC_API_KEY")), model.WithModel("claude-sonnet-4-5"), ) runtime, err := api.New(ctx, api.Options{ ProjectRoot: ".", ModelFactory: provider, }) if err != nil { log.Fatal(err) } defer runtime.Close() // 使用流式 API events := runtime.RunStream(ctx, api.Request{ Prompt: "分析当前项目结构", SessionID: "stream-demo", }) for event := range events { switch event.Type { case "content_block_delta": fmt.Print(event.Delta.Text) case "tool_execution_start": fmt.Printf("\n[执行工具] %s\n", event.ToolName) case "tool_execution_stop": fmt.Printf("[工具输出] %s\n", event.Output) case "message_stop": fmt.Println("\n[完成]") } } } ``` -------------------------------- ### Customize Tool Registration in Agent SDK (Go) Source: https://github.com/cexll/agentsdk-go/blob/main/README.md This Go example shows how to customize the tools available to the Agent SDK runtime. It demonstrates specifying which built-in tools to enable (e.g., 'bash', 'file_read') and how to append custom tools by providing a slice of `tool.Tool` implementations. If `Tools` is non-empty, it takes precedence over `EnabledBuiltinTools` and `CustomTools` for backward compatibility. ```go rt, err := api.New(ctx, api.Options{ ProjectRoot: ".", ModelFactory: provider, EnabledBuiltinTools: []string{"bash", "file_read"}, // nil = all, empty = none CustomTools: []tool.Tool{&EchoTool{}}, // appended when Tools is empty }) if err != nil { log.Fatal(err) } defert rt.Close() ``` -------------------------------- ### Run Basic Synchronous Request with agentsdk-go Source: https://context7.com/cexll/agentsdk-go/llms.txt Demonstrates how to initialize the agentsdk-go Runtime and execute a synchronous request to an AI model. It shows setting up the model provider, creating the runtime, and processing the response, including output and token usage. Requires ANTHROPIC_API_KEY environment variable. ```go package main import ( "context" "fmt" "log" "os" "github.com/cexll/agentsdk-go/pkg/api" "github.com/cexll/agentsdk-go/pkg/model" ) func main() { ctx := context.Background() // Create the Anthropic model provider provider := model.NewAnthropicProvider( model.WithAPIKey(os.Getenv("ANTHROPIC_API_KEY")), model.WithModel("claude-sonnet-4-5"), ) // Initialize the runtime with project configuration runtime, err := api.New(ctx, api.Options{ ProjectRoot: ".", ModelFactory: provider, }) if err != nil { log.Fatal(err) } defer runtime.Close() // Execute a synchronous request resp, err := runtime.Run(ctx, api.Request{ Prompt: "List files in the current directory and summarize the project structure", SessionID: "demo-session", }) if err != nil { log.Fatal(err) } fmt.Printf("Output: %s\n", resp.Result.Output) fmt.Printf("Tokens used: %d\n", resp.Result.Usage.TotalTokens) fmt.Printf("Stop reason: %s\n", resp.Result.StopReason) } ``` -------------------------------- ### Implement Rate Limiting and Monitoring Middleware in Go Source: https://github.com/cexll/agentsdk-go/blob/main/docs/getting-started.md This Go code implements a token bucket rate limiter and a monitoring middleware for an agent SDK. The rate limiter controls request frequency, while the monitoring middleware logs various stages of agent and tool execution. It requires the agentsdk-go package. ```go package main import ( "context" "errors" "log" "time" "github.com/cexll/agentsdk-go/pkg/middleware" ) // 令牌桶限流器 type rateLimiter struct { tokens int maxTokens int lastTime time.Time } func (r *rateLimiter) allow() bool { now := time.Now() elapsed := now.Sub(r.lastTime).Seconds() r.tokens = min(r.maxTokens, r.tokens+int(elapsed*5)) // 每秒补充 5 个令牌 r.lastTime = now if r.tokens > 0 { r.tokens-- return true } return false } func createRateLimitMiddleware(maxTokens int) middleware.Middleware { limiter := &rateLimiter{ tokens: maxTokens, maxTokens: maxTokens, lastTime: time.Now(), } return middleware.Middleware{ BeforeAgent: func(ctx context.Context, req *middleware.AgentRequest) (*middleware.AgentRequest, error) { if !limiter.allow() { return nil, errors.New("请求过于频繁,请稍后再试") } return req, nil }, } } func createMonitoringMiddleware() middleware.Middleware { return middleware.Middleware{ BeforeModel: func(ctx context.Context, msgs []message.Message) ([]message.Message, error) { // 记录模型调用 log.Printf("[监控] 模型调用开始") return msgs, nil }, AfterModel: func(ctx context.Context, output *agent.ModelOutput) (*agent.ModelOutput, error) { // 记录模型响应 log.Printf("[监控] 模型调用结束,生成 %d 个工具调用", len(output.ToolCalls)) return output, nil }, BeforeTool: func(ctx context.Context, call *middleware.ToolCall) (*middleware.ToolCall, error) { // 记录工具调用 log.Printf("[监控] 执行工具: %s", call.Name) return call, nil }, AfterTool: func(ctx context.Context, result *middleware.ToolResult) (*middleware.ToolResult, error) { // 记录工具结果 if result.Error != nil { log.Printf("[监控] 工具执行失败: %v", result.Error) } return result, nil }, } } func min(a, b int) int { if a < b { return a } return b } ``` -------------------------------- ### Running Go Tests Source: https://github.com/cexll/agentsdk-go/blob/main/CLAUDE.md Provides examples of how to run unit, integration, and benchmark tests for the Agent SDK using the `go test` command. ```bash # Test a single package go test ./pkg/agent # Test with verbose output go test -v ./pkg/middleware # Run specific test go test -run TestAgent_Run ./pkg/agent # Benchmark tests go test -bench=. ./pkg/agent ``` -------------------------------- ### JSON Configuration: http Transport Example Source: https://github.com/cexll/agentsdk-go/blob/main/docs/migration-guide.md Example of configuring an http transport for an MCP server using the new `mcp.servers` structure, including URL, headers, and timeout. ```json { "mcp": { "servers": { "http-api": { "type": "http", "url": "https://api.example/mcp", "headers": {"X-Api-Key": "${API_KEY}"}, "timeoutSeconds": 10 } } } } ``` -------------------------------- ### Initialize and Use Anthropic Provider Source: https://github.com/cexll/agentsdk-go/blob/main/docs/api-reference.md Demonstrates how to create an AnthropicProvider, obtain a model instance, and make a synchronous completion request. It shows the basic structure for setting up the provider, defining a request, and handling the response. ```go provider := &model.AnthropicProvider{ ModelName: "claude-3-5-sonnet", CacheTTL: 5 * time.Minute, } mdl, err := provider.Model(context.Background()) req := model.Request{ Messages: []model.Message{ {Role: "user", Content: "summarize README"}, }, MaxTokens: 1024, } resp, err := mdl.Complete(ctx, req) if err != nil { log.Fatal(err) } fmt.Printf("usage: %d tokens, stop reason=%s\n", resp.Usage.TotalTokens, resp.StopReason) ``` -------------------------------- ### JSON Configuration: stdio Transport Example Source: https://github.com/cexll/agentsdk-go/blob/main/docs/migration-guide.md Example of configuring a stdio transport for an MCP server using the new `mcp.servers` structure, including command, arguments, and environment variables. ```json { "mcp": { "servers": { "tooling": { "type": "stdio", "command": "node", "args": ["server.js"], "env": {"NODE_ENV": "production"} } } } } ``` -------------------------------- ### Build Instructions Source: https://github.com/cexll/agentsdk-go/blob/main/README.md Information on how to build the AgentSDK-Go project using the provided Makefile, including commands for testing, linting, and building the CLI tool. ```APIDOC ## Build ### Makefile Commands ```bash # Run tests make test # Generate coverage report make coverage # Lint code make lint # Build CLI tool make agentctl ``` ``` -------------------------------- ### Basic Agent SDK API Usage in Go Source: https://github.com/cexll/agentsdk-go/blob/main/CLAUDE.md A Go code snippet demonstrating the basic usage of the Agent SDK. It shows how to create an Anthropic provider, initialize the API runtime, and run a task, including error handling and deferring resource closure. ```go // Create Anthropic provider (reads ANTHROPIC_API_KEY from environment) provider := model.NewAnthropicProvider( model.WithAPIKey(os.Getenv("ANTHROPIC_API_KEY")), model.WithModel("claude-sonnet-4-5"), ) runtime, err := api.New(ctx, api.Options{ ProjectRoot: ".", ModelFactory: provider, }) if err != nil { log.Fatal(err) } defer runtime.Close() result, err := runtime.Run(ctx, api.Request{ Prompt: "Your task here", SessionID: "session-123", }) if err != nil { log.Fatal(err) } fmt.Println(result.Output) ``` -------------------------------- ### Shell Command: Start Runtime with Debug Logging Source: https://github.com/cexll/agentsdk-go/blob/main/docs/migration-guide.md Command to start the runtime with debug logging enabled via the HOOK_LOG environment variable, useful for troubleshooting selector matching and timeouts. ```bash HOOK_LOG=debug ./your-runtime-command ```