Files
anthropics_skills/skills/claude-api/ruby/claude-api.md
T
Lance Martin c30d329f58 Update claude-api skill: auth, cloud providers, Managed Agents fixes, token counting (#1276)
* Sync claude-api skill with latest upstream updates

- Add token-counting.md and SKILL.md trigger description update
- Add auth guidance: env credential resolution, ant auth login, OAuth/WIF doc links, 401 causes
- Add mid-conversation system messages (beta) to prompt-caching, agent-design, SKILL.md, Python/TS READMEs
- Add cache pre-warming (max_tokens: 0) section to prompt-caching
- Add Managed Agents pre-flight viability check to onboarding and overview
- Add Bedrock model-ID section to model-migration; add Bedrock row to live-sources
- Add /claude-api migrate subcommand row and migrate-entry callout
- Fix MA networking config: limited type with allow_package_managers/allow_mcp_servers
- Bump MA create-operations rate limit to 300 RPM
- Fix MA SDK drift: sessions.events.stream(), event.name, typed event arrays
- Add SDK coverage: stop_details, error .type, C# tool runner + MA support, Go model constants, Java 2.34.0, client config, response helpers, auto-pagination, advisor tool
- Move Sonnet 4 / Opus 4 to deprecated in models.md

* Add Anthropic CLI and Claude Platform on AWS docs to claude-api skill

- Add shared/anthropic-cli.md: install, auth profiles, OAuth scopes, command
  structure, version-controlled Managed Agents resources, credential traps
- Add shared/claude-platform-on-aws.md: AnthropicAWS clients, SigV4 auth,
  workspace_id, regions, feature availability
- Restore cross-references to both files throughout SKILL.md and the
  managed-agents docs (previously rewritten to live-sources.md pointers)
- Restore Claude Platform on AWS provider taxonomy in SKILL.md, the
  migration-guide section, and live-sources rows
2026-06-07 16:21:33 -04:00

3.4 KiB

Claude API — Ruby

Note: The Ruby SDK supports the Claude API. A tool runner is available in beta via client.beta.messages.tool_runner(). Agent SDK is not yet available for Ruby.

Installation

gem install anthropic

Client Initialization

require "anthropic"

# Default (uses ANTHROPIC_API_KEY env var)
client = Anthropic::Client.new

# Explicit API key
client = Anthropic::Client.new(api_key: "your-api-key")

Basic Message Request

message = client.messages.create(
  model: :"claude-opus-4-8",
  max_tokens: 16000,
  messages: [
    { role: "user", content: "What is the capital of France?" }
  ]
)
# content is an array of polymorphic block objects (TextBlock, ThinkingBlock,
# ToolUseBlock, ...). .type is a Symbol — compare with :text, not "text".
# .text raises NoMethodError on non-TextBlock entries.
message.content.each do |block|
  puts block.text if block.type == :text
end

Streaming

stream = client.messages.stream(
  model: :"claude-opus-4-8",
  max_tokens: 64000,
  messages: [{ role: "user", content: "Write a haiku" }]
)

stream.text.each { |text| print(text) }

Tool Use

The Ruby SDK supports tool use via raw JSON schema definitions and also provides a beta tool runner for automatic tool execution.

Tool Runner (Beta)

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-8",
  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

Manual Loop

See the shared tool use concepts for the tool definition format and agentic loop pattern.


Prompt Caching

system_: (trailing underscore — avoids shadowing Kernel#system) takes an array of text blocks; set cache_control on the last block. Plain hashes work via the OrHash type alias. For placement patterns and the silent-invalidator audit checklist, see shared/prompt-caching.md.

message = client.messages.create(
  model: :"claude-opus-4-8",
  max_tokens: 16000,
  system_: [
    { type: "text", text: long_system_prompt, cache_control: { type: "ephemeral" } }
  ],
  messages: [{ role: "user", content: "Summarize the key points" }]
)

For 1-hour TTL: cache_control: { type: "ephemeral", ttl: "1h" }. There's also a top-level cache_control: on messages.create that auto-places on the last cacheable block.

Verify hits via message.usage.cache_creation_input_tokens / message.usage.cache_read_input_tokens.


Stop Details

When stop_reason is :refusal, the response includes structured stop_details:

if message.stop_reason == :refusal && message.stop_details
  puts "Category: #{message.stop_details.category}"     # :cyber, :bio, or nil
  puts "Explanation: #{message.stop_details.explanation}"
end

Error Type

APIStatusError exposes a .type field for programmatic error classification:

begin
  client.messages.create(...)
rescue Anthropic::APIStatusError => e
  puts e.type  # :rate_limit_error, :overloaded_error, etc.
end