llm_gateway 0.9.0 → 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 (43) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +26 -0
  3. data/README.md +149 -64
  4. data/Rakefile +5 -0
  5. data/docs/migration_guide_0.10.0.md +53 -0
  6. data/docs/structured-output.md +28 -0
  7. data/lib/llm_gateway/adapter_definition.rb +64 -0
  8. data/lib/llm_gateway/adapters/adapter.rb +105 -21
  9. data/lib/llm_gateway/adapters/anthropic/messages_adapter.rb +8 -0
  10. data/lib/llm_gateway/adapters/anthropic_option_mapper.rb +29 -19
  11. data/lib/llm_gateway/adapters/groq/chat_completions_adapter.rb +8 -0
  12. data/lib/llm_gateway/adapters/groq/option_mapper.rb +7 -9
  13. data/lib/llm_gateway/adapters/normalized_stream_accumulator.rb +7 -3
  14. data/lib/llm_gateway/adapters/openai/chat_completions/option_mapper.rb +7 -9
  15. data/lib/llm_gateway/adapters/openai/chat_completions/stream_mapper.rb +1 -1
  16. data/lib/llm_gateway/adapters/openai/chat_completions_adapter.rb +6 -0
  17. data/lib/llm_gateway/adapters/openai/responses/option_mapper.rb +11 -9
  18. data/lib/llm_gateway/adapters/openai/responses/stream_mapper.rb +1 -1
  19. data/lib/llm_gateway/adapters/openai/responses_adapter.rb +6 -0
  20. data/lib/llm_gateway/adapters/openai_codex/responses_adapter.rb +8 -0
  21. data/lib/llm_gateway/adapters/stream_mapper.rb +4 -3
  22. data/lib/llm_gateway/agents/harness.rb +63 -29
  23. data/lib/llm_gateway/agents/in_memory_session_manager.rb +35 -4
  24. data/lib/llm_gateway/agents/tools/tool_utils.rb +2 -2
  25. data/lib/llm_gateway/errors.rb +3 -0
  26. data/lib/llm_gateway/models/catalog.rb +68 -0
  27. data/lib/llm_gateway/models/cost_calculator.rb +47 -0
  28. data/lib/llm_gateway/models/definition.rb +325 -0
  29. data/lib/llm_gateway/models/explicit.rb +46 -0
  30. data/lib/llm_gateway/models/generated.json +3055 -0
  31. data/lib/llm_gateway/models.rb +78 -0
  32. data/lib/llm_gateway/prompt.rb +13 -13
  33. data/lib/llm_gateway/proxy/adapter.rb +22 -12
  34. data/lib/llm_gateway/proxy/client.rb +4 -4
  35. data/lib/llm_gateway/proxy/protocol.rb +50 -0
  36. data/lib/llm_gateway/proxy/server.rb +12 -9
  37. data/lib/llm_gateway/utils.rb +12 -6
  38. data/lib/llm_gateway/version.rb +1 -1
  39. data/lib/llm_gateway.rb +4 -67
  40. data/scripts/generate_model_catalog.rb +195 -0
  41. metadata +13 -4
  42. data/lib/llm_gateway/client.rb +0 -35
  43. data/lib/llm_gateway/provider_registry.rb +0 -37
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 6110cca0d13016825c5b47cf76dae5a6d5ecfad786bc4f15b343e6ff03ef0710
4
- data.tar.gz: 7f71d8817c123293e2ff3f0914a2209f8e12ab4f9522e14e020506424613b78b
3
+ metadata.gz: 52b4361c9d53e7891a8ba2077f4420b76ad55ebf4b73e7841a34e6ae90df4acf
4
+ data.tar.gz: 05ae83106bc079aa5b2edbee2894ff7c60b23738e893c6ddb3624621e0c689d7
5
5
  SHA512:
6
- metadata.gz: e949f1d3f12fc6fc67202bdd3787caf8a1afaf27032ffb75e502e537e8c6d0a9fb55f4c393fe8e0306667a80f73c8b64a02e7ca688761d52a053ce519d42c1ae
7
- data.tar.gz: 460024732ffc2e2668cfee803f82ea029825abfbadb7964d8e9847bbd612b20d08d8f8fa7661d7842868da33f8cc8258fb21d2be9dd2ffa12f7b304bededd2ff
6
+ metadata.gz: b0bca0efd7f81d29dce06c87105542adacac799a02a2c236dbebb245b6ebbd91e67d084fd40863894f7854e87e926b2750c906cff7752a16802569988628ffe4
7
+ data.tar.gz: a9e101dd03b19d241fd2f81a2534aaa6b6769eb41884298977f6779ed0a9e073ed39d39aedc2df6bde37ad0968c5176cf0ef8e87a518cf12660c7dfb18ef9a5b
data/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
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
+
3
29
  ## [v0.9.0](https://github.com/Hyper-Unearthing/llm_gateway/tree/v0.9.0) (2026-07-13)
