-
Notifications
You must be signed in to change notification settings - Fork 5
fix(prd): parse fenced stress-test JSON and bound the walk (#927) #1040
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
e57ac55
fix(prd): parse fenced stress-test JSON and bound the walk (#927)
frankbria fccb560
Merge origin/main into fix/927-stress-test-json
frankbria 4e4d7a0
fix(prd): close the three AC gaps found in cross-family review (#927)
frankbria 5310fff
Merge branch 'main' into fix/927-stress-test-json
frankbria 6559eba
fix(prd): stop the disconnect watcher duplicating the per-event poll …
frankbria bcb4c14
Merge remote-tracking branch 'origin/fix/927-stress-test-json' into HEAD
frankbria a18b2d1
Merge branch 'main' into fix/927-stress-test-json
frankbria e0e9d08
Merge branch 'main' into fix/927-stress-test-json
frankbria File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| """Parsing JSON out of an LLM response (#927). | ||
|
|
||
| A **leaf module**: stdlib only, so every consumer can converge on it. | ||
|
|
||
| Models routinely wrap JSON in a markdown fence, and local / OpenAI-compatible | ||
| providers do it more often than Anthropic. Four call sites in this repo each | ||
| grew their own fence stripper, in two subtly different shapes — and | ||
| ``prd_stress_test`` grew none at all, so it did a raw ``json.loads``, swallowed | ||
| the failure, and reported "No ambiguities found — PRD is well-specified" after | ||
| the user had paid for the call. | ||
|
|
||
| The lesson in that bug is the reason this module exists: a parser that returns a | ||
| falsy default on failure turns a provider quirk into a clean bill of health. | ||
| ``parse_json_response`` raises instead, and callers decide what to do about it. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import re | ||
| from typing import Any | ||
|
|
||
| __all__ = ["LLMJsonError", "parse_json_response", "strip_code_fence"] | ||
|
|
||
| #: A fenced block, with or without a language tag, anywhere in the response. | ||
| #: Non-greedy so the *first* complete block wins when a model emits several. | ||
| _FENCE_RE = re.compile(r"```[ \t]*[A-Za-z0-9_+-]*[ \t]*\r?\n(.*?)```", re.DOTALL) | ||
|
|
||
|
|
||
| class LLMJsonError(ValueError): | ||
| """An LLM response could not be parsed as JSON.""" | ||
|
|
||
|
|
||
| def strip_code_fence(content: str) -> str: | ||
| """Return the contents of the first markdown fence, or the input unchanged. | ||
|
|
||
| Tolerates prose around the block ("Sure! Here you go:"), which local models | ||
| add routinely, and a fence with no language tag. | ||
| """ | ||
| match = _FENCE_RE.search(content) | ||
| return match.group(1).strip() if match else content.strip() | ||
|
|
||
|
|
||
| def parse_json_response(content: str, *, what: str = "response") -> Any: | ||
| """Parse an LLM response as JSON, stripping any markdown fence. | ||
|
|
||
| Raises: | ||
| LLMJsonError: If the content is empty or is not JSON once unfenced. | ||
| Deliberately an exception rather than a falsy default — the caller | ||
| must not be able to mistake a parse failure for an empty result. | ||
| """ | ||
| if not content or not content.strip(): | ||
| raise LLMJsonError(f"Empty {what} — nothing to parse") | ||
|
|
||
| stripped = strip_code_fence(content) | ||
| try: | ||
| return json.loads(stripped) | ||
| except (json.JSONDecodeError, TypeError) as exc: | ||
| preview = stripped[:200].replace("\n", " ") | ||
| raise LLMJsonError( | ||
| f"Could not parse {what} as JSON: {exc}. Content began: {preview!r}" | ||
| ) from exc |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.