Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
14 changes: 13 additions & 1 deletion pydantic_ai_slim/pydantic_ai/models/instrumented.py
Original file line number Diff line number Diff line change
Expand Up @@ -420,10 +420,18 @@ def _record_metrics():
return

self.instrumentation_settings.handle_messages(messages, response, system, span)

cost_attributes = {}
try:
cost_attributes = {'operation.cost': float(response.cost().total_price)}
except LookupError:
cost_attributes = {}
# The cost of this provider/model is unknown, which is common.
pass
except Exception as e:
warnings.warn(
f'Failed to get cost from response: {type(e).__name__}: {e}', CostCalculationFailedWarning
)

span.set_attributes(
{
**response.usage.opentelemetry_attributes(),
Expand Down Expand Up @@ -478,3 +486,7 @@ def serialize_any(value: Any) -> str:
return str(value)
except Exception as e:
return f'Unable to serialize: {e}'


class CostCalculationFailedWarning(Warning):
"""Warning raised when cost calculation fails."""
2 changes: 1 addition & 1 deletion pydantic_ai_slim/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ dependencies = [
"exceptiongroup; python_version < '3.11'",
"opentelemetry-api>=1.28.0",
"typing-inspection>=0.4.0",
"genai-prices>=0.0.22",
"genai-prices>=0.0.23",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There was a significant fix in price calculation logic released here, so I think this needs to be the minimum.

]

[tool.hatch.metadata.hooks.uv-dynamic-versioning.optional-dependencies]
Expand Down
70 changes: 70 additions & 0 deletions tests/models/test_instrumented.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import pytest
from inline_snapshot import snapshot
from inline_snapshot.extra import warns
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cute.

from logfire_api import DEFAULT_LOGFIRE_INSTANCE
from opentelemetry._events import NoOpEventLoggerProvider
from opentelemetry.trace import NoOpTracerProvider
Expand Down Expand Up @@ -1274,3 +1275,72 @@ def test_deprecated_event_mode_warning():
assert settings.event_mode == 'logs'
assert settings.version == 1
assert InstrumentationSettings().version == 2


async def test_response_cost_error(capfire: CaptureLogfire, monkeypatch: pytest.MonkeyPatch):
model = InstrumentedModel(MyModel())

messages: list[ModelMessage] = [ModelRequest(parts=[UserPromptPart('user_prompt')])]
monkeypatch.setattr(ModelResponse, 'cost', None)

with warns(
snapshot(
[
"CostCalculationFailedWarning: Failed to get cost from response: TypeError: 'NoneType' object is not callable"
]
)
):
await model.request(messages, model_settings=ModelSettings(), model_request_parameters=ModelRequestParameters())

assert capfire.exporter.exported_spans_as_dict(parse_json_attributes=True) == snapshot(
[
{
'name': 'chat gpt-4o',
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
'parent': None,
'start_time': 1000000000,
'end_time': 2000000000,
'attributes': {
'gen_ai.operation.name': 'chat',
'gen_ai.system': 'openai',
'gen_ai.request.model': 'gpt-4o',
'server.address': 'example.com',
'server.port': 8000,
'model_request_parameters': {
'function_tools': [],
'builtin_tools': [],
'output_mode': 'text',
'output_object': None,
'output_tools': [],
'allow_text_output': True,
},
'logfire.span_type': 'span',
'logfire.msg': 'chat gpt-4o',
'gen_ai.input.messages': [{'role': 'user', 'parts': [{'type': 'text', 'content': 'user_prompt'}]}],
'gen_ai.output.messages': [
{
'role': 'assistant',
'parts': [
{'type': 'text', 'content': 'text1'},
{'type': 'tool_call', 'id': 'tool_call_1', 'name': 'tool1', 'arguments': 'args1'},
{'type': 'tool_call', 'id': 'tool_call_2', 'name': 'tool2', 'arguments': {'args2': 3}},
{'type': 'text', 'content': 'text2'},
],
'finish_reason': 'stop',
}
],
'logfire.json_schema': {
'type': 'object',
'properties': {
'gen_ai.input.messages': {'type': 'array'},
'gen_ai.output.messages': {'type': 'array'},
'model_request_parameters': {'type': 'object'},
},
},
'gen_ai.usage.input_tokens': 100,
'gen_ai.usage.output_tokens': 200,
'gen_ai.response.model': 'gpt-4o-2024-11-20',
},
}
]
)
10 changes: 5 additions & 5 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading