ai icon indicating copy to clipboard operation
ai copied to clipboard

Disable thinking while using OpenAI-compatible chat API interface

Open MaheshKannaIntron opened this issue 1 year ago • 14 comments

Description

In Ollama we can disable thinking by passing "think": false. This will hide the thinking in UI interface, thinking will not be returned in the API resposne. Similarly add a param to hide the thinking. @ai-sdk/openai

AI SDK Version

No response

MaheshKannaIntron avatar Jun 12 '25 12:06 MaheshKannaIntron

@MaheshKannaIntron, have you seen https://ai-sdk.dev/docs/ai-sdk-core/middleware#extract-reasoning?

bestickley avatar Jun 26 '25 15:06 bestickley

Solution for Google models - I was trying to figure out how to disable thinking for gemini-2.5-flash specifically and this thread came up - its slightly buried in the docs but you can do it like so by having a thinkingBudget of 0:

const { text } = await generateText({
  model: google('gemini-2.5-flash-preview-04-17'),
  providerOptions: {
    google: {
      thinkingConfig: {
        // Disables thinking
        thinkingBudget: 0,
      },
    } satisfies GoogleGenerativeAIProviderOptions,
  },
  // ...
});

drg101 avatar Jun 30 '25 11:06 drg101

@drg101, are you sure you want to do that? Wouldn't removing thinking tags reduce accuracy?

bestickley avatar Jun 30 '25 13:06 bestickley

what is the use case for disabling reasoning for models that are capable of reasoning?

lgrammel avatar Jun 30 '25 13:06 lgrammel

@lgrammel, see from OP:

This will hide the thinking in UI interface

There is extractReasoningMiddleware so that might work for OP. But I'm using Amazon Nova models which don't accept reasoning parameter in API request to model so I'm working through just hiding in UI (using assistant-ui)

bestickley avatar Jun 30 '25 13:06 bestickley

you can just not forward it to the ui (sendReasoning: false) or if you send it just not render it.

lgrammel avatar Jun 30 '25 13:06 lgrammel

you can just not forward it to the ui (sendReasoning: false)

but then you'd have to store it somewhere (assuming stateless backend like lambda) so on next call to LLM it's included, right? I think just not rendering is "easiest" option. Working on code right now for that. Will post when have it working.

bestickley avatar Jun 30 '25 13:06 bestickley

you can also forward the reasoning but just not render it

lgrammel avatar Jun 30 '25 14:06 lgrammel

Solution to not render on client. Tricker than I initially thought!

parseMessageParts.ts
type UIMessagePartType = "text" | "thinking";

interface ParseUIMessagePartsProps {
  content: string;
  /**
   * @default "thinking"
   */
  tag?: string;
}

/**
 * Given a string LLM response containing partial or whole <thinking> tags,
 * parse text into `UIMessagePartType`s and return in array with parts
 * segmented by "thinking" or "text".
 *
 * Note, AI SDK has native [extractReasoningMiddleware](https://ai-sdk.dev/docs/reference/ai-sdk-core/extract-reasoning-middleware)
 * but this doesn't work for LLM's that don't support reasoning like Amazon Nova.
 * You could edit system prompt to remove thinking but that would reduce LLM
 * accuracy so this solution just removes `<thinking>` tags from response and
 * parses them into `UIMessagePartType`s.
 *
 * Will also combine back-to-back thinking tags.
 *
 * @example
 * parseChatContent("<thinking>I'm thinking...</thinking>The answer is ...")
 * // [{ content: "I'm thinking...", type: "thinking" }, { content: "The answer is...", type: "text" }]
 */
