Skip to content

🐛 Bug Report: Bedrock instrumentation does not record top_k / stop_sequences, and records no request parameters at all when the call fails #4557

Open

Description

@armanunix

Which component is this bug for?

Bedrock Instrumentation

📜 Description

Two gaps in how opentelemetry-instrumentation-bedrock records request parameters:

1. top_k and stop_sequences are never recorded.

  • converse / converse_stream: set_converse_model_span_attributes (span_utils.py) reads only topP, temperature and maxTokens from inferenceConfig. inferenceConfig.stopSequences is ignored, and so is additionalModelRequestFields (where top_k goes for Anthropic models on Converse).
  • invoke_model / invoke_model_with_response_stream with an Anthropic Messages body: _set_anthropic_messages_span_attributes reads only top_p, temperature and max_tokens; the body's top_k and stop_sequences are ignored.

So gen_ai.request.top_k and gen_ai.request.stop_sequences are never set, although they were sent.

2. A failed call records no request parameters.
All request attributes are set in _handle_call / the converse handlers after the response is received. When the call raises (e.g. ValidationException, ThrottlingException), the wrapper records the exception and re-raises, so the error span has only provider, operation and model: no max_tokens, temperature, top_p etc. Those are exactly the spans where the request parameters are most useful.

👟 Reproduction steps

Self-contained: a botocore before-send hook answers the requests (no AWS account or network needed). Every call sends max_tokens, temperature, top_p, top_k and stop_sequences; each API is called once successfully and once with a 400 ValidationException.

import json, logging, os
logging.disable(logging.WARNING)
os.environ["TRACELOOP_TRACE_CONTENT"] = "true"

import boto3
from botocore.awsrequest import AWSResponse
from botocore.config import Config
from opentelemetry.sdk.trace import SpanProcessor, TracerProvider
from opentelemetry.instrumentation.bedrock import BedrockInstrumentor

MODEL = "anthropic.claude-3-haiku-20240307-v1:0"

class Raw:
    def __init__(self, data): self.data = data
    def stream(self, *a, **k): yield self.data
    def read(self, amt=None): return self.data
    def close(self): pass
    release_conn = close

CONVERSE_OK = {"output": {"message": {"role": "assistant", "content": [{"text": "hello"}]}}, "stopReason": "end_turn",
               "usage": {"inputTokens": 3, "outputTokens": 1, "totalTokens": 4}, "metrics": {"latencyMs": 1}}
INVOKE_OK = {"id": "m", "type": "message", "role": "assistant", "model": "m", "stop_reason": "end_turn",
             "content": [{"type": "text", "text": "hello"}], "usage": {"input_tokens": 3, "output_tokens": 1}}
fail = {"on": False}

def before_send(request, **_):
    if fail["on"]:
        return AWSResponse(request.url, 400, {"x-amzn-ErrorType": "ValidationException:http://internal.amazon.com/",
                                              "content-type": "application/json"}, Raw(b'{"message": "bad request"}'))
    data = json.dumps(CONVERSE_OK if request.url.endswith("/converse") else INVOKE_OK).encode()
    return AWSResponse(request.url, 200, {"content-type": "application/json", "content-length": str(len(data))}, Raw(data))

class Rec(SpanProcessor):
    def __init__(self): self.ended = []
    def on_end(self, span): self.ended.append(span)

rec = Rec()
provider = TracerProvider(); provider.add_span_processor(rec)
BedrockInstrumentor().instrument(tracer_provider=provider)
client = boto3.client("bedrock-runtime", region_name="us-east-1", aws_access_key_id="x",
                      aws_secret_access_key="x", config=Config(retries={"total_max_attempts": 1}))
client.meta.events.register("before-send.bedrock-runtime.*", before_send)

def converse():
    client.converse(modelId=MODEL, messages=[{"role": "user", "content": [{"text": "hi"}]}],
                    inferenceConfig={"maxTokens": 50, "temperature": 0.3, "topP": 0.9, "stopSequences": ["END"]},
                    additionalModelRequestFields={"top_k": 40})

def invoke():
    client.invoke_model(modelId=MODEL, body=json.dumps({
        "anthropic_version": "bedrock-2023-05-31", "max_tokens": 50, "temperature": 0.3, "top_p": 0.9,
        "top_k": 40, "stop_sequences": ["END"],
        "messages": [{"role": "user", "content": [{"type": "text", "text": "hi"}]}]}))["body"].read()

