• 訊息
  • 託管代理
  • 管理
Search...
⌘K
CLI、SDK 與函式庫
概覽
ant CLI
快速入門驗證選項使用 CLI指令碼與自動化
用戶端 SDK
中介軟體PythonTypeScriptC#GoJavaPHPRuby
函式庫與整合
Apple Foundation ModelsOpenAI SDK 相容性
Log in
Ruby
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Solutions

  • AI agents
  • Code modernization
  • Coding
  • Customer support
  • Education
  • Financial services
  • Government
  • Life sciences

Partners

  • Amazon Bedrock
  • Google Cloud's Vertex AI

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Company

  • Anthropic
  • Careers
  • Economic Futures
  • Research
  • News
  • Responsible Scaling Policy
  • Security and compliance
  • Transparency

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Help and security

  • Availability
  • Status
  • Support
  • Discord

Terms and policies

  • Privacy policy
  • Responsible disclosure policy
  • Terms of service: Commercial
  • Terms of service: Consumer
  • Usage policy
CLI、SDK 與函式庫/用戶端 SDK

Ruby SDK

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

Anthropic Ruby 函式庫可讓任何 Ruby 3.2.0+ 應用程式方便地存取 Anthropic REST API。它隨附完整的型別定義與文件字串,支援 Yard、RBS 和 RBI 格式。HTTP 傳輸使用標準函式庫的 net/http,並透過 connection_pool gem 提供連線池功能。

如需包含程式碼範例的 API 功能文件,請參閱 API 參考。本頁面涵蓋 Ruby 專屬的 SDK 功能與設定。

安裝

使用 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-4-8"
)

puts(message.content)

如需了解包含「Workload Identity Federation」(工作負載身分聯合)在內的驗證選項,請參閱驗證。

串流

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

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

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

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

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

輸入結構描述與工具呼叫

SDK 提供輔助機制,可為工具定義結構化資料類別,並讓 Claude 自動執行這些工具。如需工具使用模式(包括工具執行器)的詳細文件,請參閱 Tool Runner (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-4-8",
  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-4-8"
  )
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

重試

某些錯誤預設會自動重試 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-4-8",
  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-4-8",
  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.beta.files.upload(file: Pathname("/path/to/file"))

# 或者,直接傳入檔案內容或 `StringIO`:
file_metadata = anthropic.beta.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.beta.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-4-8"
)

或者,等效的寫法:

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

# 您也可以展開(splat)完整的 Params 類別:
params = Anthropic::MessageCreateParams.new(
  max_tokens: 1024,
  messages: [Anthropic::MessageParam.new(role: "user", content: "Hello, Claude")],
  model: :"claude-opus-4-8"
)
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 中的其他類別並沒有鎖定機制來保護其底層資料結構。

發送自訂或未記載的請求

未記載的屬性

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

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

anthropic = Anthropic::Client.new
value = "example"
message =
  anthropic.messages.create(
    max_tokens: 1024,
    messages: [{role: "user", content: "Hello, Claude"}],
    model: :"claude-opus-4-8",
    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 發出請求,如下所示:

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

平台整合

如需包含程式碼範例的詳細平台設定指南,請參閱:

  • Amazon Bedrock
  • Amazon Bedrock(舊版)
  • Vertex AI
  • AWS 上的 Claude Platform

Ruby SDK 支援下列平台:

  • Bedrock: Anthropic::BedrockMantleClient,或針對 bedrock-runtime 路徑使用 Anthropic::BedrockClient。Anthropic::BedrockMantleClient 需要 aws-sdk-core gem;Anthropic::BedrockClient 需要 aws-sdk-bedrockruntime gem。
  • Vertex AI: Anthropic::VertexClient。需要 googleauth gem。
  • Foundry: Ruby SDK 目前不支援。請參閱 Microsoft Foundry 中的 Claude 以了解支援的 SDK。
  • AWS 上的 Claude Platform: 屬於主要 anthropic gem 的一部分(需要 aws-sdk-core gem)。提供 Anthropic::AWSClient。請將 workspace_id: 傳遞給建構函式,或設定 環境變數(請參閱 )。目前為測試版。

新專案請使用 Anthropic::BedrockMantleClient;Anthropic::BedrockClient 保留供使用 Bedrock InvokeModel API 的現有應用程式使用。

語意化版本控制

此套件遵循 SemVer 慣例。由於此函式庫處於初期開發階段,主版本號為 0,API 可能隨時變更。

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

其他資源

  • GitHub 儲存庫
  • YARD 文件
  • API 參考
  • 串流訊息

Was this page helpful?

  • 安裝
  • 需求
  • 使用方式
  • 串流
  • 串流輔助工具
  • 輸入結構描述與工具呼叫
  • 結構化輸出
  • 錯誤處理
  • 重試
  • 逾時
  • 分頁
  • 檔案上傳
  • Sorbet
  • 列舉
  • BaseModel
  • 並行與連線池
  • 發送自訂或未記載的請求
  • 未記載的屬性
  • 未記載的請求參數
  • 未記載的端點
  • 平台整合
  • 語意化版本控制
  • 其他資源
其他 HTTP 錯誤APIStatusError
逾時APITimeoutError
網路錯誤APIConnectionError
ANTHROPIC_AWS_WORKSPACE_ID
Workspaces