Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /pydantic_logfire /tests /otel_integrations /test_anthropic.py
from __future__ import annotations as _annotations
import gc
import json
import logging
from collections.abc import AsyncIterator, Iterator
from inspect import signature
from typing import Any, cast
import anthropic
import httpx2 as httpx
import pydantic
import pytest
from anthropic.types import (
Message,
MessageDeltaUsage,
MessageStartEvent,
MessageStopEvent,
TextBlock,
TextDelta,
Usage,
)
from dirty_equals import IsInt, IsPartialDict, IsStr
from httpx2 import MockTransport
from inline_snapshot import snapshot
import logfire
from logfire._internal.utils import get_version
from logfire.testing import TestExporter
pytestmark = [
pytest.mark.skipif(
get_version(pydantic.__version__) < get_version('2.5'),
reason='Requires Pydantic 2.5 or higher to import genai-prices and set operation.cost attribute.',
),
]
ANY_ADAPTER = pydantic.TypeAdapter(Any) # type: ignore
def test_semconv_version_defaults() -> None:
from logfire._internal.integrations.llm_providers.anthropic import get_endpoint_config
assert signature(logfire.instrument_anthropic).parameters['version'].default == 2
class MockOptions:
url = '/v1/messages'
json_data = {'model': 'claude-haiku-4-5', 'messages': [{'role': 'user', 'content': 'Hello'}]}
config = get_endpoint_config(MockOptions()) # type: ignore
assert config.span_data['request_data'] == {'model': 'claude-haiku-4-5'}
assert config.span_data['gen_ai.input.messages'] == [
{'role': 'user', 'parts': [{'type': 'text', 'content': 'Hello'}]}
]
def request_handler(request: httpx.Request) -> httpx.Response:
"""Used to mock httpx requests
We do this instead of using pytest-httpx since 1) it's nearly as simple 2) pytest-httpx doesn't support Python 3.8.
(We no longer support 3.8 either, but it's not worth changing this now)
"""
assert request.method == 'POST'
if request.url == 'https://api.anthropic.com/v1/complete':
return httpx.Response(
200,
json={'id': 'test_id', 'completion': 'completion', 'model': 'claude-2.1', 'type': 'completion'},
)
assert request.url in ['https://api.anthropic.com/v1/messages'], f'Unexpected URL: {request.url}'
json_body = json.loads(request.content)
if json_body.get('stream'):
if json_body['system'] == 'empty response chunk':
return httpx.Response(200, text='data: []\n\n')
else:
chunks = [
MessageStartEvent(
message=Message(
id='test_id',
content=[],
model='claude-3-haiku-20240307',
role='assistant',
stop_reason=None,
stop_sequence=None,
type='message',
usage=Usage(input_tokens=25, output_tokens=25),
),
type='message_start',
),
dict(content_block=TextBlock(text='', type='text'), index=0, type='content_block_start'),
dict(delta=TextDelta(text='The answer', type='text_delta'), index=0, type='content_block_delta'),
dict(delta=TextDelta(text=' is secret', type='text_delta'), index=0, type='content_block_delta'),
dict(index=0, type='content_block_stop'),
dict(
delta=dict(stop_reason='end_turn', stop_sequence=None),
type='message_delta',
usage=MessageDeltaUsage(output_tokens=55),
),
MessageStopEvent(type='message_stop'),
]
chunks_dicts = ANY_ADAPTER.dump_python(chunks) # type: ignore
return httpx.Response(
200, text=''.join(f'event: {chunk["type"]}\ndata: {json.dumps(chunk)}\n\n' for chunk in chunks_dicts)
)
elif json_body['system'] == 'tool response':
return httpx.Response(
200,
json=Message.model_construct(
id='test_id',
content=[dict(id='id', input={'param': 'param'}, name='tool', type='tool_use')],
model='claude-3-haiku-20240307',
role='assistant',
type='message',
stop_reason='tool_use',
usage=Usage(input_tokens=2, output_tokens=3),
).model_dump(mode='json'),
)
elif json_body['system'] == 'no stop reason':
# Edge case: response with no stop_reason (e.g., interrupted)
return httpx.Response(
200,
json=Message.model_construct(
id='test_id',
content=[TextBlock(text='Partial', type='text')],
model='claude-3-haiku-20240307',
role='assistant',
type='message',
stop_reason=None,
usage=Usage(input_tokens=2, output_tokens=3),
).model_dump(mode='json'),
)
else:
return httpx.Response(
200,
json=Message(
id='test_id',
content=[
TextBlock(
text='Nine',
type='text',
)
],
model='claude-3-haiku-20240307',
role='assistant',
type='message',
stop_reason='end_turn',
usage=Usage(input_tokens=2, output_tokens=3),
).model_dump(mode='json'),
)
@pytest.fixture
def instrumented_client() -> Iterator[anthropic.Anthropic]:
with httpx.Client(transport=MockTransport(request_handler)) as httpx_client:
# use a hardcoded API key to make sure one in the environment is never used
anthropic_client = anthropic.Anthropic(api_key='foobar', http_client=httpx_client)
with logfire.instrument_anthropic(anthropic_client, version=[1, 'latest']):
yield anthropic_client
@pytest.fixture
async def instrumented_async_client() -> AsyncIterator[anthropic.AsyncAnthropic]:
async with httpx.AsyncClient(transport=MockTransport(request_handler)) as httpx_client:
# use a hardcoded API key to make sure one in the environment is never used
anthropic_client = anthropic.AsyncAnthropic(api_key='foobar', http_client=httpx_client)
# Test instrumenting EVERYTHING
with logfire.instrument_anthropic(version=[1, 'latest']):
yield anthropic_client
def test_sync_messages(instrumented_client: anthropic.Anthropic, exporter: TestExporter) -> None:
response = instrumented_client.messages.create(
max_tokens=1000,
model='claude-3-haiku-20240307',
system='You are a helpful assistant.',
messages=[{'role': 'user', 'content': 'What is four plus five?'}],
)
assert isinstance(response.content[0], TextBlock)
assert response.content[0].text == 'Nine'
assert exporter.exported_spans_as_dict(parse_json_attributes=True) == snapshot(
[
{
'name': 'Message with {request_data[model]!r}',
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
'parent': None,
'start_time': 1000000000,
'end_time': 2000000000,
'attributes': {
'code.filepath': 'test_anthropic.py',
'code.function': 'test_sync_messages',
'code.lineno': 123,
'request_data': {
'max_tokens': 1000,
'system': 'You are a helpful assistant.',
'messages': [{'role': 'user', 'content': 'What is four plus five?'}],
'model': 'claude-3-haiku-20240307',
},
'gen_ai.system': 'anthropic',
'gen_ai.provider.name': 'anthropic',
'gen_ai.operation.name': 'chat',
'gen_ai.request.model': 'claude-3-haiku-20240307',
'gen_ai.request.max_tokens': 1000,
'gen_ai.input.messages': [
{'role': 'user', 'parts': [{'type': 'text', 'content': 'What is four plus five?'}]}
],
'gen_ai.system_instructions': [{'type': 'text', 'content': 'You are a helpful assistant.'}],
'async': False,
'logfire.msg_template': 'Message with {request_data[model]!r}',
'logfire.msg': "Message with 'claude-3-haiku-20240307'",
'logfire.span_type': 'span',
'logfire.tags': ('LLM',),
'response_data': {
'message': {
'content': 'Nine',
'role': 'assistant',
},
'usage': IsPartialDict(
{
'cache_creation': None,
'input_tokens': 2,
'output_tokens': 3,
'cache_creation_input_tokens': None,
'cache_read_input_tokens': None,
'server_tool_use': None,
'service_tier': None,
}
),
},
'gen_ai.output.messages': [
{
'role': 'assistant',
'parts': [{'type': 'text', 'content': 'Nine'}],
'finish_reason': 'end_turn',
}
],
'gen_ai.response.model': 'claude-3-haiku-20240307',
'gen_ai.response.id': 'test_id',
'gen_ai.usage.input_tokens': 2,
'gen_ai.usage.output_tokens': 3,
'gen_ai.usage.raw': {'input_tokens': 2, 'output_tokens': 3},
'gen_ai.response.finish_reasons': ['end_turn'],
'operation.cost': 4.25e-06,
'logfire.json_schema': {
'type': 'object',
'properties': {
'request_data': {'type': 'object'},
'gen_ai.system': {},
'gen_ai.provider.name': {},
'gen_ai.operation.name': {},
'gen_ai.request.model': {},
'gen_ai.request.max_tokens': {},
'gen_ai.input.messages': {'type': 'array'},
'gen_ai.system_instructions': {'type': 'array'},
'async': {},
'response_data': {
'type': 'object',
'properties': {
'usage': {
'type': 'object',
'title': 'Usage',
'x-python-datatype': 'PydanticModel',
},
},
},
'gen_ai.output.messages': {'type': 'array'},
'gen_ai.response.model': {},
'gen_ai.response.id': {},
'gen_ai.usage.input_tokens': {},
'gen_ai.usage.output_tokens': {},
'gen_ai.usage.raw': {'type': 'object'},
'gen_ai.response.finish_reasons': {'type': 'array'},
'operation.cost': {},
},
},
},
}
]
)
async def test_async_messages(instrumented_async_client: anthropic.AsyncAnthropic, exporter: TestExporter) -> None:
response = await instrumented_async_client.messages.create(
max_tokens=1000,
model='claude-3-haiku-20240307',
system='You are a helpful assistant.',
messages=[{'role': 'user', 'content': 'What is four plus five?'}],
)
assert isinstance(response.content[0], TextBlock)
assert response.content[0].text == 'Nine'
assert exporter.exported_spans_as_dict(parse_json_attributes=True) == snapshot(
[
{
'name': 'Message with {request_data[model]!r}',
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
'parent': None,
'start_time': 1000000000,
'end_time': 2000000000,
'attributes': {
'code.filepath': 'test_anthropic.py',
'code.function': 'test_async_messages',
'code.lineno': 123,
'request_data': {
'max_tokens': 1000,
'messages': [{'role': 'user', 'content': 'What is four plus five?'}],
'model': 'claude-3-haiku-20240307',
'system': 'You are a helpful assistant.',
},
'gen_ai.system': 'anthropic',
'gen_ai.provider.name': 'anthropic',
'gen_ai.operation.name': 'chat',
'gen_ai.request.model': 'claude-3-haiku-20240307',
'gen_ai.request.max_tokens': 1000,
'gen_ai.input.messages': [
{'role': 'user', 'parts': [{'type': 'text', 'content': 'What is four plus five?'}]}
],
'gen_ai.system_instructions': [{'type': 'text', 'content': 'You are a helpful assistant.'}],
'async': True,
'logfire.msg_template': 'Message with {request_data[model]!r}',
'logfire.msg': "Message with 'claude-3-haiku-20240307'",
'logfire.tags': ('LLM',),
'logfire.span_type': 'span',
'response_data': {
'message': {'role': 'assistant', 'content': 'Nine'},
'usage': {
'cache_creation': None,
'cache_creation_input_tokens': None,
'cache_read_input_tokens': None,
'inference_geo': None,
'input_tokens': 2,
'output_tokens': 3,
'output_tokens_details': None,
'server_tool_use': None,
'service_tier': None,
},
},
'gen_ai.output.messages': [
{
'role': 'assistant',
'parts': [{'type': 'text', 'content': 'Nine'}],
'finish_reason': 'end_turn',
}
],
'gen_ai.response.model': 'claude-3-haiku-20240307',
'gen_ai.response.id': 'test_id',
'gen_ai.usage.input_tokens': 2,
'gen_ai.usage.output_tokens': 3,
'gen_ai.usage.raw': {'input_tokens': 2, 'output_tokens': 3},
'gen_ai.response.finish_reasons': ['end_turn'],
'operation.cost': 4.25e-06,
'logfire.json_schema': {
'type': 'object',
'properties': {
'request_data': {'type': 'object'},
'gen_ai.system': {},
'gen_ai.provider.name': {},
'gen_ai.operation.name': {},
'gen_ai.request.model': {},
'gen_ai.request.max_tokens': {},
'gen_ai.input.messages': {'type': 'array'},
'gen_ai.system_instructions': {'type': 'array'},
'async': {},
'response_data': {
'type': 'object',
'properties': {
'usage': {'type': 'object', 'title': 'Usage', 'x-python-datatype': 'PydanticModel'}
},
},
'gen_ai.output.messages': {'type': 'array'},
'gen_ai.response.model': {},
'gen_ai.response.id': {},
'gen_ai.usage.input_tokens': {},
'gen_ai.usage.output_tokens': {},
'gen_ai.usage.raw': {'type': 'object'},
'gen_ai.response.finish_reasons': {'type': 'array'},
'operation.cost': {},
},
},
},
}
]
)
def test_sync_message_empty_response_chunk(instrumented_client: anthropic.Anthropic, exporter: TestExporter) -> None:
response = instrumented_client.messages.create(
max_tokens=1000,
model='claude-3-haiku-20240307',
system='empty response chunk',
messages=[],
stream=True,
)
combined = [chunk for chunk in response]
assert combined == []
assert exporter.exported_spans_as_dict(parse_json_attributes=True) == snapshot(
[
{
'name': 'Message with {request_data[model]!r}',
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
'parent': None,
'start_time': 1000000000,
'end_time': 2000000000,
'attributes': {
'code.filepath': 'test_anthropic.py',
'code.function': 'test_sync_message_empty_response_chunk',
'code.lineno': 123,
'request_data': {
'max_tokens': 1000,
'messages': [],
'model': 'claude-3-haiku-20240307',
'stream': True,
'system': 'empty response chunk',
},
'gen_ai.system': 'anthropic',
'gen_ai.provider.name': 'anthropic',
'gen_ai.operation.name': 'chat',
'gen_ai.request.model': 'claude-3-haiku-20240307',
'gen_ai.request.max_tokens': 1000,
'gen_ai.input.messages': [],
'gen_ai.system_instructions': [{'type': 'text', 'content': 'empty response chunk'}],
'async': False,
'logfire.msg_template': 'Message with {request_data[model]!r}',
'logfire.msg': "Message with 'claude-3-haiku-20240307'",
'logfire.json_schema': {
'type': 'object',
'properties': {
'request_data': {'type': 'object'},
'gen_ai.system': {},
'gen_ai.provider.name': {},
'gen_ai.operation.name': {},
'gen_ai.request.model': {},
'gen_ai.request.max_tokens': {},
'gen_ai.input.messages': {'type': 'array'},
'gen_ai.system_instructions': {'type': 'array'},
'async': {},
},
},
'logfire.span_type': 'span',
'logfire.tags': ('LLM',),
'gen_ai.response.model': 'claude-3-haiku-20240307',
},
},
{
'name': 'streaming response from {request_data[model]!r} took {duration:.2f}s',
'context': {'trace_id': 2, 'span_id': 3, 'is_remote': False},
'parent': None,
'start_time': 5000000000,
'end_time': 5000000000,
'attributes': {
'logfire.level_num': 9,
'request_data': {
'max_tokens': 1000,
'messages': [],
'model': 'claude-3-haiku-20240307',
'stream': True,
'system': 'empty response chunk',
},
'async': False,
'logfire.msg_template': 'streaming response from {request_data[model]!r} took {duration:.2f}s',
'code.filepath': 'test_anthropic.py',
'code.function': 'test_sync_message_empty_response_chunk',
'code.lineno': 123,
'logfire.msg': "streaming response from 'claude-3-haiku-20240307' took 1.00s",
'logfire.span_type': 'log',
'gen_ai.system': 'anthropic',
'gen_ai.provider.name': 'anthropic',
'gen_ai.operation.name': 'chat',
'gen_ai.request.model': 'claude-3-haiku-20240307',
'gen_ai.request.max_tokens': 1000,
'gen_ai.input.messages': [],
'gen_ai.system_instructions': [{'type': 'text', 'content': 'empty response chunk'}],
'logfire.tags': ('LLM',),
'duration': 1.0,
'response_data': {'combined_chunk_content': '', 'chunk_count': 0},
'logfire.json_schema': {
'type': 'object',
'properties': {
'duration': {},
'request_data': {'type': 'object'},
'gen_ai.system': {},
'gen_ai.provider.name': {},
'gen_ai.operation.name': {},
'gen_ai.request.model': {},
'gen_ai.request.max_tokens': {},
'gen_ai.input.messages': {'type': 'array'},
'gen_ai.system_instructions': {'type': 'array'},
'async': {},
'response_data': {'type': 'object'},
},
},
'gen_ai.response.model': 'claude-3-haiku-20240307',
},
},
]
)
def test_sync_messages_stream(instrumented_client: anthropic.Anthropic, exporter: TestExporter) -> None:
response = instrumented_client.messages.create(
max_tokens=1000,
model='claude-3-haiku-20240307',
system='You are a helpful assistant.',
messages=[{'role': 'user', 'content': 'What is four plus five?'}],
stream=True,
)
with response as stream:
combined = ''.join(
chunk.delta.text # type: ignore
for chunk in stream
if hasattr(chunk, 'delta') and isinstance(chunk.delta, TextDelta) # type: ignore
)
assert combined == 'The answer is secret'
assert exporter.exported_spans_as_dict(parse_json_attributes=True) == snapshot(
[
{
'name': 'Message with {request_data[model]!r}',
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
'parent': None,
'start_time': 1000000000,
'end_time': 2000000000,
'attributes': {
'code.filepath': 'test_anthropic.py',
'code.function': 'test_sync_messages_stream',
'code.lineno': 123,
'request_data': {
'max_tokens': 1000,
'messages': [{'role': 'user', 'content': 'What is four plus five?'}],
'model': 'claude-3-haiku-20240307',
'stream': True,
'system': 'You are a helpful assistant.',
},
'gen_ai.system': 'anthropic',
'gen_ai.provider.name': 'anthropic',
'gen_ai.operation.name': 'chat',
'gen_ai.request.model': 'claude-3-haiku-20240307',
'gen_ai.request.max_tokens': 1000,
'gen_ai.input.messages': [
{'role': 'user', 'parts': [{'type': 'text', 'content': 'What is four plus five?'}]}
],
'gen_ai.system_instructions': [{'type': 'text', 'content': 'You are a helpful assistant.'}],
'async': False,
'logfire.msg_template': 'Message with {request_data[model]!r}',
'logfire.msg': "Message with 'claude-3-haiku-20240307'",
'logfire.json_schema': {
'type': 'object',
'properties': {
'request_data': {'type': 'object'},
'gen_ai.system': {},
'gen_ai.provider.name': {},
'gen_ai.operation.name': {},
'gen_ai.request.model': {},
'gen_ai.request.max_tokens': {},
'gen_ai.input.messages': {'type': 'array'},
'gen_ai.system_instructions': {'type': 'array'},
'async': {},
},
},
'logfire.span_type': 'span',
'logfire.tags': ('LLM',),
'gen_ai.response.model': 'claude-3-haiku-20240307',
},
},
{
'name': 'streaming response from {request_data[model]!r} took {duration:.2f}s',
'context': {'trace_id': 2, 'span_id': 3, 'is_remote': False},
'parent': None,
'start_time': 5000000000,
'end_time': 5000000000,
'attributes': {
'logfire.level_num': 9,
'request_data': {
'max_tokens': 1000,
'messages': [{'role': 'user', 'content': 'What is four plus five?'}],
'model': 'claude-3-haiku-20240307',
'stream': True,
'system': 'You are a helpful assistant.',
},
'async': False,
'logfire.msg_template': 'streaming response from {request_data[model]!r} took {duration:.2f}s',
'code.filepath': 'test_anthropic.py',
'code.function': '<genexpr>',
'code.lineno': 123,
'logfire.msg': "streaming response from 'claude-3-haiku-20240307' took 1.00s",
'logfire.span_type': 'log',
'gen_ai.system': 'anthropic',
'gen_ai.provider.name': 'anthropic',
'gen_ai.operation.name': 'chat',
'gen_ai.request.model': 'claude-3-haiku-20240307',
'gen_ai.request.max_tokens': 1000,
'gen_ai.input.messages': [
{'role': 'user', 'parts': [{'type': 'text', 'content': 'What is four plus five?'}]}
],
'gen_ai.system_instructions': [{'type': 'text', 'content': 'You are a helpful assistant.'}],
'logfire.tags': ('LLM',),
'duration': 1.0,
'gen_ai.output.messages': [
{
'role': 'assistant',
'parts': [{'type': 'text', 'content': 'The answer is secret'}],
'finish_reason': 'end_turn',
}
],
'gen_ai.usage.input_tokens': 25,
'gen_ai.usage.output_tokens': 55,
'gen_ai.usage.raw': {'input_tokens': 25, 'output_tokens': 55},
'operation.cost': 7.5e-05,
'response_data': {'combined_chunk_content': 'The answer is secret', 'chunk_count': 2},
'logfire.json_schema': {
'type': 'object',
'properties': {
'duration': {},
'request_data': {'type': 'object'},
'gen_ai.system': {},
'gen_ai.provider.name': {},
'gen_ai.operation.name': {},
'gen_ai.request.model': {},
'gen_ai.request.max_tokens': {},
'gen_ai.input.messages': {'type': 'array'},
'gen_ai.system_instructions': {'type': 'array'},
'async': {},
'response_data': {'type': 'object'},
'gen_ai.output.messages': {'type': 'array'},
'gen_ai.usage.input_tokens': {},
'gen_ai.usage.output_tokens': {},
'gen_ai.usage.raw': {'type': 'object'},
'operation.cost': {},
},
},
'gen_ai.response.model': 'claude-3-haiku-20240307',
},
},
]
)
def test_sync_messages_stream_close_early(
instrumented_client: anthropic.Anthropic, exporter: TestExporter, caplog: pytest.LogCaptureFixture
) -> None:
response = instrumented_client.messages.create(
max_tokens=1000,
model='claude-3-haiku-20240307',
system='You are a helpful assistant.',
messages=[{'role': 'user', 'content': 'What is four plus five?'}],
stream=True,
)
chunks_seen = 0
chunk = None
with caplog.at_level(logging.ERROR, logger='opentelemetry.context'):
with response as stream:
for chunk in stream:
if hasattr(chunk, 'delta') and isinstance(chunk.delta, TextDelta): # type: ignore
chunks_seen += 1
break
del chunk
del stream
del response
gc.collect()
assert chunks_seen == 1
assert not [
record
for record in caplog.records
if record.name == 'opentelemetry.context' and 'Failed to detach context' in record.getMessage()
]
span_names = [span['name'] for span in exporter.exported_spans_as_dict(parse_json_attributes=True)]
assert span_names == [
'Message with {request_data[model]!r}',
'streaming response from {request_data[model]!r} took {duration:.2f}s',
]
def test_messages_stream_text_block_none() -> None:
from logfire._internal.integrations.llm_providers.anthropic import (
AnthropicMessageStreamState,
convert_response_to_semconv,
)
message = Message.model_construct(
id='test_id',
content=[TextBlock.model_construct(text=None, type='text'), TextBlock(text='Visible text', type='text')],
model='claude-3-haiku-20240307',
role='assistant',
type='message',
stop_reason='end_turn',
usage=Usage(input_tokens=25, output_tokens=55),
)
state = AnthropicMessageStreamState()
setattr(state, '_message', message)
setattr(state, '_chunk_count', 1)
assert state.get_response_data() == snapshot({'combined_chunk_content': 'Visible text', 'chunk_count': 1})
assert convert_response_to_semconv(message) == snapshot(
{
'role': 'assistant',
'parts': [{'citations': None, 'text': None, 'type': 'text'}, {'type': 'text', 'content': 'Visible text'}],
'finish_reason': 'end_turn',
}
)
async def test_async_messages_stream(
instrumented_async_client: anthropic.AsyncAnthropic, exporter: TestExporter
) -> None:
response = await instrumented_async_client.messages.create(
max_tokens=1000,
model='claude-3-haiku-20240307',
system='You are a helpful assistant.',
messages=[{'role': 'user', 'content': 'What is four plus five?'}],
stream=True,
)
async with response as stream:
chunk_content = [
chunk.delta.text # type: ignore
async for chunk in stream
if hasattr(chunk, 'delta') and isinstance(chunk.delta, TextDelta) # type: ignore
]
combined = ''.join(chunk_content)
assert combined == 'The answer is secret'
assert exporter.exported_spans_as_dict(parse_json_attributes=True) == snapshot(
[
{
'name': 'Message with {request_data[model]!r}',
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
'parent': None,
'start_time': 1000000000,
'end_time': 2000000000,
'attributes': {
'code.filepath': 'test_anthropic.py',
'code.function': 'test_async_messages_stream',
'code.lineno': 123,
'request_data': {
'max_tokens': 1000,
'messages': [{'role': 'user', 'content': 'What is four plus five?'}],
'model': 'claude-3-haiku-20240307',
'stream': True,
'system': 'You are a helpful assistant.',
},
'gen_ai.system': 'anthropic',
'gen_ai.provider.name': 'anthropic',
'gen_ai.operation.name': 'chat',
'gen_ai.request.model': 'claude-3-haiku-20240307',
'gen_ai.request.max_tokens': 1000,
'gen_ai.input.messages': [
{'role': 'user', 'parts': [{'type': 'text', 'content': 'What is four plus five?'}]}
],
'gen_ai.system_instructions': [{'type': 'text', 'content': 'You are a helpful assistant.'}],
'async': True,
'logfire.msg_template': 'Message with {request_data[model]!r}',
'logfire.msg': "Message with 'claude-3-haiku-20240307'",
'logfire.json_schema': {
'type': 'object',
'properties': {
'request_data': {'type': 'object'},
'gen_ai.system': {},
'gen_ai.provider.name': {},
'gen_ai.operation.name': {},
'gen_ai.request.model': {},
'gen_ai.request.max_tokens': {},
'gen_ai.input.messages': {'type': 'array'},
'gen_ai.system_instructions': {'type': 'array'},
'async': {},
},
},
'logfire.span_type': 'span',
'logfire.tags': ('LLM',),
'gen_ai.response.model': 'claude-3-haiku-20240307',
},
},
{
'name': 'streaming response from {request_data[model]!r} took {duration:.2f}s',
'context': {'trace_id': 2, 'span_id': 3, 'is_remote': False},
'parent': None,
'start_time': 5000000000,
'end_time': 5000000000,
'attributes': {
'logfire.level_num': 9,
'request_data': {
'max_tokens': 1000,
'messages': [{'role': 'user', 'content': 'What is four plus five?'}],
'model': 'claude-3-haiku-20240307',
'stream': True,
'system': 'You are a helpful assistant.',
},
'async': True,
'logfire.msg_template': 'streaming response from {request_data[model]!r} took {duration:.2f}s',
'code.filepath': 'test_anthropic.py',
'code.function': 'test_async_messages_stream',
'code.lineno': 123,
'logfire.msg': "streaming response from 'claude-3-haiku-20240307' took 1.00s",
'logfire.span_type': 'log',
'gen_ai.system': 'anthropic',
'gen_ai.provider.name': 'anthropic',
'gen_ai.operation.name': 'chat',
'gen_ai.request.model': 'claude-3-haiku-20240307',
'gen_ai.request.max_tokens': 1000,
'gen_ai.input.messages': [
{'role': 'user', 'parts': [{'type': 'text', 'content': 'What is four plus five?'}]}
],
'gen_ai.system_instructions': [{'type': 'text', 'content': 'You are a helpful assistant.'}],
'logfire.tags': ('LLM',),
'duration': 1.0,
'gen_ai.output.messages': [
{
'role': 'assistant',
'parts': [{'type': 'text', 'content': 'The answer is secret'}],
'finish_reason': 'end_turn',
}
],
'gen_ai.usage.input_tokens': 25,
'gen_ai.usage.output_tokens': 55,
'gen_ai.usage.raw': {'input_tokens': 25, 'output_tokens': 55},
'operation.cost': 7.5e-05,
'response_data': {'combined_chunk_content': 'The answer is secret', 'chunk_count': 2},
'logfire.json_schema': {
'type': 'object',
'properties': {
'duration': {},
'request_data': {'type': 'object'},
'gen_ai.system': {},
'gen_ai.provider.name': {},
'gen_ai.operation.name': {},
'gen_ai.request.model': {},
'gen_ai.request.max_tokens': {},
'gen_ai.input.messages': {'type': 'array'},
'gen_ai.system_instructions': {'type': 'array'},
'async': {},
'response_data': {'type': 'object'},
'gen_ai.output.messages': {'type': 'array'},
'gen_ai.usage.input_tokens': {},
'gen_ai.usage.output_tokens': {},
'gen_ai.usage.raw': {'type': 'object'},
'operation.cost': {},
},
},
'gen_ai.response.model': 'claude-3-haiku-20240307',
},
},
]
)
def test_tool_messages(instrumented_client: anthropic.Anthropic, exporter: TestExporter):
response = instrumented_client.messages.create(
max_tokens=1000,
model='claude-3-haiku-20240307',
system='tool response',
messages=[],
)
content = response.content[0]
assert content.input == {'param': 'param'} # type: ignore
assert exporter.exported_spans_as_dict(parse_json_attributes=True) == snapshot(
[
{
'name': 'Message with {request_data[model]!r}',
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
'parent': None,
'start_time': 1000000000,
'end_time': 2000000000,
'attributes': {
'code.filepath': 'test_anthropic.py',
'code.function': 'test_tool_messages',
'code.lineno': 123,
'request_data': {
'max_tokens': 1000,
'messages': [],
'model': 'claude-3-haiku-20240307',
'system': 'tool response',
},
'gen_ai.system': 'anthropic',
'gen_ai.provider.name': 'anthropic',
'gen_ai.operation.name': 'chat',
'gen_ai.request.model': 'claude-3-haiku-20240307',
'gen_ai.request.max_tokens': 1000,
'gen_ai.input.messages': [],
'gen_ai.system_instructions': [{'type': 'text', 'content': 'tool response'}],
'async': False,
'logfire.msg_template': 'Message with {request_data[model]!r}',
'logfire.msg': "Message with 'claude-3-haiku-20240307'",
'logfire.span_type': 'span',
'logfire.tags': ('LLM',),
'response_data': {
'message': {
'role': 'assistant',
'tool_calls': [
{'id': 'id', 'function': {'arguments': '{"input":{"param":"param"}}', 'name': 'tool'}}
],
},
'usage': IsPartialDict(
{
'cache_creation': None,
'cache_creation_input_tokens': None,
'cache_read_input_tokens': None,
'input_tokens': 2,
'output_tokens': 3,
'server_tool_use': None,
'service_tier': None,
}
),
},
'gen_ai.output.messages': [
{
'role': 'assistant',
'parts': [
{'type': 'tool_call', 'id': 'id', 'name': 'tool', 'arguments': {'param': 'param'}}
],
'finish_reason': 'tool_use',
}
],
'gen_ai.response.model': 'claude-3-haiku-20240307',
'gen_ai.response.id': 'test_id',
'gen_ai.usage.input_tokens': 2,
'gen_ai.usage.output_tokens': 3,
'gen_ai.usage.raw': {'input_tokens': 2, 'output_tokens': 3},
'gen_ai.response.finish_reasons': ['tool_use'],
'operation.cost': 4.25e-06,
'logfire.json_schema': {
'type': 'object',
'properties': {
'request_data': {'type': 'object'},
'gen_ai.system': {},
'gen_ai.provider.name': {},
'gen_ai.operation.name': {},
'gen_ai.request.model': {},
'gen_ai.request.max_tokens': {},
'gen_ai.input.messages': {'type': 'array'},
'gen_ai.system_instructions': {'type': 'array'},
'async': {},
'response_data': {
'type': 'object',
'properties': {
'usage': {'type': 'object', 'title': 'Usage', 'x-python-datatype': 'PydanticModel'}
},
},
'gen_ai.output.messages': {'type': 'array'},
'gen_ai.response.model': {},
'gen_ai.response.id': {},
'gen_ai.usage.input_tokens': {},
'gen_ai.usage.output_tokens': {},
'gen_ai.usage.raw': {'type': 'object'},
'gen_ai.response.finish_reasons': {'type': 'array'},
'operation.cost': {},
},
},
},
}
]
)
def test_messages_without_stop_reason(instrumented_client: anthropic.Anthropic, exporter: TestExporter) -> None:
"""Test response without stop_reason (e.g., interrupted)."""
response = instrumented_client.messages.create(
max_tokens=1000,
model='claude-3-haiku-20240307',
system='no stop reason',
messages=[{'role': 'user', 'content': 'Hello'}],
)
assert isinstance(response.content[0], TextBlock)
assert response.content[0].text == 'Partial'
# Verify finish_reasons is not present when stop_reason is None
spans = exporter.exported_spans_as_dict(parse_json_attributes=True)
assert spans == snapshot(
[
{
'name': 'Message with {request_data[model]!r}',
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
'parent': None,
'start_time': 1000000000,
'end_time': 2000000000,
'attributes': {
'code.filepath': 'test_anthropic.py',
'code.function': 'test_messages_without_stop_reason',
'code.lineno': 123,
'request_data': {
'max_tokens': 1000,
'messages': [{'role': 'user', 'content': 'Hello'}],
'model': 'claude-3-haiku-20240307',
'system': 'no stop reason',
},
'gen_ai.system': 'anthropic',
'gen_ai.provider.name': 'anthropic',
'gen_ai.operation.name': 'chat',
'gen_ai.request.model': 'claude-3-haiku-20240307',
'gen_ai.request.max_tokens': 1000,
'gen_ai.input.messages': [{'role': 'user', 'parts': [{'type': 'text', 'content': 'Hello'}]}],
'gen_ai.system_instructions': [{'type': 'text', 'content': 'no stop reason'}],
'async': False,
'logfire.msg_template': 'Message with {request_data[model]!r}',
'logfire.msg': "Message with 'claude-3-haiku-20240307'",
'logfire.tags': ('LLM',),
'logfire.span_type': 'span',
'response_data': {
'message': {'role': 'assistant', 'content': 'Partial'},
'usage': {
'cache_creation': None,
'cache_creation_input_tokens': None,
'cache_read_input_tokens': None,
'inference_geo': None,
'input_tokens': 2,
'output_tokens': 3,
'output_tokens_details': None,
'server_tool_use': None,
'service_tier': None,
},
},
'gen_ai.output.messages': [
{'role': 'assistant', 'parts': [{'type': 'text', 'content': 'Partial'}]}
],
'gen_ai.response.model': 'claude-3-haiku-20240307',
'gen_ai.response.id': 'test_id',
'gen_ai.usage.input_tokens': 2,
'gen_ai.usage.output_tokens': 3,
'gen_ai.usage.raw': {'input_tokens': 2, 'output_tokens': 3},
'operation.cost': 4.25e-06,
'logfire.json_schema': {
'type': 'object',
'properties': {
'request_data': {'type': 'object'},
'gen_ai.system': {},
'gen_ai.provider.name': {},
'gen_ai.operation.name': {},
'gen_ai.request.model': {},
'gen_ai.request.max_tokens': {},
'gen_ai.input.messages': {'type': 'array'},
'gen_ai.system_instructions': {'type': 'array'},
'async': {},
'response_data': {
'type': 'object',
'properties': {
'usage': {'type': 'object', 'title': 'Usage', 'x-python-datatype': 'PydanticModel'}
},
},
'gen_ai.output.messages': {'type': 'array'},
'gen_ai.response.model': {},
'gen_ai.response.id': {},
'gen_ai.usage.input_tokens': {},
'gen_ai.usage.output_tokens': {},
'gen_ai.usage.raw': {'type': 'object'},
'operation.cost': {},
},
},
},
}
]
)
def test_unknown_method(instrumented_client: anthropic.Anthropic, exporter: TestExporter) -> None:
response = cast(
dict[str, Any],
instrumented_client.post(
'/v1/complete',
body={'max_tokens_to_sample': 1000, 'model': 'claude-2.1', 'prompt': 'prompt'},
cast_to=object,
),
)
assert response['completion'] == 'completion'
assert exporter.exported_spans_as_dict(parse_json_attributes=True) == snapshot(
[
{
'name': 'Anthropic API call to {url!r}',
'context': {'is_remote': False, 'span_id': 1, 'trace_id': 1},
'parent': None,
'start_time': 1000000000,
'end_time': 2000000000,
'attributes': {
'logfire.span_type': 'span',
'logfire.tags': ('LLM',),
'request_data': {'max_tokens_to_sample': 1000, 'model': 'claude-2.1', 'prompt': 'prompt'},
'url': '/v1/complete',
'async': False,
'gen_ai.system': 'anthropic',
'gen_ai.provider.name': 'anthropic',
'gen_ai.request.model': 'claude-2.1',
'logfire.msg_template': 'Anthropic API call to {url!r}',
'logfire.msg': "Anthropic API call to '/v1/complete'",
'code.filepath': 'test_anthropic.py',
'code.function': 'test_unknown_method',
'code.lineno': 123,
'gen_ai.response.model': 'claude-2.1',
'logfire.json_schema': {
'type': 'object',
'properties': {
'request_data': {'type': 'object'},
'url': {},
'gen_ai.system': {},
'gen_ai.provider.name': {},
'gen_ai.request.model': {},
'async': {},
},
},
},
}
]
)
def test_request_parameters(instrumented_client: anthropic.Anthropic, exporter: TestExporter) -> None:
"""Test that all request parameters are extracted and added to span attributes."""
tools: list[Any] = [
{
'name': 'get_weather',
'description': 'Get the current weather',
'input_schema': {
'type': 'object',
'properties': {'location': {'type': 'string'}},
'required': ['location'],
},
}
]
response = instrumented_client.post(
'/v1/messages',
body={
'max_tokens': 1000,
'model': 'claude-3-haiku-20240307',
'system': 'You are a helpful assistant.',
'messages': [{'role': 'user', 'content': 'What is four plus five?'}],
'temperature': 0.7,
'top_p': 0.9,
'top_k': 40,
'stop_sequences': ['END', 'STOP'],
'tools': tools,
},
cast_to=Message,
)
assert isinstance(response.content[0], TextBlock)
assert response.content[0].text == 'Nine'
spans = exporter.exported_spans_as_dict(parse_json_attributes=True)
assert spans == snapshot(
[
{
'name': 'Message with {request_data[model]!r}',
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
'parent': None,
'start_time': 1000000000,
'end_time': 2000000000,
'attributes': {
'code.filepath': 'test_anthropic.py',
'code.function': 'test_request_parameters',
'code.lineno': 123,
'request_data': {
'max_tokens': 1000,
'messages': [{'role': 'user', 'content': 'What is four plus five?'}],
'model': 'claude-3-haiku-20240307',
'stop_sequences': ['END', 'STOP'],
'system': 'You are a helpful assistant.',
'temperature': 0.7,
'tools': [
{
'name': 'get_weather',
'description': 'Get the current weather',
'input_schema': {
'type': 'object',
'properties': {'location': {'type': 'string'}},
'required': ['location'],
},
}
],
'top_k': 40,
'top_p': 0.9,
},
'gen_ai.system': 'anthropic',
'gen_ai.provider.name': 'anthropic',
'gen_ai.operation.name': 'chat',
'gen_ai.request.model': 'claude-3-haiku-20240307',
'gen_ai.request.max_tokens': 1000,
'gen_ai.request.temperature': 0.7,
'gen_ai.request.top_p': 0.9,
'gen_ai.request.top_k': 40,
'gen_ai.request.stop_sequences': ['END', 'STOP'],
'gen_ai.tool.definitions': [
{
'name': 'get_weather',
'description': 'Get the current weather',
'input_schema': {
'type': 'object',
'properties': {'location': {'type': 'string'}},
'required': ['location'],
},
}
],
'gen_ai.input.messages': [
{'role': 'user', 'parts': [{'type': 'text', 'content': 'What is four plus five?'}]}
],
'gen_ai.system_instructions': [{'type': 'text', 'content': 'You are a helpful assistant.'}],
'async': False,
'logfire.msg_template': 'Message with {request_data[model]!r}',
'logfire.msg': "Message with 'claude-3-haiku-20240307'",
'logfire.tags': ('LLM',),
'logfire.span_type': 'span',
'response_data': {
'message': {'role': 'assistant', 'content': 'Nine'},
'usage': {
'cache_creation': None,
'cache_creation_input_tokens': None,
'cache_read_input_tokens': None,
'inference_geo': None,
'input_tokens': 2,
'output_tokens': 3,
'output_tokens_details': None,
'server_tool_use': None,
'service_tier': None,
},
},
'gen_ai.output.messages': [
{
'role': 'assistant',
'parts': [{'type': 'text', 'content': 'Nine'}],
'finish_reason': 'end_turn',
}
],
'gen_ai.response.model': 'claude-3-haiku-20240307',
'gen_ai.response.id': 'test_id',
'gen_ai.usage.input_tokens': 2,
'gen_ai.usage.output_tokens': 3,
'gen_ai.usage.raw': {'input_tokens': 2, 'output_tokens': 3},
'gen_ai.response.finish_reasons': ['end_turn'],
'operation.cost': 4.25e-06,
'logfire.json_schema': {
'type': 'object',
'properties': {
'request_data': {'type': 'object'},
'gen_ai.system': {},
'gen_ai.provider.name': {},
'gen_ai.operation.name': {},
'gen_ai.request.model': {},
'gen_ai.request.max_tokens': {},
'gen_ai.request.temperature': {},
'gen_ai.request.top_p': {},
'gen_ai.request.top_k': {},
'gen_ai.request.stop_sequences': {},
'gen_ai.tool.definitions': {},
'gen_ai.input.messages': {'type': 'array'},
'gen_ai.system_instructions': {'type': 'array'},
'async': {},
'response_data': {
'type': 'object',
'properties': {
'usage': {'type': 'object', 'title': 'Usage', 'x-python-datatype': 'PydanticModel'}
},
},
'gen_ai.output.messages': {'type': 'array'},
'gen_ai.response.model': {},
'gen_ai.response.id': {},
'gen_ai.usage.input_tokens': {},
'gen_ai.usage.output_tokens': {},
'gen_ai.usage.raw': {'type': 'object'},
'gen_ai.response.finish_reasons': {'type': 'array'},
'operation.cost': {},
},
},
},
}
]
)
def test_extract_request_parameters_without_max_tokens() -> None:
"""Test _extract_request_parameters when max_tokens is not in json_data (covers branch 37->40)."""
from logfire._internal.integrations.llm_providers.anthropic import (
_extract_request_parameters, # pyright: ignore[reportPrivateUsage]
)
# Test with no max_tokens - covers the branch where max_tokens is None
json_data: dict[str, Any] = {'temperature': 0.5}
span_data: dict[str, Any] = {}
_extract_request_parameters(json_data, span_data)
assert span_data.get('gen_ai.request.temperature') == 0.5
assert 'gen_ai.request.max_tokens' not in span_data
def test_convert_messages_no_system() -> None:
"""Test convert_messages_to_semconv with no system parameter."""
from logfire._internal.integrations.llm_providers.anthropic import convert_messages_to_semconv
input_messages, system_instructions = convert_messages_to_semconv([{'role': 'user', 'content': 'Hello'}], None)
assert (input_messages, system_instructions) == snapshot(
([{'role': 'user', 'parts': [{'type': 'text', 'content': 'Hello'}]}], [])
)
def test_convert_messages_empty_messages_and_system() -> None:
"""Test convert_messages_to_semconv with empty messages and no system."""
from logfire._internal.integrations.llm_providers.anthropic import convert_messages_to_semconv
input_messages, system_instructions = convert_messages_to_semconv([], None)
assert (input_messages, system_instructions) == snapshot(([], []))
def test_convert_messages_content_none() -> None:
"""Test convert_messages_to_semconv with a message that has content=None."""
from logfire._internal.integrations.llm_providers.anthropic import convert_messages_to_semconv
input_messages, system_instructions = convert_messages_to_semconv([{'role': 'user', 'content': None}], None)
assert (input_messages, system_instructions) == snapshot(([{'role': 'user', 'parts': []}], []))
def test_on_response_unknown_block_type() -> None:
"""Test on_response with a block that's neither text nor tool_use."""
from logfire._internal.integrations.llm_providers.anthropic import on_response
message = Message.model_construct(
id='test_id',
content=[TextBlock(text='Hello', type='text')],
model='claude-3-haiku-20240307',
role='assistant',
type='message',
stop_reason='end_turn',
usage=Usage(input_tokens=2, output_tokens=3),
)
class UnknownBlock:
type = 'thinking'
text = 'some thought'
message.content.append(UnknownBlock()) # type: ignore
class MockSpan:
def __init__(self):
self.attributes: dict[str, Any] = {}
def set_attribute(self, key: str, value: Any) -> None:
self.attributes[key] = value
def set_attributes(self, attributes: dict[str, Any]) -> None:
for key, value in attributes.items():
self.set_attribute(key, value)
span = MockSpan()
on_response(message, span, version=1) # type: ignore
assert span.attributes.get('response_data') == snapshot(
{'message': {'role': 'assistant', 'content': 'Hello'}, 'usage': Usage(input_tokens=2, output_tokens=3)}
)
def test_get_endpoint_config_v2_no_messages_no_system() -> None:
"""Test get_endpoint_config with version 2 and empty messages plus no system."""
from logfire._internal.integrations.llm_providers.anthropic import get_endpoint_config
class MockOptions:
url = '/v1/messages'
json_data: dict[str, Any] = {'model': 'claude-3-haiku', 'messages': [], 'max_tokens': 100}
config = get_endpoint_config(MockOptions(), version=2) # type: ignore
assert config.message_template == 'Message with {request_data[model]!r}'
assert 'gen_ai.input.messages' not in config.span_data
assert 'gen_ai.system_instructions' not in config.span_data
def test_get_endpoint_config_v2_messages_no_system() -> None:
"""Test get_endpoint_config with version 2 messages but no system."""
from logfire._internal.integrations.llm_providers.anthropic import get_endpoint_config
class MockOptions:
url = '/v1/messages'
json_data = {'model': 'claude-3-haiku', 'messages': [{'role': 'user', 'content': 'Hi'}], 'max_tokens': 100}
config = get_endpoint_config(MockOptions(), version=2) # type: ignore
assert 'gen_ai.input.messages' in config.span_data
assert 'gen_ai.system_instructions' not in config.span_data
@pytest.mark.vcr()
def test_sync_messages_version_latest(exporter: TestExporter) -> None:
"""Test that version='latest' uses semconv attributes with minimal request_data and no response_data."""
client = anthropic.Anthropic(api_key='foobar')
logfire.instrument_anthropic(client, version='latest')
response = client.messages.create(
max_tokens=1000,
model='claude-sonnet-4-20250514',
system='You are a helpful assistant.',
messages=[{'role': 'user', 'content': 'What is four plus five?'}],
)
assert isinstance(response.content[0], TextBlock)
assert response.content[0].text == 'Four plus five equals nine.'
assert exporter.exported_spans_as_dict(parse_json_attributes=True) == snapshot(
[
{
'name': 'Message with {request_data[model]!r}',
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
'parent': None,
'start_time': 1000000000,
'end_time': 2000000000,
'attributes': {
'code.filepath': 'test_anthropic.py',
'code.function': 'test_sync_messages_version_latest',
'code.lineno': 123,
'request_data': {'model': 'claude-sonnet-4-20250514'},
'gen_ai.system': 'anthropic',
'gen_ai.provider.name': 'anthropic',
'gen_ai.operation.name': 'chat',
'gen_ai.request.model': 'claude-sonnet-4-20250514',
'gen_ai.request.max_tokens': 1000,
'gen_ai.input.messages': [
{'role': 'user', 'parts': [{'type': 'text', 'content': 'What is four plus five?'}]}
],
'gen_ai.system_instructions': [{'type': 'text', 'content': 'You are a helpful assistant.'}],
'async': False,
'logfire.msg_template': 'Message with {request_data[model]!r}',
'logfire.msg': "Message with 'claude-sonnet-4-20250514'",
'logfire.tags': ('LLM',),
'logfire.span_type': 'span',
'gen_ai.output.messages': [
{
'role': 'assistant',
'parts': [{'type': 'text', 'content': 'Four plus five equals nine.'}],
'finish_reason': 'end_turn',
}
],
'gen_ai.response.model': 'claude-sonnet-4-20250514',
'gen_ai.response.id': IsStr(),
'gen_ai.usage.input_tokens': IsInt(),
'gen_ai.usage.output_tokens': IsInt(),
'gen_ai.usage.raw': {
'cache_creation': {'ephemeral_1h_input_tokens': 0, 'ephemeral_5m_input_tokens': 0},
'cache_creation_input_tokens': 0,
'cache_read_input_tokens': 0,
'inference_geo': 'not_available',
'input_tokens': 19,
'output_tokens': 9,
'service_tier': 'standard',
},
'gen_ai.response.finish_reasons': ['end_turn'],
'operation.cost': 0.000192,
'logfire.json_schema': {
'type': 'object',
'properties': {
'request_data': {'type': 'object'},
'gen_ai.system': {},
'gen_ai.provider.name': {},
'gen_ai.operation.name': {},
'gen_ai.request.model': {},
'gen_ai.request.max_tokens': {},
'gen_ai.input.messages': {'type': 'array'},
'gen_ai.system_instructions': {'type': 'array'},
'async': {},
'gen_ai.output.messages': {'type': 'array'},
'gen_ai.response.model': {},
'gen_ai.response.id': {},
'gen_ai.usage.input_tokens': {},
'gen_ai.usage.output_tokens': {},
'gen_ai.usage.raw': {'type': 'object'},
'gen_ai.response.finish_reasons': {'type': 'array'},
'operation.cost': {},
},
},
},
}
]
)
@pytest.mark.vcr()
def test_sync_messages_version_v1_only(exporter: TestExporter) -> None:
"""Test that version=1 does not emit gen_ai.input.messages or gen_ai.output.messages."""
client = anthropic.Anthropic(api_key='foobar')
logfire.instrument_anthropic(client, version=1)
response = client.messages.create(
max_tokens=1000,
model='claude-sonnet-4-20250514',
system='You are a helpful assistant.',
messages=[{'role': 'user', 'content': 'What is four plus five?'}],
)
assert isinstance(response.content[0], TextBlock)
assert response.content[0].text == 'Four plus five equals nine.'
assert exporter.exported_spans_as_dict(parse_json_attributes=True) == snapshot(
[
{
'name': 'Message with {request_data[model]!r}',
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
'parent': None,
'start_time': 1000000000,
'end_time': 2000000000,
'attributes': {
'code.filepath': 'test_anthropic.py',
'code.function': 'test_sync_messages_version_v1_only',
'code.lineno': 123,
'request_data': {
'max_tokens': 1000,
'messages': [{'role': 'user', 'content': 'What is four plus five?'}],
'model': 'claude-sonnet-4-20250514',
'system': 'You are a helpful assistant.',
},
'gen_ai.system': 'anthropic',
'gen_ai.provider.name': 'anthropic',
'gen_ai.operation.name': 'chat',
'gen_ai.request.model': 'claude-sonnet-4-20250514',
'gen_ai.request.max_tokens': 1000,
'async': False,
'logfire.msg_template': 'Message with {request_data[model]!r}',
'logfire.msg': "Message with 'claude-sonnet-4-20250514'",
'logfire.tags': ('LLM',),
'logfire.span_type': 'span',
'response_data': {
'message': {'role': 'assistant', 'content': 'Four plus five equals nine.'},
'usage': {
'cache_creation': {
'ephemeral_1h_input_tokens': IsInt(),
'ephemeral_5m_input_tokens': IsInt(),
},
'cache_creation_input_tokens': IsInt(),
'cache_read_input_tokens': IsInt(),
'inference_geo': IsStr(),
'input_tokens': IsInt(),
'output_tokens': IsInt(),
'output_tokens_details': None,
'server_tool_use': None,
'service_tier': IsStr(),
},
},
'gen_ai.response.model': 'claude-sonnet-4-20250514',
'gen_ai.response.id': IsStr(),
'gen_ai.usage.input_tokens': IsInt(),
'gen_ai.usage.output_tokens': IsInt(),
'gen_ai.usage.raw': {
'cache_creation': {'ephemeral_1h_input_tokens': 0, 'ephemeral_5m_input_tokens': 0},
'cache_creation_input_tokens': 0,
'cache_read_input_tokens': 0,
'inference_geo': 'not_available',
'input_tokens': 19,
'output_tokens': 9,
'service_tier': 'standard',
},
'gen_ai.response.finish_reasons': ['end_turn'],
'operation.cost': 0.000192,
'logfire.json_schema': {
'type': 'object',
'properties': {
'request_data': {'type': 'object'},
'gen_ai.system': {},
'gen_ai.provider.name': {},
'gen_ai.operation.name': {},
'gen_ai.request.model': {},
'gen_ai.request.max_tokens': {},
'async': {},
'response_data': {
'type': 'object',
'properties': {
'usage': {
'type': 'object',
'title': 'Usage',
'x-python-datatype': 'PydanticModel',
'properties': {
'cache_creation': {
'type': 'object',
'title': 'CacheCreation',
'x-python-datatype': 'PydanticModel',
}
},
}
},
},
'gen_ai.response.model': {},
'gen_ai.response.id': {},
'gen_ai.usage.input_tokens': {},
'gen_ai.usage.output_tokens': {},
'gen_ai.usage.raw': {'type': 'object'},
'gen_ai.response.finish_reasons': {'type': 'array'},
'operation.cost': {},
},
},
},
}
]
)
@pytest.mark.vcr()
def test_sync_messages_stream_version_latest(exporter: TestExporter) -> None:
"""Test that streaming with version='latest' emits semconv attributes without response_data."""
client = anthropic.Anthropic(api_key='foobar')
logfire.instrument_anthropic(client, version='latest')
response = client.messages.create(
max_tokens=1000,
model='claude-sonnet-4-20250514',
system='You are a helpful assistant.',
messages=[{'role': 'user', 'content': 'What is four plus five?'}],
stream=True,
)
with response as stream:
combined = ''.join(
chunk.delta.text # type: ignore
for chunk in stream
if hasattr(chunk, 'delta') and isinstance(chunk.delta, TextDelta) # type: ignore
)
assert combined == 'Four plus five equals nine.'
assert exporter.exported_spans_as_dict(parse_json_attributes=True) == snapshot(
[
{
'name': 'Message with {request_data[model]!r}',
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
'parent': None,
'start_time': 1000000000,
'end_time': 2000000000,
'attributes': {
'code.filepath': 'test_anthropic.py',
'code.function': 'test_sync_messages_stream_version_latest',
'code.lineno': 123,
'request_data': {'model': 'claude-sonnet-4-20250514'},
'gen_ai.system': 'anthropic',
'gen_ai.provider.name': 'anthropic',
'gen_ai.operation.name': 'chat',
'gen_ai.request.model': 'claude-sonnet-4-20250514',
'gen_ai.request.max_tokens': 1000,
'gen_ai.input.messages': [
{'role': 'user', 'parts': [{'type': 'text', 'content': 'What is four plus five?'}]}
],
'gen_ai.system_instructions': [{'type': 'text', 'content': 'You are a helpful assistant.'}],
'async': False,
'logfire.msg_template': 'Message with {request_data[model]!r}',
'logfire.msg': "Message with 'claude-sonnet-4-20250514'",
'logfire.json_schema': {
'type': 'object',
'properties': {
'request_data': {'type': 'object'},
'gen_ai.system': {},
'gen_ai.provider.name': {},
'gen_ai.operation.name': {},
'gen_ai.request.model': {},
'gen_ai.request.max_tokens': {},
'gen_ai.input.messages': {'type': 'array'},
'gen_ai.system_instructions': {'type': 'array'},
'async': {},
},
},
'logfire.tags': ('LLM',),
'logfire.span_type': 'span',
'gen_ai.response.model': 'claude-sonnet-4-20250514',
},
},
{
'name': 'streaming response from {request_data[model]!r} took {duration:.2f}s',
'context': {'trace_id': 2, 'span_id': 3, 'is_remote': False},
'parent': None,
'start_time': 5000000000,
'end_time': 5000000000,
'attributes': {
'logfire.span_type': 'log',
'logfire.level_num': 9,
'logfire.msg_template': 'streaming response from {request_data[model]!r} took {duration:.2f}s',
'logfire.msg': "streaming response from 'claude-sonnet-4-20250514' took 1.00s",
'code.filepath': 'test_anthropic.py',
'code.function': '<genexpr>',
'code.lineno': 123,
'duration': 1.0,
'request_data': {'model': 'claude-sonnet-4-20250514'},
'gen_ai.system': 'anthropic',
'gen_ai.provider.name': 'anthropic',
'gen_ai.operation.name': 'chat',
'gen_ai.request.model': 'claude-sonnet-4-20250514',
'gen_ai.request.max_tokens': 1000,
'gen_ai.input.messages': [
{'role': 'user', 'parts': [{'type': 'text', 'content': 'What is four plus five?'}]}
],
'gen_ai.system_instructions': [{'type': 'text', 'content': 'You are a helpful assistant.'}],
'async': False,
'gen_ai.output.messages': [
{
'role': 'assistant',
'parts': [{'type': 'text', 'content': 'Four plus five equals nine.'}],
'finish_reason': 'end_turn',
}
],
'gen_ai.usage.input_tokens': 19,
'gen_ai.usage.output_tokens': 9,
'gen_ai.usage.raw': {
'cache_creation': {'ephemeral_1h_input_tokens': 0, 'ephemeral_5m_input_tokens': 0},
'cache_creation_input_tokens': 0,
'cache_read_input_tokens': 0,
'inference_geo': 'not_available',
'input_tokens': 19,
'output_tokens': 9,
'service_tier': 'standard',
},
'operation.cost': 0.000192,
'logfire.json_schema': {
'type': 'object',
'properties': {
'duration': {},
'request_data': {'type': 'object'},
'gen_ai.system': {},
'gen_ai.provider.name': {},
'gen_ai.operation.name': {},
'gen_ai.request.model': {},
'gen_ai.request.max_tokens': {},
'gen_ai.input.messages': {'type': 'array'},
'gen_ai.system_instructions': {'type': 'array'},
'async': {},
'gen_ai.output.messages': {'type': 'array'},
'gen_ai.usage.input_tokens': {},
'gen_ai.usage.output_tokens': {},
'gen_ai.usage.raw': {'type': 'object'},
'operation.cost': {},
},
},
'logfire.tags': ('LLM',),
'gen_ai.response.model': 'claude-sonnet-4-20250514',
},
},
]
)
@pytest.mark.vcr()
def test_sync_messages_stream_version_v1_only(exporter: TestExporter) -> None:
"""Test that streaming with version=1 emits response_data without semconv message attributes."""
client = anthropic.Anthropic(api_key='foobar')
logfire.instrument_anthropic(client, version=1)
response = client.messages.create(
max_tokens=1000,
model='claude-sonnet-4-20250514',
system='You are a helpful assistant.',
messages=[{'role': 'user', 'content': 'What is four plus five?'}],
stream=True,
)
with response as stream:
combined = ''.join(
chunk.delta.text # type: ignore
for chunk in stream
if hasattr(chunk, 'delta') and isinstance(chunk.delta, TextDelta) # type: ignore
)
assert combined == 'Four plus five equals nine.'
assert exporter.exported_spans_as_dict(parse_json_attributes=True) == snapshot(
[
{
'name': 'Message with {request_data[model]!r}',
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
'parent': None,
'start_time': 1000000000,
'end_time': 2000000000,
'attributes': {
'code.filepath': 'test_anthropic.py',
'code.function': 'test_sync_messages_stream_version_v1_only',
'code.lineno': 123,
'request_data': {
'max_tokens': 1000,
'messages': [{'role': 'user', 'content': 'What is four plus five?'}],
'model': 'claude-sonnet-4-20250514',
'stream': True,
'system': 'You are a helpful assistant.',
},
'gen_ai.system': 'anthropic',
'gen_ai.provider.name': 'anthropic',
'gen_ai.operation.name': 'chat',
'gen_ai.request.model': 'claude-sonnet-4-20250514',
'gen_ai.request.max_tokens': 1000,
'async': False,
'logfire.msg_template': 'Message with {request_data[model]!r}',
'logfire.msg': "Message with 'claude-sonnet-4-20250514'",
'logfire.json_schema': {
'type': 'object',
'properties': {
'request_data': {'type': 'object'},
'gen_ai.system': {},
'gen_ai.provider.name': {},
'gen_ai.operation.name': {},
'gen_ai.request.model': {},
'gen_ai.request.max_tokens': {},
'async': {},
},
},
'logfire.tags': ('LLM',),
'logfire.span_type': 'span',
'gen_ai.response.model': 'claude-sonnet-4-20250514',
},
},
{
'name': 'streaming response from {request_data[model]!r} took {duration:.2f}s',
'context': {'trace_id': 2, 'span_id': 3, 'is_remote': False},
'parent': None,
'start_time': 5000000000,
'end_time': 5000000000,
'attributes': {
'logfire.span_type': 'log',
'logfire.level_num': 9,
'logfire.msg_template': 'streaming response from {request_data[model]!r} took {duration:.2f}s',
'logfire.msg': "streaming response from 'claude-sonnet-4-20250514' took 1.00s",
'code.filepath': 'test_anthropic.py',
'code.function': '<genexpr>',
'code.lineno': 123,
'duration': 1.0,
'request_data': {
'max_tokens': 1000,
'messages': [{'role': 'user', 'content': 'What is four plus five?'}],
'model': 'claude-sonnet-4-20250514',
'stream': True,
'system': 'You are a helpful assistant.',
},
'gen_ai.system': 'anthropic',
'gen_ai.provider.name': 'anthropic',
'gen_ai.operation.name': 'chat',
'gen_ai.request.model': 'claude-sonnet-4-20250514',
'gen_ai.request.max_tokens': 1000,
'async': False,
'response_data': {'combined_chunk_content': 'Four plus five equals nine.', 'chunk_count': IsInt()},
'gen_ai.usage.input_tokens': 19,
'gen_ai.usage.output_tokens': 9,
'gen_ai.usage.raw': {
'cache_creation': {'ephemeral_1h_input_tokens': 0, 'ephemeral_5m_input_tokens': 0},
'cache_creation_input_tokens': 0,
'cache_read_input_tokens': 0,
'inference_geo': 'not_available',
'input_tokens': 19,
'output_tokens': 9,
'service_tier': 'standard',
},
'operation.cost': 0.000192,
'logfire.json_schema': {
'type': 'object',
'properties': {
'duration': {},
'request_data': {'type': 'object'},
'gen_ai.system': {},
'gen_ai.provider.name': {},
'gen_ai.operation.name': {},
'gen_ai.request.model': {},
'gen_ai.request.max_tokens': {},
'async': {},
'response_data': {'type': 'object'},
'gen_ai.usage.input_tokens': {},
'gen_ai.usage.output_tokens': {},
'gen_ai.usage.raw': {'type': 'object'},
'operation.cost': {},
},
},
'logfire.tags': ('LLM',),
'gen_ai.response.model': 'claude-sonnet-4-20250514',
},
},
]
)
@pytest.mark.vcr()
def test_sync_messages_beta_stream(exporter: TestExporter) -> None:
client = anthropic.Anthropic(api_key='foobar')
logfire.instrument_anthropic(client, version=['latest', 1])
response = client.beta.messages.create(
max_tokens=1000,
model='claude-sonnet-4-20250514',
system='You are a helpful assistant.',
messages=[{'role': 'user', 'content': [{'text': 'What is four plus five?', 'type': 'text'}]}],
stream=True,
)
with response as stream:
combined = ''.join(
chunk.delta.text # type: ignore
for chunk in stream
if hasattr(chunk, 'delta') and hasattr(chunk.delta, 'text') # type: ignore
)
assert combined == snapshot('Four plus five equals nine.')
assert exporter.exported_spans_as_dict(parse_json_attributes=True) == snapshot(
[
{
'name': 'Message with {request_data[model]!r}',
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
'parent': None,
'start_time': 1000000000,
'end_time': 2000000000,
'attributes': {
'code.filepath': 'test_anthropic.py',
'code.function': 'test_sync_messages_beta_stream',
'code.lineno': 123,
'request_data': {
'max_tokens': 1000,
'messages': [
{'role': 'user', 'content': [{'text': 'What is four plus five?', 'type': 'text'}]}
],
'model': 'claude-sonnet-4-20250514',
'stream': True,
'system': 'You are a helpful assistant.',
},
'gen_ai.system': 'anthropic',
'gen_ai.provider.name': 'anthropic',
'gen_ai.operation.name': 'chat',
'gen_ai.request.model': 'claude-sonnet-4-20250514',
'gen_ai.request.max_tokens': 1000,
'gen_ai.input.messages': [
{'role': 'user', 'parts': [{'type': 'text', 'content': 'What is four plus five?'}]}
],
'gen_ai.system_instructions': [{'type': 'text', 'content': 'You are a helpful assistant.'}],
'async': False,
'logfire.msg_template': 'Message with {request_data[model]!r}',
'logfire.msg': "Message with 'claude-sonnet-4-20250514'",
'logfire.json_schema': {
'type': 'object',
'properties': {
'request_data': {'type': 'object'},
'gen_ai.system': {},
'gen_ai.provider.name': {},
'gen_ai.operation.name': {},
'gen_ai.request.model': {},
'gen_ai.request.max_tokens': {},
'gen_ai.input.messages': {'type': 'array'},
'gen_ai.system_instructions': {'type': 'array'},
'async': {},
},
},
'logfire.tags': ('LLM',),
'logfire.span_type': 'span',
'gen_ai.response.model': 'claude-sonnet-4-20250514',
},
},
{
'name': 'streaming response from {request_data[model]!r} took {duration:.2f}s',
'context': {'trace_id': 2, 'span_id': 3, 'is_remote': False},
'parent': None,
'start_time': 5000000000,
'end_time': 5000000000,
'attributes': {
'logfire.span_type': 'log',
'logfire.level_num': 9,
'logfire.msg_template': 'streaming response from {request_data[model]!r} took {duration:.2f}s',
'logfire.msg': "streaming response from 'claude-sonnet-4-20250514' took 1.00s",
'code.filepath': 'test_anthropic.py',
'code.function': '<genexpr>',
'code.lineno': 123,
'duration': 1.0,
'request_data': {
'max_tokens': 1000,
'messages': [
{'role': 'user', 'content': [{'text': 'What is four plus five?', 'type': 'text'}]}
],
'model': 'claude-sonnet-4-20250514',
'stream': True,
'system': 'You are a helpful assistant.',
},
'gen_ai.system': 'anthropic',
'gen_ai.provider.name': 'anthropic',
'gen_ai.operation.name': 'chat',
'gen_ai.request.model': 'claude-sonnet-4-20250514',
'gen_ai.request.max_tokens': 1000,
'gen_ai.input.messages': [
{'role': 'user', 'parts': [{'type': 'text', 'content': 'What is four plus five?'}]}
],
'gen_ai.system_instructions': [{'type': 'text', 'content': 'You are a helpful assistant.'}],
'async': False,
'response_data': {'combined_chunk_content': 'Four plus five equals nine.', 'chunk_count': 3},
'gen_ai.output.messages': [
{
'role': 'assistant',
'parts': [{'type': 'text', 'content': 'Four plus five equals nine.'}],
'finish_reason': 'end_turn',
}
],
'gen_ai.usage.input_tokens': 19,
'gen_ai.usage.output_tokens': 9,
'gen_ai.usage.raw': {
'cache_creation': {'ephemeral_1h_input_tokens': 0, 'ephemeral_5m_input_tokens': 0},
'cache_creation_input_tokens': 0,
'cache_read_input_tokens': 0,
'inference_geo': 'not_available',
'input_tokens': 19,
'output_tokens': 9,
'service_tier': 'standard',
},
'operation.cost': 0.000192,
'logfire.json_schema': {
'type': 'object',
'properties': {
'duration': {},
'request_data': {'type': 'object'},
'gen_ai.system': {},
'gen_ai.provider.name': {},
'gen_ai.operation.name': {},
'gen_ai.request.model': {},
'gen_ai.request.max_tokens': {},
'gen_ai.input.messages': {'type': 'array'},
'gen_ai.system_instructions': {'type': 'array'},
'async': {},
'response_data': {'type': 'object'},
'gen_ai.output.messages': {'type': 'array'},
'gen_ai.usage.input_tokens': {},
'gen_ai.usage.output_tokens': {},
'gen_ai.usage.raw': {'type': 'object'},
'operation.cost': {},
},
},
'logfire.tags': ('LLM',),
'gen_ai.response.model': 'claude-sonnet-4-20250514',
},
},
]
)
@pytest.mark.vcr()
async def test_async_beta_messages(exporter: TestExporter) -> None:
client = anthropic.AsyncAnthropic()
logfire.instrument_anthropic(client, version=['latest', 1])
response = await client.beta.messages.create(
max_tokens=1000,
model='claude-3-haiku-20240307',
system='You are a helpful assistant.',
messages=[{'role': 'user', 'content': 'What is four plus five?'}],
)
assert response.content[0].model_dump() == snapshot({'citations': None, 'text': '4 + 5 = 9.', 'type': 'text'})
assert exporter.exported_spans_as_dict(parse_json_attributes=True) == snapshot(
[
{
'name': 'Message with {request_data[model]!r}',
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
'parent': None,
'start_time': 1000000000,
'end_time': 2000000000,
'attributes': {
'code.filepath': 'test_anthropic.py',
'code.function': 'test_async_beta_messages',
'code.lineno': 123,
'request_data': {
'max_tokens': 1000,
'messages': [{'role': 'user', 'content': 'What is four plus five?'}],
'model': 'claude-3-haiku-20240307',
'system': 'You are a helpful assistant.',
},
'gen_ai.system': 'anthropic',
'gen_ai.provider.name': 'anthropic',
'gen_ai.operation.name': 'chat',
'gen_ai.request.model': 'claude-3-haiku-20240307',
'gen_ai.request.max_tokens': 1000,
'gen_ai.input.messages': [
{'role': 'user', 'parts': [{'type': 'text', 'content': 'What is four plus five?'}]}
],
'gen_ai.system_instructions': [{'type': 'text', 'content': 'You are a helpful assistant.'}],
'async': True,
'logfire.msg_template': 'Message with {request_data[model]!r}',
'logfire.msg': "Message with 'claude-3-haiku-20240307'",
'logfire.tags': ('LLM',),
'logfire.span_type': 'span',
'response_data': {
'message': {'role': 'assistant', 'content': '4 + 5 = 9.'},
'usage': {
'cache_creation': {'ephemeral_1h_input_tokens': 0, 'ephemeral_5m_input_tokens': 0},
'cache_creation_input_tokens': 0,
'cache_read_input_tokens': 0,
'fallback_credit': None,
'inference_geo': 'not_available',
'input_tokens': 19,
'iterations': None,
'output_tokens': 14,
'output_tokens_details': None,
'server_tool_use': None,
'service_tier': 'standard',
'speed': None,
},
},
'gen_ai.output.messages': [
{
'role': 'assistant',
'parts': [{'type': 'text', 'content': '4 + 5 = 9.'}],
'finish_reason': 'end_turn',
}
],
'gen_ai.response.model': 'claude-3-haiku-20240307',
'gen_ai.response.id': 'msg_01HJB23z1SCp7SjLxmybeqgF',
'gen_ai.usage.input_tokens': 19,
'gen_ai.usage.output_tokens': 14,
'gen_ai.usage.raw': {
'cache_creation': {'ephemeral_1h_input_tokens': 0, 'ephemeral_5m_input_tokens': 0},
'cache_creation_input_tokens': 0,
'cache_read_input_tokens': 0,
'inference_geo': 'not_available',
'input_tokens': 19,
'output_tokens': 14,
'service_tier': 'standard',
},
'gen_ai.response.finish_reasons': ['end_turn'],
'operation.cost': 2.225e-05,
'logfire.json_schema': {
'type': 'object',
'properties': {
'request_data': {'type': 'object'},
'gen_ai.system': {},
'gen_ai.provider.name': {},
'gen_ai.operation.name': {},
'gen_ai.request.model': {},
'gen_ai.request.max_tokens': {},
'gen_ai.input.messages': {'type': 'array'},
'gen_ai.system_instructions': {'type': 'array'},
'async': {},
'response_data': {
'type': 'object',
'properties': {
'usage': {
'type': 'object',
'title': 'BetaUsage',
'x-python-datatype': 'PydanticModel',
'properties': {
'cache_creation': {
'type': 'object',
'title': 'BetaCacheCreation',
'x-python-datatype': 'PydanticModel',
}
},
}
},
},
'gen_ai.output.messages': {'type': 'array'},
'gen_ai.response.model': {},
'gen_ai.response.id': {},
'gen_ai.usage.input_tokens': {},
'gen_ai.usage.output_tokens': {},
'gen_ai.usage.raw': {'type': 'object'},
'gen_ai.response.finish_reasons': {'type': 'array'},
'operation.cost': {},
},
},
},
}
]
)
from __future__ import annotations as _annotations
import gc
import json
import logging
from collections.abc import AsyncIterator, Iterator
from inspect import signature
from typing import Any, cast
import anthropic
import httpx2 as httpx
import pydantic
import pytest
from anthropic.types import (
Message,
MessageDeltaUsage,
MessageStartEvent,
MessageStopEvent,
TextBlock,
TextDelta,
Usage,
)
from dirty_equals import IsInt, IsPartialDict, IsStr
from httpx2 import MockTransport
from inline_snapshot import snapshot
import logfire
from logfire._internal.utils import get_version
from logfire.testing import TestExporter
pytestmark = [
pytest.mark.skipif(
get_version(pydantic.__version__) < get_version('2.5'),
reason='Requires Pydantic 2.5 or higher to import genai-prices and set operation.cost attribute.',
),
]
ANY_ADAPTER = pydantic.TypeAdapter(Any) # type: ignore
def test_semconv_version_defaults() -> None:
from logfire._internal.integrations.llm_providers.anthropic import get_endpoint_config
assert signature(logfire.instrument_anthropic).parameters['version'].default == 2
class MockOptions:
url = '/v1/messages'
json_data = {'model': 'claude-haiku-4-5', 'messages': [{'role': 'user', 'content': 'Hello'}]}
config = get_endpoint_config(MockOptions()) # type: ignore
assert config.span_data['request_data'] == {'model': 'claude-haiku-4-5'}
assert config.span_data['gen_ai.input.messages'] == [
{'role': 'user', 'parts': [{'type': 'text', 'content': 'Hello'}]}
]
def request_handler(request: httpx.Request) -> httpx.Response:
"""Used to mock httpx requests
We do this instead of using pytest-httpx since 1) it's nearly as simple 2) pytest-httpx doesn't support Python 3.8.
(We no longer support 3.8 either, but it's not worth changing this now)
"""
assert request.method == 'POST'
if request.url == 'https://api.anthropic.com/v1/complete':
return httpx.Response(
200,
json={'id': 'test_id', 'completion': 'completion', 'model': 'claude-2.1', 'type': 'completion'},
)
assert request.url in ['https://api.anthropic.com/v1/messages'], f'Unexpected URL: {request.url}'
json_body = json.loads(request.content)
if json_body.get('stream'):
if json_body['system'] == 'empty response chunk':
return httpx.Response(200, text='data: []\n\n')
else:
chunks = [
MessageStartEvent(
message=Message(
id='test_id',
content=[],
model='claude-3-haiku-20240307',
role='assistant',
stop_reason=None,
stop_sequence=None,
type='message',
usage=Usage(input_tokens=25, output_tokens=25),
),
type='message_start',
),
dict(content_block=TextBlock(text='', type='text'), index=0, type='content_block_start'),
dict(delta=TextDelta(text='The answer', type='text_delta'), index=0, type='content_block_delta'),
dict(delta=TextDelta(text=' is secret', type='text_delta'), index=0, type='content_block_delta'),
dict(index=0, type='content_block_stop'),
dict(
delta=dict(stop_reason='end_turn', stop_sequence=None),
type='message_delta',
usage=MessageDeltaUsage(output_tokens=55),
),
MessageStopEvent(type='message_stop'),
]
Xet Storage Details
- Size:
- 102 kB
- Xet hash:
- 54e099e5a482cd5d547595b66ccc24515377ddd1d7934a26c82c4c12b65b1955
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.