---
title: Ruby SDK
url: https://platform.claude.com/docs/zh-TW/cli-sdks-libraries/sdks/ruby
description: 安裝並設定 Anthropic Ruby SDK，包含 Sorbet 型別、串流輔助工具與連線池
---

Anthropic Ruby 函式庫讓任何 Ruby 3.2.0+ 應用程式都能方便地存取 Claude API。它附帶以 YARD、RBS 和 RBI 撰寫的完整型別與文件字串。HTTP 傳輸使用標準函式庫的 `net/http`，並透過 `connection_pool` gem 提供「connection pooling」（連線池）。

<Info>
  如需附有程式碼範例的 API 功能文件，請參閱 [API 參考文件](https://platform.claude.com/docs/zh-TW/api/overview)。本頁涵蓋 Ruby 專屬的 SDK 功能與設定。
</Info>

## 安裝

使用 Bundler 將此 gem 加入您應用程式的 `Gemfile`：

```bash
bundle add anthropic
```

## 需求

Ruby 3.2.0 或更高版本。

## 使用方式

```ruby
anthropic = Anthropic::Client.new(
  api_key: ENV["ANTHROPIC_API_KEY"] # This is the default and can be omitted
)

message = anthropic.messages.create(
  max_tokens: 1024,
  messages: [{role: "user", content: "Hello, Claude"}],
  model: :"claude-opus-5-5"
)

message.content.each do |block|
  puts block.text if block.type == :text
end
```

如需了解包括 Workload Identity Federation（工作負載身分聯合）在內的驗證選項，請參閱[驗證](https://platform.claude.com/docs/zh-TW/manage-claude/authentication)。如果您的 API 金鑰是可存取多個工作區的[個人或服務帳戶金鑰](https://platform.claude.com/docs/zh-TW/manage-claude/authentication#key-types)，請在 `anthropic-workspace-id` 請求標頭中設定工作區 ID；[選擇工作區](https://platform.claude.com/docs/zh-TW/manage-claude/authentication#select-a-workspace)說明了此 SDK 的逐請求選項。

## 串流

此 SDK 支援使用「Server-Sent Events」（伺服器傳送事件），即 SSE，進行「streaming」（串流）回應。

```ruby
anthropic = Anthropic::Client.new
stream = anthropic.messages.stream(
  max_tokens: 1024,
  messages: [{role: "user", content: "Hello, Claude"}],
  model: :"claude-opus-5-5"
)

stream.each do |message|
  puts(message.type)
end
```

### 串流輔助工具

此函式庫為串流訊息提供了多項便利功能，例如：

```ruby
anthropic = Anthropic::Client.new
stream = anthropic.messages.stream(
  max_tokens: 1024,
  messages: [{role: :user, content: "Say hello there!"}],
  model: :"claude-opus-5-5"
)

stream.text.each do |text|
  print(text)
end
```

使用 `anthropic.messages.stream(...)` 進行串流會提供各種輔助工具，包括累積功能與 SDK 專屬事件。

## 輸入結構描述與工具呼叫

此 SDK 提供輔助機制，可為工具定義結構化資料類別，並讓 Claude 自動執行它們。如需「tool use」（工具使用）模式的詳細文件（包含工具執行器），請參閱[工具執行器（SDK）](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-runner)。

```ruby
anthropic = Anthropic::Client.new
class CalculatorInput < Anthropic::BaseModel
  required :lhs, Float
  required :rhs, Float
  required :operator, Anthropic::InputSchema::EnumOf[:+, :-, :*, :/]
end

class Calculator < Anthropic::BaseTool
  input_schema CalculatorInput

  def call(expr)
    expr.lhs.public_send(expr.operator, expr.rhs)
  end
end

# 自動處理工具執行迴圈
anthropic.beta.messages.tool_runner(
  model: "claude-opus-5-5",
  max_tokens: 1024,
  messages: [{role: "user", content: "What's 15 * 7?"}],
  tools: [Calculator.new]
).each_message { |message| puts message.content }
```

## 結構化輸出

如需包含 Ruby 範例的完整結構化輸出文件，請參閱[結構化輸出](https://platform.claude.com/docs/zh-TW/build-with-claude/structured-outputs)。

## 錯誤處理

當函式庫無法連線至 API，或 API 回傳非成功狀態碼（即 4xx 或 5xx 回應）時，會拋出 `Anthropic::Errors::APIError` 的子類別：

```ruby
anthropic = Anthropic::Client.new
begin
  message = anthropic.messages.create(
    max_tokens: 1024,
    messages: [{role: "user", content: "Hello, Claude"}],
    model: :"claude-opus-5-5"
  )
rescue Anthropic::Errors::APIConnectionError => e
  puts("The server could not be reached")
  puts(e.cause)  # an underlying Exception, likely raised within `net/http`
rescue Anthropic::Errors::RateLimitError => e
  puts("A 429 status code was received; we should back off a bit.")
rescue Anthropic::Errors::APIStatusError => e
  puts("Another non-200-range status code was received")
  puts(e.status)
end
```

錯誤代碼如下：

| 原因          | 錯誤類型                       |
| ----------- | -------------------------- |
| HTTP 400    | `BadRequestError`          |
| HTTP 401    | `AuthenticationError`      |
| HTTP 403    | `PermissionDeniedError`    |
| HTTP 404    | `NotFoundError`            |
| HTTP 409    | `ConflictError`            |
| HTTP 422    | `UnprocessableEntityError` |
| HTTP 429    | `RateLimitError`           |
| HTTP >= 500 | `InternalServerError`      |
| 其他 HTTP 錯誤  | `APIStatusError`           |
| 逾時          | `APITimeoutError`          |
| 網路錯誤        | `APIConnectionError`       |

## 重試

某些錯誤預設會自動重試 2 次，並採用短暫的指數退避。

連線錯誤（例如因網路連線問題所致）、408 Request Timeout、409 Conflict、429 Rate Limit、>=500 內部錯誤以及逾時，預設皆會重試。

您可以使用 `max_retries` 選項來設定或停用此行為：

```ruby
# 為所有請求設定預設值：
anthropic = Anthropic::Client.new(
  max_retries: 0 # default is 2
)

# 或者，針對個別請求進行設定：
anthropic.messages.create(
  max_tokens: 1024,
  messages: [{role: "user", content: "Hello, Claude"}],
  model: :"claude-opus-5-5",
  request_options: {max_retries: 5}
)
```

## 逾時

預設情況下，請求會在 10 分鐘後逾時。您可以使用 `timeout` 選項來設定：

```ruby
# 為所有請求設定預設值：
anthropic = Anthropic::Client.new(
  timeout: 20 # 20 seconds (default is 10 minutes)
)

# 或者，針對個別請求進行設定：
anthropic.messages.create(
  max_tokens: 1024,
  messages: [{role: "user", content: "Hello, Claude"}],
  model: :"claude-opus-5-5",
  request_options: {timeout: 5}
)
```

逾時時會拋出 `Anthropic::Errors::APITimeoutError`。

請注意，逾時的請求預設會重試。

## 分頁

Claude API 中的列表方法皆採分頁處理。

此函式庫為每個列表回應提供自動分頁的迭代器，因此您無需手動請求後續頁面：

```ruby
anthropic = Anthropic::Client.new
page = anthropic.messages.batches.list(limit: 20)

# 從頁面擷取單一項目。
batch = page.data[0]
puts(batch.id)

# 視需要自動擷取更多頁面。
page.auto_paging_each do |batch|
  puts(batch.id)
end
```

或者，您可以使用 `#next_page?` 與 `#next_page` 方法，以更細緻地控制頁面操作。

```ruby
anthropic = Anthropic::Client.new
page = anthropic.messages.batches.list(limit: 20)
loop do
  page.data&.each { |batch| puts(batch.id) }
  break unless page.next_page?
  page = page.next_page
end
```

## 檔案上傳

對應檔案上傳的請求參數可以傳入原始內容、[`Pathname`](https://rubyapi.org/3.2/o/pathname) 實例、[`StringIO`](https://rubyapi.org/3.2/o/stringio) 等。

```ruby
anthropic = Anthropic::Client.new
require "pathname"

# 使用 `Pathname` 傳送檔名，並／或避免將大型檔案整個載入記憶體：
file_metadata = anthropic.files.upload(file: Pathname("/path/to/file"))

# 或者，直接傳入檔案內容或 `StringIO`：
file_metadata = anthropic.files.upload(file: File.read("/path/to/file"))

# 或者，若要控制檔名及／或內容類型：
file = Anthropic::FilePart.new(File.read("/path/to/file"), filename: "/path/to/file", content_type: "...")
file_metadata = anthropic.files.upload(file: file)

puts(file_metadata.id)
```

請注意，您也可以傳入原始的 `IO` 描述子，但這會停用重試功能，因為函式庫無法確定該描述子是檔案還是管道（管道無法倒回）。

## Sorbet

此函式庫提供完整的 [RBI](https://sorbet.org/docs/rbi) 定義，且不依賴 sorbet-runtime。

您可以如下提供型別安全的請求參數：

```ruby
anthropic = Anthropic::Client.new
anthropic.messages.create(
  max_tokens: 1024,
  messages: [Anthropic::MessageParam.new(role: "user", content: "Hello, Claude")],
  model: :"claude-opus-5-5"
)
```

或者，等效地：

```ruby
anthropic = Anthropic::Client.new
# 雜湊（Hash）可以使用，但不具型別安全：
anthropic.messages.create(
  max_tokens: 1024,
  messages: [{role: "user", content: "Hello, Claude"}],
  model: :"claude-opus-5-5"
)

# 您也可以展開（splat）完整的 Params 類別：
params = Anthropic::MessageCreateParams.new(
  max_tokens: 1024,
  messages: [Anthropic::MessageParam.new(role: "user", content: "Hello, Claude")],
  model: :"claude-opus-5-5"
)
anthropic.messages.create(**params)
```

### 列舉

由於此函式庫不依賴 `sorbet-runtime`，因此無法提供 [`T::Enum`](https://sorbet.org/docs/tenum) 實例。取而代之的是，SDK 提供「tagged symbols」（標記符號），它們在執行期一律是基本型別：

```ruby
# :auto
puts(Anthropic::MessageCreateParams::ServiceTier::AUTO)

# 顯示的型別：`T.all(Anthropic::MessageCreateParams::ServiceTier, Symbol)`
T.reveal_type(Anthropic::MessageCreateParams::ServiceTier::AUTO)
```

列舉參數具有「寬鬆」型別，因此您可以傳入列舉常數或其字面值：

```ruby
anthropic = Anthropic::Client.new
# 使用列舉常數可保留標記型別資訊：
anthropic.messages.create(
  max_tokens: 1024,
  messages: [{role: "user", content: "Hello, Claude"}],
  model: Anthropic::Model::CLAUDE_OPUS_5_5,
  service_tier: Anthropic::MessageCreateParams::ServiceTier::AUTO
)

# 也允許使用字面值：
anthropic.messages.create(
  max_tokens: 1024,
  messages: [{role: "user", content: "Hello, Claude"}],
  model: :"claude-opus-5-5",
  service_tier: :auto
)
```

## BaseModel

所有參數與回應物件皆繼承自 `Anthropic::Internal::Type::BaseModel`，它提供多項便利功能，包括：

1. 所有欄位（包含未知欄位）皆可透過 `obj[:prop]` 語法存取，並可使用 `obj => {prop: prop}` 或模式比對語法進行解構。

2. 以結構等價判斷相等性。如果兩個 API 呼叫回傳相同的值，使用 == 比較回應將回傳 true。

3. 實例與類別本身皆可美化列印。

4. 輔助方法如 `#to_h`、`#deep_to_h`、`#to_json` 與 `#to_yaml`。

## 並行與連線池

`Anthropic::Client` 實例是執行緒安全的，但僅在沒有進行中的 HTTP 請求時才是 fork 安全的。

每個 `Anthropic::Client` 實例都有自己的 HTTP 連線池，預設大小為 99。因此，在大多數情境下，建議每個應用程式只建立一次用戶端。

當連線池中所有可用連線皆已被取出時，請求會等待新連線可用，而排隊時間會計入請求逾時。

除非另有說明，SDK 中的其他類別並沒有鎖來保護其底層資料結構。

## 發送自訂或未記載的請求

### 未記載的屬性

您可以向任何端點傳送未記載的參數，並讀取未記載的回應屬性，如下所示：

<Warning>
  同名的 `extra_` 參數會覆寫已記載的參數。基於安全考量，請確保這些方法僅用於受信任的輸入資料。
</Warning>

```ruby
anthropic = Anthropic::Client.new
value = "example"
message =
  anthropic.messages.create(
    max_tokens: 1024,
    messages: [{role: "user", content: "Hello, Claude"}],
    model: :"claude-opus-5-5",
    request_options: {
      extra_query: {my_query_parameter: value},
      extra_body: {my_body_parameter: value},
      extra_headers: {"my-header": value}
    }
  )

puts(message[:my_undocumented_property])
```

### 未記載的請求參數

如果您想明確傳送額外參數，可以在發出請求時，於 `request_options:` 參數下使用 `extra_query`、`extra_body` 和 `extra_headers`，如前面的範例所示。

### 未記載的端點

若要向未記載的端點發出請求，同時保留驗證、重試等優點，您可以使用 `anthropic.request` 發出請求，如下所示：

```ruby
response = anthropic.request(
  method: :post,
  path: '/undocumented/endpoint',
  query: {"dog": "woof"},
  headers: {"useful-header": "interesting-value"},
  body: {"hello": "world"}
)
```

## 平台整合

<Note>
  如需附有程式碼範例的詳細平台設定指南，請參閱：

  * [Amazon Bedrock](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-in-amazon-bedrock)
  * [Amazon Bedrock（Opus 4.6 及更早版本）](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-on-amazon-bedrock-legacy)
  * [Claude Platform on AWS](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-platform-on-aws)
  * [Google Cloud](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-on-vertex-ai)
</Note>

Ruby SDK 支援以下平台：

* **Agent Platform：** `Anthropic::VertexClient`。需要 `googleauth` gem。
* **Bedrock：** `Anthropic::BedrockMantleClient`，或針對 `bedrock-runtime` 路徑使用 `Anthropic::BedrockClient`。`Anthropic::BedrockMantleClient` 需要 `aws-sdk-core` gem；`Anthropic::BedrockClient` 需要 `aws-sdk-bedrockruntime` gem。
* **Claude Platform on AWS：** 屬於主要 `anthropic` gem 的一部分（需要 `aws-sdk-core` gem）。提供 `Anthropic::AWSClient`。請將 `workspace_id:` 傳入建構子，或設定 `ANTHROPIC_AWS_WORKSPACE_ID` 環境變數（請參閱[工作區](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-platform-on-aws#workspaces)）。目前為 beta 版。
* **Foundry：** Ruby SDK 目前不支援。請參閱 [Claude in Microsoft Foundry](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-in-microsoft-foundry) 以了解支援的 SDK。

新專案請使用 `Anthropic::BedrockMantleClient`；`Anthropic::BedrockClient` 則保留給使用 Bedrock `InvokeModel` API 的既有應用程式。

## 語意化版本

此套件遵循 [SemVer](https://semver.org/spec/v2.0.0.html) 慣例。

此套件將對（非執行期的）`*.rbi` 與 `*.rbs` 型別定義的改進視為非破壞性變更。

## 其他資源

* [GitHub 儲存庫](https://github.com/anthropics/anthropic-sdk-ruby)
* [YARD 文件](https://gemdocs.org/gems/anthropic)
* [API 參考文件](https://platform.claude.com/docs/zh-TW/api/overview)
* [串流訊息](https://platform.claude.com/docs/zh-TW/build-with-claude/streaming)
