agent-framework icon indicating copy to clipboard operation
agent-framework copied to clipboard

Python: [Bug]: OpenAIChatCompletionClient raises JSONDecodeError on reasoning content produced by OpenAIChatClient (Responses) or AnthropicClient

Open AkshayShah03 opened this issue 2 weeks ago • 2 comments

Observed Behavior

OpenAIChatCompletionClient fails while building the request when the message history contains text_reasoning content whose protected_data isn't JSON. The request never reaches the SDK, and the error is a raw json.JSONDecodeError rather than a framework exception.

Two clients in this repo produce exactly that content:

  • OpenAIChatClient (Responses API): it stores the opaque encrypted_content in protected_data, and asks for it by default when service-side storage isn't used.
  • AnthropicClient: it stores the thinking signature in protected_data.

So a shared session or multi-agent workflow that mixes a Responses-API agent (or a Claude agent) with a Chat Completions agent breaks on the next Chat Completions call:

Responses-client output contents: [('text_reasoning', 'Adding numbers.', 'gAAAAABo-opaque-ciphertext=='), ('text', '4', None)]
OpenAIChatCompletionClient on Responses history -> EXC JSONDecodeError Expecting value: line 1 column 1 (char 0)
OpenAIChatCompletionClient on Anthropic thinking history -> EXC JSONDecodeError Expecting value: line 1 column 1 (char 0)
Agent.run -> JSONDecodeError Expecting value: line 1 column 1 (char 0)

Expected Behavior

The request is built. Reasoning payloads that aren't in the Chat Completions reasoning_details format are skipped (or the visible reasoning text is handled as it is when protected_data is None), instead of crashing.

Steps to Reproduce

  1. Get an assistant message from OpenAIChatClient with reasoning (e.g. gpt-5, stateless), or from AnthropicClient with extended thinking.
  2. Pass that history to an Agent backed by OpenAIChatCompletionClient.
  3. agent.run(history) raises JSONDecodeError.

Minimal Reproduction

Offline, no API keys needed. Run with the repo's dev environment.

"""History produced by OpenAIChatClient (Responses API, stateless default => encrypted reasoning)
or by AnthropicClient (thinking signature) crashes OpenAIChatCompletionClient request building."""
import json
from openai.types.responses import Response
from agent_framework import Message, Content
from agent_framework_openai import OpenAIChatClient, OpenAIChatCompletionClient

resp = Response.model_validate({
  "id":"resp_1","object":"response","created_at":1700000000,"model":"gpt-5","status":"completed",
  "parallel_tool_calls":True,"tool_choice":"auto","tools":[],
  "output":[
    {"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"Adding numbers."}],
     "encrypted_content":"gAAAAABo-opaque-ciphertext=="},
    {"type":"message","id":"msg_1","role":"assistant","status":"completed",
     "content":[{"type":"output_text","text":"4","annotations":[]}]}]})
responses_client = OpenAIChatClient(model="gpt-5", api_key="x")
r = responses_client._parse_response_from_openai(resp, {})
print("Responses-client output contents:", [(c.type, c.text, c.protected_data) for c in r.messages[0].contents])

cc = OpenAIChatCompletionClient(model="gpt-4o-mini", api_key="x")
history = [Message(role="user", contents=["2+2?"]), *r.messages, Message(role="user", contents=["thanks"])]
try:
    print(cc._prepare_messages_for_openai(history))
except Exception as e:
    print("OpenAIChatCompletionClient on Responses history -> EXC", type(e).__name__, e)

anth_turn = Message(role="assistant", contents=[Content.from_text_reasoning(text="simple", protected_data="EqQBCkYIBxgCKkBsig=="), Content.from_text("4")])
try:
    print(cc._prepare_messages_for_openai([Message(role="user", contents=["2+2?"]), anth_turn]))
except Exception as e:
    print("OpenAIChatCompletionClient on Anthropic thinking history -> EXC", type(e).__name__, e)

