Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import json

import boto3
from opentelemetry import trace as trace_api
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk import trace as trace_sdk
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace.export import SimpleSpanProcessor

from openinference.instrumentation.bedrock import BedrockInstrumentor

endpoint = "http://127.0.0.1:6006/v1/traces"
resource = Resource(attributes={})
tracer_provider = trace_sdk.TracerProvider(resource=resource)
tracer_provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter(endpoint)))
trace_api.set_tracer_provider(tracer_provider=tracer_provider)

BedrockInstrumentor().instrument()

session = boto3.session.Session()
client = session.client("bedrock-runtime", "us-east-1")

MODEL_ID = "global.anthropic.claude-haiku-4-5-20251001-v1:0"
SYSTEM_PROMPT = "You are a pirate. Always answer in one short sentence."


def request_body(system):
return {
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 100,
"system": system,
"messages": [{"role": "user", "content": "What is the capital of France?"}],
}


def invoke_model_with_string_system():
response = client.invoke_model(modelId=MODEL_ID, body=json.dumps(request_body(SYSTEM_PROMPT)))
response_body = json.loads(response.get("body").read())
print(response_body["content"][0]["text"])


def invoke_model_with_block_system():
system = [{"type": "text", "text": SYSTEM_PROMPT}]
response = client.invoke_model(modelId=MODEL_ID, body=json.dumps(request_body(system)))
response_body = json.loads(response.get("body").read())
print(response_body["content"][0]["text"])


def invoke_model_with_response_stream_with_block_system():
system = [{"type": "text", "text": SYSTEM_PROMPT}]
response = client.invoke_model_with_response_stream(
modelId=MODEL_ID, body=json.dumps(request_body(system))
)
for event in response["body"]:
chunk = json.loads(event["chunk"]["bytes"])
if chunk["type"] == "content_block_delta" and "text" in chunk["delta"]:
print(chunk["delta"]["text"], end="")
print()


if __name__ == "__main__":
invoke_model_with_string_system()
invoke_model_with_block_system()
invoke_model_with_response_stream_with_block_system()
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

from __future__ import annotations

from typing import Any, Dict, Iterable, Iterator, List, Mapping, Tuple
from typing import Any, Dict, Iterable, Iterator, List, Mapping, Optional, Tuple

from opentelemetry.trace import Span

Expand Down Expand Up @@ -90,6 +90,27 @@ def _get_input_messages(content: Any) -> List[Message]:
return messages


def _get_system_message(system: Any) -> Optional[Message]:
"""
Convert the request's system prompt, a string or a list of text blocks, to a system
Message, or None when there is no system prompt.
"""
if isinstance(system, str):
texts = [system] if system else []
elif isinstance(system, Iterable):
texts = [
block["text"]
for block in system
if isinstance(block, Mapping) and isinstance(block.get("text"), str)
]
else:
texts = []
if not texts:
return None
contents: List[Any] = [TextMessageContent(text=text, type="text") for text in texts]
return Message(role="system", contents=contents)


