Skip to content

AnthropicBedrock handles streaming errors differently from Anthropic client #866

@deepankarm

Description

@deepankarm

When a message sequence has a tool_use without a following tool_result:

  1. Anthropic client fails fast with a BadRequestError before stream creation.
  2. AnthropicBedrock client allows stream creation but raises a ValueError during streaming.

The bedrock client should also fail fast before creating the stream.

# Define list of messages with a `tool_use` not following a `tool_result`
msgs = [
    {"role": "user", "content": "draw a line"},
    {
        "role": "assistant",
        "content": [
            {"text": "Sure, I can help you draw a line", "type": "text"},
            {"id": "123", "input": {"color": "red"}, "name": "draw_line", "type": "tool_use"},
        ],
    },
    {"role": "user", "content": "draw a circle"},
]

tools = [...] # non-empty list of tools

Anthropic client doesn't allow stream creation (BadRequestError)

from anthropic import AsyncAnthropic

async with AsyncAnthropic(api_key=anthropic_api_key) as client:
    stream = await client.messages.create(
        max_tokens=1024,
        messages=msgs,
        model="claude-3-5-haiku",
        tools=tools,
        stream=True,
    )
    print("stream created!")
    async for message in stream:
        print(message)

"""
BadRequestError: Error code: 400 - {'type': 'error', 'error': {'type': 'invalid_request_error', 'message': 'messages.2: Did not find 1 `tool_result` block(s) at the beginning of this message. Messages following `tool_use` blocks must begin with a matching number of `tool_result` blocks.'}}
"""

AnthropicBedrock client allows stream creation and raises ValueError during streaming

from anthropic import AsyncAnthropicBedrock

async with AsyncAnthropicBedrock() as client:
    stream = await client.messages.create(
        max_tokens=1024,
        messages=msgs,
        model="us.anthropic.claude-3-5-haiku-20241022-v1:0",
        tools=tools,
        stream=True,
    )
    print("stream created!")
    async for message in stream:
        print(message)

"""
stream created!

ValueError: Bad response code, expected 200: {'status_code': 400, 'headers': {':exception-type': 'validationException', ':content-type': 'application/json', ':message-type': 'exception'}, 'body': b'{"message":"messages.2: Did not find 1 `tool_result` block(s) at the beginning of this message. Messages following `tool_use` blocks must begin with a matching number of `tool_result` blocks."}'}
"""

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions