Skip to content

Commit f592289

Browse files
authored
fix: correct Ollama batches, AG-UI IDs, and Bedrock SDK setup (#553)
## Problem The current Ollama SDK could not read `/api/embed` responses, and recorded batches collapsed to one vector. Recordings also flattened different input shapes and reused responses across dimensions and embedding operations. AG-UI convenience helpers replaced caller IDs. Bedrock examples omitted the HTTP/1 handler required by current AWS SDK versions. ## Why SDK clients need the right response shape and request identity. A saved batch must not answer a different width or operation. Concurrent AG-UI requests need their own IDs, and Bedrock clients need the transport aimock supports. ## Fix - Return Ollama's ordered `embeddings` matrix, preserve distinct vectors and metadata through record/replay, and honor fallback dimensions. New Ollama and OpenAI-compatible recordings persist `match.embeddingRequest` with the operation, original input and requested dimensions, plus the model. Keep fixture sequence counters separate for those criteria. Handwritten generic fixtures keep broad matching; re-record older captures to add the new match keys. - Build AG-UI text/tool/state/reasoning convenience events per request with caller thread/run/parent IDs and fresh content IDs. Explicit event fixtures keep their authored IDs. - Correct Bedrock setup docs and test Invoke, Converse, and both binary streams with `NodeHttpHandler`. **Default HTTP/2 remains unsupported.** Python’s `add_fixture(..., embeddingRequest=...)` routes the field under `match`, so width, input shape and operation constraints reach the server. Three public HTTP regressions cover both Ollama operations and OpenAI; the full Python suite passes 251 tests on Python 3.13.9 with Node 24. Matching metadata stays private: predicates and request journals retain their old request shape. The A7 test checks the exact new saved fields, then compares all prior fields with its unchanged frozen baseline. CLI test helpers await child processes so slow commands leave the Vitest worker free to report results. The controlled 104-test suite reproduces the reporting timeout before this change and passes under the identical slowdown afterward. That suite keeps its assertions, test count, child limits and test deadlines. Two validate CLI checks now distinguish a success status from `OK` inside a file path; filenames containing `OK` make that regression deterministic. Validation on Node 24.21.0: 17,483 tests passed across 430 files, with 11 existing skips. Format, lint, typecheck, build, package exports and workflow lint passed. All 14 generated API reports match the new optional fixture field; `public-api-addition` marks that change for review. The unchanged memory guard passed after freeing RAM. The added regressions cover successive batch/string/width/model requests, reverse cache hits, offline reload, both legacy/OpenAI recording orders, changed widths after another operation's recording, strict misses and independent fixture sequences. Focused suites passed 776 tests. Independent Node 24.11.0 and Bun 1.4.3 consumers each passed 235 expanded checks and nine review-specific checks, plus 12 transform/privacy checks. These use local fixtures, not fresh authenticated all-provider calls; counts overlap. Native stack #552: #542 → #551 → #553. Header enforcement stays opt-in. Merge after required checks pass, in stack order.
2 parents 12a4315 + ef2e102 commit f592289

42 files changed

Lines changed: 1087 additions & 75 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎CHANGELOG.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
### Added
66

7+
- Recorded Ollama and OpenAI embedding fixtures include optional `match.embeddingRequest` criteria for the operation, input shape and requested dimensions. Handwritten embedding fixtures without this field keep their broad matching behavior.
8+
79
- An independent, opt-in required-header policy accepts programmatic options, `llm.policy`, repeatable `--policy` flags on both CLIs, and `X-AIMock-Policy` request headers. Defaults remain off, including strict-only requests. Enforced Anthropic version rejection returns 400 with a safe correlated `request_id`. The recorder strips the policy header before HTTP forwarding. ([#542](https://github.com/CopilotKit/aimock/pull/542))
810

911
- Anthropic Messages and Bedrock Claude invoke responses preserve fixture cache usage, including the cache TTL breakdown. Record mode retains token counts and cache usage for replay.
@@ -18,6 +20,11 @@
1820

1921
### Fixed
2022

23+
- Bedrock SDK examples configure `NodeHttpHandler` for aimock's HTTP/1 server; the current SDK's default HTTP/2 transport remains unsupported.
24+
25+
- Ollama `/api/embed` returns an `embeddings` matrix with one vector per input, honors fallback dimensions, and retains batch vectors and metadata through recording/replay. Recorded matches preserve input shape, dimensions, model and operation, so different requests do not reuse the wrong batch or match legacy/OpenAI embedding routes. `/api/embeddings` keeps its legacy single-vector response.
26+
- AG-UI convenience helpers use each request's thread/run IDs and create fresh message/tool-call IDs. Explicit event fixtures retain their authored IDs.
27+
2128
- Anthropic model lists reject unknown `after_id` and `before_id` cursors with 400 `invalid_request_error`, including when a lifecycle filter would return an empty page. Valid cursors and OpenAI-style lists keep their existing paging behavior.
2229
- Shared `/v1/models` paths select the Anthropic catalog when `anthropic-version` is present, or when `x-api-key` is present without `Authorization`. Non-Anthropic clients that use `x-api-key` alone also receive that catalog. Use `Authorization` without `anthropic-version` to retain the OpenAI format.
2330
- Configured inbound authentication returns native 401 bodies on Anthropic Messages/count and Gemini/Vertex Google HTTP paths. Anthropic adds a `request-id` response header. Shared model paths and WebSocket rejections retain their existing bodies. Anthropic's upstream diagnostic message and body `request_id` differ. The observed Gemini gateway 403 differs from aimock's intentional inbound 401.

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,9 @@ Run them all on one port with `npx @copilotkit/aimock --config aimock.json`, or
7373
- **Timing-aware recording and replay** — Recorded fixtures capture per-frame arrival timestamps; replay uses recorded timings for approximate timing reproduction based on recorded TTFT and inter-frame cadence (replay chunk count may differ from recording — TTFT and average pace are preserved, not per-token fidelity) with configurable `--replay-speed` multiplier
7474
- **[Recorded token usage and cost](https://aimock.copilotkit.dev/record-replay)** — Recording captures the final usage frame of a streaming completion, so replayed fixtures serve real `prompt_tokens` / `completion_tokens` instead of a length estimate; OpenRouter's provider-reported `usage.cost` and its `cost_details` / `*_tokens_details` breakdowns are captured too, so an app that bills from real provider cost can e2e-test its wallet path from a tape
7575
- **[Multi-turn Conversations](https://aimock.copilotkit.dev/multi-turn)** — Record and replay multi-turn traces with tool rounds; match distinct turns via `turnIndex`, `hasToolResult`, `toolCallId`, `toolResultContains` (gate on the tool-result payload), `sequenceIndex`, `systemMessage` (gate on host-supplied agent context), or custom predicates
76+
- **[Ollama embedding recordings](https://aimock.copilotkit.dev/ollama)** — Current `/api/embed` captures retain input shape, dimensions and model in their match and stay separate from legacy/OpenAI embedding operations.
7677
- **[11 providers across 22 API surfaces](https://aimock.copilotkit.dev/docs)** — OpenAI Chat, OpenAI Responses, OpenAI Realtime (GA; an `OpenAI-Beta: realtime=v1` request gets the real sunset rejection), GPT-Live, Claude, Gemini REST, Gemini embedContent, Gemini Live, Gemini Interactions, Azure, Bedrock, Vertex AI, Ollama (chat + embeddings), Cohere (chat + embed), OpenRouter (chat + router failover), BytePlus Ark (OpenAI-compatible chat + images under `/api/v3`), ElevenLabs TTS and Voice Design — full streaming support
78+
Bedrock with the current AWS JavaScript SDK needs `requestHandler: new NodeHttpHandler()` from `@smithy/node-http-handler` for aimock's HTTP/1 server. See [SDK setup](https://aimock.copilotkit.dev/aws-bedrock/#sdk-configuration).
7779
- **Multimedia APIs** — [image generation](https://aimock.copilotkit.dev/images) (`gpt-image-1` default, Imagen; `/v1/images/variations` replays OpenAI's removal 404), [image editing](https://aimock.copilotkit.dev/images) (/v1/images/edits), [text-to-speech](https://aimock.copilotkit.dev/speech) (OpenAI + ElevenLabs TTS and Voice Design), [audio transcription](https://aimock.copilotkit.dev/transcription), [audio translation](https://aimock.copilotkit.dev/transcription) (/v1/audio/translations), [video generation](https://aimock.copilotkit.dev/video), [OpenRouter video generation](https://aimock.copilotkit.dev/openrouter-video) (/api/v1/videos with async job lifecycle), [Google Veo video generation](https://aimock.copilotkit.dev/veo-video) (:predictLongRunning + /v1beta/operations async lifecycle), [Grok Imagine video generation](https://aimock.copilotkit.dev/grok-video) (/v1/videos/generations with async job lifecycle), [BytePlus Ark video generation](https://aimock.copilotkit.dev/byteplus-video) (Seedance, /api/v3/contents/generations/tasks with async task lifecycle), [fal.ai](https://aimock.copilotkit.dev/fal-ai) (image / video / audio with queue lifecycle)
7880
- **OpenAI platform APIs** — [Files](https://aimock.copilotkit.dev/files) (byte-exact uploads, purpose validation), [Vector Stores](https://aimock.copilotkit.dev/vector-stores) (CRUD, file attach with deterministic poll progression, file batches, deterministic direct search; hosted `file_search` execution is not supported), [fine-tuning jobs](https://aimock.copilotkit.dev/fine-tuning) (deterministic lifecycle, events, cursor pages) and Batches (`/v1/batches` create/list/retrieve/cancel with deterministic poll progression and real output files)
7981
- **[MCP](https://aimock.copilotkit.dev/mcp-mock) / [A2A](https://aimock.copilotkit.dev/a2a-mock) / [AG-UI](https://aimock.copilotkit.dev/agui-mock) / [Vector](https://aimock.copilotkit.dev/vector-mock)** — Mock every protocol your AI agents use

‎docs/agui-mock/index.html‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,15 @@ <h2>Registration API</h2>
123123
</tbody>
124124
</table>
125125

126+
<p>
127+
<code>onMessage</code>, <code>onToolCall</code>, <code>onStateKey</code>, and
128+
<code>onReasoning</code> build events for each request. Run events use the caller's
129+
<code>threadId</code>, <code>runId</code>, and optional <code>parentRunId</code>; message
130+
and tool-call IDs are fresh for each run. Explicit event arrays passed to
131+
<code>addFixture</code>, <code>onRun</code>, <code>onPredicate</code>, and
132+
<code>onToolResult</code> keep their authored IDs.
133+
</p>
134+
126135
<h2>Event Types</h2>
127136
<p>AG-UI protocol event categories:</p>
128137
<table class="endpoint-table">

‎docs/aws-bedrock/index.html‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,13 +175,23 @@ <h2>Model Resolution</h2>
175175
</div>
176176

177177
<h2>SDK Configuration</h2>
178-
<p>To point the AWS SDK Bedrock Runtime client at aimock, configure the endpoint URL:</p>
178+
<p>
179+
Configure the endpoint URL and use <code>NodeHttpHandler</code> from
180+
<code>@smithy/node-http-handler</code>. Install it as a direct dev dependency (<code
181+
>pnpm add -D @smithy/node-http-handler</code
182+
>). Current Bedrock SDK versions default to HTTP/2; aimock's local server uses HTTP/1.
183+
Without this handler, calls can fail with <code>ERR_HTTP2_ERROR</code>. The same handler
184+
supports InvokeModel, Converse, and both streaming APIs.
185+
</p>
179186

180187
<div class="code-block">
181188
<div class="code-block-header">bedrock-sdk.ts <span class="lang-tag">ts</span></div>
182189
<pre><code><span class="kw">import</span> { <span class="type">BedrockRuntimeClient</span>, <span class="type">InvokeModelCommand</span> } <span class="kw">from</span> <span class="str">"@aws-sdk/client-bedrock-runtime"</span>;
183190

191+
<span class="kw">import</span> { <span class="type">NodeHttpHandler</span> } <span class="kw">from</span> <span class="str">"@smithy/node-http-handler"</span>;
192+
184193
<span class="kw">const</span> <span class="op">client</span> = <span class="kw">new</span> <span class="type">BedrockRuntimeClient</span>({
194+
<span class="prop">requestHandler</span>: <span class="kw">new</span> <span class="type">NodeHttpHandler</span>(),
185195
<span class="prop">region</span>: <span class="str">"us-east-1"</span>,
186196
<span class="prop">endpoint</span>: <span class="str">"http://localhost:4005"</span>, <span class="cm">// aimock URL</span>
187197
<span class="prop">credentials</span>: { <span class="prop">accessKeyId</span>: <span class="str">"mock"</span>, <span class="prop">secretAccessKey</span>: <span class="str">"mock"</span> },
@@ -258,7 +268,10 @@ <h2>Streaming (invoke-with-response-stream)</h2>
258268
<div class="code-block-header">streaming SDK usage <span class="lang-tag">ts</span></div>
259269
<pre><code><span class="kw">import</span> { <span class="type">BedrockRuntimeClient</span>, <span class="type">InvokeModelWithResponseStreamCommand</span> } <span class="kw">from</span> <span class="str">"@aws-sdk/client-bedrock-runtime"</span>;
260270

271+
<span class="kw">import</span> { <span class="type">NodeHttpHandler</span> } <span class="kw">from</span> <span class="str">"@smithy/node-http-handler"</span>;
272+
261273
<span class="kw">const</span> <span class="op">client</span> = <span class="kw">new</span> <span class="type">BedrockRuntimeClient</span>({
274+
<span class="prop">requestHandler</span>: <span class="kw">new</span> <span class="type">NodeHttpHandler</span>(),
262275
<span class="prop">region</span>: <span class="str">"us-east-1"</span>,
263276
<span class="prop">endpoint</span>: <span class="str">"http://localhost:4005"</span>,
264277
<span class="prop">credentials</span>: { <span class="prop">accessKeyId</span>: <span class="str">"mock"</span>, <span class="prop">secretAccessKey</span>: <span class="str">"mock"</span> },

‎docs/fixtures/index.html‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,17 @@ <h2>Match Fields</h2>
128128
<td>string | RegExp</td>
129129
<td>Match on embedding input text</td>
130130
</tr>
131+
<tr>
132+
<td>embeddingRequest</td>
133+
<td>{ operation, input, dimensions? }</td>
134+
<td>
135+
Exact operation, input shape and requested dimensions for <code>/api/embed</code>,
136+
<code>/api/embeddings</code>, or <code>/v1/embeddings</code>. Recordings set this
137+
alongside <code>inputText</code> and <code>model</code> so batches and widths stay
138+
distinct and other embedding operations cannot match. Omit this field for broad
139+
embedding fixtures.
140+
</td>
141+
</tr>
131142
<tr>
132143
<td>toolCallId</td>
133144
<td>string</td>

‎docs/ollama/index.html‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,16 @@ <h2>Endpoints</h2>
7575
<td>/api/generate</td>
7676
<td>Single-prompt text generation (no tool calls)</td>
7777
</tr>
78+
<tr>
79+
<td>POST</td>
80+
<td>/api/embed</td>
81+
<td>Current embeddings API: input text or batch, embeddings matrix</td>
82+
</tr>
83+
<tr>
84+
<td>POST</td>
85+
<td>/api/embeddings</td>
86+
<td>Legacy embeddings API: prompt text, single embedding vector</td>
87+
</tr>
7888
<tr>
7989
<td>GET</td>
8090
<td>/api/tags</td>
@@ -83,6 +93,30 @@ <h2>Endpoints</h2>
8393
</tbody>
8494
</table>
8595

96+
<h2>Embeddings</h2>
97+
<p>
98+
Use the Ollama SDK's <code>embed({ model, input })</code> with a string or array of
99+
strings. <code>/api/embed</code> returns one vector per input in <code>embeddings</code>,
100+
in input order. Unmatched inputs get separate, deterministic vectors;
101+
<code>dimensions</code> sets their width (1–100,000, default 1,536). An embedding fixture
102+
repeats its supplied vector for each input; match <code>inputText</code> against the
103+
inputs joined by spaces. Recorded batches keep every vector and the upstream JSON metadata
104+
for replay.
105+
</p>
106+
<p>
107+
New <code>/api/embed</code> recordings also store <code>match.embeddingRequest</code> with
108+
the operation, exact input shape and requested dimensions, plus <code>match.model</code>.
109+
A batch such as <code>["first", "second"]</code> therefore does not match the string
110+
<code>"first second"</code>, a different width, or another embedding operation. Re-record
111+
older captures to add these keys. New legacy Ollama and OpenAI embedding recordings use
112+
the same operation-specific match field. Handwritten embedding fixtures without
113+
<code>embeddingRequest</code> keep their broad matching behavior.
114+
</p>
115+
<p>
116+
The legacy SDK method <code>embeddings({ model, prompt })</code> still uses
117+
<code>/api/embeddings</code> and returns a single <code>embedding</code> array.
118+
</p>
119+
86120
<h2>Key Differences from OpenAI</h2>
87121
<ul>
88122
<li>

‎docs/record-replay/index.html‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1045,6 +1045,13 @@ <h2>Fixture Auto-Generation</h2>
10451045
</p>
10461046

10471047
<h2 id="model-aware-recording">Model-Aware Recording</h2>
1048+
<p>
1049+
New Ollama and OpenAI-compatible embedding recordings also keep the operation, exact input
1050+
shape and requested dimensions in <code>match.embeddingRequest</code>. This separates
1051+
batches from strings with the same joined text, different widths, and other embedding
1052+
operations, both while recording and after loading the saved file. Re-record older
1053+
captures to add this match data.
1054+
</p>
10481055
<p>
10491056
When recording fixtures, aimock automatically includes the model name in match criteria.
10501057
This prevents collisions when your app makes multiple LLM calls with the same user message

‎etc/aimock-a2a.import.api.md‎

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎etc/aimock-a2a.require.api.md‎

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎etc/aimock-agui.import.api.md‎

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)