SPB Git

Repository Public

ruby.md 14.4 KB 417 lines markdown

1---2title: Ruby SDK3url: https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/ruby4description: Install and configure the Anthropic Ruby SDK with Sorbet types, streaming helpers, and connection pooling5---67The Anthropic Ruby library provides convenient access to the Claude API from any Ruby 3.2.0+ application. It ships with comprehensive types and docstrings in Yard, RBS, and RBI. The standard library's `net/http` is used as the HTTP transport, with connection pooling through the `connection_pool` gem.89<Info>10  For API feature documentation with code examples, see the [API reference](https://platform.claude.com/docs/en/api/overview). This page covers Ruby-specific SDK features and configuration.11</Info>1213## Installation1415Add the gem to your application's `Gemfile` with Bundler:1617```bash18bundle add anthropic19```2021## Requirements2223Ruby 3.2.0 or higher.2425## Usage2627```ruby28anthropic = Anthropic::Client.new(29  api_key: ENV["ANTHROPIC_API_KEY"] # This is the default and can be omitted30)3132message = anthropic.messages.create(33  max_tokens: 1024,34  messages: [{role: "user", content: "Hello, Claude"}],35  model: :"claude-opus-5"36)3738message.content.each do |block|39  puts block.text if block.type == :text40end41```4243For authentication options including Workload Identity Federation, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication). If your API key is a [personal or service account key](https://platform.claude.com/docs/en/manage-claude/authentication#key-types) with access to multiple workspaces, set the workspace ID in the `anthropic-workspace-id` request header; [Select a workspace](https://platform.claude.com/docs/en/manage-claude/authentication#select-a-workspace) shows the per-request option for this SDK.4445## Streaming4647The SDK provides support for streaming responses using Server-Sent Events (SSE).4849```ruby50anthropic = Anthropic::Client.new51stream = anthropic.messages.stream(52  max_tokens: 1024,53  messages: [{role: "user", content: "Hello, Claude"}],54  model: :"claude-opus-5"55)5657stream.each do |message|58  puts(message.type)59end60```6162### Streaming helpers6364This library provides several conveniences for streaming messages, for example:6566```ruby67anthropic = Anthropic::Client.new68stream = anthropic.messages.stream(69  max_tokens: 1024,70  messages: [{role: :user, content: "Say hello there!"}],71  model: :"claude-opus-5"72)7374stream.text.each do |text|75  print(text)76end77```7879Streaming with `anthropic.messages.stream(...)` exposes various helpers including accumulation and SDK-specific events.8081## Input schema and tool calling8283The SDK provides helper mechanisms to define structured data classes for tools and let Claude automatically execute them. For detailed documentation on tool use patterns including the tool runner, see [Tool Runner (SDK)](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner).8485```ruby86anthropic = Anthropic::Client.new87class CalculatorInput < Anthropic::BaseModel88  required :lhs, Float89  required :rhs, Float90  required :operator, Anthropic::InputSchema::EnumOf[:+, :-, :*, :/]91end9293class Calculator < Anthropic::BaseTool94  input_schema CalculatorInput9596  def call(expr)97    expr.lhs.public_send(expr.operator, expr.rhs)98  end99end100101# Automatically handles tool execution loop102anthropic.beta.messages.tool_runner(103  model: "claude-opus-5",104  max_tokens: 1024,105  messages: [{role: "user", content: "What's 15 * 7?"}],106  tools: [Calculator.new]107).each_message { |message| puts message.content }108```109110## Structured outputs111112For complete structured outputs documentation including Ruby examples, see [Structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs).113114## Handling errors115116When the library is unable to connect to the API, or if the API returns a non-success status code (that is, 4xx or 5xx response), a subclass of `Anthropic::Errors::APIError` is raised:117118```ruby119anthropic = Anthropic::Client.new120begin121  message = anthropic.messages.create(122    max_tokens: 1024,123    messages: [{role: "user", content: "Hello, Claude"}],124    model: :"claude-opus-5"125  )126rescue Anthropic::Errors::APIConnectionError => e127  puts("The server could not be reached")128  puts(e.cause)  # an underlying Exception, likely raised within `net/http`129rescue Anthropic::Errors::RateLimitError => e130  puts("A 429 status code was received; we should back off a bit.")131rescue Anthropic::Errors::APIStatusError => e132  puts("Another non-200-range status code was received")133  puts(e.status)134end135```136137Error codes are as follows:138139| Cause            | Error Type                 |140| ---------------- | -------------------------- |141| HTTP 400         | `BadRequestError`          |142| HTTP 401         | `AuthenticationError`      |143| HTTP 403         | `PermissionDeniedError`    |144| HTTP 404         | `NotFoundError`            |145| HTTP 409         | `ConflictError`            |146| HTTP 422         | `UnprocessableEntityError` |147| HTTP 429         | `RateLimitError`           |148| HTTP >= 500      | `InternalServerError`      |149| Other HTTP error | `APIStatusError`           |150| Timeout          | `APITimeoutError`          |151| Network error    | `APIConnectionError`       |152153## Retries154155Certain errors will be automatically retried 2 times by default, with a short exponential backoff.156157Connection errors (for example, because of a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, >=500 Internal errors, and timeouts are all retried by default.158159You can use the `max_retries` option to configure or disable this:160161```ruby162# Configure the default for all requests:163anthropic = Anthropic::Client.new(164  max_retries: 0 # default is 2165)166167# Or, configure per-request:168anthropic.messages.create(169  max_tokens: 1024,170  messages: [{role: "user", content: "Hello, Claude"}],171  model: :"claude-opus-5",172  request_options: {max_retries: 5}173)174```175176## Timeouts177178By default, requests time out after 10 minutes. You can use the `timeout` option to configure this:179180```ruby181# Configure the default for all requests:182anthropic = Anthropic::Client.new(183  timeout: 20 # 20 seconds (default is 10 minutes)184)185186# Or, configure per-request:187anthropic.messages.create(188  max_tokens: 1024,189  messages: [{role: "user", content: "Hello, Claude"}],190  model: :"claude-opus-5",191  request_options: {timeout: 5}192)193```194195On timeout, `Anthropic::Errors::APITimeoutError` is raised.196197Note that requests that time out are retried by default.198199## Pagination200201List methods in the Claude API are paginated.202203This library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually:204205```ruby206anthropic = Anthropic::Client.new207page = anthropic.messages.batches.list(limit: 20)208209# Fetch single item from page.210batch = page.data[0]211puts(batch.id)212213# Automatically fetches more pages as needed.214page.auto_paging_each do |batch|215  puts(batch.id)216end217```218219Alternatively, you can use the `#next_page?` and `#next_page` methods for more granular control working with pages.220221```ruby222anthropic = Anthropic::Client.new223page = anthropic.messages.batches.list(limit: 20)224loop do225  page.data&.each { |batch| puts(batch.id) }226  break unless page.next_page?227  page = page.next_page228end229```230231## File uploads232233Request parameters that correspond to file uploads can be passed as raw contents, a [`Pathname`](https://rubyapi.org/3.2/o/pathname) instance, [`StringIO`](https://rubyapi.org/3.2/o/stringio), or more.234235```ruby236anthropic = Anthropic::Client.new237require "pathname"238239# Use `Pathname` to send the filename and/or avoid paging a large file into memory:240file_metadata = anthropic.files.upload(file: Pathname("/path/to/file"))241242# Alternatively, pass file contents or a `StringIO` directly:243file_metadata = anthropic.files.upload(file: File.read("/path/to/file"))244245# Or, to control the filename and/or content type:246file = Anthropic::FilePart.new(File.read("/path/to/file"), filename: "/path/to/file", content_type: "...")247file_metadata = anthropic.files.upload(file: file)248249puts(file_metadata.id)250```251252Note that you can also pass a raw `IO` descriptor, but this disables retries, as the library can't be sure if the descriptor is a file or pipe (which cannot be rewound).253254## Sorbet255256This library provides comprehensive [RBI](https://sorbet.org/docs/rbi) definitions, and has no dependency on sorbet-runtime.257258You can provide typesafe request parameters like so:259260```ruby261anthropic = Anthropic::Client.new262anthropic.messages.create(263  max_tokens: 1024,264  messages: [Anthropic::MessageParam.new(role: "user", content: "Hello, Claude")],265  model: :"claude-opus-5"266)267```268269Or, equivalently:270271```ruby272anthropic = Anthropic::Client.new273# Hashes work, but are not typesafe:274anthropic.messages.create(275  max_tokens: 1024,276  messages: [{role: "user", content: "Hello, Claude"}],277  model: :"claude-opus-5"278)279280# You can also splat a full Params class:281params = Anthropic::MessageCreateParams.new(282  max_tokens: 1024,283  messages: [Anthropic::MessageParam.new(role: "user", content: "Hello, Claude")],284  model: :"claude-opus-5"285)286anthropic.messages.create(**params)287```288289### Enums290291Since this library does not depend on `sorbet-runtime`, it cannot provide [`T::Enum`](https://sorbet.org/docs/tenum) instances. Instead, the SDK provides "tagged symbols", which is always a primitive at runtime:292293```ruby294# :auto295puts(Anthropic::MessageCreateParams::ServiceTier::AUTO)296297# Revealed type: `T.all(Anthropic::MessageCreateParams::ServiceTier, Symbol)`298T.reveal_type(Anthropic::MessageCreateParams::ServiceTier::AUTO)299```300301Enum parameters have a "relaxed" type, so you can either pass in enum constants or their literal value:302303```ruby304# Using the enum constants preserves the tagged type information:305anthropic.messages.create(306  service_tier: Anthropic::MessageCreateParams::ServiceTier::AUTO,307  # ...308)309310# Literal values are also permissible:311anthropic.messages.create(312  service_tier: :auto,313  # ...314)315```316317## BaseModel318319All parameter and response objects inherit from `Anthropic::Internal::Type::BaseModel`, which provides several conveniences, including:3203211. All fields, including unknown ones, are accessible with `obj[:prop]` syntax, and can be destructured with `obj => {prop: prop}` or pattern-matching syntax.3223232. Structural equivalence for equality; if two API calls return the same values, comparing the responses with == will return true.3243253. Both instances and the classes themselves can be pretty-printed.3263274. Helpers such as `#to_h`, `#deep_to_h`, `#to_json`, and `#to_yaml`.328329## Concurrency and connection pooling330331The `Anthropic::Client` instances are threadsafe, but are only fork-safe when there are no in-flight HTTP requests.332333Each instance of `Anthropic::Client` has its own HTTP connection pool with a default size of 99. As such, the recommendation is to create the client once per application in most settings.334335When all available connections from the pool are checked out, requests wait for a new connection to become available, with queue time counting toward the request timeout.336337Unless otherwise specified, other classes in the SDK do not have locks protecting their underlying data structure.338339## Making custom or undocumented requests340341### Undocumented properties342343You can send undocumented parameters to any endpoint, and read undocumented response properties, like so:344345<Warning>346  The `extra_` parameters of the same name override the documented parameters. For security reasons, ensure these methods are only used with trusted input data.347</Warning>348349```ruby350anthropic = Anthropic::Client.new351value = "example"352message =353  anthropic.messages.create(354    max_tokens: 1024,355    messages: [{role: "user", content: "Hello, Claude"}],356    model: :"claude-opus-5",357    request_options: {358      extra_query: {my_query_parameter: value},359      extra_body: {my_body_parameter: value},360      extra_headers: {"my-header": value}361    }362  )363364puts(message[:my_undocumented_property])365```366367### Undocumented request params368369If you want to explicitly send an extra param, you can do so with the `extra_query`, `extra_body`, and `extra_headers` under the `request_options:` parameter when making a request, as seen in the examples above.370371### Undocumented endpoints372373To make requests to undocumented endpoints while retaining the benefit of auth, retries, and so on, you can make requests using `anthropic.request`, like so:374375```ruby376response = anthropic.request(377  method: :post,378  path: '/undocumented/endpoint',379  query: {"dog": "woof"},380  headers: {"useful-header": "interesting-value"},381  body: {"hello": "world"}382)383```384385## Platform integrations386387<Note>388  For detailed platform setup guides with code examples, see:389390  * [Amazon Bedrock](https://platform.claude.com/docs/en/build-with-claude/claude-in-amazon-bedrock)391  * [Amazon Bedrock (Opus 4.6 and earlier)](https://platform.claude.com/docs/en/build-with-claude/claude-on-amazon-bedrock-legacy)392  * [Claude Platform on AWS](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws)393  * [Google Cloud](https://platform.claude.com/docs/en/build-with-claude/claude-on-vertex-ai)394</Note>395396The Ruby SDK supports the following platforms:397398* **Agent Platform:** `Anthropic::VertexClient`. Requires the `googleauth` gem.399* **Bedrock:** `Anthropic::BedrockMantleClient`, or `Anthropic::BedrockClient` for the `bedrock-runtime` path. `Anthropic::BedrockMantleClient` requires the `aws-sdk-core` gem; `Anthropic::BedrockClient` requires the `aws-sdk-bedrockruntime` gem.400* **Claude Platform on AWS:** Part of the main `anthropic` gem (requires the `aws-sdk-core` gem). Provides `Anthropic::AWSClient`. Pass `workspace_id:` to the constructor or set the `ANTHROPIC_AWS_WORKSPACE_ID` environment variable (see [Workspaces](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws#workspaces)). Available in beta.401* **Foundry:** Not currently supported in the Ruby SDK. See [Claude in Microsoft Foundry](https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry) for supported SDKs.402403Use `Anthropic::BedrockMantleClient` for new projects; `Anthropic::BedrockClient` remains for existing applications using the Bedrock `InvokeModel` API.404405## Semantic versioning406407This package follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions.408409This package considers improvements to the (non-runtime) `*.rbi` and `*.rbs` type definitions to be non-breaking changes.410411## Additional resources412413* [GitHub repository](https://github.com/anthropics/anthropic-sdk-ruby)414* [YARD documentation](https://gemdocs.org/gems/anthropic)415* [API reference](https://platform.claude.com/docs/en/api/overview)416* [Streaming Messages](https://platform.claude.com/docs/en/build-with-claude/streaming)417
Files main
Menu

Theme