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 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-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 自动执行它们。有关工具使用模式(包括工具运行器)的详细文档,请参阅工具运行器(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 400 | BadRequestError |
| HTTP 401 | AuthenticationError |
| HTTP 403 | PermissionDeniedError |
| HTTP 404 | NotFoundError |
| HTTP 409 | ConflictError |
| HTTP 422 | UnprocessableEntityError |
| HTTP 429 | RateLimitError |
| HTTP >= 500 | InternalServerError |
某些错误默认会自动重试 2 次,并采用短暂的指数退避策略。
连接错误(例如由于网络连接问题)、408 请求超时、409 冲突、429 速率限制、>=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 描述符,但这会禁用重试,因为库无法确定该描述符是文件还是管道(管道无法回退)。
此库提供了完整的 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"
)
# 您也可以展开传入完整的 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,
# ...
)所有参数和响应对象都继承自 Anthropic::Internal::Type::BaseModel,它提供了多种便捷功能,包括:
所有字段(包括未知字段)都可以通过 obj[:prop] 语法访问,并且可以使用 obj => {prop: prop} 或模式匹配语法进行解构。
相等性的结构等价;如果两个 API 调用返回相同的值,使用 == 比较响应将返回 true。
实例和类本身都可以进行美化打印。
辅助方法,如 #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"}
)有关包含代码示例的详细平台设置指南,请参阅:
Ruby SDK 支持以下平台:
Anthropic::BedrockMantleClient,或用于 bedrock-runtime 路径的 Anthropic::BedrockClient。Anthropic::BedrockMantleClient 需要 aws-sdk-core gem;Anthropic::BedrockClient 需要 aws-sdk-bedrockruntime gem。Anthropic::VertexClient。需要 googleauth gem。anthropic gem 的一部分(需要 aws-sdk-core gem)。提供 Anthropic::AWSClient。将 workspace_id: 传递给构造函数,或设置 环境变量(请参阅)。目前处于测试阶段。新项目请使用 Anthropic::BedrockMantleClient;Anthropic::BedrockClient 保留用于使用 Bedrock InvokeModel API 的现有应用程序。
此包遵循 SemVer 约定。由于该库处于初始开发阶段,主版本号为 0,API 可能随时更改。
此包将对(非运行时)*.rbi 和 *.rbs 类型定义的改进视为非破坏性更改。
Was this page helpful?
| 其他 HTTP 错误 | APIStatusError |
| 超时 | APITimeoutError |
| 网络错误 | APIConnectionError |
ANTHROPIC_AWS_WORKSPACE_ID