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
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c70b5fdd6e77e60cbe437a5698e078b7aa88fb41dca96311dcf9a58585238476
4
- data.tar.gz: cb9dd1f8aa71c33751ddd270acb849d964ed137b6b3fdd6c96e072082bc6e488
3
+ metadata.gz: 52b4361c9d53e7891a8ba2077f4420b76ad55ebf4b73e7841a34e6ae90df4acf
4
+ data.tar.gz: 05ae83106bc079aa5b2edbee2894ff7c60b23738e893c6ddb3624621e0c689d7
5
5
  SHA512:
6
- metadata.gz: d21ab094dd5f600731e12541c6ba0a672eb8d0862c732ce2f5f2a415c394024ff87565dee5820e2d1dcec5ee665715d7beacc5eb5fb5a35d518e98b4c3c6c6e1
7
- data.tar.gz: 97f4cabb1416beddc261fc849d23823722f9c36afb70843fcb1ef9e748e7f7eeec7f8bb4cfa0f92b25dbc864bf2c27e8751eeb9367f5c6233a906ac79d483219
6
+ metadata.gz: b0bca0efd7f81d29dce06c87105542adacac799a02a2c236dbebb245b6ebbd91e67d084fd40863894f7854e87e926b2750c906cff7752a16802569988628ffe4
7
+ data.tar.gz: a9e101dd03b19d241fd2f81a2534aaa6b6769eb41884298977f6779ed0a9e073ed39d39aedc2df6bde37ad0968c5176cf0ef8e87a518cf12660c7dfb18ef9a5b
data/CHANGELOG.md CHANGED
@@ -1,5 +1,41 @@
1
1
  # Changelog
2
2
 