def _get_llm_token_counts(usage: Dict[str, Any]) -> Iterator[Tuple[str, Any]]:
"""
Extract token count information from usage statistics.
Expand Down Expand Up @@ -215,6 +236,7 @@ def _validate_invocation_parameter(parameter: Any) -> bool:
excluded_params = (
"messages",
"modelId",
"system",
)
return parameter not in excluded_params

Expand All @@ -240,6 +262,8 @@ def get_llm_input_attributes(request_body: Dict[str, Any], model_id: str) -> Dic
"""
invocation_parameters = _get_invocation_parameters(request_body)
input_messages = _get_input_messages(request_body.get("messages"))
if system_message := _get_system_message(request_body.get("system")):
input_messages.insert(0, system_message)
return {
**get_llm_attributes(
model_name=_get_llm_model_name_from_input(model_id),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ def _attributes_from_system_message(
return
for i, block in enumerate(system):
try:
yield f"{MESSAGE_CONTENTS}.{i}.{MESSAGE_CONTENT_TEXT}", block["text"]
yield f"{prefix}{MESSAGE_CONTENTS}.{i}.{MESSAGE_CONTENT_TEXT}", block["text"]
except KeyError:
pass

Expand Down
Original file line number Diff line number Diff line change
@@ -1,20 +1,226 @@
import base64
import io
import json
from pathlib import Path
from typing import Any, Dict, Tuple
from typing import Any, Dict, Tuple, cast
from unittest.mock import MagicMock

import aioboto3
import boto3
import pytest
from aioresponses import aioresponses
from botocore.eventstream import EventStream
from botocore.response import StreamingBody
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from opentelemetry.trace import Tracer

from openinference.instrumentation import REDACTED_VALUE, OITracer, TraceConfig
from openinference.instrumentation.bedrock import _model_invocation_wrapper
from openinference.instrumentation.bedrock._wrappers import _InvokeModelWithResponseStream
from openinference.instrumentation.bedrock.utils.anthropic._messages import (
_attributes_from_image_param,
)

_CASSETTES_DIR = Path(__file__).resolve().parent / "cassettes"

_SECRET = "SECRET-SYSTEM"
_CLAUDE_MODEL_ID = "anthropic.claude-3-haiku-20240307-v1:0"


@pytest.mark.parametrize("stream", [False, True], ids=["invoke_model", "stream"])
@pytest.mark.parametrize(
"system",
[_SECRET, [{"type": "text", "text": _SECRET}]],
ids=["string", "blocks"],
)
def test_hide_inputs_redacts_system_prompt(
tracer_provider: TracerProvider,
in_memory_span_exporter: InMemorySpanExporter,
system: Any,
stream: bool,
) -> None:
_invoke_with_system(tracer_provider, TraceConfig(hide_inputs=True), system, stream)

(span,) = in_memory_span_exporter.get_finished_spans()
assert span.status.is_ok
attributes = dict(span.attributes or {})
assert attributes.pop("input.value") == REDACTED_VALUE
assert json.loads(str(attributes.pop("llm.invocation_parameters"))) == _invocation_parameters(
stream
)
assert not [key for key in attributes if key.startswith("llm.input_messages.")]
_pop_response_attributes(attributes, stream)
assert not attributes


@pytest.mark.parametrize("stream", [False, True], ids=["invoke_model", "stream"])
@pytest.mark.parametrize(
"system, texts",
[
(_SECRET, [_SECRET]),
(
[{"type": "text", "text": "first"}, {"type": "text", "text": "second"}],
["first", "second"],
),
],
ids=["string", "blocks"],
)
def test_system_prompt_is_first_input_message(
tracer_provider: TracerProvider,
in_memory_span_exporter: InMemorySpanExporter,
system: Any,
texts: list[str],
stream: bool,
) -> None:
_invoke_with_system(tracer_provider, TraceConfig(), system, stream)

(span,) = in_memory_span_exporter.get_finished_spans()
assert span.status.is_ok
attributes = dict(span.attributes or {})
assert json.loads(str(attributes.pop("input.value")))["system"] == system
assert attributes.pop("input.mime_type") == "application/json"
assert json.loads(str(attributes.pop("llm.invocation_parameters"))) == _invocation_parameters(
stream
)
assert attributes.pop("llm.input_messages.0.message.role") == "system"
for i, text in enumerate(texts):
prefix = f"llm.input_messages.0.message.contents.{i}.message_content"
assert attributes.pop(f"{prefix}.text") == text
if not stream:
assert attributes.pop(f"{prefix}.type") == "text"
assert attributes.pop("llm.input_messages.1.message.role") == "user"
if stream:
assert (
attributes.pop("llm.input_messages.1.message.contents.0.message_content.text") == "hi"
)
else:
assert attributes.pop("llm.input_messages.1.message.content") == "hi"
_pop_response_attributes(attributes, stream)
assert not attributes


def _invocation_parameters(stream: bool) -> Dict[str, Any]:
# The streaming path also leaves anthropic_version out of the invocation parameters.
if stream:
return {"max_tokens": 10}
return {"anthropic_version": "bedrock-2023-05-31", "max_tokens": 10}


def _pop_response_attributes(attributes: Dict[str, Any], stream: bool) -> None:
assert attributes.pop("openinference.span.kind") == "LLM"
assert attributes.pop("llm.model_name") == _CLAUDE_MODEL_ID
assert attributes.pop("llm.finish_reason") == "end_turn"
assert attributes.pop("llm.token_count.prompt") == 5
assert attributes.pop("llm.token_count.completion") == 1
assert attributes.pop("llm.output_messages.0.message.role") == "assistant"
if stream:
output_text_key = "llm.output_messages.0.message.contents.0.message_content.text"
else:
output_text_key = "llm.output_messages.0.message.content"
assert attributes.pop("llm.provider") == "aws"
assert attributes.pop("llm.system") == "anthropic"
assert attributes.pop(output_text_key) == "hello"
assert attributes.pop("output.mime_type") == "application/json"
assert json.loads(attributes.pop("output.value"))["content"][0]["text"] == "hello"


def _invoke_with_system(
tracer_provider: TracerProvider,
config: TraceConfig,
system: Any,
stream: bool,
) -> None:
tracer = cast(Tracer, OITracer(tracer_provider.get_tracer(__name__), config=config))
kwargs = {
"modelId": _CLAUDE_MODEL_ID,
"body": json.dumps(
{
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 10,
"system": system,
"messages": [{"role": "user", "content": "hi"}],
}
),
}
if stream:
chunks: Tuple[Dict[str, Any], ...] = (
{
"type": "message_start",
"message": {
"id": "msg_1",
"type": "message",
"role": "assistant",
"model": _CLAUDE_MODEL_ID,
"content": [],
"stop_reason": None,
"stop_sequence": None,
"usage": {"input_tokens": 5, "output_tokens": 1},
},
},
{
"type": "content_block_start",
"index": 0,
"content_block": {"type": "text", "text": ""},
},
{
"type": "content_block_delta",
"index": 0,
"delta": {"type": "text_delta", "text": "hello"},
},
{"type": "content_block_stop", "index": 0},
{
"type": "message_delta",
"delta": {"stop_reason": "end_turn", "stop_sequence": None},
"usage": {"output_tokens": 1},
},
{"type": "message_stop"},
)
event_stream = MagicMock(spec=EventStream)
event_stream.__iter__.return_value = iter(
[{"chunk": {"bytes": json.dumps(c).encode()}} for c in chunks]
)
response = {"body": event_stream}
_InvokeModelWithResponseStream(tracer)._sync_call(lambda **_: response, (), kwargs)
for _ in response["body"]:
pass
else:
payload = json.dumps(
{
"id": "msg_1",
"type": "message",
"role": "assistant",
"model": _CLAUDE_MODEL_ID,
"content": [{"type": "text", "text": "hello"}],
"stop_reason": "end_turn",
"stop_sequence": None,
"usage": {"input_tokens": 5, "output_tokens": 1},
}
).encode()
client = MagicMock()
client._unwrapped_invoke_model.return_value = {
"body": StreamingBody(io.BytesIO(payload), len(payload))
}
_model_invocation_wrapper(tracer)(client)(**kwargs)


def test_invoke_model_system_message_is_not_a_recorded_invocation_parameter() -> None:
from openinference.instrumentation.bedrock.utils.anthropic._attributes import (
_get_invocation_parameters,
)

kwargs = {
"anthropic_version": "bedrock-2023-05-31",
"system": "SECRET-SYSTEM",
"messages": [],
"modelId": "anthropic.claude-3-haiku-20240307-v1:0",
"max_tokens": 10,
}
assert _get_invocation_parameters(kwargs) == {
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 10,
}


def test_file_image_source_emits_no_attributes() -> None:
image_block: Any = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -395,3 +395,20 @@ def test_unhandled_model_request_body_is_serialized(
TOOL_CALL_ID = ToolCallAttributes.TOOL_CALL_ID
TOOL_JSON_SCHEMA = ToolAttributes.TOOL_JSON_SCHEMA
USER_ID = SpanAttributes.USER_ID


def test_system_message_block_attributes_include_message_prefix() -> None:
from openinference.instrumentation.bedrock.utils.anthropic._messages import (
_attributes_from_system_message,
)

attributes = dict(
_attributes_from_system_message(
[{"type": "text", "text": "SECRET-SYSTEM"}],
"llm.input_messages.0.",
)
)
assert attributes == {
"llm.input_messages.0.message.role": "system",
"llm.input_messages.0.message.contents.0.message_content.text": "SECRET-SYSTEM",
}
Loading