4
30
 
5
31
  [Full Changelog](https://github.com/Hyper-Unearthing/llm_gateway/compare/v0.8.1...v0.9.0)
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,6 +30,7 @@ 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)
33
35
  - [Message metadata](#message-metadata)
34
36
  - [OAuth](#oauth)
@@ -62,13 +64,13 @@ gem "llm_gateway"
62
64
 
63
65
  | Provider | Provider Key | Auth | API Surface |
64
66
  |-----------|------------------------------|-------|------------------------|
65
- | Anthropic | `anthropic_messages` | API key | Messages |
66
- | OpenAI | `openai_completions` | API key | Chat Completions |
67
- | OpenAI | `openai_responses` | API key | Responses |
68
- | OpenAI Codex | `openai_codex` | OAuth | Responses |
69
- | 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 |
70
72
 
71
- 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:`.
72
74
 
73
75
  ## Stream Options
74
76
 
@@ -106,25 +108,45 @@ Unknown provider-specific options raise `ArgumentError` with the valid option li
106
108
 
107
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.
108
110
 
109
- | Provider key | Provider/API pair | Option mapper source | Provider API documentation |
111
+ | Adapter ID | Provider/API pair | Option mapper source | Provider API documentation |
110
112
  |--------------|-------------------|----------------------|----------------------------|
111
- | `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) |
112
- | `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) |
113
- | `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) |
114
- | `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) |
115
- | `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) |
116
118
 
117
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.
118
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
+
119
142
  ## Quick Start: Streaming (all events)
120
143
 
121
144
  ```ruby
122
145
  require "llm_gateway"
123
146
  require "json"
124
147
 
125
- # Build a provider adapter directly (not via prebuilt config)
126
- adapter = LlmGateway.build_provider(
127
- 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(
128
150
  api_key: ENV.fetch("OPENAI_API_KEY")
129
151
  )
130
152
  tools = [
@@ -146,7 +168,7 @@ transcript = [
146
168
 
147
169
  streamed_tool_args = Hash.new { |h, k| h[k] = +"" }
148
170
 
149
- 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|
150
172
  case event.type
151
173
  # AssistantStreamMessageEvent
152
174
  when :message_start
@@ -232,7 +254,51 @@ End events include helpers for the finalized current content block:
232
254
  - `event.reasoning` for `:reasoning_end`
233
255
  - `event.tool_call` / `event.tool` for `:tool_end`
234
256
 
235
- 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.
236
302
 
237
303
  ### Stream API without handling events (final result only)
238
304
 
@@ -241,12 +307,11 @@ If you only care about the final `AssistantMessage`, call `stream` without a blo
241
307
  ```ruby
242
308
  require "llm_gateway"
243
309
 
