Repository navigation
Description
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 onlytopP,temperatureandmaxTokensfrominferenceConfig.inferenceConfig.stopSequencesis ignored, and so isadditionalModelRequestFields(wheretop_kgoes for Anthropic models on Converse).invoke_model/invoke_model_with_response_streamwith an Anthropic Messages body:_set_anthropic_messages_span_attributesreads onlytop_p,temperatureandmax_tokens; the body'stop_kandstop_sequencesare 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
kimnamu commentedon Oct 28, 2026
Thanks @armanunix for the self-contained
before-sendrepro. 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:8d9c93fconverseandinvoke_model['END']['END']converse['END']['END']invoke_model['END']additionalModelRequestFields={"inferenceConfig": {"topK": N}}. Bedrock rejected a top-leveltop_kfor Nova Lite, Micro, Pro and 2 Lite (and the nested form for Claude Haiku 4.5), soadditional_fields.get("top_k")never sees a Nova value. The Novainvoke_modelbody carriesinferenceConfig.topK/stopSequences, which_set_amazon_span_attributesdoesn't read yet.TestInvokeModelRequestParamstests pass on their own but fail underuv 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
Nova lines on top of #4562 (span_utils.py)
The table rows come from the issue's script with two Nova cases added (same
before-sendstub,modelId="amazon.nova-lite-v1:0").Full-suite failure and a two-line test fix
The conftest fixtures build
BedrockInstrumentor(enrich_token_usage=True)(e.g.tests/conftest.py:88), and the constructor stores that on the class-levelConfig(__init__.py:1199), so it stays on for later tests. Withresponse_body={}the helper then takes the token-counting branch and iteratesresponse_body.get("content")(line 505 with #4562 applied). Ausageblock keeps both tests on the API-usage branch:With that change, and with or without the Nova lines:
388 passed,uv run ruff check .clean.