export function parseUIMessageParts(
  props: ParseUIMessagePartsProps,
): { content: string; type: UIMessagePartType }[] {
  const { content, tag = "thinking" } = props;

  if (!content) return [];

  const openingTag = `<${tag}>`;
  const openingTagFirstChar = openingTag[0];
  const closingTag = `</${tag}>`;
  const closingTagFirstChar = closingTag[0];
  const results: { content: string; type: UIMessagePartType }[] = [];

  let textBuffer = "";
  let thinkingBuffer = "";
  let openingTagBuffer = "";
  let closingTagBuffer = "";
  let isThinking = false;

  function pushThinkingMessage(buffer: string) {
    // combine back-to-back thinking tags in 1 message part
    const lastMessagePart = results.at(-1);
    if (lastMessagePart?.type === "thinking") {
      lastMessagePart.content += `\n${buffer}`;
    } else {
      results.push({ content: buffer, type: "thinking" });
    }
  }

  for (const char of content) {
    if ((!isThinking && char === openingTagFirstChar) || openingTagBuffer) {
      if (textBuffer) {
        // if existing buffer, flush to results
        results.push({ content: textBuffer, type: "text" });
        textBuffer = "";
      }
      openingTagBuffer += char;
      if (openingTag.startsWith(openingTagBuffer)) {
        if (openingTagBuffer === openingTag) {
          isThinking = true;
          openingTagBuffer = "";
        }
      } else {
        // tag isn't a thinking tag so add chars back to buffer so it's used as text
        textBuffer += openingTagBuffer;
        openingTagBuffer = "";
      }
    } else if (isThinking) {
      if (char === closingTagFirstChar || closingTagBuffer) {
        closingTagBuffer += char;
        if (closingTag.startsWith(closingTagBuffer)) {
          if (closingTagBuffer === closingTag) {
            pushThinkingMessage(thinkingBuffer);
            isThinking = false;
            closingTagBuffer = "";
            thinkingBuffer = "";
          }
        } else {
          // tag isn't a closing tag so add chars back to buffer so it's used as text
          textBuffer += closingTagBuffer;
          closingTagBuffer = "";
        }
      } else {
        thinkingBuffer += char;
      }
    } else {
      textBuffer += char;
    }
  }

  if (textBuffer) {
    results.push({ content: textBuffer, type: "text" });
  }
  if (thinkingBuffer) {
    pushThinkingMessage(thinkingBuffer);
  }

  return results;
}

parseMessageParts.test.ts
import { describe, expect, it } from "vitest";
import { parseUIMessageParts } from "./parse-message-parts";

const thinking = "I am thinking";
const text = "Here is my answer...";
const tag = "thinking";

describe("parse-message-parts", () => {
  it("should parse thinking tags", () => {
    const parts = parseUIMessageParts({
      content: `<thinking>${thinking}</thinking>`,
      tag,
    });
    const response: ReturnType<typeof parseUIMessageParts> = [
      { content: thinking, type: "thinking" },
    ];
    expect(parts).toEqual(response);
  });

  it("should parse text", () => {
    const parts = parseUIMessageParts({ content: text });
    const response: ReturnType<typeof parseUIMessageParts> = [
      { content: text, type: "text" },
    ];
    expect(parts).toEqual(response);
  });

  it("should parse thinking and text", () => {
    const parts = parseUIMessageParts({
      content: `<thinking>${thinking}</thinking>${text}`,
    });
    const response: ReturnType<typeof parseUIMessageParts> = [
      { content: thinking, type: "thinking" },
      { content: text, type: "text" },
    ];
    expect(parts).toEqual(response);
  });

  it("should parse thinking without closing tag", () => {
    const parts = parseUIMessageParts({ content: `<thinking>${thinking}` });
    const response: ReturnType<typeof parseUIMessageParts> = [
      { content: thinking, type: "thinking" },
    ];
    expect(parts).toEqual(response);
  });

  it("should hide incomplete opening thinking tag", () => {
    expect(parseUIMessageParts({ content: `<` }).length).toBe(0);
    expect(parseUIMessageParts({ content: `<t` }).length).toBe(0);
    expect(parseUIMessageParts({ content: `<think` }).length).toBe(0);
    expect(parseUIMessageParts({ content: `<thinking>` }).length).toBe(0);
    expect(parseUIMessageParts({ content: `<thinking>I` }).length).toBe(1);
  });

  it("should hide incomplete closing thinking tag", () => {
    const response: ReturnType<typeof parseUIMessageParts> = [
      { content: thinking, type: "thinking" },
    ];
    expect(parseUIMessageParts({ content: `<thinking>${thinking}<` })).toEqual(
      response,
    );
    expect(parseUIMessageParts({ content: `<thinking>${thinking}</` })).toEqual(
      response,
    );
    expect(
      parseUIMessageParts({ content: `<thinking>${thinking}</t` }),
    ).toEqual(response);
    expect(
      parseUIMessageParts({ content: `<thinking>${thinking}</think` }),
    ).toEqual(response);
    expect(
      parseUIMessageParts({ content: `<thinking>${thinking}</thinking` }),
    ).toEqual(response);
    expect(
      parseUIMessageParts({ content: `<thinking>${thinking}</thinking>` }),
    ).toEqual(response);
    const response2: ReturnType<typeof parseUIMessageParts> = [
      { content: thinking, type: "thinking" },
      { content: "H", type: "text" },
    ];
    expect(
      parseUIMessageParts({ content: `<thinking>${thinking}</thinking>H` }),
    ).toEqual(response2);
  });

  it("should combine multiple thinking tags into 1 message part", () => {
    const parts = parseUIMessageParts({
      content: `<thinking>${thinking}</thinking><thinking>${thinking} 2</thinking>`,
    });
    const response: ReturnType<typeof parseUIMessageParts> = [
      { content: `${thinking}\n${thinking} 2`, type: "thinking" },
    ];
    expect(parts).toEqual(response);
  });
});