# Full public path (Agent.run) with a mocked SDK client: the request never reaches the SDK.
import asyncio
from unittest.mock import AsyncMock, MagicMock
from agent_framework import Agent
async def main():
    cc.client = MagicMock(); cc.client.chat.completions.create = AsyncMock(side_effect=AssertionError("SDK reached"))
    agent = Agent(client=cc, name="summarizer")
    try:
        await agent.run(history)
    except Exception as e:
        print("Agent.run ->", type(e).__name__, e)
asyncio.run(main())

Root cause (what I found)

agent_framework_openai/_chat_completion_client.py (around line 1230), in _prepare_messages_for_openai, assumes every protected_data is JSON:

case "text_reasoning" if (protected_data := content.protected_data) is not None:
    pending_reasoning = json.loads(protected_data)

Possible fix

The simplest fix is to wrap the json.loads in a try/except and drop the payload when it isn't valid JSON. A sturdier fix is to forward only the reasoning payloads that this client wrote itself, so ciphertext from other providers is never sent. I'd like to know which approach you prefer, and I can open a PR with a regression test.

Package Versions

agent-framework-core 1.25.0, agent-framework-openai 1.18.1 (main @ 22b5e752), openai 3.36.1

Python Version

3.13.11

Operating System

macOS

Regression

Unknown

Additional Context

AI assistance: the issue analysis, the repro scripts and this write-up were prepared with an AI coding assistant (Claude Code). The output shown above comes from running the repros against main @ 22b5e752.

AkshayShah03 avatar Nov 12 '26 05:11 AkshayShah03

Reproduced on main @ 22b5e752. A minimal offline test that passes an assistant text_reasoning content with non-JSON protected_data to OpenAIChatCompletionClient._prepare_messages_for_openai raises json.JSONDecodeError from json.loads(protected_data) (python/packages/openai/agent_framework_openai/_chat_completion_client.py, ~line 1230). I ran only this Anthropic-style case, not the Responses-client parsing step.

Support boundary: unclear. I found no maintained doc on cross-provider reasoning history, so a maintainer should decide the scope. A raw JSONDecodeError here is still a robustness problem.

Routed to the agents/openai package owner. Whether to skip invalid payloads or forward only self-written ones is for maintainers to decide.

Run: https://github.com/microsoft/agent-framework/actions/runs/43162767848

Generated by Issue Routing for #10289 · copilot · auto · ~19 AIC · ⌖ ~1 AIC · ⊞ 5.2K · ◷

github-actions[bot] avatar Nov 12 '26 05:11 github-actions[bot]

I reproduced this on current main with both payload shapes from the report: Responses encrypted_content and an Anthropic thinking signature. I have a fix ready to open as a PR once the direction is confirmed.

Root cause: in python/packages/openai/agent_framework_openai/_chat_completion_client.py, the text_reasoning branch of _prepare_message_for_openai calls json.loads(protected_data) unconditionally. protected_data is shared across clients, and only Chat Completions writes it as reasoning_details JSON.

Proposed fix (+6/−1): catch json.JSONDecodeError there, log at debug level and skip the payload, so a foreign opaque payload is never forwarded as reasoning_details. The visible answer is still sent. JSON payloads behave exactly as before.

I went with skipping the payload rather than surfacing the reasoning text as assistant content, because forwarding another model's reasoning as visible text seemed like the bigger behavior change. Happy to switch if you prefer the other option from the issue.

Tests: a parametrized test with both payload shapes fails on main with JSONDecodeError and passes with the fix. The openai package unit tests give 810 passed, and ruff and pyright are clean. The issue's end-to-end script (Responses output → Chat Completions request) now builds the request on both paths.

Branch: https://github.com/Poyraxx/agent-framework/compare/main...fix/chat-completions-foreign-reasoning

I prepared the fix and tests with AI assistance and reviewed and verified them myself.

Poyraxx avatar Nov 16 '26 13:11 Poyraxx