Claude Platform Docs
CLI, SDK 및 라이브러리클라이언트 SDK

Go SDK

컨텍스트 기반 취소 및 함수형 옵션을 지원하는 Anthropic Go SDK 설치 및 구성

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 의미론을 사용합니다.

필수 기본 타입 필드(예: int64 또는 string)에는 `json:"...,required"` 태그가 붙습니다. 이러한 필드는 제로 값이라도 항상 직렬화됩니다.

선택적 기본 타입은 param.Opt[T]로 래핑됩니다. 이러한 필드는 anthropic.String(string) 또는 anthropic.Int(int64)와 같이 제공되는 생성자로 설정할 수 있습니다.

모든 param.Opt[T], map, slice, struct 또는 문자열 enum은 `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]()를 사용하세요. struct 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

요청 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)

요청 유니온

유니온은 각 변형(variant)에 대해 "Of" 접두사가 붙은 필드를 가진 struct로 표현되며, 하나의 필드만 제로가 아닌 값을 가질 수 있습니다. 제로가 아닌 필드가 직렬화됩니다.

유니온의 하위 속성은 유니온 struct의 메서드를 통해 접근할 수 있습니다. 이러한 메서드는 기본 데이터가 존재하는 경우 해당 데이터에 대한 변경 가능한 포인터를 반환합니다.

// 하나의 필드만 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 타입(MessageNewParams 또는 ToolUnionParam과 같이 Param으로 끝나는 타입)은 발신 요청 전용으로 설계되었습니다. JSON으로 올바르게 마샬링되지만 왕복(round-trip) 역직렬화를 완전히 지원하지는 않습니다. 원시 JSON을 param 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이지만(union의 제약),
// 원시 JSON은 보존됩니다. API 호출을 위해 params를 다시
// 마샬링하면 tools가 올바르게 직렬화됩니다.
b2, _ := json.Marshal(params)
fmt.Println(string(b) == string(b2)) // true

이 사용 사례에서는 보다 일반적인 param.Override[T](any)보다 param.SetJSON(v1.20.0부터 사용 가능)이 권장됩니다. 타입 파라미터를 명시할 필요가 없고 왕복 의도를 명확하게 드러내기 때문입니다.

응답 객체

응답 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() 메서드를 사용하세요. .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 struct에는 struct에 지정되지 않은 json 응답의 모든 속성을 담고 있는 ExtraFields map도 포함되어 있습니다. 이는 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.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 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),
	)

긴 요청

스트리밍을 사용하지 않고 큰 MaxTokens 값을 설정하는 것은 피하세요. 일부 네트워크는 일정 시간이 지나면 유휴 연결을 끊을 수 있으며, 이로 인해 요청이 실패하거나 Anthropic으로부터 응답을 받지 못한 채 타임아웃될 수 있습니다.

이 SDK는 스트리밍이 아닌 요청이 대략 10분 이상 걸릴 것으로 예상되는 경우에도 오류를 반환합니다. .Messages.NewStreaming()을 호출하거나 사용자 정의 타임아웃을 설정하면 이 오류가 비활성화됩니다.

파일 업로드

멀티파트 요청에서 파일 업로드에 해당하는 요청 파라미터는 io.Reader 타입으로 지정됩니다. io.Reader의 내용은 기본적으로 파일 이름이 "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() string 또는 ContentType() string을 구현하여 사용자 정의할 수도 있습니다. os.FileName() 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

이 라이브러리는 함수형 옵션 패턴을 사용합니다. 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)은 디버깅 시 유용할 수 있습니다.

요청 옵션 전체 목록을 참조하세요.

HTTP 클라이언트 사용자 정의

요청 미들웨어(option.WithMiddleware) 및 기본 http.Client 교체(option.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-runtime WithConfig/WithLoadDefaultConfig 경로를 사용하든 NewMantleClient를 사용하든 적용됩니다.
  • Claude Platform on AWS: import anthropicaws "github.com/anthropics/anthropic-sdk-go/aws". anthropicaws.ClientConfig 값과 함께 anthropicaws.NewClient(ctx, cfg)를 사용하여 클라이언트를 생성하세요. config에 WorkspaceID를 설정하거나 ANTHROPIC_AWS_WORKSPACE_ID 환경 변수를 설정하세요. anthropicaws 임포트 별칭은 둘 다 임포트할 때 github.com/aws/aws-sdk-go-v2/aws와의 이름 충돌을 방지합니다. 베타로 제공됩니다.
  • Foundry: 현재 Go SDK에서 지원되지 않습니다. 지원되는 SDK는 Claude in Microsoft Foundry를 참조하세요.

새 프로젝트에는 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.Content)

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에 없는 모든 필드는 저장되며 map[string]respjson.Fieldresult.JSON.ExtraFields를 통해 접근할 수 있습니다.

시맨틱 버저닝

이 패키지는 일반적으로 SemVer 규칙을 따르지만, 특정 하위 호환되지 않는 변경 사항이 마이너 버전으로 릴리스될 수 있습니다:

  1. 기술적으로는 공개되어 있지만 외부 사용을 의도하거나 문서화하지 않은 라이브러리 내부에 대한 변경.
  2. 실제로 대다수의 사용자에게 영향을 미치지 않을 것으로 예상되는 변경.

원활한 업그레이드 경험을 보장할 수 있도록 하위 호환성을 중요하게 다루고 있습니다.

피드백을 환영합니다. 질문, 버그 또는 제안 사항이 있으면 이슈를 열어주세요.

추가 리소스

Was this page helpful?