244
- adapter = LlmGateway.build_provider(
245
- provider: "openai_responses",
310
+ adapter = LlmGateway::Adapters::OpenAI::Responses.build(
246
311
  api_key: ENV.fetch("OPENAI_API_KEY")
247
312
  )
248
313
 
249
- 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"))
250
315
 
251
316
  puts result.role # "assistant"
252
317
  puts result.timestamp # Unix milliseconds
@@ -263,7 +328,7 @@ puts text
263
328
 
264
329
  ## Prompt classes
265
330
 
266
- `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.
267
332
 
268
333
  ```ruby
269
334
  class AddTool < LlmGateway::Tool
@@ -278,11 +343,10 @@ class AddTool < LlmGateway::Tool
278
343
  end
279
344
 
280
345
  class MathPrompt < LlmGateway::Prompt
281
- self.provider = LlmGateway.build_provider(
282
- provider: "openai_responses",
346
+ self.adapter = LlmGateway::Adapters::OpenAI::Responses.build(
283
347
  api_key: ENV.fetch("OPENAI_API_KEY")
284
348
  )
285
- self.model = "gpt-5.4"
349
+ self.model = LlmGateway.models.fetch("openai/gpt-5.4")
286
350
 
287
351
  TOOLS = [AddTool].freeze
288
352
 
@@ -307,8 +371,8 @@ puts response.content.select { |block| block.type == "text" }.map(&:text).join
307
371
  How `Prompt` works now:
308
372
 
309
373
  - `prompt` is evaluated once per `run`.
310
- - `run(provider:, model:, reasoning:, **options)` calls `stream` and returns the final normalized `AssistantMessage` after any tool calls complete.
311
- - `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`.
312
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.
313
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.
314
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) }`.
@@ -319,6 +383,7 @@ How `Prompt` works now:
319
383
 
320
384
  ## Migration guides
321
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.
322
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.
323
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.
324
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.
@@ -355,8 +420,7 @@ Use `stream` without a block, inspect returned `tool_use` blocks, execute tools,
355
420
  require "llm_gateway"
356
421
  require "json"
357
422
 
358
- adapter = LlmGateway.build_provider(
359
- provider: "openai_responses",
423
+ adapter = LlmGateway::Adapters::OpenAI::Responses.build(
360
424
  api_key: ENV.fetch("OPENAI_API_KEY")
361
425
  )
362
426
  weather_tool = {
@@ -387,7 +451,7 @@ transcript = [
387
451
  ]
388
452
 
389
453
  # 1) First model pass (stream API, no event block)
390
- 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"))
391
455
  transcript << response.to_h
392
456
 
393
457
  # 2) Execute tool calls returned by the model
@@ -410,7 +474,7 @@ end
410
474
 
411
475
  # 3) Continue the conversation after tool execution
412
476
  if response.content.any? { |b| b.type == "tool_use" }
413
- 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"))
414
478
 
415
479
  final_text = final_response.content
416
480
  .select { |b| b.type == "text" }
@@ -443,8 +507,15 @@ anthropic_code_execution = {
443
507
  name: "code_execution"
444
508
  }
445
509
 
446
- tools = provider == "openai_responses" ? [openai_code_interpreter] : [anthropic_code_execution]
447
- 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|
448
519
  case event.type
449
520
  when :tool_start
450
521
  puts "server tool: #{event.name}" if event.tool_type == "server_tool_use"
@@ -513,18 +584,14 @@ class WeatherHarness < LlmGateway::Agents::Harness
513
584
  end
514
585
  end
515
586
 
516
- adapter = LlmGateway.build_provider(
517
- provider: "openai_responses",
587
+ adapter = LlmGateway::Adapters::OpenAI::Responses.build(
518
588
  api_key: ENV.fetch("OPENAI_API_KEY")
519
589
  )
520
590
 
521
591
  session = LlmGateway::Agents::InMemorySessionManager.new("weather-session")
522
- harness = WeatherHarness.new(
523
- session,
524
- provider: adapter,
525
- model: "gpt-5.4",
526
- reasoning: "high"
527
- )
592
+ session.change_model(LlmGateway.models.fetch("openai/gpt-5.4"))
593
+ session.change_reasoning("high")
594
+ harness = WeatherHarness.new(session, adapter: adapter)
528
595
 
529
596
  harness.prompt_message(
530
597
  role: "user",
@@ -554,8 +621,10 @@ puts harness.transcript.inspect
554
621
  Harness behavior:
555
622
 
556
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.
557
- - Harnesses pass `tools`, `system_prompt`, `model`, `reasoning`, `cache_key`, and `cache_retention` through the inherited `Prompt#stream` defaults.
558
- - 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)`.
559
628
  - `harness.transcript` (also aliased as `prompt`) returns the current model input: the latest compaction summary, if any, followed by active messages.
560
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.
561
630
 
@@ -598,7 +667,7 @@ Before starting a new user message and before draining queued follow-up work, th
598
667
  - the latest recorded message usage exceeds `LlmGateway::Agents::Harness::COMPACTION_TOKEN_THRESHOLD`, or
599
668
  - the latest assistant message is older than `LlmGateway::Agents::Harness::COMPACTION_IDLE_THRESHOLD_SECONDS`.
600
669
 
601
- 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.
602
671
 
603
672
  ### Built-in agent tools
604
673
 
@@ -628,8 +697,7 @@ Send images by including an `image` content block in a user message.
628
697
  require "llm_gateway"
629
698
  require "base64"
630
699
 
631
- adapter = LlmGateway.build_provider(
632
- provider: "openai_responses",
700
+ adapter = LlmGateway::Adapters::OpenAI::Responses.build(
633
701
  api_key: ENV.fetch("OPENAI_API_KEY")
634
702
  )
635
703
  image_b64 = Base64.strict_encode64(File.binread("./chart.png"))
@@ -644,7 +712,7 @@ message = [
644
712
  }
645
713
  ]
646
714
 
647
- 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
648
716
 
649
717
  text = result.content
650
718
  .select { |b| b.type == "text" }
@@ -663,19 +731,18 @@ You can request higher-effort reasoning by passing `reasoning:` to `stream`.
663
731
  ```ruby
