Claude Platform Docs
CLI、SDK 與函式庫用戶端 SDK

Ruby SDK

安裝並設定 Anthropic Ruby SDK,包含 Sorbet 型別、串流輔助工具與連線池

Anthropic Ruby 函式庫讓任何 Ruby 3.2.0+ 應用程式都能便利地存取 Claude API。它隨附完整的 Yard、RBS 與 RBI 型別及文件字串。HTTP 傳輸層使用標準函式庫的 net/http,並透過 connection_pool gem 提供「connection pooling」(連線池)功能。

安裝

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

bundle add anthropic

需求

Ruby 3.2.0 或更高版本。

使用方式

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"
)

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

如需了解包括 Workload Identity Federation(工作負載身分聯合)在內的驗證選項,請參閱驗證。如果您的 API 金鑰是可存取多個工作區的個人或服務帳戶金鑰,請在 anthropic-workspace-id 請求標頭中設定工作區 ID;選擇工作區說明了此 SDK 的逐請求選項。

串流

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

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

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

串流輔助工具

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

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

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

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

輸入結構描述與工具呼叫

此 SDK 提供輔助機制,可為工具定義結構化資料類別,並讓 Claude 自動執行它們。如需「tool use」(工具使用)模式的詳細文件(包含工具執行器),請參閱工具執行器(SDK)

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",
  max_tokens: 1024,
  messages: [{role: "user", content: "What's 15 * 7?"}],
  tools: [Calculator.new]
).each_message { |message| puts message.content }

結構化輸出

如需包含 Ruby 範例的完整結構化輸出文件,請參閱結構化輸出

錯誤處理

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

anthropic = Anthropic::Client.new
begin
  message = anthropic.messages.create(
    max_tokens: 1024,
    messages: [{role: "user", content: "Hello, Claude"}],
    model: :"claude-opus-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 400BadRequestError
HTTP 401AuthenticationError
HTTP 403PermissionDeniedError
HTTP 404NotFoundError
HTTP 409ConflictError
HTTP 422UnprocessableEntityError
HTTP 429RateLimitError
HTTP >= 500InternalServerError
其他 HTTP 錯誤APIStatusError
逾時APITimeoutError
網路錯誤APIConnectionError

重試

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

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

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

# 為所有請求設定預設值:
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",
  request_options: {max_retries: 5}
)

逾時

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

# 為所有請求設定預設值:
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",
  request_options: {timeout: 5}
)

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

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

分頁

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

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

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 方法,以更細緻地控制頁面操作。

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 實例、StringIO 等。

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 定義,且不依賴 sorbet-runtime。

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

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

或者,等效地:

anthropic = Anthropic::Client.new
# 雜湊可以運作,但不具型別安全:
anthropic.messages.create(
  max_tokens: 1024,
  messages: [{role: "user", content: "Hello, Claude"}],
  model: :"claude-opus-5"
)

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

列舉

由於此函式庫不依賴 sorbet-runtime,因此無法提供 T::Enum 實例。取而代之的是,SDK 提供「tagged symbols」(標記符號),其在執行期始終為基本型別:

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

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

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

# 使用列舉常數可保留標記型別資訊:
anthropic.messages.create(
  service_tier: Anthropic::MessageCreateParams::ServiceTier::AUTO,
  # ...
)

# 也允許使用字面值:
anthropic.messages.create(
  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 中的其他類別並沒有鎖來保護其底層資料結構。

發送自訂或未記載的請求

未記載的屬性

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

anthropic = Anthropic::Client.new
value = "example"
message =
  anthropic.messages.create(
    max_tokens: 1024,
    messages: [{role: "user", content: "Hello, Claude"}],
    model: :"claude-opus-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_queryextra_bodyextra_headers,如上方範例所示。

未記載的端點

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

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

平台整合

Ruby SDK 支援以下平台:

  • Agent Platform: Anthropic::VertexClient。需要 googleauth gem。
  • Bedrock: Anthropic::BedrockMantleClient,或針對 bedrock-runtime 路徑使用 Anthropic::BedrockClientAnthropic::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 環境變數(請參閱工作區)。目前為 beta 版。
  • Foundry: Ruby SDK 目前不支援。請參閱 Claude in Microsoft Foundry 以了解支援的 SDK。

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

語意化版本

此套件遵循 SemVer 慣例。

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

其他資源

Was this page helpful?