WANTED = ["gen_ai.request.max_tokens", "gen_ai.request.temperature", "gen_ai.request.top_p",
          "gen_ai.request.top_k", "gen_ai.request.stop_sequences"]
for name, fn in [("converse", converse), ("invoke_model", invoke)]:
    for failing in (False, True):
        fail["on"] = failing; rec.ended.clear()
        try:
            fn(); outcome = "succeeded"
        except Exception as e:
            outcome = f"failed ({type(e).__name__})"
        attrs = rec.ended[0].attributes
        print(f"--- {name}, call {outcome}")
        for k in WANTED:
            v = attrs.get(k, "MISSING")
            print(f"  {k:32s} {list(v) if isinstance(v, tuple) else v}")

Output:

boto3 1.43.108 | opentelemetry-instrumentation-bedrock 0.62.4
all calls send: max_tokens=50, temperature=0.3, top_p=0.9, top_k=40, stop_sequences=['END']
--- converse, call succeeded
  gen_ai.request.max_tokens        50
  gen_ai.request.temperature       0.3
  gen_ai.request.top_p             0.9
  gen_ai.request.top_k             MISSING
  gen_ai.request.stop_sequences    MISSING
--- converse, call failed (ValidationException)
  gen_ai.request.max_tokens        MISSING
  gen_ai.request.temperature       MISSING
  gen_ai.request.top_p             MISSING
  gen_ai.request.top_k             MISSING
  gen_ai.request.stop_sequences    MISSING
--- invoke_model, call succeeded
  gen_ai.request.max_tokens        50
  gen_ai.request.temperature       0.3
  gen_ai.request.top_p             0.9
  gen_ai.request.top_k             MISSING
  gen_ai.request.stop_sequences    MISSING
--- invoke_model, call failed (ValidationException)
  gen_ai.request.max_tokens        MISSING
  gen_ai.request.temperature       MISSING
  gen_ai.request.top_p             MISSING
  gen_ai.request.top_k             MISSING
  gen_ai.request.stop_sequences    MISSING

👍 Expected behavior

All five request parameters are recorded (gen_ai.request.max_tokens=50, temperature=0.3, top_p=0.9, top_k=40, stop_sequences=["END"]) for both converse and invoke_model, whether the call succeeds or fails.

👎 Actual Behavior with Screenshots

On success, gen_ai.request.top_k and gen_ai.request.stop_sequences are missing for both APIs. On failure, none of the request parameters are recorded.

🤖 Python Version

3.12

📃 Provide any additional context for the Bug.

