跳转至

类型定义

本节记录 ToolRegistry 面向 LLM API 的类型定义。

工具调用类型

用于转换不同 provider payload 的标准化工具调用和工具结果模型。

toolregistry.llm.tool_calls

Unified tool call types and format conversion via llm-rosetta.

Provides :class:ToolCall, :class:ToolCallResult, and :class:ErrorResult as toolregistry's internal representations, plus thin wrappers around llm-rosetta for converting between provider-specific API formats.

BaseResult dataclass

BaseResult(id: str, name: str)

Base class for tool call results.

Fields align with rosetta's ToolResultPart IR so that conversion is a trivial field mapping.

id instance-attribute

id: str

Tool call ID.

name instance-attribute

name: str

Tool name.

ErrorResult dataclass

ErrorResult(id: str, name: str, message: str = '')

Bases: BaseResult

Failed tool call result.

The message field uses "ExceptionType: detail" format (like the last line of a Python traceback) so both humans and LLMs can parse it naturally.

Attributes:

Name Type Description
message str

Error description, e.g. "ValueError: division by zero".

from_ir classmethod

from_ir(ir: dict[str, Any], name: str = '') -> ErrorResult

Create from a rosetta ToolResultPart dict with is_error=True.

to_ir

to_ir() -> dict[str, Any]

Convert to a rosetta ToolResultPart dict.

ResultList

ResultList(items: list | None = None)

Bases: list

List subclass with O(1) lookup by tool call ID.

Returned by :meth:ToolRegistry.execute_tool_calls. Supports normal list iteration and fast by_id() access::

results = registry.execute_tool_calls(tool_calls)
r = results.by_id("call_1")       # O(1)
r = results["call_1"]             # same, via __getitem__

by_id

by_id(call_id: str) -> ToolCallResult | ErrorResult

Look up a result by tool call ID.

Parameters:

Name Type Description Default
call_id str

The tool call ID.

required

Returns:

Type Description
ToolCallResult | ErrorResult

The matching result.

Raises:

Type Description
KeyError

If no result with the given ID exists.

ToolCall

Bases: BaseModel

Toolregistry's normalized tool call representation.

All provider formats are converted to/from this type via the rosetta shim layer below.

arguments instance-attribute

arguments: str

The arguments in JSON string format.

id instance-attribute

id: str

The ID of the tool call.

name instance-attribute

name: str

The name of the function to call.

type class-attribute instance-attribute

type: Literal['function', 'custom'] = 'function'

The type of the tool call.

from_ir classmethod

from_ir(ir: dict[str, Any]) -> ToolCall

Create from a rosetta IR ToolCallPart dict.

from_tool_call classmethod

from_tool_call(tool_call: Any) -> ToolCall

Convert any provider tool call format to ToolCall.

Delegates format detection and parsing to llm-rosetta, then converts through the IR shim.

Parameters:

Name Type Description Default
tool_call Any

Tool call in any supported provider format (dict, Pydantic model, or raw object).

required

Returns:

Type Description
ToolCall

Normalized ToolCall.

Raises:

Type Description
TypeError

If the format is not recognized by any provider.

to_ir

to_ir() -> dict[str, Any]

Convert to a rosetta IR ToolCallPart dict.

ToolCallResult dataclass

ToolCallResult(id: str, name: str, result: str | list = '')

Bases: BaseResult

Successful tool call result.

Attributes:

Name Type Description
result str | list

The tool output — str for text results, list[ContentBlock] for multimodal results.

from_ir classmethod

from_ir(ir: dict[str, Any], name: str = '') -> ToolCallResult

Create from a rosetta ToolResultPart dict.

to_ir

to_ir() -> dict[str, Any]

Convert to a rosetta ToolResultPart dict.

build_assistant_message

build_assistant_message(tool_calls: list[ToolCall], *, api_format: API_FORMATS = 'openai-chat') -> list[dict[str, Any]]

Deprecated: use :func:build_assistant_messages instead.

build_assistant_messages

build_assistant_messages(tool_calls: list[ToolCall], *, api_format: API_FORMATS = 'openai-chat') -> list[dict[str, Any]]

Build assistant message containing tool calls in the target format.

Parameters:

Name Type Description Default
tool_calls list[ToolCall]

Normalized ToolCall list.

required
api_format API_FORMATS

Target API format.

'openai-chat'

Returns:

Type Description
list[dict[str, Any]]

Assistant message(s) as list of dicts.

Raises:

Type Description
ValueError

If the API format is unsupported.

build_tool_response

build_tool_response(tool_responses: dict[str, str | list], *, api_format: API_FORMATS = 'openai-chat', tool_calls: list[ToolCall] | None = None) -> list[dict[str, Any]]

Deprecated: use :func:build_tool_result_messages instead.

build_tool_result_messages

build_tool_result_messages(tool_responses: dict[str, str | list], *, api_format: API_FORMATS = 'openai-chat', tool_calls: list[ToolCall] | None = None) -> list[dict[str, Any]]

