Go SDK
安裝並設定 Anthropic Go SDK,支援基於 context 的取消機制與函式選項模式
Anthropic Go 函式庫讓以 Go 撰寫的應用程式能夠便利地存取 Claude API。
安裝
import (
"github.com/anthropics/anthropic-sdk-go" // imported as anthropic
)使用 go get 安裝:
go get github.com/anthropics/anthropic-sdk-go需求
此函式庫需要 Go 1.24 以上版本。
使用方式
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)
}
}
}如需了解包括 Workload Identity Federation(工作負載身分聯合)在內的驗證選項,請參閱驗證。如果您的 API 金鑰是可存取多個工作區的個人或服務帳戶金鑰,請在 anthropic-workspace-id 請求標頭中設定工作區 ID;選擇工作區說明了此 SDK 的逐請求選項。
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)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)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())
}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...))
}請求欄位
anthropic 函式庫針對請求欄位採用 Go 1.24+ encoding/json 版本中的 omitzero 語意。
必填的基本型別欄位(例如 int64 或 string)帶有 `json:"...,required"` 標籤。這些欄位一律會被序列化,即使是零值也一樣。
選填的基本型別會包裝在 param.Opt[T] 中。這些欄位可透過提供的建構函式設定,例如 anthropic.String(string) 或 anthropic.Int(int64)。
任何 param.Opt[T]、map、slice、struct 或字串列舉都使用 `json:"...,omitzero"` 標籤。其零值會被視為省略。
param.IsOmitted(any) 函式可用來確認任何 omitzero 欄位是否存在。
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
// ... 省略的非必要欄位將不會被序列化
},
Origin: anthropic.Origin{}, // the zero value of [Origin] is considered omitted
}若要傳送 null 而非 param.Opt[T],請使用 param.Null[T]()。
若要傳送 null 而非結構體 T,請使用 param.NullStruct[T]()。
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請求結構體包含 .SetExtraFields(map[string]any) 方法,可在請求主體中傳送不符合結構定義的欄位。額外欄位會覆寫任何具有相同鍵的結構體欄位。
若要傳送自訂值而非結構體,請使用泛型函式 param.Override(例如 param.Override[anthropic.FooParams](12))。
// 若 API 指定了特定型別,
// 但您想傳送其他內容,請使用 [SetExtraFields]:
p.SetExtraFields(map[string]any{
"x": 0.01, // send "x" as a float instead of int
})
// 傳送數字而非物件
custom := param.Override[anthropic.FooParams](12)請求聯集
聯集(union)以結構體表示,其每個變體對應一個以「Of」為前綴的欄位,且只能有一個欄位為非零值。非零值的欄位會被序列化。
聯集的子屬性可透過聯集結構體上的方法存取。這些方法會回傳指向底層資料的可變指標(若資料存在)。
// 只能有一個欄位為非零值,請使用 param.IsOmitted() 檢查欄位是否已設定
type AnimalUnionParam struct {
OfCat *Cat `json:",omitzero,inline"`
OfDog *Dog `json:",omitzero,inline"`
}
animal := AnimalUnionParam{
OfCat: &Cat{
Name: "Whiskers",
Owner: PersonParam{
Address: AddressParam{Street: "3333 Coyote Hill Rd", ZipCode: 0},
},
},
}
// 修改欄位
if address := animal.GetOwner().GetAddress(); address != nil {
address.ZipCode = 94304
}反序列化參數
Param 型別(以 Param 結尾的型別,例如 MessageNewParams 或 ToolUnionParam)僅設計用於送出的請求。它們可以正確地序列化為 JSON,但不完全支援往返反序列化。如果您將原始 JSON 反序列化到 param 結構體中,即使底層 JSON 有效,像 OfBashTool20250124 這類具型別的聯集欄位仍會是 nil。
如果您需要從原始 JSON 重建參數(例如來自資料庫、中介軟體或先前的請求),請呼叫 UnmarshalJSON 填入非聯集欄位,然後使用 param.SetJSON 附加原始位元組,以便正確地重新序列化:
// 序列化 params(例如用於儲存或轉發)
b, err := json.Marshal(original)
if err != nil {
panic(err)
}
// 稍後,從儲存的 JSON 重建 params
var params anthropic.MessageNewParams
if err := params.UnmarshalJSON(b); err != nil {
panic(err)
}
param.SetJSON(b, ¶ms)
// params.Model 及其他純量欄位由 UnmarshalJSON 填入。
// params.Tools[0].OfBashTool20250124 為 nil(union 的限制),
// 但原始 JSON 會被保留。當 params 再次被 marshal
// 以進行 API 呼叫時,tools 會正確序列化。
b2, _ := json.Marshal(params)
fmt.Println(string(b) == string(b2)) // true針對此使用情境,建議使用 param.SetJSON(自 v1.20.0 起提供)而非較通用的 param.Override[T](any),因為它不需要明確寫出型別參數,並且能清楚表達往返的意圖。
回應物件
回應結構體中的所有欄位都是一般的值型別(而非指標或包裝型別)。
回應結構體還包含一個特殊的 JSON 欄位,其中含有每個屬性的中繼資料。
type Animal struct {
Name string `json:"name,nullable"`
Owners int `json:"owners"`
Age int `json:"age"`
JSON struct {
Name respjson.Field
Owners respjson.Field
Age respjson.Field
ExtraFields map[string]respjson.Field
} `json:"-"`
}若要處理選填資料,請使用 JSON 欄位上的 .Valid() 方法。
當欄位存在、非 null 且成功反序列化時,.Valid() 會回傳 true。
若 .Valid() 為 false,對應的欄位將為其零值。
raw := `{"owners": 1, "name": null}`
var res Animal
json.Unmarshal([]byte(raw), &res)
// 存取一般欄位
res.Owners // 1
res.Name // ""
res.Age // 0
// 選用欄位檢查
res.JSON.Owners.Valid() // true
res.JSON.Name.Valid() // false
res.JSON.Age.Valid() // false
// 原始 JSON 值
res.JSON.Owners.Raw() // "1"
res.JSON.Name.Raw() == "null" // true
res.JSON.Name.Raw() == respjson.Null // true
res.JSON.Age.Raw() == "" // true
res.JSON.Age.Raw() == respjson.Omitted // true這些 .JSON 結構體還包含一個 ExtraFields map,其中含有 json 回應中未在結構體中指定的任何屬性。這對於 SDK 尚未支援的 API 功能很有用。
body := res.JSON.ExtraFields["my_unexpected_field"].Raw()回應聯集
在回應中,聯集以扁平化的結構體表示,其中包含每個物件變體的所有可能欄位。
若要將其轉換為某個變體,請使用 .AsFooVariant() 方法,或使用 .AsAny() 方法(若有提供)。
如果回應值聯集包含基本型別值,基本型別欄位會與其他屬性並列,但以 Of 為前綴,並帶有 json:"...,inline" 標籤。
type AnimalUnion struct {
// 來自變體 [Dog]、[Cat]
Owner Person `json:"owner"`
// 來自變體 [Dog]
DogBreed string `json:"dog_breed"`
// 來自變體 [Cat]
CatBreed string `json:"cat_breed"`
// ...
JSON struct {
Owner respjson.Field
// ...
} `json:"-"`
}
// 若為 animal 變體
if animal.Owner.Address.ZipCode == "" {
panic("missing zip code")
}
// 依變體進行 switch
switch variant := animal.AsAny().(type) {
case Dog:
case Cat:
default:
panic("unexpected type")
}錯誤處理
當 API 回傳非成功的狀態碼時,SDK 會回傳型別為 *anthropic.Error 的錯誤。其中包含該請求的 StatusCode、*http.Request 與 *http.Response 值,以及錯誤主體的 JSON(與 SDK 中其他回應物件類似)。該錯誤還包含來自回應標頭的 RequestID,這在向 Anthropic 支援團隊尋求疑難排解時很有用。
若要處理錯誤,請使用 errors.As 模式:
_, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
MaxTokens: 1024,
Messages: []anthropic.MessageParam{{
Content: []anthropic.ContentBlockParamUnion{{
OfText: &anthropic.TextBlockParam{
Text: "What is a quaternion?",
},
}},
Role: anthropic.MessageParamRoleUser,
}},
Model: anthropic.ModelClaudeOpus5,
})
if err != nil {
var apierr *anthropic.Error
if errors.As(err, &apierr) {
println("Request ID:", apierr.RequestID)
println(string(apierr.DumpRequest(true))) // Prints the serialized HTTP request
println(string(apierr.DumpResponse(true))) // Prints the serialized HTTP response
}
panic(err.Error()) // POST "/v1/messages": 400 Bad Request (Request-ID: req_xxx) { ... }
}當發生其他錯誤時,它們會以未包裝的形式回傳;例如,若 HTTP 傳輸失敗,您可能會收到包裝了 *net.OpError 的 *url.Error。
重試
某些錯誤預設會自動重試 2 次,並採用短暫的指數退避。 SDK 預設會重試所有連線錯誤、408 Request Timeout、409 Conflict、429 Rate Limit(速率限制),以及 >=500 的內部錯誤。
您可以使用 WithMaxRetries 選項來設定或停用此行為:
// 為所有請求設定預設值:
client := anthropic.NewClient(
option.WithMaxRetries(0), // default is 2
)
// 針對個別請求覆寫:
client.Messages.New(
context.TODO(),
anthropic.MessageNewParams{
MaxTokens: 1024,
Messages: []anthropic.MessageParam{{
Content: []anthropic.ContentBlockParamUnion{{
OfText: &anthropic.TextBlockParam{
Text: "What is a quaternion?",
},
}},
Role: anthropic.MessageParamRoleUser,
}},
Model: anthropic.ModelClaudeOpus5,
},
option.WithMaxRetries(5),
)逾時
非串流的 Messages 請求預設在 10 分鐘後逾時;其他請求沒有預設逾時。請使用 context 為請求生命週期設定逾時。
請注意,若請求被重試,context 逾時不會重新計算。
若要設定每次重試的逾時,請使用 option.WithRequestTimeout()。
// 此設定為請求的逾時時間,包含所有重試。
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
client.Messages.New(
ctx,
anthropic.MessageNewParams{
MaxTokens: 1024,
Messages: []anthropic.MessageParam{{
Content: []anthropic.ContentBlockParamUnion{{
OfText: &anthropic.TextBlockParam{
Text: "What is a quaternion?",
},
}},
Role: anthropic.MessageParamRoleUser,
}},
Model: anthropic.ModelClaudeOpus5,
},
// 此設定為每次重試的逾時時間
option.WithRequestTimeout(20*time.Second),
)長時間請求
請避免在未使用串流(streaming)的情況下設定過大的 MaxTokens 值,因為某些網路可能會在一段時間後中斷閒置連線,這可能導致請求失敗或逾時,而未收到來自 Anthropic 的回應。
若預期非串流請求的時間會超過約 10 分鐘,此 SDK 也會回傳錯誤。
呼叫 .Messages.NewStreaming() 或設定自訂逾時可停用此錯誤。
檔案上傳
在 multipart 請求中對應檔案上傳的請求參數,其型別為 io.Reader。io.Reader 的內容預設會以 multipart 表單部分的形式傳送,檔名為「anonymous_file」,content-type 為「application/octet-stream」,因此建議的做法是使用 anthropic.File(reader io.Reader, filename string, contentType string) 輔助函式指定自訂的 content-type,該函式會以適當的檔名與內容類型包裝任何 io.Reader。
// 來自檔案系統的檔案
file, err := os.Open("/path/to/file.json")
anthropic.FileUploadParams{
File: anthropic.File(file, "custom-name.json", "application/json"),
}
// 來自字串的檔案
anthropic.FileUploadParams{
File: anthropic.File(strings.NewReader("my file contents"), "custom-name.json", "application/json"),
}檔名與 content-type 也可以透過在 io.Reader 的執行期型別上實作 Name() string 或 ContentType() string 來自訂。請注意,os.File 實作了 Name() string,因此由 os.Open 回傳的檔案會以磁碟上的檔名傳送。
分頁
此函式庫為分頁式列表端點提供了一些便利功能。
您可以使用 .ListAutoPaging() 方法來迭代所有頁面中的項目:
iter := client.Messages.Batches.ListAutoPaging(context.TODO(), anthropic.MessageBatchListParams{
Limit: anthropic.Int(20),
})
// 視需要自動擷取更多頁面。
for iter.Next() {
messageBatch := iter.Current()
fmt.Println(messageBatch.ID)
}
if err := iter.Err(); err != nil {
panic(err.Error())
}或者,您可以使用簡單的 .List() 方法擷取單一頁面,並取得帶有額外輔助方法(例如 .GetNextPage())的標準回應物件:
page, err := client.Messages.Batches.List(context.TODO(), anthropic.MessageBatchListParams{
Limit: anthropic.Int(20),
})
for page != nil {
for _, batch := range page.Data {
fmt.Println(batch.ID)
}
page, err = page.GetNextPage()
}
if err != nil {
panic(err.Error())
}RequestOptions
此函式庫採用函式選項(functional options)模式。option 套件中定義的函式會回傳 RequestOption,它是一個會修改 RequestConfig 的閉包。這些選項可以提供給用戶端,或用於個別請求。例如:
client := anthropic.NewClient(
// 為用戶端發出的每個請求新增標頭
option.WithHeader("X-Some-Header", "custom_header_info"),
)
client.Messages.New(context.TODO(), // ...,
// 覆寫該標頭
option.WithHeader("X-Some-Header", "some_other_custom_header_info"),
// 使用 sjson 語法在請求主體中新增未記載於文件的欄位
option.WithJSONSet("some.json.path", map[string]string{"my": "object"}),
)請求選項 option.WithDebugLog(nil) 在除錯時可能會有幫助。
請參閱請求選項完整列表。
HTTP 用戶端自訂
關於請求中介軟體(option.WithMiddleware)以及替換預設的 http.Client(option.WithHTTPClient),請參閱 SDK 中介軟體。
平台整合
Go SDK 支援下列平台:
- Agent Platform:
import "github.com/anthropics/anthropic-sdk-go/vertex"。使用vertex.WithGoogleAuth(ctx, region, projectID)或vertex.WithCredentials(ctx, region, projectID, creds)。 - Bedrock:
import "github.com/anthropics/anthropic-sdk-go/bedrock"。針對 Messages-API Bedrock 端點(透過 SSE 串流)請使用bedrock.NewMantleClient,或使用bedrock.WithLoadDefaultConfig(ctx)/bedrock.WithConfig(cfg)(bedrock-runtime路徑)。匯入bedrock套件會在全域範圍內向 SDK 的串流層註冊application/vnd.amazon.eventstream的解碼器(透過套件的init())。無論您使用bedrock-runtime的WithConfig/WithLoadDefaultConfig路徑或NewMantleClient,此行為皆適用。 - Claude Platform on AWS:
import anthropicaws "github.com/anthropics/anthropic-sdk-go/aws"。使用anthropicaws.NewClient(ctx, cfg)搭配anthropicaws.ClientConfig值來建構用戶端;請在設定中設定WorkspaceID,或設定ANTHROPIC_AWS_WORKSPACE_ID環境變數。當同時匯入github.com/aws/aws-sdk-go-v2/aws時,anthropicaws匯入別名可避免名稱衝突。目前為 beta 版。 - Foundry: Go SDK 目前不支援。請參閱 Claude in Microsoft Foundry 以了解支援的 SDK。
新專案請使用 bedrock.NewMantleClient;bedrock.WithLoadDefaultConfig/WithConfig 則保留給使用 Bedrock InvokeModel API 的既有應用程式。
進階用法
存取原始回應資料(例如回應標頭)
您可以使用 option.WithResponseInto() 請求選項來存取原始 HTTP 回應資料。當您需要檢視回應標頭、狀態碼或其他細節時,這會很有用。
// 建立一個變數來儲存 HTTP 回應
var response *http.Response
message, err := client.Messages.New(
context.TODO(),
anthropic.MessageNewParams{
MaxTokens: 1024,
Messages: []anthropic.MessageParam{{
Content: []anthropic.ContentBlockParamUnion{{
OfText: &anthropic.TextBlockParam{
Text: "What is a quaternion?",
},
}},
Role: anthropic.MessageParamRoleUser,
}},
Model: anthropic.ModelClaudeOpus5,
},
option.WithResponseInto(&response),
)
if err != nil {
// 處理錯誤
}
fmt.Printf("%+v\n", message.Content)
fmt.Printf("Status Code: %d\n", response.StatusCode)
fmt.Printf("Headers: %+#v\n", response.Header)發送自訂/未記載的請求
此函式庫具備型別定義,以便利地存取已記載的 API。如果您需要存取未記載的端點、參數或回應屬性,仍然可以使用此函式庫。
未記載的端點
若要向未記載的端點發送請求,您可以使用 client.Get、client.Post 及其他 HTTP 動詞。
發送這些請求時,用戶端上的 RequestOptions(例如重試)仍會生效。
var (
// params 可以是 io.Reader、[]byte、可由 encoding/json 序列化的物件,
// 或本函式庫中定義的「...Params」結構體。
params map[string]any
// result 可以是 []byte、*http.Response、可由 encoding/json 反序列化的物件,
// 或本函式庫中定義的模型。
result *http.Response
)
err := client.Post(context.Background(), "/unspecified", params, &result)
if err != nil {
// ...
}未記載的請求參數
若要使用未記載的參數發送請求,您可以使用 option.WithQuerySet() 或 option.WithJSONSet() 方法。
params := FooNewParams{
ID: "id_xxxx",
Data: FooNewParamsData{
FirstName: anthropic.String("John"),
},
}
client.Foo.New(context.Background(), params, option.WithJSONSet("data.last_name", "Doe"))未記載的回應屬性
若要存取未記載的回應屬性,您可以透過 result.JSON.RawJSON() 以字串形式存取回應的原始 JSON,或透過 result.JSON.Foo.Raw() 取得結果中特定欄位的原始 JSON。
任何不存在於回應結構體上的欄位都會被保存,並可透過 result.JSON.ExtraFields 存取,其型別為 map[string]respjson.Field。
語意化版本
此套件大致遵循 SemVer 慣例,但某些不向後相容的變更可能會以次要版本發布:
- 對函式庫內部的變更,這些內部在技術上是公開的,但並非設計或記載供外部使用。
- 預期實際上不會影響絕大多數使用者的變更。
我們非常重視向後相容性,以確保您能享有順暢的升級體驗。
歡迎您提供回饋;如有問題、錯誤或建議,請開立 issue。
其他資源
Was this page helpful?