---
title: Go SDK
url: https://platform.claude.com/docs/ja/cli-sdks-libraries/sdks/go
description: コンテキストベースのキャンセルと関数型オプションを備えたAnthropic Go SDKのインストールと設定
---

Anthropic Goライブラリは、Goで書かれたアプリケーションからClaude APIへの便利なアクセスを提供します。

<Info>
  コード例付きのAPI機能ドキュメントについては、[APIリファレンス](https://platform.claude.com/docs/ja/api/overview)を参照してください。このページでは、Go固有のSDK機能と設定について説明します。
</Info>

## インストール

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

`go get`でインストールします：

```bash
go get github.com/anthropics/anthropic-sdk-go
```

## 要件

このライブラリにはGo 1.24以降が必要です。

## 使用方法

```go
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_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を含む認証オプションについては、[認証](https://platform.claude.com/docs/ja/manage-claude/authentication)を参照してください。お使いのAPIキーが複数のワークスペースにアクセスできる[個人キーまたはサービスアカウントキー](https://platform.claude.com/docs/ja/manage-claude/authentication#key-types)である場合は、`anthropic-workspace-id`リクエストヘッダーにワークスペースIDを設定してください。[ワークスペースを選択する](https://platform.claude.com/docs/ja/manage-claude/authentication#select-a-workspace)では、このSDKにおけるリクエストごとのオプションを示しています。

<AccordionGroup>
  <Accordion title="会話">
    ```go
    messages := []anthropic.MessageParam{
    	anthropic.NewUserMessage(anthropic.NewTextBlock("What is my first name?")),
    }

    message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
    	Model:     anthropic.ModelClaudeOpus5_5,
    	Messages:  messages,
    	MaxTokens: 1024,
    })
    if err != nil {
    	panic(err)
    }

    fmt.Printf("%+v\n", message.Content)

    messages = append(messages, message.ToParam())
    messages = append(messages, anthropic.NewUserMessage(
    	anthropic.NewTextBlock("My full name is John Doe"),
    ))

    message, err = client.Messages.New(context.TODO(), anthropic.MessageNewParams{
    	Model:     anthropic.ModelClaudeOpus5_5,
    	Messages:  messages,
    	MaxTokens: 1024,
    })
    if err != nil {
    	panic(err)
    }

    fmt.Printf("%+v\n", message.Content)
    ```
  </Accordion>

  <Accordion title="システムプロンプト">
    ```go
    message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
    	Model:     anthropic.ModelClaudeOpus5_5,
    	MaxTokens: 1024,
    	System: []anthropic.TextBlockParam{
    		{Text: "Be very serious at all times."},
    	},
    	Messages: messages,
    })
    if err != nil {
    	panic(err)
    }
    fmt.Printf("%+v\n", message.Content)
    ```
  </Accordion>

  <Accordion title="ストリーミング">
    ```go
    content := "What is a quaternion?"

    stream := client.Messages.NewStreaming(context.TODO(), anthropic.MessageNewParams{
    	Model:     anthropic.ModelClaudeOpus5_5,
    	MaxTokens: 1024,
    	Messages: []anthropic.MessageParam{
    		anthropic.NewUserMessage(anthropic.NewTextBlock(content)),
    	},
    })

    message := anthropic.Message{}
    for stream.Next() {
    	event := stream.Current()
    	err := message.Accumulate(event)
    	if err != nil {
    		panic(err)
    	}

    	switch eventVariant := event.AsAny().(type) {
    	case anthropic.ContentBlockDeltaEvent:
    		switch deltaVariant := eventVariant.Delta.AsAny().(type) {
    		case anthropic.TextDelta:
    			print(deltaVariant.Text)
    		}

    	}
    }

    if stream.Err() != nil {
    	panic(stream.Err())
    }
    ```
  </Accordion>

  <Accordion title="ツール呼び出し">
    ```go
    messages := []anthropic.MessageParam{
    	anthropic.NewUserMessage(anthropic.NewTextBlock(content)),
    }

    toolParams := []anthropic.ToolParam{
    	{
    		Name:        "get_coordinates",
    		Description: anthropic.String("Accepts a place as an address, then returns the latitude and longitude coordinates."),
    		InputSchema: GetCoordinatesInputSchema,
    	},
    }
    tools := make([]anthropic.ToolUnionParam, len(toolParams))
    for i, toolParam := range toolParams {
    	tools[i] = anthropic.ToolUnionParam{OfTool: &toolParam}
    }

    for {
    	message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
    		Model:     anthropic.ModelClaudeOpus5_5,
    		MaxTokens: 1024,
    		Messages:  messages,
    		Tools:     tools,
    	})

    	if err != nil {
    		panic(err)
    	}

    	print(color("[assistant]: "))
    	for _, block := range message.Content {
    		switch block := block.AsAny().(type) {
    		case anthropic.TextBlock:
    			println(block.Text)
    			println()
    		case anthropic.ToolUseBlock:
    			inputJSON, _ := json.Marshal(block.Input)
    			println(block.Name + ": " + string(inputJSON))
    			println()
    		}
    	}

    	messages = append(messages, message.ToParam())
    	toolResults := []anthropic.ContentBlockParamUnion{}

    	for _, block := range message.Content {
    		switch variant := block.AsAny().(type) {
    		case anthropic.ToolUseBlock:
    			print(color("[user (" + block.Name + ")]: "))

    			var response interface{}
    			switch block.Name {
    			case "get_coordinates":
    				var input struct {
    					Location string `json:"location"`
    				}

    				err := json.Unmarshal([]byte(variant.JSON.Input.Raw()), &input)
    				if err != nil {
    					panic(err)
    				}

    				response = GetCoordinates(input.Location)
    			}

    			b, err := json.Marshal(response)
    			if err != nil {
    				panic(err)
    			}

    			println(string(b))

    			toolResults = append(toolResults, anthropic.NewToolResultBlock(block.ID, string(b), false))
    		}

    	}
    	if len(toolResults) == 0 {
    		break
    	}
    	messages = append(messages, anthropic.NewUserMessage(toolResults...))
    }
    ```
  </Accordion>
</AccordionGroup>

## リクエストフィールド

Anthropicライブラリは、リクエストフィールドに対してGo 1.24以降の`encoding/json`リリースの[`omitzero`](https://tip.golang.org/doc/go1.24#encodingjsonpkgencodingjson)セマンティクスを使用します。

必須のプリミティブフィールド（`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`フィールドの存在を確認できます。

```go
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]()`を使用します。

```go
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フィールドを上書きします。

