Class: ActiveAgent::Providers::Anthropic::Request

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/active_agent/providers/anthropic/request.rb

Overview

Request wrapper that delegates to Anthropic gem model.

Uses SimpleDelegator to wrap ::Anthropic::Models::MessageCreateParams, eliminating the need to maintain duplicate attribute definitions while providing convenience transformations and custom fields.

All standard Anthropic API fields are automatically available via delegation:

  • model, messages, max_tokens
  • system, temperature, top_k, top_p, stop_sequences
  • tools, tool_choice, thinking
  • stream, metadata, context_management, container, service_tier, mcp_servers

Custom fields managed separately:

  • response_format (simulated JSON mode feature)

Examples:

Basic usage

request = Request.new(
  model: "claude-3-5-haiku-latest",
  messages: [{role: "user", content: "Hello"}]
)
request.model      #=> "claude-3-5-haiku-latest"
request.max_tokens #=> 4096 (default)

With transformations

# String content is automatically normalized
request = Request.new(
  model: "...",
  messages: [{role: "user", content: "Hi"}]
)
# Internally becomes: [{type: "text", text: "Hi"}]

Custom field

request = Request.new(
  model: "...",
  messages: [...],
  response_format: {type: "json_object"}
)
request.response_format #=> {type: "json_object"}

Constant Summary collapse

DEFAULT_MAX_TOKENS =

Default max_tokens value when not specified

4096
DEFAULTS =

Default values for optional parameters

{
  max_tokens: DEFAULT_MAX_TOKENS,
  stop_sequences: [],
  mcp_servers: []
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**params) ⇒ Request

Returns a new instance of Request.

Parameters:

  • params (Hash)

Options Hash (**params):

  • :model (String)

    required

  • :messages (Array<Hash>)

    required

  • :max_tokens (Integer) — default: 4096
  • :response_format (Hash)

    custom field for JSON mode simulation

  • :anthropic_beta (String)

    beta version for features like MCP

Raises:

  • (ArgumentError)

    when gem model validation fails



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/active_agent/providers/anthropic/request.rb', line 72

def initialize(**params)
  # Step 1: Extract custom fields that gem doesn't support
  # Read response_format without deleting - normalize_params will delete and convert it
  # to output_config for json_schema, or drop it for other types.
  @response_format = params[:response_format]
  @stream = params.delete(:stream)
  anthropic_beta = params.delete(:anthropic_beta)

  # Step 2: Map common format 'instructions' to Anthropic's 'system'
  if params.key?(:instructions)
    params[:system] = params.delete(:instructions)
  end

  # Step 3: Apply defaults
  params = apply_defaults(params)

  # Step 4: Transform params for gem compatibility
  transformed = Transforms.normalize_params(params)

  # Step 5: Determine if we need beta params (for MCP or other beta features)
  use_beta = anthropic_beta.present? || transformed[:mcp_servers]&.any?

  # Step 6: Add betas parameter if using beta API
  if use_beta
    # Default to MCP beta version if not specified
    beta_version = anthropic_beta || "mcp-client-2025-04-04"
    transformed[:betas] = [ beta_version ]
  end

  # Step 7: Create gem model - use Beta version if needed
  gem_model = if use_beta
    ::Anthropic::Models::Beta::MessageCreateParams.new(**transformed)
  else
    ::Anthropic::Models::MessageCreateParams.new(**transformed)
  end

  # Step 8: Delegate all method calls to gem model
  super(gem_model)
rescue ArgumentError => e
  # Re-raise with more context
  raise ArgumentError, "Invalid Anthropic request parameters: #{e.message}"
end

Instance Attribute Details

#response_formatHash? (readonly)

Returns simulated JSON response format configuration.

Returns:

  • (Hash, nil)

    simulated JSON response format configuration



60
61
62
# File 'lib/active_agent/providers/anthropic/request.rb', line 60

def response_format
  @response_format
end

#streamBoolean? (readonly)

Returns whether to stream the response.

Returns:

  • (Boolean, nil)

    whether to stream the response



63
64
65
# File 'lib/active_agent/providers/anthropic/request.rb', line 63

def stream
  @stream
end

Instance Method Details

#instructionsString, ...

Alias for system (common format compatibility).

Returns:

  • (String, Array, nil)


146
147
148
# File 'lib/active_agent/providers/anthropic/request.rb', line 146

def instructions
  system
end

#instructions=(value) ⇒ Object

Parameters:

  • value (String, Array)


151
152
153
# File 'lib/active_agent/providers/anthropic/request.rb', line 151

def instructions=(value)
  self.system = value
end

#mcp_serversArray

Accessor for MCP servers.

Safely returns MCP servers array, defaulting to empty array if not set.

Returns:

  • (Array)


160
161
162
# File 'lib/active_agent/providers/anthropic/request.rb', line 160

def mcp_servers
  __getobj__.instance_variable_get(:@data)[:mcp_servers] || []
end

#pop_message!void

This method returns an undefined value.

Removes the last message from the messages array.

Used for JSON format simulation to remove the lead-in assistant message.



169
170
171
172
173
# File 'lib/active_agent/providers/anthropic/request.rb', line 169

def pop_message!
  new_messages = messages.dup
  new_messages.pop
  self.messages = new_messages
end

#serializeHash

Serializes request for API call.

Uses gem's JSON serialization and delegates cleanup to Transforms module.

Returns:

  • (Hash)


120
121
122
123
124
125
126
# File 'lib/active_agent/providers/anthropic/request.rb', line 120

def serialize
  # Use gem's JSON serialization (handles all nested objects)
  hash = Anthropic::Transforms.gem_to_hash(__getobj__)

  # Delegate cleanup to transforms module
  Transforms.cleanup_serialized_request(hash, DEFAULTS, __getobj__)
end

#systemString, ...

Accessor for system instructions.

Must override SimpleDelegator's method_missing because Ruby's Kernel.system conflicts with delegation. The gem stores data in @data instance variable.

Returns:

  • (String, Array, nil)


134
135
136
# File 'lib/active_agent/providers/anthropic/request.rb', line 134

def system
  __getobj__.instance_variable_get(:@data)[:system]
end

#system=(value) ⇒ Object

Parameters:

  • value (String, Array)


139
140
141
# File 'lib/active_agent/providers/anthropic/request.rb', line 139

def system=(value)
  __getobj__.instance_variable_get(:@data)[:system] = value
end