3
+ ## [v0.10.0](https://github.com/Hyper-Unearthing/llm_gateway/tree/v0.10.0) (2026-11-26)
4
+
5
+ [Full Changelog](https://github.com/Hyper-Unearthing/llm_gateway/compare/v0.9.0...v0.10.0)
6
+
7
+ **Breaking changes:**
8
+
9
+ - Build adapters directly instead of using the removed provider registry and configuration APIs.
10
+ - Pass catalog model definitions to streaming calls; configure prompts, harnesses and proxies with adapters.
11
+ - See the [0.10.0 migration guide](docs/migration_guide_0.10.0.md) before upgrading from the published 0.9.0 release.
12
+
13
+ **Features:**
14
+
15
+ - Expose model capabilities, modalities and cost estimates, with runtime model registration and an updated models.dev catalog ([#100](https://github.com/Hyper-Unearthing/llm_gateway/pull/100), [#104](https://github.com/Hyper-Unearthing/llm_gateway/pull/104)).
16
+
17
+ **Fixes:**
18
+
19
+ - Classify streamed OpenAI `server_is_overloaded` responses as typed overload errors while preserving provider diagnostics ([#112](https://github.com/Hyper-Unearthing/llm_gateway/pull/112)).
20
+ - Preserve structured-output schemas for Anthropic and OpenAI Responses ([#106](https://github.com/Hyper-Unearthing/llm_gateway/pull/106)).
21
+ - Preserve Rails presence semantics ([#107](https://github.com/Hyper-Unearthing/llm_gateway/pull/107)).
22
+ - Truncate output tails without breaking UTF-8 ([#102](https://github.com/Hyper-Unearthing/llm_gateway/pull/102)).
23
+
24
+ **Verification and maintenance:**
25
+
26
+ - Remove model-catalog test ordering dependence and refresh recorded provider fixtures ([#103](https://github.com/Hyper-Unearthing/llm_gateway/pull/103), [#110](https://github.com/Hyper-Unearthing/llm_gateway/pull/110)).
27
+ - Follow supported Ruby 4.0 patch builds in CI and run CI on pushes to `main`.
28
+
29
+ ## [v0.9.0](https://github.com/Hyper-Unearthing/llm_gateway/tree/v0.9.0) (2026-07-13)
30
+
31
+ [Full Changelog](https://github.com/Hyper-Unearthing/llm_gateway/compare/v0.8.1...v0.9.0)
32
+
33
+ **Merged pull requests:**
34
+
35
+ - Improve tool result [\#99](https://github.com/Hyper-Unearthing/llm_gateway/pull/99) ([billybonks](https://github.com/billybonks))
36
+ - fix: harness queue draining [\#97](https://github.com/Hyper-Unearthing/llm_gateway/pull/97) ([billybonks](https://github.com/billybonks))
37
+ - feat: pass session event to tool call [\#95](https://github.com/Hyper-Unearthing/llm_gateway/pull/95) ([billybonks](https://github.com/billybonks))
38
+
3
39
  ## [v0.8.1](https://github.com/Hyper-Unearthing/llm_gateway/tree/v0.8.1) (2026-06-27)
4
40
 
5
41
  [Full Changelog](https://github.com/Hyper-Unearthing/llm_gateway/compare/v0.8.0...v0.8.1)
data/README.md CHANGED
@@ -11,6 +11,7 @@ Provide a unified translation interface for LLM Provider API's, While allowing d
11
11
  - [Managed cross-provider options](#managed-cross-provider-options)
12
12
  - [Provider-specific options](#provider-specific-options)
13
13
  - [Quick Start: Streaming (all events)](#quick-start-streaming-all-events)
14
+ - [Model catalog](#model-catalog)
14
15
  - [Stream API without handling events (final result only)](#stream-api-without-handling-events-final-result-only)
15
16
  - [Prompt classes](#prompt-classes)
16
17
  - [Migration guides](#migration-guides)
@@ -29,7 +30,9 @@ Provide a unified translation interface for LLM Provider API's, While allowing d
29
30
  - [Streaming Thinking Content](#streaming-thinking-content)
30
31
  - [How reasoning values are mapped](#how-reasoning-values-are-mapped)
31
32
  - [Cross-Provider Handoffs](#cross-provider-handoffs)
33
+ - [Proxy](#proxy)
32
34
  - [Context Serialization](#context-serialization)
35
+ - [Message metadata](#message-metadata)
33
36
  - [OAuth](#oauth)
34
37
  - [Get initial tokens (Codex / OpenAI OAuth)](#get-initial-tokens-codex--openai-oauth)
35
38
  - [Get initial tokens (Anthropic OAuth)](#get-initial-tokens-anthropic-oauth)
@@ -61,13 +64,13 @@ gem "llm_gateway"
61
64
 
62
65
  | Provider | Provider Key | Auth | API Surface |
63
66
  |-----------|------------------------------|-------|------------------------|
64
- | Anthropic | `anthropic_messages` | API key | Messages |
65
- | OpenAI | `openai_completions` | API key | Chat Completions |
66
- | OpenAI | `openai_responses` | API key | Responses |
67
- | OpenAI Codex | `openai_codex` | OAuth | Responses |
68
- | Groq | `groq_completions` | API key | Chat Completions |
67
+ | Anthropic | `anthropic-messages` | API key | Messages |
68
+ | OpenAI | `openai-completions` | API key | Chat Completions |
69
+ | OpenAI | `openai-responses` | API key | Responses |
70
+ | OpenAI Codex | `openai-codex` | OAuth | Responses |
71
+ | Groq | `groq-completions` | API key | Chat Completions |
69
72
 
70
- Provider configuration only contains auth/client settings (for example `api_key` or `access_token`). Pass the model per request with `model:` when calling `chat` or `stream`.
73
+ Adapter configuration only contains auth/client settings (for example `api_key` or `access_token`). Pass a catalog model definition per `stream` request with `model:`.
71
74
 
72
75
  ## Stream Options
73
76
 
@@ -105,25 +108,45 @@ Unknown provider-specific options raise `ArgumentError` with the valid option li
105
108
 
106
109
  Provider-specific options are maintained as explicit allowlists in the option mapper source. Use the mapper link to see the current allowed Ruby option keys and the provider documentation link for upstream meanings and values.
107
110
 
108
- | Provider key | Provider/API pair | Option mapper source | Provider API documentation |
111
+ | Adapter ID | Provider/API pair | Option mapper source | Provider API documentation |
109
112
  |--------------|-------------------|----------------------|----------------------------|
110
- | `anthropic_messages` | Anthropic Messages Create | [`lib/llm_gateway/adapters/anthropic_option_mapper.rb`](lib/llm_gateway/adapters/anthropic_option_mapper.rb) | [Anthropic Messages API](https://platform.claude.com/docs/en/api/messages/create.md) |
111
- | `openai_completions` | OpenAI Chat Completions Create | [`lib/llm_gateway/adapters/openai/chat_completions/option_mapper.rb`](lib/llm_gateway/adapters/openai/chat_completions/option_mapper.rb) | [OpenAI Chat Completions API](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create/index.md) |
112
- | `openai_responses` | OpenAI Responses Create | [`lib/llm_gateway/adapters/openai/responses/option_mapper.rb`](lib/llm_gateway/adapters/openai/responses/option_mapper.rb) | [OpenAI Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create/index.md) |
113
- | `openai_codex` | OpenAI Codex Responses-compatible endpoint | [`lib/llm_gateway/adapters/openai_codex/option_mapper.rb`](lib/llm_gateway/adapters/openai_codex/option_mapper.rb) | [OpenAI Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create/index.md) |
114
- | `groq_completions` | Groq Chat Completions Create | [`lib/llm_gateway/adapters/groq/option_mapper.rb`](lib/llm_gateway/adapters/groq/option_mapper.rb) | [Groq Chat API](https://console.groq.com/docs/api-reference.md#chat-create) |
113
+ | `anthropic-messages` | Anthropic Messages Create | [`lib/llm_gateway/adapters/anthropic_option_mapper.rb`](lib/llm_gateway/adapters/anthropic_option_mapper.rb) | [Anthropic Messages API](https://platform.claude.com/docs/en/api/messages/create.md) |
114
+ | `openai-completions` | OpenAI Chat Completions Create | [`lib/llm_gateway/adapters/openai/chat_completions/option_mapper.rb`](lib/llm_gateway/adapters/openai/chat_completions/option_mapper.rb) | [OpenAI Chat Completions API](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create/index.md) |
115
+ | `openai-responses` | OpenAI Responses Create | [`lib/llm_gateway/adapters/openai/responses/option_mapper.rb`](lib/llm_gateway/adapters/openai/responses/option_mapper.rb) | [OpenAI Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create/index.md) |
116
+ | `openai-codex` | OpenAI Codex Responses-compatible endpoint | [`lib/llm_gateway/adapters/openai_codex/option_mapper.rb`](lib/llm_gateway/adapters/openai_codex/option_mapper.rb) | [OpenAI Responses API](https://developers.openai.com/api/reference/resources/responses/methods/create/index.md) |
117
+ | `groq-completions` | Groq Chat Completions Create | [`lib/llm_gateway/adapters/groq/option_mapper.rb`](lib/llm_gateway/adapters/groq/option_mapper.rb) | [Groq Chat API](https://console.groq.com/docs/api-reference.md#chat-create) |
115
118
 
116
119
  Common provider-native options you may pass directly when allowed include OpenAI `prompt_cache_key` / `prompt_cache_retention` and Groq `reasoning_effort` / `reasoning_format`. Prefer the managed options above when you want portable behavior across providers.
117
120
 
121
+ ### Building adapters
122
+
123
+ Prefer public adapter definitions so application code does not depend on string IDs or know which client class an adapter needs:
124
+
125
+ ```ruby
126
+ LlmGateway::Adapters::OpenAI::Responses.build(api_key: ENV.fetch("OPENAI_API_KEY"))
127
+ LlmGateway::Adapters::OpenAI::ChatCompletions.build(api_key: ENV.fetch("OPENAI_API_KEY"))
128
+ LlmGateway::Adapters::Anthropic::Messages.build(api_key: ENV.fetch("ANTHROPIC_API_KEY"))
129
+ LlmGateway::Adapters::Groq::ChatCompletions.build(api_key: ENV.fetch("GROQ_API_KEY"))
130
+ LlmGateway::Adapters::OpenAICodex::Responses.build(api_key: oauth_token)
131
+ ```
132
+
133
+ Adapter implementation classes provide the lower-level typed API when needed:
134
+
135
+ ```ruby
136
+ adapter_class = LlmGateway::Adapters::OpenAI::ResponsesAdapter
137
+ adapter_class.build(api_key: ENV.fetch("OPENAI_API_KEY"))
138
+ ```
139
+
140
+ Runtime adapter identity is the implementation class itself. Stable string names exist only in the proxy wire protocol, where `LlmGateway::Proxy::Protocol` maps them to allowlisted adapter classes.
141
+
118
142
  ## Quick Start: Streaming (all events)
119
143
 
120
144
  ```ruby
121
145
  require "llm_gateway"
122
146
  require "json"
123
147
 
124
- # Build a provider adapter directly (not via prebuilt config)
125
- adapter = LlmGateway.build_provider(
126
- provider: "openai_responses", # or anthropic_messages, groq_completions, ...
148
+ # Select the API by its public definition and supply only transport/auth config.
149
+ adapter = LlmGateway::Adapters::OpenAI::Responses.build(
127
150
  api_key: ENV.fetch("OPENAI_API_KEY")
128
151
  )
129
152
  tools = [
@@ -145,7 +168,7 @@ transcript = [
145
168
 
146
169
  streamed_tool_args = Hash.new { |h, k| h[k] = +"" }
147
170
 
148
- response = adapter.stream(transcript, tools: tools, model: "gpt-5.4", reasoning: "high") do |event|
171
+ response = adapter.stream(transcript, tools: tools, model: LlmGateway.models.fetch("openai/gpt-5.4"), reasoning: "high") do |event|
149
172
  case event.type
150
173
  # AssistantStreamMessageEvent
151
174
  when :message_start
@@ -231,7 +254,51 @@ End events include helpers for the finalized current content block:
231
254
  - `event.reasoning` for `:reasoning_end`
232
255
  - `event.tool_call` / `event.tool` for `:tool_end`
233
256
 
234
- Usage counters are normalized as `:input`, `:cache_write`, `:cache_read`, `:output`, and `:total`. `:total` is the sum of all input-side buckets plus output. `usage[:raw]` contains the original provider usage/token payload.
257
+ Usage counters are normalized as `:input`, `:cache_write`, `:cache_read`, `:output`, and `:total`. `:total` is the sum of all input-side buckets plus output. `usage[:raw]` contains the original provider usage/token payload. `usage[:cost]` is a USD breakdown (`:input`, `:cache_write`, `:cache_read`, `:output`, `:total`) when the requested model is priced in the built-in catalog; it is `nil` for unknown or unpriced models.
258
+
259
+ ### Model catalog
260
+
261
+ Adapters require a provider-level model definition. Fetch by qualified reference or with keywords (recommended when an ID contains `/`):
262
+
263
+ ```ruby
264
+ model = LlmGateway.models.fetch("openai/gpt-5.5")
265
+ groq_model = LlmGateway.models.fetch(provider: "groq", id: "openai/gpt-oss-120b")
266
+
267
+ model.supports?(:text_generation) # true, false, or nil when unknown
268
+ model.supports?(:tool_calling)
269
+ model.supports_reasoning? # true, false, or nil when unknown
270
+ model.reasoning_options # canonical UI symbols, e.g. [:default, :low, :medium, :high, :max]
271
+ model.reasoning_control_for(:high) # internal effort, budget, or toggle control
272
+ model.supports_input?(:image)
273
+ model.supports_output?(:text)
274
+
275
+ LlmGateway::Adapters::OpenAI::ResponsesAdapter.supports_model?(model)
276
+ LlmGateway::Adapters::OpenAI::ResponsesAdapter.provider_model_key(model)
277
+ ```
278
+
279
+ The built-in catalog includes all models returned by models.dev. `reasoning_options` is a canonical, UI-safe projection of the model's controls; `reasoning_controls` retains raw catalog/provider control metadata for adapter mapping. Capabilities are metadata rather than local request validation; unsupported model/API, tool, modality, and reasoning combinations are currently left for the provider API to reject.
280
+
281
+ Applications can register models released between catalog regenerations or models from custom providers. Duplicate provider/model IDs are rejected unless replacement is explicit:
282
+
283
+ ```ruby
284
+ LlmGateway.models.register(
285
+ provider: "custom-provider",
286
+ id: "new-model",
287
+ input_modalities: [:text],
288
+ output_modalities: [:text],
289
+ capabilities: {
290
+ text_generation: true,
291
+ tool_calling: nil,
292
+ structured_output: false,
293
+ reasoning: false
294
+ },
295
+ pricing: { input: "1.25", output: "5.00" }
296
+ )
297
+
298
+ LlmGateway.models.register(updated_definition, replace: true)
299
+ ```
300
+
301
+ A definition is unique by provider/model ID and can be shared by multiple adapters. Adapter classes own model support and provider model-key behavior; the default supports catalog models from the adapter's provider and sends the catalog model ID unchanged. Adapter/API aliases such as `openai-responses/gpt-5.5` are not model references. Run `rake models:generate` to refresh the bundled catalog.
235
302
 
236
303
  ### Stream API without handling events (final result only)
237
304
 
@@ -240,12 +307,11 @@ If you only care about the final `AssistantMessage`, call `stream` without a blo
240
307
  ```ruby
241
308
  require "llm_gateway"
242
309
 
243
- adapter = LlmGateway.build_provider(
244
- provider: "openai_responses",
310
+ adapter = LlmGateway::Adapters::OpenAI::Responses.build(
245
311
  api_key: ENV.fetch("OPENAI_API_KEY")
246
312
  )
247
313
 
248
- result = adapter.stream("Write one short sentence about Ruby.", model: "gpt-5.4")
314
+ result = adapter.stream("Write one short sentence about Ruby.", model: LlmGateway.models.fetch("openai/gpt-5.4"))
249
315
 
250
316
  puts result.role # "assistant"
251
317
  puts result.timestamp # Unix milliseconds
@@ -262,7 +328,7 @@ puts text
262
328
 
263
329
  ## Prompt classes
264
330
 
265
- `LlmGateway::Prompt` wraps a reusable prompt, provider/model defaults, callbacks, optional tools, and prompt-cache options around the `stream` API.
331
+ `LlmGateway::Prompt` wraps a reusable prompt, adapter/model defaults, callbacks, optional tools, and prompt-cache options around the `stream` API.
266
332
 
267
333
  ```ruby
268
334
  class AddTool < LlmGateway::Tool
@@ -271,17 +337,16 @@ class AddTool < LlmGateway::Tool
271
337
  input_schema(type: "object")
272
338
  cache true # optional: mark the tool definition as cacheable where supported
273
339
 
274
- def execute(input)
275
- input[:left] + input[:right]
340
+ def execute(input, tool_use_id:)
341
+ tool_result(input[:left] + input[:right], tool_use_id: tool_use_id)
276
342
  end
277
343
  end
278
344
 
279
345
  class MathPrompt < LlmGateway::Prompt
280
- self.provider = LlmGateway.build_provider(
281
- provider: "openai_responses",
346
+ self.adapter = LlmGateway::Adapters::OpenAI::Responses.build(
282
347
  api_key: ENV.fetch("OPENAI_API_KEY")
283
348
  )
284
- self.model = "gpt-5.4"
349
+ self.model = LlmGateway.models.fetch("openai/gpt-5.4")
285
350
 
286
351
  TOOLS = [AddTool].freeze
287
352
 
@@ -306,9 +371,11 @@ puts response.content.select { |block| block.type == "text" }.map(&:text).join
306
371
  How `Prompt` works now:
307
372
 
308
373
  - `prompt` is evaluated once per `run`.
309
- - `run(provider:, model:, reasoning:, **options)` calls `stream` and returns the final normalized `AssistantMessage` after any tool calls complete.
310
- - `stream(input = prompt, provider:, model:, reasoning:, **options, &block)` forwards to the provider and returns the normalized `AssistantMessage`.
374
+ - `run(adapter:, model:, reasoning:, **options)` calls `stream` and returns the final normalized `AssistantMessage` after any tool calls complete.
375
+ - `stream(input = prompt, adapter:, model:, reasoning:, **options, &block)` forwards to the adapter and returns the normalized `AssistantMessage`.
311
376
  - Tools are declared as tool classes in a `TOOLS` constant. `run` automatically executes returned `tool_use` blocks, appends `tool_result` messages, and loops until no tool calls remain.
377
+ - `LlmGateway::Tool#execute(input, tool_use_id:)` should return a `LlmGateway::Agents::Event::ToolCallResult` or a descendant; use the inherited `tool_result(content, tool_use_id: tool_use_id)` helper for the common case. The original tool call id is passed into `execute` so custom tools can construct their own result object and decide what is serialized into sessions.
378
+ - Override the protected `execute_tool_requests(requests:, assistant_message:, session_event:)` hook to wrap tool execution with setup/teardown, result post-processing, or wrapper-message customization; call `yield requests` to let the harness/prompt execute tools normally, then return a `LlmGateway::Agents::Event::ToolResultMessage`. A `Harness` receives the persisted assistant event as `session_event:`; a `Prompt` receives `nil`. The default serializes as `{ role: "user", content: tool_results.map(&:to_h) }`.
312
379
  - `system_prompt`, `tools`, `model`, `reasoning`, `cache_key`, and `cache_retention` are forwarded as stream options.
313
380
  - `cache_retention` can also enable provider cache control for prompt-owned system/tool blocks where supported, and `Tool.cache true` marks a tool definition with `cache_control`.
314
381
  - `before_execute` callbacks receive the resolved input. `after_execute` callbacks receive the final `AssistantMessage`.
@@ -316,6 +383,8 @@ How `Prompt` works now:
316
383
 
317
384
  ## Migration guides
318
385
 
386
+ - [0.10.0 migration guide](docs/migration_guide_0.10.0.md) — build adapters directly, pass catalog model definitions, and update `Prompt`, `Harness`, and proxy setup.
387
+ - [0.9.0 migration guide](docs/migration_guide_0.9.0.md) — update custom tools to return `ToolCallResult`, migrate harness queue behavior, and update tool-result event consumers.
319
388
  - [0.7.0 migration guide](docs/migration_guide_0.7.0.md) — update `Prompt` subclasses for normalized `AssistantMessage` return values, automatic tool loops, `TOOLS`, and removed response hooks.
320
389
  - [0.6.0 migration guide](docs/migration_guide_0.6.0.md) — move `model_key` to per-request `model:`, update provider keys, update `Prompt` usage, and migrate stream event/usage changes.
321
390
  - [Migrating from `chat` to `stream`](docs/migration-guide.md) — use `stream` without a block when you only need the final response.
@@ -351,8 +420,7 @@ Use `stream` without a block, inspect returned `tool_use` blocks, execute tools,
351
420
  require "llm_gateway"
352
421
  require "json"
353
422
 
354
- adapter = LlmGateway.build_provider(
355
- provider: "openai_responses",
423
+ adapter = LlmGateway::Adapters::OpenAI::Responses.build(
356
424
  api_key: ENV.fetch("OPENAI_API_KEY")
357
425
  )
358
426
  weather_tool = {
@@ -383,7 +451,7 @@ transcript = [
383
451
  ]
384
452
 
385
453
  # 1) First model pass (stream API, no event block)
386
- response = adapter.stream(transcript, tools: [weather_tool], model: "gpt-5.4")
454
+ response = adapter.stream(transcript, tools: [weather_tool], model: LlmGateway.models.fetch("openai/gpt-5.4"))
387
455
  transcript << response.to_h
388
456
 
389
457
  # 2) Execute tool calls returned by the model
@@ -406,7 +474,7 @@ end
406
474
 
407
475
  # 3) Continue the conversation after tool execution
408
476
  if response.content.any? { |b| b.type == "tool_use" }
409
- final_response = adapter.stream(transcript, tools: [weather_tool], model: "gpt-5.4")
477
+ final_response = adapter.stream(transcript, tools: [weather_tool], model: LlmGateway.models.fetch("openai/gpt-5.4"))
410
478
 
411
479
  final_text = final_response.content
412
480
  .select { |b| b.type == "text" }
@@ -420,6 +488,8 @@ end
420
488
  Notes:
421
489
  - Tool calls are returned as `ToolCall` blocks with `type: "tool_use"`, `id`, `name`, and `input`.
422
490
  - Tool results are sent back in the transcript as `{ type: "tool_result", tool_use_id:, content: }` blocks.
491
+ - When using `LlmGateway::Tool`, the tool call id is passed to `execute` as `tool_use_id:`. Return `ToolCallResult` directly, or return a descendant if you need custom fields/serialization behavior for session persistence.
492
+ - `Prompt`/`Harness` subclasses can override `execute_tool_requests(requests:, assistant_message:, session_event:)` to wrap tool execution, then call `yield requests` for the default execution path and return a `ToolResultMessage` that wraps those tool result blocks.
423
493
  - For multimodal-capable models, `tool_result` content can include image blocks when supported by the provider/model.
424
494
 
425
495
  ### Server Tool Use
@@ -437,8 +507,15 @@ anthropic_code_execution = {
437
507
  name: "code_execution"
438
508
  }
439
509
 
440
- tools = provider == "openai_responses" ? [openai_code_interpreter] : [anthropic_code_execution]
441
- response = adapter.stream("Create a chart from this CSV and save it as PNG.", tools: tools) do |event|
510
+ adapter = LlmGateway::Adapters::OpenAI::Responses.build(
511
+ api_key: ENV.fetch("OPENAI_API_KEY")
512
+ )
513
+ model = LlmGateway.models.fetch("openai/gpt-5.4")
514
+ tools = [openai_code_interpreter]
515
+
516
+ # For Anthropic, build Adapters::Anthropic::Messages, fetch an Anthropic model,
517
+ # and use [anthropic_code_execution] instead.
518
+ response = adapter.stream("Create a chart from this CSV and save it as PNG.", model: model, tools: tools) do |event|
442
519
  case event.type
443
520
  when :tool_start
444
521
  puts "server tool: #{event.name}" if event.tool_type == "server_tool_use"
@@ -485,13 +562,16 @@ class WeatherTool < LlmGateway::Tool
485
562
  required: ["location"]
486
563
  )
487
564
 
488
- def execute(input)
565
+ def execute(input, tool_use_id:)
489
566
  location = input[:location] || input["location"]
490
567
 
491
- JSON.generate(
492
- location: location,
493
- temperature: 14,
494
- condition: "Cloudy"
568
+ tool_result(
569
+ JSON.generate(
570
+ location: location,
571
+ temperature: 14,
572
+ condition: "Cloudy"
573
+ ),
574
+ tool_use_id: tool_use_id
495
575
  )
496
576
  end
497
577
  end
@@ -504,18 +584,14 @@ class WeatherHarness < LlmGateway::Agents::Harness
504
584
  end
505
585
  end
506
586
 
507
- adapter = LlmGateway.build_provider(
508
- provider: "openai_responses",
587
+ adapter = LlmGateway::Adapters::OpenAI::Responses.build(
509
588
  api_key: ENV.fetch("OPENAI_API_KEY")
510
589
  )
511
590
 
512
591
  session = LlmGateway::Agents::InMemorySessionManager.new("weather-session")
513
- harness = WeatherHarness.new(
514
- session,
515
- provider: adapter,
516
- model: "gpt-5.4",
517
- reasoning: "high"
518
- )
592
+ session.change_model(LlmGateway.models.fetch("openai/gpt-5.4"))
593
+ session.change_reasoning("high")
594
+ harness = WeatherHarness.new(session, adapter: adapter)
519
595
 
520
596
  harness.prompt_message(
521
597
  role: "user",
@@ -545,10 +621,12 @@ puts harness.transcript.inspect
545
621
  Harness behavior:
546
622
 
547
623
  - `prompt_message(message)` accepts an LLM-shaped message hash, records it in the session, streams the provider response, records the final assistant message, executes any returned tool calls from the harness class's `TOOLS` constant, records a user `tool_result` message, and continues until no tool calls remain.
548
- - Harnesses pass `tools`, `system_prompt`, `model`, `reasoning`, `cache_key`, and `cache_retention` through the inherited `Prompt#stream` defaults.
549
- - Pass `model:` and optional `reasoning:` to `new`, or set them later with `harness.model = "..."` / `harness.reasoning = "..."`. Model and reasoning changes are recorded as session events.
624
+ - Harnesses receive an already-built adapter and never construct one or read global client configuration.
625
+ - Pass optional `cache_key:` and `cache_retention:` values to the Harness constructor; they are forwarded on every model request and can be changed through the inherited accessors.
626
+ - Initialize the session with `session.change_model(definition)` and optional `session.change_reasoning(level)`. Set them later with `harness.model = definition` / `harness.reasoning = level`; changes are recorded as session events.
627
+ - Use `harness.change_adapter(adapter)` for another compatible adapter. Changing providers requires `harness.change_adapter(adapter, model: definition)`.
550
628
  - `harness.transcript` (also aliased as `prompt`) returns the current model input: the latest compaction summary, if any, followed by active messages.
551
- - `harness.run` / `harness.continue` continues from the current session state without adding a new user message.
629
+ - `harness.run` continues from the current session state without adding a new user message. `harness.continue` requires an idle agent; it marks the agent busy, drains queued `:steer` messages and then queued `:follow_up` messages, runs, and marks the agent idle when finished. `prompt_message`/`steer_message`/`follow_up_message` enqueue the new user message; if the agent is idle, they then call `continue`, so existing queued messages in that queue stay ahead of the new message.
552
630
 
553
631
  ### Agent events
554
632
 
@@ -560,8 +638,8 @@ When a block is passed to `prompt_message`, `run`, or `continue`, the harness em
560
638
  - `:message_update` with `event.stream_event` containing the normalized streaming event from the provider
561
639
  - `:message_end` with `event.message`
562
640
  - `:tool_execution_start` with `event.parameters` (`id`, `type`, `name`, `input`)
563
- - `:tool_execution_end` with `event.parameters` and `event.result`
564
- - `:turn_end` with `event.message` and `event.tool_results`
641
+ - `:tool_execution_end` with `event.parameters` and `event.result` (`LlmGateway::Agents::Event::ToolCallResult`, or a descendant returned by the tool)
642
+ - `:turn_end` with `event.message` and `event.tool_results` (`LlmGateway::Agents::Event::ToolCallResult` objects, or descendants returned by tools)
565
643
  - `:agent_end`
566
644
 
567
645
  ### Session managers and persistence
@@ -575,22 +653,21 @@ When a block is passed to `prompt_message`, `run`, or `continue`, the harness em
575
653
 
576
654
  Calls made while a harness is already processing are queued instead of recursively starting another run.
577
655
 
578
- - `prompt_message(message)` queues to the harness's default queue while busy. The default is `:next_turn`.
579
- - `steer_message(message)`, `follow_up_message(message)`, and `next_turn_message(message)` enqueue to their matching queue while busy. When idle, they behave like `prompt_message`.
656
+ - `prompt_message(message)` queues to the harness's default queue while busy. The default is `:follow_up`.
657
+ - `steer_message(message)` and `follow_up_message(message)` enqueue to their matching queue. When idle, they also start `continue` after enqueueing.
580
658
  - `:steer` messages are drained before the next model request in the current run.
581
- - `:follow_up` messages run after the current turn finishes and before `:next_turn` messages.
582
- - `:next_turn` messages run after the current agent run completes.
659
+ - `:follow_up` messages run after the current turn finishes and after any tool-call loop has completed.
583
660
  - Queued messages drain as `:all` by default. Set `harness.queue_drain_mode = :one_at_a_time` to drain one FIFO message at a time.
584
- - Set `harness.default_queue_mode = :steer`, `:follow_up`, or `:next_turn` to change where busy `prompt_message` calls are queued.
661
+ - Set `harness.default_queue_mode = :steer` or `:follow_up` to change where busy `prompt_message` calls are queued.
585
662
 
586
663
  ### Compaction
587
664
 
588
- Before starting a new user message and before draining queued follow-up/next-turn work, the harness checks whether compaction is needed. It compacts when either:
665
+ Before starting a new user message and before draining queued follow-up work, the harness checks whether compaction is needed. It compacts when either:
589
666
 
590
667
  - the latest recorded message usage exceeds `LlmGateway::Agents::Harness::COMPACTION_TOKEN_THRESHOLD`, or
591
668
  - the latest assistant message is older than `LlmGateway::Agents::Harness::COMPACTION_IDLE_THRESHOLD_SECONDS`.
592
669
 
593
- Compaction calls `adapter.stream(active_messages, system: "Summarize the conversation so far for future context.", tools: [])`, stores the returned assistant message as a `compaction` event, and builds future model input as the compaction summary plus messages recorded after that compaction.
670
+ Compaction calls the harness adapter with the session's current model definition, stores the returned assistant message as a `compaction` event, and builds future model input as the compaction summary plus messages recorded after that compaction.
594
671
 
595
672
  ### Built-in agent tools
596
673
 
@@ -620,8 +697,7 @@ Send images by including an `image` content block in a user message.
620
697
  require "llm_gateway"
621
698
  require "base64"
622
699
 
623
- adapter = LlmGateway.build_provider(
624
- provider: "openai_responses",
700
+ adapter = LlmGateway::Adapters::OpenAI::Responses.build(
625
701
  api_key: ENV.fetch("OPENAI_API_KEY")
626
702
  )
627
703
  image_b64 = Base64.strict_encode64(File.binread("./chart.png"))
@@ -636,7 +712,7 @@ message = [
636
712
  }
637
713
  ]
638
714
 
639
- result = adapter.stream(message, model: "gpt-5.4") # stream API, no event block
715
+ result = adapter.stream(message, model: LlmGateway.models.fetch("openai/gpt-5.4")) # stream API, no event block
640
716
 
641
717
  text = result.content
642
718
  .select { |b| b.type == "text" }
@@ -655,19 +731,18 @@ You can request higher-effort reasoning by passing `reasoning:` to `stream`.
655
731
  ```ruby
656
732
  require "llm_gateway"
657
733
 
658
- adapter = LlmGateway.build_provider(
659
- provider: "openai_responses",
734
+ adapter = LlmGateway::Adapters::OpenAI::Responses.build(
660
735
  api_key: ENV.fetch("OPENAI_API_KEY")
661
736
  )
662
737
 
663
738
  result = adapter.stream(
664
739
  "Think step by step and then compute 482 * 17.",
665
- model: "gpt-5.4",
740
+ model: LlmGateway.models.fetch("openai/gpt-5.4"),
666
741
  reasoning: "high"
667
742
  )
668
743
 
669
744
  puts "stop_reason: #{result.stop_reason}"
670
- puts "usage: #{result.usage.inspect}" # normalized keys: :input, :cache_write, :cache_read, :output, :total, :raw
745
+ puts "usage: #{result.usage.inspect}" # normalized keys: :input, :cache_write, :cache_read, :output, :total, :raw, :cost
671
746
 
672
747
  result.content.each do |block|
673
748
  case block.type
@@ -687,7 +762,7 @@ If you want incremental thinking/reasoning tokens as they arrive, pass a block t
687
762
  ```ruby
688
763
  reasoning_text = +""
689
764
 
690
- result = adapter.stream("Solve 99 * 99 with brief reasoning.", model: "gpt-5.4", reasoning: "high") do |event|
765
+ result = adapter.stream("Solve 99 * 99 with brief reasoning.", model: LlmGateway.models.fetch("openai/gpt-5.4"), reasoning: "high") do |event|
691
766
  case event.type
692
767
  when :reasoning_start
693
768
  print "\n[thinking start]\n"
@@ -730,7 +805,7 @@ Notes:
730
805
 
731
806
  Internally, `llm_gateway` handles handoffs by normalizing message history into a provider-agnostic shape, then remapping that shape to the target provider API on each request.
732
807
 
733
- What happens under the hood on `stream`/`chat`:
808
+ What happens under the hood on `stream`:
734
809
 
735
810
  1. **Normalize input**
736
811
  - String input is converted to a user message.
@@ -756,6 +831,26 @@ Why this matters:
756
831
  - Tool calls/reasoning/text are exposed through a consistent API even when upstream event formats differ.
757
832
  - Your app can keep one conversation state format while switching providers for cost, latency, capability, or reliability reasons.
758
833
 
834
+ ## Proxy
835
+
836
+ Use `LlmGateway::Proxy` to stream through a remote `LlmGateway::Proxy::Server`. Select the target with an adapter definition (not a provider string), and pass the target adapter's credentials in `target_config`:
837
+
838
+ ```ruby
839
+ proxy = LlmGateway::Proxy.build(
840
+ url: "https://gateway.example.com",
841
+ api_key: ENV["PROXY_API_KEY"], # optional proxy authorization
842
+ adapter: LlmGateway::Adapters::OpenAI::Responses,
843
+ target_config: { api_key: ENV.fetch("OPENAI_API_KEY") }
844
+ )
845
+
846
+ response = proxy.stream(
847
+ "Hello",
848
+ model: LlmGateway.models.fetch("openai/gpt-5.4")
849
+ )
850
+ ```
851
+
852
+ The proxy wire protocol allowlists the built-in adapter definitions. A proxy request must include a catalog model; its provider must be supported by the selected target adapter.
853
+
759
854
  ## Context Serialization
760
855
 
761
856
  `llm_gateway` contexts are plain Ruby hashes/arrays, so they can be serialized to JSON and restored later.
@@ -764,8 +859,7 @@ Why this matters:
764
859
  require "llm_gateway"
765
860
  require "json"
766
861
 
767
- adapter = LlmGateway.build_provider(
768
- provider: "openai_responses",
862
+ adapter = LlmGateway::Adapters::OpenAI::Responses.build(
769
863
  api_key: ENV.fetch("OPENAI_API_KEY")
770
864
  )
771
865
  # Build context (transcript)
@@ -774,7 +868,7 @@ transcript = [
774
868
  ]
775
869
 
776
870
  # Run one turn and persist assistant output
777
- first = adapter.stream(transcript, model: "gpt-5.4")
871
+ first = adapter.stream(transcript, model: LlmGateway.models.fetch("openai/gpt-5.4"))
778
872
  transcript << first.to_h
779
873
 
780
874
  # Serialize (store in DB/file/cache)
@@ -785,7 +879,7 @@ restored_transcript = JSON.parse(json_context)
785
879
 
786
880
  # Continue conversation from restored context
787
881
  restored_transcript << { role: "user", content: "Now make it budget-friendly." }
788
- second = adapter.stream(restored_transcript, model: "gpt-5.4")
882
+ second = adapter.stream(restored_transcript, model: LlmGateway.models.fetch("openai/gpt-5.4"))
789
883
 
790
884
  puts second.content.select { |b| b.type == "text" }.map(&:text).join
791
885
  ```
@@ -797,9 +891,27 @@ What to persist:
797
891
 
798
892
  Tip: if you serialize to JSON, keys become strings on parse; `llm_gateway` accepts standard hash input and normalizes internally.
799
893
 
894
+ ### Message metadata
895
+
896
+ Input messages may include app-owned metadata, for example a `details` hash used for trace IDs, database IDs, UI state, or other per-message decorations:
897
+
898
+ ```ruby
899
+ transcript = [
900
+ {
901
+ role: "user",
902
+ content: "Hello",
903
+ details: { trace_id: "msg-123", ui_thread_id: "thread-456" }
904
+ }
905
+ ]
906
+
907
+ adapter.stream(transcript, model: LlmGateway.models.fetch("openai/gpt-5.4"))
908
+ ```
909
+
910
+ `llm_gateway` preserves this as part of your local transcript shape, but strips `details` before sending user or assistant messages to provider APIs. This lets applications keep message metadata next to the message without leaking unsupported fields to OpenAI, Anthropic, Groq, or Codex request payloads.
911
+
800
912
  ## OAuth
801
913
 
802
- Use OAuth-capable providers (for example `openai_codex` and `anthropic_messages`) by supplying an `access_token` when building the adapter.
914
+ Use OAuth-capable providers (for example `openai-codex` and `anthropic-messages`) by supplying an `access_token` when building the adapter.
803
915
 
804
916
  ### Get initial tokens (Codex / OpenAI OAuth)
805
917
 
@@ -905,12 +1017,11 @@ current_access_token = manager.access_token
905
1017
  Build the provider with the current access token:
906
1018
 
907
1019
  ```ruby
908
- adapter = LlmGateway.build_provider(
909
- provider: "openai_codex",
910
- access_token: current_access_token
1020
+ adapter = LlmGateway::Adapters::OpenAICodex::Responses.build(
1021
+ api_key: current_access_token
911
1022
  )
912
1023
 
913
- result = adapter.stream("Hello from OAuth auth", model: "gpt-5.4")
1024
+ result = adapter.stream("Hello from OAuth auth", model: LlmGateway.models.fetch("openai/gpt-5.4"))
914
1025
  puts result.content.select { |b| b.type == "text" }.map(&:text).join
915
1026
  ```
916
1027
 
@@ -922,7 +1033,7 @@ OpenAI Codex usage-limit responses include reset information on `LlmGateway::Err
922
1033
 
923
1034
  ```ruby
924
1035
  begin
925
- adapter.stream("Hello from OAuth auth", model: "gpt-5.4")
1036
+ adapter.stream("Hello from OAuth auth", model: LlmGateway.models.fetch("openai/gpt-5.4"))
926
1037
  rescue LlmGateway::Errors::RateLimitError => e
927
1038
  puts e.message # "The usage limit has been reached"
928
1039
  puts e.reset_after_seconds # primary reset window, when available
@@ -963,6 +1074,6 @@ bundle exec ruby -Itest test/integration/live/stream_test.rb
963
1074
 
964
1075
  Cassette names are derived from the test file and test name, with VCR sanitizing path segments such as `stream_test.rb` to `stream_test_rb`.
965
1076
 
966
- For OAuth-backed providers (`anthropic_messages`, `openai_codex`), the live test helper only loads real OAuth credentials while the cassette is being recorded. Once the cassette exists, replay uses placeholder tokens/account IDs so the test suite can run without local OAuth state. API-key providers still require the relevant API key when recording. Sensitive authorization headers and selected response headers are redacted before cassettes are written.
1077
+ For OAuth-backed providers (`anthropic-messages`, `openai-codex`), the live test helper only loads real OAuth credentials while the cassette is being recorded. Once the cassette exists, replay uses placeholder tokens/account IDs so the test suite can run without local OAuth state. API-key providers still require the relevant API key when recording. Sensitive authorization headers and selected response headers are redacted before cassettes are written.
967
1078
 
968
1079
  Some tests pass `redact_request_body: true` to `with_vcr_adapter`; those cassettes match on method and URI only and replace large request bodies with `"<huge prompt body redacted>"`.
data/Rakefile CHANGED
@@ -10,6 +10,11 @@ require "rubocop/rake_task"
10
10
 
11
11
  RuboCop::RakeTask.new
12
12
 
13
+ desc "Regenerate the built-in model catalog from models.dev"
14
+ task "models:generate" do
15
+ ruby "scripts/generate_model_catalog.rb"
16
+ end
17
+
13
18
  begin
14
19
  desc "Release with changelog"
15
20
  task :gem_release do