Skip to content

Python: [Bug]: Preserve reasoning_content when invoking tools with OpenAI-compatible Chat Completions providers #8382

Closed

Description

@peter-chenqing

Description

Description

When using OpenAIChatCompletionClient with an OpenAI-compatible provider that supports reasoning/thinking and tool calling, the follow-up request after a tool call can fail because reasoning_content is not preserved in the exact assistant message structure required by the provider.

The issue was reproduced with the official DeepSeek API and a thinking-enabled model.

Environment

  • OS: macOS
  • Python: 3.14
  • Agent Framework: 1.18.0
  • Client: OpenAIChatCompletionClient
  • API: OpenAI-compatible Chat Completions API
  • Provider: DeepSeek
  • Base URL: https://api.deepseek.com
  • Model: deepseek-flash
  • requires-python = ">=3.14"
  • dependencies = [

repro_replay.log

repro_replay.log

"numpy>=2.5.3",
"openmeteo-requests>=1.7.5",
"pandas>=3.0.5",
"python-dotenv>=1.2.3",
"requests-cache>=1.3.3",
"retry-requests>=2.0.0",

]

Minimal Reproduction

from agent_framework import Agent, tool
from agent_framework.openai import OpenAIChatCompletionClient

@tool
def get_weather(location: str) -> str:
    return f"Weather result for {location}"

client = OpenAIChatCompletionClient(
    base_url="https://api.deepseek.com",
    api_key="...",
    model="deepseek-flash",
)

agent = Agent(
    client=client,
    instructions="Use the get_weather tool when the user asks about weather.",
    tools=[get_weather],
)

response = await agent.run(
    "What is the weather in New York City?",
    options={
        "extra_body": {
            "thinking": {
                "type": "enabled"
            }
        }
    },
)

### Code Sample

