Anthropic Ruby SDK

repository·main·Indexed 18 days ago

https://github.com/anthropics/anthropic-sdk-ruby

A programmatic interface for Ruby applications to access the Claude API. The SDK supports the Messages and Completions APIs, real-time response streaming via MessageStream, and structured outputs using Anthropic::BaseModel. It includes a beta auto-looping tool runner for automated tool execution and supports multiple authentication methods including API keys, environment variables, and Workload Identity Federation. Requires Ruby 3.2.0 or higher.

Tokens
11.4K
Snippets
30
Records
49
Agent score
62%

What's inside anthropic-sdk-ruby

  1. Define input schemas with Anthropic::BaseModel

    main

    Use Anthropic::BaseModel to define structured data classes for tools and structured outputs. This allows you to specify required/optional fields, types, and documentation.

    Field Definitions:

    • required :name, Type: Field must be provided and cannot be nil.
    • optional :name, Type: Field may be omitted; if provided, it cannot be nil.
    • required :name, Type, nil?: true: Field must be provided but can be nil.
    • optional :name, Type, nil?: true: Field may be omitted or be nil.

    Supported Types:

    • Basic: String, Integer, Float, Anthropic::Boolean.
    • Complex:
      • Anthropic::EnumOf[:opt1, :opt2]
      • Anthropic::ArrayOf[Type]
      • Anthropic::UnionOf[Type1, Type2]
      • Nested Models: Other Anthropic::BaseModel subclasses.
    • Nullability: Use nil?: true or Anthropic::UnionOf[Type, NilClass] to allow null values.
    class GetWeatherInput < Anthropic::BaseModel
      required :location, String, doc: "The city and state, e.g. San Francisco, CA"
      optional :unit, Anthropic::EnumOf[:celsius, :fahrenheit], doc: "Temperature unit"
    end
  2. Stream structured outputs

    main

    Structured outputs are compatible with streaming. While you can stream the raw text chunks as they arrive, the fully parsed model instance is only available once the stream is complete. You can access the final parsed object via stream.accumulated_message.parsed_output.

    stream = anthropic.messages.stream(
      model: "claude-sonnet-5",
      max_tokens: 1024,
      messages: [{role: "user", content: "give me some famous numbers"}],
      output_config: {format: Output}
    )
    
    # Stream the raw text as it arrives
    stream.text.each { |text| print(text) }
    
    # Get the parsed output from the accumulated message after completion
    stream.accumulated_message.parsed_output
  3. Define structured outputs using Input Schema Helpers

    main

    You can define the expected structure of Claude's response by subclassing Anthropic::BaseModel. This allows you to specify required and optional fields with specific types, documentation strings, and constraints like min_length or max_length.

    Use these models in the output_config parameter of the messages.create method.

    class FamousNumber < Anthropic::BaseModel
      required :value, Float
      optional :reason, String, doc: "why is this number mathematically significant?"
    end
    
    class Output < Anthropic::BaseModel
      doc "some famous numbers"
    
      required :numbers, Anthropic::ArrayOf[FamousNumber], min_length: 3, max_length: 5
    end
    
    message = anthropic.messages.create(
      model: "claude-sonnet-5",
      max_tokens: 1024,
      messages: [{role: "user", content: "give me some famous numbers"}],
      output_config: {format: Output}
    )
  4. Get started with the Anthropic Ruby SDK

    main

    To interact with Claude, initialize an Anthropic::Client and use the messages.create method. By default, the client looks for your API key in the ANTHROPIC_API_KEY environment variable, so you can omit the api_key argument if it is set.

    require "bundler/setup"
    require "anthropic"
    
    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-6"
    )
    
    puts(message.content)
  5. Implement tools using Manual, Streaming, or Auto-Looping approaches

    main

    The SDK provides three ways to handle tool use:

    1. Manual Tool Handling

    Manually check if the stop_reason is :tool_use, extract the ToolUseBlock from the message content, execute your logic, and send the result back.

    2. Streaming Tools

    Use client.messages.stream and listen for Anthropic::Streaming::InputJsonEvent to get incremental JSON updates and snapshots of the tool input as they are generated.

    3. Auto-Looping Tool Runner (Beta)

    Use client.beta.messages.tool_runner to automatically execute tools and manage the conversation loop. This requires tools to inherit from Anthropic::BaseTool and define an input_schema using a BaseModel.

    class Calculator < Anthropic::BaseTool
      doc "i am a calculator and i am good at math"
      input_schema CalculatorInput
    
      def call(expr)
        expr.lhs.public_send(expr.operator, expr.rhs)
      end
    end
    
    tool = Calculator.new
    
    client.beta.messages.tool_runner(
      model: "claude-sonnet-5",
      max_tokens: 1024,
      messages: [{role: "user", content: "What's 15 * 7?"}],
      tools: [tool]
    ).each_message { puts _1.content }
  6. Configure output_config for structured outputs

    main

    The output_config parameter controls how Claude formats its response. It accepts two formats:

    1. BaseModel Class: Pass a subclass of Anthropic::BaseModel directly to use the helper's validation and parsing.
    2. Raw JSON Schema: Pass a hash specifying the schema type: {format: {type: :json_schema, schema: {...}}}.
  7. Configure Identity Token sources for OIDC Federation

    main

    When using OIDC_FEDERATION authentication, you must provide an identity token. The SDK supports two primary sources for this token via the identity_token configuration key:

    1. File: Specify a path to a file containing the token.
      • Configuration shape: { identity_token: { source: 'file', path: '/path/to/token' } } or simply { identity_token: '/path/to/token' }.
    2. Environment Variable: Specify the name of an environment variable that contains the token.
      • Configuration shape: { identity_token: { source: 'env', value: 'ENV_VAR_NAME' } }.

    Required Fields for OIDC Federation:

    • authentication.type: Must be OIDC_FEDERATION.
    • authentication.federation_rule_id: The ID of the federation rule.
    • organization_id: The top-level organization ID.
    • identity_token: One of the sources described above.
  8. How credential precedence works in the Anthropic SDK

    main

    The SDK resolves credentials using a tiered approach to allow for both local development (via env vars) and production environments (via federation/profiles).

    Precedence Order (Highest to Lowest):

    1. Explicit Constructor Arguments: api_key, auth_token, credentials, or config.
    2. Environment Variables: ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN.
    3. Profile Selection: ANTHROPIC_PROFILE.
    4. Direct Env-var Federation: ANTHROPIC_IDENTITY_TOKEN[_FILE], ANTHROPIC_FEDERATION_RULE_ID, and ANTHROPIC_ORGANIZATION_ID.
    5. Disk-based Profiles: The active profile from disk (e.g., default).

    Important: If you provide a static credential in step 1 or 2, the SDK will skip steps 3-5 entirely. This is intended to prevent accidental credential leakage or unexpected behavior when a developer explicitly defines a key.

  9. Integrate Model Context Protocol (MCP) servers with Anthropic SDK

    main

    The Anthropic::Helpers::Tools::Mcp module provides helpers to convert types returned by the mcp gem into the shapes required by the Anthropic Beta Messages API. This allows you to use MCP tools, messages, and resources directly with the Anthropic SDK without writing manual glue code.

    Requirement: The mcp gem is an optional dependency. You must install it separately:

    gem install mcp
    require "mcp"
    require "anthropic"
    
    transport  = MCP::Client::HTTP.new(url: "https://example.com/mcp")
    mcp_client = MCP::Client.new(transport: transport)
    anthropic  = Anthropic::Client.new
    
    runner = anthropic.beta.messages.tool_runner(
      model: "claude-sonnet-4-5",
      max_tokens: 1024,
      messages: [{role: "user", content: "Use the available tools"}],
      tools: Anthropic::Mcp.tools(mcp_client.tools, mcp_client)
    )
    runner.run_until_finished
  10. Use the Anthropic Google Cloud Client

    main

    The Anthropic::Helpers::GoogleCloud::Client is a specialized client for accessing the Claude Platform via the Google Cloud gateway. Unlike the Anthropic::VertexClient (which targets the :rawPredict publisher-model API), this client supports the full first-party Anthropic API surface, including standard /v1/* paths and model names. It does not support the deprecated text Completions endpoint.

    Authentication

    Authentication is handled via Google credentials. The client resolves credentials in the following order of precedence:

    1. token_provider: A callable that returns a GCP access token string (called per attempt).
    2. google_credentials: A googleauth-compatible object responding to #apply.
    3. Application Default Credentials (ADC): Automatically resolved via Google::Auth.get_application_default with the cloud-platform scope.

    Note: skip_auth: true can be used to disable authentication entirely, which is useful when fronting with your own authenticated proxy. This is mutually exclusive with token_provider and google_credentials.

    # Example using Application Default Credentials
    client = Anthropic::Helpers::GoogleCloud::Client.new(
      project: 'your-gcp-project-id',
      location: 'us-central1',
      workspace_id: 'your-workspace-id'
    )
    
    # Accessing resources
    response = client.messages.create(
      model: 'claude-3-5-sonnet-20240620',
      max_tokens: 1024,
      messages: [{ role: 'user', content: 'Hello, Claude!' }]
    )