llm_gateway 0.8.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +36 -0
  3. data/README.md +190 -79
  4. data/Rakefile +5 -0
  5. data/docs/migration_guide_0.10.0.md +53 -0
  6. data/docs/migration_guide_0.9.0.md +166 -0
  7. data/docs/structured-output.md +28 -0
  8. data/lib/llm_gateway/adapter_definition.rb +64 -0
  9. data/lib/llm_gateway/adapters/adapter.rb +105 -21
  10. data/lib/llm_gateway/adapters/anthropic/messages_adapter.rb +8 -0
  11. data/lib/llm_gateway/adapters/anthropic_option_mapper.rb +29 -19
  12. data/lib/llm_gateway/adapters/groq/chat_completions_adapter.rb +8 -0
  13. data/lib/llm_gateway/adapters/groq/option_mapper.rb +7 -9
  14. data/lib/llm_gateway/adapters/normalized_stream_accumulator.rb +7 -3
  15. data/lib/llm_gateway/adapters/openai/chat_completions/option_mapper.rb +7 -9
  16. data/lib/llm_gateway/adapters/openai/chat_completions/stream_mapper.rb +1 -1
  17. data/lib/llm_gateway/adapters/openai/chat_completions_adapter.rb +6 -0
  18. data/lib/llm_gateway/adapters/openai/responses/option_mapper.rb +11 -9
  19. data/lib/llm_gateway/adapters/openai/responses/stream_mapper.rb +1 -1
  20. data/lib/llm_gateway/adapters/openai/responses_adapter.rb +6 -0
  21. data/lib/llm_gateway/adapters/openai_codex/responses_adapter.rb +8 -0
  22. data/lib/llm_gateway/adapters/stream_mapper.rb +4 -3
  23. data/lib/llm_gateway/agents/event.rb +31 -3
  24. data/lib/llm_gateway/agents/harness.rb +107 -74
  25. data/lib/llm_gateway/agents/in_memory_session_manager.rb +40 -9
  26. data/lib/llm_gateway/agents/tools/bash_tool.rb +6 -5
  27. data/lib/llm_gateway/agents/tools/edit_tool.rb +7 -6
  28. data/lib/llm_gateway/agents/tools/read_tool.rb +11 -10
  29. data/lib/llm_gateway/agents/tools/tool_utils.rb +2 -2
  30. data/lib/llm_gateway/agents/tools/write_tool.rb +4 -3
  31. data/lib/llm_gateway/errors.rb +3 -0
  32. data/lib/llm_gateway/models/catalog.rb +68 -0
  33. data/lib/llm_gateway/models/cost_calculator.rb +47 -0
  34. data/lib/llm_gateway/models/definition.rb +325 -0
  35. data/lib/llm_gateway/models/explicit.rb +46 -0
  36. data/lib/llm_gateway/models/generated.json +3055 -0
  37. data/lib/llm_gateway/models.rb +78 -0
  38. data/lib/llm_gateway/prompt.rb +55 -31
  39. data/lib/llm_gateway/proxy/adapter.rb +22 -12
  40. data/lib/llm_gateway/proxy/client.rb +4 -4
  41. data/lib/llm_gateway/proxy/protocol.rb +50 -0
  42. data/lib/llm_gateway/proxy/server.rb +12 -9
  43. data/lib/llm_gateway/tool.rb +49 -40
  44. data/lib/llm_gateway/utils.rb +12 -6
  45. data/lib/llm_gateway/version.rb +1 -1
  46. data/lib/llm_gateway.rb +5 -68
  47. data/scripts/generate_model_catalog.rb +195 -0
  48. metadata +14 -4
  49. data/lib/llm_gateway/client.rb +0 -35
  50. data/lib/llm_gateway/provider_registry.rb +0 -37
@@ -3,6 +3,7 @@
3
3
  require "json"
4
4
 
5
5
  require_relative "../utils"
