Claude Platform Docs
CLI、SDK 與函式庫用戶端 SDK

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 的逐請求選項。

請求欄位

anthropic 函式庫針對請求欄位採用 Go 1.24+ encoding/json 版本中的 omitzero 語意。

必填的基本型別欄位(例如 int64string)帶有 `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 結尾的型別,例如 MessageNewParamsToolUnionParam)僅設計用於送出的請求。它們可以正確地序列化為 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, &params)

// 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.Readerio.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() stringContentType() 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.Clientoption.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-runtimeWithConfig/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.NewMantleClientbedrock.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.Getclient.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 慣例,但某些不向後相容的變更可能會以次要版本發布:

  1. 對函式庫內部的變更,這些內部在技術上是公開的,但並非設計或記載供外部使用。
  2. 預期實際上不會影響絕大多數使用者的變更。

我們非常重視向後相容性,以確保您能享有順暢的升級體驗。

歡迎您提供回饋;如有問題、錯誤或建議,請開立 issue

其他資源

Was this page helpful?