664
732
  require "llm_gateway"
665
733
 
666
- adapter = LlmGateway.build_provider(
667
- provider: "openai_responses",
734
+ adapter = LlmGateway::Adapters::OpenAI::Responses.build(
668
735
  api_key: ENV.fetch("OPENAI_API_KEY")
669
736
  )
670
737
 
671
738
  result = adapter.stream(
672
739
  "Think step by step and then compute 482 * 17.",
673
- model: "gpt-5.4",
740
+ model: LlmGateway.models.fetch("openai/gpt-5.4"),
674
741
  reasoning: "high"
675
742
  )
676
743
 
677
744
  puts "stop_reason: #{result.stop_reason}"
678
- 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
679
746
 
680
747
  result.content.each do |block|
681
748
  case block.type
@@ -695,7 +762,7 @@ If you want incremental thinking/reasoning tokens as they arrive, pass a block t
695
762
  ```ruby
696
763
  reasoning_text = +""
697
764
 
698
- 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|
699
766
  case event.type
700
767
  when :reasoning_start
701
768
  print "\n[thinking start]\n"
@@ -738,7 +805,7 @@ Notes:
738
805
 
739
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.
740
807
 
741
- What happens under the hood on `stream`/`chat`:
808
+ What happens under the hood on `stream`:
742
809
 
743
810
  1. **Normalize input**
744
811
  - String input is converted to a user message.
@@ -764,6 +831,26 @@ Why this matters:
764
831
  - Tool calls/reasoning/text are exposed through a consistent API even when upstream event formats differ.
765
832
  - Your app can keep one conversation state format while switching providers for cost, latency, capability, or reliability reasons.
766
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
+
767
854
  ## Context Serialization
768
855
 
769
856
  `llm_gateway` contexts are plain Ruby hashes/arrays, so they can be serialized to JSON and restored later.
@@ -772,8 +859,7 @@ Why this matters:
772
859
  require "llm_gateway"
773
860
  require "json"
774
861
 
775
- adapter = LlmGateway.build_provider(
776
- provider: "openai_responses",
862
+ adapter = LlmGateway::Adapters::OpenAI::Responses.build(
777
863
  api_key: ENV.fetch("OPENAI_API_KEY")
778
864
  )
779
865
  # Build context (transcript)
@@ -782,7 +868,7 @@ transcript = [
782
868
  ]
783
869
 
784
870
  # Run one turn and persist assistant output
785
- first = adapter.stream(transcript, model: "gpt-5.4")
871
+ first = adapter.stream(transcript, model: LlmGateway.models.fetch("openai/gpt-5.4"))
786
872
  transcript << first.to_h
787
873
 
788
874
  # Serialize (store in DB/file/cache)
@@ -793,7 +879,7 @@ restored_transcript = JSON.parse(json_context)
793
879
 
794
880
  # Continue conversation from restored context
795
881
  restored_transcript << { role: "user", content: "Now make it budget-friendly." }
796
- second = adapter.stream(restored_transcript, model: "gpt-5.4")
882
+ second = adapter.stream(restored_transcript, model: LlmGateway.models.fetch("openai/gpt-5.4"))
797
883
 
798
884
  puts second.content.select { |b| b.type == "text" }.map(&:text).join
799
885
  ```
@@ -818,14 +904,14 @@ transcript = [
818
904
  }
819
905
  ]
820
906
 
821
- adapter.stream(transcript, model: "gpt-5.4")
907
+ adapter.stream(transcript, model: LlmGateway.models.fetch("openai/gpt-5.4"))
822
908
  ```
823
909
 
824
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.
825
911
 
826
912
  ## OAuth
827
913
 
828
- 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.
829
915
 
830
916
  ### Get initial tokens (Codex / OpenAI OAuth)
831
917
 
@@ -931,12 +1017,11 @@ current_access_token = manager.access_token
931
1017
  Build the provider with the current access token:
932
1018
 
933
1019
  ```ruby