6
+ require_relative "../models/cost_calculator"
6
7
  require_relative "structs"
7
8
 
8
9
  module LlmGateway
@@ -54,7 +55,7 @@ module LlmGateway
54
55
  # The accumulator creates the public Assistant* event structs, updates its
55
56
  # accumulated message state, then yields the created event to the callback.
56
57
  attr_accessor :blocks, :message_hash, :usage_hash
57
- attr_reader :active_block_type, :final_message
58
+ attr_reader :active_block_type, :final_message, :model_definition
58
59
 
59
60
  DEFAULT_USAGE = {
60
61
  input: 0,
@@ -62,7 +63,8 @@ module LlmGateway
62
63
  cache_read: 0,
63
64
  output: 0,
64
65
  total: 0,
65
- raw: {}
66
+ raw: {},
67
+ cost: nil
66
68
  }.freeze
67
69
 
68
70
  BLOCK_EVENT_TRANSITIONS = {
@@ -80,9 +82,10 @@ module LlmGateway
80
82
  reasoning_end: { block_type: :reasoning, phase: :end }
81
83
  }.freeze
82
84
 
83
- def initialize(provider: nil, api: nil)
85
+ def initialize(provider: nil, api: nil, model_definition: nil)
84
86
  @provider = provider
85
87
  @api = api
88
+ @model_definition = model_definition
86
89
  @message_hash = {}
87
90
  @usage_hash = default_usage
88
91
  @blocks = []
@@ -322,6 +325,7 @@ module LlmGateway
322
325
  usage = default_usage.merge(usage.to_h.symbolize_keys.slice(*DEFAULT_USAGE.keys))
323
326
  usage[:total] = usage[:input] + usage[:cache_write] + usage[:cache_read] + usage[:output]
324
327
  usage[:raw] ||= {}
328
+ usage[:cost] = LlmGateway::Models::CostCalculator.calculate(model_definition, usage)
325
329
  usage
326
330
  end
327
331
 
@@ -6,7 +6,6 @@ module LlmGateway
6
6
  module ChatCompletions
7
7
  module OptionMapper
8
8
  DEFAULT_MAX_COMPLETION_TOKENS = 20_480
9
- VALID_REASONING_LEVELS = %w[low medium high xhigh].freeze
10
9
 
11
10
  # Source: https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create/index.md
12
11
  # API: OpenAI Chat Completions Create; accessed 2026-05-18.
@@ -58,7 +57,7 @@ module LlmGateway
58
57
  ].freeze
59
58
 
60
59
  MANAGED_OPTIONS = %i[
61
- reasoning
60
+ reasoning_control
62
61
  cache_key
63
62
  cache_retention
64
63
  ].freeze
@@ -85,9 +84,9 @@ module LlmGateway
85
84
  mapped_options.delete(:prompt_cache_retention)
86
85
  end
87
86
 
88
- reasoning = options[:reasoning]
89
- mapped_options[:reasoning_effort] = normalize_reasoning_effort(reasoning) \
90
- unless reasoning.nil? || reasoning.to_s == "none"
87
+ reasoning_control = options[:reasoning_control]
88
+ mapped_options[:reasoning_effort] = reasoning_effort(reasoning_control) \
89
+ unless reasoning_control.nil? || reasoning_control[:type] == :none
91
90
 
92
91
  validate_options!(mapped_options)
93
92
  mapped_options
@@ -116,11 +115,10 @@ module LlmGateway
116
115
  end
117
116
  end
118
117
 
119
- def normalize_reasoning_effort(reasoning)
120
- effort = reasoning.to_s
121
- return effort if VALID_REASONING_LEVELS.include?(effort)
118
+ def reasoning_effort(control)
119
+ return control.fetch(:value) if control[:type] == :effort
122
120
 