opentelemetry-instrumentation-bedrock 0.62.4, boto3 / botocore 1.43.108, Linux.
Possible fix: read stopSequences from inferenceConfig and top_k from additionalModelRequestFields for Converse, and top_k / stop_sequences from the Anthropic body for InvokeModel; and set the request attributes before calling the wrapped method (they depend only on the request), so failed calls keep them. The OpenAI package had the same stop_sequences gap (#4538).

👀 Have you spent some time to check if this bug has been raised before?

  • I checked and didn't find similar issue

Are you willing to submit PR?

Yes I am willing to submit a PR!

Activity

  1. kimnamu commented on Oct 28, 2026

    @kimnamu

    Thanks @armanunix for the self-contained before-send repro. It ran unchanged against main and against #4562, which made checking this quick.

    Everything in the report still reproduces on main 8d9c93f. #4562 fixes the Anthropic shapes on both APIs; two things are left before it covers part 1:

    top_k / stop_sequences on a successful call main 8d9c93f #4562 #4562 + lines below
    Anthropic converse and invoke_model MISSING / MISSING 40 / ['END'] 40 / ['END']
    Nova converse MISSING / MISSING MISSING / ['END'] 40 / ['END']
    Nova invoke_model MISSING / MISSING MISSING / MISSING 40 / ['END']
    any failed call (part 2) no request params no request params no request params
    1. Nova nests top_k: additionalModelRequestFields={"inferenceConfig": {"topK": N}}. Bedrock rejected a top-level top_k for Nova Lite, Micro, Pro and 2 Lite (and the nested form for Claude Haiku 4.5), so additional_fields.get("top_k") never sees a Nova value. The Nova invoke_model body carries inferenceConfig.topK / stopSequences, which _set_amazon_span_attributes doesn't read yet.
    2. The two TestInvokeModelRequestParams tests pass on their own but fail under uv run pytest tests/, the package's test target (CI hasn't run on fix(bedrock): record top_k and stop_sequences request parameters #4562 yet).

    Happy to leave both with @aniketkrs. The lines I checked are below in case they save a step.

    Live Bedrock check, us-east-1
    converse  amazon.nova-lite-v1:0  {"inferenceConfig":{"topK":40}}  -> stopReason max_tokens
    converse  amazon.nova-lite-v1:0  {"top_k":40}                     -> ValidationException: Malformed input request: #: extraneous key [top_k] is not permitted
    converse  amazon.nova-pro-v1:0, amazon.nova-micro-v1:0, us.amazon.nova-2-lite-v1:0: same two results
    converse  us.anthropic.claude-haiku-4-5-20251001-v1:0  {"top_k":40}                     -> stopReason max_tokens
    converse  us.anthropic.claude-haiku-4-5-20251001-v1:0  {"inferenceConfig":{"topK":40}}  -> ValidationException: inferenceConfig: Extra inputs are not permitted
    invoke_model  amazon.nova-lite-v1:0  inferenceConfig {"topK":40,"stopSequences":["END"]}  -> stopReason max_tokens
    
    Nova lines on top of #4562 (span_utils.py)
    @@ -636,6 +636,12 @@ def _set_amazon_span_attributes(
             _set_span_attribute(
                 span, GenAIAttributes.GEN_AI_REQUEST_MAX_TOKENS, config.get("maxTokens")
             )
    +        _set_span_attribute(span, GenAIAttributes.GEN_AI_REQUEST_TOP_K, config.get("topK"))
    +        stop_sequences = config.get("stopSequences")
    +        if stop_sequences:
    +            _set_span_attribute(
    +                span, GenAIAttributes.GEN_AI_REQUEST_STOP_SEQUENCES, stop_sequences
    +            )
     
         total_completion_tokens = 0
         total_prompt_tokens = 0
    @@ -884,9 +890,10 @@ def set_converse_model_span_attributes(span, provider, model, kwargs):
                 additional_fields = json.loads(additional_fields)
             except (json.JSONDecodeError, TypeError):
                 additional_fields = {}
    -    _set_span_attribute(
    -        span, GenAIAttributes.GEN_AI_REQUEST_TOP_K, additional_fields.get("top_k")
    -    )
    +    top_k = additional_fields.get("top_k")
    +    if top_k is None:  # Nova nests it: {"inferenceConfig": {"topK": N}}
    +        top_k = (additional_fields.get("inferenceConfig") or {}).get("topK")
    +    _set_span_attribute(span, GenAIAttributes.GEN_AI_REQUEST_TOP_K, top_k)

    The table rows come from the issue's script with two Nova cases added (same before-send stub, modelId="amazon.nova-lite-v1:0").

    Full-suite failure and a two-line test fix
    $ uv run pytest tests/ -q --record-mode=none        # #4562 applied on main 8d9c93f
    FAILED tests/test_bedrock_request_params.py::TestInvokeModelRequestParams::test_top_k_and_stop_sequences_recorded
    FAILED tests/test_bedrock_request_params.py::TestInvokeModelRequestParams::test_absent_params_set_no_attributes
    2 failed, 386 passed, 145 warnings in 5.14s
    E           TypeError: 'NoneType' object is not iterable
    opentelemetry/instrumentation/bedrock/span_utils.py:505: TypeError
    
    $ uv run pytest tests/test_bedrock_request_params.py -q
    4 passed, 1 warning in 0.02s
    

    The conftest fixtures build BedrockInstrumentor(enrich_token_usage=True) (e.g. tests/conftest.py:88), and the constructor stores that on the class-level Config (__init__.py:1199), so it stays on for later tests. With response_body={} the helper then takes the token-counting branch and iterates response_body.get("content") (line 505 with #4562 applied). A usage block keeps both tests on the API-usage branch:

    -            response_body={},
    +            response_body={"usage": {"input_tokens": 1, "output_tokens": 1}},

    With that change, and with or without the Nova lines: 388 passed, uv run ruff check . clean.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions