pipecat icon indicating copy to clipboard operation
pipecat copied to clipboard

AWSBedrockLLMService ignores tool_choice="required"

Open chaitanya0305 opened this issue 1 week ago • 2 comments

Summary

AWSBedrockLLMService ignores tool_choice="required". It maps the context's tool_choice to the Converse API's toolConfig.toolChoice for "auto" and for a named function, but has no case for "required". So no toolChoice is sent, Bedrock falls back to auto, and the model can answer in plain text instead of calling a tool. Nothing reports an error.

This breaks flows that depend on a forced tool call (structured extraction, routing, function-only turns) set through LLMContext(tool_choice="required") or LLMSetToolChoiceFrame("required").

Reproduction

Run on current main (62bbb9b2e). No AWS credentials or network needed: the Converse call is patched and the request is printed.

import asyncio
from unittest.mock import AsyncMock, patch

from pipecat.adapters.llm.schemas.function_schema import FunctionSchema
from pipecat.adapters.llm.schemas.tools_schema import ToolsSchema
from pipecat.processors.aggregators.llm_context import LLMContext
from pipecat.services.aws.llm import AWSBedrockLLMService


async def run(tool_choice):
    svc = AWSBedrockLLMService(model="anthropic.claude-test", aws_region="us-east-1",
                               aws_access_key="x", aws_secret_key="y")
    tools = ToolsSchema(standard_tools=[FunctionSchema(
        name="get_weather", description="w", properties={"city": {"type": "string"}}, required=["city"])])
    ctx = LLMContext(messages=[{"role": "user", "content": "weather in Paris?"}],
                     tools=tools, tool_choice=tool_choice)

    async def stream():
        yield {"messageStop": {"stopReason": "end_turn"}}

    m = AsyncMock(return_value={"stream": stream()})
    with patch.object(svc, "_create_converse_stream", m):
        await svc._process_context(ctx)
    return m.call_args.args[1].get("toolConfig", {}).get("toolChoice", "<absent>")


async def main():
    for tc in ["auto", "required", {"type": "function", "function": {"name": "get_weather"}}]:
        print(repr(tc), "->", await run(tc))

asyncio.run(main())

Actual

'auto' -> {'auto': {}}
'required' -> <absent>
{'type': 'function', 'function': {'name': 'get_weather'}} -> {'tool': {'name': 'get_weather'}}

Expected

'required' -> {'any': {}}

In the Converse API, ToolChoice.any means "the model must request at least one tool (no text is generated)", which is the equivalent of OpenAI's "required".

Cause

_process_context in src/pipecat/services/aws/llm.py (around line 531) has branches for "auto", "none" (skipped on purpose, as Converse has no "none" option) and a named function, and nothing for "required". BedrockLLMAdapter passes tool_choice through unchanged and leaves the conversion to the service, so this is the only place to fix.

Proposed fix

Add elif tool_choice == "required": tool_config["toolChoice"] = {"any": {}} (two lines), plus a parametrized test over auto / required / named function in tests/test_aws_bedrock_llm_context_conversion.py. "auto", "none" and named-function behaviour is unchanged.

I used an AI coding assistant (Claude) to find and analyse this; I reproduced it and checked the fix myself.

I've tested a fix with a regression test: https://github.com/chaitanya0305/pipecat/compare/main...chaitanya0305:pipecat:fix/bedrock-tool-choice-required. If this is accepted, I'll open the PR straight away.

chaitanya0305 avatar Nov 25 '26 14:11 chaitanya0305

Reproduced on main (261d8debd). I also ran your branch (a47614673). It sends {'any': {}} for "required", and tests/test_aws_bedrock_llm_context_conversion.py passes there (8 tests, 5 on main).

I added "none" to the repro, and it has the same problem from the other side:

'auto'                                                       tools sent=['get_weather'] toolChoice={'auto': {}}
'required'                                                   tools sent=['get_weather'] toolChoice=<absent>
'none'                                                       tools sent=['get_weather'] toolChoice=<absent>
{'type': 'function', 'function': {'name': 'get_weather'}}    tools sent=['get_weather'] toolChoice={'tool': {'name': 'get_weather'}}

With "none" the request still carries the full tool list and no toolChoice. The Converse docs give auto as the default, so the request is the same as "auto" and the model can still call get_weather. Your branch leaves this as it is (same output for "none"). Converse has no none choice, so the way to get it is to stop offering the tools. The service already has a path for that. When the history has tool blocks but no tools are set, it sends only the placeholder tool (aws/llm.py:522-524). For "none", the service could skip toolConfig when the history has no tool blocks, and send only the placeholder when it does. I haven't run that against Bedrock itself, so it needs checking that Converse accepts the placeholder-only config with real toolUse blocks in the history. It's the same shape the service already sends in that case, though.

For whoever picks this up: the same "context tool_choice is translated per service and some values are dropped" gap is open in other services too, each with its own fix:

  • Anthropic: #6404 (AnthropicLLMService ignores tool_choice entirely), with PRs #6474 and #6749. #6474 maps "none" to {"type": "none"} and "required" to {"type": "any"}.
  • OpenAI Responses: #5641, with PRs #5644 and #5645.
  • Gemini: no issue that I found, but PRs #3545 and #4039 add it. On main, GeminiLLMAdapter doesn't read tool_choice, and GoogleLLMService only sends the tool_config passed to its constructor (google/llm.py:592-594).

AWSBedrockLLMAdapter passes tool_choice straight through and leaves the mapping to the service (bedrock_adapter.py:156-159). So the fix belongs in aws/llm.py as you have it, unless the maintainers want the mapping in each adapter, the way OpenAILLMAdapter does it with openai_from_llm_context_tool_choice.

Script (your repro plus "none" and the tool names sent; no AWS credentials needed)
import asyncio
from unittest.mock import AsyncMock, patch

from pipecat.adapters.llm.schemas.function_schema import FunctionSchema
from pipecat.adapters.llm.schemas.tools_schema import ToolsSchema
from pipecat.processors.aggregators.llm_context import LLMContext
from pipecat.services.aws.llm import AWSBedrockLLMService


async def request_for(tool_choice):
    svc = AWSBedrockLLMService(model="anthropic.claude-test", aws_region="us-east-1",
                               aws_access_key="x", aws_secret_key="y")
    tools = ToolsSchema(standard_tools=[FunctionSchema(
        name="get_weather", description="w", properties={"city": {"type": "string"}}, required=["city"])])
    ctx = LLMContext(messages=[{"role": "user", "content": "weather in Paris?"}],
                     tools=tools, tool_choice=tool_choice)

    async def stream():
        yield {"messageStop": {"stopReason": "end_turn"}}

    m = AsyncMock(return_value={"stream": stream()})
    with patch.object(svc, "_create_converse_stream", m):
        await svc._process_context(ctx)
    return m.call_args.args[1].get("toolConfig", {})


async def main():
    for tc in ["auto", "required", "none", {"type": "function", "function": {"name": "get_weather"}}]:
        cfg = await request_for(tc)
        names = [t["toolSpec"]["name"] for t in cfg.get("tools", []) if "toolSpec" in t]
        print(f"{tc!r:60} tools sent={names} toolChoice={cfg.get('toolChoice', '<absent>')}")

asyncio.run(main())

ayushmnnit avatar Nov 26 '26 03:11 ayushmnnit

Thanks @ayushmnnit for confirming this and running the branch. Good catch on "none". I'll check how Converse handles a placeholder-only toolConfig when the history already has toolUse blocks, and cover "none" in the same fix with a test.

chaitanya0305 avatar Nov 26 '26 06:11 chaitanya0305