123
- raise ArgumentError, "Invalid reasoning '#{reasoning}'. Use 'none', 'low', 'medium', 'high', or 'xhigh'."
121
+ raise ArgumentError, "Unsupported OpenAI Chat Completions reasoning control: #{control.inspect}"
124
122
  end
125
123
  end
126
124
  end
@@ -9,7 +9,7 @@ module LlmGateway
9
9
  class StreamMapper < LlmGateway::Adapters::StreamMapper
10
10
  def map(chunk, &block)
11
11
  data = chunk[:data] || {}
12
- raise_stream_error!(data) if chunk[:event] == "error" || data[:error] || data[:type] == "error"
12
+ raise_stream_error!(data, overload_codes: [ "server_is_overloaded" ]) if chunk[:event] == "error" || data[:error] || data[:type] == "error"
13
13
 
14
14
  push_patches(patches_for(data), &block)
15
15
  end
@@ -12,8 +12,14 @@ module LlmGateway
12
12
  module Adapters
13
13
  module OpenAI
14
14
  class ChatCompletionsAdapter < Adapter
15
+ provider "openai"
16
+ client_class LlmGateway::Clients::OpenAI
17
+
15
18
  include ActsLikeOpenAIChatCompletions
16
19
  end
20
+
21
+ ChatCompletions.extend(DefinitionFacade)
22
+ ChatCompletions.define_adapter(ChatCompletionsAdapter)
17
23
  end
18
24
  end
19
25
  end
@@ -6,7 +6,6 @@ module LlmGateway
6
6
  module Responses
7
7
  module OptionMapper
8
8
  DEFAULT_MAX_OUTPUT_TOKENS = 20_480
9
- VALID_REASONING_LEVELS = %w[low medium high xhigh].freeze
10
9
 
11
10
  # Source: https://developers.openai.com/api/reference/resources/responses/methods/create/index.md
12
11
  # API: OpenAI Responses Create; accessed 2026-05-18.
@@ -49,6 +48,7 @@ module LlmGateway
49
48
  ].freeze
50
49
 
