Skip to content

fix: strip markdown code fences from JSON responses in OpenAIGenericClient#1291

Open
devmao wants to merge 1 commit intogetzep:mainfrom
devmao:fix/strip-code-fence-json-response
Open

fix: strip markdown code fences from JSON responses in OpenAIGenericClient#1291
devmao wants to merge 1 commit intogetzep:mainfrom
devmao:fix/strip-code-fence-json-response

Conversation

@devmao
Copy link

@devmao devmao commented Mar 3, 2026

Summary

Some LLMs (especially non-OpenAI models accessed via OpenRouter or other proxy backends) wrap their JSON output in markdown code fences — e.g. json\n{...}\n — even when response_format={"type": "json_object"} is requested. This causes json.loads() to raise a JSONDecodeError and the call to fail.

This fix strips a leading code fence and its closing backticks from the response content before parsing, making OpenAIGenericClient robust to this behaviour.

Type of Change

  • Bug fix

Objective

N/A (bug fix)

Testing

  • Unit tests added/updated
  • Integration tests added/updated
  • All existing tests pass

Added tests/llm_client/test_openai_generic_client.py with four cases:

  • plain JSON (no fence) — unchanged
  • json\n{...}\n fence
  • \n{...}\n plain fence (no language tag)
  • fence with extra surrounding whitespace

Breaking Changes

  • This PR contains breaking changes

Checklist

  • Code follows project style guidelines (make lint passes)
  • Self-review completed
  • Documentation updated where necessary
  • No secrets or sensitive information committed

Related Issues

N/A

…lient

Some LLMs (especially via OpenRouter or other proxy backends) wrap their
JSON response in markdown code fences (e.g. ```json ... ```) even
when response_format={"type": "json_object"} is requested, causing
json.loads() to fail.

Strip a leading code fence and its closing backticks before parsing so
the client is robust to this behaviour.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant