go
cli-sdks-libraries/sdks/go
History
cli-sdks-libraries/sdks/go Changed · +1 / -1 lines
} ``` -For authentication options including Workload Identity Federation, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication). +For authentication options including Workload Identity Federation, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication). If your API key is a [personal or service account key](https://platform.claude.com/docs/en/manage-claude/authentication#key-types) with access to multiple workspaces, set the workspace ID in the `anthropic-workspace-id` request header; [Select a workspace](https://platform.claude.com/docs/en/manage-claude/authentication#select-a-workspace) shows the per-request option for this SDK. <AccordionGroup> <Accordion title="Conversations">
cli-sdks-libraries/sdks/go Changed · +3 / -3 lines
## Requirements -This library requires Go 1.23+. +This library requires Go 1.24+. ## Usage
```go // A file from the file system file, err := os.Open("/path/to/file.json") -anthropic.BetaFileUploadParams{ +anthropic.FileUploadParams{ File: anthropic.File(file, "custom-name.json", "application/json"), } // A file from a string -anthropic.BetaFileUploadParams{ +anthropic.FileUploadParams{ File: anthropic.File(strings.NewReader("my file contents"), "custom-name.json", "application/json"), } ```
cli-sdks-libraries/sdks/go First recorded · 752 lines, first recorded
## Installation ## Requirements ## Usage ## Request fields ### Request unions ### Deserializing params ## Response objects ### Response unions ## Error handling ## Retries ## Timeouts ## Long requests ## File uploads ## Pagination ## RequestOptions ## HTTP client customization ## Platform integrations ## Advanced usage ### Accessing raw response data (for example, response headers) ### Making custom/undocumented requests #### Undocumented endpoints #### Undocumented request params #### Undocumented response properties ## Semantic versioning ## Additional resources
The first capture of this source. The page was already there, and this is what it said.
---
title: Go SDK
url: https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/go
description: Install and configure the Anthropic Go SDK with context-based cancellation and functional options
---
The Anthropic Go library provides convenient access to the Claude API from applications written in Go.
<Info>
For API feature documentation with code examples, see the [API reference](https://platform.claude.com/docs/en/api/overview). This page covers Go-specific SDK features and configuration.
</Info>
## Installation
```go
import (
"github.com/anthropics/anthropic-sdk-go" // imported as anthropic
)
```
Install with `go get`:
```bash
go get github.com/anthropics/anthropic-sdk-go
```
## Requirements
This library requires Go 1.23+.
## Usage
```go
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.ModelClaudeOpus5,
})
if err != nil {
panic(err.Error())
}
for _, block := range message.Content {
if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {
fmt.Println(textBlock.Text)
}
}
}
```
For authentication options including Workload Identity Federation, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication).
<AccordionGroup>
<Accordion title="Conversations">
```go
messages := []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock("What is my first name?")),
}
message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus5,
Messages: messages,
MaxTokens: 1024,
})
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", message.Content)
messages = append(messages, message.ToParam())
messages = append(messages, anthropic.NewUserMessage(
anthropic.NewTextBlock("My full name is John Doe"),
))
message, err = client.Messages.New(context.TODO(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus5,
Messages: messages,
MaxTokens: 1024,
})
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", message.Content)
```
</Accordion>
<Accordion title="System prompts">
```go
message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus5,
MaxTokens: 1024,
System: []anthropic.TextBlockParam{
{Text: "Be very serious at all times."},
},
Messages: messages,
})
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", message.Content)
```
</Accordion>
<Accordion title="Streaming">
```go
content := "What is a quaternion?"
stream := client.Messages.NewStreaming(context.TODO(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus5,
MaxTokens: 1024,
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock(content)),
},
})
message := anthropic.Message{}
for stream.Next() {
event := stream.Current()
err := message.Accumulate(event)
if err != nil {
panic(err)
}
switch eventVariant := event.AsAny().(type) {
case anthropic.ContentBlockDeltaEvent:
switch deltaVariant := eventVariant.Delta.AsAny().(type) {
case anthropic.TextDelta:
print(deltaVariant.Text)
}
}
}
if stream.Err() != nil {
panic(stream.Err())
}
```
</Accordion>
<Accordion title="Tool calling">
```go
messages := []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock(content)),
}
toolParams := []anthropic.ToolParam{
{
Name: "get_coordinates",
Description: anthropic.String("Accepts a place as an address, then returns the latitude and longitude coordinates."),
InputSchema: GetCoordinatesInputSchema,
},
}
tools := make([]anthropic.ToolUnionParam, len(toolParams))
for i, toolParam := range toolParams {
tools[i] = anthropic.ToolUnionParam{OfTool: &toolParam}
}
for {
message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus5,
MaxTokens: 1024,
Messages: messages,
Tools: tools,
})
if err != nil {
panic(err)
}
print(color("[assistant]: "))
for _, block := range message.Content {
switch block := block.AsAny().(type) {
case anthropic.TextBlock:
println(block.Text)
println()
case anthropic.ToolUseBlock:
inputJSON, _ := json.Marshal(block.Input)
println(block.Name + ": " + string(inputJSON))
println()
}
}
messages = append(messages, message.ToParam())
toolResults := []anthropic.ContentBlockParamUnion{}
for _, block := range message.Content {
switch variant := block.AsAny().(type) {
case anthropic.ToolUseBlock:
print(color("[user (" + block.Name + ")]: "))
var response interface{}
switch block.Name {
case "get_coordinates":
var input struct {
Location string `json:"location"`
}
err := json.Unmarshal([]byte(variant.JSON.Input.Raw()), &input)
if err != nil {
panic(err)
}
response = GetCoordinates(input.Location)
}
b, err := json.Marshal(response)
if err != nil {
panic(err)
}
println(string(b))
toolResults = append(toolResults, anthropic.NewToolResultBlock(block.ID, string(b), false))
}
}
if len(toolResults) == 0 {
break
}
messages = append(messages, anthropic.NewUserMessage(toolResults...))
}
```
</Accordion>
</AccordionGroup>
## Request fields
The anthropic library uses the [`omitzero`](https://tip.golang.org/doc/go1.24#encodingjsonpkgencodingjson) semantics from the Go 1.24+ `encoding/json` release for request fields.
Required primitive fields (such as `int64` or `string`) feature the tag `` `json:"...,required"` ``. These fields are always serialized, even their zero values.
Optional primitive types are wrapped in a `param.Opt[T]`. These fields can be set with the provided constructors, such as `anthropic.String(string)` or `anthropic.Int(int64)`.
Any `param.Opt[T]`, map, slice, struct or string enum uses the tag `` `json:"...,omitzero"` ``. Its zero value is considered omitted.
The `param.IsOmitted(any)` function can confirm the presence of any `omitzero` field.
```go
p := anthropic.ExampleParams{
ID: "id_xxx", // required property
Name: anthropic.String("..."), // optional property
Point: anthropic.Point{
X: 0, // required field will serialize as 0
Y: anthropic.Int(1), // optional field will serialize as 1
// ... omitted non-required fields will not be serialized
},
Origin: anthropic.Origin{}, // the zero value of [Origin] is considered omitted
}
```
To send `null` instead of a `param.Opt[T]`, use `param.Null[T]()`. To send `null` instead of a struct `T`, use `param.NullStruct[T]()`.
```go
p.Name = param.Null[string]() // 'null' instead of string
p.Point = param.NullStruct[Point]() // 'null' instead of struct
param.IsNull(p.Name) // true
param.IsNull(p.Point) // true
```
Request structs contain a `.SetExtraFields(map[string]any)` method which can send non-conforming fields in the request body. Extra fields overwrite any struct fields with a matching key.
<Warning>
For security reasons, only use `SetExtraFields` with trusted data.
</Warning>
To send a custom value instead of a struct, use the generic function `param.Override` (for example, `param.Override[anthropic.FooParams](12)`).
```go
// In cases where the API specifies a given type,
// but you want to send something else, use [SetExtraFields]:
p.SetExtraFields(map[string]any{
"x": 0.01, // send "x" as a float instead of int
})
// Send a number instead of an object
custom := param.Override[anthropic.FooParams](12)
```
### Request unions
Cut at 300 lines.