51
50
  MANAGED_OPTIONS = %i[
51
+ reasoning_control
52
52
  max_completion_tokens
53
53
  response_format
54
54
  cache_key
@@ -80,9 +80,9 @@ module LlmGateway
80
80
  response_format = options[:response_format]
81
81
  mapped_options[:text] = text_with_response_format(mapped_options[:text], response_format) unless response_format.nil?
82
82
 
83
- reasoning = mapped_options.delete(:reasoning)
84
- mapped_options[:reasoning] = normalize_reasoning(reasoning) \
85
- unless reasoning.nil? || reasoning.to_s == "none"
83
+ reasoning_control = options[:reasoning_control]
84
+ mapped_options[:reasoning] = normalize_reasoning(reasoning_control) \
85
+ unless reasoning_control.nil? || reasoning_control[:type] == :none
86
86
 
87
87
  validate_options!(mapped_options)
88
88
  mapped_options
@@ -111,16 +111,18 @@ module LlmGateway
111
111
  end
112
112
  end
113
113
 
114
- def normalize_reasoning(reasoning)
115
- effort = reasoning.to_s
116
- return { effort: effort, summary: "detailed" } if VALID_REASONING_LEVELS.include?(effort)
114
+ def normalize_reasoning(control)
115
+ return { effort: control.fetch(:value), summary: "detailed" } if control[:type] == :effort
117
116
 
118
- raise ArgumentError, "Invalid reasoning '#{reasoning}'. Use 'none', 'low', 'medium', 'high', or 'xhigh'."
117
+ raise ArgumentError, "Unsupported OpenAI Responses reasoning control: #{control.inspect}"
119
118
  end
120
119
 
121
120
  def text_with_response_format(text, response_format)
122
121
  text_options = text ? text.dup : {}
123
- text_options[:format] = response_format.is_a?(String) ? { type: response_format } : response_format
122
+ format = response_format.is_a?(String) ? { type: response_format } : response_format
123
+ definition = format[:json_schema] || format["json_schema"]
124
+ format = definition.merge(type: "json_schema") if definition
125
+ text_options[:format] = format
124
126
  text_options
125
127
  end
126
128
  end
@@ -12,7 +12,7 @@ module LlmGateway
12
12
  def map(chunk, &block)
13
13
  event_type = chunk[:event]
14
14
  data = chunk[:data] || {}
15
- raise_stream_error!(data) if event_type == "error" || data[:error] || data[:type] == "error"
15
+ raise_stream_error!(data, overload_codes: [ "server_is_overloaded" ]) if event_type == "error" || data[:error] || data[:type] == "error"
16
16
 
17
17
  push_patches(patches_for(event_type, data), &block)
18
18
  end
@@ -12,8 +12,14 @@ module LlmGateway
12
12
  module Adapters
13
13
  module OpenAI
14
14
  class ResponsesAdapter < Adapter
15
+ provider "openai"
16
+ client_class LlmGateway::Clients::OpenAI
17
+
15
18
  include ActsLikeOpenAIResponses
16
19
  end
20
+
21
+ Responses.extend(DefinitionFacade)
22
+ Responses.define_adapter(ResponsesAdapter)
17
23
  end
18
24
  end
19
25
  end
@@ -12,6 +12,9 @@ module LlmGateway
12
12
  module Adapters
13
13
  module OpenAICodex
14
14
  class ResponsesAdapter < Adapter
15
+ provider "openai"
16
+ client_class LlmGateway::Clients::OpenAI
17
+
15
18
  include ActsLikeOpenAIResponses
16
19
 
17
20
  private
@@ -28,6 +31,11 @@ module LlmGateway
28
31
  client.stream_codex(messages, tools: tools, system: system, **options, &block)
29
32
  end
30
33
  end
34
+
35
+ module Responses
36
+ extend DefinitionFacade
37
+ define_adapter ResponsesAdapter
38
+ end
31
39
  end
32
40
  end
33
41
  end
@@ -5,9 +5,10 @@ require_relative "normalized_stream_accumulator"
5
5
  module LlmGateway
6
6
  module Adapters
7
7
  class StreamMapper
8
- def initialize(provider:, api:)
8
+ def initialize(provider:, api:, model_definition: nil)
9
9
  @provider = provider
10
10
  @api = api
11
+ @model_definition = model_definition
11
12
  end
12
13
 
13
14
  def result
@@ -16,10 +17,10 @@ module LlmGateway
16
17
 
17
18
  private
18
19
 
19
- attr_reader :provider, :api
20
+ attr_reader :provider, :api, :model_definition
20
21
 
21
22
  def accumulator
22
- @accumulator ||= LlmGateway::Adapters::NormalizedStreamAccumulator.new(provider:, api:)
23
+ @accumulator ||= LlmGateway::Adapters::NormalizedStreamAccumulator.new(provider:, api:, model_definition:)
23
24
  end
24
25
 
25
26
  def push_patches(patches, &block)
@@ -30,15 +30,17 @@ module LlmGateway
30
30
  )
31
31
 
32
32
  class ToolCallResult < ::BaseStruct
33
- attribute :type, Types::Coercible::Symbol.enum(:tool_result)
33
+ attribute :type, Types::Coercible::Symbol.default(:tool_result).enum(:tool_result)
34
34
  attribute :tool_use_id, Types::String
35
35
  attribute :content, Types::Any
36
+ attribute :is_error, Types::Bool.default(false)
36
37
 
37
38
  def to_h
38
39
  {
39
40
  type: type.to_s,
40
41
  tool_use_id: tool_use_id,
41
- content: content
42
+ content: content,
43
+ is_error: is_error
42
44
  }
43
45
  end
44
46
 
@@ -47,6 +49,32 @@ module LlmGateway
47
49
  end
48
50
  end
