Skip to content

⚡️ Speed up function _map_usage by 42% #29

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: try-refinement
Choose a base branch
from
Open
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
10 changes: 6 additions & 4 deletions pydantic_ai_slim/pydantic_ai/models/anthropic.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from ..settings import ModelSettings
from ..tools import ToolDefinition
from . import Model, ModelRequestParameters, StreamedResponse, check_allow_model_requests, download_item, get_user_agent
from anthropic.types.beta import BetaMessage, BetaRawMessageDeltaEvent, BetaRawMessageStartEvent, BetaRawMessageStreamEvent

try:
from anthropic import NOT_GIVEN, APIStatusError, AsyncAnthropic, AsyncStream
Expand Down Expand Up @@ -425,11 +426,11 @@ def _map_tool_definition(f: ToolDefinition) -> BetaToolParam:


def _map_usage(message: BetaMessage | BetaRawMessageStreamEvent) -> usage.Usage:
if isinstance(message, BetaMessage):
if type(message) is BetaMessage:
response_usage = message.usage
elif isinstance(message, BetaRawMessageStartEvent):
elif type(message) is BetaRawMessageStartEvent:
response_usage = message.message.usage
elif isinstance(message, BetaRawMessageDeltaEvent):
elif type(message) is BetaRawMessageDeltaEvent:
response_usage = message.usage
else:
# No usage information provided in:
Expand All @@ -441,8 +442,9 @@ def _map_usage(message: BetaMessage | BetaRawMessageStreamEvent) -> usage.Usage:

# Store all integer-typed usage values in the details, except 'output_tokens' which is represented exactly by
# `response_tokens`
usage_dict = response_usage.model_dump()
details: dict[str, int] = {
key: value for key, value in response_usage.model_dump().items() if isinstance(value, int)
key: value for key, value in usage_dict.items() if isinstance(value, int)
}

# Usage coming from the RawMessageDeltaEvent doesn't have input token data, hence using `get`
Expand Down
Loading