<Warning>
  セキュリティ上の理由から、`SetExtraFields`は信頼できるデータでのみ使用してください。
</Warning>

structの代わりにカスタム値を送信するには、ジェネリック関数`param.Override`を使用します（例：`param.Override[anthropic.FooParams](12)`）。

```go
// 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」というプレフィックスが付いたフィールドを持つstructとして表現されます。 非ゼロにできるフィールドは1つだけです。非ゼロのフィールドがシリアライズされます。

ユニオンのサブプロパティには、ユニオンstructのメソッドを通じてアクセスできます。 これらのメソッドは、基になるデータが存在する場合、そのデータへの変更可能なポインタを返します。

```go
// ゼロ以外にできるフィールドは1つだけです。フィールドが設定されているか確認するには 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
}
```

### パラメータのデシリアライズ

<Note>
  `param.SetJSON`にはSDK v1.20.0以降が必要です。
</Note>

Param型（`MessageNewParams`や`ToolUnionParam`など、`Param`で終わる型）は、送信リクエスト専用に設計されています。JSONへのマーシャリングは正しく行われますが、ラウンドトリップのデシリアライズは完全にはサポートされていません。生のJSONをparam structにアンマーシャルすると、基になるJSONが有効であっても、`OfBashTool20250124`のような型付きユニオンフィールドはnilになります。

生のJSON（例えば、データベース、ミドルウェア、または以前のリクエストから）からparamsを再構築する必要がある場合は、`UnmarshalJSON`を呼び出して非ユニオンフィールドを設定し、次に`param.SetJSON`を使用して正しく再シリアライズするための生のバイトを添付します：

```go
// 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が再度マーシャルされると、
// ツールは正しくシリアライズされます。
b2, _ := json.Marshal(params)
fmt.Println(string(b) == string(b2)) // true
```

このユースケースでは、より汎用的な`param.Override[T](any)`よりも`param.SetJSON`（v1.20.0以降で利用可能）が推奨されます。型パラメータを明示的に記述する必要がなく、ラウンドトリップの意図が明確になるためです。

## レスポンスオブジェクト

レスポンスstructのすべてのフィールドは通常の値型です（ポインタやラッパーではありません）。 レスポンスstructには、各プロパティに関するメタデータを含む特別な`JSON`フィールドも含まれています。

```go
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の場合、対応するフィールドはゼロ値になります。

