genkit icon indicating copy to clipboard operation
genkit copied to clipboard

[JS] genkitx-ollama: streaming drops tool_calls and returns literal "undefined" text (breaks defineAgent & generateStream)

Open lperezp opened this issue 1 week ago • 4 comments

Describe the bug When using genkitx-ollama with tool calling enabled in streaming mode (e.g., via ai.defineAgent from genkit/beta or ai.generateStream with tools), any tool_calls emitted by Ollama are silently dropped and the model response returns the literal string "undefined" (outputCharacters: 9) with finishReason: "stop".

Because ai.defineAgent runs model generation in streaming mode internally, this completely breaks tool calling for all Ollama chat models when used with Genkit Agents.

To Reproduce

import { z } from 'genkit';
import { genkit } from 'genkit/beta';
import { ollama } from 'genkitx-ollama';

const ai = genkit({
  plugins: [
    ollama({
      serverAddress: 'http://127.0.0.1:11434',
      models: [{ name: 'gemma4:12b', type: 'chat', supports: { tools: true } }],
    }),
  ],
});

const getProfile = ai.defineTool(
  {
    name: 'getProfile',
    description: 'Returns the user fitness profile.',
    inputSchema: z.object({}),
    outputSchema: z.object({ goal: z.string() }),
  },
  async () => ({ goal: 'First marathon (42K)' })
);

const coachAgent = ai.defineAgent({
  name: 'coachAgent',
  model: 'ollama/gemma4:12b',
  tools: [getProfile],
  system: 'Always call getProfile before answering.',
});

const res = await coachAgent.chat().send('How should I start training for my goal?');
console.log(res.text); // Logs: "undefined" (tool is never executed)

Expected behavior When Ollama streams a chunk containing tool_calls, genkitx-ollama should preserve the toolRequest parts in the returned message.content. Genkit should execute the requested tool(s) and continue the generation loop.

Screenshots If applicable, add screenshots to help explain your problem.

Runtime (please complete the following information):

** Node version

  • Node.js: v24.21.0

Additional context parseMessage(json, type) correctly parses response.message.tool_calls into { content: [{ toolRequest: ... }] }.

Because message2.content[0] is a toolRequest (not a text part), message2.content[0].text is undefined, turning textResponse into "undefined".

The final returned message always wraps textResponse as a text part and discards all toolRequest parts, causing Genkit to stop without invoking any tools.

lperezp avatar Nov 24 '26 15:11 lperezp

I can confirm this from the source on main (js/plugins/ollama/src/index.ts). There's a second problem in the same loop that you'll probably hit next:

for await (const chunk of readChunks(reader)) {
  const chunkText = textDecoder.decode(chunk);
  const json = JSON.parse(chunkText);        // assumes 1 network chunk == 1 NDJSON line
  const message = parseMessage(json, type);
  ...
  textResponse += message.content[0].text;   // undefined for a toolRequest part
}
message = { role: 'model', content: [{ text: textResponse }] };  // tool parts discarded
  • The "undefined" text and the dropped tool calls come from the last two lines, as you described.
  • JSON.parse(chunkText) fails when a single read contains two NDJSON lines, or ends in the middle of one. That happens with larger or faster streams and surfaces as a SyntaxError. decode(chunk) without { stream: true } can also split a multi-byte UTF-8 character.

Note that #6782 (open since October) fixes the same two things. A maintainer may want to pick one of the two PRs.

Until one of them is released, you can point the OpenAI-compatible plugin at Ollama's /v1 endpoint for agents. Its streaming path handles tool call deltas:

import openAICompatible from '@genkit-ai/compat-oai';

const ai = genkit({
  plugins: [
    openAICompatible({
      name: 'ollama-oai',
      apiKey: 'ollama',                       // any non-empty string
      baseURL: 'http://127.0.0.1:11434/v1',
    }),
  ],
});
// models resolve on demand: model: 'ollama-oai/gemma4:12b'

emreyoleridev avatar Nov 25 '26 03:11 emreyoleridev

Confirmed on main (js/plugins/ollama/src/index.ts): the streaming loop has three defects in the same place. (1) The final message is rebuilt as text-only after the loop, so tool requests from streamed chunks are dropped — that's the tool-calling breakage. (2) textResponse += message.content[0].text appends the string "undefined" on tool chunks, which have no .text — that's the literal "undefined" you see. (3) The TextDecoder runs without { stream: true }, so a multi-byte character split across chunks is mangled.

I'd like to fix all three: accumulate tool requests (mirroring the non-streaming precedence where tool_calls win), guard the text append, and decode with stream: true, with node:test regressions for streamed text and streamed tool calls (the latter asserts the agent loop completes).

One related gap I'd leave for a follow-up: the loop still parses one JSON object per read chunk, so an NDJSON line split across chunks would throw — line buffering is a separate change.

Taking this unless you're already on it.

insuffer avatar Nov 25 '26 09:11 insuffer

Heads up before you start: #6782 is still open and already covers the tool-call accumulation plus the line buffering you want to leave for later (it parses the stream line by line). It hasn't had activity since October, so it may be easier to build on it or ask its author than to start a second PR on the same loop.

emreyoleridev avatar Nov 25 '26 10:11 emreyoleridev

Update: withdrawing my claim — thanks to @emreyoleridev for the pointer, I had missed that #6782 already covers this.

I pulled #6782 down and verified it against current main: it applies cleanly and its streaming suite passes 15/15 here. It is a complete fix for the three defects in this issue — the tool-call accumulation, the "undefined" append, and the decoder without { stream: true } — plus the line buffering I had flagged as a follow-up, so there is nothing left for a second PR on this loop to add.

It has been quiet since October; the author may still need to sign the CLA (google-cla commented on 10-12). If anything, it likely needs a maintainer nudge rather than a new PR.

insuffer avatar Nov 27 '26 06:11 insuffer