latent.wire.encoders.ai_sdk¶
AI SDK UI Data Stream encoder.
This module converts normalized events into AI SDK UI Data Stream protocol parts. The parts follow the specification at: https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol#data-stream-protocol
Protocol Requirements: - All parts are JSON objects with a "type" field - Stream must include x-vercel-ai-ui-message-stream: v1 header - Stream ends with [DONE] termination marker
Functions¶
encode_any_event¶
Encode any normalized event to an AI SDK part.
This convenience dispatcher attempts the category-specific encoders in a defined order and returns the first successful result. If the event does not match any supported category, it returns None.
Order:
1. Text events (TextStart, TextDelta, TextEnd)
2. Reasoning events (ReasoningStart, ReasoningDelta, ReasoningEnd)
3. Tool events (ToolInputStart, ToolInputDelta, ToolInputAvailable, ToolOutputAvailable)
4. Error / StartStep / FinishStep events
5. DataLatent fidelity events (data-latent-
Returns: The encoded AI SDK part as a dictionary, or None if unsupported.
encode_data_latent_part¶
Encode a data-latent-<name> AI SDK custom data part.
AI SDK lets servers stream arbitrary application data as data-* parts
({"type": "data-<x>", "data": <json>}). We use one per canonical event
that has no native part, namespacing the type with the AgentEvent class
name and keeping that name inside data as well so the decoder can
reconstruct the exact event without parsing the type string.
Args:
name: The canonical AgentEvent subclass name (e.g. "Usage").
payload: The event's serialized fields.
Returns:
Dictionary representing the data-latent-<name> part.
Example: >>> encode_data_latent_part("Usage", {"input_tokens": 3}) {'type': 'data-latent-Usage', 'data': {'name': 'Usage', 'payload': {'input_tokens': 3}}}
Protocol Reference: https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol#data-part
encode_error_part¶
Encode an error part.
This part is emitted when an error occurs during stream processing. It includes the error message text that can be displayed to the user. After emitting an error part, you MUST still emit a finish part and [DONE] marker to properly terminate the stream.
Args: error_text: Human-readable error message to display
Returns: Dictionary representing the error part in AI SDK format
Example: >>> part = encode_error_part("Connection timeout") >>> assert part == {"type": "error", "errorText": "Connection timeout"}
Protocol Reference: https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol#error-part Format: {"type":"error","errorText":"error message"}
encode_finish_part¶
Encode a finish message part.
This part MUST be emitted at the end of every successful stream to signal completion. It tells the frontend that no more parts will arrive for this message and the message is ready for final processing.
Metadata can be included to provide additional information such as: - Token usage metrics (inputTokens, outputTokens, totalTokens, etc.) - Finish timestamp (when the stream completed) - Any other completion-related information
Args: metadata: Optional metadata dictionary to include in the finish part
Returns: Dictionary representing the finish part in AI SDK format
Example: >>> part = encode_finish_part() >>> assert part == {"type": "finish"}
>>> part = encode_finish_part({"finishTime": "2024-10-28T10:30:00Z", "totalTokens": 150})
>>> assert part == {"type": "finish", "messageMetadata": {...}}
Protocol Reference: https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol#finish-message-part Format: {"type":"finish"} or {"type":"finish","messageMetadata":{...}}
encode_reasoning_delta_part¶
Encode a reasoning delta part.
This part contains an incremental chunk of reasoning content. Multiple reasoning-delta parts can be emitted for the same reasoning block, each adding more content. All deltas for a reasoning block share the same reasoning_id.
Args: reasoning_id: Unique identifier for the reasoning block (must match preceding reasoning-start) delta: Incremental reasoning text fragment to append
Returns: Dictionary representing the reasoning-delta part in AI SDK format
Example: >>> part = encode_reasoning_delta_part("reasoning_123", "Let me think...") >>> assert part == {"type": "reasoning-delta", "id": "reasoning_123", "delta": "Let me think..."}
Protocol Reference: https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol#reasoning-delta-part Format: {"type":"reasoning-delta","id":"...","delta":"..."}
encode_reasoning_end_part¶
Encode a reasoning end part.
This part MUST be emitted after all reasoning-delta parts for a reasoning block to signal completion. It establishes a clear boundary: no more reasoning-delta parts will follow for this reasoning_id.
Args: reasoning_id: Unique identifier for the reasoning block (must match preceding reasoning-start)
Returns: Dictionary representing the reasoning-end part in AI SDK format
Example: >>> part = encode_reasoning_end_part("reasoning_123") >>> assert part == {"type": "reasoning-end", "id": "reasoning_123"}
Protocol Reference: https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol#reasoning-end-part Format: {"type":"reasoning-end","id":"..."}
encode_reasoning_event¶
Encode a reasoning-related normalized event to an AI SDK part.
This is a convenience helper that dispatches to the appropriate encoder based on the event type. It mirrors the behavior of encode_text_event but for reasoning events.
Args: event: A normalized event object (ReasoningStart, ReasoningDelta, or ReasoningEnd)
Returns: Dictionary representing the AI SDK part, or None if event type is not supported
Example: >>> from latent.wire.core.events import ReasoningStart, ReasoningDelta, ReasoningEnd >>> event = ReasoningStart(reasoning_id="reasoning_123") >>> part = encode_reasoning_event(event) >>> assert part == {"type": "reasoning-start", "id": "reasoning_123"}
>>> event = ReasoningDelta(reasoning_id="reasoning_123", delta="Thinking...")
>>> part = encode_reasoning_event(event)
>>> assert part == {"type": "reasoning-delta", "id": "reasoning_123", "delta": "Thinking..."}
>>> event = ReasoningEnd(reasoning_id="reasoning_123")
>>> part = encode_reasoning_event(event)
>>> assert part == {"type": "reasoning-end", "id": "reasoning_123"}
encode_reasoning_start_part¶
Encode a reasoning start part.
This part MUST be emitted before any reasoning-delta parts for the same reasoning block. It establishes the reasoning_id that subsequent deltas will reference.
Args: reasoning_id: Unique identifier for this reasoning block (e.g., "reasoning_abc123")
Returns: Dictionary representing the reasoning-start part in AI SDK format
Example: >>> part = encode_reasoning_start_part("reasoning_123") >>> assert part == {"type": "reasoning-start", "id": "reasoning_123"}
Protocol Reference: https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol#reasoning-start-part Format: {"type":"reasoning-start","id":"..."}
encode_start_part¶
Encode a message start part.
This part MUST be emitted at the beginning of every stream to initialize the message with a unique ID. The frontend uses this ID to track the message throughout its lifecycle.
Args: message_id: Unique identifier for the message (e.g., "msg_abc123") metadata: Optional metadata dictionary to include in the start part
Returns: Dictionary representing the start part in AI SDK format
Example: >>> part = encode_start_part("msg_123") >>> assert part == {"type": "start", "messageId": "msg_123"}
>>> part = encode_start_part("msg_123", {"userId": "user_1"})
>>> assert part == {"type": "start", "messageId": "msg_123", "messageMetadata": {"userId": "user_1"}}
Protocol Reference: https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol#message-start-part Format: {"type":"start","messageId":"..."}
encode_step_finish_part¶
encode_step_start_part¶
encode_text_delta_part¶
Encode a text delta part.
This part contains an incremental chunk of text content. Multiple text-delta parts can be emitted for the same text block, each adding more content. All deltas for a text block share the same text_id.
Args: text_id: Unique identifier for the text block (must match preceding text-start) delta: Incremental text fragment to append
Returns: Dictionary representing the text-delta part in AI SDK format
Example: >>> part = encode_text_delta_part("txt_123", "Hello") >>> assert part == {"type": "text-delta", "id": "txt_123", "delta": "Hello"}
Protocol Reference: https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol#text-delta-part Format: {"type":"text-delta","id":"...","delta":"..."}
encode_text_end_part¶
Encode a text end part.
This part MUST be emitted after all text-delta parts for a text block to signal completion. It establishes a clear boundary: no more text-delta parts will follow for this text_id.
Args: text_id: Unique identifier for the text block (must match preceding text-start)
Returns: Dictionary representing the text-end part in AI SDK format
Example: >>> part = encode_text_end_part("txt_123") >>> assert part == {"type": "text-end", "id": "txt_123"}
Protocol Reference: https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol#text-end-part Format: {"type":"text-end","id":"..."}
encode_text_event¶
Encode a text-related normalized event to an AI SDK part.
This is a convenience helper that dispatches to the appropriate encoder based on the event type. It simplifies integration by accepting event objects directly instead of requiring manual field extraction.
Args: event: A normalized event object (TextStart, TextDelta, or TextEnd)
Returns: Dictionary representing the AI SDK part, or None if event type is not supported
Example: >>> from latent.wire.core.events import TextStart, TextDelta, TextEnd >>> event = TextStart(text_id="txt_123") >>> part = encode_text_event(event) >>> assert part == {"type": "text-start", "id": "txt_123"}
>>> event = TextDelta(text_id="txt_123", delta="Hello")
>>> part = encode_text_event(event)
>>> assert part == {"type": "text-delta", "id": "txt_123", "delta": "Hello"}
>>> event = TextEnd(text_id="txt_123")
>>> part = encode_text_event(event)
>>> assert part == {"type": "text-end", "id": "txt_123"}
encode_text_start_part¶
Encode a text start part.
This part MUST be emitted before any text-delta parts for the same text block. It establishes the text_id that subsequent deltas will reference.
Text blocks represent visible assistant output content (as opposed to reasoning, which may be hidden or displayed separately).
Args: text_id: Unique identifier for this text block (e.g., "txt_abc123")
Returns: Dictionary representing the text-start part in AI SDK format
Example: >>> part = encode_text_start_part("txt_123") >>> assert part == {"type": "text-start", "id": "txt_123"}
Protocol Reference: https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol#text-start-part Format: {"type":"text-start","id":"..."}
encode_tool_event¶
Encode a tool-related normalized event to an AI SDK part.
This convenience helper dispatches to the specific tool encoder based on the tool event type. It mirrors the behavior of the text and reasoning helpers, but for tool input/output events.
Args: event: A normalized event object (ToolInputStart, ToolInputDelta, ToolInputAvailable, or ToolOutputAvailable)
Returns: Dictionary representing the AI SDK part, or None if event type is not supported
Example: >>> from latent.wire.core.events import ToolInputStart >>> e = ToolInputStart(tool_call_id="call_1", tool_name="getWeather") >>> part = encode_tool_event(e) >>> assert part == { ... "type": "tool-input-start", ... "toolCallId": "call_1", ... "toolName": "getWeather", ... }
Protocol Reference: https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol#data-stream-protocol
encode_tool_input_available_part¶
Encode a tool-input-available part.
This part indicates that the complete, structured tool input is available and ready for execution. It includes the parsed input object.
Args: tool_call_id: Unique identifier for the tool call tool_name: Name of the tool being invoked input_object: Complete structured input (JSON-serializable dict)
Returns: Dictionary representing the tool-input-available part in AI SDK format
Example: >>> part = encode_tool_input_available_part( ... "call_123", "getWeather", {"city": "San Francisco"} ... ) >>> assert part == { ... "type": "tool-input-available", ... "toolCallId": "call_123", ... "toolName": "getWeather", ... "input": {"city": "San Francisco"}, ... }
Protocol Reference: https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol#tool-input-available-part Format: {"type":"tool-input-available","toolCallId":"...","toolName":"...","input":{...}}
encode_tool_input_delta_part¶
Encode a tool-input-delta part.
This part carries an incremental fragment of the tool input as text. The AI SDK protocol expects the field name to be "inputTextDelta". Multiple deltas may be sent and will be concatenated by the receiver until a complete input becomes available.
Args: tool_call_id: Unique identifier for the tool call (must match start part) input_text_delta: Incremental input fragment (often partial JSON text)
Returns: Dictionary representing the tool-input-delta part in AI SDK format
Example: >>> part = encode_tool_input_delta_part("call_123", "{"city": "") >>> assert part == { ... "type": "tool-input-delta", ... "toolCallId": "call_123", ... "inputTextDelta": "{"city": "", ... }
Protocol Reference: https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol#tool-input-delta-part Format: {"type":"tool-input-delta","toolCallId":"...","inputTextDelta":"..."}
encode_tool_input_start_part¶
Encode a tool-input-start part.
This part MUST be emitted before any tool-input-delta or tool-input-available parts for the same tool call. It announces that a tool invocation has begun and provides the tool's name and call identifier.
Args: tool_call_id: Unique identifier for this tool call (e.g., "call_abc123") tool_name: Name of the tool being invoked (must match provider/tool registry)
Returns: Dictionary representing the tool-input-start part in AI SDK format
Example: >>> part = encode_tool_input_start_part("call_123", "getWeather") >>> assert part == { ... "type": "tool-input-start", ... "toolCallId": "call_123", ... "toolName": "getWeather", ... }
Protocol Reference: https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol#tool-input-start-part Format: {"type":"tool-input-start","toolCallId":"...","toolName":"..."}
encode_tool_output_available_part¶
Encode a tool-output-available part.
This part carries the final tool execution result. The AI SDK protocol does not define incremental output streaming for tools; only the final output is sent using this part.
Args: tool_call_id: Unique identifier for the tool call output_object: Structured output (JSON-serializable dict)
Returns: Dictionary representing the tool-output-available part in AI SDK format
Example: >>> part = encode_tool_output_available_part( ... "call_123", {"status": "success", "content": [{"type": "text", "text": "OK"}]} ... ) >>> assert part == { ... "type": "tool-output-available", ... "toolCallId": "call_123", ... "output": {"status": "success", "content": [{"type": "text", "text": "OK"}]}, ... }
Protocol Reference: https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol#tool-output-available-part Format: {"type":"tool-output-available","toolCallId":"...","output":{...}}