Claude SDK for Go

repository·main·Indexed 22 days ago

https://github.com/anthropics/anthropic-sdk-go

A type-safe Go SDK for interacting with the Anthropic Claude API. It provides interfaces for the Messages API, including token counting and batch management, as well as model information retrieval. The SDK supports advanced features such as tool use (web search, web fetch, bash, and text editor), thinking mode configuration, and beta model capabilities. Requires Go 1.24+.

Tokens
61.1K
Snippets
159
Records
237
Agent score
77%

What's inside anthropic-sdk-go

  1. Manage managed-agents sessions

    main

    The SDK provides tools for interacting with managed-agents sessions.

    • Session Tool Runner: Use client.Beta.Sessions.Events.NewToolRunner to attach a tool registry to a session's event stream. It dispatches tools on both agent.tool_use and agent.custom_tool_use events.
    • Self-Hosted Environment Worker: Use environments.NewEnvironmentWorker for a full self-hosted runner. This composes a work poller with a session tool runner, handles skill downloads, and manages work-item leases/heartbeats.

    Standard agent tools (like bash, read, write) are available in the github.com/anthropics/anthropic-sdk-go/tools/agenttoolset package.

  2. Handle Tool Results and Blocks

    main

    When a model uses a tool, the response includes blocks that you must handle. Key types include:

    • ToolUseBlockParam: Represents the model's request to use a tool.
    • ToolResultBlockParam: Represents the result of a tool execution that you provide back to the model.
    • ToolReferenceBlockParam: Used for referencing tools.

    Specific tool implementations have their own result types, such as WebFetchToolResultBlockParam or WebSearchToolResultBlockParam.

  3. Understand Message parameter types

    main
    The SDK uses specific parameter types to construct messages for the Claude API. When using the Messages API, you must provide parameters that define the role and content of each message in the conversation history. These types ensure that the structure of the conversation (e.g., alternating user and assistant roles) adheres to the API requirements.
  4. Handle tool execution errors

    main

    If a tool handler returns an error, the SDK automatically converts that error into a tool result with is_error: true and sends it back to Claude. This allows the model to see the error and attempt to recover or try a different approach.

    func handler(ctx context.Context, input MyInput) (anthropic.BetaToolResultBlockParamContentUnion, error) {
    	if input.City == "" {
    		return anthropic.BetaToolResultBlockParamContentUnion{}, errors.New("city is required")
    	}
    	// ...
    }
  5. Define tools using toolrunner

    main

    The toolrunner package allows you to create BetaTool objects, which pair a tool's JSON schema definition with a Go handler function. The generic type of the handler is automatically inferred from its signature. There are three primary ways to define a tool:

    1. Automatic Schema Generation (Recommended): Use NewBetaToolFromJSONSchema. This uses jsonschema tags on a Go struct to generate the required JSON schema.
    2. JSON Bytes: Use NewBetaToolFromBytes to provide a raw JSON schema as a byte slice.
    3. Explicit Schema: Use NewBetaTool to pass a BetaToolInputSchemaParam for full manual control.

    If you want to handle parsing manually, you can use json.RawMessage or []byte as the input type in your handler.

    type GetWeatherInput struct {
    	City  string `json:"city" jsonschema:"required,description=The city name"`
    	Units string `json:"units,omitempty" jsonschema:"enum=celsius,enum=fahrenheit,description=Temperature units"`
    }
    
    weatherTool, err := toolrunner.NewBetaToolFromJSONSchema(
    	"get_weather",
    	"Get current weather for a city",
    	func(ctx context.Context, input GetWeatherInput) (anthropic.BetaToolResultBlockParamContentUnion, error) {
    		return anthropic.BetaToolResultBlockParamContentUnion{
    			OfText: &anthropic.BetaTextBlockParam{
    				Text: fmt.Sprintf("Weather in %s: 72°F, sunny", input.City),
    			},
    		}, nil
    },
    )
  6. Use BetaToolRunner to automate the conversation loop

    main

    The BetaToolRunner manages the iterative loop between Claude and your tools. It automatically sends messages, executes tool calls in parallel, adds results back to the conversation, and repeats until Claude provides a final response.

    Execution Modes

    • RunToCompletion: Executes the entire loop until no more tool calls are requested.
    • Iterating (All): Use runner.All(ctx) to iterate over every message generated during the conversation.
    • Step-by-Step (NextMessage): Use runner.NextMessage(ctx) to advance the conversation one turn at a time for manual control.

    Streaming

    For real-time responses, use NewToolRunnerStreaming(). You can iterate over events using runner.AllStreaming(ctx) or step through them with runner.NextStreaming(ctx).

    tools := []anthropic.BetaTool{weatherTool}
    
    runner := client.Beta.Messages.NewToolRunner(tools, anthropic.BetaToolRunnerParams{
    	BetaMessageNewParams: anthropic.BetaMessageNewParams{
    		Model:     anthropic.ModelClaudeSonnet4_5_20250929,
    		MaxTokens: 1024,
    		Messages: []anthropic.BetaMessageParam{
    			anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("What's the weather in Tokyo?")),
    		},
    	},
    })
    
    // Run the entire conversation to completion
    message, err := runner.RunToCompletion(context.Background())
  7. Get started with the Claude SDK

    main

    To use the SDK, initialize a client using anthropic.NewClient. You can provide an API key using option.WithAPIKey. If no option is provided, the client defaults to looking up the ANTHROPIC_API_KEY environment variable.

    To create a message, use the client.Messages.New method, which requires a context.Context and a anthropic.MessageNewParams object. The parameters object allows you to specify MaxTokens, the Messages array (constructed using helpers like anthropic.NewUserMessage), and the Model (e.g., anthropic.ModelClaudeOpus4_6).

    package main
    
    import (
    	"context"
    	"fmt"
    
    	"github.com/anthropics/anthropic-sdk-go"
    	"github.com/anthropics/anthropic-sdk-go/option"
    )
    
    func main() {
    	client := anthropic.NewClient(
    		option.WithAPIKey("my-anthropic-api-key"), // defaults to os.LookupEnv("ANTHROPIC_API_KEY")
    	)
    	message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
    		MaxTokens: 1024,
    		Messages: []anthropic.MessageParam{
    			anthropic.NewUserMessage(anthropic.NewTextBlock("What is a quaternion?")),
    		},
    		Model: anthropic.ModelClaudeOpus4_6,
    	})
    	if err != nil {
    		panic(err.Error())
    	}
    	fmt.Printf("%+v\n", message.Content)
    }
  8. Install the Claude SDK for Go

    main

    You can install the SDK by adding the import path to your Go files or by explicitly running the go get command to fetch a specific version.

    Import path: github.com/anthropics/anthropic-sdk-go (commonly aliased as anthropic)

    To install version v1.61.0 specifically, use:

    go get -u 'github.com/anthropics/anthropic-sdk-go@v1.61.0'
  9. Manage skills with BetaSkillService

    main

    The BetaSkillService provides methods to manage Anthropic skills via the API. It includes functionality to create, retrieve, list, and delete skills.

    Note: You should not instantiate this service directly. Instead, use the NewBetaSkillService method. Unlike the main client, this service does not automatically read variables from the environment.

    Key methods:

    • New: Creates a new skill using multipart file uploads.
    • Get: Retrieves a specific skill by its ID.
    • List: Lists skills with support for pagination and filtering by source.
    • ListAutoPaging: A convenience method for automatically iterating through all pages of skills.
    • Delete: Removes a specific skill by its ID.
  10. Configure Cloud Environment Networking

    main

    When using cloud environments, you can configure networking via BetaCloudConfigParamsNetworkingUnion. This union supports two variants:

    1. Unrestricted: Provides unrestricted network access.
    2. Limited: Provides restricted access. You can configure:
      • AllowMCPServers: Permits outbound access to MCP server endpoints.
      • AllowPackageManagers: Permits outbound access to public package registries (e.g., PyPI, npm).
      • AllowedHosts: A list of specific domains the container can reach.

    Use the AsUnrestricted() or AsLimited() methods on BetaCloudConfigNetworkingUnion to access the specific variant.

    switch variant := networkingUnion.AsAny().(type) {
    case anthropic.BetaUnrestrictedNetwork:
    	// Handle unrestricted
    case anthropic.BetaLimitedNetwork:
    	// Handle limited
    default:
    	// Handle error
    }
  11. Manage Managed Agents Session updates

    main

    When updating a Managed Agents session, you can perform a mid-session configuration update for the agent. Note that only tools and mcp_servers are updatable.

    Important: Updates are full replacements. To preserve existing entries, you must first GET the session, modify the array locally, and then POST the entire updated array back. Sending an empty array will clear the existing tools or MCP servers.