```go
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`マップも含まれています。これは、SDKにまだ存在しないAPI機能に役立つ場合があります。

```go
body := res.JSON.ExtraFields["my_unexpected_field"].Raw()
```

### レスポンスユニオン

レスポンスでは、ユニオンは各オブジェクトバリアントのすべての可能なフィールドを含むフラット化されたstructとして表現されます。 バリアントに変換するには、`.AsFooVariant()`メソッド、または存在する場合は`.AsAny()`メソッドを使用します。

レスポンス値のユニオンにプリミティブ値が含まれる場合、プリミティブフィールドはプロパティと並んで配置されますが、`Of`で始まり、`json:"...,inline"`タグが付きます。

```go
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`パターンを使用します：

```go
_, 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_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トランスポートが失敗した場合、`*net.OpError`をラップした`*url.Error`を受け取ることがあります。

## リトライ

特定のエラーは、デフォルトで短い指数バックオフを伴って2回自動的にリトライされます。 SDKはデフォルトで、すべての接続エラー、408 Request Timeout、409 Conflict、429 Rate Limit、および500以上のInternalエラーをリトライします。

`WithMaxRetries`オプションを使用して、これを設定または無効化できます：

```go
// すべてのリクエストのデフォルトを設定します:
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_5,
		},
		option.WithMaxRetries(5),
	)
```

## タイムアウト

非ストリーミングのMessagesリクエストはデフォルトで10分後にタイムアウトします。その他のリクエストにはデフォルトのタイムアウトはありません。リクエストのライフサイクルにタイムアウトを設定するには、contextを使用します。

リクエストが[リトライ](https://platform.claude.com/docs/ja/cli-sdks-libraries/sdks/go#retries)された場合、contextのタイムアウトは最初からやり直されないことに注意してください。 リトライごとのタイムアウトを設定するには、`option.WithRequestTimeout()`を使用します。

```go
// すべてのリトライを含む、リクエスト全体のタイムアウトを設定します。
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_5,
		},
		// リトライごとのタイムアウトを設定します
		option.WithRequestTimeout(20*time.Second),
	)
