[ PROMPT_NODE_23844 ]
claude-api
[ SKILL_DOCUMENTATION ]
# Claude API — Ruby
> **注意:** Ruby SDK 支持 Claude API。工具运行器(Tool Runner)目前处于测试阶段,可通过 `client.beta.messages.tool_runner()` 使用。智能体 SDK 尚未提供 Ruby 版本。
## 安装
bash
gem install anthropic
## 客户端初始化
ruby
require "anthropic"
# 默认(使用 ANTHROPIC_API_KEY 环境变量)
client = Anthropic::Client.new
# 显式指定 API 密钥
client = Anthropic::Client.new(api_key: "your-api-key")
---
## 基础消息请求
ruby
message = client.messages.create(
model: :"claude-opus-4-7",
max_tokens: 16000,
messages: [
{ role: "user", content: "What is the capital of France?" }
]
)
# content 是多态块对象数组(TextBlock, ThinkingBlock, ToolUseBlock 等)。
# .type 是一个 Symbol — 请与 :text 进行比较,而不是 "text"。
# 对非 TextBlock 条目调用 .text 会引发 NoMethodError。
message.content.each do |block|
puts block.text if block.type == :text
end
---
## 流式传输
ruby
stream = client.messages.stream(
model: :"claude-opus-4-7",
max_tokens: 64000,
messages: [{ role: "user", content: "Write a haiku" }]
)
stream.text.each { |text| print(text) }
---
## 工具使用
Ruby SDK 通过原始 JSON 模式定义支持工具使用,并提供了一个用于自动工具执行的测试版工具运行器。
### 工具运行器 (Beta)
ruby
class GetWeatherInput < Anthropic::BaseModel
required :location, String, doc: "City and state, e.g. San Francisco, CA"
end
class GetWeather < Anthropic::BaseTool
doc "Get the current weather for a location"
input_schema GetWeatherInput
def call(input)
"The weather in #{input.location} is sunny and 72°F."
end
end
client.beta.messages.tool_runner(
model: :"claude-opus-4-7",
max_tokens: 16000,
tools: [GetWeather.new],
messages: [{ role: "user", content: "What's the weather in San Francisco?" }]
).each_message do |message|
puts message.content
end
### 手动循环
有关工具定义格式和智能体循环模式,请参阅 [共享工具使用概念](../shared/tool-use-concepts.md)。
---
## 提示词缓存
`system_:`(尾随下划线 — 避免遮蔽 `Kernel#system`)接受一个文本块数组;在最后一个块上设置 `cache_control`。普通哈希通过 `OrHash` 类型别名工作。有关放置模式和静默失效审计清单,请参阅 `shared/prompt-caching.md`。
ruby
message = client.messages.create(
model: :"claude-opus-4-7",
max_tokens: 16000,
system_: [
{ type: "text"}