Skip to content

fix(bedrock): preserve thinking blocks in multi-turn tool use - #1873

Merged
EItanya merged 1 commit into
kagent-dev:mainfrom
moezdil:fix/bedrock-thinking-tool-use
Jun 4, 2026
Merged

EItanya merged 1 commit into
kagent-dev:mainfrom
moezdil:fix/bedrock-thinking-tool-use

Conversation

@moezdil

@moezdil moezdil commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1870

When extended thinking is active, Bedrock returns thinking content blocks together with tool use blocks.

The API requires these blocks to be sent back unmodified in the next request.

Without them, Bedrock returns a ValidationException with toolUse.input is empty.

See the API requirement: https://docs.aws.amazon.com/bedrock/latest/userguide/claude-messages-extended-thinking.html

Tests added for thinking block round-trip and temperature/top_p exclusion.

cc @marcofranssen @supreme-gg-gg @EItanya

Copilot AI review requested due to automatic review settings May 15, 2026 14:19
@github-actions github-actions Bot added the bug Something isn't working label May 15, 2026
@github-actions github-actions Bot added bug Something isn't working and removed bug Something isn't working labels May 15, 2026
@moezdil
moezdil force-pushed the fix/bedrock-thinking-tool-use branch from 3eeb362 to 78e2467 Compare May 15, 2026 14:23

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR addresses Amazon Bedrock (Converse API) extended thinking + tool-use multi-turn behavior by preserving Bedrock “reasoning/thinking” content blocks across turns so subsequent requests validate correctly, and it also adds Helm chart support for exposing controller metrics (service, RBAC, and optional ServiceMonitor).

Changes:

  • Bedrock: parse/accumulate reasoning content blocks (non-streaming + streaming) and round-trip them back into subsequent requests; omit temperature/top_p when thinking is enabled.
  • Helm: add controller.metrics.* values and templates for a dedicated metrics Service, optional ServiceMonitor, and RBAC to support secure metrics scraping.
  • Tests: add unit tests for thinking-block round-trip conversion and add Helm unittest coverage for metrics resources.

Reviewed changes

Copilot reviewed 14 out of 14 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
helm/kagent/values.yaml Adds configurable controller.metrics settings (port, secure mode, ServiceMonitor knobs).
helm/kagent/templates/controller-deployment.yaml Exposes an optional metrics container port when metrics are enabled.
helm/kagent/templates/controller-configmap.yaml Wires metrics bind address + secure flag into controller config when enabled.
helm/kagent/templates/controller-metrics-service.yaml Adds a dedicated ClusterIP Service for metrics.
helm/kagent/templates/controller-servicemonitor.yaml Adds an optional Prometheus Operator ServiceMonitor for controller metrics.
helm/kagent/templates/rbac/metrics-auth-role.yaml Adds ClusterRole/Binding for delegated auth (TokenReview/SAR) when secure metrics enabled.
helm/kagent/templates/rbac/metrics-reader-role.yaml Adds ClusterRole allowing GET /metrics when metrics enabled.
helm/kagent/tests/controller-deployment_test.yaml Ensures metrics port + configmap env are rendered when enabled and not otherwise.
helm/kagent/tests/controller-service_test.yaml Ensures main controller Service does not gain extra ports when metrics enabled.
helm/kagent/tests/controller-metrics-service_test.yaml Tests rendering and shape of the dedicated metrics Service.
helm/kagent/tests/controller-servicemonitor_test.yaml Tests ServiceMonitor conditional rendering and TLS settings.
helm/kagent/tests/metrics-rbac_test.yaml Tests metrics RBAC templates render conditions and rule contents.
go/adk/pkg/models/bedrock.go Implements reasoning/thinking block parsing (streaming + non-streaming), round-trip conversion, and inference-config adjustments under thinking.
go/adk/pkg/models/bedrock_test.go Adds a thinking-block conversion test and a minimal thinking/temperature test case.
Comments suppressed due to low confidence (1)

