Skip to content

Commit 622617e

Browse files
committed
Avoid double copy of streaming body
1 parent d1540ce commit 622617e

File tree

2 files changed

+8
-12
lines changed
  • instrumentation/opentelemetry-instrumentation-botocore

2 files changed

+8
-12
lines changed

instrumentation/opentelemetry-instrumentation-botocore/src/opentelemetry/instrumentation/botocore/extensions/bedrock.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -226,19 +226,17 @@ def _invoke_model_on_success(
226226
original_body = result["body"]
227227
body_content = original_body.read()
228228

229-
# Use one stream for telemetry
230-
stream = io.BytesIO(body_content)
231-
telemetry_content = stream.read()
232-
response_body = json.loads(telemetry_content.decode("utf-8"))
229+
# Replenish stream for downstream application use
230+
new_stream = io.BytesIO(body_content)
231+
result["body"] = StreamingBody(new_stream, len(body_content))
232+
233+
response_body = json.loads(body_content.decode("utf-8"))
233234
if "amazon.titan" in model_id:
234235
self._handle_amazon_titan_response(span, response_body)
235236
elif "amazon.nova" in model_id:
236237
self._handle_amazon_nova_response(span, response_body)
237238
elif "anthropic.claude" in model_id:
238239
self._handle_anthropic_claude_response(span, response_body)
239-
# Replenish stream for downstream application use
240-
new_stream = io.BytesIO(body_content)
241-
result["body"] = StreamingBody(new_stream, len(body_content))
242240

243241
except json.JSONDecodeError:
244242
_logger.debug("Error: Unable to parse the response body as JSON")

instrumentation/opentelemetry-instrumentation-botocore/tests/bedrock_utils.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414

1515
from __future__ import annotations
1616

17-
import io
1817
import json
1918
from typing import Any
2019

@@ -40,12 +39,11 @@ def assert_completion_attributes_from_streaming_body(
4039
input_tokens = None
4140
output_tokens = None
4241
finish_reason = None
43-
if response:
42+
if response is not None:
4443
original_body = response["body"]
4544
body_content = original_body.read()
46-
stream = io.BytesIO(body_content)
47-
telemetry_content = stream.read()
48-
response = json.loads(telemetry_content.decode("utf-8"))
45+
response = json.loads(body_content.decode("utf-8"))
46+
assert response
4947

5048
if "amazon.titan" in request_model:
5149
input_tokens = response.get("inputTextTokenCount")

0 commit comments

Comments
 (0)