Skip to content

fix(bedrock): strip think tags and fix reask crash for reasoning models - #2287

Closed
octo-patch wants to merge 1 commit into
567-labs:mainfrom
octo-patch:fix/issue-2076-bedrock-think-tags
Closed

octo-patch wants to merge 1 commit into
567-labs:mainfrom
octo-patch:fix/issue-2076-bedrock-think-tags

Conversation

@octo-patch

Copy link
Copy Markdown
Contributor

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_JSON is used with from_bedrock() and a validation error fires, reask_md_json tries to access response.choices[0]. Bedrock responses are plain dicts (no .choices), so this raises:

AttributeError: 'dict' object has no attribute 'choices'

Because dict also 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 by BEDROCK_JSON mode): strip <think>…</think> before code-block extraction and JSON parse.
  • _extract_text_content (used by parse_json / MD_JSON mode): 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.py cover:

  • Plain JSON with no think tags (regression guard)
  • Think tags before JSON
  • Think tags that themselves contain braces (the core failure case)
  • Think tags combined with markdown code-fence responses
  • Multi-line think blocks
  • _extract_text_content stripping for the MD_JSON path
  • reask_md_json with a Bedrock dict response (asserts correct Bedrock-format correction message)
  • reask_md_json with a normal OpenAI response (unchanged behavior)
9 passed in 26.82s

…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>
@jxnl

jxnl commented Jun 29, 2026

Copy link
Copy Markdown
Collaborator

Reviewed for merge readiness. This is the right scoped PR for #2076 and should stay open: it handles both the <think>...</think> parsing failure and the Bedrock dict retry crash. It is currently conflicting, mostly around changelog/current parser code, so it needs a rebase/refresh and CI before merge. One cleanup I would make while rebasing: avoid duplicating think-tag stripping helpers across modules unless both are actually used.

jxnl added a commit that referenced this pull request Aug 3, 2026
## 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 -->

jxnl commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator

Rebuilt this on the current v2 Bedrock handler in #2514, with credit to @octo-patch. Current main already contains the Bedrock-dict reask path; the canonical PR replaces the remaining provider-local JSON regex with the shared last-complete-JSON extractor, preserves escaped content, and adds caller-input immutability regressions. Keeping this PR open until #2514 reaches main, then it can close as superseded.

jxnl commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator

Closing this PR as superseded by #2514. Current main already contains the Bedrock dict-reask correction from this patch; #2514 carries the remaining reasoning-prefixed JSON fix on the current v2 handler by reusing the shared JSON extractor, with deterministic regression coverage and a fully green matrix. Credit is retained in #2514. Issue #2076 remains open until the fix reaches main.

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.

Allow MD_JSON for bedrock client

3 participants