```

## 長時間のリクエスト

<Warning>
  長時間実行されるリクエストには、ストリーミングMessages APIの使用を検討してください。
</Warning>

ストリーミングを使用せずに大きな`MaxTokens`値を設定することは避けてください。一部のネットワークでは、一定時間後にアイドル状態の接続が切断される場合があり、その結果、Anthropicからレスポンスを受け取らずにリクエストが失敗したり[タイムアウト](https://platform.claude.com/docs/ja/cli-sdks-libraries/sdks/go#timeouts)したりする可能性があります。

このSDKは、非ストリーミングリクエストがおよそ10分を超えると予想される場合にもエラーを返します。 `.Messages.NewStreaming()`を呼び出すか、[カスタムタイムアウトを設定する](https://platform.claude.com/docs/ja/cli-sdks-libraries/sdks/go#timeouts)と、このエラーは無効になります。

## ファイルアップロード

マルチパートリクエストでのファイルアップロードに対応するリクエストパラメータは、`io.Reader`として型付けされています。`io.Reader`の内容は、デフォルトでファイル名`anonymous_file`、コンテンツタイプ`application/octet-stream`のマルチパートフォームパートとして送信されます。そのため、推奨される方法は、`anthropic.File(reader io.Reader, filename string, contentType string)`ヘルパーを使用してカスタムコンテンツタイプを指定することです。このヘルパーは、任意の`io.Reader`を適切なファイル名とコンテンツタイプでラップします。

```go
// ファイルシステムからのファイル
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()`メソッドを使用して、すべてのページにわたってアイテムを反復処理できます：

```go
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()`のような追加のヘルパーメソッドを持つ標準のレスポンスオブジェクトを受け取ることもできます：

```go
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`パッケージで定義された関数は`RequestOption`を返します。これは`RequestConfig`を変更するクロージャです。これらのオプションは、クライアントまたは個々のリクエストに指定できます。例：

```go
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)`は、デバッグ中に役立つ場合があります。

[リクエストオプションの完全なリスト](https://pkg.go.dev/github.com/anthropics/anthropic-sdk-go/option)を参照してください。

## HTTPクライアントのカスタマイズ

リクエストミドルウェア（`option.WithMiddleware`）およびデフォルトの`http.Client`の置き換え（`option.WithHTTPClient`）については、[SDKミドルウェア](https://platform.claude.com/docs/ja/cli-sdks-libraries/middleware)を参照してください。

## プラットフォーム統合

<Note>
  コード例付きの詳細なプラットフォームセットアップガイドについては、以下を参照してください：

  * [Amazon Bedrock](https://platform.claude.com/docs/ja/build-with-claude/claude-in-amazon-bedrock)
  * [Amazon Bedrock（Opus 4.6以前）](https://platform.claude.com/docs/ja/build-with-claude/claude-on-amazon-bedrock-legacy)
  * [Claude Platform on AWS](https://platform.claude.com/docs/ja/build-with-claude/claude-platform-on-aws)
  * [Google Cloud](https://platform.claude.com/docs/ja/build-with-claude/claude-on-vertex-ai)
  * [Microsoft Foundry](https://platform.claude.com/docs/ja/build-with-claude/claude-in-microsoft-foundry)
</Note>

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`パッケージをインポートすると、`application/vnd.amazon.eventstream`用のデコーダーがSDKのストリーミングレイヤーにグローバルに登録されます（パッケージの`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:** `import "github.com/anthropics/anthropic-sdk-go/foundry"`。`foundry.ClientConfig`値とともに`foundry.NewClient(cfg)`を使用してクライアントを構築します。configで`APIKey`（またはMicrosoft Entra IDの場合は`AzureADTokenProvider`）と`Resource`を設定するか、`ANTHROPIC_FOUNDRY_API_KEY`および`ANTHROPIC_FOUNDRY_RESOURCE`環境変数を設定します。

新しいプロジェクトには`bedrock.NewMantleClient`を使用してください。`bedrock.WithLoadDefaultConfig`/`WithConfig`は、Bedrock `InvokeModel` APIを使用する既存のアプリケーション向けに引き続き提供されます。

## 高度な使用方法

### 生のレスポンスデータへのアクセス（例：レスポンスヘッダー）

`option.WithResponseInto()`リクエストオプションを使用して、生のHTTPレスポンスデータにアクセスできます。これは、レスポンスヘッダー、ステータスコード、またはその他の詳細を調べる必要がある場合に便利です。

```go
// 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_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)
```

### カスタム/ドキュメント化されていないリクエストの実行

このライブラリは、ドキュメント化されたAPIに便利にアクセスできるように型付けされています。ドキュメント化されていないエンドポイント、パラメータ、またはレスポンスプロパティにアクセスする必要がある場合でも、このライブラリを使用できます。

#### ドキュメント化されていないエンドポイント

ドキュメント化されていないエンドポイントにリクエストを行うには、`client.Get`、`client.Post`、およびその他のHTTP動詞を使用できます。 これらのリクエストを行う際、リトライなどのクライアントの`RequestOptions`は尊重されます。

```go
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()`メソッドのいずれかを使用できます。

```go
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.Field`である`result.JSON.ExtraFields`を通じてアクセスできます。

## セマンティックバージョニング

このパッケージは概ね[SemVer](https://semver.org/spec/v2.0.0.html)の規約に従っていますが、特定の後方互換性のない変更がマイナーバージョンとしてリリースされる場合があります：

1. 技術的には公開されているが、外部での使用を意図またはドキュメント化していないライブラリ内部への変更。
2. 実際には大多数のユーザーに影響を与えないと予想される変更。

スムーズなアップグレード体験を確実に提供できるよう、後方互換性は真剣に考慮されています。

フィードバックを歓迎します。質問、バグ、または提案がある場合は[issue](https://github.com/anthropics/anthropic-sdk-go/issues)を作成してください。

## 追加リソース

* [GitHubリポジトリ](https://github.com/anthropics/anthropic-sdk-go)
* [Goパッケージドキュメント](https://pkg.go.dev/github.com/anthropics/anthropic-sdk-go)
* [APIリファレンス](https://platform.claude.com/docs/ja/api/overview)
* [ストリーミングメッセージ](https://platform.claude.com/docs/ja/build-with-claude/streaming)