49
51
 
52
+ class ToolResultMessage < ::BaseStruct
53
+ attribute :role, Types::String.default("user")
54
+ attribute :content, Types::Array.of(ToolCallResult)
55
+ attribute? :details, Types::Hash.optional
56
+
57
+ def empty?
58
+ content.empty?
59
+ end
60
+
61
+ def any?
62
+ content.any?
63
+ end
64
+
65
+ def tool_results
66
+ content
67
+ end
68
+
69
+ def to_h
70
+ {
71
+ role: role,
72
+ content: content.map(&:to_h),
73
+ details: details
74
+ }.compact
75
+ end
76
+ end
77
+
50
78
  class Base < ::BaseStruct
51
79
  attribute :type, AgentEventType
52
80
 
@@ -93,7 +121,7 @@ module LlmGateway
93
121
  class TurnEnd < Base
94
122
  attribute :type, Types::Coercible::Symbol.default(:turn_end).enum(:turn_end)
95
123
  attribute :message, Types.Instance(AssistantMessage)
96
- attribute :tool_results, Types::Array.of(Types.Instance(::ToolResult))
124
+ attribute :tool_results, Types::Array.of(ToolCallResult)
97
125
  end
98
126
 
99
127
  class AgentEnd < Base
@@ -8,16 +8,14 @@ module LlmGateway
8
8
  class Harness < LlmGateway::Prompt
9
9
  COMPACTION_TOKEN_THRESHOLD = 180_000
10
10
  COMPACTION_IDLE_THRESHOLD_SECONDS = 60 * 60
11
- attr_accessor :provider
12
- attr_reader :session_manager, :default_queue_mode, :queue_drain_mode,
13
- :model, :reasoning
14
11
 
15
- def initialize(session_manager, provider:, model: nil, reasoning: "high")
16
- @provider = provider
17
- super(provider: provider, model: model, reasoning: reasoning)
12
+ attr_reader :session_manager, :adapter, :default_queue_mode, :queue_drain_mode
13
+
14
+ def initialize(session_manager, adapter:, cache_key: nil, cache_retention: nil)
15
+ super(adapter:, cache_key:, cache_retention:)
18
16
  @session_manager = session_manager
19
- sync_initial_configuration_events
20
- self.default_queue_mode = :next_turn
17
+ validate_adapter_model!(adapter, model)
18
+ self.default_queue_mode = :follow_up
21
19
  self.queue_drain_mode = :all
22
20
  end
23
21
 
@@ -26,20 +24,24 @@ module LlmGateway
26
24
  end
27
25
  alias :prompt :transcript
28
26
 
27
+ def model
28
+ runtime_configuration.model
29
+ end
30
+
31
+ def reasoning
32
+ runtime_configuration.reasoning
33
+ end
34
+
29
35
  def prompt_message(message, &block)
30
- enqueue_or_run_message(message, default_queue_mode, &block)
36
+ enqueue_and_continue_if_idle(message, default_queue_mode, &block)
31
37
  end
32
38
 
33
39
  def steer_message(message, &block)
34
- enqueue_or_run_message(message, :steer, &block)
40
+ enqueue_and_continue_if_idle(message, :steer, &block)
35
41
  end
36
42
 
37
43
  def follow_up_message(message, &block)
38
- enqueue_or_run_message(message, :follow_up, &block)
39
- end
40
-
41
- def next_turn_message(message, &block)
42
- enqueue_or_run_message(message, :next_turn, &block)
44
+ enqueue_and_continue_if_idle(message, :follow_up, &block)
43
45
  end
44
46
 
45
47
  def default_queue_mode=(mode)
@@ -50,24 +52,51 @@ module LlmGateway
50
52
  @queue_drain_mode = session_manager.validate_drain_mode!(mode)
51
53
  end
52
54
 
