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], 맵, 슬라이스, 구조체 또는 문자열 열거형은 `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
}param.Opt[T] 대신 null을 보내려면 param.Null[T]()을 사용하세요.
구조체 T 대신 null을 보내려면 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) 메서드가 포함되어 있습니다. 추가 필드는 일치하는 키를 가진 구조체 필드를 덮어씁니다.
보안상의 이유로 SetExtraFields는 신뢰할 수 있는 데이터에만 사용하세요.
구조체 대신 사용자 지정 값을 보내려면 제네릭 함수 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)유니온은 각 변형에 대해 "Of"로 시작하는 필드를 가진 구조체로 표현되며, 하나의 필드만 제로 값이 아닐 수 있습니다. 제로 값이 아닌 필드가 직렬화됩니다.
유니온의 하위 속성은 유니온 구조체의 메서드를 통해 접근할 수 있습니다. 이러한 메서드는 기본 데이터가 존재하는 경우 해당 데이터에 대한 변경 가능한 포인터를 반환합니다.
// 하나의 필드만 0이 아닌 값을 가질 수 있으며, 필드 설정 여부는 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 이상이 필요합니다.
파라미터 타입(MessageNewParams 또는 ToolUnionParam과 같이 Param으로 끝나는 타입)은 나가는 요청 전용으로 설계되었습니다. JSON으로 올바르게 마샬링되지만 왕복 역직렬화를 완전히 지원하지는 않습니다. 원시 JSON을 파라미터 구조체로 언마샬링하면 기본 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이지만(유니온 제약),
// 원본 JSON은 보존됩니다. API 호출을 위해 params가 다시
// 마샬링될 때 도구는 올바르게 직렬화됩니다.
b2, _ := json.Marshal(params)
fmt.Println(string(b) == string(b2)) // true이 사용 사례에서는 타입 매개변수를 명시할 필요가 없고 왕복 의도를 명확하게 하기 때문에 더 일반적인 param.Override[T](any)보다 param.SetJSON(v1.20.0부터 사용 가능)이 선호됩니다.
응답 구조체의 모든 필드는 일반 값 타입입니다(포인터나 래퍼가 아님). 응답 구조체에는 각 속성에 대한 메타데이터를 포함하는 특수 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() 메서드를 사용하세요. .Valid()는 필드가 존재하고, null이 아니며, 성공적으로 언마샬링된 경우 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 구조체에는 구조체에 지정되지 않은 json 응답의 모든 속성을 포함하는 ExtraFields 맵도 포함되어 있습니다. 이는 아직 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 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 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.ModelClaudeOpus4_8,
},
option.WithMaxRetries(5),
)스트리밍이 아닌 Messages 요청은 기본적으로 10분 후에 타임아웃됩니다. 다른 요청에는 기본 타임아웃이 없습니다. 요청 수명 주기에 대한 타임아웃을 구성하려면 컨텍스트를 사용하세요.
요청이 재시도되는 경우 컨텍스트 타임아웃은 다시 시작되지 않습니다. 재시도별 타임아웃을 설정하려면 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으로부터 응답을 받지 못한 채 요청이 실패하거나 타임아웃될 수 있습니다.
이 SDK는 스트리밍이 아닌 요청이 대략 10분 이상 걸릴 것으로 예상되는 경우에도 오류를 반환합니다. .Messages.NewStreaming()을 호출하거나 사용자 지정 타임아웃을 설정하면 이 오류가 비활성화됩니다.
멀티파트 요청에서 파일 업로드에 해당하는 요청 매개변수는 io.Reader 타입입니다. io.Reader의 내용은 기본적으로 파일 이름이 "anonymous_file"이고 content-type이 "application/octet-stream"인 멀티파트 폼 파트로 전송되므로, 권장되는 방법은 모든 io.Reader를 적절한 파일 이름과 content type으로 래핑하는 anthropic.File(reader io.Reader, filename string, contentType string) 헬퍼를 사용하여 사용자 지정 content-type을 지정하는 것입니다.
// 파일 시스템의 파일
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())
}이 라이브러리는 함수형 옵션 패턴을 사용합니다. option 패키지에 정의된 함수는 RequestConfig를 변경하는 클로저인 RequestOption을 반환합니다. 이러한 옵션은 클라이언트 또는 개별 요청에 제공할 수 있습니다. 예를 들어:
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/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 "github.com/anthropics/anthropic-sdk-go/vertex". vertex.WithGoogleAuth(ctx, region, projectID) 또는 vertex.WithCredentials(ctx, region, projectID, creds)를 사용하세요.import anthropicaws "github.com/anthropics/anthropic-sdk-go/aws". anthropicaws.ClientConfig 값과 함께 anthropicaws.NewClient(ctx, cfg)를 사용하여 클라이언트를 생성하세요. 구성에서 WorkspaceID를 설정하거나 ANTHROPIC_AWS_WORKSPACE_ID 환경 변수를 설정하세요. anthropicaws 임포트 별칭은 두 패키지를 모두 임포트할 때 github.com/aws/aws-sdk-go-v2/aws와의 이름 충돌을 방지합니다. 베타로 제공됩니다.새 프로젝트에는 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을 가져올 수 있습니다.
응답 구조체에 없는 모든 필드는 저장되며 map[string]respjson.Field인 result.JSON.ExtraFields를 통해 접근할 수 있습니다.
이 패키지는 일반적으로 SemVer 규칙을 따르지만, 특정 하위 호환성이 없는 변경 사항이 마이너 버전으로 릴리스될 수 있습니다:
원활한 업그레이드 경험을 보장하기 위해 하위 호환성을 중요하게 고려합니다.
피드백을 환영합니다. 질문, 버그 또는 제안 사항이 있으면 이슈를 열어주세요.
Was this page helpful?