ai icon indicating copy to clipboard operation
ai copied to clipboard

Double answers / Repeated tool-calls issue

Open pavlo-tkhir opened this issue 1 year ago β€’ 18 comments

Description

Hi,

I'm experiencing a weird issue. Sometimes LMM calls the same tool multiple times. Tool call ids are different so this is not a frontend duplication issue. Another related (I think) issue is that sometimes LLM replies, calls the tool, and then replies again. So the user gets double replies. The replies are a bit different, so I can't write a workaround to exclude them from rendering.

Additional information

  • It's not frequent and hard to reproduce. Maybe once it 20-30 executions
  • The same message history does not lead to the same "broken" response. Could potentially mean a race condition issue.
  • I experience it with Gemini and OpenAI models/adapters. However, I haven't tested the setup with other models
  • Turning on reasoning does not help.

Here is an example of repeated tool calls. It stuck in a loop and stopped when it reached the stop condition (stopWhen: stepCountIs(5),)

Image

These multiple tool calls are within one AI answer message.

{
    "id": "qnnAcVnEtPlXHdbI",
    "role": "assistant",
    "parts": [
      {
        "type": "step-start"
      },
      {
        "type": "tool-generateChatTitle",
        "input": {
          "title": "Jokes and Humor"
        },
        "state": "output-available",
        "output": {
          "title": "Jokes and Humor",
          "success": true
        },
        "toolCallId": "7ND7L0Fq4gIeCoLQ"
      },
      {
        "type": "step-start"
      },
      {
        "type": "tool-generateChatTitle",
        "input": {
          "title": "Jokes and Humor"
        },
        "state": "output-available",
        "output": {
          "title": "Jokes and Humor",
          "success": true
        },
        "toolCallId": "klVKahaY96NgEgvx"
      },
      {
        "type": "step-start"
      },
      {
        "type": "tool-generateChatTitle",
        "input": {
          "title": "Jokes and Humor"
        },
        "state": "output-available",
        "output": {
          "title": "Jokes and Humor",
          "success": true
        },
        "toolCallId": "29Z9EHq25MVaW4Kg"
      },
      {
        "type": "step-start"
      },
      {
        "type": "tool-generateChatTitle",
        "input": {
          "title": "Jokes and Humor"
        },
        "state": "output-available",
        "output": {
          "title": "Jokes and Humor",
          "success": true
        },
        "toolCallId": "eMxjBoFDGllaAks3"
      },
      {
        "type": "step-start"
      },
      {
        "type": "tool-generateChatTitle",
        "input": {
          "title": "Jokes and Humor"
        },
        "state": "output-available",
        "output": {
          "title": "Jokes and Humor",
          "success": true
        },
        "toolCallId": "0UKDIsu3s97NkSJG"
      }
    ],
    "metadata": {
      "model": {
        "id": "gemini-2.5-flash",
        "provider": "google"
      },
      "duration": 4609,
      "totalUsage": {
        "inputTokens": 2180,
        "totalTokens": 2669,
        "outputTokens": 90,
        "reasoningTokens": 399
      }
    }

This second example shows a "double response" issue. It looks like the LLM does not see what it generated before the tool call:

Image
{
    "id": "aitxt-8Ui2pZdJ5DQTbSSC4IjxxP3S",
    "role": "assistant",
    "parts": [
      {
        "type": "step-start"
      },
      {
        "text": "This image is a concise guide to \"Good Strategy,\" stating that it's more than just a plan. According to the graphic, a good strategy involves three key steps:\n\n1.  **Diagnosing the problem:** This implies understanding the core issue that needs to be addressed.\n2.  **Defining guiding principles:** These are the foundational ideas or rules that will direct the approach.\n3.  **Taking coherent action:** This refers to implementing actions that are consistent with the diagnosis and guiding principles.\n\nThe image is labeled \"Strategic Thinking 101,\" suggesting it's a basic lesson on the topic.\n",
        "type": "text",
        "state": "done"
      },
      {
        "type": "tool-generateChatTitle",
        "input": {
          "title": "Good Strategy Explained"
        },
        "state": "output-available",
        "output": {
          "title": "Good Strategy Explained",
          "success": true
        },
        "toolCallId": "dhjpnmJ5JrhSNmkR"
      },
      {
        "type": "step-start"
      },
      {
        "text": "This image is an educational graphic titled \"Good Strategy β‰  Just a Plan\". It outlines three essential components for a good strategy:\n\n1.  **Diagnose the problem** (with a target emoji 🎯)\n2.  **Define guiding principles** (with a compass emoji 🧭)\n3.  **Take coherent action** (with a rocket emoji πŸš€)\n\nThe bottom of the image also includes the text \"Strategic Thinking 101\". It serves as a brief guide to the fundamental elements of effective strategic thinking.",
        "type": "text",
        "state": "done"
      }
    ]
  }

And here is my backend code (nestjs):

@Post("message")
async chat(@Body() model: ChatMessageModel, @Res() res: Response) {
  // ... extract old messages from the DB

  const stream = createUIMessageStream({
    execute({ writer }) {
      const result = streamText({
        model: google("gemini-2.5-flash"),
        system: "You have to do the following:
                  - Call the generateChatTitle tool to update the title. Current chat title is '${chatSession.name}'. This is the most accurate title from the database. If you see any tool calls to update the title with a different values, ignore them.
                  - Reply to the user.
        ",
        messages: convertToModelMessages(uiChatMessages),
        stopWhen: stepCountIs(5),
        tools: {
          generateChatTitle: tool({
            description: "Generate a concise, descriptive title for the chat session based on the conversation.",
            inputSchema: z.object({
              title: z.string().describe("A concise title (3-6 words) that describes the main topic or purpose of the conversation"),
            }),
            execute: async ({ title }) => {
              // .. update title in the DB ..
              return { success: true, title };
            },
          }),
        },
      });
      writer.merge(
        result.toUIMessageStream({
          sendReasoning: true,
          messageMetadata: messageMetadataProvider(llmModel, startTime),
        })
      );
    },
    onFinish: (data) => {
      // store response message in the DB
    },
  });
  pipeUIMessageStreamToResponse({ response: res, stream });
}

Thanks!

AI SDK Version

  • "@ai-sdk/google": "^2.0.0-beta.6"
  • "ai": "^5.0.0-beta.4"
  • "@ai-sdk/react": "^2.0.0-beta.4",

Backend: NestJS

pavlo-tkhir avatar Jul 13 '25 16:07 pavlo-tkhir

Please add originalMessages to either createUIMessageStream or toUIMessageStream (depending on what you are using on the outer level) so that the correct message id is set. The last assistant message id needs to be reused to prevent double messages.

lgrammel avatar Jul 14 '25 08:07 lgrammel

@lgrammel, thanks for the prompt reply. I'm testing your fix and will get back to you with the results. However, I have a couple of questions:

  1. originalMessages in createUIMessageStream have this description: "The original messages. If they are provided, persistence mode is assumed, and a message ID is provided for the response message." Does that mean that if we are not using "persistence" mode, we will get a random agent behaviour?
  2. How does the configuration in createUIMessageStream impact the inner const result = streamText? My understanding is that streamText is responsible for all the communication with LLM, and createUIMessageStream is simply converting the stream from one format to another. I want to understand the mechanics of this weird behaviour.

pavlo-tkhir avatar Jul 14 '25 09:07 pavlo-tkhir

@pavlo-tkhir the persistence part is misleading, ignore it for now. the issue is that ui messages have ids, model messages do not. also ui messages compress several assistant-tool-assistant-tool model messages into a single assistant ui message (for rendering). therefore the ui message id of the last assistant msg needs to be reused. the duplication happens because there are different ids being sent

lgrammel avatar Jul 14 '25 09:07 lgrammel

@lgrammel It looks like your suggestion didn't fix the issue.

[
  {
    "role": "user",
    "id": "xjAKKqEzVkOmpNPl",
    "parts": [
      {
        "type": "text",
        "text": "what is the weather like today"
      }
    ],
    "metadata": {
      "model": {
        "id": "gemini-2.5-flash",
        "provider": "google",
        "capabilities": [
          "thinking"
        ]
      }
    }
  },
  {
    "id": "T7qPKdjllh2AeK4M",
    "metadata": {
      "model": {
        "id": "gemini-2.5-flash",
        "provider": "google",
        "capabilities": [
          "thinking"
        ]
      },
      "duration": 2419,
      "totalUsage": {
        "inputTokens": 630,
        "outputTokens": 62,
        "totalTokens": 779,
        "reasoningTokens": 87
      }
    },
    "role": "assistant",
    "parts": [
      {
        "type": "step-start"
      },
      {
        "type": "reasoning",
        "text": "**Unable to Retrieve Weather**\n\nI've determined that I cannot currently access or provide weather information. My tools only allow for generating chat titles and documents. Therefore, I'm unable to answer the user's specific query about the weather at this time.\n\n\n**Confirming Weather Inaccessibility**\n\nI've clarified that the tools at my disposal don't include the ability to retrieve weather data. I can't fulfill the request. I'll need to inform the user about this limitation and adjust the chat title to reflect the weather-related topic. I'm focusing on crafting a helpful response.\n\n\n",
        "state": "done"
      },
      {
        "type": "text",
        "text": "I am sorry, I cannot tell you what the weather is like today. I can only generate chat titles and documents.\n",
        "state": "done"
      },
      {
        "type": "tool-generateChatTitle",
        "toolCallId": "YfeNNgDRnTMPI3UI",
        "state": "output-available",
        "input": {
          "title": "Weather query"
        },
        "output": {
          "success": true
        }
      },
      {
        "type": "step-start"
      },
      {
        "type": "text",
        "text": "I am sorry, I cannot tell you what the weather is like today. I can only generate chat titles and documents.",
        "state": "done"
      }
    ]
  }
]

It looks like this happens more frequently when there is no tool for LLM to use and with Google and XAI models. This happens less with Anthoropic and OpenAI models. There is even more extream case with grok

[
  {
    "role": "user",
    "id": "B5hDHuybK7l7U4ce",
    "parts": [
      {
        "type": "text",
        "text": "what is the weather like today?"
      }
    ],
    "metadata": {
      "model": {
        "id": "grok-4",
        "provider": "xai",
        "capabilities": [
          "thinking"
        ]
      }
    }
  },
  {
    "id": "JiAgs6WCqIgvTOnZ",
    "metadata": {
      "model": {
        "id": "grok-4-0709",
        "provider": "xai",
        "capabilities": [
          "thinking"
        ]
      },
      "duration": 82457,
      "totalUsage": {
        "inputTokens": 5720,
        "outputTokens": 206,
        "totalTokens": 9480,
        "reasoningTokens": 3554
      }
    },
    "role": "assistant",
    "parts": [
      {
        "type": "step-start"
      },
      {
        "type": "reasoning",
        "text": "Thinking... Thinking... Thinking... Thinking... Thinking... Thinking... Thinking... Thinking... Thinking... ",
        "state": "done"
      },
      {
        "type": "tool-generateChatTitle",
        "toolCallId": "call_21991023",
        "state": "output-available",
        "input": {
          "title": "Today's Weather Inquiry"
        },
        "output": {
          "success": true
        }
      },
      {
        "type": "text",
        "text": "I'm sorry, but I don't have access to real-time weather information. Could you please specify the location you're asking about? That way, I can try to help you better or suggest how to find out.",
        "state": "done"
      },
      {
        "type": "step-start"
      },
      {
        "type": "reasoning",
        "text": "Thinking... Thinking... Thinking... Thinking... Thinking... Thinking... Thinking... Thinking... Thinking... Thinking... Thinking... Thinking... Thinking... Thinking... Thinking... Thinking... Thinking... Thinking... Thinking... Thinking... Thinking... Thinking... Thinking... ",
        "state": "done"
      },
      {
        "type": "tool-generateChatTitle",
        "toolCallId": "call_16412357",
        "state": "output-available",
        "input": {
          "title": "New chat 15/07/2025, 14:25:43"
        },
        "output": {
          "success": true
        }
      },
      {
        "type": "text",
        "text": "I'm sorry, I don't have access to real-time weather information. To give you an accurate answer, I'd need to know your location. Can you provide that? \n\nAlternatively, I can suggest using a weather app or website like Weather.com or the built-in weather feature on your device.",
        "state": "done"
      },
      {
        "type": "step-start"
      },
      {
        "type": "reasoning",
        "text": "Thinking... Thinking... Thinking... Thinking... Thinking... ",
        "state": "done"
      },
      {
        "type": "text",
        "text": "I'm sorry, but I don't have access to real-time weather information in this mode. If you provide a specific location, I can help guide you on how to check it or suggest general advice!",
        "state": "done"
      }
    ]
  }
]

There is also an issue with Grok thinking, but I'll open another ticket.

pavlo-tkhir avatar Jul 15 '25 13:07 pavlo-tkhir

Also experiencing this. @pavlo-tkhir were you able to find a solution?

paulonasc avatar Aug 11 '25 06:08 paulonasc

@paulonasc, Unfortunately, no. We had to move to an "alternative framework" to solve this.

pavlo-tkhir avatar Aug 11 '25 13:08 pavlo-tkhir

@pavlo-tkhir Gotcha! Which framework/library did you switch to?

paulonasc avatar Aug 11 '25 14:08 paulonasc

@paulonasc we have moved to langgraph. I can't say it was a great decision, but at least we no longer have this issue. However, we have got a lot of other problems. Here is my list of pros/cons of LangGraph compared to AI SDK:

Pros

  1. You don't have this issue πŸ˜†
  2. A lot of tutorials and examples
  3. More control
  4. Agentic workflows (however, I've recently discovered voltagent that should cover this gap for the AI SDK. I haven't tested it, though)

Cons

  1. Langgraph is pushing its approaches and services on the backend. For example, "checkpointers", langgraph cli, langsmith, etc.
  2. LangGraph does not fully abstract LLM model responses. If you want to use models from different providers, you have to convert messages to the appropriate format. E.g., you can't use the response from Anthropic models and send them to Gemini to summarize. It will fail because the messages are incompatible, despite being instances of AIMessage provided by LangGraph (LangChain).
  3. LangGraph is focused on the backend use cases (e.g., offline workflows). Their frontend support is not so great.

From the ease/usability perspective, the AI SDK is a clear winner here. However, it lacks multi-agent capabilities and has this nasty bug that forced us to move. We were early in the development, so it was not hard for us to do.

By the way, are you also using NestJS (not Next) for the backend or something different? I want to understand if this has something to do with it.

pavlo-tkhir avatar Aug 11 '25 15:08 pavlo-tkhir

Please also check out our troubleshooting page for duplicated assistant messages: https://ai-sdk.dev/docs/troubleshooting/repeated-assistant-messages

lgrammel avatar Aug 21 '25 09:08 lgrammel

We’re using Vercel AI SDK on the backend with streamText(...) and running into the same issue: assistant messages are duplicated instead of continued.

nareshtank001 avatar Sep 15 '25 06:09 nareshtank001

We're also encountering weird issues after switching to Vercel AI SDK (server side) where we will get back the same, or very similar, agent text responses when using streaming responses. Sometimes its related to a function call, sometimes its not. It seems entirely intermittent and difficult to reproduce.

lylepratt avatar Jan 05 '26 22:01 lylepratt

Same issue here as @lylepratt with client side tools as well

aoztanir avatar Jan 06 '26 23:01 aoztanir

having the same issue even though parallel tool calls are disabled

ouzkagan avatar Jan 09 '26 12:01 ouzkagan

In our case, this ended up being because Vercel uses OpenAI's Requests API by default, instead of Chat Completions. The Requests API will randomly provide multiple "versions" of its output (there seems to be no way to disable this and there are complaints about this all over the OpenAI forums). When in "streaming" mode, these versions come through as "text-delta" events with different IDs. If you've previously been using the Chat Completions API, this doesn't happen. To solve the problem, we look at the first text-delta ID we receive and make sure to only stream other text-delta's with the same ID. Hope this helps someone!

lylepratt avatar Jan 09 '26 20:01 lylepratt

Happens here too

ylnsnv avatar Jan 10 '26 13:01 ylnsnv

I don't think this should be closed. This is a real issue with the OpenAI requests api, as mentioned by @lylepratt and it is something the ai sdk should offer a mitigation option for. We can use the completions api if we use the OpenAI provider, but to my knowledge there is no way to do it if we're using Vercel AI Gateway, which I'm a customer of.

albertkim avatar Feb 23 '26 21:02 albertkim

this is really a pain.. how is this not solved? Putting up a troubleshooting docs page is.. nice, but it's a band-aid πŸ™

joeyorlando avatar Mar 19 '26 19:03 joeyorlando

Identify issue type

Identified as Bug
Confidence: High

Rationale

This describes concrete, unintended duplication in existing streaming and tool-call behavior rather than a request for new functionality. The issue remains reproducible despite the suggested message-ID configuration and is corroborated by multiple users.

Evidence

  • The reporter shows one streamed assistant message containing repeated tool calls with distinct IDs and duplicate text responses after tool execution.
  • Adding originalMessages, initially suggested to prevent duplicate UI messages, did not resolve the reproduced duplication.
  • Multiple users later report the same intermittent behavior across server-side streaming, client-side tools, and several providers.
  • A later report attributes one variant to multiple streamed output versions from OpenAI's Responses API and notes that AI SDK/Gateway lacks a mitigation option.

lgrammel avatar Jul 22 '26 14:07 lgrammel