• 訊息
  • 託管代理
  • 管理
Search...
⌘K
CLI、SDK 與函式庫
概覽
ant CLI
快速入門驗證選項使用 CLI指令碼與自動化
用戶端 SDK
中介軟體PythonTypeScriptC#GoJavaPHPRuby
函式庫與整合
Apple Foundation ModelsOpenAI SDK 相容性
Log in
Go
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Solutions

  • AI agents
  • Code modernization
  • Coding
  • Customer support
  • Education
  • Financial services
  • Government
  • Life sciences

Partners

  • Amazon Bedrock
  • Google Cloud's Vertex AI

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Company

  • Anthropic
  • Careers
  • Economic Futures
  • Research
  • News
  • Responsible Scaling Policy
  • Security and compliance
  • Transparency

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Help and security

  • Availability
  • Status
  • Support
  • Discord

Terms and policies

  • Privacy policy
  • Responsible disclosure policy
  • Terms of service: Commercial
  • Terms of service: Consumer
  • Usage policy
CLI、SDK 與函式庫/用戶端 SDK

Go SDK

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

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.ModelClaudeOpus4_8,
	})
	if err != nil {
		panic(err.Error())
	}
	fmt.Printf("%+v\n", message.Content)
}

如需了解包含「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, &params)

// params.Model 與其他純量欄位會由 UnmarshalJSON 填入。
// params.Tools[0].OfBashTool20250124 為 nil(聯合型別的限制),
// 但原始 JSON 會被保留。當 params 再次被序列化
// 以供 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 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.ModelClaudeOpus4_8,
})
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.ModelClaudeOpus4_8,
		},
		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.ModelClaudeOpus4_8,
		},
		// 這會設定每次重試的逾時時間
		option.WithRequestTimeout(20*time.Second),
	)

長時間請求

對於執行時間較長的請求,請考慮使用串流 Messages API。

避免在不使用串流的情況下設定較大的 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,該函式會以適當的檔案名稱和 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())
}

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 中介軟體。

平台整合

如需包含程式碼範例的詳細平台設定指南,請參閱:

  • Amazon Bedrock
  • Amazon Bedrock(舊版)
  • Vertex AI
  • AWS 上的 Claude Platform

Go SDK 支援以下平台:

  • Bedrock: import "github.com/anthropics/anthropic-sdk-go/bedrock"。使用 bedrock.NewMantleClient 來存取 Messages-API Bedrock 端點(透過 SSE 串流),或使用 bedrock.WithLoadDefaultConfig(ctx) / bedrock.WithConfig(cfg)(bedrock-runtime 路徑)。匯入 bedrock 套件會在全域範圍內(透過套件 init())向 SDK 的串流層註冊 application/vnd.amazon.eventstream 的解碼器。無論您使用 bedrock-runtime 的 WithConfig/WithLoadDefaultConfig 路徑或 NewMantleClient,此行為皆適用。
  • Vertex AI: import "github.com/anthropics/anthropic-sdk-go/vertex"。使用 vertex.WithGoogleAuth(ctx, region, projectID) 或 vertex.WithCredentials(ctx, region, projectID, creds)。
  • Foundry: Go SDK 目前不支援。請參閱 Microsoft Foundry 中的 Claude 以了解支援的 SDK。
  • AWS 上的 Claude Platform: 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.ModelClaudeOpus4_8,
	},
	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 慣例,但某些向後不相容的變更可能會以次要版本發布:

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

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

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

其他資源

  • GitHub 儲存庫
  • Go 套件文件
  • API 參考
  • 串流 Messages

Was this page helpful?

  • 安裝
  • 需求
  • 使用方式
  • 請求欄位
  • 請求聯集型別
  • 反序列化參數
  • 回應物件
  • 回應聯集型別
  • 錯誤處理
  • 重試
  • 逾時
  • 長時間請求
  • 檔案上傳
  • 分頁
  • RequestOptions
  • HTTP 用戶端自訂
  • 平台整合
  • 進階用法
  • 存取原始回應資料(例如回應標頭)
  • 發出自訂/未記載的請求
  • 語意化版本控制
  • 其他資源