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

Go SDK

安裝並設定 Anthropic Go SDK,支援基於 context 的取消機制與函式選項

Anthropic Go 函式庫讓以 Go 撰寫的應用程式能夠便利地存取 Claude API。

安裝

import (
	"github.com/anthropics/anthropic-sdk-go/v2" // imported as anthropic
)

使用 go get 安裝:

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

需求

此函式庫需要 Go 1.25+。

使用方式

package main

import (
	"context"
	"fmt"

	"github.com/anthropics/anthropic-sdk-go/v2"
	"github.com/anthropics/anthropic-sdk-go/v2/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_5,
	})
	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 的逐請求選項,請參閱開發者 API 金鑰頁面上的選擇工作區。

請求欄位

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 欄位。

若要傳送自訂值而非 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 結尾的型別,例如 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, &params)

// params.Model 及其他純量欄位會由 UnmarshalJSON 填入。
// params.Tools[0].OfBashTool20250124 為 nil(聯集的限制),
// 但原始 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),因為它不需要明確寫出型別參數,並且能清楚表達往返的意圖。

回應物件

回應 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{
		anthropic.NewUserMessage(anthropic.NewTextBlock("What is a quaternion?")),
	},
	Model: anthropic.ModelClaudeOpus5_5,
})
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 狀態進行分支處理,請參閱處理錯誤。

發生其他錯誤時,它們會以未包裝的形式回傳;例如, 如果 HTTP 傳輸失敗,您可能會收到包裝了 *net.OpError 的 *url.Error。

重試

SDK 預設會對某些錯誤最多重試兩次(總共三次嘗試)。對於某些建立方法,它重試的情況較少。

對於大多數方法,例如 client.Messages.New(),SDK 會重試連線錯誤、逾時、408 Request Timeout、409 Conflict、 429 Too Many Requests,以及 5xx 伺服器錯誤。

對於這些方法,如果回應帶有 x-should-retry 標頭(true 或 false),SDK 會依照該標頭而非狀態碼來決定。在兩次嘗試之間,SDK 會依 retry-after 標頭指示的時間等待,或採用短暫的指數退避。

使用 option.WithMaxRetries() 來設定或停用重試:

// 設定所有請求的預設值:
client := anthropic.NewClient(
	option.WithMaxRetries(0), // default is 2
)

// 針對個別請求覆寫:

	client.Messages.New(
		context.TODO(),
		anthropic.MessageNewParams{
			MaxTokens: 1024,
			Messages: []anthropic.MessageParam{
				anthropic.NewUserMessage(anthropic.NewTextBlock("What is a quaternion?")),
			},
			Model: anthropic.ModelClaudeOpus5_5,
		},
		option.WithMaxRetries(5),
	)

建立方法的重試

為了避免產生重複的資源,SDK 對某些建立方法(例如 client.Beta.Agents.New())僅在兩種情況下進行重試:

  • API 回傳 429 Too Many Requests 回應。
  • SDK 無法連線至 API,因此從未送出請求。

在這兩種情況下,API 都尚未處理該請求,因此重試不會建立第二個資源。

這些方法在遇到任何其他錯誤時都會直接回傳而不重試,即使回應帶有 x-should-retry: true 也一樣。如果發生了伺服器錯誤,或是 SDK 送出請求後連線中斷或逾時,API 可能已經建立了該資源。再次呼叫該方法之前,請先確認該資源是否存在。

逾時

非串流的 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{
				anthropic.NewUserMessage(anthropic.NewTextBlock("What is a quaternion?")),
			},
			Model: anthropic.ModelClaudeOpus5_5,
		},
		// 此設定每次重試的逾時時間
		option.WithRequestTimeout(20*time.Second),
	)

長時間請求

請避免在未使用串流的情況下設定較大的 MaxTokens 值,因為某些網路可能會在一段時間後中斷閒置連線,這 可能導致請求失敗或在未收到 Anthropic 回應的情況下逾時。

如果預期非串流請求的時間會超過約 10 分鐘,此 SDK 也會回傳錯誤。 呼叫 .Messages.NewStreaming() 或設定自訂逾時可停用此錯誤。

