✨ openai-responses: a provider for OpenAI's Responses API (ticket 178)
OpenAI's reasoning models refuse function tools with active reasoning on
/v1/chat/completions, and an mm agent always sends tools. The new
provider openai-responses talks to the same servers (same address, key,
probe and error messages as openai) through POST /responses, with a
Genkit model of mm's own: plain HTTP, JSON and SSE. Text, tool-call
argument and reasoning deltas stream like on Chat Completions (thoughts,
watchdog, runaway guard); errors keep the existing handling (Explain,
one retry of a broken stream, broken tool arguments handed back).
The reasoning stays with the tools: store false, encrypted reasoning
requested, kept on the model message's metadata and sent back with the
tool results. The sampling block goes as written (max_tokens and
max_completion_tokens become max_output_tokens, reasoning_effort becomes
reasoning.effort; reasoning: {summary: auto} shows the summary as
thoughts). The compaction summary asks for reasoning.effort none.
mm init offers openai-responses with the same endpoint and key
questions as openai. The openai provider is unchanged. Docs EN+FR (new
how-to use-the-openai-responses-api.md).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>ac82813 parent: d2942fd modified
.tickets/issues/0178-support-openai-s-responses-api-to-keep-reasoning.yaml +89 -10 | @@ -1,15 +1,15 @@ | ||
| 1 | 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. |
| 2 | 2 | id: 178 |
| 3 | 3 | title: Support OpenAI's Responses API, to keep reasoning and tools together (gpt-6-luna) |
| 4 | -state: open | |
| 4 | +state: closed | |
| 5 | 5 | author: |
| 6 | 6 | name: k33g |
| 7 | 7 | email: ph.charriere@gmail.com |
| 8 | 8 | createdAt: 2026-10-26T19:30:00.000Z |
| 9 | -updatedAt: 2026-11-11T06:48:27.885Z | |
| 9 | +updatedAt: 2026-11-18T06:36:21.000Z | |
| 10 | 10 | labels: |
| 11 | 11 | - kind::feature |
| 12 | -milestone: v2.0.0 | |
| 12 | +milestone: v1.1.1 | |
| 13 | 13 | epic: Providers (LLM Engine) |
| 14 | 14 | related: |
| 15 | 15 | - 176 |
| @@ -54,50 +54,129 @@ body: | | ||
| 54 | 54 | tasks: |
| 55 | 55 | - id: 1 |
| 56 | 56 | title: "Decide: a new provider (A) or an api key on openai (B); store false + encrypted reasoning, or previous_response_id" |
| 57 | - state: open | |
| 57 | + state: closed | |
| 58 | 58 | priority: none |
| 59 | 59 | author: |
| 60 | 60 | name: k33g |
| 61 | 61 | email: ph.charriere@gmail.com |
| 62 | 62 | createdAt: 2026-10-26T19:30:00.000Z |
| 63 | + updatedAt: 2026-11-18T06:06:11.000Z | |
| 64 | + closedAt: 2026-11-18T06:06:11.000Z | |
| 63 | 65 | - id: 2 |
| 64 | 66 | title: Check which OpenAI-compatible servers serve /v1/responses (vLLM, Ollama, llama-server…) |
| 65 | - state: open | |
| 67 | + state: closed | |
| 66 | 68 | priority: none |
| 67 | 69 | author: |
| 68 | 70 | name: k33g |
| 69 | 71 | email: ph.charriere@gmail.com |
| 70 | 72 | createdAt: 2026-10-26T19:30:00.000Z |
| 73 | + updatedAt: 2026-11-18T06:36:21.000Z | |
| 74 | + closedAt: 2026-11-18T06:36:21.000Z | |
| 71 | 75 | - id: 3 |
| 72 | 76 | title: "A Genkit model on openai-go's responses package: request/response conversion, streaming events, tool calls" |
| 73 | - state: open | |
| 77 | + state: closed | |
| 74 | 78 | priority: none |
| 75 | 79 | author: |
| 76 | 80 | name: k33g |
| 77 | 81 | email: ph.charriere@gmail.com |
| 78 | 82 | createdAt: 2026-10-26T19:30:00.000Z |
| 83 | + updatedAt: 2026-11-18T06:06:11.000Z | |
| 84 | + closedAt: 2026-11-18T06:06:11.000Z | |
| 79 | 85 | - id: 4 |
| 80 | 86 | title: Reasoning items carried between turns; thoughts, usage, structuredOutput, compaction, max_output_tokens |
| 81 | - state: open | |
| 87 | + state: closed | |
| 82 | 88 | priority: none |
| 83 | 89 | author: |
| 84 | 90 | name: k33g |
| 85 | 91 | email: ph.charriere@gmail.com |
| 86 | 92 | createdAt: 2026-10-26T19:30:00.000Z |
| 93 | + updatedAt: 2026-11-18T06:06:11.000Z | |
| 94 | + closedAt: 2026-11-18T06:06:11.000Z | |
| 87 | 95 | - id: 5 |
| 88 | 96 | title: Tests against a fake /v1/responses server; a live check with a reasoning model |
| 89 | - state: open | |
| 97 | + state: closed | |
| 90 | 98 | priority: none |
| 91 | 99 | author: |
| 92 | 100 | name: k33g |
| 93 | 101 | email: ph.charriere@gmail.com |
| 94 | 102 | createdAt: 2026-10-26T19:30:00.000Z |
| 103 | + updatedAt: 2026-11-18T06:36:21.000Z | |
| 104 | + closedAt: 2026-11-18T06:36:21.000Z | |
| 95 | 105 | - id: 6 |
| 96 | 106 | title: mm init and docs EN + FR |
| 97 | - state: open | |
| 107 | + state: closed | |
| 98 | 108 | priority: none |
| 99 | 109 | author: |
| 100 | 110 | name: k33g |
| 101 | 111 | email: ph.charriere@gmail.com |
| 102 | 112 | createdAt: 2026-10-26T19:30:00.000Z |
| 103 | -comments: [] | |
| 113 | + updatedAt: 2026-11-18T06:06:11.000Z | |
| 114 | + closedAt: 2026-11-18T06:06:11.000Z | |
| 115 | +comments: | |
| 116 | + - id: 1 | |
| 117 | + author: | |
| 118 | + name: k33g | |
| 119 | + email: ph.charriere@gmail.com | |
| 120 | + createdAt: 2026-11-18T06:06:11.000Z | |
| 121 | + body: | | |
| 122 | + Moved to v1.1.1; option **A** chosen by the user (2026-11-18): a new | |
| 123 | + provider `openai-responses`, nothing changed for `openai`. | |
| 124 | + Implemented on `feature/openai-responses` (uncommitted). | |
| 125 | + | |
| 126 | + - Decision taken here (the ticket's second question): **`store: | |
| 127 | + false` + `include: ["reasoning.encrypted_content"]`**, the | |
| 128 | + reasoning items carried on the model message's metadata | |
| 129 | + (`openaiResponsesReasoning`) and sent back before its function | |
| 130 | + calls. Stateless on OpenAI's side, and it fits mm's own history | |
| 131 | + (sessions save it too). `store` / `include` in `sampling` win. | |
| 132 | + - Engine: an `openaiCompat` entry with a `responses` flag (same | |
| 133 | + address, key, probe, Explain, URL helpers as openai); `Open` | |
| 134 | + defines a Genkit model of mm's own (`internal/engine/responses.go`) | |
| 135 | + speaking POST /responses in plain HTTP + JSON + SSE (not openai-go's | |
| 136 | + `responses` package). Streaming: output_text.delta → text chunks, | |
| 137 | + function_call_arguments.delta → tool-request chunks (runaway guard, | |
| 138 | + watchdog), reasoning_summary_text / reasoning_text deltas → the | |
| 139 | + turn's reasoning listener (thoughts, heartbeat); the answer from | |
| 140 | + response.completed / incomplete / failed. Errors: HTTP status in | |
| 141 | + the OpenAI client's text form (Explain reads it), error event and | |
| 142 | + cut stream → "stream error" (retried once), bad tool args → "could | |
| 143 | + not parse tool args" (handed back to the model). Usage incl. cached | |
| 144 | + and reasoning tokens. structuredOutput → text.format json_schema | |
| 145 | + (strict, as openai). Summary: not streamed, reasoning.effort none. | |
| 146 | + Sampling as written; max_tokens / max_completion_tokens → | |
| 147 | + max_output_tokens, reasoning_effort → reasoning.effort. Tools as | |
| 148 | + non-strict function tools. The trace middleware applies. | |
| 149 | + - Config: sampling is the file's block only, like openai. | |
| 150 | + - mm init / acp-create: `openai-responses` offered after `openai`, | |
| 151 | + same endpoint/key questions and keyed model list (`isOpenAI`), no | |
| 152 | + `reasoning_effort: none` hint in its file. | |
| 153 | + - Docs EN+FR: new how-to `use-the-openai-responses-api.md`; | |
| 154 | + configuration (provider key, sampling, providers table + paragraph, | |
| 155 | + /v1/systemone table, unknown-provider message), cli (`--provider`, | |
| 156 | + `--base-url`, `--api-key-env`), providers explanation, mm-init | |
| 157 | + explanation, create-an-agent, the openai-compatible guide (points | |
| 158 | + to the new provider), README indexes. | |
| 159 | + | |
| 160 | + Tests: `responses_test.go` against a fake /v1/responses (tool turn | |
| 161 | + with encrypted reasoning sent back and function_call_output by | |
| 162 | + call_id, reasoning listener, summary, refused key, error event, cut | |
| 163 | + stream, cut tool args, incomplete answer, failed, request fields, | |
| 164 | + registry), config and mm init tests; whole suite green, gofmt + vet | |
| 165 | + clean. End to end with the built binary and a fake Python server: | |
| 166 | + thoughts shown, `bash` ran, second request carried system, user, | |
| 167 | + reasoning (encrypted), function_call, function_call_output. | |
| 168 | + | |
| 169 | + Not done: task 2 (which servers besides OpenAI serve /v1/responses) | |
| 170 | + and the live check of task 5 (needs an OpenAI key and a reasoning | |
| 171 | + model). Not handled: `toolFormat: xml_tools` (the tools go as | |
| 172 | + function tools), a decider with this provider (refused, no | |
| 173 | + /v1/systemone), unloading, prompt-reading progress. | |
| 174 | + - id: 2 | |
| 175 | + author: | |
| 176 | + name: k33g | |
| 177 | + email: ph.charriere@gmail.com | |
| 178 | + createdAt: 2026-11-18T06:36:21.000Z | |
| 179 | + body: | | |
| 180 | + Tested by the user (2026-11-18): it works. Closed at the user's | |
| 181 | + request. Task 2 (which other servers serve /v1/responses) closed | |
| 182 | + without being checked. | |
| @@ -1,15 +1,15 @@ | |||
| 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. |
| 2 | id: 178 | 2 | id: 178 |
| 3 | title: Support OpenAI's Responses API, to keep reasoning and tools together (gpt-6-luna) | 3 | title: Support OpenAI's Responses API, to keep reasoning and tools together (gpt-6-luna) |
| 4 | -state: open | 4 | +state: closed |
| 5 | author: | 5 | author: |
| 6 | name: k33g | 6 | name: k33g |
| 7 | email: ph.charriere@gmail.com | 7 | email: ph.charriere@gmail.com |
| 8 | createdAt: 2026-10-26T19:30:00.000Z | 8 | createdAt: 2026-10-26T19:30:00.000Z |
| 9 | -updatedAt: 2026-11-11T06:48:27.885Z | 9 | +updatedAt: 2026-11-18T06:36:21.000Z |
| 10 | labels: | 10 | labels: |
| 11 | - kind::feature | 11 | - kind::feature |
| 12 | -milestone: v2.0.0 | 12 | +milestone: v1.1.1 |
| 13 | epic: Providers (LLM Engine) | 13 | epic: Providers (LLM Engine) |
| 14 | related: | 14 | related: |
| 15 | - 176 | 15 | - 176 |
| @@ -54,50 +54,129 @@ body: | | |||
| 54 | tasks: | 54 | tasks: |
| 55 | - id: 1 | 55 | - id: 1 |
| 56 | title: "Decide: a new provider (A) or an api key on openai (B); store false + encrypted reasoning, or previous_response_id" | 56 | title: "Decide: a new provider (A) or an api key on openai (B); store false + encrypted reasoning, or previous_response_id" |
| 57 | - state: open | 57 | + state: closed |
| 58 | priority: none | 58 | priority: none |
| 59 | author: | 59 | author: |
| 60 | name: k33g | 60 | name: k33g |
| 61 | email: ph.charriere@gmail.com | 61 | email: ph.charriere@gmail.com |
| 62 | createdAt: 2026-10-26T19:30:00.000Z | 62 | createdAt: 2026-10-26T19:30:00.000Z |
| 63 | + updatedAt: 2026-11-18T06:06:11.000Z | ||
| 64 | + closedAt: 2026-11-18T06:06:11.000Z | ||
| 63 | - id: 2 | 65 | - id: 2 |
| 64 | title: Check which OpenAI-compatible servers serve /v1/responses (vLLM, Ollama, llama-server…) | 66 | title: Check which OpenAI-compatible servers serve /v1/responses (vLLM, Ollama, llama-server…) |
| 65 | - state: open | 67 | + state: closed |
| 66 | priority: none | 68 | priority: none |
| 67 | author: | 69 | author: |
| 68 | name: k33g | 70 | name: k33g |
| 69 | email: ph.charriere@gmail.com | 71 | email: ph.charriere@gmail.com |
| 70 | createdAt: 2026-10-26T19:30:00.000Z | 72 | createdAt: 2026-10-26T19:30:00.000Z |
| 73 | + updatedAt: 2026-11-18T06:36:21.000Z | ||
| 74 | + closedAt: 2026-11-18T06:36:21.000Z | ||
| 71 | - id: 3 | 75 | - id: 3 |
| 72 | title: "A Genkit model on openai-go's responses package: request/response conversion, streaming events, tool calls" | 76 | title: "A Genkit model on openai-go's responses package: request/response conversion, streaming events, tool calls" |
| 73 | - state: open | 77 | + state: closed |
| 74 | priority: none | 78 | priority: none |
| 75 | author: | 79 | author: |
| 76 | name: k33g | 80 | name: k33g |
| 77 | email: ph.charriere@gmail.com | 81 | email: ph.charriere@gmail.com |
| 78 | createdAt: 2026-10-26T19:30:00.000Z | 82 | createdAt: 2026-10-26T19:30:00.000Z |
| 83 | + updatedAt: 2026-11-18T06:06:11.000Z | ||
| 84 | + closedAt: 2026-11-18T06:06:11.000Z | ||
| 79 | - id: 4 | 85 | - id: 4 |
| 80 | title: Reasoning items carried between turns; thoughts, usage, structuredOutput, compaction, max_output_tokens | 86 | title: Reasoning items carried between turns; thoughts, usage, structuredOutput, compaction, max_output_tokens |
| 81 | - state: open | 87 | + state: closed |
| 82 | priority: none | 88 | priority: none |
| 83 | author: | 89 | author: |
| 84 | name: k33g | 90 | name: k33g |
| 85 | email: ph.charriere@gmail.com | 91 | email: ph.charriere@gmail.com |
| 86 | createdAt: 2026-10-26T19:30:00.000Z | 92 | createdAt: 2026-10-26T19:30:00.000Z |
| 93 | + updatedAt: 2026-11-18T06:06:11.000Z | ||
| 94 | + closedAt: 2026-11-18T06:06:11.000Z | ||
| 87 | - id: 5 | 95 | - id: 5 |
| 88 | title: Tests against a fake /v1/responses server; a live check with a reasoning model | 96 | title: Tests against a fake /v1/responses server; a live check with a reasoning model |
| 89 | - state: open | 97 | + state: closed |
| 90 | priority: none | 98 | priority: none |
| 91 | author: | 99 | author: |
| 92 | name: k33g | 100 | name: k33g |
| 93 | email: ph.charriere@gmail.com | 101 | email: ph.charriere@gmail.com |
| 94 | createdAt: 2026-10-26T19:30:00.000Z | 102 | createdAt: 2026-10-26T19:30:00.000Z |
| 103 | + updatedAt: 2026-11-18T06:36:21.000Z | ||
| 104 | + closedAt: 2026-11-18T06:36:21.000Z | ||
| 95 | - id: 6 | 105 | - id: 6 |
| 96 | title: mm init and docs EN + FR | 106 | title: mm init and docs EN + FR |
| 97 | - state: open | 107 | + state: closed |
| 98 | priority: none | 108 | priority: none |
| 99 | author: | 109 | author: |
| 100 | name: k33g | 110 | name: k33g |
| 101 | email: ph.charriere@gmail.com | 111 | email: ph.charriere@gmail.com |
| 102 | createdAt: 2026-10-26T19:30:00.000Z | 112 | createdAt: 2026-10-26T19:30:00.000Z |
| 103 | -comments: [] | 113 | + updatedAt: 2026-11-18T06:06:11.000Z |
| 114 | + closedAt: 2026-11-18T06:06:11.000Z | ||
| 115 | +comments: | ||
| 116 | + - id: 1 | ||
| 117 | + author: | ||
| 118 | + name: k33g | ||
| 119 | + email: ph.charriere@gmail.com | ||
| 120 | + createdAt: 2026-11-18T06:06:11.000Z | ||
| 121 | + body: | | ||
| 122 | + Moved to v1.1.1; option **A** chosen by the user (2026-11-18): a new | ||
| 123 | + provider `openai-responses`, nothing changed for `openai`. | ||
| 124 | + Implemented on `feature/openai-responses` (uncommitted). | ||
| 125 | + | ||
| 126 | + - Decision taken here (the ticket's second question): **`store: | ||
| 127 | + false` + `include: ["reasoning.encrypted_content"]`**, the | ||
| 128 | + reasoning items carried on the model message's metadata | ||
| 129 | + (`openaiResponsesReasoning`) and sent back before its function | ||
| 130 | + calls. Stateless on OpenAI's side, and it fits mm's own history | ||
| 131 | + (sessions save it too). `store` / `include` in `sampling` win. | ||
| 132 | + - Engine: an `openaiCompat` entry with a `responses` flag (same | ||
| 133 | + address, key, probe, Explain, URL helpers as openai); `Open` | ||
| 134 | + defines a Genkit model of mm's own (`internal/engine/responses.go`) | ||
| 135 | + speaking POST /responses in plain HTTP + JSON + SSE (not openai-go's | ||
| 136 | + `responses` package). Streaming: output_text.delta → text chunks, | ||
| 137 | + function_call_arguments.delta → tool-request chunks (runaway guard, | ||
| 138 | + watchdog), reasoning_summary_text / reasoning_text deltas → the | ||
| 139 | + turn's reasoning listener (thoughts, heartbeat); the answer from | ||
| 140 | + response.completed / incomplete / failed. Errors: HTTP status in | ||
| 141 | + the OpenAI client's text form (Explain reads it), error event and | ||
| 142 | + cut stream → "stream error" (retried once), bad tool args → "could | ||
| 143 | + not parse tool args" (handed back to the model). Usage incl. cached | ||
| 144 | + and reasoning tokens. structuredOutput → text.format json_schema | ||
| 145 | + (strict, as openai). Summary: not streamed, reasoning.effort none. | ||
| 146 | + Sampling as written; max_tokens / max_completion_tokens → | ||
| 147 | + max_output_tokens, reasoning_effort → reasoning.effort. Tools as | ||
| 148 | + non-strict function tools. The trace middleware applies. | ||
| 149 | + - Config: sampling is the file's block only, like openai. | ||
| 150 | + - mm init / acp-create: `openai-responses` offered after `openai`, | ||
| 151 | + same endpoint/key questions and keyed model list (`isOpenAI`), no | ||
| 152 | + `reasoning_effort: none` hint in its file. | ||
| 153 | + - Docs EN+FR: new how-to `use-the-openai-responses-api.md`; | ||
| 154 | + configuration (provider key, sampling, providers table + paragraph, | ||
| 155 | + /v1/systemone table, unknown-provider message), cli (`--provider`, | ||
| 156 | + `--base-url`, `--api-key-env`), providers explanation, mm-init | ||
| 157 | + explanation, create-an-agent, the openai-compatible guide (points | ||
| 158 | + to the new provider), README indexes. | ||
| 159 | + | ||
| 160 | + Tests: `responses_test.go` against a fake /v1/responses (tool turn | ||
| 161 | + with encrypted reasoning sent back and function_call_output by | ||
| 162 | + call_id, reasoning listener, summary, refused key, error event, cut | ||
| 163 | + stream, cut tool args, incomplete answer, failed, request fields, | ||
| 164 | + registry), config and mm init tests; whole suite green, gofmt + vet | ||
| 165 | + clean. End to end with the built binary and a fake Python server: | ||
| 166 | + thoughts shown, `bash` ran, second request carried system, user, | ||
| 167 | + reasoning (encrypted), function_call, function_call_output. | ||
| 168 | + | ||
| 169 | + Not done: task 2 (which servers besides OpenAI serve /v1/responses) | ||
| 170 | + and the live check of task 5 (needs an OpenAI key and a reasoning | ||
| 171 | + model). Not handled: `toolFormat: xml_tools` (the tools go as | ||
| 172 | + function tools), a decider with this provider (refused, no | ||
| 173 | + /v1/systemone), unloading, prompt-reading progress. | ||
| 174 | + - id: 2 | ||
| 175 | + author: | ||
| 176 | + name: k33g | ||
| 177 | + email: ph.charriere@gmail.com | ||
| 178 | + createdAt: 2026-11-18T06:36:21.000Z | ||
| 179 | + body: | | ||
| 180 | + Tested by the user (2026-11-18): it works. Closed at the user's | ||
| 181 | + request. Task 2 (which other servers serve /v1/responses) closed | ||
| 182 | + without being checked. | ||
modified
docs/en/README.md +1 -0 | @@ -18,6 +18,7 @@ This documentation is organised along the four [Diátaxis](https://diataxis.fr) | ||
| 18 | 18 | - [Run mini-me on Ollama](how-to/run-with-ollama.md) — `provider: ollama`, the demo config in `demos/ollama/` |
| 19 | 19 | - [Run mini-me on Kronk](how-to/run-with-kronk.md) — `provider: kronk`, the demo config in `demos/kronk/` |
| 20 | 20 | - [Use any OpenAI-compatible server](how-to/run-with-an-openai-compatible-server.md) — `provider: openai`: the OpenAI API, vLLM, LM Studio, a gateway |
| 21 | +- [Keep reasoning and tools together with OpenAI's Responses API](how-to/use-the-openai-responses-api.md) — `provider: openai-responses`: OpenAI's reasoning models with tools | |
| 21 | 22 | - [Ask another mm agent from your session](how-to/ask-another-agent.md) — `mmConfigs`, `/ask-<name>`, `/ask-with-context-<name>` |
| 22 | 23 | - [See the JSON sent to the model and its answer](how-to/inspect-model-traffic.md) — `trace`, `AGENT_TRACE`, reading the files with jq |
| 23 | 24 | - [Give the agent your project's instructions](how-to/give-project-instructions.md) — `AGENTS.md`, read per conversation, `agentsMd` settings |
| @@ -18,6 +18,7 @@ This documentation is organised along the four [Diátaxis](https://diataxis.fr) | |||
| 18 | - [Run mini-me on Ollama](how-to/run-with-ollama.md) — `provider: ollama`, the demo config in `demos/ollama/` | 18 | - [Run mini-me on Ollama](how-to/run-with-ollama.md) — `provider: ollama`, the demo config in `demos/ollama/` |
| 19 | - [Run mini-me on Kronk](how-to/run-with-kronk.md) — `provider: kronk`, the demo config in `demos/kronk/` | 19 | - [Run mini-me on Kronk](how-to/run-with-kronk.md) — `provider: kronk`, the demo config in `demos/kronk/` |
| 20 | - [Use any OpenAI-compatible server](how-to/run-with-an-openai-compatible-server.md) — `provider: openai`: the OpenAI API, vLLM, LM Studio, a gateway | 20 | - [Use any OpenAI-compatible server](how-to/run-with-an-openai-compatible-server.md) — `provider: openai`: the OpenAI API, vLLM, LM Studio, a gateway |
| 21 | +- [Keep reasoning and tools together with OpenAI's Responses API](how-to/use-the-openai-responses-api.md) — `provider: openai-responses`: OpenAI's reasoning models with tools | ||
| 21 | - [Ask another mm agent from your session](how-to/ask-another-agent.md) — `mmConfigs`, `/ask-<name>`, `/ask-with-context-<name>` | 22 | - [Ask another mm agent from your session](how-to/ask-another-agent.md) — `mmConfigs`, `/ask-<name>`, `/ask-with-context-<name>` |
| 22 | - [See the JSON sent to the model and its answer](how-to/inspect-model-traffic.md) — `trace`, `AGENT_TRACE`, reading the files with jq | 23 | - [See the JSON sent to the model and its answer](how-to/inspect-model-traffic.md) — `trace`, `AGENT_TRACE`, reading the files with jq |
| 23 | - [Give the agent your project's instructions](how-to/give-project-instructions.md) — `AGENTS.md`, read per conversation, `agentsMd` settings | 24 | - [Give the agent your project's instructions](how-to/give-project-instructions.md) — `AGENTS.md`, read per conversation, `agentsMd` settings |
modified
docs/en/explanation/mm-init.md +1 -1 | @@ -18,7 +18,7 @@ The server knows the exact model that is loaded, so it is the most specific sour | ||
| 18 | 18 | | `llamacpp` | `/props` | the window and the chat template | |
| 19 | 19 | | `kronk` | `/models`, then `/v1/kronk/models/<id>` | the model list, the architecture, the window the model is configured with (the trained one when none), the sampling written in the GGUF, the chat template; for a profile, its own sampling, which wins over every other source: `mm` sends its sampling with every request and a request's value replaces a profile's, so the profile's values would otherwise never apply | |
| 20 | 20 | | `dmr` | `/models` | the model list only | |
| 21 | -| `openai` | `/models` (with the key) | the model list only | | |
| 21 | +| `openai`, `openai-responses` | `/models` (with the key) | the model list only | | |
| 22 | 22 | |
| 23 | 23 | From the chat template, `templateThinking` reads how the model's reasoning is switched on or off. It finds `enable_thinking` and its default (on or off), or `reasoning_effort` and the values the template accepts. A model whose template knows neither gets no reasoning switch. |
| 24 | 24 | |
| @@ -18,7 +18,7 @@ The server knows the exact model that is loaded, so it is the most specific sour | |||
| 18 | | `llamacpp` | `/props` | the window and the chat template | | 18 | | `llamacpp` | `/props` | the window and the chat template | |
| 19 | | `kronk` | `/models`, then `/v1/kronk/models/<id>` | the model list, the architecture, the window the model is configured with (the trained one when none), the sampling written in the GGUF, the chat template; for a profile, its own sampling, which wins over every other source: `mm` sends its sampling with every request and a request's value replaces a profile's, so the profile's values would otherwise never apply | | 19 | | `kronk` | `/models`, then `/v1/kronk/models/<id>` | the model list, the architecture, the window the model is configured with (the trained one when none), the sampling written in the GGUF, the chat template; for a profile, its own sampling, which wins over every other source: `mm` sends its sampling with every request and a request's value replaces a profile's, so the profile's values would otherwise never apply | |
| 20 | | `dmr` | `/models` | the model list only | | 20 | | `dmr` | `/models` | the model list only | |
| 21 | -| `openai` | `/models` (with the key) | the model list only | | 21 | +| `openai`, `openai-responses` | `/models` (with the key) | the model list only | |
| 22 | 22 | ||
| 23 | From the chat template, `templateThinking` reads how the model's reasoning is switched on or off. It finds `enable_thinking` and its default (on or off), or `reasoning_effort` and the values the template accepts. A model whose template knows neither gets no reasoning switch. | 23 | From the chat template, `templateThinking` reads how the model's reasoning is switched on or off. It finds `enable_thinking` and its default (on or off), or `reasoning_effort` and the values the template accepts. A model whose template knows neither gets no reasoning switch. |
| 24 | 24 | ||
modified
docs/en/explanation/providers.md +1 -1 | @@ -6,7 +6,7 @@ | ||
| 6 | 6 | |
| 7 | 7 | ## Why it is designed this way |
| 8 | 8 | |
| 9 | -**One provider type per wire protocol, not per vendor.** When the engine was split out, exactly one function and two string constants were specific to Docker Model Runner. Everything else, the streaming, the watchdog, the retry, the command counter, behaved the same against a fake engine that is not DMR either. So `dmr` and `llamacpp` are two data entries of a single `openaiCompat` type: a default base URL, an optional fallback URL, a key policy, and the words used in error messages. Adding another OpenAI-compatible server is a registry entry; adding a different protocol would be a new type. | |
| 9 | +**One provider type per wire protocol, not per vendor.** When the engine was split out, exactly one function and two string constants were specific to Docker Model Runner. Everything else, the streaming, the watchdog, the retry, the command counter, behaved the same against a fake engine that is not DMR either. So `dmr` and `llamacpp` are two data entries of a single `openaiCompat` type: a default base URL, an optional fallback URL, a key policy, and the words used in error messages. Adding another OpenAI-compatible server is a registry entry; adding a different protocol would be a new type. The one exception so far is `openai-responses` (ticket 178): OpenAI's Responses API is a second wire protocol, but for the same servers — same address, same key, same probe, same error messages — so it is an entry of the same type with a `responses` flag, and only the model call differs: a Genkit model of mm's own (`responses.go`), since Genkit's plugin knows Chat Completions only. | |
| 10 | 10 | |
| 11 | 11 | **A provider owns four things.** It resolves the configuration into a concrete backend (URL after environment overrides and fallback probe, key read from the environment, model name); it opens Genkit with its plugin; it probes the server before the first question; and it explains a transport error in one line. |
| 12 | 12 | |
| @@ -6,7 +6,7 @@ | |||
| 6 | 6 | ||
| 7 | ## Why it is designed this way | 7 | ## Why it is designed this way |
| 8 | 8 | ||
| 9 | -**One provider type per wire protocol, not per vendor.** When the engine was split out, exactly one function and two string constants were specific to Docker Model Runner. Everything else, the streaming, the watchdog, the retry, the command counter, behaved the same against a fake engine that is not DMR either. So `dmr` and `llamacpp` are two data entries of a single `openaiCompat` type: a default base URL, an optional fallback URL, a key policy, and the words used in error messages. Adding another OpenAI-compatible server is a registry entry; adding a different protocol would be a new type. | 9 | +**One provider type per wire protocol, not per vendor.** When the engine was split out, exactly one function and two string constants were specific to Docker Model Runner. Everything else, the streaming, the watchdog, the retry, the command counter, behaved the same against a fake engine that is not DMR either. So `dmr` and `llamacpp` are two data entries of a single `openaiCompat` type: a default base URL, an optional fallback URL, a key policy, and the words used in error messages. Adding another OpenAI-compatible server is a registry entry; adding a different protocol would be a new type. The one exception so far is `openai-responses` (ticket 178): OpenAI's Responses API is a second wire protocol, but for the same servers — same address, same key, same probe, same error messages — so it is an entry of the same type with a `responses` flag, and only the model call differs: a Genkit model of mm's own (`responses.go`), since Genkit's plugin knows Chat Completions only. |
| 10 | 10 | ||
| 11 | **A provider owns four things.** It resolves the configuration into a concrete backend (URL after environment overrides and fallback probe, key read from the environment, model name); it opens Genkit with its plugin; it probes the server before the first question; and it explains a transport error in one line. | 11 | **A provider owns four things.** It resolves the configuration into a concrete backend (URL after environment overrides and fallback probe, key read from the environment, model name); it opens Genkit with its plugin; it probes the server before the first question; and it explains a transport error in one line. |
| 12 | 12 | ||
modified
docs/en/how-to/create-an-agent.md +1 -1 | @@ -81,7 +81,7 @@ This guide shows how to write a new agent.yaml for a model and a job, with mm's | ||
| 81 | 81 | - **See the file without writing it.** `-o -` prints it on stdout. Nothing is created, not even the `.mm` or skills folder. |
| 82 | 82 | - **Everything in a `.mm` folder.** Answer `yes` to the first question, or give `--project yes`: mm creates `.mm/` and writes `.mm/agent.yaml`, its paths written from the project root. Started from that root, `mm` and `mm tui` find it with no argument. See [How to keep a project's mini-me files in a `.mm` folder](keep-the-config-in-a-mm-folder.md). |
| 83 | 83 | - **Sessions and skills.** `--sessions yes` writes a `sessions` section, so every conversation is saved and `/resume` can reopen it. `--skills yes` writes `skillsDir` and creates the folder (`skills/`, or `.mm/skills/` with `--project yes`); add your skills there (see [How to add a skill](add-a-skill.md)). |
| 84 | -- **An OpenAI-compatible service (OpenAI, Cerebras, Hugging Face…).** Choose `openai`: two more questions follow, the endpoint (`https://api.openai.com/v1` by default) and the name of the variable that holds the API key (`OPENAI_API_KEY` by default, `CEREBRAS_API_KEY`, `HF_TOKEN`…). Export the key before running `mm init`: with it, the model question lists the service's models; without it, you type the model's ID (the question says the variable is not set). Flags: `--provider openai --base-url https://api.cerebras.ai/v1 --api-key-env CEREBRAS_API_KEY`. The file gets `baseUrl` and `apiKeyEnv`, and a commented `reasoning_effort: none` in `sampling`, to uncomment if the API answers "Function tools with reasoning_effort are not supported". | |
| 84 | +- **An OpenAI-compatible service (OpenAI, Cerebras, Hugging Face…).** Choose `openai`: two more questions follow, the endpoint (`https://api.openai.com/v1` by default) and the name of the variable that holds the API key (`OPENAI_API_KEY` by default, `CEREBRAS_API_KEY`, `HF_TOKEN`…). Export the key before running `mm init`: with it, the model question lists the service's models; without it, you type the model's ID (the question says the variable is not set). Flags: `--provider openai --base-url https://api.cerebras.ai/v1 --api-key-env CEREBRAS_API_KEY`. The file gets `baseUrl` and `apiKeyEnv`, and a commented `reasoning_effort: none` in `sampling`, to uncomment if the API answers "Function tools with reasoning_effort are not supported". For an OpenAI reasoning model that must keep reasoning while it calls tools, choose `openai-responses` instead: the same questions, and the file talks to the Responses API (see [How to keep reasoning and tools together with OpenAI's Responses API](use-the-openai-responses-api.md)). | |
| 85 | 85 | - **A server elsewhere.** `--base-url http://192.168.1.20:17434/v1`; it is written into the file as `baseUrl`. Without it, the file has no `baseUrl` and records the provider's default address and fallback as comments, ready to uncomment. |
| 86 | 86 | - **A server that does not answer.** mm says so and asks for the model's name: the settings then come from the family table only. |
| 87 | 87 | - **An existing file.** mm asks `Overwrite agent.yaml?`, and `no` is the default: it then asks for another file. A file named with `-o` is asked about first, a file typed in the wizard right after it. With `--yes`, or when the input ends, nothing is overwritten: mm says so and stops. |
| @@ -81,7 +81,7 @@ This guide shows how to write a new agent.yaml for a model and a job, with mm's | |||
| 81 | - **See the file without writing it.** `-o -` prints it on stdout. Nothing is created, not even the `.mm` or skills folder. | 81 | - **See the file without writing it.** `-o -` prints it on stdout. Nothing is created, not even the `.mm` or skills folder. |
| 82 | - **Everything in a `.mm` folder.** Answer `yes` to the first question, or give `--project yes`: mm creates `.mm/` and writes `.mm/agent.yaml`, its paths written from the project root. Started from that root, `mm` and `mm tui` find it with no argument. See [How to keep a project's mini-me files in a `.mm` folder](keep-the-config-in-a-mm-folder.md). | 82 | - **Everything in a `.mm` folder.** Answer `yes` to the first question, or give `--project yes`: mm creates `.mm/` and writes `.mm/agent.yaml`, its paths written from the project root. Started from that root, `mm` and `mm tui` find it with no argument. See [How to keep a project's mini-me files in a `.mm` folder](keep-the-config-in-a-mm-folder.md). |
| 83 | - **Sessions and skills.** `--sessions yes` writes a `sessions` section, so every conversation is saved and `/resume` can reopen it. `--skills yes` writes `skillsDir` and creates the folder (`skills/`, or `.mm/skills/` with `--project yes`); add your skills there (see [How to add a skill](add-a-skill.md)). | 83 | - **Sessions and skills.** `--sessions yes` writes a `sessions` section, so every conversation is saved and `/resume` can reopen it. `--skills yes` writes `skillsDir` and creates the folder (`skills/`, or `.mm/skills/` with `--project yes`); add your skills there (see [How to add a skill](add-a-skill.md)). |
| 84 | -- **An OpenAI-compatible service (OpenAI, Cerebras, Hugging Face…).** Choose `openai`: two more questions follow, the endpoint (`https://api.openai.com/v1` by default) and the name of the variable that holds the API key (`OPENAI_API_KEY` by default, `CEREBRAS_API_KEY`, `HF_TOKEN`…). Export the key before running `mm init`: with it, the model question lists the service's models; without it, you type the model's ID (the question says the variable is not set). Flags: `--provider openai --base-url https://api.cerebras.ai/v1 --api-key-env CEREBRAS_API_KEY`. The file gets `baseUrl` and `apiKeyEnv`, and a commented `reasoning_effort: none` in `sampling`, to uncomment if the API answers "Function tools with reasoning_effort are not supported". | 84 | +- **An OpenAI-compatible service (OpenAI, Cerebras, Hugging Face…).** Choose `openai`: two more questions follow, the endpoint (`https://api.openai.com/v1` by default) and the name of the variable that holds the API key (`OPENAI_API_KEY` by default, `CEREBRAS_API_KEY`, `HF_TOKEN`…). Export the key before running `mm init`: with it, the model question lists the service's models; without it, you type the model's ID (the question says the variable is not set). Flags: `--provider openai --base-url https://api.cerebras.ai/v1 --api-key-env CEREBRAS_API_KEY`. The file gets `baseUrl` and `apiKeyEnv`, and a commented `reasoning_effort: none` in `sampling`, to uncomment if the API answers "Function tools with reasoning_effort are not supported". For an OpenAI reasoning model that must keep reasoning while it calls tools, choose `openai-responses` instead: the same questions, and the file talks to the Responses API (see [How to keep reasoning and tools together with OpenAI's Responses API](use-the-openai-responses-api.md)). |
| 85 | - **A server elsewhere.** `--base-url http://192.168.1.20:17434/v1`; it is written into the file as `baseUrl`. Without it, the file has no `baseUrl` and records the provider's default address and fallback as comments, ready to uncomment. | 85 | - **A server elsewhere.** `--base-url http://192.168.1.20:17434/v1`; it is written into the file as `baseUrl`. Without it, the file has no `baseUrl` and records the provider's default address and fallback as comments, ready to uncomment. |
| 86 | - **A server that does not answer.** mm says so and asks for the model's name: the settings then come from the family table only. | 86 | - **A server that does not answer.** mm says so and asks for the model's name: the settings then come from the family table only. |
| 87 | - **An existing file.** mm asks `Overwrite agent.yaml?`, and `no` is the default: it then asks for another file. A file named with `-o` is asked about first, a file typed in the wizard right after it. With `--yes`, or when the input ends, nothing is overwritten: mm says so and stops. | 87 | - **An existing file.** mm asks `Overwrite agent.yaml?`, and `no` is the default: it then asks for another file. A file named with `-o` is asked about first, a file typed in the wizard right after it. With `--yes`, or when the input ends, nothing is overwritten: mm says so and stops. |
modified
docs/en/how-to/run-with-an-openai-compatible-server.md +1 -1 | @@ -34,7 +34,7 @@ This guide shows how to run mini-me on a model server that has no dedicated prov | ||
| 34 | 34 | ## Variants |
| 35 | 35 | |
| 36 | 36 | - **The OpenAI API.** No `baseUrl`, `OPENAI_API_KEY` exported, a model such as `gpt-5-mini`. Its reasoning models accept only the default temperature and take `max_completion_tokens` instead of `max_tokens`: write `temperature: 1.0` and `max_completion_tokens` in `sampling`. With `provider: openai` mm sends that block as written, without its own defaults (`top_p`, `max_tokens`), so remove a key the API still refuses and nothing else gets in the way. `mm init` writes such a block. (The request's content was checked against a local server; no call to the OpenAI API was made in this repository.) |
| 37 | -- **"Function tools with reasoning_effort are not supported".** Some OpenAI models (seen: `gpt-6-luna`) refuse tools on `/v1/chat/completions` while they reason; mm uses that route and always sends tools. Add `reasoning_effort: none` to `sampling` (it turns the reasoning off). Not verified in this repository: reported by a user. | |
| 37 | +- **"Function tools with reasoning_effort are not supported".** Some OpenAI models (seen: `gpt-6-luna`) refuse tools on `/v1/chat/completions` while they reason; mm uses that route and always sends tools. Use `provider: openai-responses`, which speaks the Responses API and keeps the reasoning with the tools: see [How to keep reasoning and tools together with OpenAI's Responses API](use-the-openai-responses-api.md). Or add `reasoning_effort: none` to `sampling` (it turns the reasoning off). The error was reported by a user, not reproduced in this repository. | |
| 38 | 38 | - **The key is refused.** The start-up warning says `openai: <baseUrl> refused the key (HTTP 401) — export OPENAI_API_KEY`. |
| 39 | 39 | - **Nothing answers.** The warning says `openai: nothing answers at <baseUrl> — check baseUrl: …`: the address must be the OpenAI-compatible one, usually ending in `/v1`. |
| 40 | 40 | - **A server mm has a provider for.** Prefer it (`dmr`, `llamacpp`, `llmman`, `ollama`): those know how the server reads a long prompt, turns reasoning off for a summary, unloads a model, and tell the window size. The generic provider does none of that. |
| @@ -34,7 +34,7 @@ This guide shows how to run mini-me on a model server that has no dedicated prov | |||
| 34 | ## Variants | 34 | ## Variants |
| 35 | 35 | ||
| 36 | - **The OpenAI API.** No `baseUrl`, `OPENAI_API_KEY` exported, a model such as `gpt-5-mini`. Its reasoning models accept only the default temperature and take `max_completion_tokens` instead of `max_tokens`: write `temperature: 1.0` and `max_completion_tokens` in `sampling`. With `provider: openai` mm sends that block as written, without its own defaults (`top_p`, `max_tokens`), so remove a key the API still refuses and nothing else gets in the way. `mm init` writes such a block. (The request's content was checked against a local server; no call to the OpenAI API was made in this repository.) | 36 | - **The OpenAI API.** No `baseUrl`, `OPENAI_API_KEY` exported, a model such as `gpt-5-mini`. Its reasoning models accept only the default temperature and take `max_completion_tokens` instead of `max_tokens`: write `temperature: 1.0` and `max_completion_tokens` in `sampling`. With `provider: openai` mm sends that block as written, without its own defaults (`top_p`, `max_tokens`), so remove a key the API still refuses and nothing else gets in the way. `mm init` writes such a block. (The request's content was checked against a local server; no call to the OpenAI API was made in this repository.) |
| 37 | -- **"Function tools with reasoning_effort are not supported".** Some OpenAI models (seen: `gpt-6-luna`) refuse tools on `/v1/chat/completions` while they reason; mm uses that route and always sends tools. Add `reasoning_effort: none` to `sampling` (it turns the reasoning off). Not verified in this repository: reported by a user. | 37 | +- **"Function tools with reasoning_effort are not supported".** Some OpenAI models (seen: `gpt-6-luna`) refuse tools on `/v1/chat/completions` while they reason; mm uses that route and always sends tools. Use `provider: openai-responses`, which speaks the Responses API and keeps the reasoning with the tools: see [How to keep reasoning and tools together with OpenAI's Responses API](use-the-openai-responses-api.md). Or add `reasoning_effort: none` to `sampling` (it turns the reasoning off). The error was reported by a user, not reproduced in this repository. |
| 38 | - **The key is refused.** The start-up warning says `openai: <baseUrl> refused the key (HTTP 401) — export OPENAI_API_KEY`. | 38 | - **The key is refused.** The start-up warning says `openai: <baseUrl> refused the key (HTTP 401) — export OPENAI_API_KEY`. |
| 39 | - **Nothing answers.** The warning says `openai: nothing answers at <baseUrl> — check baseUrl: …`: the address must be the OpenAI-compatible one, usually ending in `/v1`. | 39 | - **Nothing answers.** The warning says `openai: nothing answers at <baseUrl> — check baseUrl: …`: the address must be the OpenAI-compatible one, usually ending in `/v1`. |
| 40 | - **A server mm has a provider for.** Prefer it (`dmr`, `llamacpp`, `llmman`, `ollama`): those know how the server reads a long prompt, turns reasoning off for a summary, unloads a model, and tell the window size. The generic provider does none of that. | 40 | - **A server mm has a provider for.** Prefer it (`dmr`, `llamacpp`, `llmman`, `ollama`): those know how the server reads a long prompt, turns reasoning off for a summary, unloads a model, and tell the window size. The generic provider does none of that. |
added
docs/en/how-to/use-the-openai-responses-api.md +59 -0 | new file mode 100644 | ||
| @@ -0,0 +1,59 @@ | ||
| 1 | +# How to keep reasoning and tools together with OpenAI's Responses API | |
| 2 | + | |
| 3 | +This guide shows how to run mini-me on an OpenAI reasoning model that refuses tools on Chat Completions while it reasons — seen with `gpt-6-luna`: | |
| 4 | + | |
| 5 | +```text | |
| 6 | +Function tools with reasoning_effort are not supported for gpt-6-luna in /v1/chat/completions. | |
| 7 | +To use function tools, use /v1/responses or set reasoning_effort to 'none'. | |
| 8 | +``` | |
| 9 | + | |
| 10 | +An mm agent always sends tools. `reasoning_effort: none` makes the `openai` provider work, but the model no longer reasons. The `openai-responses` provider speaks the Responses API (`POST /v1/responses`) instead, and keeps both. It assumes an OpenAI API key and a model that serves `/v1/responses`. | |
| 11 | + | |
| 12 | +## Steps | |
| 13 | + | |
| 14 | +1. Write the agent file with `provider: openai-responses`: | |
| 15 | + | |
| 16 | + ```yaml | |
| 17 | + provider: openai-responses | |
| 18 | + model: gpt-6-luna | |
| 19 | + contextWindow: 400000 # this provider cannot ask the server for its window | |
| 20 | + sampling: | |
| 21 | + reasoning_effort: medium # sent as reasoning.effort | |
| 22 | + max_completion_tokens: 16000 # sent as max_output_tokens | |
| 23 | + ``` | |
| 24 | + | |
| 25 | + No `baseUrl`: the default is the OpenAI API, `https://api.openai.com/v1`. | |
| 26 | + | |
| 27 | +2. Export the key — it never goes in the YAML: | |
| 28 | + | |
| 29 | + ```bash | |
| 30 | + export OPENAI_API_KEY=sk-… | |
| 31 | + ``` | |
| 32 | + | |
| 33 | + Another variable name: `apiKeyEnv: MY_KEY`. | |
| 34 | + | |
| 35 | +3. Start mm as usual (`mm`, `mm tui`, `mm acp`, `mm -p "…"`). The model's reasoning summary, when the API streams one, shows as thoughts (`💭`, with `showThinking: true`); the tool calls run as with every other provider. | |
| 36 | + | |
| 37 | +`mm init` writes such a file: choose `openai-responses`, then the endpoint and the key's variable (or `--provider openai-responses`). | |
| 38 | + | |
| 39 | +## What the provider sends | |
| 40 | + | |
| 41 | +- **The `sampling:` block as written**, without mm's defaults (`top_p`, `max_tokens`), like `provider: openai`. Two Chat Completions names are renamed for this API: `max_tokens` and `max_completion_tokens` become `max_output_tokens`, and `reasoning_effort` becomes `reasoning.effort`. Any other key goes as it is, so `reasoning: {summary: auto}` asks for the reasoning summary, for instance. | |
| 42 | +- **`store: false` and `include: ["reasoning.encrypted_content"]`.** Nothing is kept on OpenAI's side. The model's encrypted reasoning comes back with each answer, and mm sends it back with the tool results, so the model keeps its thread from one tool call to the next. It is also saved with the conversation when sessions are on. Write `store` or `include` in `sampling` to choose otherwise. | |
| 43 | +- **The tools as function tools**, not strict: mm's tool schemas have optional fields, which strict mode refuses. | |
| 44 | +- **`structuredOutput`** as `text.format` (`json_schema`, strict, as the `openai` provider sends it). | |
| 45 | +- **The summary of a compaction** with `reasoning.effort: none`, not streamed, with no tools. | |
| 46 | + | |
| 47 | +## Variants | |
| 48 | + | |
| 49 | +- **Another server.** Set `baseUrl` to its OpenAI-compatible address (ending in `/v1`); it must serve `POST /responses`. Which servers do — vLLM, Ollama, llama-server… — is not verified. If one refuses `include` or `store`, write them in `sampling` (`include: []`). | |
| 50 | +- **The key is refused.** The start-up warning says `openai-responses: <baseUrl> refused the key (HTTP 401) — export OPENAI_API_KEY`, and a failed question says `authentication failed … is $OPENAI_API_KEY set and valid?`. | |
| 51 | +- **No reasoning summary on screen.** The API sends a summary only when asked: `reasoning: {summary: auto}` in `sampling`. OpenAI may require a verified organisation for it. | |
| 52 | +- **Chat Completions is enough.** For a model that does not reason, or one served by vLLM, LM Studio or a gateway that only speaks Chat Completions, keep `provider: openai` — see [How to use any OpenAI-compatible server](run-with-an-openai-compatible-server.md). | |
| 53 | + | |
| 54 | +Checked against a fake `/v1/responses` server, in tests and with the built binary: the reasoning summary was shown, a `bash` call ran, and the encrypted reasoning and the tool's output went back with the call's `call_id`. No call to the OpenAI API was made in this repository. | |
| 55 | + | |
| 56 | +## See also | |
| 57 | + | |
| 58 | +- [Configuration reference — provider defaults](../reference/configuration.md#provider-defaults) | |
| 59 | +- [Providers — explanation](../explanation/providers.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,59 @@ | |||
| 1 | +# How to keep reasoning and tools together with OpenAI's Responses API | ||
| 2 | + | ||
| 3 | +This guide shows how to run mini-me on an OpenAI reasoning model that refuses tools on Chat Completions while it reasons — seen with `gpt-6-luna`: | ||
| 4 | + | ||
| 5 | +```text | ||
| 6 | +Function tools with reasoning_effort are not supported for gpt-6-luna in /v1/chat/completions. | ||
| 7 | +To use function tools, use /v1/responses or set reasoning_effort to 'none'. | ||
| 8 | +``` | ||
| 9 | + | ||
| 10 | +An mm agent always sends tools. `reasoning_effort: none` makes the `openai` provider work, but the model no longer reasons. The `openai-responses` provider speaks the Responses API (`POST /v1/responses`) instead, and keeps both. It assumes an OpenAI API key and a model that serves `/v1/responses`. | ||
| 11 | + | ||
| 12 | +## Steps | ||
| 13 | + | ||
| 14 | +1. Write the agent file with `provider: openai-responses`: | ||
| 15 | + | ||
| 16 | + ```yaml | ||
| 17 | + provider: openai-responses | ||
| 18 | + model: gpt-6-luna | ||
| 19 | + contextWindow: 400000 # this provider cannot ask the server for its window | ||
| 20 | + sampling: | ||
| 21 | + reasoning_effort: medium # sent as reasoning.effort | ||
| 22 | + max_completion_tokens: 16000 # sent as max_output_tokens | ||
| 23 | + ``` | ||
| 24 | + | ||
| 25 | + No `baseUrl`: the default is the OpenAI API, `https://api.openai.com/v1`. | ||
| 26 | + | ||
| 27 | +2. Export the key — it never goes in the YAML: | ||
| 28 | + | ||
| 29 | + ```bash | ||
| 30 | + export OPENAI_API_KEY=sk-… | ||
| 31 | + ``` | ||
| 32 | + | ||
| 33 | + Another variable name: `apiKeyEnv: MY_KEY`. | ||
| 34 | + | ||
| 35 | +3. Start mm as usual (`mm`, `mm tui`, `mm acp`, `mm -p "…"`). The model's reasoning summary, when the API streams one, shows as thoughts (`💭`, with `showThinking: true`); the tool calls run as with every other provider. | ||
| 36 | + | ||
| 37 | +`mm init` writes such a file: choose `openai-responses`, then the endpoint and the key's variable (or `--provider openai-responses`). | ||
| 38 | + | ||
| 39 | +## What the provider sends | ||
| 40 | + | ||
| 41 | +- **The `sampling:` block as written**, without mm's defaults (`top_p`, `max_tokens`), like `provider: openai`. Two Chat Completions names are renamed for this API: `max_tokens` and `max_completion_tokens` become `max_output_tokens`, and `reasoning_effort` becomes `reasoning.effort`. Any other key goes as it is, so `reasoning: {summary: auto}` asks for the reasoning summary, for instance. | ||
| 42 | +- **`store: false` and `include: ["reasoning.encrypted_content"]`.** Nothing is kept on OpenAI's side. The model's encrypted reasoning comes back with each answer, and mm sends it back with the tool results, so the model keeps its thread from one tool call to the next. It is also saved with the conversation when sessions are on. Write `store` or `include` in `sampling` to choose otherwise. | ||
| 43 | +- **The tools as function tools**, not strict: mm's tool schemas have optional fields, which strict mode refuses. | ||
| 44 | +- **`structuredOutput`** as `text.format` (`json_schema`, strict, as the `openai` provider sends it). | ||
| 45 | +- **The summary of a compaction** with `reasoning.effort: none`, not streamed, with no tools. | ||
| 46 | + | ||
| 47 | +## Variants | ||
| 48 | + | ||
| 49 | +- **Another server.** Set `baseUrl` to its OpenAI-compatible address (ending in `/v1`); it must serve `POST /responses`. Which servers do — vLLM, Ollama, llama-server… — is not verified. If one refuses `include` or `store`, write them in `sampling` (`include: []`). | ||
| 50 | +- **The key is refused.** The start-up warning says `openai-responses: <baseUrl> refused the key (HTTP 401) — export OPENAI_API_KEY`, and a failed question says `authentication failed … is $OPENAI_API_KEY set and valid?`. | ||
| 51 | +- **No reasoning summary on screen.** The API sends a summary only when asked: `reasoning: {summary: auto}` in `sampling`. OpenAI may require a verified organisation for it. | ||
| 52 | +- **Chat Completions is enough.** For a model that does not reason, or one served by vLLM, LM Studio or a gateway that only speaks Chat Completions, keep `provider: openai` — see [How to use any OpenAI-compatible server](run-with-an-openai-compatible-server.md). | ||
| 53 | + | ||
| 54 | +Checked against a fake `/v1/responses` server, in tests and with the built binary: the reasoning summary was shown, a `bash` call ran, and the encrypted reasoning and the tool's output went back with the call's `call_id`. No call to the OpenAI API was made in this repository. | ||
| 55 | + | ||
| 56 | +## See also | ||
| 57 | + | ||
| 58 | +- [Configuration reference — provider defaults](../reference/configuration.md#provider-defaults) | ||
| 59 | +- [Providers — explanation](../explanation/providers.md) | ||
modified
docs/en/reference/cli.md +3 -3 | @@ -239,9 +239,9 @@ An agent file outside the workspace only gives a warning: see [when the agent fi | ||
| 239 | 239 | | Flag | Question when absent | Default | |
| 240 | 240 | |------|----------------------|---------| |
| 241 | 241 | | `--project yes\|no` | Keep everything in a `.mm` folder? — asked first. `yes`: the file is `.mm/agent.yaml` (the folder is created), its paths are written from the project root (`skillsDir: .mm/skills`), and `mm` / `mm tui` started there find it with no argument | `no` | |
| 242 | -| `--provider` | Model server: `llamacpp`, `llmman`, `ollama`, `dmr`, `kronk`, `openai` | the first local one whose server answers, in that order (`llamacpp` on 9931, then 8080), else `llamacpp` (`openai` is never probed: its default address is the OpenAI API) | | |
| 243 | -| `--base-url` | `openai` only: Endpoint — the service's OpenAI-compatible address (OpenAI, Cerebras, Hugging Face…); for the other providers, not asked | `https://api.openai.com/v1` for `openai`; otherwise `AGENT_BASE_URL` when set, else the first of the provider's local addresses whose model list answers — its default, then the same with `127.0.0.1` when the default names `localhost`, then for `llamacpp` llama-server's former port, `http://127.0.0.1:8080/v1` — and its container fallback (`host.docker.internal`) only when none does. The model question names the address its list comes from (`Model? (listed from …)`). Written as `baseUrl` unless it is the default | | |
| 244 | -| `--api-key-env` | `openai` only: Environment variable that holds the API key | `OPENAI_API_KEY`. Written as `apiKeyEnv` unless it is the default | | |
| 242 | +| `--provider` | Model server: `llamacpp`, `llmman`, `ollama`, `dmr`, `kronk`, `openai`, `openai-responses` | the first local one whose server answers, in that order (`llamacpp` on 9931, then 8080), else `llamacpp` (`openai` and `openai-responses` are never probed: their default address is the OpenAI API) | | |
| 243 | +| `--base-url` | `openai` and `openai-responses` only: Endpoint — the service's OpenAI-compatible address (OpenAI, Cerebras, Hugging Face…); for the other providers, not asked | `https://api.openai.com/v1` for `openai` and `openai-responses`; otherwise `AGENT_BASE_URL` when set, else the first of the provider's local addresses whose model list answers — its default, then the same with `127.0.0.1` when the default names `localhost`, then for `llamacpp` llama-server's former port, `http://127.0.0.1:8080/v1` — and its container fallback (`host.docker.internal`) only when none does. The model question names the address its list comes from (`Model? (listed from …)`). Written as `baseUrl` unless it is the default | | |
| 244 | +| `--api-key-env` | `openai` and `openai-responses` only: Environment variable that holds the API key | `OPENAI_API_KEY`. Written as `apiKeyEnv` unless it is the default | | |
| 245 | 245 | | `--model` | Model: a list of the server's models (`/api/tags` for llmman and Ollama, `/models` for the others; 5 s for a local server, 20 s for `openai`), or a name to type when there is no list — the question says why (`<VARIABLE> is not set: no list`, or the server's error). For `openai` the list is asked with the key read from the variable named above, and not asked at all when that variable is empty | the first of the list | |
| 246 | 246 | | `--family` | Model family | detected from the model's name, then from the server's family name | |
| 247 | 247 | | `--usage` | What the agent is for: `developer`, `reviewer`, `translator`, `writer`, `assistant`, `researcher`, `docs`, `json`, `coordinator` | `developer` | |
| @@ -239,9 +239,9 @@ An agent file outside the workspace only gives a warning: see [when the agent fi | |||
| 239 | | Flag | Question when absent | Default | | 239 | | Flag | Question when absent | Default | |
| 240 | |------|----------------------|---------| | 240 | |------|----------------------|---------| |
| 241 | | `--project yes\|no` | Keep everything in a `.mm` folder? — asked first. `yes`: the file is `.mm/agent.yaml` (the folder is created), its paths are written from the project root (`skillsDir: .mm/skills`), and `mm` / `mm tui` started there find it with no argument | `no` | | 241 | | `--project yes\|no` | Keep everything in a `.mm` folder? — asked first. `yes`: the file is `.mm/agent.yaml` (the folder is created), its paths are written from the project root (`skillsDir: .mm/skills`), and `mm` / `mm tui` started there find it with no argument | `no` | |
| 242 | -| `--provider` | Model server: `llamacpp`, `llmman`, `ollama`, `dmr`, `kronk`, `openai` | the first local one whose server answers, in that order (`llamacpp` on 9931, then 8080), else `llamacpp` (`openai` is never probed: its default address is the OpenAI API) | | 242 | +| `--provider` | Model server: `llamacpp`, `llmman`, `ollama`, `dmr`, `kronk`, `openai`, `openai-responses` | the first local one whose server answers, in that order (`llamacpp` on 9931, then 8080), else `llamacpp` (`openai` and `openai-responses` are never probed: their default address is the OpenAI API) | |
| 243 | -| `--base-url` | `openai` only: Endpoint — the service's OpenAI-compatible address (OpenAI, Cerebras, Hugging Face…); for the other providers, not asked | `https://api.openai.com/v1` for `openai`; otherwise `AGENT_BASE_URL` when set, else the first of the provider's local addresses whose model list answers — its default, then the same with `127.0.0.1` when the default names `localhost`, then for `llamacpp` llama-server's former port, `http://127.0.0.1:8080/v1` — and its container fallback (`host.docker.internal`) only when none does. The model question names the address its list comes from (`Model? (listed from …)`). Written as `baseUrl` unless it is the default | | 243 | +| `--base-url` | `openai` and `openai-responses` only: Endpoint — the service's OpenAI-compatible address (OpenAI, Cerebras, Hugging Face…); for the other providers, not asked | `https://api.openai.com/v1` for `openai` and `openai-responses`; otherwise `AGENT_BASE_URL` when set, else the first of the provider's local addresses whose model list answers — its default, then the same with `127.0.0.1` when the default names `localhost`, then for `llamacpp` llama-server's former port, `http://127.0.0.1:8080/v1` — and its container fallback (`host.docker.internal`) only when none does. The model question names the address its list comes from (`Model? (listed from …)`). Written as `baseUrl` unless it is the default | |
| 244 | -| `--api-key-env` | `openai` only: Environment variable that holds the API key | `OPENAI_API_KEY`. Written as `apiKeyEnv` unless it is the default | | 244 | +| `--api-key-env` | `openai` and `openai-responses` only: Environment variable that holds the API key | `OPENAI_API_KEY`. Written as `apiKeyEnv` unless it is the default | |
| 245 | | `--model` | Model: a list of the server's models (`/api/tags` for llmman and Ollama, `/models` for the others; 5 s for a local server, 20 s for `openai`), or a name to type when there is no list — the question says why (`<VARIABLE> is not set: no list`, or the server's error). For `openai` the list is asked with the key read from the variable named above, and not asked at all when that variable is empty | the first of the list | | 245 | | `--model` | Model: a list of the server's models (`/api/tags` for llmman and Ollama, `/models` for the others; 5 s for a local server, 20 s for `openai`), or a name to type when there is no list — the question says why (`<VARIABLE> is not set: no list`, or the server's error). For `openai` the list is asked with the key read from the variable named above, and not asked at all when that variable is empty | the first of the list | |
| 246 | | `--family` | Model family | detected from the model's name, then from the server's family name | | 246 | | `--family` | Model family | detected from the model's name, then from the server's family name | |
| 247 | | `--usage` | What the agent is for: `developer`, `reviewer`, `translator`, `writer`, `assistant`, `researcher`, `docs`, `json`, `coordinator` | `developer` | | 247 | | `--usage` | What the agent is for: `developer`, `reviewer`, `translator`, `writer`, `assistant`, `researcher`, `docs`, `json`, `coordinator` | `developer` | |
modified
docs/en/reference/configuration.md +7 -3 | @@ -8,7 +8,7 @@ Where `mm` looks for this file: [Configuration file resolution](cli.md#configura | ||
| 8 | 8 | |
| 9 | 9 | | Key | Type | Default | Description | |
| 10 | 10 | |-----|------|---------|-------------| |
| 11 | -| `provider` | string | `dmr` | Registry key of the LLM server: `dmr`, `llamacpp`, `llmman`, `ollama`, `kronk`, or `openai` for any other OpenAI-compatible server (see [How to use any OpenAI-compatible server](../how-to/run-with-an-openai-compatible-server.md)). Overridden by `AGENT_PROVIDER`. | | |
| 11 | +| `provider` | string | `dmr` | Registry key of the LLM server: `dmr`, `llamacpp`, `llmman`, `ollama`, `kronk`, `openai` for any other OpenAI-compatible server (see [How to use any OpenAI-compatible server](../how-to/run-with-an-openai-compatible-server.md)), or `openai-responses` for the same servers through OpenAI's Responses API (see [How to keep reasoning and tools together with OpenAI's Responses API](../how-to/use-the-openai-responses-api.md)). Overridden by `AGENT_PROVIDER`. | | |
| 12 | 12 | | `model` | string | `huggingface.co/jetbrains/mellum2-12b-a2.5b-instruct-gguf-q4_k_m:Q4_K_M` | Model identifier in the provider's naming. Overridden by `AGENT_MODEL`. | |
| 13 | 13 | | `baseUrl` | string | `""` (provider default) | OpenAI-compatible endpoint tried first. Overridden by `AGENT_BASE_URL`. | |
| 14 | 14 | | `fallback` | string or absent | absent (provider default) | Endpoint used when `baseUrl` does not answer `/models` within 2 s. Absent = provider default; `""` = no fallback. | |
| @@ -36,7 +36,7 @@ Where `mm` looks for this file: [Configuration file resolution](cli.md#configura | ||
| 36 | 36 | | `saveAnswerTool` | bool | `false` | Declare `save_answer`, which writes an answer the model already gave to a new file: the model sends a file name, not the text again. Off by default. The `/save` command exists either way. See [tools](tools.md#save_answer). | |
| 37 | 37 | | `unloadModels` | bool | `true` | The `/unload [model]` command (terminal, window, editor) and the `unload_model` tool, which free a model from the server's memory: llmman and Ollama, Kronk, llama-server in router mode. `false` removes both. The tool is never declared beside a `structuredOutput` or a `decision` block. See [tools](tools.md#unload_model) and [How to free a model's memory](../how-to/unload-a-model.md). | |
| 38 | 38 | | `autoPull` | bool | `false` | At start-up, download the models this agent will use and the server does not list: its own, its `mmConfigs` agents', its `skillRouting` / `toolRouting` deciders'. The progress goes to stderr — one line rewritten in place on a terminal (`⬇ pulling <model> — 52 MB / 145 MB (35 %)`), a line per tenth elsewhere — then `⬇ pulled <model> in 0.8s`. The agent's own model failing stops `mm` with the server's message (`[engine error: autoPull: <model>: the server says: …]`); another model failing, a server that does not answer, or a provider that cannot pull is a `[warning: autoPull: …]`. An agent started by `/ask` or `ask_agent` pulls nothing; `mm --ask` pulls nothing either. A model the server already lists is never pulled (a name without a tag also matches its `:latest` entry). By provider: `llmman` and `ollama` — `POST /api/pull`; `kronk` — `POST /v1/kronk/models/pull`, the pull counting as done only when Kronk's stream ends with `"downloaded": true` (Kronk answers 200 to a failed pull; its last status is then the message); `dmr` — `POST /models/create` on the runner (the base URL without `/engines/…`), the pull counting as done once the runner lists the model; `llamacpp` — no download over the API: the warning says to start llama-server with `-hf <repo>:<quant>`, or to put the GGUF in the router's models directory; `openai` — a warning. | |
| 39 | -| `sampling` | map | `temperature: 0.0`, `top_p: 0.9`, `max_tokens: 4096` | Generation settings, OpenAI API key names, passed to the server. The file's block is merged with these defaults: a default the file does not name is still sent. **Except with `provider: openai`**: the request carries exactly the file's block, nothing added (no block: no sampling key, the server's defaults apply) — the hosted OpenAI reasoning models refuse `max_tokens` and accept only the default temperature, so a default left in would be a 400. A key the OpenAI API does not declare is sent as it is, at the top level of the request — for example `chat_template_kwargs: {enable_thinking: false}`, which tells a llama.cpp server (`dmr`, `llamacpp`, `llmman`) or Kronk not to reason; `reasoning_effort: none` does the same on Ollama. `messages`, `tools`, `tool_choice` (and the legacy `functions`, `function_call`) are ignored: Genkit builds them from the conversation. The shipped `agent.yaml` adds `parallel_tool_calls: false`. `max_tokens` also bounds one tool call: a `write_file` of a long document (or a thinking model's reasoning plus the call) can hit it, and the call is then cut off. mm hands it back to the model twice, asking for smaller pieces, then stops with `the model hit max_tokens (N) while writing a tool call`; raise the value if that happens. A config that names the limit `max_completion_tokens` (the OpenAI API's name for its newer models) is read the same way: that name is used in this message and for the summary request of the context compression. With streaming, mm also asks the server for token counts (`stream_options.include_usage`). | | |
| 39 | +| `sampling` | map | `temperature: 0.0`, `top_p: 0.9`, `max_tokens: 4096` | Generation settings, OpenAI API key names, passed to the server. The file's block is merged with these defaults: a default the file does not name is still sent. **Except with `provider: openai` and `provider: openai-responses`**: the request carries exactly the file's block, nothing added (no block: no sampling key, the server's defaults apply) — the hosted OpenAI reasoning models refuse `max_tokens` and accept only the default temperature, so a default left in would be a 400. A key the OpenAI API does not declare is sent as it is, at the top level of the request — for example `chat_template_kwargs: {enable_thinking: false}`, which tells a llama.cpp server (`dmr`, `llamacpp`, `llmman`) or Kronk not to reason; `reasoning_effort: none` does the same on Ollama. `messages`, `tools`, `tool_choice` (and the legacy `functions`, `function_call`) are ignored: Genkit builds them from the conversation. The shipped `agent.yaml` adds `parallel_tool_calls: false`. `max_tokens` also bounds one tool call: a `write_file` of a long document (or a thinking model's reasoning plus the call) can hit it, and the call is then cut off. mm hands it back to the model twice, asking for smaller pieces, then stops with `the model hit max_tokens (N) while writing a tool call`; raise the value if that happens. A config that names the limit `max_completion_tokens` (the OpenAI API's name for its newer models) is read the same way: that name is used in this message and for the summary request of the context compression. With streaming, mm also asks the server for token counts (`stream_options.include_usage`). | | |
| 40 | 40 | | `watchdogTimeout` | duration | `20s` | Silence tolerated between two streamed tokens before the connection is declared hung. Doubled for summary requests. | |
| 41 | 41 | | `firstTokenTimeout` | duration | `3m` | Silence tolerated before a model call's first token, while the server reads the prompt (every round trip of a turn has one). Never shorter than `watchdogTimeout`; must be >= 0. With a llama.cpp server (`dmr`, `llamacpp`, `llmman` — whose local GGUF models run in llama-server) mm asks for `return_progress`: each progress report restarts this clock, and the spinner shows `Reading the prompt 12.0k/25.3k tokens`. Ollama and Kronk send no progress: this one wait covers the whole prompt (and the model's loading). On a timeout the watchdog says `no first token from the server after …` (before the first token) or `connection hang detected after …` (after). | |
| 42 | 42 | | `bashTimeout` | duration | `30s` | How long one `bash` command may run before it is killed; the tool then answers `[error: <bashTimeout> timeout exceeded]`. Must be > 0. The watchdog keeps counting while a command runs (ticket 57): a command longer than `watchdogTimeout` ends the turn, so raise both together. | |
| @@ -202,11 +202,14 @@ tools: | ||
| 202 | 202 | | `ollama` | `http://localhost:11434/v1` | `http://host.docker.internal:11434/v1` | `OLLAMA_API_KEY` | no | |
| 203 | 203 | | `kronk` | `http://127.0.0.1:11435/v1` | `http://host.docker.internal:11435/v1` | `KRONK_TOKEN` | no — only Kronk's `authenticated` and `full-protected` modes check it | |
| 204 | 204 | | `openai` | `https://api.openai.com/v1` | none | `OPENAI_API_KEY` | no — a server that needs one answers 401, and the start-up warning names the variable | |
| 205 | +| `openai-responses` | `https://api.openai.com/v1` | none | `OPENAI_API_KEY` | no — as `openai` | | |
| 205 | 206 | |
| 206 | 207 | `llamacpp`: llama-server's default port is `9931` since llama.cpp b11521 (2026-10-09), `8080` before and in the official Docker images. When the address in use is `http://127.0.0.1:9931/v1` (no `baseUrl`, or that one) and it does not answer, mm tries `http://127.0.0.1:8080/v1`, then the `fallback`. |
| 207 | 208 | |
| 208 | 209 | The `openai` provider sends only standard fields: no `return_progress` (so no prompt-reading progress while a long prompt is read), no reasoning switch on a summary request, no `/unload`. It cannot ask the server for its window: set `contextWindow`, or compression counts messages (`context.maxMessages`). Its start-up probe sends the key to `GET /models`; a 401 or 403 is reported as a refused key, not as a server that does not answer. |
| 209 | 210 | |
| 211 | +The `openai-responses` provider (ticket 178) talks to the same servers through OpenAI's Responses API, `POST <baseUrl>/responses`, instead of Chat Completions: what OpenAI's reasoning models need to call tools while they reason. It sends the `sampling` block as written, with `max_tokens` / `max_completion_tokens` renamed `max_output_tokens` and `reasoning_effort` sent as `reasoning.effort`; it adds `store: false` and `include: ["reasoning.encrypted_content"]` unless the block sets them, and sends the model's encrypted reasoning back with the tool results. Its summary request sets `reasoning.effort: none`. Like `openai`: no prompt-reading progress, no `/unload`, the window from `contextWindow` only. See [How to keep reasoning and tools together with OpenAI's Responses API](../how-to/use-the-openai-responses-api.md). | |
| 212 | + | |
| 210 | 213 | ## `structuredOutput` |
| 211 | 214 | |
| 212 | 215 | A YAML block string holding Go declarations. Each `type` is a definition; the one `var` (`var X T` or `var X = T{}`) names the root of the answer. Only `type` and `var` declarations are allowed. |
| @@ -328,6 +331,7 @@ decision: | ||
| 328 | 331 | | `llmman` | yes | |
| 329 | 332 | | `ollama` | yes | |
| 330 | 333 | | `openai` | the server's own: a server without the route answers 404 | |
| 334 | +| `openai-responses` | no — refused at start-up | | |
| 331 | 335 | | `dmr` | no (404, Docker Model Runner v1.2.8) — refused at start-up | |
| 332 | 336 | |
| 333 | 337 | The route serves models it knows as decision models: LiquidAI d1 (`LiquidAI/d1-3B-GGUF:Q4_K_M`) was accepted by all three; evalengine's `decision-4b` was refused by llmman (`501 This model is not a decision model`) and Ollama (`400 … is not a llama.cpp decision model`). |
| @@ -470,7 +474,7 @@ Reported on stderr as `[config error: <path>: <message>]`, exit code 1 — in ev | ||
| 470 | 474 | | `mmConfigs: "with-context-x" is not a valid name (it would read as /ask-with-context-…)` | a name starting with `with-context` | |
| 471 | 475 | | `mmConfigs.<name>: the path must not be empty` | `<name>: ""`, or a long form without `path` | |
| 472 | 476 | | `hooks: unknown event "x" (…)`, `hooks.<event>[N]: …` | an invalid `hooks:` block — see [hooks](hooks.md#validation-errors) | |
| 473 | -| `unknown provider "x" (known: dmr, kronk, llamacpp, llmman, ollama, openai)` | Reported by the engine, as `[engine error: …]`. | | |
| 477 | +| `unknown provider "x" (known: dmr, kronk, llamacpp, llmman, ollama, openai, openai-responses)` | Reported by the engine, as `[engine error: …]`. | | |
| 474 | 478 | |
| 475 | 479 | A start-up warning, not an error, is printed when `context.enabled` is `true`, the window is unknown and `context.maxMessages` is `0`, and when a declared tool has the name of an MCP tool (`tools: <name> skipped — an MCP tool already has that name`; the tool is not declared), and when the file sets the deprecated `permissions` key (`permissions: ask is deprecated — use yolo: false instead …`). |
| 476 | 480 | |
| @@ -8,7 +8,7 @@ Where `mm` looks for this file: [Configuration file resolution](cli.md#configura | |||
| 8 | 8 | ||
| 9 | | Key | Type | Default | Description | | 9 | | Key | Type | Default | Description | |
| 10 | |-----|------|---------|-------------| | 10 | |-----|------|---------|-------------| |
| 11 | -| `provider` | string | `dmr` | Registry key of the LLM server: `dmr`, `llamacpp`, `llmman`, `ollama`, `kronk`, or `openai` for any other OpenAI-compatible server (see [How to use any OpenAI-compatible server](../how-to/run-with-an-openai-compatible-server.md)). Overridden by `AGENT_PROVIDER`. | | 11 | +| `provider` | string | `dmr` | Registry key of the LLM server: `dmr`, `llamacpp`, `llmman`, `ollama`, `kronk`, `openai` for any other OpenAI-compatible server (see [How to use any OpenAI-compatible server](../how-to/run-with-an-openai-compatible-server.md)), or `openai-responses` for the same servers through OpenAI's Responses API (see [How to keep reasoning and tools together with OpenAI's Responses API](../how-to/use-the-openai-responses-api.md)). Overridden by `AGENT_PROVIDER`. | |
| 12 | | `model` | string | `huggingface.co/jetbrains/mellum2-12b-a2.5b-instruct-gguf-q4_k_m:Q4_K_M` | Model identifier in the provider's naming. Overridden by `AGENT_MODEL`. | | 12 | | `model` | string | `huggingface.co/jetbrains/mellum2-12b-a2.5b-instruct-gguf-q4_k_m:Q4_K_M` | Model identifier in the provider's naming. Overridden by `AGENT_MODEL`. | |
| 13 | | `baseUrl` | string | `""` (provider default) | OpenAI-compatible endpoint tried first. Overridden by `AGENT_BASE_URL`. | | 13 | | `baseUrl` | string | `""` (provider default) | OpenAI-compatible endpoint tried first. Overridden by `AGENT_BASE_URL`. | |
| 14 | | `fallback` | string or absent | absent (provider default) | Endpoint used when `baseUrl` does not answer `/models` within 2 s. Absent = provider default; `""` = no fallback. | | 14 | | `fallback` | string or absent | absent (provider default) | Endpoint used when `baseUrl` does not answer `/models` within 2 s. Absent = provider default; `""` = no fallback. | |
| @@ -36,7 +36,7 @@ Where `mm` looks for this file: [Configuration file resolution](cli.md#configura | |||
| 36 | | `saveAnswerTool` | bool | `false` | Declare `save_answer`, which writes an answer the model already gave to a new file: the model sends a file name, not the text again. Off by default. The `/save` command exists either way. See [tools](tools.md#save_answer). | | 36 | | `saveAnswerTool` | bool | `false` | Declare `save_answer`, which writes an answer the model already gave to a new file: the model sends a file name, not the text again. Off by default. The `/save` command exists either way. See [tools](tools.md#save_answer). | |
| 37 | | `unloadModels` | bool | `true` | The `/unload [model]` command (terminal, window, editor) and the `unload_model` tool, which free a model from the server's memory: llmman and Ollama, Kronk, llama-server in router mode. `false` removes both. The tool is never declared beside a `structuredOutput` or a `decision` block. See [tools](tools.md#unload_model) and [How to free a model's memory](../how-to/unload-a-model.md). | | 37 | | `unloadModels` | bool | `true` | The `/unload [model]` command (terminal, window, editor) and the `unload_model` tool, which free a model from the server's memory: llmman and Ollama, Kronk, llama-server in router mode. `false` removes both. The tool is never declared beside a `structuredOutput` or a `decision` block. See [tools](tools.md#unload_model) and [How to free a model's memory](../how-to/unload-a-model.md). | |
| 38 | | `autoPull` | bool | `false` | At start-up, download the models this agent will use and the server does not list: its own, its `mmConfigs` agents', its `skillRouting` / `toolRouting` deciders'. The progress goes to stderr — one line rewritten in place on a terminal (`⬇ pulling <model> — 52 MB / 145 MB (35 %)`), a line per tenth elsewhere — then `⬇ pulled <model> in 0.8s`. The agent's own model failing stops `mm` with the server's message (`[engine error: autoPull: <model>: the server says: …]`); another model failing, a server that does not answer, or a provider that cannot pull is a `[warning: autoPull: …]`. An agent started by `/ask` or `ask_agent` pulls nothing; `mm --ask` pulls nothing either. A model the server already lists is never pulled (a name without a tag also matches its `:latest` entry). By provider: `llmman` and `ollama` — `POST /api/pull`; `kronk` — `POST /v1/kronk/models/pull`, the pull counting as done only when Kronk's stream ends with `"downloaded": true` (Kronk answers 200 to a failed pull; its last status is then the message); `dmr` — `POST /models/create` on the runner (the base URL without `/engines/…`), the pull counting as done once the runner lists the model; `llamacpp` — no download over the API: the warning says to start llama-server with `-hf <repo>:<quant>`, or to put the GGUF in the router's models directory; `openai` — a warning. | | 38 | | `autoPull` | bool | `false` | At start-up, download the models this agent will use and the server does not list: its own, its `mmConfigs` agents', its `skillRouting` / `toolRouting` deciders'. The progress goes to stderr — one line rewritten in place on a terminal (`⬇ pulling <model> — 52 MB / 145 MB (35 %)`), a line per tenth elsewhere — then `⬇ pulled <model> in 0.8s`. The agent's own model failing stops `mm` with the server's message (`[engine error: autoPull: <model>: the server says: …]`); another model failing, a server that does not answer, or a provider that cannot pull is a `[warning: autoPull: …]`. An agent started by `/ask` or `ask_agent` pulls nothing; `mm --ask` pulls nothing either. A model the server already lists is never pulled (a name without a tag also matches its `:latest` entry). By provider: `llmman` and `ollama` — `POST /api/pull`; `kronk` — `POST /v1/kronk/models/pull`, the pull counting as done only when Kronk's stream ends with `"downloaded": true` (Kronk answers 200 to a failed pull; its last status is then the message); `dmr` — `POST /models/create` on the runner (the base URL without `/engines/…`), the pull counting as done once the runner lists the model; `llamacpp` — no download over the API: the warning says to start llama-server with `-hf <repo>:<quant>`, or to put the GGUF in the router's models directory; `openai` — a warning. | |
| 39 | -| `sampling` | map | `temperature: 0.0`, `top_p: 0.9`, `max_tokens: 4096` | Generation settings, OpenAI API key names, passed to the server. The file's block is merged with these defaults: a default the file does not name is still sent. **Except with `provider: openai`**: the request carries exactly the file's block, nothing added (no block: no sampling key, the server's defaults apply) — the hosted OpenAI reasoning models refuse `max_tokens` and accept only the default temperature, so a default left in would be a 400. A key the OpenAI API does not declare is sent as it is, at the top level of the request — for example `chat_template_kwargs: {enable_thinking: false}`, which tells a llama.cpp server (`dmr`, `llamacpp`, `llmman`) or Kronk not to reason; `reasoning_effort: none` does the same on Ollama. `messages`, `tools`, `tool_choice` (and the legacy `functions`, `function_call`) are ignored: Genkit builds them from the conversation. The shipped `agent.yaml` adds `parallel_tool_calls: false`. `max_tokens` also bounds one tool call: a `write_file` of a long document (or a thinking model's reasoning plus the call) can hit it, and the call is then cut off. mm hands it back to the model twice, asking for smaller pieces, then stops with `the model hit max_tokens (N) while writing a tool call`; raise the value if that happens. A config that names the limit `max_completion_tokens` (the OpenAI API's name for its newer models) is read the same way: that name is used in this message and for the summary request of the context compression. With streaming, mm also asks the server for token counts (`stream_options.include_usage`). | | 39 | +| `sampling` | map | `temperature: 0.0`, `top_p: 0.9`, `max_tokens: 4096` | Generation settings, OpenAI API key names, passed to the server. The file's block is merged with these defaults: a default the file does not name is still sent. **Except with `provider: openai` and `provider: openai-responses`**: the request carries exactly the file's block, nothing added (no block: no sampling key, the server's defaults apply) — the hosted OpenAI reasoning models refuse `max_tokens` and accept only the default temperature, so a default left in would be a 400. A key the OpenAI API does not declare is sent as it is, at the top level of the request — for example `chat_template_kwargs: {enable_thinking: false}`, which tells a llama.cpp server (`dmr`, `llamacpp`, `llmman`) or Kronk not to reason; `reasoning_effort: none` does the same on Ollama. `messages`, `tools`, `tool_choice` (and the legacy `functions`, `function_call`) are ignored: Genkit builds them from the conversation. The shipped `agent.yaml` adds `parallel_tool_calls: false`. `max_tokens` also bounds one tool call: a `write_file` of a long document (or a thinking model's reasoning plus the call) can hit it, and the call is then cut off. mm hands it back to the model twice, asking for smaller pieces, then stops with `the model hit max_tokens (N) while writing a tool call`; raise the value if that happens. A config that names the limit `max_completion_tokens` (the OpenAI API's name for its newer models) is read the same way: that name is used in this message and for the summary request of the context compression. With streaming, mm also asks the server for token counts (`stream_options.include_usage`). | |
| 40 | | `watchdogTimeout` | duration | `20s` | Silence tolerated between two streamed tokens before the connection is declared hung. Doubled for summary requests. | | 40 | | `watchdogTimeout` | duration | `20s` | Silence tolerated between two streamed tokens before the connection is declared hung. Doubled for summary requests. | |
| 41 | | `firstTokenTimeout` | duration | `3m` | Silence tolerated before a model call's first token, while the server reads the prompt (every round trip of a turn has one). Never shorter than `watchdogTimeout`; must be >= 0. With a llama.cpp server (`dmr`, `llamacpp`, `llmman` — whose local GGUF models run in llama-server) mm asks for `return_progress`: each progress report restarts this clock, and the spinner shows `Reading the prompt 12.0k/25.3k tokens`. Ollama and Kronk send no progress: this one wait covers the whole prompt (and the model's loading). On a timeout the watchdog says `no first token from the server after …` (before the first token) or `connection hang detected after …` (after). | | 41 | | `firstTokenTimeout` | duration | `3m` | Silence tolerated before a model call's first token, while the server reads the prompt (every round trip of a turn has one). Never shorter than `watchdogTimeout`; must be >= 0. With a llama.cpp server (`dmr`, `llamacpp`, `llmman` — whose local GGUF models run in llama-server) mm asks for `return_progress`: each progress report restarts this clock, and the spinner shows `Reading the prompt 12.0k/25.3k tokens`. Ollama and Kronk send no progress: this one wait covers the whole prompt (and the model's loading). On a timeout the watchdog says `no first token from the server after …` (before the first token) or `connection hang detected after …` (after). | |
| 42 | | `bashTimeout` | duration | `30s` | How long one `bash` command may run before it is killed; the tool then answers `[error: <bashTimeout> timeout exceeded]`. Must be > 0. The watchdog keeps counting while a command runs (ticket 57): a command longer than `watchdogTimeout` ends the turn, so raise both together. | | 42 | | `bashTimeout` | duration | `30s` | How long one `bash` command may run before it is killed; the tool then answers `[error: <bashTimeout> timeout exceeded]`. Must be > 0. The watchdog keeps counting while a command runs (ticket 57): a command longer than `watchdogTimeout` ends the turn, so raise both together. | |
| @@ -202,11 +202,14 @@ tools: | |||
| 202 | | `ollama` | `http://localhost:11434/v1` | `http://host.docker.internal:11434/v1` | `OLLAMA_API_KEY` | no | | 202 | | `ollama` | `http://localhost:11434/v1` | `http://host.docker.internal:11434/v1` | `OLLAMA_API_KEY` | no | |
| 203 | | `kronk` | `http://127.0.0.1:11435/v1` | `http://host.docker.internal:11435/v1` | `KRONK_TOKEN` | no — only Kronk's `authenticated` and `full-protected` modes check it | | 203 | | `kronk` | `http://127.0.0.1:11435/v1` | `http://host.docker.internal:11435/v1` | `KRONK_TOKEN` | no — only Kronk's `authenticated` and `full-protected` modes check it | |
| 204 | | `openai` | `https://api.openai.com/v1` | none | `OPENAI_API_KEY` | no — a server that needs one answers 401, and the start-up warning names the variable | | 204 | | `openai` | `https://api.openai.com/v1` | none | `OPENAI_API_KEY` | no — a server that needs one answers 401, and the start-up warning names the variable | |
| 205 | +| `openai-responses` | `https://api.openai.com/v1` | none | `OPENAI_API_KEY` | no — as `openai` | | ||
| 205 | 206 | ||
| 206 | `llamacpp`: llama-server's default port is `9931` since llama.cpp b11521 (2026-10-09), `8080` before and in the official Docker images. When the address in use is `http://127.0.0.1:9931/v1` (no `baseUrl`, or that one) and it does not answer, mm tries `http://127.0.0.1:8080/v1`, then the `fallback`. | 207 | `llamacpp`: llama-server's default port is `9931` since llama.cpp b11521 (2026-10-09), `8080` before and in the official Docker images. When the address in use is `http://127.0.0.1:9931/v1` (no `baseUrl`, or that one) and it does not answer, mm tries `http://127.0.0.1:8080/v1`, then the `fallback`. |
| 207 | 208 | ||
| 208 | The `openai` provider sends only standard fields: no `return_progress` (so no prompt-reading progress while a long prompt is read), no reasoning switch on a summary request, no `/unload`. It cannot ask the server for its window: set `contextWindow`, or compression counts messages (`context.maxMessages`). Its start-up probe sends the key to `GET /models`; a 401 or 403 is reported as a refused key, not as a server that does not answer. | 209 | The `openai` provider sends only standard fields: no `return_progress` (so no prompt-reading progress while a long prompt is read), no reasoning switch on a summary request, no `/unload`. It cannot ask the server for its window: set `contextWindow`, or compression counts messages (`context.maxMessages`). Its start-up probe sends the key to `GET /models`; a 401 or 403 is reported as a refused key, not as a server that does not answer. |
| 209 | 210 | ||
| 211 | +The `openai-responses` provider (ticket 178) talks to the same servers through OpenAI's Responses API, `POST <baseUrl>/responses`, instead of Chat Completions: what OpenAI's reasoning models need to call tools while they reason. It sends the `sampling` block as written, with `max_tokens` / `max_completion_tokens` renamed `max_output_tokens` and `reasoning_effort` sent as `reasoning.effort`; it adds `store: false` and `include: ["reasoning.encrypted_content"]` unless the block sets them, and sends the model's encrypted reasoning back with the tool results. Its summary request sets `reasoning.effort: none`. Like `openai`: no prompt-reading progress, no `/unload`, the window from `contextWindow` only. See [How to keep reasoning and tools together with OpenAI's Responses API](../how-to/use-the-openai-responses-api.md). | ||
| 212 | + | ||
| 210 | ## `structuredOutput` | 213 | ## `structuredOutput` |
| 211 | 214 | ||
| 212 | A YAML block string holding Go declarations. Each `type` is a definition; the one `var` (`var X T` or `var X = T{}`) names the root of the answer. Only `type` and `var` declarations are allowed. | 215 | A YAML block string holding Go declarations. Each `type` is a definition; the one `var` (`var X T` or `var X = T{}`) names the root of the answer. Only `type` and `var` declarations are allowed. |
| @@ -328,6 +331,7 @@ decision: | |||
| 328 | | `llmman` | yes | | 331 | | `llmman` | yes | |
| 329 | | `ollama` | yes | | 332 | | `ollama` | yes | |
| 330 | | `openai` | the server's own: a server without the route answers 404 | | 333 | | `openai` | the server's own: a server without the route answers 404 | |
| 334 | +| `openai-responses` | no — refused at start-up | | ||
| 331 | | `dmr` | no (404, Docker Model Runner v1.2.8) — refused at start-up | | 335 | | `dmr` | no (404, Docker Model Runner v1.2.8) — refused at start-up | |
| 332 | 336 | ||
| 333 | The route serves models it knows as decision models: LiquidAI d1 (`LiquidAI/d1-3B-GGUF:Q4_K_M`) was accepted by all three; evalengine's `decision-4b` was refused by llmman (`501 This model is not a decision model`) and Ollama (`400 … is not a llama.cpp decision model`). | 337 | The route serves models it knows as decision models: LiquidAI d1 (`LiquidAI/d1-3B-GGUF:Q4_K_M`) was accepted by all three; evalengine's `decision-4b` was refused by llmman (`501 This model is not a decision model`) and Ollama (`400 … is not a llama.cpp decision model`). |
| @@ -470,7 +474,7 @@ Reported on stderr as `[config error: <path>: <message>]`, exit code 1 — in ev | |||
| 470 | | `mmConfigs: "with-context-x" is not a valid name (it would read as /ask-with-context-…)` | a name starting with `with-context` | | 474 | | `mmConfigs: "with-context-x" is not a valid name (it would read as /ask-with-context-…)` | a name starting with `with-context` | |
| 471 | | `mmConfigs.<name>: the path must not be empty` | `<name>: ""`, or a long form without `path` | | 475 | | `mmConfigs.<name>: the path must not be empty` | `<name>: ""`, or a long form without `path` | |
| 472 | | `hooks: unknown event "x" (…)`, `hooks.<event>[N]: …` | an invalid `hooks:` block — see [hooks](hooks.md#validation-errors) | | 476 | | `hooks: unknown event "x" (…)`, `hooks.<event>[N]: …` | an invalid `hooks:` block — see [hooks](hooks.md#validation-errors) | |
| 473 | -| `unknown provider "x" (known: dmr, kronk, llamacpp, llmman, ollama, openai)` | Reported by the engine, as `[engine error: …]`. | | 477 | +| `unknown provider "x" (known: dmr, kronk, llamacpp, llmman, ollama, openai, openai-responses)` | Reported by the engine, as `[engine error: …]`. | |
| 474 | 478 | ||
| 475 | A start-up warning, not an error, is printed when `context.enabled` is `true`, the window is unknown and `context.maxMessages` is `0`, and when a declared tool has the name of an MCP tool (`tools: <name> skipped — an MCP tool already has that name`; the tool is not declared), and when the file sets the deprecated `permissions` key (`permissions: ask is deprecated — use yolo: false instead …`). | 479 | A start-up warning, not an error, is printed when `context.enabled` is `true`, the window is unknown and `context.maxMessages` is `0`, and when a declared tool has the name of an MCP tool (`tools: <name> skipped — an MCP tool already has that name`; the tool is not declared), and when the file sets the deprecated `permissions` key (`permissions: ask is deprecated — use yolo: false instead …`). |
| 476 | 480 | ||
modified
docs/fr/README.md +1 -0 | @@ -18,6 +18,7 @@ Cette documentation est organisée selon les quatre quadrants [Diátaxis](https: | ||
| 18 | 18 | - [Faire tourner mini-me sur Ollama](how-to/run-with-ollama.md) — `provider: ollama`, la config de démo dans `demos/ollama/` |
| 19 | 19 | - [Faire tourner mini-me sur Kronk](how-to/run-with-kronk.md) — `provider: kronk`, la config de démo dans `demos/kronk/` |
| 20 | 20 | - [Utiliser n'importe quel serveur compatible OpenAI](how-to/run-with-an-openai-compatible-server.md) — `provider: openai` : l'API d'OpenAI, vLLM, LM Studio, une passerelle |
| 21 | +- [Garder le raisonnement et les outils avec l'API Responses d'OpenAI](how-to/use-the-openai-responses-api.md) — `provider: openai-responses` : les modèles de raisonnement d'OpenAI avec des outils | |
| 21 | 22 | - [Interroger un autre agent mm depuis votre session](how-to/ask-another-agent.md) — `mmConfigs`, `/ask-<nom>`, `/ask-with-context-<nom>` |
| 22 | 23 | - [Voir le JSON envoyé au modèle et sa réponse](how-to/inspect-model-traffic.md) — `trace`, `AGENT_TRACE`, lire les fichiers avec jq |
| 23 | 24 | - [Donner à l'agent les consignes de votre projet](how-to/give-project-instructions.md) — `AGENTS.md`, lu à chaque conversation, réglages `agentsMd` |
| @@ -18,6 +18,7 @@ Cette documentation est organisée selon les quatre quadrants [Diátaxis](https: | |||
| 18 | - [Faire tourner mini-me sur Ollama](how-to/run-with-ollama.md) — `provider: ollama`, la config de démo dans `demos/ollama/` | 18 | - [Faire tourner mini-me sur Ollama](how-to/run-with-ollama.md) — `provider: ollama`, la config de démo dans `demos/ollama/` |
| 19 | - [Faire tourner mini-me sur Kronk](how-to/run-with-kronk.md) — `provider: kronk`, la config de démo dans `demos/kronk/` | 19 | - [Faire tourner mini-me sur Kronk](how-to/run-with-kronk.md) — `provider: kronk`, la config de démo dans `demos/kronk/` |
| 20 | - [Utiliser n'importe quel serveur compatible OpenAI](how-to/run-with-an-openai-compatible-server.md) — `provider: openai` : l'API d'OpenAI, vLLM, LM Studio, une passerelle | 20 | - [Utiliser n'importe quel serveur compatible OpenAI](how-to/run-with-an-openai-compatible-server.md) — `provider: openai` : l'API d'OpenAI, vLLM, LM Studio, une passerelle |
| 21 | +- [Garder le raisonnement et les outils avec l'API Responses d'OpenAI](how-to/use-the-openai-responses-api.md) — `provider: openai-responses` : les modèles de raisonnement d'OpenAI avec des outils | ||
| 21 | - [Interroger un autre agent mm depuis votre session](how-to/ask-another-agent.md) — `mmConfigs`, `/ask-<nom>`, `/ask-with-context-<nom>` | 22 | - [Interroger un autre agent mm depuis votre session](how-to/ask-another-agent.md) — `mmConfigs`, `/ask-<nom>`, `/ask-with-context-<nom>` |
| 22 | - [Voir le JSON envoyé au modèle et sa réponse](how-to/inspect-model-traffic.md) — `trace`, `AGENT_TRACE`, lire les fichiers avec jq | 23 | - [Voir le JSON envoyé au modèle et sa réponse](how-to/inspect-model-traffic.md) — `trace`, `AGENT_TRACE`, lire les fichiers avec jq |
| 23 | - [Donner à l'agent les consignes de votre projet](how-to/give-project-instructions.md) — `AGENTS.md`, lu à chaque conversation, réglages `agentsMd` | 24 | - [Donner à l'agent les consignes de votre projet](how-to/give-project-instructions.md) — `AGENTS.md`, lu à chaque conversation, réglages `agentsMd` |
modified
docs/fr/explanation/mm-init.md +1 -1 | @@ -18,7 +18,7 @@ Le serveur connaît le modèle exact qui est chargé : c'est la source la plus p | ||
| 18 | 18 | | `llamacpp` | `/props` | la fenêtre et le template de chat | |
| 19 | 19 | | `kronk` | `/models`, puis `/v1/kronk/models/<id>` | la liste des modèles, l'architecture, la fenêtre avec laquelle le modèle est configuré (celle d'entraînement à défaut), l'échantillonnage écrit dans le GGUF, le template de chat ; pour un profil, son propre échantillonnage, qui l'emporte sur toute autre source : `mm` envoie son échantillonnage à chaque requête et une valeur de la requête remplace celle du profil, donc sans cette copie les valeurs du profil ne s'appliqueraient jamais | |
| 20 | 20 | | `dmr` | `/models` | la liste des modèles seulement | |
| 21 | -| `openai` | `/models` (avec la clé) | la liste des modèles seulement | | |
| 21 | +| `openai`, `openai-responses` | `/models` (avec la clé) | la liste des modèles seulement | | |
| 22 | 22 | |
| 23 | 23 | Dans le template de chat, `templateThinking` lit comment le raisonnement du modèle s'active et se désactive. Il trouve `enable_thinking` et sa valeur par défaut (activé ou non), ou `reasoning_effort` et les valeurs que le template accepte. Un modèle dont le template ne connaît ni l'un ni l'autre n'a pas d'interrupteur de raisonnement. |
| 24 | 24 | |
| @@ -18,7 +18,7 @@ Le serveur connaît le modèle exact qui est chargé : c'est la source la plus p | |||
| 18 | | `llamacpp` | `/props` | la fenêtre et le template de chat | | 18 | | `llamacpp` | `/props` | la fenêtre et le template de chat | |
| 19 | | `kronk` | `/models`, puis `/v1/kronk/models/<id>` | la liste des modèles, l'architecture, la fenêtre avec laquelle le modèle est configuré (celle d'entraînement à défaut), l'échantillonnage écrit dans le GGUF, le template de chat ; pour un profil, son propre échantillonnage, qui l'emporte sur toute autre source : `mm` envoie son échantillonnage à chaque requête et une valeur de la requête remplace celle du profil, donc sans cette copie les valeurs du profil ne s'appliqueraient jamais | | 19 | | `kronk` | `/models`, puis `/v1/kronk/models/<id>` | la liste des modèles, l'architecture, la fenêtre avec laquelle le modèle est configuré (celle d'entraînement à défaut), l'échantillonnage écrit dans le GGUF, le template de chat ; pour un profil, son propre échantillonnage, qui l'emporte sur toute autre source : `mm` envoie son échantillonnage à chaque requête et une valeur de la requête remplace celle du profil, donc sans cette copie les valeurs du profil ne s'appliqueraient jamais | |
| 20 | | `dmr` | `/models` | la liste des modèles seulement | | 20 | | `dmr` | `/models` | la liste des modèles seulement | |
| 21 | -| `openai` | `/models` (avec la clé) | la liste des modèles seulement | | 21 | +| `openai`, `openai-responses` | `/models` (avec la clé) | la liste des modèles seulement | |
| 22 | 22 | ||
| 23 | Dans le template de chat, `templateThinking` lit comment le raisonnement du modèle s'active et se désactive. Il trouve `enable_thinking` et sa valeur par défaut (activé ou non), ou `reasoning_effort` et les valeurs que le template accepte. Un modèle dont le template ne connaît ni l'un ni l'autre n'a pas d'interrupteur de raisonnement. | 23 | Dans le template de chat, `templateThinking` lit comment le raisonnement du modèle s'active et se désactive. Il trouve `enable_thinking` et sa valeur par défaut (activé ou non), ou `reasoning_effort` et les valeurs que le template accepte. Un modèle dont le template ne connaît ni l'un ni l'autre n'a pas d'interrupteur de raisonnement. |
| 24 | 24 | ||
modified
docs/fr/explanation/providers.md +1 -1 | @@ -6,7 +6,7 @@ | ||
| 6 | 6 | |
| 7 | 7 | ## Pourquoi c'est conçu ainsi |
| 8 | 8 | |
| 9 | -**Un type de fournisseur par protocole réseau, pas par éditeur.** Quand le moteur a été extrait, exactement une fonction et deux constantes de chaîne étaient spécifiques à Docker Model Runner. Tout le reste, le streaming, le watchdog, la nouvelle tentative, le compteur de commandes, se comportait de la même façon face à un faux moteur qui n'est pas DMR non plus. Donc `dmr` et `llamacpp` sont deux entrées de données d'un seul type `openaiCompat` : une URL de base par défaut, une URL de repli optionnelle, une politique de clé, et les mots employés dans les messages d'erreur. Ajouter un autre serveur compatible OpenAI est une entrée de registre ; ajouter un protocole différent serait un nouveau type. | |
| 9 | +**Un type de fournisseur par protocole réseau, pas par éditeur.** Quand le moteur a été extrait, exactement une fonction et deux constantes de chaîne étaient spécifiques à Docker Model Runner. Tout le reste, le streaming, le watchdog, la nouvelle tentative, le compteur de commandes, se comportait de la même façon face à un faux moteur qui n'est pas DMR non plus. Donc `dmr` et `llamacpp` sont deux entrées de données d'un seul type `openaiCompat` : une URL de base par défaut, une URL de repli optionnelle, une politique de clé, et les mots employés dans les messages d'erreur. Ajouter un autre serveur compatible OpenAI est une entrée de registre ; ajouter un protocole différent serait un nouveau type. La seule exception à ce jour est `openai-responses` (ticket 178) : l'API Responses d'OpenAI est un second protocole, mais pour les mêmes serveurs — même adresse, même clé, même sonde, mêmes messages d'erreur — c'est donc une entrée du même type avec un drapeau `responses`, et seul l'appel au modèle change : un modèle Genkit propre à mm (`responses.go`), puisque le plugin de Genkit ne connaît que Chat Completions. | |
| 10 | 10 | |
| 11 | 11 | **Un fournisseur possède quatre choses.** Il résout la configuration en un backend concret (URL après surcharges d'environnement et sonde de repli, clé lue dans l'environnement, nom du modèle) ; il ouvre Genkit avec son plugin ; il sonde le serveur avant la première question ; et il explique une erreur de transport en une ligne. |
| 12 | 12 | |
| @@ -6,7 +6,7 @@ | |||
| 6 | 6 | ||
| 7 | ## Pourquoi c'est conçu ainsi | 7 | ## Pourquoi c'est conçu ainsi |
| 8 | 8 | ||
| 9 | -**Un type de fournisseur par protocole réseau, pas par éditeur.** Quand le moteur a été extrait, exactement une fonction et deux constantes de chaîne étaient spécifiques à Docker Model Runner. Tout le reste, le streaming, le watchdog, la nouvelle tentative, le compteur de commandes, se comportait de la même façon face à un faux moteur qui n'est pas DMR non plus. Donc `dmr` et `llamacpp` sont deux entrées de données d'un seul type `openaiCompat` : une URL de base par défaut, une URL de repli optionnelle, une politique de clé, et les mots employés dans les messages d'erreur. Ajouter un autre serveur compatible OpenAI est une entrée de registre ; ajouter un protocole différent serait un nouveau type. | 9 | +**Un type de fournisseur par protocole réseau, pas par éditeur.** Quand le moteur a été extrait, exactement une fonction et deux constantes de chaîne étaient spécifiques à Docker Model Runner. Tout le reste, le streaming, le watchdog, la nouvelle tentative, le compteur de commandes, se comportait de la même façon face à un faux moteur qui n'est pas DMR non plus. Donc `dmr` et `llamacpp` sont deux entrées de données d'un seul type `openaiCompat` : une URL de base par défaut, une URL de repli optionnelle, une politique de clé, et les mots employés dans les messages d'erreur. Ajouter un autre serveur compatible OpenAI est une entrée de registre ; ajouter un protocole différent serait un nouveau type. La seule exception à ce jour est `openai-responses` (ticket 178) : l'API Responses d'OpenAI est un second protocole, mais pour les mêmes serveurs — même adresse, même clé, même sonde, mêmes messages d'erreur — c'est donc une entrée du même type avec un drapeau `responses`, et seul l'appel au modèle change : un modèle Genkit propre à mm (`responses.go`), puisque le plugin de Genkit ne connaît que Chat Completions. |
| 10 | 10 | ||
| 11 | **Un fournisseur possède quatre choses.** Il résout la configuration en un backend concret (URL après surcharges d'environnement et sonde de repli, clé lue dans l'environnement, nom du modèle) ; il ouvre Genkit avec son plugin ; il sonde le serveur avant la première question ; et il explique une erreur de transport en une ligne. | 11 | **Un fournisseur possède quatre choses.** Il résout la configuration en un backend concret (URL après surcharges d'environnement et sonde de repli, clé lue dans l'environnement, nom du modèle) ; il ouvre Genkit avec son plugin ; il sonde le serveur avant la première question ; et il explique une erreur de transport en une ligne. |
| 12 | 12 | ||
modified
docs/fr/how-to/create-an-agent.md +1 -1 | @@ -81,7 +81,7 @@ Ce guide montre comment écrire un nouvel agent.yaml pour un modèle et une tâc | ||
| 81 | 81 | - **Voir le fichier sans l'écrire.** `-o -` l'affiche sur la sortie standard. Rien n'est créé, pas même le dossier `.mm` ni celui des skills. |
| 82 | 82 | - **Tout dans un dossier `.mm`.** Répondez `yes` à la première question, ou donnez `--project yes` : mm crée `.mm/` et écrit `.mm/agent.yaml`, avec ses chemins écrits depuis la racine du projet. Lancés depuis cette racine, `mm` et `mm tui` le trouvent sans argument. Voir [Comment ranger les fichiers mini-me d'un projet dans un dossier `.mm`](keep-the-config-in-a-mm-folder.md). |
| 83 | 83 | - **Sessions et skills.** `--sessions yes` écrit une section `sessions` : chaque conversation est enregistrée, et `/resume` peut la rouvrir. `--skills yes` écrit `skillsDir` et crée le dossier (`skills/`, ou `.mm/skills/` avec `--project yes`) ; ajoutez-y vos skills (voir [Comment ajouter un skill](add-a-skill.md)). |
| 84 | -- **Un service compatible OpenAI (OpenAI, Cerebras, Hugging Face…).** Choisissez `openai` : deux questions de plus suivent, l'endpoint (`https://api.openai.com/v1` par défaut) et le nom de la variable qui contient la clé d'API (`OPENAI_API_KEY` par défaut, `CEREBRAS_API_KEY`, `HF_TOKEN`…). Exportez la clé avant de lancer `mm init` : avec elle, la question du modèle liste les modèles du service ; sans elle, vous tapez l'ID du modèle (la question dit que la variable n'est pas renseignée). Options : `--provider openai --base-url https://api.cerebras.ai/v1 --api-key-env CEREBRAS_API_KEY`. Le fichier reçoit `baseUrl` et `apiKeyEnv`, et un `reasoning_effort: none` en commentaire dans `sampling`, à décommenter si l'API répond « Function tools with reasoning_effort are not supported ». | |
| 84 | +- **Un service compatible OpenAI (OpenAI, Cerebras, Hugging Face…).** Choisissez `openai` : deux questions de plus suivent, l'endpoint (`https://api.openai.com/v1` par défaut) et le nom de la variable qui contient la clé d'API (`OPENAI_API_KEY` par défaut, `CEREBRAS_API_KEY`, `HF_TOKEN`…). Exportez la clé avant de lancer `mm init` : avec elle, la question du modèle liste les modèles du service ; sans elle, vous tapez l'ID du modèle (la question dit que la variable n'est pas renseignée). Options : `--provider openai --base-url https://api.cerebras.ai/v1 --api-key-env CEREBRAS_API_KEY`. Le fichier reçoit `baseUrl` et `apiKeyEnv`, et un `reasoning_effort: none` en commentaire dans `sampling`, à décommenter si l'API répond « Function tools with reasoning_effort are not supported ». Pour un modèle de raisonnement d'OpenAI qui doit continuer à raisonner pendant qu'il appelle des outils, choisissez plutôt `openai-responses` : les mêmes questions, et le fichier parle à l'API Responses (voir [Garder le raisonnement et les outils avec l'API Responses d'OpenAI](use-the-openai-responses-api.md)). | |
| 85 | 85 | - **Un serveur ailleurs.** `--base-url http://192.168.1.20:17434/v1` ; il est écrit dans le fichier comme `baseUrl`. Sans lui, le fichier n'a pas de `baseUrl` et garde en commentaire l'adresse par défaut du fournisseur et son fallback, prêts à être décommentés. |
| 86 | 86 | - **Un serveur qui ne répond pas.** mm le dit et demande le nom du modèle : les réglages viennent alors de la seule table des familles. |
| 87 | 87 | - **Un fichier existant.** mm demande `Overwrite agent.yaml?`, et `no` est la réponse par défaut : il demande alors un autre fichier. Pour un fichier donné avec `-o`, la question vient en premier ; pour un fichier saisi dans l'assistant, juste après. Avec `--yes`, ou quand l'entrée se termine, rien n'est écrasé : mm le dit et s'arrête. |
| @@ -81,7 +81,7 @@ Ce guide montre comment écrire un nouvel agent.yaml pour un modèle et une tâc | |||
| 81 | - **Voir le fichier sans l'écrire.** `-o -` l'affiche sur la sortie standard. Rien n'est créé, pas même le dossier `.mm` ni celui des skills. | 81 | - **Voir le fichier sans l'écrire.** `-o -` l'affiche sur la sortie standard. Rien n'est créé, pas même le dossier `.mm` ni celui des skills. |
| 82 | - **Tout dans un dossier `.mm`.** Répondez `yes` à la première question, ou donnez `--project yes` : mm crée `.mm/` et écrit `.mm/agent.yaml`, avec ses chemins écrits depuis la racine du projet. Lancés depuis cette racine, `mm` et `mm tui` le trouvent sans argument. Voir [Comment ranger les fichiers mini-me d'un projet dans un dossier `.mm`](keep-the-config-in-a-mm-folder.md). | 82 | - **Tout dans un dossier `.mm`.** Répondez `yes` à la première question, ou donnez `--project yes` : mm crée `.mm/` et écrit `.mm/agent.yaml`, avec ses chemins écrits depuis la racine du projet. Lancés depuis cette racine, `mm` et `mm tui` le trouvent sans argument. Voir [Comment ranger les fichiers mini-me d'un projet dans un dossier `.mm`](keep-the-config-in-a-mm-folder.md). |
| 83 | - **Sessions et skills.** `--sessions yes` écrit une section `sessions` : chaque conversation est enregistrée, et `/resume` peut la rouvrir. `--skills yes` écrit `skillsDir` et crée le dossier (`skills/`, ou `.mm/skills/` avec `--project yes`) ; ajoutez-y vos skills (voir [Comment ajouter un skill](add-a-skill.md)). | 83 | - **Sessions et skills.** `--sessions yes` écrit une section `sessions` : chaque conversation est enregistrée, et `/resume` peut la rouvrir. `--skills yes` écrit `skillsDir` et crée le dossier (`skills/`, ou `.mm/skills/` avec `--project yes`) ; ajoutez-y vos skills (voir [Comment ajouter un skill](add-a-skill.md)). |
| 84 | -- **Un service compatible OpenAI (OpenAI, Cerebras, Hugging Face…).** Choisissez `openai` : deux questions de plus suivent, l'endpoint (`https://api.openai.com/v1` par défaut) et le nom de la variable qui contient la clé d'API (`OPENAI_API_KEY` par défaut, `CEREBRAS_API_KEY`, `HF_TOKEN`…). Exportez la clé avant de lancer `mm init` : avec elle, la question du modèle liste les modèles du service ; sans elle, vous tapez l'ID du modèle (la question dit que la variable n'est pas renseignée). Options : `--provider openai --base-url https://api.cerebras.ai/v1 --api-key-env CEREBRAS_API_KEY`. Le fichier reçoit `baseUrl` et `apiKeyEnv`, et un `reasoning_effort: none` en commentaire dans `sampling`, à décommenter si l'API répond « Function tools with reasoning_effort are not supported ». | 84 | +- **Un service compatible OpenAI (OpenAI, Cerebras, Hugging Face…).** Choisissez `openai` : deux questions de plus suivent, l'endpoint (`https://api.openai.com/v1` par défaut) et le nom de la variable qui contient la clé d'API (`OPENAI_API_KEY` par défaut, `CEREBRAS_API_KEY`, `HF_TOKEN`…). Exportez la clé avant de lancer `mm init` : avec elle, la question du modèle liste les modèles du service ; sans elle, vous tapez l'ID du modèle (la question dit que la variable n'est pas renseignée). Options : `--provider openai --base-url https://api.cerebras.ai/v1 --api-key-env CEREBRAS_API_KEY`. Le fichier reçoit `baseUrl` et `apiKeyEnv`, et un `reasoning_effort: none` en commentaire dans `sampling`, à décommenter si l'API répond « Function tools with reasoning_effort are not supported ». Pour un modèle de raisonnement d'OpenAI qui doit continuer à raisonner pendant qu'il appelle des outils, choisissez plutôt `openai-responses` : les mêmes questions, et le fichier parle à l'API Responses (voir [Garder le raisonnement et les outils avec l'API Responses d'OpenAI](use-the-openai-responses-api.md)). |
| 85 | - **Un serveur ailleurs.** `--base-url http://192.168.1.20:17434/v1` ; il est écrit dans le fichier comme `baseUrl`. Sans lui, le fichier n'a pas de `baseUrl` et garde en commentaire l'adresse par défaut du fournisseur et son fallback, prêts à être décommentés. | 85 | - **Un serveur ailleurs.** `--base-url http://192.168.1.20:17434/v1` ; il est écrit dans le fichier comme `baseUrl`. Sans lui, le fichier n'a pas de `baseUrl` et garde en commentaire l'adresse par défaut du fournisseur et son fallback, prêts à être décommentés. |
| 86 | - **Un serveur qui ne répond pas.** mm le dit et demande le nom du modèle : les réglages viennent alors de la seule table des familles. | 86 | - **Un serveur qui ne répond pas.** mm le dit et demande le nom du modèle : les réglages viennent alors de la seule table des familles. |
| 87 | - **Un fichier existant.** mm demande `Overwrite agent.yaml?`, et `no` est la réponse par défaut : il demande alors un autre fichier. Pour un fichier donné avec `-o`, la question vient en premier ; pour un fichier saisi dans l'assistant, juste après. Avec `--yes`, ou quand l'entrée se termine, rien n'est écrasé : mm le dit et s'arrête. | 87 | - **Un fichier existant.** mm demande `Overwrite agent.yaml?`, et `no` est la réponse par défaut : il demande alors un autre fichier. Pour un fichier donné avec `-o`, la question vient en premier ; pour un fichier saisi dans l'assistant, juste après. Avec `--yes`, ou quand l'entrée se termine, rien n'est écrasé : mm le dit et s'arrête. |
modified
docs/fr/how-to/run-with-an-openai-compatible-server.md +1 -1 | @@ -34,7 +34,7 @@ Ce guide montre comment faire tourner mini-me sur un serveur de modèles qui n'a | ||
| 34 | 34 | ## Variantes |
| 35 | 35 | |
| 36 | 36 | - **L'API d'OpenAI.** Pas de `baseUrl`, `OPENAI_API_KEY` exportée, un modèle comme `gpt-5-mini`. Ses modèles à raisonnement n'acceptent que la température par défaut et prennent `max_completion_tokens` au lieu de `max_tokens` : écrivez `temperature: 1.0` et `max_completion_tokens` dans `sampling`. Avec `provider: openai`, mm envoie ce bloc tel quel, sans ses propres valeurs par défaut (`top_p`, `max_tokens`) : retirez seulement une clé que l'API refuserait encore. `mm init` écrit un tel bloc. (Le contenu de la requête a été vérifié contre un serveur local ; aucun appel à l'API OpenAI n'a été fait dans ce dépôt.) |
| 37 | -- **« Function tools with reasoning_effort are not supported ».** Certains modèles OpenAI (vu : `gpt-6-luna`) refusent les outils sur `/v1/chat/completions` pendant qu'ils raisonnent ; mm utilise cette route et envoie toujours des outils. Ajoutez `reasoning_effort: none` à `sampling` (cela coupe le raisonnement). Non vérifié dans ce dépôt : signalé par un utilisateur. | |
| 37 | +- **« Function tools with reasoning_effort are not supported ».** Certains modèles OpenAI (vu : `gpt-6-luna`) refusent les outils sur `/v1/chat/completions` pendant qu'ils raisonnent ; mm utilise cette route et envoie toujours des outils. Utilisez `provider: openai-responses`, qui parle l'API Responses et garde le raisonnement avec les outils : voir [Garder le raisonnement et les outils avec l'API Responses d'OpenAI](use-the-openai-responses-api.md). Ou ajoutez `reasoning_effort: none` à `sampling` (cela coupe le raisonnement). L'erreur a été signalée par un utilisateur, pas reproduite dans ce dépôt. | |
| 38 | 38 | - **La clé est refusée.** L'avertissement de démarrage indique `openai: <baseUrl> refused the key (HTTP 401) — export OPENAI_API_KEY`. |
| 39 | 39 | - **Rien ne répond.** L'avertissement indique `openai: nothing answers at <baseUrl> — check baseUrl: …` : l'adresse doit être celle compatible OpenAI, qui finit généralement par `/v1`. |
| 40 | 40 | - **Un serveur pour lequel mm a un fournisseur.** Préférez-le (`dmr`, `llamacpp`, `llmman`, `ollama`) : ceux-là savent comment le serveur lit un long prompt, coupent le raisonnement pour un résumé, déchargent un modèle et donnent la taille de la fenêtre. Le fournisseur générique ne fait rien de tout cela. |
| @@ -34,7 +34,7 @@ Ce guide montre comment faire tourner mini-me sur un serveur de modèles qui n'a | |||
| 34 | ## Variantes | 34 | ## Variantes |
| 35 | 35 | ||
| 36 | - **L'API d'OpenAI.** Pas de `baseUrl`, `OPENAI_API_KEY` exportée, un modèle comme `gpt-5-mini`. Ses modèles à raisonnement n'acceptent que la température par défaut et prennent `max_completion_tokens` au lieu de `max_tokens` : écrivez `temperature: 1.0` et `max_completion_tokens` dans `sampling`. Avec `provider: openai`, mm envoie ce bloc tel quel, sans ses propres valeurs par défaut (`top_p`, `max_tokens`) : retirez seulement une clé que l'API refuserait encore. `mm init` écrit un tel bloc. (Le contenu de la requête a été vérifié contre un serveur local ; aucun appel à l'API OpenAI n'a été fait dans ce dépôt.) | 36 | - **L'API d'OpenAI.** Pas de `baseUrl`, `OPENAI_API_KEY` exportée, un modèle comme `gpt-5-mini`. Ses modèles à raisonnement n'acceptent que la température par défaut et prennent `max_completion_tokens` au lieu de `max_tokens` : écrivez `temperature: 1.0` et `max_completion_tokens` dans `sampling`. Avec `provider: openai`, mm envoie ce bloc tel quel, sans ses propres valeurs par défaut (`top_p`, `max_tokens`) : retirez seulement une clé que l'API refuserait encore. `mm init` écrit un tel bloc. (Le contenu de la requête a été vérifié contre un serveur local ; aucun appel à l'API OpenAI n'a été fait dans ce dépôt.) |
| 37 | -- **« Function tools with reasoning_effort are not supported ».** Certains modèles OpenAI (vu : `gpt-6-luna`) refusent les outils sur `/v1/chat/completions` pendant qu'ils raisonnent ; mm utilise cette route et envoie toujours des outils. Ajoutez `reasoning_effort: none` à `sampling` (cela coupe le raisonnement). Non vérifié dans ce dépôt : signalé par un utilisateur. | 37 | +- **« Function tools with reasoning_effort are not supported ».** Certains modèles OpenAI (vu : `gpt-6-luna`) refusent les outils sur `/v1/chat/completions` pendant qu'ils raisonnent ; mm utilise cette route et envoie toujours des outils. Utilisez `provider: openai-responses`, qui parle l'API Responses et garde le raisonnement avec les outils : voir [Garder le raisonnement et les outils avec l'API Responses d'OpenAI](use-the-openai-responses-api.md). Ou ajoutez `reasoning_effort: none` à `sampling` (cela coupe le raisonnement). L'erreur a été signalée par un utilisateur, pas reproduite dans ce dépôt. |
| 38 | - **La clé est refusée.** L'avertissement de démarrage indique `openai: <baseUrl> refused the key (HTTP 401) — export OPENAI_API_KEY`. | 38 | - **La clé est refusée.** L'avertissement de démarrage indique `openai: <baseUrl> refused the key (HTTP 401) — export OPENAI_API_KEY`. |
| 39 | - **Rien ne répond.** L'avertissement indique `openai: nothing answers at <baseUrl> — check baseUrl: …` : l'adresse doit être celle compatible OpenAI, qui finit généralement par `/v1`. | 39 | - **Rien ne répond.** L'avertissement indique `openai: nothing answers at <baseUrl> — check baseUrl: …` : l'adresse doit être celle compatible OpenAI, qui finit généralement par `/v1`. |
| 40 | - **Un serveur pour lequel mm a un fournisseur.** Préférez-le (`dmr`, `llamacpp`, `llmman`, `ollama`) : ceux-là savent comment le serveur lit un long prompt, coupent le raisonnement pour un résumé, déchargent un modèle et donnent la taille de la fenêtre. Le fournisseur générique ne fait rien de tout cela. | 40 | - **Un serveur pour lequel mm a un fournisseur.** Préférez-le (`dmr`, `llamacpp`, `llmman`, `ollama`) : ceux-là savent comment le serveur lit un long prompt, coupent le raisonnement pour un résumé, déchargent un modèle et donnent la taille de la fenêtre. Le fournisseur générique ne fait rien de tout cela. |
added
docs/fr/how-to/use-the-openai-responses-api.md +59 -0 | new file mode 100644 | ||
| @@ -0,0 +1,59 @@ | ||
| 1 | +# Garder le raisonnement et les outils avec l'API Responses d'OpenAI | |
| 2 | + | |
| 3 | +Ce guide montre comment faire tourner mini-me sur un modèle de raisonnement d'OpenAI qui refuse les outils sur Chat Completions pendant qu'il raisonne — vu avec `gpt-6-luna` : | |
| 4 | + | |
| 5 | +```text | |
| 6 | +Function tools with reasoning_effort are not supported for gpt-6-luna in /v1/chat/completions. | |
| 7 | +To use function tools, use /v1/responses or set reasoning_effort to 'none'. | |
| 8 | +``` | |
| 9 | + | |
| 10 | +Un agent mm envoie toujours des outils. `reasoning_effort: none` fait marcher le fournisseur `openai`, mais le modèle ne raisonne plus. Le fournisseur `openai-responses` parle l'API Responses (`POST /v1/responses`) à la place, et garde les deux. Il suppose une clé d'API OpenAI et un modèle servi sur `/v1/responses`. | |
| 11 | + | |
| 12 | +## Étapes | |
| 13 | + | |
| 14 | +1. Écrivez le fichier d'agent avec `provider: openai-responses` : | |
| 15 | + | |
| 16 | + ```yaml | |
| 17 | + provider: openai-responses | |
| 18 | + model: gpt-6-luna | |
| 19 | + contextWindow: 400000 # ce fournisseur ne peut pas demander sa fenêtre au serveur | |
| 20 | + sampling: | |
| 21 | + reasoning_effort: medium # envoyé comme reasoning.effort | |
| 22 | + max_completion_tokens: 16000 # envoyé comme max_output_tokens | |
| 23 | + ``` | |
| 24 | + | |
| 25 | + Pas de `baseUrl` : la valeur par défaut est l'API d'OpenAI, `https://api.openai.com/v1`. | |
| 26 | + | |
| 27 | +2. Exportez la clé — elle ne va jamais dans le YAML : | |
| 28 | + | |
| 29 | + ```bash | |
| 30 | + export OPENAI_API_KEY=sk-… | |
| 31 | + ``` | |
| 32 | + | |
| 33 | + Un autre nom de variable : `apiKeyEnv: MA_CLE`. | |
| 34 | + | |
| 35 | +3. Lancez mm comme d'habitude (`mm`, `mm tui`, `mm acp`, `mm -p "…"`). Le résumé du raisonnement du modèle, quand l'API en envoie un, s'affiche comme des pensées (`💭`, avec `showThinking: true`) ; les appels d'outils tournent comme avec tous les autres fournisseurs. | |
| 36 | + | |
| 37 | +`mm init` écrit un tel fichier : choisissez `openai-responses`, puis l'adresse et la variable de la clé (ou `--provider openai-responses`). | |
| 38 | + | |
| 39 | +## Ce que le fournisseur envoie | |
| 40 | + | |
| 41 | +- **Le bloc `sampling:` tel qu'il est écrit**, sans les valeurs par défaut de mm (`top_p`, `max_tokens`), comme `provider: openai`. Deux noms de Chat Completions sont renommés pour cette API : `max_tokens` et `max_completion_tokens` deviennent `max_output_tokens`, et `reasoning_effort` devient `reasoning.effort`. Toute autre clé part telle quelle : `reasoning: {summary: auto}` demande par exemple le résumé du raisonnement. | |
| 42 | +- **`store: false` et `include: ["reasoning.encrypted_content"]`.** Rien n'est gardé chez OpenAI. Le raisonnement chiffré du modèle revient avec chaque réponse, et mm le renvoie avec les résultats des outils : le modèle garde le fil d'un appel d'outil au suivant. Il est aussi enregistré avec la conversation quand les sessions sont actives. Écrivez `store` ou `include` dans `sampling` pour choisir autrement. | |
| 43 | +- **Les outils comme outils de fonction**, non stricts : les schémas des outils de mm ont des champs facultatifs, que le mode strict refuse. | |
| 44 | +- **`structuredOutput`** comme `text.format` (`json_schema`, strict, comme l'envoie le fournisseur `openai`). | |
| 45 | +- **Le résumé d'une compression** avec `reasoning.effort: none`, sans streaming, sans outils. | |
| 46 | + | |
| 47 | +## Variantes | |
| 48 | + | |
| 49 | +- **Un autre serveur.** Mettez dans `baseUrl` son adresse compatible OpenAI (qui finit par `/v1`) ; il doit servir `POST /responses`. Quels serveurs le font — vLLM, Ollama, llama-server… — n'est pas vérifié. S'il refuse `include` ou `store`, écrivez-les dans `sampling` (`include: []`). | |
| 50 | +- **La clé est refusée.** L'avertissement de démarrage dit `openai-responses: <baseUrl> refused the key (HTTP 401) — export OPENAI_API_KEY`, et une question qui échoue dit `authentication failed … is $OPENAI_API_KEY set and valid?`. | |
| 51 | +- **Pas de résumé du raisonnement à l'écran.** L'API n'envoie de résumé que si on le demande : `reasoning: {summary: auto}` dans `sampling`. OpenAI peut exiger une organisation vérifiée pour cela. | |
| 52 | +- **Chat Completions suffit.** Pour un modèle qui ne raisonne pas, ou servi par vLLM, LM Studio ou une passerelle qui ne parle que Chat Completions, gardez `provider: openai` — voir [Utiliser n'importe quel serveur compatible OpenAI](run-with-an-openai-compatible-server.md). | |
| 53 | + | |
| 54 | +Vérifié contre un faux serveur `/v1/responses`, dans les tests et avec le binaire construit : le résumé du raisonnement s'est affiché, un appel à `bash` a tourné, et le raisonnement chiffré et la sortie de l'outil sont repartis avec le `call_id` de l'appel. Aucun appel à l'API d'OpenAI n'a été fait dans ce dépôt. | |
| 55 | + | |
| 56 | +## Voir aussi | |
| 57 | + | |
| 58 | +- [Référence de configuration — valeurs par défaut des fournisseurs](../reference/configuration.md#valeurs-par-défaut-des-fournisseurs) | |
| 59 | +- [Fournisseurs — explication](../explanation/providers.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,59 @@ | |||
| 1 | +# Garder le raisonnement et les outils avec l'API Responses d'OpenAI | ||
| 2 | + | ||
| 3 | +Ce guide montre comment faire tourner mini-me sur un modèle de raisonnement d'OpenAI qui refuse les outils sur Chat Completions pendant qu'il raisonne — vu avec `gpt-6-luna` : | ||
| 4 | + | ||
| 5 | +```text | ||
| 6 | +Function tools with reasoning_effort are not supported for gpt-6-luna in /v1/chat/completions. | ||
| 7 | +To use function tools, use /v1/responses or set reasoning_effort to 'none'. | ||
| 8 | +``` | ||
| 9 | + | ||
| 10 | +Un agent mm envoie toujours des outils. `reasoning_effort: none` fait marcher le fournisseur `openai`, mais le modèle ne raisonne plus. Le fournisseur `openai-responses` parle l'API Responses (`POST /v1/responses`) à la place, et garde les deux. Il suppose une clé d'API OpenAI et un modèle servi sur `/v1/responses`. | ||
| 11 | + | ||
| 12 | +## Étapes | ||
| 13 | + | ||
| 14 | +1. Écrivez le fichier d'agent avec `provider: openai-responses` : | ||
| 15 | + | ||
| 16 | + ```yaml | ||
| 17 | + provider: openai-responses | ||
| 18 | + model: gpt-6-luna | ||
| 19 | + contextWindow: 400000 # ce fournisseur ne peut pas demander sa fenêtre au serveur | ||
| 20 | + sampling: | ||
| 21 | + reasoning_effort: medium # envoyé comme reasoning.effort | ||
| 22 | + max_completion_tokens: 16000 # envoyé comme max_output_tokens | ||
| 23 | + ``` | ||
| 24 | + | ||
| 25 | + Pas de `baseUrl` : la valeur par défaut est l'API d'OpenAI, `https://api.openai.com/v1`. | ||
| 26 | + | ||
| 27 | +2. Exportez la clé — elle ne va jamais dans le YAML : | ||
| 28 | + | ||
| 29 | + ```bash | ||
| 30 | + export OPENAI_API_KEY=sk-… | ||
| 31 | + ``` | ||
| 32 | + | ||
| 33 | + Un autre nom de variable : `apiKeyEnv: MA_CLE`. | ||
| 34 | + | ||
| 35 | +3. Lancez mm comme d'habitude (`mm`, `mm tui`, `mm acp`, `mm -p "…"`). Le résumé du raisonnement du modèle, quand l'API en envoie un, s'affiche comme des pensées (`💭`, avec `showThinking: true`) ; les appels d'outils tournent comme avec tous les autres fournisseurs. | ||
| 36 | + | ||
| 37 | +`mm init` écrit un tel fichier : choisissez `openai-responses`, puis l'adresse et la variable de la clé (ou `--provider openai-responses`). | ||
| 38 | + | ||
| 39 | +## Ce que le fournisseur envoie | ||
| 40 | + | ||
| 41 | +- **Le bloc `sampling:` tel qu'il est écrit**, sans les valeurs par défaut de mm (`top_p`, `max_tokens`), comme `provider: openai`. Deux noms de Chat Completions sont renommés pour cette API : `max_tokens` et `max_completion_tokens` deviennent `max_output_tokens`, et `reasoning_effort` devient `reasoning.effort`. Toute autre clé part telle quelle : `reasoning: {summary: auto}` demande par exemple le résumé du raisonnement. | ||
| 42 | +- **`store: false` et `include: ["reasoning.encrypted_content"]`.** Rien n'est gardé chez OpenAI. Le raisonnement chiffré du modèle revient avec chaque réponse, et mm le renvoie avec les résultats des outils : le modèle garde le fil d'un appel d'outil au suivant. Il est aussi enregistré avec la conversation quand les sessions sont actives. Écrivez `store` ou `include` dans `sampling` pour choisir autrement. | ||
| 43 | +- **Les outils comme outils de fonction**, non stricts : les schémas des outils de mm ont des champs facultatifs, que le mode strict refuse. | ||
| 44 | +- **`structuredOutput`** comme `text.format` (`json_schema`, strict, comme l'envoie le fournisseur `openai`). | ||
| 45 | +- **Le résumé d'une compression** avec `reasoning.effort: none`, sans streaming, sans outils. | ||
| 46 | + | ||
| 47 | +## Variantes | ||
| 48 | + | ||
| 49 | +- **Un autre serveur.** Mettez dans `baseUrl` son adresse compatible OpenAI (qui finit par `/v1`) ; il doit servir `POST /responses`. Quels serveurs le font — vLLM, Ollama, llama-server… — n'est pas vérifié. S'il refuse `include` ou `store`, écrivez-les dans `sampling` (`include: []`). | ||
| 50 | +- **La clé est refusée.** L'avertissement de démarrage dit `openai-responses: <baseUrl> refused the key (HTTP 401) — export OPENAI_API_KEY`, et une question qui échoue dit `authentication failed … is $OPENAI_API_KEY set and valid?`. | ||
| 51 | +- **Pas de résumé du raisonnement à l'écran.** L'API n'envoie de résumé que si on le demande : `reasoning: {summary: auto}` dans `sampling`. OpenAI peut exiger une organisation vérifiée pour cela. | ||
| 52 | +- **Chat Completions suffit.** Pour un modèle qui ne raisonne pas, ou servi par vLLM, LM Studio ou une passerelle qui ne parle que Chat Completions, gardez `provider: openai` — voir [Utiliser n'importe quel serveur compatible OpenAI](run-with-an-openai-compatible-server.md). | ||
| 53 | + | ||
| 54 | +Vérifié contre un faux serveur `/v1/responses`, dans les tests et avec le binaire construit : le résumé du raisonnement s'est affiché, un appel à `bash` a tourné, et le raisonnement chiffré et la sortie de l'outil sont repartis avec le `call_id` de l'appel. Aucun appel à l'API d'OpenAI n'a été fait dans ce dépôt. | ||
| 55 | + | ||
| 56 | +## Voir aussi | ||
| 57 | + | ||
| 58 | +- [Référence de configuration — valeurs par défaut des fournisseurs](../reference/configuration.md#valeurs-par-défaut-des-fournisseurs) | ||
| 59 | +- [Fournisseurs — explication](../explanation/providers.md) | ||
modified
docs/fr/reference/cli.md +3 -3 | @@ -239,9 +239,9 @@ Un fichier d'agent hors du workspace ne donne qu'un avertissement : voir [quand | ||
| 239 | 239 | | Option | Question quand elle est absente | Défaut | |
| 240 | 240 | |--------|---------------------------------|--------| |
| 241 | 241 | | `--project yes\|no` | Tout ranger dans un dossier `.mm` ? — posée en premier. `yes` : le fichier est `.mm/agent.yaml` (le dossier est créé), ses chemins sont écrits depuis la racine du projet (`skillsDir: .mm/skills`), et `mm` / `mm tui` lancés là le trouvent sans argument | `no` | |
| 242 | -| `--provider` | Serveur de modèles : `llamacpp`, `llmman`, `ollama`, `dmr`, `kronk`, `openai` | le premier serveur local qui répond, dans cet ordre (`llamacpp` sur 9931, puis 8080), sinon `llamacpp` (`openai` n'est jamais sondé : son adresse par défaut est l'API d'OpenAI) | | |
| 243 | -| `--base-url` | `openai` seulement : Endpoint — l'adresse compatible OpenAI du service (OpenAI, Cerebras, Hugging Face…) ; pour les autres fournisseurs, pas posée | `https://api.openai.com/v1` pour `openai` ; sinon `AGENT_BASE_URL` s'il est défini, sinon la première des adresses locales du fournisseur dont la liste de modèles répond — son adresse par défaut, puis la même avec `127.0.0.1` quand elle nomme `localhost`, puis pour `llamacpp` l'ancien port de llama-server, `http://127.0.0.1:8080/v1` — et son adresse de secours pour conteneur (`host.docker.internal`) seulement quand aucune ne répond. La question du modèle nomme l'adresse d'où vient sa liste (`Model? (listed from …)`). Écrite comme `baseUrl` sauf si c'est la valeur par défaut | | |
| 244 | -| `--api-key-env` | `openai` seulement : variable d'environnement qui contient la clé d'API | `OPENAI_API_KEY`. Écrite comme `apiKeyEnv` sauf si c'est la valeur par défaut | | |
| 242 | +| `--provider` | Serveur de modèles : `llamacpp`, `llmman`, `ollama`, `dmr`, `kronk`, `openai`, `openai-responses` | le premier serveur local qui répond, dans cet ordre (`llamacpp` sur 9931, puis 8080), sinon `llamacpp` (`openai` et `openai-responses` ne sont jamais sondés : leur adresse par défaut est l'API d'OpenAI) | | |
| 243 | +| `--base-url` | `openai` et `openai-responses` seulement : Endpoint — l'adresse compatible OpenAI du service (OpenAI, Cerebras, Hugging Face…) ; pour les autres fournisseurs, pas posée | `https://api.openai.com/v1` pour `openai` et `openai-responses` ; sinon `AGENT_BASE_URL` s'il est défini, sinon la première des adresses locales du fournisseur dont la liste de modèles répond — son adresse par défaut, puis la même avec `127.0.0.1` quand elle nomme `localhost`, puis pour `llamacpp` l'ancien port de llama-server, `http://127.0.0.1:8080/v1` — et son adresse de secours pour conteneur (`host.docker.internal`) seulement quand aucune ne répond. La question du modèle nomme l'adresse d'où vient sa liste (`Model? (listed from …)`). Écrite comme `baseUrl` sauf si c'est la valeur par défaut | | |
| 244 | +| `--api-key-env` | `openai` et `openai-responses` seulement : variable d'environnement qui contient la clé d'API | `OPENAI_API_KEY`. Écrite comme `apiKeyEnv` sauf si c'est la valeur par défaut | | |
| 245 | 245 | | `--model` | Modèle : la liste des modèles du serveur (`/api/tags` pour llmman et Ollama, `/models` pour les autres ; 5 s pour un serveur local, 20 s pour `openai`), ou un nom à taper quand il n'y a pas de liste — la question dit pourquoi (`<VARIABLE> is not set: no list`, ou l'erreur du serveur). Pour `openai`, la liste est demandée avec la clé lue dans la variable nommée plus haut, et pas demandée du tout quand cette variable est vide | le premier de la liste | |
| 246 | 246 | | `--family` | Famille du modèle | détectée d'après le nom du modèle, puis d'après le nom de famille donné par le serveur | |
| 247 | 247 | | `--usage` | À quoi sert l'agent : `developer`, `reviewer`, `translator`, `writer`, `assistant`, `researcher`, `docs`, `json`, `coordinator` | `developer` | |
| @@ -239,9 +239,9 @@ Un fichier d'agent hors du workspace ne donne qu'un avertissement : voir [quand | |||
| 239 | | Option | Question quand elle est absente | Défaut | | 239 | | Option | Question quand elle est absente | Défaut | |
| 240 | |--------|---------------------------------|--------| | 240 | |--------|---------------------------------|--------| |
| 241 | | `--project yes\|no` | Tout ranger dans un dossier `.mm` ? — posée en premier. `yes` : le fichier est `.mm/agent.yaml` (le dossier est créé), ses chemins sont écrits depuis la racine du projet (`skillsDir: .mm/skills`), et `mm` / `mm tui` lancés là le trouvent sans argument | `no` | | 241 | | `--project yes\|no` | Tout ranger dans un dossier `.mm` ? — posée en premier. `yes` : le fichier est `.mm/agent.yaml` (le dossier est créé), ses chemins sont écrits depuis la racine du projet (`skillsDir: .mm/skills`), et `mm` / `mm tui` lancés là le trouvent sans argument | `no` | |
| 242 | -| `--provider` | Serveur de modèles : `llamacpp`, `llmman`, `ollama`, `dmr`, `kronk`, `openai` | le premier serveur local qui répond, dans cet ordre (`llamacpp` sur 9931, puis 8080), sinon `llamacpp` (`openai` n'est jamais sondé : son adresse par défaut est l'API d'OpenAI) | | 242 | +| `--provider` | Serveur de modèles : `llamacpp`, `llmman`, `ollama`, `dmr`, `kronk`, `openai`, `openai-responses` | le premier serveur local qui répond, dans cet ordre (`llamacpp` sur 9931, puis 8080), sinon `llamacpp` (`openai` et `openai-responses` ne sont jamais sondés : leur adresse par défaut est l'API d'OpenAI) | |
| 243 | -| `--base-url` | `openai` seulement : Endpoint — l'adresse compatible OpenAI du service (OpenAI, Cerebras, Hugging Face…) ; pour les autres fournisseurs, pas posée | `https://api.openai.com/v1` pour `openai` ; sinon `AGENT_BASE_URL` s'il est défini, sinon la première des adresses locales du fournisseur dont la liste de modèles répond — son adresse par défaut, puis la même avec `127.0.0.1` quand elle nomme `localhost`, puis pour `llamacpp` l'ancien port de llama-server, `http://127.0.0.1:8080/v1` — et son adresse de secours pour conteneur (`host.docker.internal`) seulement quand aucune ne répond. La question du modèle nomme l'adresse d'où vient sa liste (`Model? (listed from …)`). Écrite comme `baseUrl` sauf si c'est la valeur par défaut | | 243 | +| `--base-url` | `openai` et `openai-responses` seulement : Endpoint — l'adresse compatible OpenAI du service (OpenAI, Cerebras, Hugging Face…) ; pour les autres fournisseurs, pas posée | `https://api.openai.com/v1` pour `openai` et `openai-responses` ; sinon `AGENT_BASE_URL` s'il est défini, sinon la première des adresses locales du fournisseur dont la liste de modèles répond — son adresse par défaut, puis la même avec `127.0.0.1` quand elle nomme `localhost`, puis pour `llamacpp` l'ancien port de llama-server, `http://127.0.0.1:8080/v1` — et son adresse de secours pour conteneur (`host.docker.internal`) seulement quand aucune ne répond. La question du modèle nomme l'adresse d'où vient sa liste (`Model? (listed from …)`). Écrite comme `baseUrl` sauf si c'est la valeur par défaut | |
| 244 | -| `--api-key-env` | `openai` seulement : variable d'environnement qui contient la clé d'API | `OPENAI_API_KEY`. Écrite comme `apiKeyEnv` sauf si c'est la valeur par défaut | | 244 | +| `--api-key-env` | `openai` et `openai-responses` seulement : variable d'environnement qui contient la clé d'API | `OPENAI_API_KEY`. Écrite comme `apiKeyEnv` sauf si c'est la valeur par défaut | |
| 245 | | `--model` | Modèle : la liste des modèles du serveur (`/api/tags` pour llmman et Ollama, `/models` pour les autres ; 5 s pour un serveur local, 20 s pour `openai`), ou un nom à taper quand il n'y a pas de liste — la question dit pourquoi (`<VARIABLE> is not set: no list`, ou l'erreur du serveur). Pour `openai`, la liste est demandée avec la clé lue dans la variable nommée plus haut, et pas demandée du tout quand cette variable est vide | le premier de la liste | | 245 | | `--model` | Modèle : la liste des modèles du serveur (`/api/tags` pour llmman et Ollama, `/models` pour les autres ; 5 s pour un serveur local, 20 s pour `openai`), ou un nom à taper quand il n'y a pas de liste — la question dit pourquoi (`<VARIABLE> is not set: no list`, ou l'erreur du serveur). Pour `openai`, la liste est demandée avec la clé lue dans la variable nommée plus haut, et pas demandée du tout quand cette variable est vide | le premier de la liste | |
| 246 | | `--family` | Famille du modèle | détectée d'après le nom du modèle, puis d'après le nom de famille donné par le serveur | | 246 | | `--family` | Famille du modèle | détectée d'après le nom du modèle, puis d'après le nom de famille donné par le serveur | |
| 247 | | `--usage` | À quoi sert l'agent : `developer`, `reviewer`, `translator`, `writer`, `assistant`, `researcher`, `docs`, `json`, `coordinator` | `developer` | | 247 | | `--usage` | À quoi sert l'agent : `developer`, `reviewer`, `translator`, `writer`, `assistant`, `researcher`, `docs`, `json`, `coordinator` | `developer` | |
modified
docs/fr/reference/configuration.md +7 -3 | @@ -8,7 +8,7 @@ Où `mm` cherche ce fichier : [Résolution du fichier de configuration](cli.md#r | ||
| 8 | 8 | |
| 9 | 9 | | Clé | Type | Défaut | Description | |
| 10 | 10 | |-----|------|--------|-------------| |
| 11 | -| `provider` | chaîne | `dmr` | Clé du registre du serveur LLM : `dmr`, `llamacpp`, `llmman`, `ollama`, `kronk`, ou `openai` pour tout autre serveur compatible OpenAI (voir [Utiliser n'importe quel serveur compatible OpenAI](../how-to/run-with-an-openai-compatible-server.md)). Surchargée par `AGENT_PROVIDER`. | | |
| 11 | +| `provider` | chaîne | `dmr` | Clé du registre du serveur LLM : `dmr`, `llamacpp`, `llmman`, `ollama`, `kronk`, `openai` pour tout autre serveur compatible OpenAI (voir [Utiliser n'importe quel serveur compatible OpenAI](../how-to/run-with-an-openai-compatible-server.md)), ou `openai-responses` pour les mêmes serveurs par l'API Responses d'OpenAI (voir [Garder le raisonnement et les outils avec l'API Responses d'OpenAI](../how-to/use-the-openai-responses-api.md)). Surchargée par `AGENT_PROVIDER`. | | |
| 12 | 12 | | `model` | chaîne | `huggingface.co/jetbrains/mellum2-12b-a2.5b-instruct-gguf-q4_k_m:Q4_K_M` | Identifiant du modèle dans la nomenclature du fournisseur. Surchargé par `AGENT_MODEL`. | |
| 13 | 13 | | `baseUrl` | chaîne | `""` (défaut du fournisseur) | Point d'accès compatible OpenAI essayé en premier. Surchargé par `AGENT_BASE_URL`. | |
| 14 | 14 | | `fallback` | chaîne ou absente | absente (défaut du fournisseur) | Point d'accès utilisé quand `baseUrl` ne répond pas sur `/models` en 2 s. Absente = défaut du fournisseur ; `""` = pas de repli. | |
| @@ -36,7 +36,7 @@ Où `mm` cherche ce fichier : [Résolution du fichier de configuration](cli.md#r | ||
| 36 | 36 | | `saveAnswerTool` | bool | `false` | Déclare `save_answer`, qui écrit dans un nouveau fichier une réponse que le modèle a déjà donnée : le modèle envoie un nom de fichier, pas le texte une seconde fois. Désactivé par défaut. La commande `/save` existe dans tous les cas. Voir les [outils](tools.md#save_answer). | |
| 37 | 37 | | `unloadModels` | bool | `true` | La commande `/unload [modèle]` (terminal, fenêtre, éditeur) et l'outil `unload_model`, qui libèrent un modèle de la mémoire du serveur : llmman et Ollama, Kronk, llama-server en mode router. `false` retire les deux. L'outil n'est jamais déclaré à côté d'une `structuredOutput` ni d'un bloc `decision`. Voir les [outils](tools.md#unload_model) et [Libérer la mémoire d'un modèle](../how-to/unload-a-model.md). | |
| 38 | 38 | | `autoPull` | booléen | `false` | Au démarrage, télécharge les modèles que cet agent utilisera et que le serveur ne liste pas : le sien, ceux de ses agents `mmConfigs`, ceux de ses deciders `skillRouting` / `toolRouting`. La progression va sur stderr — une ligne réécrite sur place dans un terminal (`⬇ pulling <modèle> — 52 MB / 145 MB (35 %)`), une ligne par dixième ailleurs — puis `⬇ pulled <modèle> in 0.8s`. Un échec sur le modèle de l'agent arrête `mm` avec le message du serveur (`[engine error: autoPull: <modèle>: the server says: …]`) ; un échec sur un autre modèle, un serveur qui ne répond pas ou un fournisseur qui ne sait pas télécharger donne un `[warning: autoPull: …]`. Un agent lancé par `/ask` ou `ask_agent` ne télécharge rien ; `mm --ask` non plus. Un modèle que le serveur liste déjà n'est jamais téléchargé (un nom sans tag correspond aussi à son entrée `:latest`). Par fournisseur : `llmman` et `ollama` — `POST /api/pull` ; `kronk` — `POST /v1/kronk/models/pull`, le téléchargement ne comptant comme fait que si le flux de Kronk se termine par `"downloaded": true` (Kronk répond 200 à un téléchargement raté ; son dernier statut est alors le message) ; `dmr` — `POST /models/create` sur le runner (l'URL de base sans `/engines/…`), le téléchargement ne comptant comme fait qu'une fois le modèle listé par le runner ; `llamacpp` — pas de téléchargement par l'API : l'avertissement dit de lancer llama-server avec `-hf <dépôt>:<quant>`, ou de mettre le GGUF dans le dossier de modèles du router ; `openai` — un avertissement. | |
| 39 | -| `sampling` | dictionnaire | `temperature: 0.0`, `top_p: 0.9`, `max_tokens: 4096` | Paramètres de génération, noms de l'API OpenAI, transmis au serveur. Le bloc du fichier est fusionné avec ces valeurs par défaut : une valeur par défaut que le fichier ne nomme pas est quand même envoyée. **Sauf avec `provider: openai`** : la requête porte exactement le bloc du fichier, rien d'ajouté (pas de bloc : aucune clé de génération, les valeurs par défaut du serveur s'appliquent) — les modèles de raisonnement hébergés par OpenAI refusent `max_tokens` et n'acceptent que la température par défaut, une valeur par défaut laissée là donnerait une erreur 400. Une clé que l'API OpenAI ne déclare pas est envoyée telle quelle, au premier niveau de la requête — par exemple `chat_template_kwargs: {enable_thinking: false}`, qui demande à un serveur llama.cpp (`dmr`, `llamacpp`, `llmman`) ou à Kronk de ne pas raisonner ; `reasoning_effort: none` fait de même avec Ollama. `messages`, `tools`, `tool_choice` (et les anciens `functions`, `function_call`) sont ignorées : Genkit les construit à partir de la conversation. L'`agent.yaml` livré ajoute `parallel_tool_calls: false`. `max_tokens` borne aussi un appel d'outil : un `write_file` de long document (ou le raisonnement d'un modèle « thinking » plus l'appel) peut l'atteindre, et l'appel est alors coupé. mm le rend deux fois au modèle en lui demandant de procéder par morceaux, puis s'arrête avec `the model hit max_tokens (N) while writing a tool call` ; augmentez la valeur si cela arrive. Une configuration qui nomme la limite `max_completion_tokens` (le nom de l'API OpenAI pour ses modèles récents) est lue de la même façon : ce nom est repris dans ce message et dans la requête de résumé de la compression du contexte. En streaming, mm demande aussi au serveur le compte des tokens (`stream_options.include_usage`). | | |
| 39 | +| `sampling` | dictionnaire | `temperature: 0.0`, `top_p: 0.9`, `max_tokens: 4096` | Paramètres de génération, noms de l'API OpenAI, transmis au serveur. Le bloc du fichier est fusionné avec ces valeurs par défaut : une valeur par défaut que le fichier ne nomme pas est quand même envoyée. **Sauf avec `provider: openai` et `provider: openai-responses`** : la requête porte exactement le bloc du fichier, rien d'ajouté (pas de bloc : aucune clé de génération, les valeurs par défaut du serveur s'appliquent) — les modèles de raisonnement hébergés par OpenAI refusent `max_tokens` et n'acceptent que la température par défaut, une valeur par défaut laissée là donnerait une erreur 400. Une clé que l'API OpenAI ne déclare pas est envoyée telle quelle, au premier niveau de la requête — par exemple `chat_template_kwargs: {enable_thinking: false}`, qui demande à un serveur llama.cpp (`dmr`, `llamacpp`, `llmman`) ou à Kronk de ne pas raisonner ; `reasoning_effort: none` fait de même avec Ollama. `messages`, `tools`, `tool_choice` (et les anciens `functions`, `function_call`) sont ignorées : Genkit les construit à partir de la conversation. L'`agent.yaml` livré ajoute `parallel_tool_calls: false`. `max_tokens` borne aussi un appel d'outil : un `write_file` de long document (ou le raisonnement d'un modèle « thinking » plus l'appel) peut l'atteindre, et l'appel est alors coupé. mm le rend deux fois au modèle en lui demandant de procéder par morceaux, puis s'arrête avec `the model hit max_tokens (N) while writing a tool call` ; augmentez la valeur si cela arrive. Une configuration qui nomme la limite `max_completion_tokens` (le nom de l'API OpenAI pour ses modèles récents) est lue de la même façon : ce nom est repris dans ce message et dans la requête de résumé de la compression du contexte. En streaming, mm demande aussi au serveur le compte des tokens (`stream_options.include_usage`). | | |
| 40 | 40 | | `watchdogTimeout` | durée | `20s` | Silence toléré entre deux tokens diffusés avant de déclarer la connexion bloquée. Doublé pour les requêtes de résumé. | |
| 41 | 41 | | `firstTokenTimeout` | durée | `3m` | Silence toléré avant le premier token d'un appel au modèle, pendant que le serveur lit le prompt (chaque aller-retour d'un tour en a un). Jamais plus court que `watchdogTimeout` ; doit être >= 0. Avec un serveur llama.cpp (`dmr`, `llamacpp`, `llmman` — dont les modèles GGUF locaux tournent dans llama-server), mm demande `return_progress` : chaque rapport d'avancement relance ce délai, et le spinner affiche `Reading the prompt 12.0k/25.3k tokens`. Ollama et Kronk n'envoient pas d'avancement : cette seule attente couvre tout le prompt (et le chargement du modèle). À l'expiration, le watchdog dit `no first token from the server after …` (avant le premier token) ou `connection hang detected after …` (après). | |
| 42 | 42 | | `bashTimeout` | durée | `30s` | Durée maximale d'une commande `bash` avant qu'elle soit tuée ; l'outil répond alors `[error: <bashTimeout> timeout exceeded]`. Doit être > 0. Le watchdog continue de compter pendant qu'une commande tourne (ticket 57) : une commande plus longue que `watchdogTimeout` termine le tour, donc relevez les deux ensemble. | |
| @@ -202,11 +202,14 @@ tools: | ||
| 202 | 202 | | `ollama` | `http://localhost:11434/v1` | `http://host.docker.internal:11434/v1` | `OLLAMA_API_KEY` | non | |
| 203 | 203 | | `kronk` | `http://127.0.0.1:11435/v1` | `http://host.docker.internal:11435/v1` | `KRONK_TOKEN` | non — seuls les modes `authenticated` et `full-protected` de Kronk la vérifient | |
| 204 | 204 | | `openai` | `https://api.openai.com/v1` | aucun | `OPENAI_API_KEY` | non — un serveur qui en exige une répond 401, et l'avertissement de démarrage nomme la variable | |
| 205 | +| `openai-responses` | `https://api.openai.com/v1` | aucun | `OPENAI_API_KEY` | non — comme `openai` | | |
| 205 | 206 | |
| 206 | 207 | `llamacpp` : le port par défaut de llama-server est `9931` depuis llama.cpp b11521 (2026-10-09), `8080` avant et dans les images Docker officielles. Quand l'adresse utilisée est `http://127.0.0.1:9931/v1` (pas de `baseUrl`, ou celle-ci) et qu'elle ne répond pas, mm essaie `http://127.0.0.1:8080/v1`, puis le `fallback`. |
| 207 | 208 | |
| 208 | 209 | Le fournisseur `openai` n'envoie que des champs standard : pas de `return_progress` (donc pas de progression pendant la lecture d'un long prompt), pas d'interrupteur de raisonnement sur une requête de résumé, pas de `/unload`. Il ne peut pas demander sa fenêtre au serveur : renseignez `contextWindow`, sinon la compression compte les messages (`context.maxMessages`). Sa sonde de démarrage envoie la clé à `GET /models` ; un 401 ou un 403 est signalé comme une clé refusée, pas comme un serveur qui ne répond pas. |
| 209 | 210 | |
| 211 | +Le fournisseur `openai-responses` (ticket 178) parle aux mêmes serveurs par l'API Responses d'OpenAI, `POST <baseUrl>/responses`, au lieu de Chat Completions : ce qu'il faut aux modèles de raisonnement d'OpenAI pour appeler des outils pendant qu'ils raisonnent. Il envoie le bloc `sampling` tel qu'il est écrit, avec `max_tokens` / `max_completion_tokens` renommés `max_output_tokens` et `reasoning_effort` envoyé comme `reasoning.effort` ; il ajoute `store: false` et `include: ["reasoning.encrypted_content"]` sauf si le bloc les fixe, et renvoie le raisonnement chiffré du modèle avec les résultats des outils. Sa requête de résumé fixe `reasoning.effort: none`. Comme `openai` : pas de progression de lecture du prompt, pas de `/unload`, la fenêtre seulement par `contextWindow`. Voir [Garder le raisonnement et les outils avec l'API Responses d'OpenAI](../how-to/use-the-openai-responses-api.md). | |
| 212 | + | |
| 210 | 213 | ## `structuredOutput` |
| 211 | 214 | |
| 212 | 215 | Un bloc YAML qui contient des déclarations Go. Chaque `type` est une définition ; l'unique `var` (`var X T` ou `var X = T{}`) nomme la racine de la réponse. Seules les déclarations `type` et `var` sont acceptées. |
| @@ -328,6 +331,7 @@ decision: | ||
| 328 | 331 | | `llmman` | oui | |
| 329 | 332 | | `ollama` | oui | |
| 330 | 333 | | `openai` | celle du serveur : un serveur sans la route répond 404 | |
| 334 | +| `openai-responses` | non — refusé au démarrage | | |
| 331 | 335 | | `dmr` | non (404, Docker Model Runner v1.2.8) — refusé au démarrage | |
| 332 | 336 | |
| 333 | 337 | La route sert les modèles qu'elle reconnaît comme modèles de décision : LiquidAI d1 (`LiquidAI/d1-3B-GGUF:Q4_K_M`) a été accepté par les trois ; `decision-4b` d'evalengine a été refusé par llmman (`501 This model is not a decision model`) et Ollama (`400 … is not a llama.cpp decision model`). |
| @@ -470,7 +474,7 @@ Signalées sur stderr sous la forme `[config error: <chemin>: <message>]`, code | ||
| 470 | 474 | | `mmConfigs: "with-context-x" is not a valid name (it would read as /ask-with-context-…)` | un nom commençant par `with-context` | |
| 471 | 475 | | `mmConfigs.<nom>: the path must not be empty` | `<nom>: ""`, ou une forme longue sans `path` | |
| 472 | 476 | | `hooks: unknown event "x" (…)`, `hooks.<événement>[N]: …` | un bloc `hooks:` invalide — voir [les hooks](hooks.md#erreurs-de-validation) | |
| 473 | -| `unknown provider "x" (known: dmr, kronk, llamacpp, llmman, ollama, openai)` | Signalée par le moteur, sous la forme `[engine error: …]`. | | |
| 477 | +| `unknown provider "x" (known: dmr, kronk, llamacpp, llmman, ollama, openai, openai-responses)` | Signalée par le moteur, sous la forme `[engine error: …]`. | | |
| 474 | 478 | |
| 475 | 479 | Un avertissement au démarrage, et non une erreur, est affiché quand `context.enabled` vaut `true`, que la fenêtre est inconnue et que `context.maxMessages` vaut `0`, quand un outil déclaré porte le nom d'un outil MCP (`tools: <nom> skipped — an MCP tool already has that name` ; l'outil n'est pas déclaré), et quand le fichier pose la clé obsolète `permissions` (`permissions: ask is deprecated — use yolo: false instead …`). |
| 476 | 480 | |
| @@ -8,7 +8,7 @@ Où `mm` cherche ce fichier : [Résolution du fichier de configuration](cli.md#r | |||
| 8 | 8 | ||
| 9 | | Clé | Type | Défaut | Description | | 9 | | Clé | Type | Défaut | Description | |
| 10 | |-----|------|--------|-------------| | 10 | |-----|------|--------|-------------| |
| 11 | -| `provider` | chaîne | `dmr` | Clé du registre du serveur LLM : `dmr`, `llamacpp`, `llmman`, `ollama`, `kronk`, ou `openai` pour tout autre serveur compatible OpenAI (voir [Utiliser n'importe quel serveur compatible OpenAI](../how-to/run-with-an-openai-compatible-server.md)). Surchargée par `AGENT_PROVIDER`. | | 11 | +| `provider` | chaîne | `dmr` | Clé du registre du serveur LLM : `dmr`, `llamacpp`, `llmman`, `ollama`, `kronk`, `openai` pour tout autre serveur compatible OpenAI (voir [Utiliser n'importe quel serveur compatible OpenAI](../how-to/run-with-an-openai-compatible-server.md)), ou `openai-responses` pour les mêmes serveurs par l'API Responses d'OpenAI (voir [Garder le raisonnement et les outils avec l'API Responses d'OpenAI](../how-to/use-the-openai-responses-api.md)). Surchargée par `AGENT_PROVIDER`. | |
| 12 | | `model` | chaîne | `huggingface.co/jetbrains/mellum2-12b-a2.5b-instruct-gguf-q4_k_m:Q4_K_M` | Identifiant du modèle dans la nomenclature du fournisseur. Surchargé par `AGENT_MODEL`. | | 12 | | `model` | chaîne | `huggingface.co/jetbrains/mellum2-12b-a2.5b-instruct-gguf-q4_k_m:Q4_K_M` | Identifiant du modèle dans la nomenclature du fournisseur. Surchargé par `AGENT_MODEL`. | |
| 13 | | `baseUrl` | chaîne | `""` (défaut du fournisseur) | Point d'accès compatible OpenAI essayé en premier. Surchargé par `AGENT_BASE_URL`. | | 13 | | `baseUrl` | chaîne | `""` (défaut du fournisseur) | Point d'accès compatible OpenAI essayé en premier. Surchargé par `AGENT_BASE_URL`. | |
| 14 | | `fallback` | chaîne ou absente | absente (défaut du fournisseur) | Point d'accès utilisé quand `baseUrl` ne répond pas sur `/models` en 2 s. Absente = défaut du fournisseur ; `""` = pas de repli. | | 14 | | `fallback` | chaîne ou absente | absente (défaut du fournisseur) | Point d'accès utilisé quand `baseUrl` ne répond pas sur `/models` en 2 s. Absente = défaut du fournisseur ; `""` = pas de repli. | |
| @@ -36,7 +36,7 @@ Où `mm` cherche ce fichier : [Résolution du fichier de configuration](cli.md#r | |||
| 36 | | `saveAnswerTool` | bool | `false` | Déclare `save_answer`, qui écrit dans un nouveau fichier une réponse que le modèle a déjà donnée : le modèle envoie un nom de fichier, pas le texte une seconde fois. Désactivé par défaut. La commande `/save` existe dans tous les cas. Voir les [outils](tools.md#save_answer). | | 36 | | `saveAnswerTool` | bool | `false` | Déclare `save_answer`, qui écrit dans un nouveau fichier une réponse que le modèle a déjà donnée : le modèle envoie un nom de fichier, pas le texte une seconde fois. Désactivé par défaut. La commande `/save` existe dans tous les cas. Voir les [outils](tools.md#save_answer). | |
| 37 | | `unloadModels` | bool | `true` | La commande `/unload [modèle]` (terminal, fenêtre, éditeur) et l'outil `unload_model`, qui libèrent un modèle de la mémoire du serveur : llmman et Ollama, Kronk, llama-server en mode router. `false` retire les deux. L'outil n'est jamais déclaré à côté d'une `structuredOutput` ni d'un bloc `decision`. Voir les [outils](tools.md#unload_model) et [Libérer la mémoire d'un modèle](../how-to/unload-a-model.md). | | 37 | | `unloadModels` | bool | `true` | La commande `/unload [modèle]` (terminal, fenêtre, éditeur) et l'outil `unload_model`, qui libèrent un modèle de la mémoire du serveur : llmman et Ollama, Kronk, llama-server en mode router. `false` retire les deux. L'outil n'est jamais déclaré à côté d'une `structuredOutput` ni d'un bloc `decision`. Voir les [outils](tools.md#unload_model) et [Libérer la mémoire d'un modèle](../how-to/unload-a-model.md). | |
| 38 | | `autoPull` | booléen | `false` | Au démarrage, télécharge les modèles que cet agent utilisera et que le serveur ne liste pas : le sien, ceux de ses agents `mmConfigs`, ceux de ses deciders `skillRouting` / `toolRouting`. La progression va sur stderr — une ligne réécrite sur place dans un terminal (`⬇ pulling <modèle> — 52 MB / 145 MB (35 %)`), une ligne par dixième ailleurs — puis `⬇ pulled <modèle> in 0.8s`. Un échec sur le modèle de l'agent arrête `mm` avec le message du serveur (`[engine error: autoPull: <modèle>: the server says: …]`) ; un échec sur un autre modèle, un serveur qui ne répond pas ou un fournisseur qui ne sait pas télécharger donne un `[warning: autoPull: …]`. Un agent lancé par `/ask` ou `ask_agent` ne télécharge rien ; `mm --ask` non plus. Un modèle que le serveur liste déjà n'est jamais téléchargé (un nom sans tag correspond aussi à son entrée `:latest`). Par fournisseur : `llmman` et `ollama` — `POST /api/pull` ; `kronk` — `POST /v1/kronk/models/pull`, le téléchargement ne comptant comme fait que si le flux de Kronk se termine par `"downloaded": true` (Kronk répond 200 à un téléchargement raté ; son dernier statut est alors le message) ; `dmr` — `POST /models/create` sur le runner (l'URL de base sans `/engines/…`), le téléchargement ne comptant comme fait qu'une fois le modèle listé par le runner ; `llamacpp` — pas de téléchargement par l'API : l'avertissement dit de lancer llama-server avec `-hf <dépôt>:<quant>`, ou de mettre le GGUF dans le dossier de modèles du router ; `openai` — un avertissement. | | 38 | | `autoPull` | booléen | `false` | Au démarrage, télécharge les modèles que cet agent utilisera et que le serveur ne liste pas : le sien, ceux de ses agents `mmConfigs`, ceux de ses deciders `skillRouting` / `toolRouting`. La progression va sur stderr — une ligne réécrite sur place dans un terminal (`⬇ pulling <modèle> — 52 MB / 145 MB (35 %)`), une ligne par dixième ailleurs — puis `⬇ pulled <modèle> in 0.8s`. Un échec sur le modèle de l'agent arrête `mm` avec le message du serveur (`[engine error: autoPull: <modèle>: the server says: …]`) ; un échec sur un autre modèle, un serveur qui ne répond pas ou un fournisseur qui ne sait pas télécharger donne un `[warning: autoPull: …]`. Un agent lancé par `/ask` ou `ask_agent` ne télécharge rien ; `mm --ask` non plus. Un modèle que le serveur liste déjà n'est jamais téléchargé (un nom sans tag correspond aussi à son entrée `:latest`). Par fournisseur : `llmman` et `ollama` — `POST /api/pull` ; `kronk` — `POST /v1/kronk/models/pull`, le téléchargement ne comptant comme fait que si le flux de Kronk se termine par `"downloaded": true` (Kronk répond 200 à un téléchargement raté ; son dernier statut est alors le message) ; `dmr` — `POST /models/create` sur le runner (l'URL de base sans `/engines/…`), le téléchargement ne comptant comme fait qu'une fois le modèle listé par le runner ; `llamacpp` — pas de téléchargement par l'API : l'avertissement dit de lancer llama-server avec `-hf <dépôt>:<quant>`, ou de mettre le GGUF dans le dossier de modèles du router ; `openai` — un avertissement. | |
| 39 | -| `sampling` | dictionnaire | `temperature: 0.0`, `top_p: 0.9`, `max_tokens: 4096` | Paramètres de génération, noms de l'API OpenAI, transmis au serveur. Le bloc du fichier est fusionné avec ces valeurs par défaut : une valeur par défaut que le fichier ne nomme pas est quand même envoyée. **Sauf avec `provider: openai`** : la requête porte exactement le bloc du fichier, rien d'ajouté (pas de bloc : aucune clé de génération, les valeurs par défaut du serveur s'appliquent) — les modèles de raisonnement hébergés par OpenAI refusent `max_tokens` et n'acceptent que la température par défaut, une valeur par défaut laissée là donnerait une erreur 400. Une clé que l'API OpenAI ne déclare pas est envoyée telle quelle, au premier niveau de la requête — par exemple `chat_template_kwargs: {enable_thinking: false}`, qui demande à un serveur llama.cpp (`dmr`, `llamacpp`, `llmman`) ou à Kronk de ne pas raisonner ; `reasoning_effort: none` fait de même avec Ollama. `messages`, `tools`, `tool_choice` (et les anciens `functions`, `function_call`) sont ignorées : Genkit les construit à partir de la conversation. L'`agent.yaml` livré ajoute `parallel_tool_calls: false`. `max_tokens` borne aussi un appel d'outil : un `write_file` de long document (ou le raisonnement d'un modèle « thinking » plus l'appel) peut l'atteindre, et l'appel est alors coupé. mm le rend deux fois au modèle en lui demandant de procéder par morceaux, puis s'arrête avec `the model hit max_tokens (N) while writing a tool call` ; augmentez la valeur si cela arrive. Une configuration qui nomme la limite `max_completion_tokens` (le nom de l'API OpenAI pour ses modèles récents) est lue de la même façon : ce nom est repris dans ce message et dans la requête de résumé de la compression du contexte. En streaming, mm demande aussi au serveur le compte des tokens (`stream_options.include_usage`). | | 39 | +| `sampling` | dictionnaire | `temperature: 0.0`, `top_p: 0.9`, `max_tokens: 4096` | Paramètres de génération, noms de l'API OpenAI, transmis au serveur. Le bloc du fichier est fusionné avec ces valeurs par défaut : une valeur par défaut que le fichier ne nomme pas est quand même envoyée. **Sauf avec `provider: openai` et `provider: openai-responses`** : la requête porte exactement le bloc du fichier, rien d'ajouté (pas de bloc : aucune clé de génération, les valeurs par défaut du serveur s'appliquent) — les modèles de raisonnement hébergés par OpenAI refusent `max_tokens` et n'acceptent que la température par défaut, une valeur par défaut laissée là donnerait une erreur 400. Une clé que l'API OpenAI ne déclare pas est envoyée telle quelle, au premier niveau de la requête — par exemple `chat_template_kwargs: {enable_thinking: false}`, qui demande à un serveur llama.cpp (`dmr`, `llamacpp`, `llmman`) ou à Kronk de ne pas raisonner ; `reasoning_effort: none` fait de même avec Ollama. `messages`, `tools`, `tool_choice` (et les anciens `functions`, `function_call`) sont ignorées : Genkit les construit à partir de la conversation. L'`agent.yaml` livré ajoute `parallel_tool_calls: false`. `max_tokens` borne aussi un appel d'outil : un `write_file` de long document (ou le raisonnement d'un modèle « thinking » plus l'appel) peut l'atteindre, et l'appel est alors coupé. mm le rend deux fois au modèle en lui demandant de procéder par morceaux, puis s'arrête avec `the model hit max_tokens (N) while writing a tool call` ; augmentez la valeur si cela arrive. Une configuration qui nomme la limite `max_completion_tokens` (le nom de l'API OpenAI pour ses modèles récents) est lue de la même façon : ce nom est repris dans ce message et dans la requête de résumé de la compression du contexte. En streaming, mm demande aussi au serveur le compte des tokens (`stream_options.include_usage`). | |
| 40 | | `watchdogTimeout` | durée | `20s` | Silence toléré entre deux tokens diffusés avant de déclarer la connexion bloquée. Doublé pour les requêtes de résumé. | | 40 | | `watchdogTimeout` | durée | `20s` | Silence toléré entre deux tokens diffusés avant de déclarer la connexion bloquée. Doublé pour les requêtes de résumé. | |
| 41 | | `firstTokenTimeout` | durée | `3m` | Silence toléré avant le premier token d'un appel au modèle, pendant que le serveur lit le prompt (chaque aller-retour d'un tour en a un). Jamais plus court que `watchdogTimeout` ; doit être >= 0. Avec un serveur llama.cpp (`dmr`, `llamacpp`, `llmman` — dont les modèles GGUF locaux tournent dans llama-server), mm demande `return_progress` : chaque rapport d'avancement relance ce délai, et le spinner affiche `Reading the prompt 12.0k/25.3k tokens`. Ollama et Kronk n'envoient pas d'avancement : cette seule attente couvre tout le prompt (et le chargement du modèle). À l'expiration, le watchdog dit `no first token from the server after …` (avant le premier token) ou `connection hang detected after …` (après). | | 41 | | `firstTokenTimeout` | durée | `3m` | Silence toléré avant le premier token d'un appel au modèle, pendant que le serveur lit le prompt (chaque aller-retour d'un tour en a un). Jamais plus court que `watchdogTimeout` ; doit être >= 0. Avec un serveur llama.cpp (`dmr`, `llamacpp`, `llmman` — dont les modèles GGUF locaux tournent dans llama-server), mm demande `return_progress` : chaque rapport d'avancement relance ce délai, et le spinner affiche `Reading the prompt 12.0k/25.3k tokens`. Ollama et Kronk n'envoient pas d'avancement : cette seule attente couvre tout le prompt (et le chargement du modèle). À l'expiration, le watchdog dit `no first token from the server after …` (avant le premier token) ou `connection hang detected after …` (après). | |
| 42 | | `bashTimeout` | durée | `30s` | Durée maximale d'une commande `bash` avant qu'elle soit tuée ; l'outil répond alors `[error: <bashTimeout> timeout exceeded]`. Doit être > 0. Le watchdog continue de compter pendant qu'une commande tourne (ticket 57) : une commande plus longue que `watchdogTimeout` termine le tour, donc relevez les deux ensemble. | | 42 | | `bashTimeout` | durée | `30s` | Durée maximale d'une commande `bash` avant qu'elle soit tuée ; l'outil répond alors `[error: <bashTimeout> timeout exceeded]`. Doit être > 0. Le watchdog continue de compter pendant qu'une commande tourne (ticket 57) : une commande plus longue que `watchdogTimeout` termine le tour, donc relevez les deux ensemble. | |
| @@ -202,11 +202,14 @@ tools: | |||
| 202 | | `ollama` | `http://localhost:11434/v1` | `http://host.docker.internal:11434/v1` | `OLLAMA_API_KEY` | non | | 202 | | `ollama` | `http://localhost:11434/v1` | `http://host.docker.internal:11434/v1` | `OLLAMA_API_KEY` | non | |
| 203 | | `kronk` | `http://127.0.0.1:11435/v1` | `http://host.docker.internal:11435/v1` | `KRONK_TOKEN` | non — seuls les modes `authenticated` et `full-protected` de Kronk la vérifient | | 203 | | `kronk` | `http://127.0.0.1:11435/v1` | `http://host.docker.internal:11435/v1` | `KRONK_TOKEN` | non — seuls les modes `authenticated` et `full-protected` de Kronk la vérifient | |
| 204 | | `openai` | `https://api.openai.com/v1` | aucun | `OPENAI_API_KEY` | non — un serveur qui en exige une répond 401, et l'avertissement de démarrage nomme la variable | | 204 | | `openai` | `https://api.openai.com/v1` | aucun | `OPENAI_API_KEY` | non — un serveur qui en exige une répond 401, et l'avertissement de démarrage nomme la variable | |
| 205 | +| `openai-responses` | `https://api.openai.com/v1` | aucun | `OPENAI_API_KEY` | non — comme `openai` | | ||
| 205 | 206 | ||
| 206 | `llamacpp` : le port par défaut de llama-server est `9931` depuis llama.cpp b11521 (2026-10-09), `8080` avant et dans les images Docker officielles. Quand l'adresse utilisée est `http://127.0.0.1:9931/v1` (pas de `baseUrl`, ou celle-ci) et qu'elle ne répond pas, mm essaie `http://127.0.0.1:8080/v1`, puis le `fallback`. | 207 | `llamacpp` : le port par défaut de llama-server est `9931` depuis llama.cpp b11521 (2026-10-09), `8080` avant et dans les images Docker officielles. Quand l'adresse utilisée est `http://127.0.0.1:9931/v1` (pas de `baseUrl`, ou celle-ci) et qu'elle ne répond pas, mm essaie `http://127.0.0.1:8080/v1`, puis le `fallback`. |
| 207 | 208 | ||
| 208 | Le fournisseur `openai` n'envoie que des champs standard : pas de `return_progress` (donc pas de progression pendant la lecture d'un long prompt), pas d'interrupteur de raisonnement sur une requête de résumé, pas de `/unload`. Il ne peut pas demander sa fenêtre au serveur : renseignez `contextWindow`, sinon la compression compte les messages (`context.maxMessages`). Sa sonde de démarrage envoie la clé à `GET /models` ; un 401 ou un 403 est signalé comme une clé refusée, pas comme un serveur qui ne répond pas. | 209 | Le fournisseur `openai` n'envoie que des champs standard : pas de `return_progress` (donc pas de progression pendant la lecture d'un long prompt), pas d'interrupteur de raisonnement sur une requête de résumé, pas de `/unload`. Il ne peut pas demander sa fenêtre au serveur : renseignez `contextWindow`, sinon la compression compte les messages (`context.maxMessages`). Sa sonde de démarrage envoie la clé à `GET /models` ; un 401 ou un 403 est signalé comme une clé refusée, pas comme un serveur qui ne répond pas. |
| 209 | 210 | ||
| 211 | +Le fournisseur `openai-responses` (ticket 178) parle aux mêmes serveurs par l'API Responses d'OpenAI, `POST <baseUrl>/responses`, au lieu de Chat Completions : ce qu'il faut aux modèles de raisonnement d'OpenAI pour appeler des outils pendant qu'ils raisonnent. Il envoie le bloc `sampling` tel qu'il est écrit, avec `max_tokens` / `max_completion_tokens` renommés `max_output_tokens` et `reasoning_effort` envoyé comme `reasoning.effort` ; il ajoute `store: false` et `include: ["reasoning.encrypted_content"]` sauf si le bloc les fixe, et renvoie le raisonnement chiffré du modèle avec les résultats des outils. Sa requête de résumé fixe `reasoning.effort: none`. Comme `openai` : pas de progression de lecture du prompt, pas de `/unload`, la fenêtre seulement par `contextWindow`. Voir [Garder le raisonnement et les outils avec l'API Responses d'OpenAI](../how-to/use-the-openai-responses-api.md). | ||
| 212 | + | ||
| 210 | ## `structuredOutput` | 213 | ## `structuredOutput` |
| 211 | 214 | ||
| 212 | Un bloc YAML qui contient des déclarations Go. Chaque `type` est une définition ; l'unique `var` (`var X T` ou `var X = T{}`) nomme la racine de la réponse. Seules les déclarations `type` et `var` sont acceptées. | 215 | Un bloc YAML qui contient des déclarations Go. Chaque `type` est une définition ; l'unique `var` (`var X T` ou `var X = T{}`) nomme la racine de la réponse. Seules les déclarations `type` et `var` sont acceptées. |
| @@ -328,6 +331,7 @@ decision: | |||
| 328 | | `llmman` | oui | | 331 | | `llmman` | oui | |
| 329 | | `ollama` | oui | | 332 | | `ollama` | oui | |
| 330 | | `openai` | celle du serveur : un serveur sans la route répond 404 | | 333 | | `openai` | celle du serveur : un serveur sans la route répond 404 | |
| 334 | +| `openai-responses` | non — refusé au démarrage | | ||
| 331 | | `dmr` | non (404, Docker Model Runner v1.2.8) — refusé au démarrage | | 335 | | `dmr` | non (404, Docker Model Runner v1.2.8) — refusé au démarrage | |
| 332 | 336 | ||
| 333 | La route sert les modèles qu'elle reconnaît comme modèles de décision : LiquidAI d1 (`LiquidAI/d1-3B-GGUF:Q4_K_M`) a été accepté par les trois ; `decision-4b` d'evalengine a été refusé par llmman (`501 This model is not a decision model`) et Ollama (`400 … is not a llama.cpp decision model`). | 337 | La route sert les modèles qu'elle reconnaît comme modèles de décision : LiquidAI d1 (`LiquidAI/d1-3B-GGUF:Q4_K_M`) a été accepté par les trois ; `decision-4b` d'evalengine a été refusé par llmman (`501 This model is not a decision model`) et Ollama (`400 … is not a llama.cpp decision model`). |
| @@ -470,7 +474,7 @@ Signalées sur stderr sous la forme `[config error: <chemin>: <message>]`, code | |||
| 470 | | `mmConfigs: "with-context-x" is not a valid name (it would read as /ask-with-context-…)` | un nom commençant par `with-context` | | 474 | | `mmConfigs: "with-context-x" is not a valid name (it would read as /ask-with-context-…)` | un nom commençant par `with-context` | |
| 471 | | `mmConfigs.<nom>: the path must not be empty` | `<nom>: ""`, ou une forme longue sans `path` | | 475 | | `mmConfigs.<nom>: the path must not be empty` | `<nom>: ""`, ou une forme longue sans `path` | |
| 472 | | `hooks: unknown event "x" (…)`, `hooks.<événement>[N]: …` | un bloc `hooks:` invalide — voir [les hooks](hooks.md#erreurs-de-validation) | | 476 | | `hooks: unknown event "x" (…)`, `hooks.<événement>[N]: …` | un bloc `hooks:` invalide — voir [les hooks](hooks.md#erreurs-de-validation) | |
| 473 | -| `unknown provider "x" (known: dmr, kronk, llamacpp, llmman, ollama, openai)` | Signalée par le moteur, sous la forme `[engine error: …]`. | | 477 | +| `unknown provider "x" (known: dmr, kronk, llamacpp, llmman, ollama, openai, openai-responses)` | Signalée par le moteur, sous la forme `[engine error: …]`. | |
| 474 | 478 | ||
| 475 | Un avertissement au démarrage, et non une erreur, est affiché quand `context.enabled` vaut `true`, que la fenêtre est inconnue et que `context.maxMessages` vaut `0`, quand un outil déclaré porte le nom d'un outil MCP (`tools: <nom> skipped — an MCP tool already has that name` ; l'outil n'est pas déclaré), et quand le fichier pose la clé obsolète `permissions` (`permissions: ask is deprecated — use yolo: false instead …`). | 479 | Un avertissement au démarrage, et non une erreur, est affiché quand `context.enabled` vaut `true`, que la fenêtre est inconnue et que `context.maxMessages` vaut `0`, quand un outil déclaré porte le nom d'un outil MCP (`tools: <nom> skipped — an MCP tool already has that name` ; l'outil n'est pas déclaré), et quand le fichier pose la clé obsolète `permissions` (`permissions: ask is deprecated — use yolo: false instead …`). |
| 476 | 480 | ||
modified
internal/agentinit/decide.go +2 -2 | @@ -7,7 +7,7 @@ import ( | ||
| 7 | 7 | |
| 8 | 8 | // Choices are the wizard's answers. |
| 9 | 9 | type Choices struct { |
| 10 | - Provider string // llamacpp, llmman, ollama, dmr, kronk, openai | |
| 10 | + Provider string // llamacpp, llmman, ollama, dmr, kronk, openai, openai-responses | |
| 11 | 11 | BaseURL string // "" = the provider's default |
| 12 | 12 | // APIKeyEnv names the variable holding the API key of an |
| 13 | 13 | // OpenAI-compatible service (provider openai); "" = OPENAI_API_KEY. |
| @@ -129,7 +129,7 @@ func (s *Settings) decideTop() { | ||
| 129 | 129 | u, m, f := s.Usage, s.Machine, s.Facts |
| 130 | 130 | window := "0" |
| 131 | 131 | reason := "0 = mm asks the server for the window it serves" |
| 132 | - if s.Choices.Provider == "openai" { | |
| 132 | + if isOpenAI(s.Choices.Provider) { | |
| 133 | 133 | reason = "0 = unknown: the generic openai provider cannot ask the server for its window, so compression counts messages (context.maxMessages) instead — set the window your server serves" |
| 134 | 134 | } |
| 135 | 135 | if f.ContextLength > 0 { |
| @@ -7,7 +7,7 @@ import ( | |||
| 7 | 7 | ||
| 8 | // Choices are the wizard's answers. | 8 | // Choices are the wizard's answers. |
| 9 | type Choices struct { | 9 | type Choices struct { |
| 10 | - Provider string // llamacpp, llmman, ollama, dmr, kronk, openai | 10 | + Provider string // llamacpp, llmman, ollama, dmr, kronk, openai, openai-responses |
| 11 | BaseURL string // "" = the provider's default | 11 | BaseURL string // "" = the provider's default |
| 12 | // APIKeyEnv names the variable holding the API key of an | 12 | // APIKeyEnv names the variable holding the API key of an |
| 13 | // OpenAI-compatible service (provider openai); "" = OPENAI_API_KEY. | 13 | // OpenAI-compatible service (provider openai); "" = OPENAI_API_KEY. |
| @@ -129,7 +129,7 @@ func (s *Settings) decideTop() { | |||
| 129 | u, m, f := s.Usage, s.Machine, s.Facts | 129 | u, m, f := s.Usage, s.Machine, s.Facts |
| 130 | window := "0" | 130 | window := "0" |
| 131 | reason := "0 = mm asks the server for the window it serves" | 131 | reason := "0 = mm asks the server for the window it serves" |
| 132 | - if s.Choices.Provider == "openai" { | 132 | + if isOpenAI(s.Choices.Provider) { |
| 133 | reason = "0 = unknown: the generic openai provider cannot ask the server for its window, so compression counts messages (context.maxMessages) instead — set the window your server serves" | 133 | reason = "0 = unknown: the generic openai provider cannot ask the server for its window, so compression counts messages (context.maxMessages) instead — set the window your server serves" |
| 134 | } | 134 | } |
| 135 | if f.ContextLength > 0 { | 135 | if f.ContextLength > 0 { |
modified
internal/agentinit/facts.go +2 -2 | @@ -105,7 +105,7 @@ func call(ctx context.Context, method, url string, body any, timeout time.Durati | ||
| 105 | 105 | // names, err := agentinit.Models(ctx, "llmman", "http://127.0.0.1:17434/v1") |
| 106 | 106 | func Models(ctx context.Context, provider, base string) ([]string, error) { |
| 107 | 107 | key := "" |
| 108 | - if provider == "openai" { | |
| 108 | + if isOpenAI(provider) { | |
| 109 | 109 | key = os.Getenv("OPENAI_API_KEY") |
| 110 | 110 | } |
| 111 | 111 | return ListModels(ctx, provider, base, key) |
| @@ -129,7 +129,7 @@ const ( | ||
| 129 | 129 | func ListModels(ctx context.Context, provider, base, key string) ([]string, error) { |
| 130 | 130 | ctx = withKey(ctx, key) |
| 131 | 131 | timeout := localListTimeout |
| 132 | - if provider == "openai" { | |
| 132 | + if isOpenAI(provider) { | |
| 133 | 133 | timeout = remoteListTimeout |
| 134 | 134 | } |
| 135 | 135 | var names []string |
| @@ -105,7 +105,7 @@ func call(ctx context.Context, method, url string, body any, timeout time.Durati | |||
| 105 | // names, err := agentinit.Models(ctx, "llmman", "http://127.0.0.1:17434/v1") | 105 | // names, err := agentinit.Models(ctx, "llmman", "http://127.0.0.1:17434/v1") |
| 106 | func Models(ctx context.Context, provider, base string) ([]string, error) { | 106 | func Models(ctx context.Context, provider, base string) ([]string, error) { |
| 107 | key := "" | 107 | key := "" |
| 108 | - if provider == "openai" { | 108 | + if isOpenAI(provider) { |
| 109 | key = os.Getenv("OPENAI_API_KEY") | 109 | key = os.Getenv("OPENAI_API_KEY") |
| 110 | } | 110 | } |
| 111 | return ListModels(ctx, provider, base, key) | 111 | return ListModels(ctx, provider, base, key) |
| @@ -129,7 +129,7 @@ const ( | |||
| 129 | func ListModels(ctx context.Context, provider, base, key string) ([]string, error) { | 129 | func ListModels(ctx context.Context, provider, base, key string) ([]string, error) { |
| 130 | ctx = withKey(ctx, key) | 130 | ctx = withKey(ctx, key) |
| 131 | timeout := localListTimeout | 131 | timeout := localListTimeout |
| 132 | - if provider == "openai" { | 132 | + if isOpenAI(provider) { |
| 133 | timeout = remoteListTimeout | 133 | timeout = remoteListTimeout |
| 134 | } | 134 | } |
| 135 | var names []string | 135 | var names []string |
modified
internal/agentinit/flow.go +13 -5 | @@ -144,7 +144,7 @@ func (f *Flow) Steps() []Step { | ||
| 144 | 144 | if key == "yolo" && !f.asksYolo() { |
| 145 | 145 | continue |
| 146 | 146 | } |
| 147 | - if (key == "endpoint" || key == "keyenv") && f.c.Provider != "openai" { | |
| 147 | + if (key == "endpoint" || key == "keyenv") && !isOpenAI(f.c.Provider) { | |
| 148 | 148 | continue |
| 149 | 149 | } |
| 150 | 150 | out = append(out, f.Step(key)) |
| @@ -349,7 +349,7 @@ func (f *Flow) Set(key, value string) error { | ||
| 349 | 349 | // The OpenAI API's own address is openai's default: no baseUrl |
| 350 | 350 | // line then, the file records it as a comment instead. |
| 351 | 351 | f.c.BaseURL = value |
| 352 | - if f.c.Provider == "openai" && value == openAIDefaultBase() { | |
| 352 | + if isOpenAI(f.c.Provider) && value == openAIDefaultBase() { | |
| 353 | 353 | f.c.BaseURL = "" |
| 354 | 354 | } |
| 355 | 355 | f.base = "" |
| @@ -527,7 +527,7 @@ func (f *Flow) keyEnv() string { | ||
| 527 | 527 | // typeModelPrompt asks for the model's ID when there is no list, and says |
| 528 | 528 | // why — in the window as in the line mode, both show the prompt. |
| 529 | 529 | func (f *Flow) typeModelPrompt() string { |
| 530 | - if f.c.Provider == "openai" && os.Getenv(f.keyEnv()) == "" { | |
| 530 | + if isOpenAI(f.c.Provider) && os.Getenv(f.keyEnv()) == "" { | |
| 531 | 531 | return fmt.Sprintf("Model ID? (%s is not set: no list — type it)", f.keyEnv()) |
| 532 | 532 | } |
| 533 | 533 | if f.modelsErr != nil { |
| @@ -536,6 +536,14 @@ func (f *Flow) typeModelPrompt() string { | ||
| 536 | 536 | return "Model (as the server names it)?" |
| 537 | 537 | } |
| 538 | 538 | |
| 539 | +// isOpenAI: the provider is an OpenAI-compatible service mm asks for an | |
| 540 | +// endpoint and a key variable — `openai` (Chat Completions) and | |
| 541 | +// `openai-responses` (the Responses API, ticket 178), which share their | |
| 542 | +// address and key. | |
| 543 | +func isOpenAI(provider string) bool { | |
| 544 | + return provider == "openai" || provider == "openai-responses" | |
| 545 | +} | |
| 546 | + | |
| 539 | 547 | // openAIDefaultBase is the openai provider's default address (the OpenAI API). |
| 540 | 548 | func openAIDefaultBase() string { |
| 541 | 549 | base, _, _ := engine.DefaultURLs("openai") |
| @@ -596,7 +604,7 @@ func (f *Flow) modelList() []string { | ||
| 596 | 604 | return nil |
| 597 | 605 | } |
| 598 | 606 | key := f.c.Provider + " " + f.Base() |
| 599 | - if f.c.Provider == "openai" { | |
| 607 | + if isOpenAI(f.c.Provider) { | |
| 600 | 608 | key += " " + f.keyEnv() |
| 601 | 609 | } |
| 602 | 610 | if f.listed != key { |
| @@ -610,7 +618,7 @@ func (f *Flow) modelList() []string { | ||
| 610 | 618 | // is asked with the key read from the variable the user named — and not at |
| 611 | 619 | // all when that variable is empty: the request would only be refused. |
| 612 | 620 | func (f *Flow) listModels() ([]string, error) { |
| 613 | - if f.c.Provider != "openai" { | |
| 621 | + if !isOpenAI(f.c.Provider) { | |
| 614 | 622 | return Models(f.ctx, f.c.Provider, f.Base()) |
| 615 | 623 | } |
| 616 | 624 | key := os.Getenv(f.keyEnv()) |
| @@ -144,7 +144,7 @@ func (f *Flow) Steps() []Step { | |||
| 144 | if key == "yolo" && !f.asksYolo() { | 144 | if key == "yolo" && !f.asksYolo() { |
| 145 | continue | 145 | continue |
| 146 | } | 146 | } |
| 147 | - if (key == "endpoint" || key == "keyenv") && f.c.Provider != "openai" { | 147 | + if (key == "endpoint" || key == "keyenv") && !isOpenAI(f.c.Provider) { |
| 148 | continue | 148 | continue |
| 149 | } | 149 | } |
| 150 | out = append(out, f.Step(key)) | 150 | out = append(out, f.Step(key)) |
| @@ -349,7 +349,7 @@ func (f *Flow) Set(key, value string) error { | |||
| 349 | // The OpenAI API's own address is openai's default: no baseUrl | 349 | // The OpenAI API's own address is openai's default: no baseUrl |
| 350 | // line then, the file records it as a comment instead. | 350 | // line then, the file records it as a comment instead. |
| 351 | f.c.BaseURL = value | 351 | f.c.BaseURL = value |
| 352 | - if f.c.Provider == "openai" && value == openAIDefaultBase() { | 352 | + if isOpenAI(f.c.Provider) && value == openAIDefaultBase() { |
| 353 | f.c.BaseURL = "" | 353 | f.c.BaseURL = "" |
| 354 | } | 354 | } |
| 355 | f.base = "" | 355 | f.base = "" |
| @@ -527,7 +527,7 @@ func (f *Flow) keyEnv() string { | |||
| 527 | // typeModelPrompt asks for the model's ID when there is no list, and says | 527 | // typeModelPrompt asks for the model's ID when there is no list, and says |
| 528 | // why — in the window as in the line mode, both show the prompt. | 528 | // why — in the window as in the line mode, both show the prompt. |
| 529 | func (f *Flow) typeModelPrompt() string { | 529 | func (f *Flow) typeModelPrompt() string { |
| 530 | - if f.c.Provider == "openai" && os.Getenv(f.keyEnv()) == "" { | 530 | + if isOpenAI(f.c.Provider) && os.Getenv(f.keyEnv()) == "" { |
| 531 | return fmt.Sprintf("Model ID? (%s is not set: no list — type it)", f.keyEnv()) | 531 | return fmt.Sprintf("Model ID? (%s is not set: no list — type it)", f.keyEnv()) |
| 532 | } | 532 | } |
| 533 | if f.modelsErr != nil { | 533 | if f.modelsErr != nil { |
| @@ -536,6 +536,14 @@ func (f *Flow) typeModelPrompt() string { | |||
| 536 | return "Model (as the server names it)?" | 536 | return "Model (as the server names it)?" |
| 537 | } | 537 | } |
| 538 | 538 | ||
| 539 | +// isOpenAI: the provider is an OpenAI-compatible service mm asks for an | ||
| 540 | +// endpoint and a key variable — `openai` (Chat Completions) and | ||
| 541 | +// `openai-responses` (the Responses API, ticket 178), which share their | ||
| 542 | +// address and key. | ||
| 543 | +func isOpenAI(provider string) bool { | ||
| 544 | + return provider == "openai" || provider == "openai-responses" | ||
| 545 | +} | ||
| 546 | + | ||
| 539 | // openAIDefaultBase is the openai provider's default address (the OpenAI API). | 547 | // openAIDefaultBase is the openai provider's default address (the OpenAI API). |
| 540 | func openAIDefaultBase() string { | 548 | func openAIDefaultBase() string { |
| 541 | base, _, _ := engine.DefaultURLs("openai") | 549 | base, _, _ := engine.DefaultURLs("openai") |
| @@ -596,7 +604,7 @@ func (f *Flow) modelList() []string { | |||
| 596 | return nil | 604 | return nil |
| 597 | } | 605 | } |
| 598 | key := f.c.Provider + " " + f.Base() | 606 | key := f.c.Provider + " " + f.Base() |
| 599 | - if f.c.Provider == "openai" { | 607 | + if isOpenAI(f.c.Provider) { |
| 600 | key += " " + f.keyEnv() | 608 | key += " " + f.keyEnv() |
| 601 | } | 609 | } |
| 602 | if f.listed != key { | 610 | if f.listed != key { |
| @@ -610,7 +618,7 @@ func (f *Flow) modelList() []string { | |||
| 610 | // is asked with the key read from the variable the user named — and not at | 618 | // is asked with the key read from the variable the user named — and not at |
| 611 | // all when that variable is empty: the request would only be refused. | 619 | // all when that variable is empty: the request would only be refused. |
| 612 | func (f *Flow) listModels() ([]string, error) { | 620 | func (f *Flow) listModels() ([]string, error) { |
| 613 | - if f.c.Provider != "openai" { | 621 | + if !isOpenAI(f.c.Provider) { |
| 614 | return Models(f.ctx, f.c.Provider, f.Base()) | 622 | return Models(f.ctx, f.c.Provider, f.Base()) |
| 615 | } | 623 | } |
| 616 | key := os.Getenv(f.keyEnv()) | 624 | key := os.Getenv(f.keyEnv()) |
modified
internal/agentinit/openai_flow_test.go +33 -0 | @@ -176,3 +176,36 @@ func TestOpenAIFileHasTheEndpointTheKeyAndTheReasoningHint(t *testing.T) { | ||
| 176 | 176 | t.Errorf("defaults written out:\n%s", text) |
| 177 | 177 | } |
| 178 | 178 | } |
| 179 | + | |
| 180 | +// Ticket 178: openai-responses is offered by mm init, asks the same endpoint | |
| 181 | +// and key questions as openai, lists the models with the key, and writes | |
| 182 | +// its file without the reasoning_effort hint — the Responses API keeps the | |
| 183 | +// reasoning with the tools, which is the point of the provider. | |
| 184 | +func TestOpenAIResponsesIsAnOpenAIProviderInMMInit(t *testing.T) { | |
| 185 | + if !strings.Contains(strings.Join(providers, " "), "openai openai-responses") { | |
| 186 | + t.Errorf("providers = %v, want openai-responses after openai", providers) | |
| 187 | + } | |
| 188 | + keepConfig(t) | |
| 189 | + p, _ := LoadPresets() | |
| 190 | + f := NewFlow(context.Background(), p, Choices{Provider: "openai-responses"}, "") | |
| 191 | + if got := keys(f.Pending()); !strings.HasPrefix(got, "project,endpoint,keyenv,model,") { | |
| 192 | + t.Errorf("pending = %s, want project, endpoint, keyenv, then the model", got) | |
| 193 | + } | |
| 194 | + svc := newOpenAIService(t) | |
| 195 | + t.Setenv("MY_KEY", "sk-good") | |
| 196 | + f = NewFlow(context.Background(), p, Choices{Provider: "openai-responses", BaseURL: svc.url, APIKeyEnv: "MY_KEY"}, "") | |
| 197 | + if st := f.Step("model"); len(st.Options) != 2 || svc.auth != "Bearer sk-good" { | |
| 198 | + t.Errorf("model step options %v, auth %q: want the service's list, asked with the key", st.Options, svc.auth) | |
| 199 | + } | |
| 200 | + | |
| 201 | + c := Choices{Provider: "openai-responses", APIKeyEnv: "MY_KEY", Model: "gpt-6-luna", Usage: "developer", Machine: "small"} | |
| 202 | + text := Render(Decide(p, c, Facts{})) | |
| 203 | + for _, want := range []string{"provider: openai-responses", "apiKeyEnv: MY_KEY"} { | |
| 204 | + if !strings.Contains(text, want) { | |
| 205 | + t.Errorf("the file has no %q:\n%s", want, text) | |
| 206 | + } | |
| 207 | + } | |
| 208 | + if strings.Contains(text, "reasoning_effort: none") { | |
| 209 | + t.Errorf("openai-responses file has the Chat Completions hint:\n%s", text) | |
| 210 | + } | |
| 211 | +} | |
| @@ -176,3 +176,36 @@ func TestOpenAIFileHasTheEndpointTheKeyAndTheReasoningHint(t *testing.T) { | |||
| 176 | t.Errorf("defaults written out:\n%s", text) | 176 | t.Errorf("defaults written out:\n%s", text) |
| 177 | } | 177 | } |
| 178 | } | 178 | } |
| 179 | + | ||
| 180 | +// Ticket 178: openai-responses is offered by mm init, asks the same endpoint | ||
| 181 | +// and key questions as openai, lists the models with the key, and writes | ||
| 182 | +// its file without the reasoning_effort hint — the Responses API keeps the | ||
| 183 | +// reasoning with the tools, which is the point of the provider. | ||
| 184 | +func TestOpenAIResponsesIsAnOpenAIProviderInMMInit(t *testing.T) { | ||
| 185 | + if !strings.Contains(strings.Join(providers, " "), "openai openai-responses") { | ||
| 186 | + t.Errorf("providers = %v, want openai-responses after openai", providers) | ||
| 187 | + } | ||
| 188 | + keepConfig(t) | ||
| 189 | + p, _ := LoadPresets() | ||
| 190 | + f := NewFlow(context.Background(), p, Choices{Provider: "openai-responses"}, "") | ||
| 191 | + if got := keys(f.Pending()); !strings.HasPrefix(got, "project,endpoint,keyenv,model,") { | ||
| 192 | + t.Errorf("pending = %s, want project, endpoint, keyenv, then the model", got) | ||
| 193 | + } | ||
| 194 | + svc := newOpenAIService(t) | ||
| 195 | + t.Setenv("MY_KEY", "sk-good") | ||
| 196 | + f = NewFlow(context.Background(), p, Choices{Provider: "openai-responses", BaseURL: svc.url, APIKeyEnv: "MY_KEY"}, "") | ||
| 197 | + if st := f.Step("model"); len(st.Options) != 2 || svc.auth != "Bearer sk-good" { | ||
| 198 | + t.Errorf("model step options %v, auth %q: want the service's list, asked with the key", st.Options, svc.auth) | ||
| 199 | + } | ||
| 200 | + | ||
| 201 | + c := Choices{Provider: "openai-responses", APIKeyEnv: "MY_KEY", Model: "gpt-6-luna", Usage: "developer", Machine: "small"} | ||
| 202 | + text := Render(Decide(p, c, Facts{})) | ||
| 203 | + for _, want := range []string{"provider: openai-responses", "apiKeyEnv: MY_KEY"} { | ||
| 204 | + if !strings.Contains(text, want) { | ||
| 205 | + t.Errorf("the file has no %q:\n%s", want, text) | ||
| 206 | + } | ||
| 207 | + } | ||
| 208 | + if strings.Contains(text, "reasoning_effort: none") { | ||
| 209 | + t.Errorf("openai-responses file has the Chat Completions hint:\n%s", text) | ||
| 210 | + } | ||
| 211 | +} | ||
modified
internal/agentinit/render.go +1 -1 | @@ -42,7 +42,7 @@ func Render(s Settings) string { | ||
| 42 | 42 | } else { |
| 43 | 43 | writeDefaultURLs(&b, c.Provider) |
| 44 | 44 | } |
| 45 | - if c.Provider == "openai" { | |
| 45 | + if isOpenAI(c.Provider) { | |
| 46 | 46 | writeKeyEnv(&b, c) |
| 47 | 47 | } |
| 48 | 48 | b.WriteString("\n") |
| @@ -42,7 +42,7 @@ func Render(s Settings) string { | |||
| 42 | } else { | 42 | } else { |
| 43 | writeDefaultURLs(&b, c.Provider) | 43 | writeDefaultURLs(&b, c.Provider) |
| 44 | } | 44 | } |
| 45 | - if c.Provider == "openai" { | 45 | + if isOpenAI(c.Provider) { |
| 46 | writeKeyEnv(&b, c) | 46 | writeKeyEnv(&b, c) |
| 47 | } | 47 | } |
| 48 | b.WriteString("\n") | 48 | b.WriteString("\n") |
modified
internal/agentinit/wizard.go +1 -1 | @@ -21,7 +21,7 @@ import ( | ||
| 21 | 21 | // providers are the servers mm speaks to, in the order they are offered. |
| 22 | 22 | // llamacpp first (ticket 221, user's choice): the default when nothing |
| 23 | 23 | // answers (firstAnswering). |
| 24 | -var providers = []string{"llamacpp", "llmman", "ollama", "dmr", "kronk", "openai"} | |
| 24 | +var providers = []string{"llamacpp", "llmman", "ollama", "dmr", "kronk", "openai", "openai-responses"} | |
| 25 | 25 | |
| 26 | 26 | // local are the providers probed for the first question's default, in this |
| 27 | 27 | // order: the first that answers is proposed — llamacpp when llama-server |
| @@ -21,7 +21,7 @@ import ( | |||
| 21 | // providers are the servers mm speaks to, in the order they are offered. | 21 | // providers are the servers mm speaks to, in the order they are offered. |
| 22 | // llamacpp first (ticket 221, user's choice): the default when nothing | 22 | // llamacpp first (ticket 221, user's choice): the default when nothing |
| 23 | // answers (firstAnswering). | 23 | // answers (firstAnswering). |
| 24 | -var providers = []string{"llamacpp", "llmman", "ollama", "dmr", "kronk", "openai"} | 24 | +var providers = []string{"llamacpp", "llmman", "ollama", "dmr", "kronk", "openai", "openai-responses"} |
| 25 | 25 | ||
| 26 | // local are the providers probed for the first question's default, in this | 26 | // local are the providers probed for the first question's default, in this |
| 27 | // order: the first that answers is proposed — llamacpp when llama-server | 27 | // order: the first that answers is proposed — llamacpp when llama-server |
modified
internal/config/sampling.go +2 -2 | @@ -32,10 +32,10 @@ func ownSampling(data []byte) (map[string]any, error) { | ||
| 32 | 32 | } |
| 33 | 33 | |
| 34 | 34 | // applyProviderSampling replaces the merged sampling by the file's own block |
| 35 | -// when the provider takes no default (openai). It runs after applyEnv, so | |
| 35 | +// when the provider takes no default (openai, openai-responses). It runs after applyEnv, so | |
| 36 | 36 | // AGENT_PROVIDER=openai counts too. |
| 37 | 37 | func applyProviderSampling(own map[string]any) { |
| 38 | - if Cfg.Provider != "openai" { | |
| 38 | + if Cfg.Provider != "openai" && Cfg.Provider != "openai-responses" { | |
| 39 | 39 | return |
| 40 | 40 | } |
| 41 | 41 | if own == nil { |
| @@ -32,10 +32,10 @@ func ownSampling(data []byte) (map[string]any, error) { | |||
| 32 | } | 32 | } |
| 33 | 33 | ||
| 34 | // applyProviderSampling replaces the merged sampling by the file's own block | 34 | // applyProviderSampling replaces the merged sampling by the file's own block |
| 35 | -// when the provider takes no default (openai). It runs after applyEnv, so | 35 | +// when the provider takes no default (openai, openai-responses). It runs after applyEnv, so |
| 36 | // AGENT_PROVIDER=openai counts too. | 36 | // AGENT_PROVIDER=openai counts too. |
| 37 | func applyProviderSampling(own map[string]any) { | 37 | func applyProviderSampling(own map[string]any) { |
| 38 | - if Cfg.Provider != "openai" { | 38 | + if Cfg.Provider != "openai" && Cfg.Provider != "openai-responses" { |
| 39 | return | 39 | return |
| 40 | } | 40 | } |
| 41 | if own == nil { | 41 | if own == nil { |
modified
internal/config/sampling_test.go +13 -0 | @@ -66,3 +66,16 @@ func TestLoadLeavesTheDefaultSamplingUntouched(t *testing.T) { | ||
| 66 | 66 | t.Errorf("default sampling after a load = %v, want it untouched %v", Cfg.Sampling, before) |
| 67 | 67 | } |
| 68 | 68 | } |
| 69 | + | |
| 70 | +// Ticket 178: openai-responses talks to the same OpenAI API, so it gets the | |
| 71 | +// file's block exactly too — mm's defaults (max_tokens, top_p) would be | |
| 72 | +// refused by the reasoning models it is for. | |
| 73 | +func TestOpenAIResponsesSamplingIsExactlyTheFilesBlock(t *testing.T) { | |
| 74 | + if err := loadYAML(t, "provider: openai-responses\nmodel: gpt-6-luna\nsampling:\n reasoning_effort: high\n"); err != nil { | |
| 75 | + t.Fatal(err) | |
| 76 | + } | |
| 77 | + want := map[string]any{"reasoning_effort": "high"} | |
| 78 | + if !maps.Equal(Cfg.Sampling, want) { | |
| 79 | + t.Errorf("sampling = %v, want only the file's keys %v", Cfg.Sampling, want) | |
| 80 | + } | |
| 81 | +} | |
| @@ -66,3 +66,16 @@ func TestLoadLeavesTheDefaultSamplingUntouched(t *testing.T) { | |||
| 66 | t.Errorf("default sampling after a load = %v, want it untouched %v", Cfg.Sampling, before) | 66 | t.Errorf("default sampling after a load = %v, want it untouched %v", Cfg.Sampling, before) |
| 67 | } | 67 | } |
| 68 | } | 68 | } |
| 69 | + | ||
| 70 | +// Ticket 178: openai-responses talks to the same OpenAI API, so it gets the | ||
| 71 | +// file's block exactly too — mm's defaults (max_tokens, top_p) would be | ||
| 72 | +// refused by the reasoning models it is for. | ||
| 73 | +func TestOpenAIResponsesSamplingIsExactlyTheFilesBlock(t *testing.T) { | ||
| 74 | + if err := loadYAML(t, "provider: openai-responses\nmodel: gpt-6-luna\nsampling:\n reasoning_effort: high\n"); err != nil { | ||
| 75 | + t.Fatal(err) | ||
| 76 | + } | ||
| 77 | + want := map[string]any{"reasoning_effort": "high"} | ||
| 78 | + if !maps.Equal(Cfg.Sampling, want) { | ||
| 79 | + t.Errorf("sampling = %v, want only the file's keys %v", Cfg.Sampling, want) | ||
| 80 | + } | ||
| 81 | +} | ||
modified
internal/engine/openai.go +15 -0 | @@ -25,6 +25,21 @@ func init() { | ||
| 25 | 25 | notFoundHint: "the server has no model %s — GET <baseUrl>/models lists the ones it has", |
| 26 | 26 | probe: probeOpenAI, |
| 27 | 27 | }) |
| 28 | + // The same servers through OpenAI's Responses API (ticket 178): what | |
| 29 | + // OpenAI's reasoning models need to keep reasoning AND call tools. A | |
| 30 | + // separate provider, so the `openai` files keep Chat Completions. No | |
| 31 | + // thinkingOff: responses.go turns the reasoning off itself for a summary | |
| 32 | + // (reasoning.effort "none"). | |
| 33 | + register(&openaiCompat{ | |
| 34 | + name: "openai-responses", | |
| 35 | + baseURL: "https://api.openai.com/v1", | |
| 36 | + apiKeyEnv: "OPENAI_API_KEY", | |
| 37 | + dummyKey: "not-needed", | |
| 38 | + startHint: "check baseUrl: the server's OpenAI-compatible address, usually ending in /v1 (default: the OpenAI API); it must serve POST /responses", | |
| 39 | + notFoundHint: "the server has no model %s — GET <baseUrl>/models lists the ones it has", | |
| 40 | + probe: probeOpenAI, | |
| 41 | + responses: true, | |
| 42 | + }) | |
| 28 | 43 | } |
| 29 | 44 | |
| 30 | 45 | // probeOpenAI asks GET /models WITH the key: a remote API answers 401 to an |
| @@ -25,6 +25,21 @@ func init() { | |||
| 25 | notFoundHint: "the server has no model %s — GET <baseUrl>/models lists the ones it has", | 25 | notFoundHint: "the server has no model %s — GET <baseUrl>/models lists the ones it has", |
| 26 | probe: probeOpenAI, | 26 | probe: probeOpenAI, |
| 27 | }) | 27 | }) |
| 28 | + // The same servers through OpenAI's Responses API (ticket 178): what | ||
| 29 | + // OpenAI's reasoning models need to keep reasoning AND call tools. A | ||
| 30 | + // separate provider, so the `openai` files keep Chat Completions. No | ||
| 31 | + // thinkingOff: responses.go turns the reasoning off itself for a summary | ||
| 32 | + // (reasoning.effort "none"). | ||
| 33 | + register(&openaiCompat{ | ||
| 34 | + name: "openai-responses", | ||
| 35 | + baseURL: "https://api.openai.com/v1", | ||
| 36 | + apiKeyEnv: "OPENAI_API_KEY", | ||
| 37 | + dummyKey: "not-needed", | ||
| 38 | + startHint: "check baseUrl: the server's OpenAI-compatible address, usually ending in /v1 (default: the OpenAI API); it must serve POST /responses", | ||
| 39 | + notFoundHint: "the server has no model %s — GET <baseUrl>/models lists the ones it has", | ||
| 40 | + probe: probeOpenAI, | ||
| 41 | + responses: true, | ||
| 42 | + }) | ||
| 28 | } | 43 | } |
| 29 | 44 | ||
| 30 | // probeOpenAI asks GET /models WITH the key: a remote API answers 401 to an | 45 | // probeOpenAI asks GET /models WITH the key: a remote API answers 401 to an |
modified
internal/engine/openai_compat.go +9 -0 | @@ -75,6 +75,12 @@ type openaiCompat struct { | ||
| 75 | 75 | // warning gives instead ("" = none). |
| 76 | 76 | pull pullFunc |
| 77 | 77 | noPull string |
| 78 | + | |
| 79 | + // responses: the server is spoken to through OpenAI's Responses API | |
| 80 | + // (POST /responses, responses.go) instead of Chat Completions — the | |
| 81 | + // `openai-responses` provider, ticket 178. Everything else (address, | |
| 82 | + // key, probe, explanations) is this entry's like any other. | |
| 83 | + responses bool | |
| 78 | 84 | } |
| 79 | 85 | |
| 80 | 86 | // DefaultURLs returns the address a provider uses when the config gives no |
| @@ -283,6 +289,9 @@ func (p *openaiCompat) resolve(cfg config.Config, useEnv bool) (Backend, error) | ||
| 283 | 289 | |
| 284 | 290 | // Open is the former dmr.Init with the constants replaced by the Backend. |
| 285 | 291 | func (p *openaiCompat) Open(ctx context.Context, b Backend) (*genkit.Genkit, string, error) { |
| 292 | + if p.responses { | |
| 293 | + return p.openResponses(ctx, b) | |
| 294 | + } | |
| 286 | 295 | client := &compat_oai.OpenAICompatible{ |
| 287 | 296 | Provider: p.name, // model prefix: "<provider>/<id>" |
| 288 | 297 | BaseURL: b.BaseURL, |
| @@ -75,6 +75,12 @@ type openaiCompat struct { | |||
| 75 | // warning gives instead ("" = none). | 75 | // warning gives instead ("" = none). |
| 76 | pull pullFunc | 76 | pull pullFunc |
| 77 | noPull string | 77 | noPull string |
| 78 | + | ||
| 79 | + // responses: the server is spoken to through OpenAI's Responses API | ||
| 80 | + // (POST /responses, responses.go) instead of Chat Completions — the | ||
| 81 | + // `openai-responses` provider, ticket 178. Everything else (address, | ||
| 82 | + // key, probe, explanations) is this entry's like any other. | ||
| 83 | + responses bool | ||
| 78 | } | 84 | } |
| 79 | 85 | ||
| 80 | // DefaultURLs returns the address a provider uses when the config gives no | 86 | // DefaultURLs returns the address a provider uses when the config gives no |
| @@ -283,6 +289,9 @@ func (p *openaiCompat) resolve(cfg config.Config, useEnv bool) (Backend, error) | |||
| 283 | 289 | ||
| 284 | // Open is the former dmr.Init with the constants replaced by the Backend. | 290 | // Open is the former dmr.Init with the constants replaced by the Backend. |
| 285 | func (p *openaiCompat) Open(ctx context.Context, b Backend) (*genkit.Genkit, string, error) { | 291 | func (p *openaiCompat) Open(ctx context.Context, b Backend) (*genkit.Genkit, string, error) { |
| 292 | + if p.responses { | ||
| 293 | + return p.openResponses(ctx, b) | ||
| 294 | + } | ||
| 286 | client := &compat_oai.OpenAICompatible{ | 295 | client := &compat_oai.OpenAICompatible{ |
| 287 | Provider: p.name, // model prefix: "<provider>/<id>" | 296 | Provider: p.name, // model prefix: "<provider>/<id>" |
| 288 | BaseURL: b.BaseURL, | 297 | BaseURL: b.BaseURL, |
added
internal/engine/responses.go +604 -0 | new file mode 100644 | ||
| @@ -0,0 +1,604 @@ | ||
| 1 | +package engine | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "bufio" | |
| 5 | + "bytes" | |
| 6 | + "context" | |
| 7 | + "encoding/json" | |
| 8 | + "errors" | |
| 9 | + "fmt" | |
| 10 | + "io" | |
| 11 | + "net/http" | |
| 12 | + "strings" | |
| 13 | + | |
| 14 | + "mm/internal/config" | |
| 15 | + | |
| 16 | + "github.com/firebase/genkit/go/ai" | |
| 17 | + "github.com/firebase/genkit/go/genkit" | |
| 18 | + "github.com/openai/openai-go/option" | |
| 19 | +) | |
| 20 | + | |
| 21 | +// The `openai-responses` provider (ticket 178) speaks OpenAI's Responses API, | |
| 22 | +// POST <baseUrl>/responses, instead of Chat Completions. OpenAI's reasoning | |
| 23 | +// models refuse function tools with active reasoning on /v1/chat/completions | |
| 24 | +// ("To use function tools, use /v1/responses or set reasoning_effort to | |
| 25 | +// 'none'"), and an mm agent always sends tools: on Responses they keep both. | |
| 26 | +// | |
| 27 | +// Genkit's compat_oai plugin only knows Chat Completions, so this file is a | |
| 28 | +// Genkit model of its own: it turns Genkit's request into a Responses request, | |
| 29 | +// reads the typed SSE events back, and hands Genkit an ordinary response — | |
| 30 | +// text, tool requests, usage, finish reason. Everything above the model call | |
| 31 | +// (the watchdog, the struggle signals, the tool hooks, the history) is the | |
| 32 | +// same as for every other provider. | |
| 33 | +// | |
| 34 | +// Plain HTTP and JSON rather than openai-go's `responses` package: the wire | |
| 35 | +// format is small, its unions are heavy in Go, and a request built here is | |
| 36 | +// one a fake server in a test can read back. | |
| 37 | +// | |
| 38 | +// The reasoning between the model calls of a turn: the request says | |
| 39 | +// `store: false` (nothing kept on OpenAI's side) and asks for | |
| 40 | +// `reasoning.encrypted_content`; the reasoning items of an answer ride on the | |
| 41 | +// model message's metadata (responsesReasoningKey) and are sent back before | |
| 42 | +// that message's tool calls, so the model keeps its thread after each tool | |
| 43 | +// result. The file's `sampling:` can set `store` or `include` itself; then it | |
| 44 | +// is taken as written. | |
| 45 | + | |
| 46 | +// responsesReasoningKey is the message-metadata key holding the reasoning | |
| 47 | +// items of a Responses answer, as the server returned them. | |
| 48 | +const responsesReasoningKey = "openaiResponsesReasoning" | |
| 49 | + | |
| 50 | +// responsesClient: no overall timeout — a reasoning model can think for | |
| 51 | +// minutes; the watchdog and the context bound the call. | |
| 52 | +var responsesClient = &http.Client{} | |
| 53 | + | |
| 54 | +// openResponses is Open for the Responses API: a Genkit with no plugin, and | |
| 55 | +// one model defined here. | |
| 56 | +func (p *openaiCompat) openResponses(ctx context.Context, b Backend) (*genkit.Genkit, string, error) { | |
| 57 | + quietGenkit() | |
| 58 | + g := genkit.Init(ctx) | |
| 59 | + name := p.name + "/" + b.Model | |
| 60 | + r := &responsesModel{backend: b, chain: responsesMiddlewares()} | |
| 61 | + genkit.DefineModel(g, name, &ai.ModelOptions{ //nolint:staticcheck // DefineModelAction would type the config; the sampling map is untyped on purpose | |
| 62 | + Label: b.Model, | |
| 63 | + Supports: modelSupports(), | |
| 64 | + }, r.generate) | |
| 65 | + return g, name, nil | |
| 66 | +} | |
| 67 | + | |
| 68 | +// responsesMiddlewares is the HTTP chain: only the trace — the Chat | |
| 69 | +// Completions ones rewrite fields this API does not have. | |
| 70 | +func responsesMiddlewares() []option.Middleware { | |
| 71 | + if config.Cfg.Trace.Enabled { | |
| 72 | + return []option.Middleware{traceMiddleware(config.Cfg.Trace.Dir, config.Cfg.ACP.Name)} | |
| 73 | + } | |
| 74 | + return nil | |
| 75 | +} | |
| 76 | + | |
| 77 | +// responsesModel is the model behind one Engine. | |
| 78 | +type responsesModel struct { | |
| 79 | + backend Backend | |
| 80 | + chain []option.Middleware | |
| 81 | +} | |
| 82 | + | |
| 83 | +// generate is the Genkit model function: one model call. | |
| 84 | +func (r *responsesModel) generate(ctx context.Context, req *ai.ModelRequest, cb ai.ModelStreamCallback) (*ai.ModelResponse, error) { | |
| 85 | + off, _ := ctx.Value(noThinkKey{}).(bool) | |
| 86 | + body, err := responsesRequest(r.backend.Model, req, cb != nil, off) | |
| 87 | + if err != nil { | |
| 88 | + return nil, err | |
| 89 | + } | |
| 90 | + resp, err := r.post(ctx, body) | |
| 91 | + if err != nil { | |
| 92 | + return nil, err | |
| 93 | + } | |
| 94 | + defer func() { _ = resp.Body.Close() }() | |
| 95 | + var out *responsesResult | |
| 96 | + if cb != nil && strings.Contains(resp.Header.Get("Content-Type"), "text/event-stream") { | |
| 97 | + out, err = readResponsesStream(ctx, resp.Body, cb) | |
| 98 | + } else { | |
| 99 | + out = &responsesResult{} | |
| 100 | + err = json.NewDecoder(resp.Body).Decode(out) | |
| 101 | + if err != nil { | |
| 102 | + err = fmt.Errorf("responses: reading the answer: %w", err) | |
| 103 | + } | |
| 104 | + } | |
| 105 | + if err != nil { | |
| 106 | + return nil, err | |
| 107 | + } | |
| 108 | + mr, err := out.modelResponse() | |
| 109 | + if err != nil { | |
| 110 | + return nil, err | |
| 111 | + } | |
| 112 | + mr.Request = req | |
| 113 | + return mr, nil | |
| 114 | +} | |
| 115 | + | |
| 116 | +// post sends the request through the middlewares and returns a 2xx answer; | |
| 117 | +// anything else is an error whose text carries the status the way the | |
| 118 | +// OpenAI client's does (`POST "<url>": 401 Unauthorized {…}`), so Explain | |
| 119 | +// reads it the same. | |
| 120 | +func (r *responsesModel) post(ctx context.Context, body []byte) (*http.Response, error) { | |
| 121 | + url := strings.TrimSuffix(r.backend.BaseURL, "/") + "/responses" | |
| 122 | + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) | |
| 123 | + if err != nil { | |
| 124 | + return nil, err | |
| 125 | + } | |
| 126 | + req.Header.Set("Content-Type", "application/json") | |
| 127 | + req.Header.Set("Authorization", "Bearer "+r.backend.APIKey) | |
| 128 | + req.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(body)), nil } | |
| 129 | + next := func(req *http.Request) (*http.Response, error) { return responsesClient.Do(req) } | |
| 130 | + for i := len(r.chain) - 1; i >= 0; i-- { | |
| 131 | + mw, inner := r.chain[i], next | |
| 132 | + next = func(req *http.Request) (*http.Response, error) { return mw(req, inner) } | |
| 133 | + } | |
| 134 | + resp, err := next(req) | |
| 135 | + if err != nil { | |
| 136 | + return nil, err | |
| 137 | + } | |
| 138 | + if resp.StatusCode/100 != 2 { | |
| 139 | + defer func() { _ = resp.Body.Close() }() | |
| 140 | + said, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) | |
| 141 | + return nil, fmt.Errorf("POST %q: %s %s", url, resp.Status, strings.TrimSpace(string(said))) | |
| 142 | + } | |
| 143 | + return resp, nil | |
| 144 | +} | |
| 145 | + | |
| 146 | +// responsesRequest builds the JSON body of one call. | |
| 147 | +// | |
| 148 | +// body, _ := responsesRequest("gpt-6-luna", req, true, false) | |
| 149 | +// // {"model":"gpt-6-luna","input":[…],"tools":[…],"stream":true,"store":false,"include":["reasoning.encrypted_content"],…} | |
| 150 | +func responsesRequest(model string, req *ai.ModelRequest, stream, noThink bool) ([]byte, error) { | |
| 151 | + m, err := samplingFields(req.Config) | |
| 152 | + if err != nil { | |
| 153 | + return nil, err | |
| 154 | + } | |
| 155 | + if noThink { | |
| 156 | + setReasoning(m, "effort", "none") | |
| 157 | + } | |
| 158 | + input, err := responsesInput(req.Messages) | |
| 159 | + if err != nil { | |
| 160 | + return nil, err | |
| 161 | + } | |
| 162 | + m["model"] = model | |
| 163 | + m["input"] = input | |
| 164 | + if len(req.Tools) > 0 { | |
| 165 | + m["tools"] = responsesTools(req.Tools) | |
| 166 | + } | |
| 167 | + if req.ToolChoice != "" { | |
| 168 | + m["tool_choice"] = string(req.ToolChoice) | |
| 169 | + } | |
| 170 | + if format := responsesFormat(req.Output); format != nil { | |
| 171 | + text, _ := m["text"].(map[string]any) | |
| 172 | + if text == nil { | |
| 173 | + text = map[string]any{} | |
| 174 | + } | |
| 175 | + text["format"] = format | |
| 176 | + m["text"] = text | |
| 177 | + } | |
| 178 | + m["stream"] = stream | |
| 179 | + if _, set := m["store"]; !set { | |
| 180 | + m["store"] = false | |
| 181 | + } | |
| 182 | + if _, set := m["include"]; !set && m["store"] == false { | |
| 183 | + m["include"] = []string{"reasoning.encrypted_content"} | |
| 184 | + } | |
| 185 | + return json.Marshal(m) | |
| 186 | +} | |
| 187 | + | |
| 188 | +// samplingFields is the request's config — the file's `sampling:` block — | |
| 189 | +// as the fields of a Responses request, written as they are except for the | |
| 190 | +// Chat Completions names this API spells differently: the answer limit | |
| 191 | +// (max_tokens, max_completion_tokens → max_output_tokens) and | |
| 192 | +// reasoning_effort (→ reasoning.effort). | |
| 193 | +func samplingFields(cfg any) (map[string]any, error) { | |
| 194 | + m := map[string]any{} | |
| 195 | + switch c := cfg.(type) { | |
| 196 | + case nil: | |
| 197 | + case map[string]any: | |
| 198 | + for k, v := range c { | |
| 199 | + m[k] = v | |
| 200 | + } | |
| 201 | + default: | |
| 202 | + raw, err := json.Marshal(c) | |
| 203 | + if err != nil { | |
| 204 | + return nil, fmt.Errorf("responses: config: %w", err) | |
| 205 | + } | |
| 206 | + if err := json.Unmarshal(raw, &m); err != nil { | |
| 207 | + return nil, fmt.Errorf("responses: config: %w", err) | |
| 208 | + } | |
| 209 | + } | |
| 210 | + for _, key := range []string{"max_completion_tokens", "max_tokens"} { | |
| 211 | + if v, ok := m[key]; ok { | |
| 212 | + if _, set := m["max_output_tokens"]; !set { | |
| 213 | + m["max_output_tokens"] = v | |
| 214 | + } | |
| 215 | + delete(m, key) | |
| 216 | + } | |
| 217 | + } | |
| 218 | + if v, ok := m["reasoning_effort"]; ok { | |
| 219 | + delete(m, "reasoning_effort") | |
| 220 | + if r, _ := m["reasoning"].(map[string]any); r == nil || r["effort"] == nil { | |
| 221 | + setReasoning(m, "effort", v) | |
| 222 | + } | |
| 223 | + } | |
| 224 | + return m, nil | |
| 225 | +} | |
| 226 | + | |
| 227 | +// setReasoning sets one field of the `reasoning` object, keeping the others. | |
| 228 | +func setReasoning(m map[string]any, key string, value any) { | |
| 229 | + r, _ := m["reasoning"].(map[string]any) | |
| 230 | + if r == nil { | |
| 231 | + r = map[string]any{} | |
| 232 | + } else { | |
| 233 | + copied := make(map[string]any, len(r)+1) | |
| 234 | + for k, v := range r { | |
| 235 | + copied[k] = v | |
| 236 | + } | |
| 237 | + r = copied | |
| 238 | + } | |
| 239 | + r[key] = value | |
| 240 | + m["reasoning"] = r | |
| 241 | +} | |
| 242 | + | |
| 243 | +// responsesInput turns Genkit's messages into Responses input items: | |
| 244 | +// system and user messages, the model's earlier answers (its reasoning | |
| 245 | +// items, its text, its function calls) and the tool results. | |
| 246 | +func responsesInput(messages []*ai.Message) ([]any, error) { | |
| 247 | + var items []any | |
| 248 | + for _, msg := range messages { | |
| 249 | + if msg == nil { | |
| 250 | + continue | |
| 251 | + } | |
| 252 | + switch msg.Role { | |
| 253 | + case ai.RoleSystem: | |
| 254 | + if text := msg.Text(); text != "" { | |
| 255 | + items = append(items, map[string]any{"role": "system", "content": text}) | |
| 256 | + } | |
| 257 | + case ai.RoleUser: | |
| 258 | + if content := userContent(msg.Content); len(content) > 0 { | |
| 259 | + items = append(items, map[string]any{"role": "user", "content": content}) | |
| 260 | + } | |
| 261 | + case ai.RoleModel: | |
| 262 | + modelItems, err := modelInput(msg) | |
| 263 | + if err != nil { | |
| 264 | + return nil, err | |
| 265 | + } | |
| 266 | + items = append(items, modelItems...) | |
| 267 | + case ai.RoleTool: | |
| 268 | + for _, p := range msg.Content { | |
| 269 | + if p == nil || !p.IsToolResponse() || p.ToolResponse == nil { | |
| 270 | + continue | |
| 271 | + } | |
| 272 | + out, err := responsesToolOutput(p.ToolResponse.Output) | |
| 273 | + if err != nil { | |
| 274 | + return nil, err | |
| 275 | + } | |
| 276 | + items = append(items, map[string]any{"type": "function_call_output", "call_id": callID(p.ToolResponse.Ref, p.ToolResponse.Name), "output": out}) | |
| 277 | + } | |
| 278 | + } | |
| 279 | + } | |
| 280 | + return items, nil | |
| 281 | +} | |
| 282 | + | |
| 283 | +// userContent is a user message's parts: text, and images by URL. | |
| 284 | +func userContent(parts []*ai.Part) []any { | |
| 285 | + var content []any | |
| 286 | + for _, p := range parts { | |
| 287 | + switch { | |
| 288 | + case p == nil: | |
| 289 | + case p.IsText(): | |
| 290 | + content = append(content, map[string]any{"type": "input_text", "text": p.Text}) | |
| 291 | + case p.IsMedia(): | |
| 292 | + content = append(content, map[string]any{"type": "input_image", "image_url": p.Text}) | |
| 293 | + } | |
| 294 | + } | |
| 295 | + return content | |
| 296 | +} | |
| 297 | + | |
| 298 | +// modelInput is one of the model's earlier answers, in the order the server | |
| 299 | +// produced them: reasoning, text, function calls. | |
| 300 | +func modelInput(msg *ai.Message) ([]any, error) { | |
| 301 | + var items []any | |
| 302 | + if raw, ok := msg.Metadata[responsesReasoningKey].([]any); ok { | |
| 303 | + items = append(items, raw...) | |
| 304 | + } | |
| 305 | + var text strings.Builder | |
| 306 | + for _, p := range msg.Content { | |
| 307 | + if p != nil && p.IsText() { | |
| 308 | + text.WriteString(p.Text) | |
| 309 | + } | |
| 310 | + } | |
| 311 | + if text.Len() > 0 { | |
| 312 | + items = append(items, map[string]any{"role": "assistant", "content": text.String()}) | |
| 313 | + } | |
| 314 | + for _, p := range msg.Content { | |
| 315 | + if p == nil || !p.IsToolRequest() || p.ToolRequest == nil { | |
| 316 | + continue | |
| 317 | + } | |
| 318 | + args, err := toolArguments(p.ToolRequest.Input) | |
| 319 | + if err != nil { | |
| 320 | + return nil, err | |
| 321 | + } | |
| 322 | + items = append(items, map[string]any{"type": "function_call", "call_id": callID(p.ToolRequest.Ref, p.ToolRequest.Name), "name": p.ToolRequest.Name, "arguments": args}) | |
| 323 | + } | |
| 324 | + return items, nil | |
| 325 | +} | |
| 326 | + | |
| 327 | +// callID is the call's id, the tool's name when Genkit has none (as | |
| 328 | +// compat_oai does). | |
| 329 | +func callID(ref, name string) string { | |
| 330 | + if ref != "" { | |
| 331 | + return ref | |
| 332 | + } | |
| 333 | + return name | |
| 334 | +} | |
| 335 | + | |
| 336 | +// toolArguments is a tool call's input as the JSON string the API wants. | |
| 337 | +func toolArguments(input any) (string, error) { | |
| 338 | + if s, ok := input.(string); ok { | |
| 339 | + return s, nil | |
| 340 | + } | |
| 341 | + if input == nil { | |
| 342 | + return "{}", nil | |
| 343 | + } | |
| 344 | + raw, err := json.Marshal(input) | |
| 345 | + if err != nil { | |
| 346 | + return "", fmt.Errorf("responses: tool arguments: %w", err) | |
| 347 | + } | |
| 348 | + return string(raw), nil | |
| 349 | +} | |
| 350 | + | |
| 351 | +// responsesToolOutput is a tool's result as a string: a string as is, anything else | |
| 352 | +// in JSON (what compat_oai sends as the tool message). | |
| 353 | +func responsesToolOutput(output any) (string, error) { | |
| 354 | + if s, ok := output.(string); ok { | |
| 355 | + return s, nil | |
| 356 | + } | |
| 357 | + raw, err := json.Marshal(output) | |
| 358 | + if err != nil { | |
| 359 | + return "", fmt.Errorf("responses: tool output: %w", err) | |
| 360 | + } | |
| 361 | + return string(raw), nil | |
| 362 | +} | |
| 363 | + | |
| 364 | +// responsesTools declares the tools as function tools, not strict: mm's | |
| 365 | +// schemas have optional properties, which strict mode refuses. | |
| 366 | +func responsesTools(tools []*ai.ToolDefinition) []any { | |
| 367 | + out := make([]any, 0, len(tools)) | |
| 368 | + for _, t := range tools { | |
| 369 | + if t == nil { | |
| 370 | + continue | |
| 371 | + } | |
| 372 | + params := t.InputSchema | |
| 373 | + if params == nil { | |
| 374 | + params = map[string]any{"type": "object", "properties": map[string]any{}} | |
| 375 | + } | |
| 376 | + out = append(out, map[string]any{"type": "function", "name": t.Name, "description": t.Description, "parameters": params, "strict": false}) | |
| 377 | + } | |
| 378 | + return out | |
| 379 | +} | |
| 380 | + | |
| 381 | +// responsesFormat is `text.format` for structuredOutput (ticket 80): the | |
| 382 | +// schema, strict as the openai provider sends it; nil for plain text. | |
| 383 | +func responsesFormat(output *ai.ModelOutputConfig) map[string]any { | |
| 384 | + if output == nil || output.Format != "json" { | |
| 385 | + return nil | |
| 386 | + } | |
| 387 | + if output.Schema == nil { | |
| 388 | + return map[string]any{"type": "json_object"} | |
| 389 | + } | |
| 390 | + return map[string]any{"type": "json_schema", "name": "output", "schema": output.Schema, "strict": true} | |
| 391 | +} | |
| 392 | + | |
| 393 | +// responsesResult is the little of a Responses answer mm reads. | |
| 394 | +type responsesResult struct { | |
| 395 | + Status string `json:"status"` | |
| 396 | + Output []json.RawMessage `json:"output"` | |
| 397 | + IncompleteDetails *struct { | |
| 398 | + Reason string `json:"reason"` | |
| 399 | + } `json:"incomplete_details"` | |
| 400 | + Error *struct { | |
| 401 | + Message string `json:"message"` | |
| 402 | + } `json:"error"` | |
| 403 | + Usage *struct { | |
| 404 | + InputTokens int `json:"input_tokens"` | |
| 405 | + OutputTokens int `json:"output_tokens"` | |
| 406 | + TotalTokens int `json:"total_tokens"` | |
| 407 | + InputTokensDetails struct { | |
| 408 | + CachedTokens int `json:"cached_tokens"` | |
| 409 | + } `json:"input_tokens_details"` | |
| 410 | + OutputTokensDetails struct { | |
| 411 | + ReasoningTokens int `json:"reasoning_tokens"` | |
| 412 | + } `json:"output_tokens_details"` | |
| 413 | + } `json:"usage"` | |
| 414 | +} | |
| 415 | + | |
| 416 | +// outputItem is one item of the answer's output. | |
| 417 | +type outputItem struct { | |
| 418 | + Type string `json:"type"` | |
| 419 | + CallID string `json:"call_id"` | |
| 420 | + Name string `json:"name"` | |
| 421 | + Arguments string `json:"arguments"` | |
| 422 | + Content []struct { | |
| 423 | + Type string `json:"type"` | |
| 424 | + Text string `json:"text"` | |
| 425 | + Refusal string `json:"refusal"` | |
| 426 | + } `json:"content"` | |
| 427 | +} | |
| 428 | + | |
| 429 | +// modelResponse turns the answer into Genkit's response. A failed answer is | |
| 430 | +// an error; tool arguments that do not parse are the error compat_oai gives | |
| 431 | +// ("could not parse tool args"), so the call is handed back to the model the | |
| 432 | +// same way (toolargs.go). | |
| 433 | +func (r *responsesResult) modelResponse() (*ai.ModelResponse, error) { | |
| 434 | + if r.Status == "failed" { | |
| 435 | + msg := "the response failed" | |
| 436 | + if r.Error != nil && r.Error.Message != "" { | |
| 437 | + msg = r.Error.Message | |
| 438 | + } | |
| 439 | + return nil, fmt.Errorf("stream error: %s", msg) | |
| 440 | + } | |
| 441 | + msg := &ai.Message{Role: ai.RoleModel, Content: []*ai.Part{}} | |
| 442 | + resp := &ai.ModelResponse{Message: msg, FinishReason: ai.FinishReasonStop} | |
| 443 | + var reasoning []any | |
| 444 | + var text strings.Builder | |
| 445 | + var calls []*ai.Part | |
| 446 | + for _, raw := range r.Output { | |
| 447 | + var item outputItem | |
| 448 | + if json.Unmarshal(raw, &item) != nil { | |
| 449 | + continue | |
| 450 | + } | |
| 451 | + switch item.Type { | |
| 452 | + case "reasoning": | |
| 453 | + var keep any | |
| 454 | + if json.Unmarshal(raw, &keep) == nil { | |
| 455 | + reasoning = append(reasoning, keep) | |
| 456 | + } | |
| 457 | + case "message": | |
| 458 | + for _, c := range item.Content { | |
| 459 | + switch c.Type { | |
| 460 | + case "output_text": | |
| 461 | + text.WriteString(c.Text) | |
| 462 | + case "refusal": | |
| 463 | + resp.FinishReason, resp.FinishMessage = ai.FinishReasonBlocked, c.Refusal | |
| 464 | + } | |
| 465 | + } | |
| 466 | + case "function_call": | |
| 467 | + input := map[string]any{} | |
| 468 | + if strings.TrimSpace(item.Arguments) != "" { | |
| 469 | + if err := json.Unmarshal([]byte(item.Arguments), &input); err != nil { | |
| 470 | + return nil, fmt.Errorf("could not parse tool args: %w", err) | |
| 471 | + } | |
| 472 | + } | |
| 473 | + calls = append(calls, ai.NewToolRequestPart(&ai.ToolRequest{Ref: item.CallID, Name: item.Name, Input: input})) | |
| 474 | + } | |
| 475 | + } | |
| 476 | + if text.Len() > 0 { | |
| 477 | + msg.Content = append(msg.Content, ai.NewTextPart(text.String())) | |
| 478 | + } | |
| 479 | + msg.Content = append(msg.Content, calls...) | |
| 480 | + if len(reasoning) > 0 { | |
| 481 | + msg.Metadata = map[string]any{responsesReasoningKey: reasoning} | |
| 482 | + } | |
| 483 | + if r.Status == "incomplete" && r.IncompleteDetails != nil { | |
| 484 | + switch r.IncompleteDetails.Reason { | |
| 485 | + case "max_output_tokens": | |
| 486 | + resp.FinishReason = ai.FinishReasonLength | |
| 487 | + case "content_filter": | |
| 488 | + resp.FinishReason = ai.FinishReasonBlocked | |
| 489 | + default: | |
| 490 | + resp.FinishReason, resp.FinishMessage = ai.FinishReasonOther, r.IncompleteDetails.Reason | |
| 491 | + } | |
| 492 | + } | |
| 493 | + if u := r.Usage; u != nil { | |
| 494 | + resp.Usage = &ai.GenerationUsage{ | |
| 495 | + InputTokens: u.InputTokens, | |
| 496 | + OutputTokens: u.OutputTokens, | |
| 497 | + TotalTokens: u.TotalTokens, | |
| 498 | + ThoughtsTokens: u.OutputTokensDetails.ReasoningTokens, | |
| 499 | + CachedContentTokens: u.InputTokensDetails.CachedTokens, | |
| 500 | + } | |
| 501 | + } | |
| 502 | + return resp, nil | |
| 503 | +} | |
| 504 | + | |
| 505 | +// responsesEvent is one streamed event: its type and the fields mm reads. | |
| 506 | +type responsesEvent struct { | |
| 507 | + Type string `json:"type"` | |
| 508 | + Delta string `json:"delta"` | |
| 509 | + ItemID string `json:"item_id"` | |
| 510 | + Message string `json:"message"` | |
| 511 | + Item *json.RawMessage `json:"item"` | |
| 512 | + Response *responsesResult `json:"response"` | |
| 513 | +} | |
| 514 | + | |
| 515 | +// readResponsesStream reads the SSE events of a streamed call: text deltas | |
| 516 | +// go to Genkit's callback, function-call argument deltas too (the runaway | |
| 517 | +// guard and the watchdog read them), reasoning to the turn's listener | |
| 518 | +// (reasoning.go). The answer is the one `response.completed` (or | |
| 519 | +// `response.incomplete`, `response.failed`) carries. A stream that ends | |
| 520 | +// without one broke: "stream error", which the model call retries once. | |
| 521 | +func readResponsesStream(ctx context.Context, body io.Reader, cb ai.ModelStreamCallback) (*responsesResult, error) { | |
| 522 | + onReasoning := reasoningFrom(ctx) | |
| 523 | + calls := map[string]*ai.ToolRequest{} // item id → name and call id | |
| 524 | + sc := bufio.NewScanner(body) | |
| 525 | + sc.Buffer(make([]byte, 64<<10), maxSSELine*8) | |
| 526 | + for sc.Scan() { | |
| 527 | + data, ok := strings.CutPrefix(strings.TrimSpace(sc.Text()), "data:") | |
| 528 | + if !ok { | |
| 529 | + continue | |
| 530 | + } | |
| 531 | + data = strings.TrimSpace(data) | |
| 532 | + if data == "" || data == "[DONE]" { | |
| 533 | + continue | |
| 534 | + } | |
| 535 | + var ev responsesEvent | |
| 536 | + if json.Unmarshal([]byte(data), &ev) != nil { | |
| 537 | + continue | |
| 538 | + } | |
| 539 | + switch ev.Type { | |
| 540 | + case "response.output_text.delta": | |
| 541 | + if err := sendPart(ctx, cb, ai.NewTextPart(ev.Delta)); err != nil { | |
| 542 | + return nil, err | |
| 543 | + } | |
| 544 | + case "response.reasoning_summary_text.delta", "response.reasoning_text.delta": | |
| 545 | + if onReasoning != nil && ev.Delta != "" { | |
| 546 | + onReasoning(ev.Delta) | |
| 547 | + } | |
| 548 | + case "response.output_item.added": | |
| 549 | + if ev.Item != nil { | |
| 550 | + var item outputItem | |
| 551 | + var id struct { | |
| 552 | + ID string `json:"id"` | |
| 553 | + } | |
| 554 | + if json.Unmarshal(*ev.Item, &item) == nil && json.Unmarshal(*ev.Item, &id) == nil && item.Type == "function_call" { | |
| 555 | + calls[id.ID] = &ai.ToolRequest{Name: item.Name, Ref: item.CallID} | |
| 556 | + } | |
| 557 | + } | |
| 558 | + case "response.function_call_arguments.delta": | |
| 559 | + call := calls[ev.ItemID] | |
| 560 | + if call == nil { | |
| 561 | + call = &ai.ToolRequest{} | |
| 562 | + } | |
| 563 | + if err := sendPart(ctx, cb, ai.NewToolRequestPart(&ai.ToolRequest{Name: call.Name, Ref: call.Ref, Input: ev.Delta})); err != nil { | |
| 564 | + return nil, err | |
| 565 | + } | |
| 566 | + case "response.completed", "response.incomplete", "response.failed": | |
| 567 | + if ev.Response == nil { | |
| 568 | + return nil, fmt.Errorf("stream error: %s without a response", ev.Type) | |
| 569 | + } | |
| 570 | + if ev.Type == "response.failed" && ev.Response.Status == "" { | |
| 571 | + ev.Response.Status = "failed" | |
| 572 | + } | |
| 573 | + return ev.Response, nil | |
| 574 | + case "error": | |
| 575 | + msg := ev.Message | |
| 576 | + if msg == "" { | |
| 577 | + msg = data | |
| 578 | + } | |
| 579 | + if errs := serverErrorsFrom(ctx); errs != nil { | |
| 580 | + errs.record(msg) | |
| 581 | + } | |
| 582 | + return nil, fmt.Errorf("stream error: %s", msg) | |
| 583 | + } | |
| 584 | + } | |
| 585 | + if err := sc.Err(); err != nil { | |
| 586 | + if errors.Is(err, context.Canceled) || ctx.Err() != nil { | |
| 587 | + return nil, err | |
| 588 | + } | |
| 589 | + return nil, fmt.Errorf("stream error: %w", err) | |
| 590 | + } | |
| 591 | + return nil, fmt.Errorf("stream error: the stream ended without response.completed (unexpected EOF)") | |
| 592 | +} | |
| 593 | + | |
| 594 | +// sendPart hands one part to Genkit's callback; a callback error stops the | |
| 595 | +// stream (the runaway guard uses it), worded as compat_oai words it. | |
| 596 | +func sendPart(ctx context.Context, cb ai.ModelStreamCallback, part *ai.Part) error { | |
| 597 | + if cb == nil { | |
| 598 | + return nil | |
| 599 | + } | |
| 600 | + if err := cb(ctx, &ai.ModelResponseChunk{Content: []*ai.Part{part}}); err != nil { | |
| 601 | + return fmt.Errorf("callback error: %w", err) | |
| 602 | + } | |
| 603 | + return nil | |
| 604 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,604 @@ | |||
| 1 | +package engine | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "bufio" | ||
| 5 | + "bytes" | ||
| 6 | + "context" | ||
| 7 | + "encoding/json" | ||
| 8 | + "errors" | ||
| 9 | + "fmt" | ||
| 10 | + "io" | ||
| 11 | + "net/http" | ||
| 12 | + "strings" | ||
| 13 | + | ||
| 14 | + "mm/internal/config" | ||
| 15 | + | ||
| 16 | + "github.com/firebase/genkit/go/ai" | ||
| 17 | + "github.com/firebase/genkit/go/genkit" | ||
| 18 | + "github.com/openai/openai-go/option" | ||
| 19 | +) | ||
| 20 | + | ||
| 21 | +// The `openai-responses` provider (ticket 178) speaks OpenAI's Responses API, | ||
| 22 | +// POST <baseUrl>/responses, instead of Chat Completions. OpenAI's reasoning | ||
| 23 | +// models refuse function tools with active reasoning on /v1/chat/completions | ||
| 24 | +// ("To use function tools, use /v1/responses or set reasoning_effort to | ||
| 25 | +// 'none'"), and an mm agent always sends tools: on Responses they keep both. | ||
| 26 | +// | ||
| 27 | +// Genkit's compat_oai plugin only knows Chat Completions, so this file is a | ||
| 28 | +// Genkit model of its own: it turns Genkit's request into a Responses request, | ||
| 29 | +// reads the typed SSE events back, and hands Genkit an ordinary response — | ||
| 30 | +// text, tool requests, usage, finish reason. Everything above the model call | ||
| 31 | +// (the watchdog, the struggle signals, the tool hooks, the history) is the | ||
| 32 | +// same as for every other provider. | ||
| 33 | +// | ||
| 34 | +// Plain HTTP and JSON rather than openai-go's `responses` package: the wire | ||
| 35 | +// format is small, its unions are heavy in Go, and a request built here is | ||
| 36 | +// one a fake server in a test can read back. | ||
| 37 | +// | ||
| 38 | +// The reasoning between the model calls of a turn: the request says | ||
| 39 | +// `store: false` (nothing kept on OpenAI's side) and asks for | ||
| 40 | +// `reasoning.encrypted_content`; the reasoning items of an answer ride on the | ||
| 41 | +// model message's metadata (responsesReasoningKey) and are sent back before | ||
| 42 | +// that message's tool calls, so the model keeps its thread after each tool | ||
| 43 | +// result. The file's `sampling:` can set `store` or `include` itself; then it | ||
| 44 | +// is taken as written. | ||
| 45 | + | ||
| 46 | +// responsesReasoningKey is the message-metadata key holding the reasoning | ||
| 47 | +// items of a Responses answer, as the server returned them. | ||
| 48 | +const responsesReasoningKey = "openaiResponsesReasoning" | ||
| 49 | + | ||
| 50 | +// responsesClient: no overall timeout — a reasoning model can think for | ||
| 51 | +// minutes; the watchdog and the context bound the call. | ||
| 52 | +var responsesClient = &http.Client{} | ||
| 53 | + | ||
| 54 | +// openResponses is Open for the Responses API: a Genkit with no plugin, and | ||
| 55 | +// one model defined here. | ||
| 56 | +func (p *openaiCompat) openResponses(ctx context.Context, b Backend) (*genkit.Genkit, string, error) { | ||
| 57 | + quietGenkit() | ||
| 58 | + g := genkit.Init(ctx) | ||
| 59 | + name := p.name + "/" + b.Model | ||
| 60 | + r := &responsesModel{backend: b, chain: responsesMiddlewares()} | ||
| 61 | + genkit.DefineModel(g, name, &ai.ModelOptions{ //nolint:staticcheck // DefineModelAction would type the config; the sampling map is untyped on purpose | ||
| 62 | + Label: b.Model, | ||
| 63 | + Supports: modelSupports(), | ||
| 64 | + }, r.generate) | ||
| 65 | + return g, name, nil | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +// responsesMiddlewares is the HTTP chain: only the trace — the Chat | ||
| 69 | +// Completions ones rewrite fields this API does not have. | ||
| 70 | +func responsesMiddlewares() []option.Middleware { | ||
| 71 | + if config.Cfg.Trace.Enabled { | ||
| 72 | + return []option.Middleware{traceMiddleware(config.Cfg.Trace.Dir, config.Cfg.ACP.Name)} | ||
| 73 | + } | ||
| 74 | + return nil | ||
| 75 | +} | ||
| 76 | + | ||
| 77 | +// responsesModel is the model behind one Engine. | ||
| 78 | +type responsesModel struct { | ||
| 79 | + backend Backend | ||
| 80 | + chain []option.Middleware | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +// generate is the Genkit model function: one model call. | ||
| 84 | +func (r *responsesModel) generate(ctx context.Context, req *ai.ModelRequest, cb ai.ModelStreamCallback) (*ai.ModelResponse, error) { | ||
| 85 | + off, _ := ctx.Value(noThinkKey{}).(bool) | ||
| 86 | + body, err := responsesRequest(r.backend.Model, req, cb != nil, off) | ||
| 87 | + if err != nil { | ||
| 88 | + return nil, err | ||
| 89 | + } | ||
| 90 | + resp, err := r.post(ctx, body) | ||
| 91 | + if err != nil { | ||
| 92 | + return nil, err | ||
| 93 | + } | ||
| 94 | + defer func() { _ = resp.Body.Close() }() | ||
| 95 | + var out *responsesResult | ||
| 96 | + if cb != nil && strings.Contains(resp.Header.Get("Content-Type"), "text/event-stream") { | ||
| 97 | + out, err = readResponsesStream(ctx, resp.Body, cb) | ||
| 98 | + } else { | ||
| 99 | + out = &responsesResult{} | ||
| 100 | + err = json.NewDecoder(resp.Body).Decode(out) | ||
| 101 | + if err != nil { | ||
| 102 | + err = fmt.Errorf("responses: reading the answer: %w", err) | ||
| 103 | + } | ||
| 104 | + } | ||
| 105 | + if err != nil { | ||
| 106 | + return nil, err | ||
| 107 | + } | ||
| 108 | + mr, err := out.modelResponse() | ||
| 109 | + if err != nil { | ||
| 110 | + return nil, err | ||
| 111 | + } | ||
| 112 | + mr.Request = req | ||
| 113 | + return mr, nil | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +// post sends the request through the middlewares and returns a 2xx answer; | ||
| 117 | +// anything else is an error whose text carries the status the way the | ||
| 118 | +// OpenAI client's does (`POST "<url>": 401 Unauthorized {…}`), so Explain | ||
| 119 | +// reads it the same. | ||
| 120 | +func (r *responsesModel) post(ctx context.Context, body []byte) (*http.Response, error) { | ||
| 121 | + url := strings.TrimSuffix(r.backend.BaseURL, "/") + "/responses" | ||
| 122 | + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) | ||
| 123 | + if err != nil { | ||
| 124 | + return nil, err | ||
| 125 | + } | ||
| 126 | + req.Header.Set("Content-Type", "application/json") | ||
| 127 | + req.Header.Set("Authorization", "Bearer "+r.backend.APIKey) | ||
| 128 | + req.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(body)), nil } | ||
| 129 | + next := func(req *http.Request) (*http.Response, error) { return responsesClient.Do(req) } | ||
| 130 | + for i := len(r.chain) - 1; i >= 0; i-- { | ||
| 131 | + mw, inner := r.chain[i], next | ||
| 132 | + next = func(req *http.Request) (*http.Response, error) { return mw(req, inner) } | ||
| 133 | + } | ||
| 134 | + resp, err := next(req) | ||
| 135 | + if err != nil { | ||
| 136 | + return nil, err | ||
| 137 | + } | ||
| 138 | + if resp.StatusCode/100 != 2 { | ||
| 139 | + defer func() { _ = resp.Body.Close() }() | ||
| 140 | + said, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) | ||
| 141 | + return nil, fmt.Errorf("POST %q: %s %s", url, resp.Status, strings.TrimSpace(string(said))) | ||
| 142 | + } | ||
| 143 | + return resp, nil | ||
| 144 | +} | ||
| 145 | + | ||
| 146 | +// responsesRequest builds the JSON body of one call. | ||
| 147 | +// | ||
| 148 | +// body, _ := responsesRequest("gpt-6-luna", req, true, false) | ||
| 149 | +// // {"model":"gpt-6-luna","input":[…],"tools":[…],"stream":true,"store":false,"include":["reasoning.encrypted_content"],…} | ||
| 150 | +func responsesRequest(model string, req *ai.ModelRequest, stream, noThink bool) ([]byte, error) { | ||
| 151 | + m, err := samplingFields(req.Config) | ||
| 152 | + if err != nil { | ||
| 153 | + return nil, err | ||
| 154 | + } | ||
| 155 | + if noThink { | ||
| 156 | + setReasoning(m, "effort", "none") | ||
| 157 | + } | ||
| 158 | + input, err := responsesInput(req.Messages) | ||
| 159 | + if err != nil { | ||
| 160 | + return nil, err | ||
| 161 | + } | ||
| 162 | + m["model"] = model | ||
| 163 | + m["input"] = input | ||
| 164 | + if len(req.Tools) > 0 { | ||
| 165 | + m["tools"] = responsesTools(req.Tools) | ||
| 166 | + } | ||
| 167 | + if req.ToolChoice != "" { | ||
| 168 | + m["tool_choice"] = string(req.ToolChoice) | ||
| 169 | + } | ||
| 170 | + if format := responsesFormat(req.Output); format != nil { | ||
| 171 | + text, _ := m["text"].(map[string]any) | ||
| 172 | + if text == nil { | ||
| 173 | + text = map[string]any{} | ||
| 174 | + } | ||
| 175 | + text["format"] = format | ||
| 176 | + m["text"] = text | ||
| 177 | + } | ||
| 178 | + m["stream"] = stream | ||
| 179 | + if _, set := m["store"]; !set { | ||
| 180 | + m["store"] = false | ||
| 181 | + } | ||
| 182 | + if _, set := m["include"]; !set && m["store"] == false { | ||
| 183 | + m["include"] = []string{"reasoning.encrypted_content"} | ||
| 184 | + } | ||
| 185 | + return json.Marshal(m) | ||
| 186 | +} | ||
| 187 | + | ||
| 188 | +// samplingFields is the request's config — the file's `sampling:` block — | ||
| 189 | +// as the fields of a Responses request, written as they are except for the | ||
| 190 | +// Chat Completions names this API spells differently: the answer limit | ||
| 191 | +// (max_tokens, max_completion_tokens → max_output_tokens) and | ||
| 192 | +// reasoning_effort (→ reasoning.effort). | ||
| 193 | +func samplingFields(cfg any) (map[string]any, error) { | ||
| 194 | + m := map[string]any{} | ||
| 195 | + switch c := cfg.(type) { | ||
| 196 | + case nil: | ||
| 197 | + case map[string]any: | ||
| 198 | + for k, v := range c { | ||
| 199 | + m[k] = v | ||
| 200 | + } | ||
| 201 | + default: | ||
| 202 | + raw, err := json.Marshal(c) | ||
| 203 | + if err != nil { | ||
| 204 | + return nil, fmt.Errorf("responses: config: %w", err) | ||
| 205 | + } | ||
| 206 | + if err := json.Unmarshal(raw, &m); err != nil { | ||
| 207 | + return nil, fmt.Errorf("responses: config: %w", err) | ||
| 208 | + } | ||
| 209 | + } | ||
| 210 | + for _, key := range []string{"max_completion_tokens", "max_tokens"} { | ||
| 211 | + if v, ok := m[key]; ok { | ||
| 212 | + if _, set := m["max_output_tokens"]; !set { | ||
| 213 | + m["max_output_tokens"] = v | ||
| 214 | + } | ||
| 215 | + delete(m, key) | ||
| 216 | + } | ||
| 217 | + } | ||
| 218 | + if v, ok := m["reasoning_effort"]; ok { | ||
| 219 | + delete(m, "reasoning_effort") | ||
| 220 | + if r, _ := m["reasoning"].(map[string]any); r == nil || r["effort"] == nil { | ||
| 221 | + setReasoning(m, "effort", v) | ||
| 222 | + } | ||
| 223 | + } | ||
| 224 | + return m, nil | ||
| 225 | +} | ||
| 226 | + | ||
| 227 | +// setReasoning sets one field of the `reasoning` object, keeping the others. | ||
| 228 | +func setReasoning(m map[string]any, key string, value any) { | ||
| 229 | + r, _ := m["reasoning"].(map[string]any) | ||
| 230 | + if r == nil { | ||
| 231 | + r = map[string]any{} | ||
| 232 | + } else { | ||
| 233 | + copied := make(map[string]any, len(r)+1) | ||
| 234 | + for k, v := range r { | ||
| 235 | + copied[k] = v | ||
| 236 | + } | ||
| 237 | + r = copied | ||
| 238 | + } | ||
| 239 | + r[key] = value | ||
| 240 | + m["reasoning"] = r | ||
| 241 | +} | ||
| 242 | + | ||
| 243 | +// responsesInput turns Genkit's messages into Responses input items: | ||
| 244 | +// system and user messages, the model's earlier answers (its reasoning | ||
| 245 | +// items, its text, its function calls) and the tool results. | ||
| 246 | +func responsesInput(messages []*ai.Message) ([]any, error) { | ||
| 247 | + var items []any | ||
| 248 | + for _, msg := range messages { | ||
| 249 | + if msg == nil { | ||
| 250 | + continue | ||
| 251 | + } | ||
| 252 | + switch msg.Role { | ||
| 253 | + case ai.RoleSystem: | ||
| 254 | + if text := msg.Text(); text != "" { | ||
| 255 | + items = append(items, map[string]any{"role": "system", "content": text}) | ||
| 256 | + } | ||
| 257 | + case ai.RoleUser: | ||
| 258 | + if content := userContent(msg.Content); len(content) > 0 { | ||
| 259 | + items = append(items, map[string]any{"role": "user", "content": content}) | ||
| 260 | + } | ||
| 261 | + case ai.RoleModel: | ||
| 262 | + modelItems, err := modelInput(msg) | ||
| 263 | + if err != nil { | ||
| 264 | + return nil, err | ||
| 265 | + } | ||
| 266 | + items = append(items, modelItems...) | ||
| 267 | + case ai.RoleTool: | ||
| 268 | + for _, p := range msg.Content { | ||
| 269 | + if p == nil || !p.IsToolResponse() || p.ToolResponse == nil { | ||
| 270 | + continue | ||
| 271 | + } | ||
| 272 | + out, err := responsesToolOutput(p.ToolResponse.Output) | ||
| 273 | + if err != nil { | ||
| 274 | + return nil, err | ||
| 275 | + } | ||
| 276 | + items = append(items, map[string]any{"type": "function_call_output", "call_id": callID(p.ToolResponse.Ref, p.ToolResponse.Name), "output": out}) | ||
| 277 | + } | ||
| 278 | + } | ||
| 279 | + } | ||
| 280 | + return items, nil | ||
| 281 | +} | ||
| 282 | + | ||
| 283 | +// userContent is a user message's parts: text, and images by URL. | ||
| 284 | +func userContent(parts []*ai.Part) []any { | ||
| 285 | + var content []any | ||
| 286 | + for _, p := range parts { | ||
| 287 | + switch { | ||
| 288 | + case p == nil: | ||
| 289 | + case p.IsText(): | ||
| 290 | + content = append(content, map[string]any{"type": "input_text", "text": p.Text}) | ||
| 291 | + case p.IsMedia(): | ||
| 292 | + content = append(content, map[string]any{"type": "input_image", "image_url": p.Text}) | ||
| 293 | + } | ||
| 294 | + } | ||
| 295 | + return content | ||
| 296 | +} | ||
| 297 | + | ||
| 298 | +// modelInput is one of the model's earlier answers, in the order the server | ||
| 299 | +// produced them: reasoning, text, function calls. | ||
| 300 | +func modelInput(msg *ai.Message) ([]any, error) { | ||
| 301 | + var items []any | ||
| 302 | + if raw, ok := msg.Metadata[responsesReasoningKey].([]any); ok { | ||
| 303 | + items = append(items, raw...) | ||
| 304 | + } | ||
| 305 | + var text strings.Builder | ||
| 306 | + for _, p := range msg.Content { | ||
| 307 | + if p != nil && p.IsText() { | ||
| 308 | + text.WriteString(p.Text) | ||
| 309 | + } | ||
| 310 | + } | ||
| 311 | + if text.Len() > 0 { | ||
| 312 | + items = append(items, map[string]any{"role": "assistant", "content": text.String()}) | ||
| 313 | + } | ||
| 314 | + for _, p := range msg.Content { | ||
| 315 | + if p == nil || !p.IsToolRequest() || p.ToolRequest == nil { | ||
| 316 | + continue | ||
| 317 | + } | ||
| 318 | + args, err := toolArguments(p.ToolRequest.Input) | ||
| 319 | + if err != nil { | ||
| 320 | + return nil, err | ||
| 321 | + } | ||
| 322 | + items = append(items, map[string]any{"type": "function_call", "call_id": callID(p.ToolRequest.Ref, p.ToolRequest.Name), "name": p.ToolRequest.Name, "arguments": args}) | ||
| 323 | + } | ||
| 324 | + return items, nil | ||
| 325 | +} | ||
| 326 | + | ||
| 327 | +// callID is the call's id, the tool's name when Genkit has none (as | ||
| 328 | +// compat_oai does). | ||
| 329 | +func callID(ref, name string) string { | ||
| 330 | + if ref != "" { | ||
| 331 | + return ref | ||
| 332 | + } | ||
| 333 | + return name | ||
| 334 | +} | ||
| 335 | + | ||
| 336 | +// toolArguments is a tool call's input as the JSON string the API wants. | ||
| 337 | +func toolArguments(input any) (string, error) { | ||
| 338 | + if s, ok := input.(string); ok { | ||
| 339 | + return s, nil | ||
| 340 | + } | ||
| 341 | + if input == nil { | ||
| 342 | + return "{}", nil | ||
| 343 | + } | ||
| 344 | + raw, err := json.Marshal(input) | ||
| 345 | + if err != nil { | ||
| 346 | + return "", fmt.Errorf("responses: tool arguments: %w", err) | ||
| 347 | + } | ||
| 348 | + return string(raw), nil | ||
| 349 | +} | ||
| 350 | + | ||
| 351 | +// responsesToolOutput is a tool's result as a string: a string as is, anything else | ||
| 352 | +// in JSON (what compat_oai sends as the tool message). | ||
| 353 | +func responsesToolOutput(output any) (string, error) { | ||
| 354 | + if s, ok := output.(string); ok { | ||
| 355 | + return s, nil | ||
| 356 | + } | ||
| 357 | + raw, err := json.Marshal(output) | ||
| 358 | + if err != nil { | ||
| 359 | + return "", fmt.Errorf("responses: tool output: %w", err) | ||
| 360 | + } | ||
| 361 | + return string(raw), nil | ||
| 362 | +} | ||
| 363 | + | ||
| 364 | +// responsesTools declares the tools as function tools, not strict: mm's | ||
| 365 | +// schemas have optional properties, which strict mode refuses. | ||
| 366 | +func responsesTools(tools []*ai.ToolDefinition) []any { | ||
| 367 | + out := make([]any, 0, len(tools)) | ||
| 368 | + for _, t := range tools { | ||
| 369 | + if t == nil { | ||
| 370 | + continue | ||
| 371 | + } | ||
| 372 | + params := t.InputSchema | ||
| 373 | + if params == nil { | ||
| 374 | + params = map[string]any{"type": "object", "properties": map[string]any{}} | ||
| 375 | + } | ||
| 376 | + out = append(out, map[string]any{"type": "function", "name": t.Name, "description": t.Description, "parameters": params, "strict": false}) | ||
| 377 | + } | ||
| 378 | + return out | ||
| 379 | +} | ||
| 380 | + | ||
| 381 | +// responsesFormat is `text.format` for structuredOutput (ticket 80): the | ||
| 382 | +// schema, strict as the openai provider sends it; nil for plain text. | ||
| 383 | +func responsesFormat(output *ai.ModelOutputConfig) map[string]any { | ||
| 384 | + if output == nil || output.Format != "json" { | ||
| 385 | + return nil | ||
| 386 | + } | ||
| 387 | + if output.Schema == nil { | ||
| 388 | + return map[string]any{"type": "json_object"} | ||
| 389 | + } | ||
| 390 | + return map[string]any{"type": "json_schema", "name": "output", "schema": output.Schema, "strict": true} | ||
| 391 | +} | ||
| 392 | + | ||
| 393 | +// responsesResult is the little of a Responses answer mm reads. | ||
| 394 | +type responsesResult struct { | ||
| 395 | + Status string `json:"status"` | ||
| 396 | + Output []json.RawMessage `json:"output"` | ||
| 397 | + IncompleteDetails *struct { | ||
| 398 | + Reason string `json:"reason"` | ||
| 399 | + } `json:"incomplete_details"` | ||
| 400 | + Error *struct { | ||
| 401 | + Message string `json:"message"` | ||
| 402 | + } `json:"error"` | ||
| 403 | + Usage *struct { | ||
| 404 | + InputTokens int `json:"input_tokens"` | ||
| 405 | + OutputTokens int `json:"output_tokens"` | ||
| 406 | + TotalTokens int `json:"total_tokens"` | ||
| 407 | + InputTokensDetails struct { | ||
| 408 | + CachedTokens int `json:"cached_tokens"` | ||
| 409 | + } `json:"input_tokens_details"` | ||
| 410 | + OutputTokensDetails struct { | ||
| 411 | + ReasoningTokens int `json:"reasoning_tokens"` | ||
| 412 | + } `json:"output_tokens_details"` | ||
| 413 | + } `json:"usage"` | ||
| 414 | +} | ||
| 415 | + | ||
| 416 | +// outputItem is one item of the answer's output. | ||
| 417 | +type outputItem struct { | ||
| 418 | + Type string `json:"type"` | ||
| 419 | + CallID string `json:"call_id"` | ||
| 420 | + Name string `json:"name"` | ||
| 421 | + Arguments string `json:"arguments"` | ||
| 422 | + Content []struct { | ||
| 423 | + Type string `json:"type"` | ||
| 424 | + Text string `json:"text"` | ||
| 425 | + Refusal string `json:"refusal"` | ||
| 426 | + } `json:"content"` | ||
| 427 | +} | ||
| 428 | + | ||
| 429 | +// modelResponse turns the answer into Genkit's response. A failed answer is | ||
| 430 | +// an error; tool arguments that do not parse are the error compat_oai gives | ||
| 431 | +// ("could not parse tool args"), so the call is handed back to the model the | ||
| 432 | +// same way (toolargs.go). | ||
| 433 | +func (r *responsesResult) modelResponse() (*ai.ModelResponse, error) { | ||
| 434 | + if r.Status == "failed" { | ||
| 435 | + msg := "the response failed" | ||
| 436 | + if r.Error != nil && r.Error.Message != "" { | ||
| 437 | + msg = r.Error.Message | ||
| 438 | + } | ||
| 439 | + return nil, fmt.Errorf("stream error: %s", msg) | ||
| 440 | + } | ||
| 441 | + msg := &ai.Message{Role: ai.RoleModel, Content: []*ai.Part{}} | ||
| 442 | + resp := &ai.ModelResponse{Message: msg, FinishReason: ai.FinishReasonStop} | ||
| 443 | + var reasoning []any | ||
| 444 | + var text strings.Builder | ||
| 445 | + var calls []*ai.Part | ||
| 446 | + for _, raw := range r.Output { | ||
| 447 | + var item outputItem | ||
| 448 | + if json.Unmarshal(raw, &item) != nil { | ||
| 449 | + continue | ||
| 450 | + } | ||
| 451 | + switch item.Type { | ||
| 452 | + case "reasoning": | ||
| 453 | + var keep any | ||
| 454 | + if json.Unmarshal(raw, &keep) == nil { | ||
| 455 | + reasoning = append(reasoning, keep) | ||
| 456 | + } | ||
| 457 | + case "message": | ||
| 458 | + for _, c := range item.Content { | ||
| 459 | + switch c.Type { | ||
| 460 | + case "output_text": | ||
| 461 | + text.WriteString(c.Text) | ||
| 462 | + case "refusal": | ||
| 463 | + resp.FinishReason, resp.FinishMessage = ai.FinishReasonBlocked, c.Refusal | ||
| 464 | + } | ||
| 465 | + } | ||
| 466 | + case "function_call": | ||
| 467 | + input := map[string]any{} | ||
| 468 | + if strings.TrimSpace(item.Arguments) != "" { | ||
| 469 | + if err := json.Unmarshal([]byte(item.Arguments), &input); err != nil { | ||
| 470 | + return nil, fmt.Errorf("could not parse tool args: %w", err) | ||
| 471 | + } | ||
| 472 | + } | ||
| 473 | + calls = append(calls, ai.NewToolRequestPart(&ai.ToolRequest{Ref: item.CallID, Name: item.Name, Input: input})) | ||
| 474 | + } | ||
| 475 | + } | ||
| 476 | + if text.Len() > 0 { | ||
| 477 | + msg.Content = append(msg.Content, ai.NewTextPart(text.String())) | ||
| 478 | + } | ||
| 479 | + msg.Content = append(msg.Content, calls...) | ||
| 480 | + if len(reasoning) > 0 { | ||
| 481 | + msg.Metadata = map[string]any{responsesReasoningKey: reasoning} | ||
| 482 | + } | ||
| 483 | + if r.Status == "incomplete" && r.IncompleteDetails != nil { | ||
| 484 | + switch r.IncompleteDetails.Reason { | ||
| 485 | + case "max_output_tokens": | ||
| 486 | + resp.FinishReason = ai.FinishReasonLength | ||
| 487 | + case "content_filter": | ||
| 488 | + resp.FinishReason = ai.FinishReasonBlocked | ||
| 489 | + default: | ||
| 490 | + resp.FinishReason, resp.FinishMessage = ai.FinishReasonOther, r.IncompleteDetails.Reason | ||
| 491 | + } | ||
| 492 | + } | ||
| 493 | + if u := r.Usage; u != nil { | ||
| 494 | + resp.Usage = &ai.GenerationUsage{ | ||
| 495 | + InputTokens: u.InputTokens, | ||
| 496 | + OutputTokens: u.OutputTokens, | ||
| 497 | + TotalTokens: u.TotalTokens, | ||
| 498 | + ThoughtsTokens: u.OutputTokensDetails.ReasoningTokens, | ||
| 499 | + CachedContentTokens: u.InputTokensDetails.CachedTokens, | ||
| 500 | + } | ||
| 501 | + } | ||
| 502 | + return resp, nil | ||
| 503 | +} | ||
| 504 | + | ||
| 505 | +// responsesEvent is one streamed event: its type and the fields mm reads. | ||
| 506 | +type responsesEvent struct { | ||
| 507 | + Type string `json:"type"` | ||
| 508 | + Delta string `json:"delta"` | ||
| 509 | + ItemID string `json:"item_id"` | ||
| 510 | + Message string `json:"message"` | ||
| 511 | + Item *json.RawMessage `json:"item"` | ||
| 512 | + Response *responsesResult `json:"response"` | ||
| 513 | +} | ||
| 514 | + | ||
| 515 | +// readResponsesStream reads the SSE events of a streamed call: text deltas | ||
| 516 | +// go to Genkit's callback, function-call argument deltas too (the runaway | ||
| 517 | +// guard and the watchdog read them), reasoning to the turn's listener | ||
| 518 | +// (reasoning.go). The answer is the one `response.completed` (or | ||
| 519 | +// `response.incomplete`, `response.failed`) carries. A stream that ends | ||
| 520 | +// without one broke: "stream error", which the model call retries once. | ||
| 521 | +func readResponsesStream(ctx context.Context, body io.Reader, cb ai.ModelStreamCallback) (*responsesResult, error) { | ||
| 522 | + onReasoning := reasoningFrom(ctx) | ||
| 523 | + calls := map[string]*ai.ToolRequest{} // item id → name and call id | ||
| 524 | + sc := bufio.NewScanner(body) | ||
| 525 | + sc.Buffer(make([]byte, 64<<10), maxSSELine*8) | ||
| 526 | + for sc.Scan() { | ||
| 527 | + data, ok := strings.CutPrefix(strings.TrimSpace(sc.Text()), "data:") | ||
| 528 | + if !ok { | ||
| 529 | + continue | ||
| 530 | + } | ||
| 531 | + data = strings.TrimSpace(data) | ||
| 532 | + if data == "" || data == "[DONE]" { | ||
| 533 | + continue | ||
| 534 | + } | ||
| 535 | + var ev responsesEvent | ||
| 536 | + if json.Unmarshal([]byte(data), &ev) != nil { | ||
| 537 | + continue | ||
| 538 | + } | ||
| 539 | + switch ev.Type { | ||
| 540 | + case "response.output_text.delta": | ||
| 541 | + if err := sendPart(ctx, cb, ai.NewTextPart(ev.Delta)); err != nil { | ||
| 542 | + return nil, err | ||
| 543 | + } | ||
| 544 | + case "response.reasoning_summary_text.delta", "response.reasoning_text.delta": | ||
| 545 | + if onReasoning != nil && ev.Delta != "" { | ||
| 546 | + onReasoning(ev.Delta) | ||
| 547 | + } | ||
| 548 | + case "response.output_item.added": | ||
| 549 | + if ev.Item != nil { | ||
| 550 | + var item outputItem | ||
| 551 | + var id struct { | ||
| 552 | + ID string `json:"id"` | ||
| 553 | + } | ||
| 554 | + if json.Unmarshal(*ev.Item, &item) == nil && json.Unmarshal(*ev.Item, &id) == nil && item.Type == "function_call" { | ||
| 555 | + calls[id.ID] = &ai.ToolRequest{Name: item.Name, Ref: item.CallID} | ||
| 556 | + } | ||
| 557 | + } | ||
| 558 | + case "response.function_call_arguments.delta": | ||
| 559 | + call := calls[ev.ItemID] | ||
| 560 | + if call == nil { | ||
| 561 | + call = &ai.ToolRequest{} | ||
| 562 | + } | ||
| 563 | + if err := sendPart(ctx, cb, ai.NewToolRequestPart(&ai.ToolRequest{Name: call.Name, Ref: call.Ref, Input: ev.Delta})); err != nil { | ||
| 564 | + return nil, err | ||
| 565 | + } | ||
| 566 | + case "response.completed", "response.incomplete", "response.failed": | ||
| 567 | + if ev.Response == nil { | ||
| 568 | + return nil, fmt.Errorf("stream error: %s without a response", ev.Type) | ||
| 569 | + } | ||
| 570 | + if ev.Type == "response.failed" && ev.Response.Status == "" { | ||
| 571 | + ev.Response.Status = "failed" | ||
| 572 | + } | ||
| 573 | + return ev.Response, nil | ||
| 574 | + case "error": | ||
| 575 | + msg := ev.Message | ||
| 576 | + if msg == "" { | ||
| 577 | + msg = data | ||
| 578 | + } | ||
| 579 | + if errs := serverErrorsFrom(ctx); errs != nil { | ||
| 580 | + errs.record(msg) | ||
| 581 | + } | ||
| 582 | + return nil, fmt.Errorf("stream error: %s", msg) | ||
| 583 | + } | ||
| 584 | + } | ||
| 585 | + if err := sc.Err(); err != nil { | ||
| 586 | + if errors.Is(err, context.Canceled) || ctx.Err() != nil { | ||
| 587 | + return nil, err | ||
| 588 | + } | ||
| 589 | + return nil, fmt.Errorf("stream error: %w", err) | ||
| 590 | + } | ||
| 591 | + return nil, fmt.Errorf("stream error: the stream ended without response.completed (unexpected EOF)") | ||
| 592 | +} | ||
| 593 | + | ||
| 594 | +// sendPart hands one part to Genkit's callback; a callback error stops the | ||
| 595 | +// stream (the runaway guard uses it), worded as compat_oai words it. | ||
| 596 | +func sendPart(ctx context.Context, cb ai.ModelStreamCallback, part *ai.Part) error { | ||
| 597 | + if cb == nil { | ||
| 598 | + return nil | ||
| 599 | + } | ||
| 600 | + if err := cb(ctx, &ai.ModelResponseChunk{Content: []*ai.Part{part}}); err != nil { | ||
| 601 | + return fmt.Errorf("callback error: %w", err) | ||
| 602 | + } | ||
| 603 | + return nil | ||
| 604 | +} | ||
added
internal/engine/responses_test.go +354 -0 | new file mode 100644 | ||
| @@ -0,0 +1,354 @@ | ||
| 1 | +package engine | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "context" | |
| 5 | + "encoding/json" | |
| 6 | + "fmt" | |
| 7 | + "io" | |
| 8 | + "net/http" | |
| 9 | + "net/http/httptest" | |
| 10 | + "strings" | |
| 11 | + "sync" | |
| 12 | + "testing" | |
| 13 | + | |
| 14 | + "mm/internal/config" | |
| 15 | + | |
| 16 | + "github.com/firebase/genkit/go/ai" | |
| 17 | + "github.com/firebase/genkit/go/genkit" | |
| 18 | +) | |
| 19 | + | |
| 20 | +// fakeResponses is a /v1/responses server: each POST is answered by the next | |
| 21 | +// script — SSE events when the request streams, the last event's response as | |
| 22 | +// JSON otherwise — and its body is kept for the test to read. | |
| 23 | +type fakeResponses struct { | |
| 24 | + mu sync.Mutex | |
| 25 | + scripts [][]map[string]any | |
| 26 | + bodies []map[string]any | |
| 27 | +} | |
| 28 | + | |
| 29 | +func (f *fakeResponses) serve(t *testing.T) *httptest.Server { | |
| 30 | + t.Helper() | |
| 31 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 32 | + if r.Method != http.MethodPost || r.URL.Path != "/v1/responses" { | |
| 33 | + http.NotFound(w, r) | |
| 34 | + return | |
| 35 | + } | |
| 36 | + raw, _ := io.ReadAll(r.Body) | |
| 37 | + var body map[string]any | |
| 38 | + if err := json.Unmarshal(raw, &body); err != nil { | |
| 39 | + t.Errorf("request body is not JSON: %s", raw) | |
| 40 | + } | |
| 41 | + f.mu.Lock() | |
| 42 | + n := len(f.bodies) | |
| 43 | + f.bodies = append(f.bodies, body) | |
| 44 | + f.mu.Unlock() | |
| 45 | + if n >= len(f.scripts) { | |
| 46 | + t.Errorf("call %d: no script left", n+1) | |
| 47 | + http.Error(w, "no script", http.StatusInternalServerError) | |
| 48 | + return | |
| 49 | + } | |
| 50 | + events := f.scripts[n] | |
| 51 | + if body["stream"] != true { | |
| 52 | + w.Header().Set("Content-Type", "application/json") | |
| 53 | + _ = json.NewEncoder(w).Encode(events[len(events)-1]["response"]) | |
| 54 | + return | |
| 55 | + } | |
| 56 | + w.Header().Set("Content-Type", "text/event-stream") | |
| 57 | + for _, ev := range events { | |
| 58 | + data, _ := json.Marshal(ev) | |
| 59 | + _, _ = fmt.Fprintf(w, "event: %s\ndata: %s\n\n", ev["type"], data) | |
| 60 | + } | |
| 61 | + })) | |
| 62 | + t.Cleanup(srv.Close) | |
| 63 | + return srv | |
| 64 | +} | |
| 65 | + | |
| 66 | +// responsesEngine opens the openai-responses provider against srv, with a | |
| 67 | +// `bash` tool, the way New does. | |
| 68 | +func responsesEngine(t *testing.T, srv *httptest.Server, sampling map[string]any) *Engine { | |
| 69 | + t.Helper() | |
| 70 | + saved := config.Cfg | |
| 71 | + t.Cleanup(func() { config.Cfg = saved }) | |
| 72 | + config.Cfg.Provider, config.Cfg.Model, config.Cfg.BaseURL = "openai-responses", "gpt-test", srv.URL+"/v1" | |
| 73 | + config.Cfg.Sampling = sampling | |
| 74 | + config.Cfg.ShowThinking = false | |
| 75 | + config.Cfg.Trace.Enabled = false | |
| 76 | + config.Cfg.OutputSchema = nil | |
| 77 | + p, err := Lookup("openai-responses") | |
| 78 | + if err != nil { | |
| 79 | + t.Fatal(err) | |
| 80 | + } | |
| 81 | + b, err := p.Resolve(config.Cfg) | |
| 82 | + if err != nil { | |
| 83 | + t.Fatal(err) | |
| 84 | + } | |
| 85 | + g, model, err := p.Open(context.Background(), b) | |
| 86 | + if err != nil { | |
| 87 | + t.Fatal(err) | |
| 88 | + } | |
| 89 | + genkit.DefineTool(g, "bash", "run a shell command", | |
| 90 | + func(_ *ai.ToolContext, in struct { | |
| 91 | + Command string `json:"command"` | |
| 92 | + }) (string, error) { | |
| 93 | + return "hello from " + in.Command, nil | |
| 94 | + }) | |
| 95 | + return &Engine{G: g, Model: model, Provider: p, Backend: b} | |
| 96 | +} | |
| 97 | + | |
| 98 | +func completed(output []map[string]any, usage map[string]any) map[string]any { | |
| 99 | + return map[string]any{"type": "response.completed", "response": map[string]any{"status": "completed", "output": output, "usage": usage}} | |
| 100 | +} | |
| 101 | + | |
| 102 | +// A tool turn over the Responses API: the call streams, the tool runs, its | |
| 103 | +// output goes back as function_call_output with the same call_id, the | |
| 104 | +// encrypted reasoning goes back before the call, and the answer and the | |
| 105 | +// usage come through. | |
| 106 | +func TestResponsesToolTurn(t *testing.T) { | |
| 107 | + reasoning := map[string]any{"type": "reasoning", "id": "rs_1", "summary": []any{}, "encrypted_content": "SECRET"} | |
| 108 | + call := map[string]any{"type": "function_call", "id": "fc_1", "call_id": "call_1", "name": "bash", "arguments": `{"command":"ls"}`} | |
| 109 | + f := &fakeResponses{scripts: [][]map[string]any{ | |
| 110 | + { | |
| 111 | + {"type": "response.created"}, | |
| 112 | + {"type": "response.reasoning_summary_text.delta", "delta": "Listing first."}, | |
| 113 | + {"type": "response.output_item.added", "item": map[string]any{"type": "function_call", "id": "fc_1", "call_id": "call_1", "name": "bash"}}, | |
| 114 | + {"type": "response.function_call_arguments.delta", "item_id": "fc_1", "delta": `{"command":`}, | |
| 115 | + {"type": "response.function_call_arguments.delta", "item_id": "fc_1", "delta": `"ls"}`}, | |
| 116 | + completed([]map[string]any{reasoning, call}, map[string]any{"input_tokens": 120, "output_tokens": 30, "total_tokens": 150, "output_tokens_details": map[string]any{"reasoning_tokens": 20}}), | |
| 117 | + }, | |
| 118 | + { | |
| 119 | + {"type": "response.output_text.delta", "delta": "There is "}, | |
| 120 | + {"type": "response.output_text.delta", "delta": "one file."}, | |
| 121 | + completed([]map[string]any{{"type": "message", "role": "assistant", "content": []any{map[string]any{"type": "output_text", "text": "There is one file."}}}}, | |
| 122 | + map[string]any{"input_tokens": 200, "output_tokens": 5, "total_tokens": 205, "input_tokens_details": map[string]any{"cached_tokens": 100}}), | |
| 123 | + }, | |
| 124 | + }} | |
| 125 | + srv := f.serve(t) | |
| 126 | + e := responsesEngine(t, srv, map[string]any{"max_completion_tokens": 512, "reasoning_effort": "high"}) | |
| 127 | + | |
| 128 | + resp, full, err := e.Generate(context.Background(), | |
| 129 | + []*ai.Message{ai.NewSystemTextMessage("be brief"), ai.NewUserTextMessage("list the files")}, | |
| 130 | + []ai.ToolRef{ai.ToolName("bash")}) | |
| 131 | + if err != nil { | |
| 132 | + t.Fatalf("Generate: %v", err) | |
| 133 | + } | |
| 134 | + if resp.Text() != "There is one file." { | |
| 135 | + t.Errorf("answer = %q", resp.Text()) | |
| 136 | + } | |
| 137 | + if len(full) < 4 { | |
| 138 | + t.Fatalf("full conversation has %d messages, want system, user, the call, its result", len(full)) | |
| 139 | + } | |
| 140 | + if e.LastInputTokens() != 200 { | |
| 141 | + t.Errorf("LastInputTokens = %d, want the server's 200", e.LastInputTokens()) | |
| 142 | + } | |
| 143 | + if resp.Usage == nil || resp.Usage.CachedContentTokens != 100 { | |
| 144 | + t.Errorf("usage = %+v, want the cached tokens", resp.Usage) | |
| 145 | + } | |
| 146 | + | |
| 147 | + if len(f.bodies) != 2 { | |
| 148 | + t.Fatalf("%d calls, want 2", len(f.bodies)) | |
| 149 | + } | |
| 150 | + first := f.bodies[0] | |
| 151 | + if first["stream"] != true || first["store"] != false || first["model"] != "gpt-test" { | |
| 152 | + t.Errorf("first request: stream %v store %v model %v", first["stream"], first["store"], first["model"]) | |
| 153 | + } | |
| 154 | + if inc, _ := first["include"].([]any); len(inc) != 1 || inc[0] != "reasoning.encrypted_content" { | |
| 155 | + t.Errorf("include = %v", first["include"]) | |
| 156 | + } | |
| 157 | + if first["max_output_tokens"] != float64(512) || first["max_completion_tokens"] != nil || first["max_tokens"] != nil { | |
| 158 | + t.Errorf("limit: max_output_tokens %v, max_completion_tokens %v, max_tokens %v", first["max_output_tokens"], first["max_completion_tokens"], first["max_tokens"]) | |
| 159 | + } | |
| 160 | + if r, _ := first["reasoning"].(map[string]any); r["effort"] != "high" || first["reasoning_effort"] != nil { | |
| 161 | + t.Errorf("reasoning = %v, reasoning_effort = %v", first["reasoning"], first["reasoning_effort"]) | |
| 162 | + } | |
| 163 | + tools, _ := first["tools"].([]any) | |
| 164 | + if len(tools) != 1 || tools[0].(map[string]any)["type"] != "function" || tools[0].(map[string]any)["name"] != "bash" { | |
| 165 | + t.Errorf("tools = %v", tools) | |
| 166 | + } | |
| 167 | + input, _ := first["input"].([]any) | |
| 168 | + if len(input) != 2 || input[0].(map[string]any)["role"] != "system" || input[1].(map[string]any)["role"] != "user" { | |
| 169 | + t.Errorf("first input = %v", input) | |
| 170 | + } | |
| 171 | + | |
| 172 | + second, _ := f.bodies[1]["input"].([]any) | |
| 173 | + var kinds []string | |
| 174 | + for _, it := range second { | |
| 175 | + m := it.(map[string]any) | |
| 176 | + kind, _ := m["type"].(string) | |
| 177 | + if kind == "" { | |
| 178 | + kind, _ = m["role"].(string) | |
| 179 | + } | |
| 180 | + kinds = append(kinds, kind) | |
| 181 | + switch kind { | |
| 182 | + case "reasoning": | |
| 183 | + if m["encrypted_content"] != "SECRET" { | |
| 184 | + t.Errorf("reasoning item sent back without its encrypted content: %v", m) | |
| 185 | + } | |
| 186 | + case "function_call": | |
| 187 | + if m["call_id"] != "call_1" || m["name"] != "bash" || m["arguments"] != `{"command":"ls"}` { | |
| 188 | + t.Errorf("function_call = %v", m) | |
| 189 | + } | |
| 190 | + case "function_call_output": | |
| 191 | + if m["call_id"] != "call_1" || !strings.Contains(fmt.Sprint(m["output"]), "hello from ls") { | |
| 192 | + t.Errorf("function_call_output = %v", m) | |
| 193 | + } | |
| 194 | + } | |
| 195 | + } | |
| 196 | + if got := strings.Join(kinds, " "); got != "system user reasoning function_call function_call_output" { | |
| 197 | + t.Errorf("second input = %s", got) | |
| 198 | + } | |
| 199 | +} | |
| 200 | + | |
| 201 | +// The reasoning summary streamed reaches the turn's listener (thoughts on | |
| 202 | +// screen, and the watchdog's heartbeat). | |
| 203 | +func TestResponsesReasoningReachesTheListener(t *testing.T) { | |
| 204 | + events := []map[string]any{ | |
| 205 | + {"type": "response.reasoning_summary_text.delta", "delta": "Think "}, | |
| 206 | + {"type": "response.reasoning_text.delta", "delta": "hard."}, | |
| 207 | + {"type": "response.output_text.delta", "delta": "ok"}, | |
| 208 | + completed([]map[string]any{{"type": "message", "content": []any{map[string]any{"type": "output_text", "text": "ok"}}}}, nil), | |
| 209 | + } | |
| 210 | + body := strings.Builder{} | |
| 211 | + for _, ev := range events { | |
| 212 | + data, _ := json.Marshal(ev) | |
| 213 | + fmt.Fprintf(&body, "data: %s\n\n", data) | |
| 214 | + } | |
| 215 | + var thought, text strings.Builder | |
| 216 | + ctx := WithReasoning(context.Background(), func(s string) { thought.WriteString(s) }) | |
| 217 | + res, err := readResponsesStream(ctx, strings.NewReader(body.String()), func(_ context.Context, c *ai.ModelResponseChunk) error { | |
| 218 | + text.WriteString(c.Text()) | |
| 219 | + return nil | |
| 220 | + }) | |
| 221 | + if err != nil { | |
| 222 | + t.Fatal(err) | |
| 223 | + } | |
| 224 | + if thought.String() != "Think hard." || text.String() != "ok" || res.Status != "completed" { | |
| 225 | + t.Errorf("thought %q, text %q, status %q", thought.String(), text.String(), res.Status) | |
| 226 | + } | |
| 227 | +} | |
| 228 | + | |
| 229 | +// The summary of a compaction: not streamed, no tools, reasoning off, the | |
| 230 | +// limit under the Responses name. | |
| 231 | +func TestResponsesSummary(t *testing.T) { | |
| 232 | + f := &fakeResponses{scripts: [][]map[string]any{{ | |
| 233 | + completed([]map[string]any{{"type": "message", "content": []any{map[string]any{"type": "output_text", "text": "## Goal\nnotes"}}}}, nil), | |
| 234 | + }}} | |
| 235 | + srv := f.serve(t) | |
| 236 | + e := responsesEngine(t, srv, map[string]any{"max_completion_tokens": 4096, "reasoning_effort": "high"}) | |
| 237 | + text, err := e.Summarize(context.Background(), []*ai.Message{ai.NewSystemTextMessage("note-taker"), ai.NewUserTextMessage("summarise")}, 300) | |
| 238 | + if err != nil { | |
| 239 | + t.Fatalf("Summarize: %v", err) | |
| 240 | + } | |
| 241 | + if text != "## Goal\nnotes" { | |
| 242 | + t.Errorf("summary = %q", text) | |
| 243 | + } | |
| 244 | + body := f.bodies[0] | |
| 245 | + if r, _ := body["reasoning"].(map[string]any); r["effort"] != "none" { | |
| 246 | + t.Errorf("summary reasoning = %v, want effort none", body["reasoning"]) | |
| 247 | + } | |
| 248 | + if body["max_output_tokens"] != float64(300) || body["tools"] != nil { | |
| 249 | + t.Errorf("summary: max_output_tokens %v, tools %v", body["max_output_tokens"], body["tools"]) | |
| 250 | + } | |
| 251 | +} | |
| 252 | + | |
| 253 | +// What can go wrong: a refused key (Explain names the variable), an error | |
| 254 | +// event (a broken stream, retried once by the model call), tool arguments | |
| 255 | +// cut off (handed back to the model like on Chat Completions), an answer cut | |
| 256 | +// by the limit. | |
| 257 | +func TestResponsesFailures(t *testing.T) { | |
| 258 | + t.Run("refused key", func(t *testing.T) { | |
| 259 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { | |
| 260 | + http.Error(w, `{"error":{"message":"Incorrect API key"}}`, http.StatusUnauthorized) | |
| 261 | + })) | |
| 262 | + t.Cleanup(srv.Close) | |
| 263 | + e := responsesEngine(t, srv, nil) | |
| 264 | + e.Backend.APIKeyEnv = "OPENAI_API_KEY" | |
| 265 | + _, _, err := e.Generate(context.Background(), []*ai.Message{ai.NewUserTextMessage("hi")}, nil) | |
| 266 | + if err == nil || !strings.Contains(e.Explain(err), "is $OPENAI_API_KEY set and valid?") { | |
| 267 | + t.Errorf("err = %v, explained %q", err, e.Explain(err)) | |
| 268 | + } | |
| 269 | + }) | |
| 270 | + t.Run("error event", func(t *testing.T) { | |
| 271 | + stream := "data: {\"type\":\"error\",\"message\":\"overloaded\"}\n\n" | |
| 272 | + _, err := readResponsesStream(context.Background(), strings.NewReader(stream), nil) | |
| 273 | + if !streamBroken(err) || !strings.Contains(err.Error(), "overloaded") { | |
| 274 | + t.Errorf("err = %v, want a broken stream with the server's words", err) | |
| 275 | + } | |
| 276 | + }) | |
| 277 | + t.Run("stream cut", func(t *testing.T) { | |
| 278 | + _, err := readResponsesStream(context.Background(), strings.NewReader("data: {\"type\":\"response.output_text.delta\",\"delta\":\"a\"}\n\n"), nil) | |
| 279 | + if !streamBroken(err) { | |
| 280 | + t.Errorf("err = %v, want a broken stream", err) | |
| 281 | + } | |
| 282 | + }) | |
| 283 | + t.Run("arguments cut off", func(t *testing.T) { | |
| 284 | + r := &responsesResult{Status: "incomplete", Output: []json.RawMessage{json.RawMessage(`{"type":"function_call","call_id":"c","name":"bash","arguments":"{\"command\":\"ec"}`)}} | |
| 285 | + _, err := r.modelResponse() | |
| 286 | + if truncated, _ := argsError(err); !truncated { | |
| 287 | + t.Errorf("err = %v, want truncated tool arguments", err) | |
| 288 | + } | |
| 289 | + }) | |
| 290 | + t.Run("answer cut by the limit", func(t *testing.T) { | |
| 291 | + var r responsesResult | |
| 292 | + _ = json.Unmarshal([]byte(`{"status":"incomplete","incomplete_details":{"reason":"max_output_tokens"},"output":[{"type":"message","content":[{"type":"output_text","text":"half"}]}]}`), &r) | |
| 293 | + resp, err := r.modelResponse() | |
| 294 | + if err != nil || resp.FinishReason != ai.FinishReasonLength || resp.Text() != "half" { | |
| 295 | + t.Errorf("resp = %+v, err = %v", resp, err) | |
| 296 | + } | |
| 297 | + }) | |
| 298 | + t.Run("failed", func(t *testing.T) { | |
| 299 | + r := &responsesResult{Status: "failed"} | |
| 300 | + if _, err := r.modelResponse(); !streamBroken(err) { | |
| 301 | + t.Errorf("err = %v", err) | |
| 302 | + } | |
| 303 | + }) | |
| 304 | +} | |
| 305 | + | |
| 306 | +// The sampling block goes as written, with the Chat Completions names this | |
| 307 | +// API spells differently renamed; `store` and `include` written in the file | |
| 308 | +// win; structuredOutput becomes text.format. | |
| 309 | +func TestResponsesRequestFields(t *testing.T) { | |
| 310 | + req := &ai.ModelRequest{ | |
| 311 | + Config: map[string]any{"temperature": 1.0, "max_tokens": 100, "reasoning": map[string]any{"summary": "auto"}, "reasoning_effort": "low", "store": true}, | |
| 312 | + Messages: []*ai.Message{ai.NewUserTextMessage("hi")}, | |
| 313 | + Output: &ai.ModelOutputConfig{Format: "json", Schema: map[string]any{"type": "object"}, Constrained: true}, | |
| 314 | + } | |
| 315 | + raw, err := responsesRequest("m", req, false, false) | |
| 316 | + if err != nil { | |
| 317 | + t.Fatal(err) | |
| 318 | + } | |
| 319 | + var body map[string]any | |
| 320 | + _ = json.Unmarshal(raw, &body) | |
| 321 | + if body["temperature"] != 1.0 || body["max_output_tokens"] != float64(100) || body["max_tokens"] != nil { | |
| 322 | + t.Errorf("sampling: %v", body) | |
| 323 | + } | |
| 324 | + r, _ := body["reasoning"].(map[string]any) | |
| 325 | + if r["summary"] != "auto" || r["effort"] != "low" { | |
| 326 | + t.Errorf("reasoning = %v, want summary kept and effort added", r) | |
| 327 | + } | |
| 328 | + if body["store"] != true || body["include"] != nil { | |
| 329 | + t.Errorf("store %v include %v: the file's store wins, no include then", body["store"], body["include"]) | |
| 330 | + } | |
| 331 | + format, _ := body["text"].(map[string]any)["format"].(map[string]any) | |
| 332 | + if format["type"] != "json_schema" || format["name"] != "output" { | |
| 333 | + t.Errorf("text.format = %v", format) | |
| 334 | + } | |
| 335 | + if req.Config.(map[string]any)["max_tokens"] != 100 { | |
| 336 | + t.Error("the request's config map was changed in place") | |
| 337 | + } | |
| 338 | +} | |
| 339 | + | |
| 340 | +// The provider is registered, with OpenAI's address and key, and a model | |
| 341 | +// that declares tools. | |
| 342 | +func TestResponsesProviderEntry(t *testing.T) { | |
| 343 | + base, fallback, ok := DefaultURLs("openai-responses") | |
| 344 | + if !ok || base != "https://api.openai.com/v1" || fallback != "" { | |
| 345 | + t.Errorf("DefaultURLs = %q, %q, %v", base, fallback, ok) | |
| 346 | + } | |
| 347 | + p, _ := registry["openai-responses"].(*openaiCompat) | |
| 348 | + if p == nil || !p.responses || p.apiKeyEnv != "OPENAI_API_KEY" { | |
| 349 | + t.Errorf("entry = %+v", p) | |
| 350 | + } | |
| 351 | + if o, _ := registry["openai"].(*openaiCompat); o == nil || o.responses { | |
| 352 | + t.Error("the openai provider must keep Chat Completions") | |
| 353 | + } | |
| 354 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,354 @@ | |||
| 1 | +package engine | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "context" | ||
| 5 | + "encoding/json" | ||
| 6 | + "fmt" | ||
| 7 | + "io" | ||
| 8 | + "net/http" | ||
| 9 | + "net/http/httptest" | ||
| 10 | + "strings" | ||
| 11 | + "sync" | ||
| 12 | + "testing" | ||
| 13 | + | ||
| 14 | + "mm/internal/config" | ||
| 15 | + | ||
| 16 | + "github.com/firebase/genkit/go/ai" | ||
| 17 | + "github.com/firebase/genkit/go/genkit" | ||
| 18 | +) | ||
| 19 | + | ||
| 20 | +// fakeResponses is a /v1/responses server: each POST is answered by the next | ||
| 21 | +// script — SSE events when the request streams, the last event's response as | ||
| 22 | +// JSON otherwise — and its body is kept for the test to read. | ||
| 23 | +type fakeResponses struct { | ||
| 24 | + mu sync.Mutex | ||
| 25 | + scripts [][]map[string]any | ||
| 26 | + bodies []map[string]any | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +func (f *fakeResponses) serve(t *testing.T) *httptest.Server { | ||
| 30 | + t.Helper() | ||
| 31 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| 32 | + if r.Method != http.MethodPost || r.URL.Path != "/v1/responses" { | ||
| 33 | + http.NotFound(w, r) | ||
| 34 | + return | ||
| 35 | + } | ||
| 36 | + raw, _ := io.ReadAll(r.Body) | ||
| 37 | + var body map[string]any | ||
| 38 | + if err := json.Unmarshal(raw, &body); err != nil { | ||
| 39 | + t.Errorf("request body is not JSON: %s", raw) | ||
| 40 | + } | ||
| 41 | + f.mu.Lock() | ||
| 42 | + n := len(f.bodies) | ||
| 43 | + f.bodies = append(f.bodies, body) | ||
| 44 | + f.mu.Unlock() | ||
| 45 | + if n >= len(f.scripts) { | ||
| 46 | + t.Errorf("call %d: no script left", n+1) | ||
| 47 | + http.Error(w, "no script", http.StatusInternalServerError) | ||
| 48 | + return | ||
| 49 | + } | ||
| 50 | + events := f.scripts[n] | ||
| 51 | + if body["stream"] != true { | ||
| 52 | + w.Header().Set("Content-Type", "application/json") | ||
| 53 | + _ = json.NewEncoder(w).Encode(events[len(events)-1]["response"]) | ||
| 54 | + return | ||
| 55 | + } | ||
| 56 | + w.Header().Set("Content-Type", "text/event-stream") | ||
| 57 | + for _, ev := range events { | ||
| 58 | + data, _ := json.Marshal(ev) | ||
| 59 | + _, _ = fmt.Fprintf(w, "event: %s\ndata: %s\n\n", ev["type"], data) | ||
| 60 | + } | ||
| 61 | + })) | ||
| 62 | + t.Cleanup(srv.Close) | ||
| 63 | + return srv | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +// responsesEngine opens the openai-responses provider against srv, with a | ||
| 67 | +// `bash` tool, the way New does. | ||
| 68 | +func responsesEngine(t *testing.T, srv *httptest.Server, sampling map[string]any) *Engine { | ||
| 69 | + t.Helper() | ||
| 70 | + saved := config.Cfg | ||
| 71 | + t.Cleanup(func() { config.Cfg = saved }) | ||
| 72 | + config.Cfg.Provider, config.Cfg.Model, config.Cfg.BaseURL = "openai-responses", "gpt-test", srv.URL+"/v1" | ||
| 73 | + config.Cfg.Sampling = sampling | ||
| 74 | + config.Cfg.ShowThinking = false | ||
| 75 | + config.Cfg.Trace.Enabled = false | ||
| 76 | + config.Cfg.OutputSchema = nil | ||
| 77 | + p, err := Lookup("openai-responses") | ||
| 78 | + if err != nil { | ||
| 79 | + t.Fatal(err) | ||
| 80 | + } | ||
| 81 | + b, err := p.Resolve(config.Cfg) | ||
| 82 | + if err != nil { | ||
| 83 | + t.Fatal(err) | ||
| 84 | + } | ||
| 85 | + g, model, err := p.Open(context.Background(), b) | ||
| 86 | + if err != nil { | ||
| 87 | + t.Fatal(err) | ||
| 88 | + } | ||
| 89 | + genkit.DefineTool(g, "bash", "run a shell command", | ||
| 90 | + func(_ *ai.ToolContext, in struct { | ||
| 91 | + Command string `json:"command"` | ||
| 92 | + }) (string, error) { | ||
| 93 | + return "hello from " + in.Command, nil | ||
| 94 | + }) | ||
| 95 | + return &Engine{G: g, Model: model, Provider: p, Backend: b} | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +func completed(output []map[string]any, usage map[string]any) map[string]any { | ||
| 99 | + return map[string]any{"type": "response.completed", "response": map[string]any{"status": "completed", "output": output, "usage": usage}} | ||
| 100 | +} | ||
| 101 | + | ||
| 102 | +// A tool turn over the Responses API: the call streams, the tool runs, its | ||
| 103 | +// output goes back as function_call_output with the same call_id, the | ||
| 104 | +// encrypted reasoning goes back before the call, and the answer and the | ||
| 105 | +// usage come through. | ||
| 106 | +func TestResponsesToolTurn(t *testing.T) { | ||
| 107 | + reasoning := map[string]any{"type": "reasoning", "id": "rs_1", "summary": []any{}, "encrypted_content": "SECRET"} | ||
| 108 | + call := map[string]any{"type": "function_call", "id": "fc_1", "call_id": "call_1", "name": "bash", "arguments": `{"command":"ls"}`} | ||
| 109 | + f := &fakeResponses{scripts: [][]map[string]any{ | ||
| 110 | + { | ||
| 111 | + {"type": "response.created"}, | ||
| 112 | + {"type": "response.reasoning_summary_text.delta", "delta": "Listing first."}, | ||
| 113 | + {"type": "response.output_item.added", "item": map[string]any{"type": "function_call", "id": "fc_1", "call_id": "call_1", "name": "bash"}}, | ||
| 114 | + {"type": "response.function_call_arguments.delta", "item_id": "fc_1", "delta": `{"command":`}, | ||
| 115 | + {"type": "response.function_call_arguments.delta", "item_id": "fc_1", "delta": `"ls"}`}, | ||
| 116 | + completed([]map[string]any{reasoning, call}, map[string]any{"input_tokens": 120, "output_tokens": 30, "total_tokens": 150, "output_tokens_details": map[string]any{"reasoning_tokens": 20}}), | ||
| 117 | + }, | ||
| 118 | + { | ||
| 119 | + {"type": "response.output_text.delta", "delta": "There is "}, | ||
| 120 | + {"type": "response.output_text.delta", "delta": "one file."}, | ||
| 121 | + completed([]map[string]any{{"type": "message", "role": "assistant", "content": []any{map[string]any{"type": "output_text", "text": "There is one file."}}}}, | ||
| 122 | + map[string]any{"input_tokens": 200, "output_tokens": 5, "total_tokens": 205, "input_tokens_details": map[string]any{"cached_tokens": 100}}), | ||
| 123 | + }, | ||
| 124 | + }} | ||
| 125 | + srv := f.serve(t) | ||
| 126 | + e := responsesEngine(t, srv, map[string]any{"max_completion_tokens": 512, "reasoning_effort": "high"}) | ||
| 127 | + | ||
| 128 | + resp, full, err := e.Generate(context.Background(), | ||
| 129 | + []*ai.Message{ai.NewSystemTextMessage("be brief"), ai.NewUserTextMessage("list the files")}, | ||
| 130 | + []ai.ToolRef{ai.ToolName("bash")}) | ||
| 131 | + if err != nil { | ||
| 132 | + t.Fatalf("Generate: %v", err) | ||
| 133 | + } | ||
| 134 | + if resp.Text() != "There is one file." { | ||
| 135 | + t.Errorf("answer = %q", resp.Text()) | ||
| 136 | + } | ||
| 137 | + if len(full) < 4 { | ||
| 138 | + t.Fatalf("full conversation has %d messages, want system, user, the call, its result", len(full)) | ||
| 139 | + } | ||
| 140 | + if e.LastInputTokens() != 200 { | ||
| 141 | + t.Errorf("LastInputTokens = %d, want the server's 200", e.LastInputTokens()) | ||
| 142 | + } | ||
| 143 | + if resp.Usage == nil || resp.Usage.CachedContentTokens != 100 { | ||
| 144 | + t.Errorf("usage = %+v, want the cached tokens", resp.Usage) | ||
| 145 | + } | ||
| 146 | + | ||
| 147 | + if len(f.bodies) != 2 { | ||
| 148 | + t.Fatalf("%d calls, want 2", len(f.bodies)) | ||
| 149 | + } | ||
| 150 | + first := f.bodies[0] | ||
| 151 | + if first["stream"] != true || first["store"] != false || first["model"] != "gpt-test" { | ||
| 152 | + t.Errorf("first request: stream %v store %v model %v", first["stream"], first["store"], first["model"]) | ||
| 153 | + } | ||
| 154 | + if inc, _ := first["include"].([]any); len(inc) != 1 || inc[0] != "reasoning.encrypted_content" { | ||
| 155 | + t.Errorf("include = %v", first["include"]) | ||
| 156 | + } | ||
| 157 | + if first["max_output_tokens"] != float64(512) || first["max_completion_tokens"] != nil || first["max_tokens"] != nil { | ||
| 158 | + t.Errorf("limit: max_output_tokens %v, max_completion_tokens %v, max_tokens %v", first["max_output_tokens"], first["max_completion_tokens"], first["max_tokens"]) | ||
| 159 | + } | ||
| 160 | + if r, _ := first["reasoning"].(map[string]any); r["effort"] != "high" || first["reasoning_effort"] != nil { | ||
| 161 | + t.Errorf("reasoning = %v, reasoning_effort = %v", first["reasoning"], first["reasoning_effort"]) | ||
| 162 | + } | ||
| 163 | + tools, _ := first["tools"].([]any) | ||
| 164 | + if len(tools) != 1 || tools[0].(map[string]any)["type"] != "function" || tools[0].(map[string]any)["name"] != "bash" { | ||
| 165 | + t.Errorf("tools = %v", tools) | ||
| 166 | + } | ||
| 167 | + input, _ := first["input"].([]any) | ||
| 168 | + if len(input) != 2 || input[0].(map[string]any)["role"] != "system" || input[1].(map[string]any)["role"] != "user" { | ||
| 169 | + t.Errorf("first input = %v", input) | ||
| 170 | + } | ||
| 171 | + | ||
| 172 | + second, _ := f.bodies[1]["input"].([]any) | ||
| 173 | + var kinds []string | ||
| 174 | + for _, it := range second { | ||
| 175 | + m := it.(map[string]any) | ||
| 176 | + kind, _ := m["type"].(string) | ||
| 177 | + if kind == "" { | ||
| 178 | + kind, _ = m["role"].(string) | ||
| 179 | + } | ||
| 180 | + kinds = append(kinds, kind) | ||
| 181 | + switch kind { | ||
| 182 | + case "reasoning": | ||
| 183 | + if m["encrypted_content"] != "SECRET" { | ||
| 184 | + t.Errorf("reasoning item sent back without its encrypted content: %v", m) | ||
| 185 | + } | ||
| 186 | + case "function_call": | ||
| 187 | + if m["call_id"] != "call_1" || m["name"] != "bash" || m["arguments"] != `{"command":"ls"}` { | ||
| 188 | + t.Errorf("function_call = %v", m) | ||
| 189 | + } | ||
| 190 | + case "function_call_output": | ||
| 191 | + if m["call_id"] != "call_1" || !strings.Contains(fmt.Sprint(m["output"]), "hello from ls") { | ||
| 192 | + t.Errorf("function_call_output = %v", m) | ||
| 193 | + } | ||
| 194 | + } | ||
| 195 | + } | ||
| 196 | + if got := strings.Join(kinds, " "); got != "system user reasoning function_call function_call_output" { | ||
| 197 | + t.Errorf("second input = %s", got) | ||
| 198 | + } | ||
| 199 | +} | ||
| 200 | + | ||
| 201 | +// The reasoning summary streamed reaches the turn's listener (thoughts on | ||
| 202 | +// screen, and the watchdog's heartbeat). | ||
| 203 | +func TestResponsesReasoningReachesTheListener(t *testing.T) { | ||
| 204 | + events := []map[string]any{ | ||
| 205 | + {"type": "response.reasoning_summary_text.delta", "delta": "Think "}, | ||
| 206 | + {"type": "response.reasoning_text.delta", "delta": "hard."}, | ||
| 207 | + {"type": "response.output_text.delta", "delta": "ok"}, | ||
| 208 | + completed([]map[string]any{{"type": "message", "content": []any{map[string]any{"type": "output_text", "text": "ok"}}}}, nil), | ||
| 209 | + } | ||
| 210 | + body := strings.Builder{} | ||
| 211 | + for _, ev := range events { | ||
| 212 | + data, _ := json.Marshal(ev) | ||
| 213 | + fmt.Fprintf(&body, "data: %s\n\n", data) | ||
| 214 | + } | ||
| 215 | + var thought, text strings.Builder | ||
| 216 | + ctx := WithReasoning(context.Background(), func(s string) { thought.WriteString(s) }) | ||
| 217 | + res, err := readResponsesStream(ctx, strings.NewReader(body.String()), func(_ context.Context, c *ai.ModelResponseChunk) error { | ||
| 218 | + text.WriteString(c.Text()) | ||
| 219 | + return nil | ||
| 220 | + }) | ||
| 221 | + if err != nil { | ||
| 222 | + t.Fatal(err) | ||
| 223 | + } | ||
| 224 | + if thought.String() != "Think hard." || text.String() != "ok" || res.Status != "completed" { | ||
| 225 | + t.Errorf("thought %q, text %q, status %q", thought.String(), text.String(), res.Status) | ||
| 226 | + } | ||
| 227 | +} | ||
| 228 | + | ||
| 229 | +// The summary of a compaction: not streamed, no tools, reasoning off, the | ||
| 230 | +// limit under the Responses name. | ||
| 231 | +func TestResponsesSummary(t *testing.T) { | ||
| 232 | + f := &fakeResponses{scripts: [][]map[string]any{{ | ||
| 233 | + completed([]map[string]any{{"type": "message", "content": []any{map[string]any{"type": "output_text", "text": "## Goal\nnotes"}}}}, nil), | ||
| 234 | + }}} | ||
| 235 | + srv := f.serve(t) | ||
| 236 | + e := responsesEngine(t, srv, map[string]any{"max_completion_tokens": 4096, "reasoning_effort": "high"}) | ||
| 237 | + text, err := e.Summarize(context.Background(), []*ai.Message{ai.NewSystemTextMessage("note-taker"), ai.NewUserTextMessage("summarise")}, 300) | ||
| 238 | + if err != nil { | ||
| 239 | + t.Fatalf("Summarize: %v", err) | ||
| 240 | + } | ||
| 241 | + if text != "## Goal\nnotes" { | ||
| 242 | + t.Errorf("summary = %q", text) | ||
| 243 | + } | ||
| 244 | + body := f.bodies[0] | ||
| 245 | + if r, _ := body["reasoning"].(map[string]any); r["effort"] != "none" { | ||
| 246 | + t.Errorf("summary reasoning = %v, want effort none", body["reasoning"]) | ||
| 247 | + } | ||
| 248 | + if body["max_output_tokens"] != float64(300) || body["tools"] != nil { | ||
| 249 | + t.Errorf("summary: max_output_tokens %v, tools %v", body["max_output_tokens"], body["tools"]) | ||
| 250 | + } | ||
| 251 | +} | ||
| 252 | + | ||
| 253 | +// What can go wrong: a refused key (Explain names the variable), an error | ||
| 254 | +// event (a broken stream, retried once by the model call), tool arguments | ||
| 255 | +// cut off (handed back to the model like on Chat Completions), an answer cut | ||
| 256 | +// by the limit. | ||
| 257 | +func TestResponsesFailures(t *testing.T) { | ||
| 258 | + t.Run("refused key", func(t *testing.T) { | ||
| 259 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { | ||
| 260 | + http.Error(w, `{"error":{"message":"Incorrect API key"}}`, http.StatusUnauthorized) | ||
| 261 | + })) | ||
| 262 | + t.Cleanup(srv.Close) | ||
| 263 | + e := responsesEngine(t, srv, nil) | ||
| 264 | + e.Backend.APIKeyEnv = "OPENAI_API_KEY" | ||
| 265 | + _, _, err := e.Generate(context.Background(), []*ai.Message{ai.NewUserTextMessage("hi")}, nil) | ||
| 266 | + if err == nil || !strings.Contains(e.Explain(err), "is $OPENAI_API_KEY set and valid?") { | ||
| 267 | + t.Errorf("err = %v, explained %q", err, e.Explain(err)) | ||
| 268 | + } | ||
| 269 | + }) | ||
| 270 | + t.Run("error event", func(t *testing.T) { | ||
| 271 | + stream := "data: {\"type\":\"error\",\"message\":\"overloaded\"}\n\n" | ||
| 272 | + _, err := readResponsesStream(context.Background(), strings.NewReader(stream), nil) | ||
| 273 | + if !streamBroken(err) || !strings.Contains(err.Error(), "overloaded") { | ||
| 274 | + t.Errorf("err = %v, want a broken stream with the server's words", err) | ||
| 275 | + } | ||
| 276 | + }) | ||
| 277 | + t.Run("stream cut", func(t *testing.T) { | ||
| 278 | + _, err := readResponsesStream(context.Background(), strings.NewReader("data: {\"type\":\"response.output_text.delta\",\"delta\":\"a\"}\n\n"), nil) | ||
| 279 | + if !streamBroken(err) { | ||
| 280 | + t.Errorf("err = %v, want a broken stream", err) | ||
| 281 | + } | ||
| 282 | + }) | ||
| 283 | + t.Run("arguments cut off", func(t *testing.T) { | ||
| 284 | + r := &responsesResult{Status: "incomplete", Output: []json.RawMessage{json.RawMessage(`{"type":"function_call","call_id":"c","name":"bash","arguments":"{\"command\":\"ec"}`)}} | ||
| 285 | + _, err := r.modelResponse() | ||
| 286 | + if truncated, _ := argsError(err); !truncated { | ||
| 287 | + t.Errorf("err = %v, want truncated tool arguments", err) | ||
| 288 | + } | ||
| 289 | + }) | ||
| 290 | + t.Run("answer cut by the limit", func(t *testing.T) { | ||
| 291 | + var r responsesResult | ||
| 292 | + _ = json.Unmarshal([]byte(`{"status":"incomplete","incomplete_details":{"reason":"max_output_tokens"},"output":[{"type":"message","content":[{"type":"output_text","text":"half"}]}]}`), &r) | ||
| 293 | + resp, err := r.modelResponse() | ||
| 294 | + if err != nil || resp.FinishReason != ai.FinishReasonLength || resp.Text() != "half" { | ||
| 295 | + t.Errorf("resp = %+v, err = %v", resp, err) | ||
| 296 | + } | ||
| 297 | + }) | ||
| 298 | + t.Run("failed", func(t *testing.T) { | ||
| 299 | + r := &responsesResult{Status: "failed"} | ||
| 300 | + if _, err := r.modelResponse(); !streamBroken(err) { | ||
| 301 | + t.Errorf("err = %v", err) | ||
| 302 | + } | ||
| 303 | + }) | ||
| 304 | +} | ||
| 305 | + | ||
| 306 | +// The sampling block goes as written, with the Chat Completions names this | ||
| 307 | +// API spells differently renamed; `store` and `include` written in the file | ||
| 308 | +// win; structuredOutput becomes text.format. | ||
| 309 | +func TestResponsesRequestFields(t *testing.T) { | ||
| 310 | + req := &ai.ModelRequest{ | ||
| 311 | + Config: map[string]any{"temperature": 1.0, "max_tokens": 100, "reasoning": map[string]any{"summary": "auto"}, "reasoning_effort": "low", "store": true}, | ||
| 312 | + Messages: []*ai.Message{ai.NewUserTextMessage("hi")}, | ||
| 313 | + Output: &ai.ModelOutputConfig{Format: "json", Schema: map[string]any{"type": "object"}, Constrained: true}, | ||
| 314 | + } | ||
| 315 | + raw, err := responsesRequest("m", req, false, false) | ||
| 316 | + if err != nil { | ||
| 317 | + t.Fatal(err) | ||
| 318 | + } | ||
| 319 | + var body map[string]any | ||
| 320 | + _ = json.Unmarshal(raw, &body) | ||
| 321 | + if body["temperature"] != 1.0 || body["max_output_tokens"] != float64(100) || body["max_tokens"] != nil { | ||
| 322 | + t.Errorf("sampling: %v", body) | ||
| 323 | + } | ||
| 324 | + r, _ := body["reasoning"].(map[string]any) | ||
| 325 | + if r["summary"] != "auto" || r["effort"] != "low" { | ||
| 326 | + t.Errorf("reasoning = %v, want summary kept and effort added", r) | ||
| 327 | + } | ||
| 328 | + if body["store"] != true || body["include"] != nil { | ||
| 329 | + t.Errorf("store %v include %v: the file's store wins, no include then", body["store"], body["include"]) | ||
| 330 | + } | ||
| 331 | + format, _ := body["text"].(map[string]any)["format"].(map[string]any) | ||
| 332 | + if format["type"] != "json_schema" || format["name"] != "output" { | ||
| 333 | + t.Errorf("text.format = %v", format) | ||
| 334 | + } | ||
| 335 | + if req.Config.(map[string]any)["max_tokens"] != 100 { | ||
| 336 | + t.Error("the request's config map was changed in place") | ||
| 337 | + } | ||
| 338 | +} | ||
| 339 | + | ||
| 340 | +// The provider is registered, with OpenAI's address and key, and a model | ||
| 341 | +// that declares tools. | ||
| 342 | +func TestResponsesProviderEntry(t *testing.T) { | ||
| 343 | + base, fallback, ok := DefaultURLs("openai-responses") | ||
| 344 | + if !ok || base != "https://api.openai.com/v1" || fallback != "" { | ||
| 345 | + t.Errorf("DefaultURLs = %q, %q, %v", base, fallback, ok) | ||
| 346 | + } | ||
| 347 | + p, _ := registry["openai-responses"].(*openaiCompat) | ||
| 348 | + if p == nil || !p.responses || p.apiKeyEnv != "OPENAI_API_KEY" { | ||
| 349 | + t.Errorf("entry = %+v", p) | ||
| 350 | + } | ||
| 351 | + if o, _ := registry["openai"].(*openaiCompat); o == nil || o.responses { | ||
| 352 | + t.Error("the openai provider must keep Chat Completions") | ||
| 353 | + } | ||
| 354 | +} | ||