go/adk/pkg/models/bedrock.go:383

  • In streaming mode the final Parts ordering does not preserve the original Bedrock content-block order: all thinking parts are prepended, then all text is concatenated, then all tool calls are appended. Bedrock requires reasoning/tool blocks to be sent back in the same order as returned; reordering by type can break multi-turn tool-use validation. Consider accumulating completed blocks keyed by ContentBlockIndex (including text/tool/thinking) and assembling finalParts by increasing index (or by the exact stop/start sequence) instead of grouping by kind.
	// thinking parts first; block order must match what Bedrock returned.
	finalParts := []*genai.Part{}
	finalParts = append(finalParts, completedThinkingParts...)
	text := aggregatedText.String()
	if text != "" {
		finalParts = append(finalParts, &genai.Part{Text: text})
	}
	// Add completed tool calls
	finalParts = append(finalParts, completedToolCalls...)


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread go/adk/pkg/models/bedrock_test.go Resolved
Comment thread helm/kagent/values.yaml Resolved
@moezdil
moezdil force-pushed the fix/bedrock-thinking-tool-use branch 3 times, most recently from 3c9ede6 to 98103aa Compare May 15, 2026 14:34
@marcofranssen

Copy link
Copy Markdown
Contributor

I was doing an atempt here as well, but couldn't get it to work just yet, allthough there might be parts useful for this PR.

#1872

@moezdil
moezdil force-pushed the fix/bedrock-thinking-tool-use branch 3 times, most recently from 942405c to bf0a8e7 Compare May 15, 2026 19:35
@EItanya

EItanya commented May 18, 2026

Copy link
Copy Markdown
Contributor

I was doing an atempt here as well, but couldn't get it to work just yet, allthough there might be parts useful for this PR.

#1872

@marcofranssen any chance you can give this PR a smoke test before I review/approve?

@moezdil
moezdil force-pushed the fix/bedrock-thinking-tool-use branch from 06a04b0 to 9ef3656 Compare May 22, 2026 15:58

@EItanya EItanya left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you please separate the tracing changes into a different PR. The changes make sense but they are unrelated. Separately I think it should be optional so as to not break current flows

@moezdil
moezdil force-pushed the fix/bedrock-thinking-tool-use branch 3 times, most recently from 150daf2 to 04b1f0e Compare June 3, 2026 20:51
EItanya
EItanya previously approved these changes Jun 3, 2026
When extended thinking is active, Bedrock returns thinking content blocks
together with tool use blocks. The API requires these blocks to be sent
back unmodified in the next request. Without them, Bedrock returns a
ValidationException with toolUse.input is empty.

Only emit thinking blocks for the last assistant turn before tool results.
Sending them in all turns causes token counts to compound across long sessions.

Truncate tool results in historical turns to 2000 chars. Older turns do
not need full fidelity for large kubectl or YAML outputs.

Extract inference config construction into a testable helper so that
the temperature/top_p exclusion logic for extended thinking can be
exercised directly without mocking the AWS Bedrock client.

Fixes #1870

Signed-off-by: mesutoezdil <mesudozdil@gmail.com>
@moezdil
moezdil force-pushed the fix/bedrock-thinking-tool-use branch from 04b1f0e to 0f4c548 Compare June 3, 2026 21:02
@EItanya
EItanya merged commit 8e390a6 into kagent-dev:main Jun 4, 2026
21 checks passed
social4hyq pushed a commit to social4hyq/homebrew-core that referenced this pull request Sep 20, 2026
kagent 0.9.6

Created-by: HarmonybrewBot
Commit-by: HarmonybrewBot
Merged-by: HarmonybrewBot
Description: Created by `brew bump`

---

Created with `brew bump-formula-pr`.<details>
  <summary>release notes</summary>
  <pre><!-- Release notes generated using configuration in .github/release.yml at v0.9.6 -->

## What's Changed
### Features
* feat(mcp): expose agents as MCP resource with change notifications by @onematchfox in kagent-dev/kagent#1856
* feat(adk): propagate parent + root context_id headers on outbound A2A calls by @Prefix in kagent-dev/kagent#1927
### Bug Fixes
* fix(compaction): preserve namespaced tool names in LLM summarizer prompt by @yashrajshuklaaa in kagent-dev/kagent#1907
* fix: preserve Ollama streaming tool calls by @andreivince in kagent-dev/kagent#1948
* fix(bedrock): preserve thinking blocks in multi-turn tool use by @mesutoezdil in kagent-dev/kagent#1873
* fix(translator): forward Anthropic config fields to model config by @mesutoezdil in kagent-dev/kagent#1962
* fix(openai): apply ReasoningEffort in applyOpenAIConfig by @mesutoezdil in kagent-dev/kagent#1959
* fix(mcp): handle null tools field in MCP server configs by @mesutoezdil in kagent-dev/kagent#1960
### Documentation
* docs(api): add field descriptions for BYO agent spec by @marians in kagent-dev/kagent#1969
### Other Changes
* Fix/1945 fix for wrong validation being triggered by @gauravshinde1729 in kagent-dev/kagent#1946
* openclaw substrate support  by @peterj in kagent-dev/kagent#1939
* chore(deps): bump the npm-minor-patch group in /ui with 14 updates by @dependabot[bot] in kagent-dev/kagent#1951
* Link fixes by @kristin-kronstain-brown in kagent-dev/kagent#1950
* RemoteMCPServer TLS + companion-Secret API + plaintext egress rewrite by @iplay88keys in kagent-dev/kagent#1905