53
- def model=(model_id)
54
- return @model if @model == model_id
55
+ def model=(definition)
56
+ return model if model.equal?(definition)
55
57
 
56
- @model = model_id
57
- publish_session_event(type: "model_change", model_id: model_id)
58
- @model
58
+ validate_adapter_model!(adapter, definition)
59
+ session_manager.change_model(definition)
59
60
  end
60
61
 
61
62
  def reasoning=(level)
62
- return @reasoning if @reasoning == level
63
+ return reasoning if reasoning == level
64
+
65
+ session_manager.change_reasoning(level)
66
+ end
67
+
68
+ def change_adapter(new_adapter, model: nil)
69
+ current_model = self.model
70
+ if model.nil? && new_adapter.provider != "proxy" && new_adapter.provider != current_model.provider
71
+ raise LlmGateway::Errors::ModelProviderMismatch,
72
+ "Changing providers requires a model definition for the new provider"
73
+ end
74
+
75
+ candidate_model = model || current_model
76
+ validate_adapter_model!(new_adapter, candidate_model)
77
+ session_manager.change_model(candidate_model) unless candidate_model.equal?(current_model)
78
+ @adapter = new_adapter
79
+ end
63
80
 
64
- @reasoning = level
65
- publish_session_event(type: "reasoning_change", reasoning: level)
66
- @reasoning
81
+ def adapter=(new_adapter)
82
+ change_adapter(new_adapter)
67
83
  end
68
84
 
69
85
  def compact
70
- session_manager.compaction(provider)
86
+ session_manager.compaction(adapter)
87
+ end
88
+
89
+ def stream(input = transcript, **options, &block)
90
+ stream_options = {
91
+ cache_key: cache_key,
92
+ cache_retention: cache_retention
93
+ }.compact.merge(options).merge(
94
+ model: model,
95
+ tools: tools,
96
+ system: system_prompt,
97
+ reasoning: reasoning
98
+ )
99
+ adapter.stream(input, **stream_options, &block)
71
100
  end
72
101
 
73
102
  def run(&block)
@@ -80,29 +109,25 @@ module LlmGateway
80
109
  emit(Event::MessageUpdate.new(stream_event: event), &block)
81
110
  end
82
111
 
83
- session_manager.push_message(assistant_message.to_h)
112
+ persisted_message = session_manager.push_message(assistant_message.to_h)
84
113
  emit(Event::MessageEnd.new(message: assistant_message), &block)
85
114
 
86
- tool_results = tool_requests(assistant_message).map do |message|
87
- parameters = message.to_h
88
- emit(Event::ToolExecutionStart.new(parameters: parameters), &block)
89
- tool_result = find_and_execute_tool(message)
90
- emit(Event::ToolExecutionEnd.new(parameters: parameters, result: tool_result), &block)
91
- tool_result
115
+ tool_request_blocks = tool_requests(assistant_message)
116
+ tool_result_message = execute_tool_requests(
117
+ requests: tool_request_blocks,
118
+ assistant_message: assistant_message,
119
+ session_event: persisted_message
120
+ ) do |requests_to_execute|
121
+ run_tool_requests(requests_to_execute, session_event: persisted_message, &block)
92
122
  end
123
+ tool_results = tool_result_message.tool_results
93
124
 
94
- tool_result_content = tool_results.map(&:to_h)
95
- session_manager.push_message(
96
- role: "user",
97
- content: tool_result_content,
98
- ) unless tool_result_content.empty?
125
+ session_manager.push_message(tool_result_message.to_h) if tool_result_message.any?
99
126
 
100
127
  turn_end_event = Event::TurnEnd.new(message: assistant_message, tool_results: tool_results)
101
128
  emit(turn_end_event, &block)
102
129
 
103
- if tool_results.length.positive?
104
- return run(&block)
105
- end
130
+ return run(&block) if tool_results.length.positive?
106
131
 
107
132
  if session_manager.queued_messages?(:follow_up)