Build tool result messages in the target format.

Parameters:

Name Type Description Default
tool_responses dict[str, str | list]

Mapping of tool call IDs to results.

required
api_format API_FORMATS

Target API format.

'openai-chat'
tool_calls list[ToolCall] | None

Optional ToolCall list for Gemini name resolution.

None

Returns:

Type Description
list[dict[str, Any]]

Tool result messages in the specified format.

Raises:

Type Description
ValueError

If the API format is unsupported.

convert_tool_calls

convert_tool_calls(tool_calls: list[Any]) -> list[ToolCall]

Convert a list of provider tool calls to ToolCall objects.

Parameters:

Name Type Description Default
tool_calls list[Any]

Tool call objects in any supported format.

required

Returns:

Type Description
list[ToolCall]

Normalized ToolCall list.

recover_assistant_message

recover_assistant_message(tool_calls: list[ToolCall], *, api_format: API_FORMATS = 'openai-chat') -> list[dict[str, Any]]

Deprecated: use :func:build_assistant_messages instead.

recover_tool_message

recover_tool_message(tool_responses: dict[str, str | list], *, api_format: API_FORMATS = 'openai-chat', tool_calls: list[ToolCall] | None = None) -> list[dict[str, Any]]

Deprecated: use :func:build_tool_result_messages instead.

Content Blocks

用于构建工具结果消息的文本和多模态 content block 辅助类型。

toolregistry.llm.content_blocks

Canonical content block types for multimodal tool results.

Defines a lightweight, JSON-compatible representation for multimodal content using :class:~typing.TypedDict. The ImageBlock structure mirrors the Anthropic API format.

All API formats receive text-only tool results. Multimodal content is delivered via a subsequent user message produced by :func:extract_multimodal_content. This uniform approach eliminates per-provider differences in tool result handling.

ContentBlock module-attribute

ContentBlock = Union[TextBlock, ImageBlock]

Union type for all supported content block kinds.

Base64ImageSource

Bases: TypedDict

Base64-encoded image data with media type.

ImageBlock

Bases: TypedDict

An image content block with base64-encoded source.

TextBlock

Bases: TypedDict

A plain text content block.

build_expanded_user_message

build_expanded_user_message(content_parts: list[dict[str, Any]], api_format: str) -> dict[str, Any]

Deprecated: use :func:build_multimodal_user_message instead.

build_multimodal_user_message

build_multimodal_user_message(content_parts: list[dict[str, Any]], api_format: str) -> dict[str, Any]

Build a user message from expanded multimodal content parts.

Converts canonical content blocks (TextBlock / ImageBlock) into the user message format required by the target API.

Parameters:

Name Type Description Default
content_parts list[dict[str, Any]]

List of content block dicts produced by :func:extract_multimodal_content.

required
api_format str

Target API format (e.g. "openai-chat", "anthropic", "gemini").

required

Returns:

Type Description
dict[str, Any]

A user message dict ready to append to the conversation.

content_blocks_to_text

content_blocks_to_text(blocks: list[ContentBlock]) -> str

Render content blocks as a plain-text string.

Text blocks are concatenated directly. Image blocks are replaced with a human-readable placeholder indicating the media type and approximate data size.

Parameters:

Name Type Description Default
blocks list[ContentBlock]

List of content blocks to render.

required

Returns:

Type Description
str

A plain-text representation of the content.

expand_content_blocks

expand_content_blocks(tool_responses: dict[str, str | list]) -> tuple[dict[str, str | list], list[dict[str, Any]]]

Deprecated: use :func:extract_multimodal_content instead.

extract_multimodal_content

extract_multimodal_content(tool_responses: dict[str, str | list]) -> tuple[dict[str, str | list], list[dict[str, Any]]]

Separate multimodal content from tool responses for uniform handling.

For each tool response that contains content blocks (multimodal), replaces the value with a placeholder string referencing a <tool-content> tag, and collects the actual content blocks into user message content parts that should follow the tool result messages.

This approach is provider-agnostic: all API formats receive text-only tool results, and multimodal content is delivered via a subsequent user message.

Parameters:

Name Type Description Default
tool_responses dict[str, str | list]

Mapping of tool call IDs to results. Values may be str or list[ContentBlock].

required

Returns:

Type Description
dict[str, str | list]

A tuple of:

list[dict[str, Any]]
  • text_only_responses -- Same mapping but with all content block lists replaced by placeholder strings.
tuple[dict[str, str | list], list[dict[str, Any]]]
  • extra_user_content -- List of content parts (dicts) for a user message. Empty if no multimodal content was found.

is_content_block_list

is_content_block_list(value: Any) -> bool

Check whether value is a list of content blocks.

A valid content block list is a non-empty list where every element is a dict with a "type" key whose value is one of the recognized content block types ("text" or "image").

Parameters:

Name Type Description Default
value Any

The value to check.

required

Returns:

Type Description
bool

True if value conforms to the content block list shape.