Skip to content

⚡️ Speed up function multi_modal_content_identifier by 137% #26

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
9 changes: 8 additions & 1 deletion pydantic_ai_slim/pydantic_ai/_agent_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from .output import OutputDataT, OutputSpec
from .settings import ModelSettings, merge_model_settings
from .tools import RunContext, Tool, ToolDefinition, ToolsPrepareFunc
import functools

if TYPE_CHECKING:
from .mcp import MCPServer
Expand Down Expand Up @@ -617,7 +618,7 @@ def multi_modal_content_identifier(identifier: str | bytes) -> str:
"""Generate stable identifier for multi-modal content to help LLM in finding a specific file in tool call responses."""
if isinstance(identifier, str):
identifier = identifier.encode('utf-8')
return hashlib.sha1(identifier).hexdigest()[:6]
return _multi_modal_content_identifier_cached(identifier)


async def process_function_tools( # noqa C901
Expand Down Expand Up @@ -977,3 +978,9 @@ async def _process_message_history(
sync_processor = cast(_HistoryProcessorSync, processor)
messages = await run_in_executor(sync_processor, messages)
return messages


@functools.lru_cache(maxsize=4096)
def _multi_modal_content_identifier_cached(identifier_bytes: bytes) -> str:
# Get the first 3 bytes (6 hex chars) directly
return hashlib.sha1(identifier_bytes).digest()[:3].hex()
Loading