108
133
  compact_if_needed
@@ -112,48 +137,48 @@ module LlmGateway
112
137
  emit(Event::AgentEnd.new(messages: []), &block)
113
138
  assistant_message
114
139
  end
115
- alias :continue :run
116
140
 
117
- private
118
-
119
- def publish_session_event(type:, **attributes)
120
- session_manager.push_entry(type: type, **attributes)
121
- end
122
-
123
- def sync_initial_configuration_events
124
- publish_session_event(type: "model_change", model_id: model) if model && !session_manager.last_model_used
125
- if reasoning && !session_manager.last_reasoning_level_used
126
- publish_session_event(type: "reasoning_change", reasoning: reasoning)
127
- end
128
- end
141
+ def continue(&block)
142
+ raise RuntimeError, "Cannot continue a busy agent" if session_manager.busy?
129
143
 
130
- def enqueue_or_run_message(message, queue, &block)
131
- if session_manager.idle?
144
+ session_manager.busy!
145
+ begin
132
146
  drain_queue(:steer)
133
- drain_queue(:next_turn)
134
147
  drain_queue(:follow_up)
148
+ run(&block)
149
+ ensure
150
+ session_manager.idle!
135
151
  end
136
- prepared_input = LlmGateway::Utils.deep_symbolize_keys(message)
137
- result = session_manager.start_or_enqueue_user_message(prepared_input, queue: queue) do
138
- compact_if_needed
139
- end
140
- return if result == session_manager.class::MESSAGE_QUEUED
152
+ end
141
153
 
142
- begin
154
+ private
143
155
 
156
+ def runtime_configuration
157
+ session_manager.current_configuration
158
+ end
144
159
 
145
- continue(&block)
160
+ def validate_adapter_model!(candidate_adapter, candidate_model)
161
+ unless candidate_adapter.respond_to?(:resolve_model!)
162
+ raise ArgumentError, "adapter must implement #resolve_model!"
163
+ end
164
+ unless candidate_model
165
+ raise LlmGateway::Errors::InvalidModelDefinition,
166
+ "The session must have a model before constructing a harness"
167
+ end
146
168
 
147
- loop do
148
- break unless session_manager.queued_messages?(:next_turn)
169
+ candidate_adapter.resolve_model!(candidate_model)
170
+ end
149
171
 
150
- compact_if_needed
151
- drain_queue(:next_turn)
152
- continue(&block)
153
- end
154
- ensure
155
- session_manager.idle!
172
+ def enqueue_and_continue_if_idle(message, queue, &block)
173
+ prepared_input = LlmGateway::Utils.deep_symbolize_keys(message)
174
+ if session_manager.busy?
175
+ session_manager.push_message_to_queue(prepared_input, queue)
176
+ return
156
177
  end
178
+
179
+ compact_if_needed
180
+ session_manager.push_message_to_queue(prepared_input, queue)
181
+ continue(&block)
157
182
  end
158
183
 
159
184
  def compact_if_needed
@@ -173,10 +198,18 @@ module LlmGateway
173
198
  session_manager.drain_message_queue(queue, mode: queue_drain_mode)
174
199
  end
175
200
 
176
- def emit(event, &block)
177
- return unless block
201
+ def run_tool_requests(requests, session_event:, &block)
202
+ requests.map do |tool_content_block|
203
+ parameters = tool_content_block.to_h
204
+ emit(Event::ToolExecutionStart.new(parameters: parameters), &block)
205
+ tool_result = find_and_execute_tool(tool_content_block, session_event: session_event)
206
+ emit(Event::ToolExecutionEnd.new(parameters: parameters, result: tool_result), &block)
207
+ tool_result
208
+ end
209
+ end
178
210
 
179
- block.call(event)
211
+ def emit(event, &block)
212
+ block&.call(event)
180
213
  end
181
214
  end
182
215
  end