```markdown
import os
import sys
import asyncio
import json
from functools import partial
from pathlib import Path
from typing import Any
from dotenv import load_dotenv
from agent_framework import Agent, Content, tool
from agent_framework.openai import OpenAIChatCompletionClient, OpenAIChatClient
from agent_framework.anthropic import AnthropicClient

if __package__ in (None, ""):
    sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from utility.get_weather_from_open_meteo import WeatherAPI


def parse_openai_compatible_response(message: Any, contents: list[Content]) -> list[Content]:
    reasoning_content = getattr(message, "reasoning_content", None)
    if reasoning_content is None:
        extra = getattr(message, "model_extra", None) or getattr(message, "additional_kwargs", None) or {}
        reasoning_content = extra.get("reasoning_content") or extra.get("reasoning_details")
    if reasoning_content and not any(content.type == "text_reasoning" for content in contents):
        contents.append(Content.from_text_reasoning(protected_data=json.dumps(reasoning_content)))
    return contents


def prepare_openai_compatible_message(
    message: Any,
    prepared_messages: list[dict[str, Any]],
    reasoning_field: str = "reasoning_details",
) -> list[dict[str, Any]]:
    for prepared_message in prepared_messages:
        if "reasoning_details" in prepared_message:
            prepared_message[reasoning_field] = prepared_message.pop("reasoning_details")

    merged_messages = []
    for prepared_message in prepared_messages:
        is_assistant = prepared_message.get("role") == "assistant"
        previous_message = merged_messages[-1] if merged_messages else None
        can_merge = (
            is_assistant
            and previous_message is not None
            and previous_message.get("role") == "assistant"
            and "tool_call_id" not in prepared_message
            and "tool_call_id" not in previous_message
        )
        if not can_merge:
            merged_messages.append(prepared_message)
            continue

        if prepared_message.get("content"):
            previous_content = previous_message.get("content")
            if previous_content:
                previous_message["content"] = f"{previous_content}{prepared_message['content']}"
            else:
                previous_message["content"] = prepared_message["content"]
        if prepared_message.get("tool_calls"):
            previous_message.setdefault("tool_calls", []).extend(prepared_message["tool_calls"])
        if prepared_message.get("reasoning_content") is not None:
            previous_message["reasoning_content"] = prepared_message["reasoning_content"]

    return merged_messages


prepare_deepseek_message = partial(
    prepare_openai_compatible_message,
    reasoning_field="reasoning_content",
)

env_path = Path(__file__).parent.parent / ".env"
load_dotenv(env_path)

#deepseek model configuration
deepseek_url=os.environ.get("deepseek_base_url")
deepseek_api_key=os.environ.get("deepseek_api_key")
deepseek_model=os.environ.get("deepseek_model")
deepseek_client = OpenAIChatCompletionClient(
    base_url=deepseek_url,
    api_key=deepseek_api_key,
    model=deepseek_model,
    response_parser=parse_openai_compatible_response,
    message_preparer=prepare_deepseek_message,
)

#create tool
@tool
def get_weather(location: str) -> str:
    """
    Get hourly weather information for a given location name.
    """
    try:
        weather_df = WeatherAPI().get_weather(location)
    except Exception as error:
        return f"Weather lookup failed for {location!r}: {error}"

    if weather_df.empty:
        return f"Weather lookup returned no data for {location!r}."

    return weather_df.to_string()

#create agents
agent1 = Agent(
    client=deepseek_client, 
    instructions="You are a helpful assistant that answers questions by calling the get_weather tool to get weather information for a given location.",
    tools=[get_weather]
)
agent2 = Agent(
    client=anthropic_client,
    instructions="You are a helpful assistant that answers questions by calling the get_weather tool to get weather information for a given location.",
    tools=[get_weather]
)


async def main():
    prompt = "What is the weather in Los Angeles?"
    response = await agent1.run(
        prompt,
        options={"extra_body": {"thinking": {"type": "enabled"}}},
    )
    print("Response from agent1:")
    print(response.text)


if __name__ == "__main__":
    asyncio.run(main())

Error Messages / Stack Traces

pls refer to below addition context.

Package Versions

agent-framework-core version 1.18.0

Python Version

Python 3.14

Additional Context

repro_replay.log

repro_agent_buggy.log

ISSUE_reasoning_content_tool_call.md

Activity

  1. added
    python
    triage
    on Sep 15, 2026
  2. added
    reproduced
    on Sep 15, 2026
  3. github-actions commented on Sep 15, 2026

    @github-actions
    Contributor

    🤖 Automated triage reproduction notes (agent-authored — trust but verify)

    Agent analysis

    The bug reproduces in python/packages/openai/agent_framework_openai/_chat_completion_client.py::_parse_response_from_openai and _build_openai_messages when one provider response contains text, a tool call, and protected reasoning. Minimal repro: parse a ChatCompletionMessage containing content, tool_calls, and reasoning_content through provider hooks, then prepare the parsed framework message; it produces two assistant dictionaries instead of one.

    • Failing test: python/packages/openai/tests/openai/test_openai_chat_completion_client.py::test_roundtrip_reasoning_content_with_text_and_function_call_keps_single_assistant_message
    • Files examined: python/packages/openai/agent_framework_openai/_chat_completion_client.py, python/packages/openai/tests/openai/test_openai_chat_completion_client.py, docs/specs/004-python-function-calling-loop.md, python/packages/openai/pyproject.toml
    • Tests run: test_roundtrip_reasoning_content_with_text_and_function_call_keps_single_assistant_message (failed), test_parse_text_reasoning_content_from_response (passed), test_prepare_message_with_text_reasoning_before_function_call (passed), test_hooks_roundtrip_vllm_reasoning (passed)
    • Reported version: 1.14.3
    • Current version: 1.14.3
  4. added
    agents
    and removed
    triage
    on Sep 15, 2026
  5. anishmehta24 commented on Sep 15, 2026

    @anishmehta24
    Contributor

    I'd like to take this on. I reproduced it in a unit test: _build_openai_messages emits a text-only assistant dict and a separate tool_calls dict for one turn, and the buffered reasoning field only lands on the second one, which is why DeepSeek rejects the tool-result follow-up. The fix keeps text, tool_calls and the reasoning field on a single assistant message while leaving hook-surfaced reasoning text and other content untouched, so the existing response_parser/message_preparer pattern for reasoning_content works end to end. PR incoming with regression tests.

  6. added a commit that references this issue on Sep 16, 2026
    fca126d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

agentspythonreproduced

Type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions