Repository navigation
fix(bedrock): strip think tags and fix reask crash for reasoning models - #2287
octo-patch wants to merge 1 commit into
Conversation
…ls (fixes 567-labs#2076) Reasoning models on Bedrock (e.g. Kimi K2 Thinking) prefix their output with a <think>...</think> block before the actual JSON. The naive first-brace / last-brace extraction in extract_json_from_codeblock picks up braces inside the think block and produces invalid JSON, causing spurious retries that eventually time out. Two changes fix this: 1. Strip <think>...</think> blocks in parse_bedrock_json (BEDROCK_JSON mode) and in _extract_text_content (MD_JSON mode via parse_json) before any JSON extraction is attempted. 2. Fix reask_md_json so it no longer crashes with AttributeError: 'dict' object has no attribute 'choices' when a Bedrock converse dict is passed as the response during retries. Bedrock dicts lack .choices and were incorrectly falling into the stream-response branch; the Bedrock dict case is now checked first. Co-Authored-By: Octopus <liyuan851277048@icloud.com>
|
Reviewed for merge readiness. This is the right scoped PR for #2076 and should stay open: it handles both the |
## Summary - accumulate declared, nested, and unknown numeric OpenAI/Anthropic usage fields across retries while preserving non-numeric metadata - add corrective feedback when a Responses API retry receives no tool call - preserve raw iterable type hints through sync and async v2 parallel-tool wrappers - strengthen API-key-free coverage for current and future SDK usage counters ## Consolidated and superseded items - closes #2493 - consolidates contributor work from #2498, #2500, and #2501 with original commit authorship preserved - supersedes #2497 because it drops unknown `model_extra` counters - supersedes #2499 because its hand-maintained provider field lists would drift as SDKs evolve ## Validation - focused changed-surface suite: `110 passed` - broad offline v2/coverage suite: `2368 passed, 91 skipped, 73 deselected` - Ruff check and format check: passed - scoped `ty check`: passed - `uv lock --check`: passed - pre-commit hooks and `git diff --check`: passed The 73 deselected tests require live provider credentials. An unfiltered local run confirmed its 22 failures were provider network connections in the restricted environment; GitHub provider jobs remain the authoritative validation for those paths. ## Intentionally skipped - provider additions or expansions: #2436, #2435, #2423, #2409, #2384, #2322, #2306, #2298, #2283, #2168, #2086; issues #2408, #2383, #2365, #2260, #2084, #2076 - broad architecture, product, security, or streaming decisions: #2394, #2392, #2357, #2356, #2355, #2351, #2321, #2307, #2287, #2263; issues #2479, #2403, #2393, #2391, #2316, #2272, #2056 - dependency batch: #2433 - nontrivial examples and editorial/resource additions: #2468, #2405, #2401, #2354, #2346, #2311, #2305; issue #2404 These remain open because they need dedicated product, architecture, provider, security, dependency, or editorial review and are not required for the `1.15.5` patch release. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes retry usage totals and reask message content on failure paths; scope is limited and heavily covered by tests, with no auth or data-store changes. > > **Overview** > Bundles three v2 retry and wrapper fixes for a patch release. > > **Retry usage accounting** replaces hand-maintained token field sums with generic `_accumulate_models` on Pydantic usage objects. Numeric fields (including nested models and `model_extra` counters) add across retries; booleans and other non-numeric metadata are not treated as billable. OpenAI and Anthropic paths share this logic. > > **OpenAI Responses reask** appends a user correction when `RESPONSES_TOOLS` validation fails but the output has no tool calls (e.g. reasoning-only), so retries include feedback instead of repeating the same request. > > **Parallel tools** in `patch_v2` skips `prepare_response_model` and does not replace `response_model` with the handler’s prepared wrapper for parallel modes, keeping raw `Iterable[...]` hints so schemas and parsed results include every member type. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit bbddca1. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY -->
|
Rebuilt this on the current v2 Bedrock handler in #2514, with credit to @octo-patch. Current |
|
Closing this PR as superseded by #2514. Current |
Fixes #2076
Problem
Reasoning models on AWS Bedrock (e.g. Kimi K2 Thinking) prefix their text response with a
<think>...</think>block before emitting the actual JSON. The JSON extractor (extract_json_from_codeblock) finds the first{and last}in the whole response, which may land inside the think block and produce invalid JSON. This causes repeated validation failures and costly retries.A second related bug: when
Mode.MD_JSONis used withfrom_bedrock()and a validation error fires,reask_md_jsontries to accessresponse.choices[0]. Bedrock responses are plain dicts (no.choices), so this raises:Because
dictalso lacks.choices, Bedrock responses were incorrectly hitting the stream-response branch and the assistant turn was silently dropped from the retry message list.Solution
1. Think-tag stripping (
instructor/processing/function_calls.py)parse_bedrock_json(used byBEDROCK_JSONmode): strip<think>…</think>before code-block extraction and JSON parse._extract_text_content(used byparse_json/MD_JSONmode): strip think tags when the completion is a Bedrock dict.2. Bedrock-aware reask (
instructor/providers/openai/utils.py)reask_md_json: check for Bedrock dict responses (isinstance(response, dict) and "output" in response) before the stream-response guard so they are handled with the correct Bedrock message format instead of crashing.Testing
9 new unit tests in
tests/llm/test_bedrock/test_think_tags.pycover:_extract_text_contentstripping for the MD_JSON pathreask_md_jsonwith a Bedrock dict response (asserts correct Bedrock-format correction message)reask_md_jsonwith a normal OpenAI response (unchanged behavior)