@@ -8,9 +8,16 @@ module LlmGateway
8
8
  class InMemorySessionManager
9
9
  MESSAGE_QUEUED = :queued
10
10
  MESSAGE_STARTED = :started
11
- QUEUES = [ :steer, :follow_up, :next_turn ].freeze
11
+ QUEUES = [ :steer, :follow_up ].freeze
12
12
  DRAIN_MODES = [ :one_at_a_time, :all ].freeze
13
13
 
14
+ RuntimeConfiguration = Struct.new(:model, :reasoning, keyword_init: true) do
15
+ def initialize(model: nil, reasoning: nil)
16
+ super
17
+ freeze
18
+ end
19
+ end
20
+
14
21
  attr_reader :session_id, :session_start
15
22
 
16
23
  def initialize(session_id = nil)
@@ -27,17 +34,17 @@ module LlmGateway
27
34
  @state = :idle
28
35
  end
29
36
 
30
- def drain_message_queue(queue = :next_turn, mode: :all)
37
+ def drain_message_queue(queue = :follow_up, mode: :all)
31
38
  messages = queued_messages(queue, mode)
32
39
  messages.each { |message| push_message(message) }
33
40
  messages
34
41
  end
35
42
 
36
- def queued_messages?(queue = :next_turn)
43
+ def queued_messages?(queue = :follow_up)
37
44
  @message_queues[validate_queue!(queue)].any?
38
45
  end
39
46
 
40
- def push_message_to_queue(message, queue = :next_turn)
47
+ def push_message_to_queue(message, queue = :follow_up)
41
48
  @message_queues[validate_queue!(queue)] << message
42
49
  end
43
50
 
@@ -63,7 +70,7 @@ module LlmGateway
63
70
  mode
64
71
  end
65
72
 
66
- def start_or_enqueue_user_message(payload, queue: :next_turn)
73
+ def start_or_enqueue_user_message(payload, queue: :follow_up)
67
74
  if busy?
68
75
  push_message_to_queue(payload, queue)
69
76
  MESSAGE_QUEUED
@@ -106,12 +113,35 @@ module LlmGateway
106
113
  message_events.last&.dig(:id)
107
114
  end
108
115
 
109
- def last_model_used
110
- events.reverse.find { |event| event[:type] == "model_change" }&.dig(:model_id)
116
+ def change_model(model)
117
+ canonical = LlmGateway.models.fetch(provider: model.provider, id: model.id)
118
+ push_entry(type: "model_change", provider: canonical.provider, model_id: canonical.id)
119
+ canonical
120
+ end
121
+
122
+ def change_reasoning(reasoning)
123
+ push_entry(type: "reasoning_change", reasoning: reasoning)
124
+ reasoning
111
125
  end
112
126
 
113
- def last_reasoning_level_used
114
- events.reverse.find { |event| event[:type] == "reasoning_change" }&.dig(:reasoning)
127
+ def current_configuration
128
+ model_event = nil
129
+ reasoning = nil
130
+
131
+ events.reverse_each do |event|
132
+ model_event ||= event if event[:type] == "model_change"
133
+ reasoning ||= event[:reasoning] if event[:type] == "reasoning_change"
134
+ break if model_event && reasoning
135
+ end
136
+
137
+ model = if model_event
138
+ LlmGateway.models.fetch(
139
+ provider: model_event.fetch(:provider),
140
+ id: model_event.fetch(:model_id)
141
+ )
142
+ end
143
+
144
+ RuntimeConfiguration.new(model: model, reasoning: reasoning || "high")
115
145
  end
116
146
 
117
147
  def events_until(event_id)
@@ -144,6 +174,7 @@ module LlmGateway
144
174
  def compaction(adapter)
145
175
  response = adapter.stream(
146
176
  active_messages,
177
+ model: current_configuration.model,
147
178
  system: "Summarize the conversation so far for future context.",
148
179
  tools: []
149
180
  )