## New Contributors
* @yashrajshuklaaa made their first contribution in kagent-dev/kagent#1907
* @andreivince made their first contribution in kagent-dev/kagent#1948
* @kristin-kronstain-brown made their first contribution in kagent-dev/kagent#1950
* @Prefix made their first contribution in kagent-dev/kagent#1927
* @marians made their first contribution in kagent-dev/kagent#1969

**Full Changelog**: https://github.com/kagent-dev/kagent/compare/v0.9.5...v0.9.6</pre>
  <p>View the full release notes at <a href="https://github.com/kagent-dev/kagent/releases/tag/v0.9.6">https://github.com/kagent-dev/kagent/releases/tag/v0.9.6</a>.</p>
</details>
<hr>

See merge request: Harmonybrew/homebrew-core!10637
hironow pushed a commit to hironow/kagent that referenced this pull request Nov 20, 2026
Fixes kagent-dev#2946

## Summary

When the Go ADK rebuilds the Converse history for Bedrock, it cuts every
tool result except the most recent one to 2000 bytes:

```go
func truncateToolResult(s string, maxLen int) string {
	if len(s) <= maxLen {
		return s
	}
	return s[:maxLen] + fmt.Sprintf("\n... [truncated, %d chars omitted]", len(s)-maxLen)
}
```

Anything an agent reads through a tool is therefore only fully visible
to the model until its next tool call. As kagent-dev#2946 describes, a loaded
SKILL.md loses its later instructions while the agent is following them.
No other adapter edits history, including the Python runtime's Bedrock
adapter.

The cut came with kagent-dev#1873 (from kagent-dev#1872) as a guard against prompt growth,
when the Go runtime did not yet honour context compaction; kagent-dev#2790 added
that. Only kagent-dev#1873's thinking-block rule is required by Bedrock's API.

## Change

Remove the cut so tool results are sent unmodified. The thinking-block
handling from kagent-dev#1873 is unchanged. This also drops the byte-based
slicing, which could split multi-byte characters.

Long Bedrock sessions without compaction will now send more input
tokens, as every other provider does. `spec.kagent.compaction` on the
Harness bounds the prompt; a Bedrock-specific limit could follow if
still wanted.

## Tests

`TestHistoricalToolResultsSentInFull` replaces the two tests that
asserted the cut. It checks that an earlier multi-byte tool result
longer than the old limit reaches the Converse messages byte for byte.
Without the fix:

```
bedrock_test.go:711: earlier tool result was modified: got 2036 bytes, want 8600
```

`TestThinkingOnlyInLastAssistantTurn` still passes. `go test ./adk/...`,
`go test -race ./adk/pkg/models/` and `make -C go lint` (0 issues) pass
locally.

Live test on Kind (`main` at `5d192ea1`, Go ADK harness on Substrate):
two Agents differing only in runtime image, with a Bedrock
`ModelConfig`. The agent fetched a pod's YAML (5,843 bytes), made one
more tool call, then was asked for
`status.containerStatuses[0].imageID`:

| | `main` | this PR |
|---|---|---|
| YAML in the next request | 2,036 bytes, truncated | 5,843 bytes |
| Answer | "not visible in the provided YAML" | correct digest |

<details><summary>Prompt used</summary>

> Do these steps one tool call at a time, never in parallel. 1) Call
k8s_get_resources to list pods in namespace kagent. 2) Call
k8s_get_resource_yaml for the pod whose name starts with kagent-tools in
namespace kagent. 3) Call k8s_get_resources to list services in
namespace kagent. 4) Finally, answer: what is the exact value of
status.containerStatuses[0].imageID in that pod YAML? Quote it exactly,
or say you cannot see it.

</details>

Signed-off-by: GuilleQP <36505071+GuilleQP@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG]: ModelConfig Bedrock Thinking not working.

4 participants