934
- adapter = LlmGateway.build_provider(
935
- provider: "openai_codex",
936
- access_token: current_access_token
1020
+ adapter = LlmGateway::Adapters::OpenAICodex::Responses.build(
1021
+ api_key: current_access_token
937
1022
  )
938
1023
 
939
- 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"))
940
1025
  puts result.content.select { |b| b.type == "text" }.map(&:text).join
941
1026
  ```
942
1027
 
@@ -948,7 +1033,7 @@ OpenAI Codex usage-limit responses include reset information on `LlmGateway::Err
948
1033
 
949
1034
  ```ruby
950
1035
  begin
951
- 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"))
952
1037
  rescue LlmGateway::Errors::RateLimitError => e
953
1038
  puts e.message # "The usage limit has been reached"
954
1039
  puts e.reset_after_seconds # primary reset window, when available
@@ -989,6 +1074,6 @@ bundle exec ruby -Itest test/integration/live/stream_test.rb
989
1074
 
990
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`.
991
1076
 
992
- 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.
993
1078
 
994
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
@@ -0,0 +1,53 @@
1
+ # Migration guide: v0.9.0 to v0.10.0
2
+
3
+ ## Build adapters directly
4
+
5
+ `LlmGateway.build_provider`, `LlmGateway.configure`, `configured_clients`, and `ProviderRegistry` were removed. Build and retain the adapter your application needs:
6
+
7
+ ```ruby
8
+ # Before
9
+ adapter = LlmGateway.build_provider(provider: "openai_responses", api_key: key)
10
+
11
+ # After
12
+ adapter = LlmGateway::Adapters::OpenAI::Responses.build(api_key: key)
13
+ ```
14
+
15
+ Use `Anthropic::Messages`, `OpenAI::ChatCompletions`, `OpenAI::Responses`, `OpenAICodex::Responses`, or `Groq::ChatCompletions`. `Adapter.build` accepts only client/transport configuration, not `model:` or `model_key:`.
16
+
17
+ ## Pass model definitions, not strings
18
+
19
+ `stream` now requires a catalog model definition. Fetch one and reuse it:
20
+
21
+ ```ruby
22
+ model = LlmGateway.models.fetch("openai/gpt-5.4")
23
+ adapter.stream("Hello", model: model)
24
+ ```
25
+
26
+ For a newly released or custom model, register a `LlmGateway::Models::Definition` through `LlmGateway.models.register(...)` before using it. The adapter and model providers must match.
27
+
28
+ ## Update Prompt and Harness setup
29
+
30
+ `Prompt` accepts `adapter:` instead of `provider:`. Set `self.adapter` on subclasses or pass `adapter:` to `new`, `run`, or `stream`.
31
+
32
+ A `Harness` also requires an adapter, while its model and reasoning live in the session:
33
+
34
+ ```ruby
35
+ session.change_model(model)
36
+ session.change_reasoning("high")
37
+ harness = MyHarness.new(session, adapter: adapter)
38
+ ```
39
+
40
+ Use `harness.change_adapter(new_adapter, model: new_model)` when switching providers.
41
+
42
+ ## Update proxy clients
43
+
44
+ Build proxies with `adapter:` rather than `target_provider:`. Pass an adapter definition, class, or instance:
45
+
46
+ ```ruby
47
+ proxy = LlmGateway::Proxy.build(
48
+ url: url,
49
+ adapter: LlmGateway::Adapters::OpenAI::Responses
50
+ )
51
+ ```
52
+
53
+ The proxy protocol now uses allowlisted hyphenated adapter names internally.
@@ -0,0 +1,28 @@
1
+ # Structured final output
2
+
3
+ Pass a JSON Schema through `response_format` when the selected provider/model supports structured output:
4
+
5
+ ```ruby
6
+ adapter.stream(messages, model: model, tools: tools, response_format: {
7
+ type: "json_schema",
8
+ json_schema: {
9
+ name: "repair_result",
10
+ strict: true,
11
+ schema: {
12
+ type: "object",
13
+ additionalProperties: false,
14
+ properties: {
15
+ outcome: { type: "string", enum: ["resolved", "needs_human"] },
16
+ message: { type: "string" }
17
+ },
18
+ required: ["outcome", "message"]
19
+ }
20
+ }
21
+ })
22
+ ```
23
+
24
+ OpenAI Chat Completions and Groq receive this envelope directly. OpenAI Responses (including Codex) receives the definition under `text.format`; Anthropic receives the schema under `output_config.format`, preserving native output settings and reasoning effort. Symbol and JSON string keys are supported. Provider-native options remain available.
25
+
26
+ Anthropic does not support schema-less `json_object` mode: use an explicit schema. Older gateway versions incorrectly discarded the supplied schema and emitted an invalid `output_config.format` string.
27
+
28
+ This changes request translation, not response parsing or agent completion semantics. Tool-call turns remain ordinary tool calls; validate the final text against the application's result contract. A refusal, interruption, missing final message, or invalid JSON is not a successful structured result. Provider/model support for schemas alongside tools varies and is ultimately enforced by the provider.