Anthropic Ruby 库为任何 Ruby 3.2.0+ 应用程序提供了对 Anthropic REST API 的便捷访问。它附带了 Yard、RBS 和 RBI 格式的全面类型和文档字符串。标准库的 net/http 被用作 HTTP 传输层,并通过 connection_pool gem 实现连接池。
有关包含代码示例的 API 功能文档,请参阅 API 参考。本页面涵盖 Ruby 特有的 SDK 功能和配置。
使用 Bundler 将 gem 添加到您应用程序的 Gemfile 中:
bundle add anthropicRuby 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(工作负载身份联合)在内的身份验证选项,请参阅身份验证。
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-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 自动执行它们。有关工具使用模式(包括工具运行器)的详细文档,请参阅工具运行器(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 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 选项来配置或禁用此功能:
# 为所有请求配置默认值:
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.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 描述符,但这会禁用重试功能,因为库无法确定该描述符是文件还是管道(管道无法回退)。
此库提供了全面的 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
# 哈希(Hash)可以使用,但不是类型安全的:
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,
# ...
)所有参数和响应对象都继承自 Anthropic::Internal::Type::BaseModel,它提供了多种便利功能,包括:
所有字段(包括未知字段)都可以通过 obj[:prop] 语法访问,并且可以使用 obj => {prop: prop} 或模式匹配语法进行解构。
使用结构等价性进行相等性判断;如果两次 API 调用返回相同的值,使用 == 比较响应将返回 true。
实例和类本身都可以被美化打印(pretty-printed)。
诸如 #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-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 发起请求,如下所示:
response = anthropic.request(
method: :post,
path: '/undocumented/endpoint',
query: {"dog": "woof"},
headers: {"useful-header": "interesting-value"},
body: {"hello": "world"}
)有关包含代码示例的详细平台设置指南,请参阅:
Ruby SDK 支持以下平台:
Anthropic::VertexClient。需要 googleauth gem。Anthropic::BedrockMantleClient,或用于 bedrock-runtime 路径的 Anthropic::BedrockClient。Anthropic::BedrockMantleClient 需要 aws-sdk-core gem;Anthropic::BedrockClient 需要 aws-sdk-bedrockruntime gem。anthropic gem 的一部分(需要 aws-sdk-core gem)。提供 Anthropic::AWSClient。将 workspace_id: 传递给构造函数或设置 ANTHROPIC_AWS_WORKSPACE_ID 环境变量(请参阅工作区)。目前处于测试版。新项目请使用 Anthropic::BedrockMantleClient;Anthropic::BedrockClient 保留给使用 Bedrock InvokeModel API 的现有应用程序。
此包遵循 SemVer 约定。由于该库处于初始开发阶段,主版本号为 0,API 可能随时发生变化。
此包将对(非运行时的)*.rbi 和 *.rbs 类型定义的改进视为非破坏性变更。
Was this page helpful?