bestickley avatar Jun 30 '25 16:06 bestickley

Fully disabling thinking is for low latency usecases - see here. Many new models are meant to support either system in a dynamic / hybrid way

It looks like Google's native API also supports dynamically enabling thinking with thinkingBudget: -1.

Ollama allows both fully disabling thinking with nothink or think: false, along with hiding it from the UI with --hidethinking

drg101 avatar Jun 30 '25 18:06 drg101

If you want to exclude reasoning for latency purposes, you would need to look into the provider specific ways to turn it off for now, as @drg101 pointed out. There is no clear "turn off reasoning" pattern yet that we would want to abstract.

lgrammel avatar Jul 01 '25 07:07 lgrammel

hey, I just found how to do this. Edit model works fine again when I disabled reasoning on reasoningable model like gpt5.4. If you have a openai-compatible model, edit your config.yaml like:

  • name: gpt-5.4-mini provider: openai model: gpt-5.4-mini apiKey: x apiBase: x roles:
    • edit requestOptions: extraBodyProperties: reasoning: effort: none

by reasoning:effort none (follow format above), you can turn off reasoning, which is cleared by OpenAI docs. If you are using another provider, check docs and search how to disable it. After disabling this, the response from model is no longer with thinking process, just the code only like below: ---------Log-from-Continue-Console------------------------------- ); }

Z2IRIM avatar Mar 19 '26 04:03 Z2IRIM

Identify issue type

Identified type: Feature
Confidence: High

Rationale: The report asks for a new SDK/API capability or abstraction to disable/hide reasoning output; it does not describe broken existing behavior or a documentation-only change.

Evidence:

  • The issue requests adding a parameter to @ai-sdk/openai/OpenAI-compatible chat API to disable or hide model “thinking,” similar to Ollama's think: false.
  • Comments discuss possible workarounds such as extractReasoningMiddleware, sendReasoning: false, provider-specific options like Google thinkingBudget: 0, and OpenAI-compatible reasoning.effort: none.
  • A maintainer states there is no clear generic “turn off reasoning” pattern yet to abstract.

lgrammel avatar Jul 02 '26 09:07 lgrammel

This is now supported with the top level reasoning option, including in the OpenAI-compatible provider.

import { generateText } from 'ai';

const { text, reasoning, reasoningText } = await generateText({
  model: 'anthropic/claude-sonnet-5',
  reasoning: 'none',
  prompt: 'How many people will live in the world in 2040?',
});

Added in #13553 and #13648

n1ckoates avatar Sep 25 '26 00:09 n1ckoates