檔案上傳

對應於 multipart 請求中檔案上傳的請求參數,其型別為 io.Reader。io.Reader 的內容預設會以 multipart 表單 部分傳送,檔名為 anonymous_file,內容類型為 application/octet-stream。因此,建議的做法是使用 anthropic.File(reader io.Reader, filename string, contentType string) 輔助函式指定自訂內容類型。此輔助函式會以適當的檔名與內容類型包裝任何 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"),
}

也可以透過在 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 pattern」(函式選項模式)。定義於 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 支援以下平台:

  • Claude Models on Google Cloud (Google managed): import "github.com/anthropics/anthropic-sdk-go/v2/vertex"。使用 vertex.WithGoogleAuth(ctx, region, projectID) 或 vertex.WithCredentials(ctx, region, projectID, creds)。
  • Bedrock: import "github.com/anthropics/anthropic-sdk-go/v2/bedrock"。您使用的方式取決於端點:
    • bedrock-mantle: bedrock.NewMantleClient。它透過 SSE 串流。
    • bedrock-runtime: bedrock.WithLoadDefaultConfig(ctx) 或 bedrock.WithConfig(cfg),用於 InvokeModel API。
  • Claude Platform on AWS: import anthropicaws "github.com/anthropics/anthropic-sdk-go/v2/aws"。使用 anthropicaws.NewClient(ctx, cfg) 搭配 anthropicaws.ClientConfig 值來建構用戶端;在設定中指定 WorkspaceID,或設定 ANTHROPIC_AWS_WORKSPACE_ID 環境變數。當同時匯入 github.com/aws/aws-sdk-go-v2/aws 時,anthropicaws 匯入別名可避免名稱衝突。以 beta 形式提供。
  • Foundry: import "github.com/anthropics/anthropic-sdk-go/v2/foundry"。使用 foundry.NewClient(cfg) 搭配 foundry.ClientConfig 值來建構用戶端;在設定中指定 APIKey(或針對 Microsoft Entra ID 使用 AzureADTokenProvider)與 Resource,或設定 ANTHROPIC_FOUNDRY_API_KEY 與 ANTHROPIC_FOUNDRY_RESOURCE 環境變數。

Go SDK 也透過 github.com/anthropics/anthropic-sdk-go/v2/googlecloud 套件支援 Claude Models on Google Cloud (Anthropic managed)。若要建構用戶端,請以 googlecloud.ClientConfig 值呼叫 googlecloud.NewClient(ctx, cfg)。此用戶端目前為 beta 版。請在設定中指定 WorkspaceID,或設定 ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_ID 環境變數。關於用戶端如何解析工作區 ID,請參閱專案、位置與工作區解析。

進階用法

存取原始回應資料(例如回應標頭)

您可以使用 option.WithResponseInto() 請求選項來存取原始 HTTP 回應資料。當 您需要檢查回應標頭、狀態碼或其他詳細資訊時,這會很有用。

// 建立一個變數來儲存 HTTP 回應
var response *http.Response
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_5,
	},
	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)

OpenTelemetry 追蹤

當您的應用程式註冊 OpenTelemetry tracer provider 時,SDK 會為其傳送的每個請求發出一個 span。若要將這些 span 傳送至您的可觀測性平台,請參閱搭配 Anthropic SDK 設定 OpenTelemetry。

發送自訂/未記載的請求

此函式庫具有型別定義,以便於存取已記載的 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 慣例,但某些不向下相容的變更可能會以次要版本發布:

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

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

對 Claude API 的每個請求都會使用一個 API 版本。使用此 SDK 時,您的請求會使用您的 SDK 主要版本發布時的最新 API 版本,因此您可以透過升級至新的主要版本來改用新的 API 版本。版本 2.0.0 是第一個使用 2026-10-21 的版本。其模組路徑為 github.com/anthropics/anthropic-sdk-go/v2。請參閱遷移至 API 版本 2026-10-21以了解如何升級。

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

其他資源

這個頁面有幫助嗎?