Anthropic Go 函式庫讓以 Go 撰寫的應用程式能夠方便地存取 Anthropic REST API。
如需包含程式碼範例的 API 功能文件,請參閱 API 參考。本頁涵蓋 Go 特有的 SDK 功能與設定。
import (
"github.com/anthropics/anthropic-sdk-go" // imported as anthropic
)使用 go get 安裝:
go get github.com/anthropics/anthropic-sdk-go此函式庫需要 Go 1.23+。
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」(工作負載身分聯合)在內的驗證選項,請參閱驗證。
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 而非 struct 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請求 struct 包含一個 .SetExtraFields(map[string]any) 方法,可以在請求主體中傳送不符合規範的
欄位。額外欄位會覆寫任何具有相同鍵的 struct 欄位。
基於安全考量,請僅對受信任的資料使用 SetExtraFields。
若要傳送自訂值而非 struct,請使用泛型函式 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)以 struct 表示,其每個變體的欄位都以「Of」為前綴, 只有一個欄位可以是非零值。非零值的欄位將會被序列化。
聯集的子屬性可以透過聯集 struct 上的方法存取。 如果存在,這些方法會回傳指向底層資料的可變指標。
// 只有一個欄位可以是非零值,使用 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.SetJSON 需要 SDK v1.20.0 或更新版本。
參數型別(以 Param 結尾的型別,例如 MessageNewParams 或 ToolUnionParam)僅設計用於傳出請求。它們可以正確地序列化為 JSON,但不完全支援往返反序列化。如果您將原始 JSON 反序列化到參數 struct 中,即使底層 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 再次被序列化
// 以進行 API 呼叫時,工具會正確序列化。
b2, _ := json.Marshal(params)
fmt.Println(string(b) == string(b2)) // true對於此使用情境,param.SetJSON(自 v1.20.0 起可用)比更通用的 param.Override[T](any) 更為推薦,因為它不需要明確指定型別參數,並使往返意圖更加明確。
回應 struct 中的所有欄位都是一般的值型別(而非指標或包裝器)。
回應 struct 也包含一個特殊的 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 struct 也包含一個 ExtraFields map,其中包含
json 回應中未在 struct 中指定的任何屬性。這對於 SDK 中
尚未提供的 API 功能很有用。
body := res.JSON.ExtraFields["my_unexpected_field"].Raw()在回應中,聯集以一個扁平化的 struct 表示,其中包含每個物件變體的所有可能欄位。
若要將其轉換為變體,請使用 .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 次,並採用短暫的指數退避(exponential backoff)。 SDK 預設會重試所有連線錯誤、408 Request Timeout、409 Conflict、429 Rate Limit 以及 >=500 Internal 錯誤。
您可以使用 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),
)對於執行時間較長的請求,請考慮使用串流 Messages API。
避免在不使用串流的情況下設定較大的 MaxTokens 值,因為某些網路可能會在一段時間後中斷閒置連線,
這可能導致請求失敗或逾時而未收到來自 Anthropic 的回應。
如果非串流請求預計會超過大約 10 分鐘,此 SDK 也會回傳錯誤。
呼叫 .Messages.NewStreaming() 或設定自訂逾時可停用此錯誤。
在 multipart 請求中對應於檔案上傳的請求參數型別為
io.Reader。io.Reader 的內容預設會以檔案名稱「anonymous_file」和 content-type「application/octet-stream」作為 multipart 表單
部分傳送,因此建議的做法是使用 anthropic.File(reader io.Reader, filename string, contentType string)
輔助函式指定自訂的 content-type,它會以適當的檔案名稱和內容類型包裝任何 io.Reader。
// 來自檔案系統的檔案
file, err := os.Open("/path/to/file.json")
anthropic.BetaFileUploadParams{
File: anthropic.File(file, "custom-name.json", "application/json"),
}
// 來自字串的檔案
anthropic.BetaFileUploadParams{
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.Printf("%+v\n", messageBatch)
}
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.Printf("%+v\n", batch)
}
page, err = page.GetNextPage()
}
if err != nil {
panic(err.Error())
}此函式庫使用函式選項(functional options)模式。在
option 套件中定義的函式會回傳一個 RequestOption,這是一個會變更
RequestConfig 的閉包(closure)。這些選項可以提供給用戶端或個別
請求。例如:
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) 可能會有所幫助。
請參閱完整的請求選項列表。
關於請求中介軟體(option.WithMiddleware)以及替換預設的 http.Client(option.WithHTTPClient),請參閱 SDK 中介軟體。
如需包含程式碼範例的詳細平台設定指南,請參閱:
Go SDK 支援以下平台:
import "github.com/anthropics/anthropic-sdk-go/vertex"。使用 vertex.WithGoogleAuth(ctx, region, projectID) 或 vertex.WithCredentials(ctx, region, projectID, creds)。import "github.com/anthropics/anthropic-sdk-go/bedrock"。對於 Messages-API Bedrock 端點(透過 SSE 串流),請使用 bedrock.NewMantleClient;或使用 bedrock.WithLoadDefaultConfig(ctx) / bedrock.WithConfig(cfg)(bedrock-runtime 路徑)。匯入 bedrock 套件會(透過套件的 init())在 SDK 的串流層全域註冊一個 application/vnd.amazon.eventstream 的解碼器。無論您使用 bedrock-runtime 的 WithConfig/WithLoadDefaultConfig 路徑還是 NewMantleClient,這都適用。import anthropicaws "github.com/anthropics/anthropic-sdk-go/aws"。使用 anthropicaws.NewClient(ctx, cfg) 搭配 anthropicaws.ClientConfig 值來建構用戶端;在設定中設定 WorkspaceID 或使用 ANTHROPIC_AWS_WORKSPACE_ID 環境變數。anthropicaws 匯入別名可避免在同時匯入 github.com/aws/aws-sdk-go-v2/aws 時發生名稱衝突。目前為 beta 版。新專案請使用 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)
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。
任何不存在於回應 struct 上的欄位都會被保存,並可透過 result.JSON.ExtraFields 存取,它是一個 map[string]respjson.Field。
此套件大致遵循 SemVer 慣例,但某些不向後相容的變更可能會以次要版本發布:
我們嚴肅看待向後相容性,以確保您能享有順暢的升級體驗。
歡迎您提供回饋;如有問題、錯誤或建議,請開啟一個 issue。
Was this page helpful?