Skip to content

参考数据:Claude API 参考 — Go

Data: Claude API reference — Go

v2.1.63

Go SDK reference

Claude API — Go

注意: Go SDK 支持 Claude API 和通过 BetaToolRunner 进行的 beta 工具使用。Agent SDK 尚未适用于 Go。

安装

bash
go get github.com/anthropics/anthropic-sdk-go

客户端初始化

go
import (
    "github.com/anthropics/anthropic-sdk-go"
    "github.com/anthropics/anthropic-sdk-go/option"
)

// 默认(使用 ANTHROPIC_API_KEY 环境变量)
client := anthropic.NewClient()

// 显式指定 API key
client := anthropic.NewClient(
    option.WithAPIKey("your-api-key"),
)

基础消息请求

go
response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
    Model:     anthropic.ModelClaudeOpus4_6,
    MaxTokens: 1024,
    Messages: []anthropic.MessageParam{
        anthropic.NewUserMessage(anthropic.NewTextBlock("What is the capital of France?")),
    },
})
if err != nil {
    log.Fatal(err)
}
fmt.Println(response.Content[0].Text)

流式传输

go
stream := client.Messages.NewStreaming(context.TODO(), anthropic.MessageNewParams{
    Model:     anthropic.ModelClaudeOpus4_6,
    MaxTokens: 1024,
    Messages: []anthropic.MessageParam{
        anthropic.NewUserMessage(anthropic.NewTextBlock("Write a haiku")),
    },
})

for stream.Next() {
    event := stream.Current()
    switch eventVariant := event.AsAny().(type) {
    case anthropic.ContentBlockDeltaEvent:
        switch deltaVariant := eventVariant.Delta.AsAny().(type) {
        case anthropic.TextDelta:
            fmt.Print(deltaVariant.Text)
        }
    }
}
if err := stream.Err(); err != nil {
    log.Fatal(err)
}

工具使用

工具运行器(Beta — 推荐)

Beta: Go SDK 通过 toolrunner 包提供了 BetaToolRunner,用于自动化的工具使用循环。

go
import (
    "context"
    "fmt"
    "log"

    "github.com/anthropics/anthropic-sdk-go"
    "github.com/anthropics/anthropic-sdk-go/toolrunner"
)

// 使用 jsonschema 标签定义工具输入,用于自动生成 schema
type GetWeatherInput struct {
    City string `json:"city" jsonschema:"required,description=The city name"`
}

// 从结构体标签自动生成 schema 来创建工具
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("The weather in %s is sunny, 72°F", input.City),
            },
        }, nil
    },
)
if err != nil {
    log.Fatal(err)
}

// 创建一个能自动处理对话循环的工具运行器
runner := client.Beta.Messages.NewToolRunner(
    []anthropic.BetaTool{weatherTool},
    anthropic.BetaToolRunnerParams{
        BetaMessageNewParams: anthropic.BetaMessageNewParams{
            Model:     anthropic.ModelClaudeOpus4_6,
            MaxTokens: 1024,
            Messages: []anthropic.BetaMessageParam{
                anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("What's the weather in Paris?")),
            },
        },
        MaxIterations: 5,
    },
)

// 运行直到 Claude 产生最终响应
message, err := runner.RunToCompletion(context.Background())
if err != nil {
    log.Fatal(err)
}
fmt.Println(message.Content[0].Text)

Go 工具运行器的关键特性:

  • 通过 jsonschema 标签从 Go 结构体自动生成 schema
  • RunToCompletion() 用于简单的一次性使用
  • All() 迭代器用于处理对话中的每条消息
  • NextMessage() 用于逐步迭代
  • 通过 NewToolRunnerStreaming()AllStreaming() 提供流式传输变体

手动循环

如需细粒度控制,可通过 JSON schema 使用原始工具定义。有关工具定义格式和智能体循环模式,请参阅共享的工具使用概念


英文原文 / English Original

Claude API — Go

Note: The Go SDK supports the Claude API and beta tool use with BetaToolRunner. Agent SDK is not yet available for Go.

Installation

bash
go get github.com/anthropics/anthropic-sdk-go

Client Initialization

go
import (
    "github.com/anthropics/anthropic-sdk-go"
    "github.com/anthropics/anthropic-sdk-go/option"
)

// Default (uses ANTHROPIC_API_KEY env var)
client := anthropic.NewClient()

// Explicit API key
client := anthropic.NewClient(
    option.WithAPIKey("your-api-key"),
)

Basic Message Request

go
response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
    Model:     anthropic.ModelClaudeOpus4_6,
    MaxTokens: 1024,
    Messages: []anthropic.MessageParam{
        anthropic.NewUserMessage(anthropic.NewTextBlock("What is the capital of France?")),
    },
})
if err != nil {
    log.Fatal(err)
}
fmt.Println(response.Content[0].Text)

Streaming

go
stream := client.Messages.NewStreaming(context.TODO(), anthropic.MessageNewParams{
    Model:     anthropic.ModelClaudeOpus4_6,
    MaxTokens: 1024,
    Messages: []anthropic.MessageParam{
        anthropic.NewUserMessage(anthropic.NewTextBlock("Write a haiku")),
    },
})

for stream.Next() {
    event := stream.Current()
    switch eventVariant := event.AsAny().(type) {
    case anthropic.ContentBlockDeltaEvent:
        switch deltaVariant := eventVariant.Delta.AsAny().(type) {
        case anthropic.TextDelta:
            fmt.Print(deltaVariant.Text)
        }
    }
}
if err := stream.Err(); err != nil {
    log.Fatal(err)
}

Tool Use

Beta: The Go SDK provides BetaToolRunner for automatic tool use loops via the toolrunner package.

go
import (
    "context"
    "fmt"
    "log"

    "github.com/anthropics/anthropic-sdk-go"
    "github.com/anthropics/anthropic-sdk-go/toolrunner"
)

// Define tool input with jsonschema tags for automatic schema generation
type GetWeatherInput struct {
    City string `json:"city" jsonschema:"required,description=The city name"`
}

// Create a tool with automatic schema generation from struct tags
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("The weather in %s is sunny, 72°F", input.City),
            },
        }, nil
    },
)
if err != nil {
    log.Fatal(err)
}

// Create a tool runner that handles the conversation loop automatically
runner := client.Beta.Messages.NewToolRunner(
    []anthropic.BetaTool{weatherTool},
    anthropic.BetaToolRunnerParams{
        BetaMessageNewParams: anthropic.BetaMessageNewParams{
            Model:     anthropic.ModelClaudeOpus4_6,
            MaxTokens: 1024,
            Messages: []anthropic.BetaMessageParam{
                anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("What's the weather in Paris?")),
            },
        },
        MaxIterations: 5,
    },
)

// Run until Claude produces a final response
message, err := runner.RunToCompletion(context.Background())
if err != nil {
    log.Fatal(err)
}
fmt.Println(message.Content[0].Text)

Key features of the Go tool runner:

  • Automatic schema generation from Go structs via jsonschema tags
  • RunToCompletion() for simple one-shot usage
  • All() iterator for processing each message in the conversation
  • NextMessage() for step-by-step iteration
  • Streaming variant via NewToolRunnerStreaming() with AllStreaming()

Manual Loop

For fine-grained control, use raw tool definitions via JSON schema. See the shared tool use concepts for the tool definition format and agentic loop pattern.