- Spec files
pypi-pydantic-ai
Describes: pkg:pypi/pydantic-ai@0.8.x
- Description
- Agent Framework / shim to use Pydantic with LLMs
- Author
- tessl
- Last updated
messages.md docs/
1# Messages and Media23Rich message system supporting text, images, audio, video, documents, and binary content. Includes comprehensive streaming support and delta updates for real-time interactions.45## Capabilities67### Message Structure89Core message types for agent-model communication.1011```python { .api }12class ModelRequest:13"""14Request message sent to a model.15"""16parts: list[ModelRequestPart]17kind: Literal['request']1819class ModelResponse:20"""21Response message received from a model.22"""23parts: list[ModelResponsePart]24timestamp: datetime25kind: Literal['response']2627ModelMessage = ModelRequest | ModelResponse2829class ModelMessagesTypeAdapter:30"""31Type adapter for serializing/deserializing model messages.32"""33def validate_python(self, data: Any) -> list[ModelMessage]: ...34def dump_python(self, messages: list[ModelMessage]) -> list[dict]: ...35```3637### Request Message Parts3839Parts that can be included in requests to models.4041```python { .api }42class SystemPromptPart:43"""System prompt message part."""44content: str45kind: Literal['system-prompt']4647class UserPromptPart:48"""User prompt message part."""49content: str | list[UserContent]50timestamp: datetime51kind: Literal['user-prompt']5253class ToolReturnPart:54"""Tool return message part."""55tool_name: str56content: Any57tool_id: str | None58timestamp: datetime59kind: Literal['tool-return']6061class BuiltinToolReturnPart:62"""Built-in tool return message part."""63tool_name: str64content: Any65tool_id: str | None66timestamp: datetime67kind: Literal['builtin-tool-return']6869class RetryPromptPart:70"""Retry prompt message part."""71content: str72tool_name: str | None73tool_id: str | None74timestamp: datetime75kind: Literal['retry-prompt']7677ModelRequestPart = (78SystemPromptPart |79UserPromptPart |80ToolReturnPart |81BuiltinToolReturnPart |82RetryPromptPart83)84```8586### Response Message Parts8788Parts that can be included in responses from models.8990```python { .api }91class TextPart:92"""Plain text response part."""93content: str94kind: Literal['text']9596class ThinkingPart:97"""Thinking response part for reasoning models like o1."""98content: str99kind: Literal['thinking']100101class ToolCallPart:102"""Tool call request part."""103tool_name: str104args: dict[str, Any]105tool_id: str | None106kind: Literal['tool-call']107108class BuiltinToolCallPart:109"""Built-in tool call part."""110tool_name: str111args: dict[str, Any]112tool_id: str | None113kind: Literal['builtin-tool-call']114115ModelResponsePart = (116TextPart |117ThinkingPart |118ToolCallPart |119BuiltinToolCallPart120)121```122123### Media and File Types124125Support for various media types and file content.126127```python { .api }128class FileUrl:129"""Abstract base for URL-based files."""130url: str131132class ImageUrl(FileUrl):133"""Image file URL with format and media type."""134def __init__(135self,136url: str,137*,138alt: str | None = None,139media_type: ImageMediaType | None = None140):141"""142Create image URL.143144Parameters:145- url: URL to image file146- alt: Alt text for accessibility147- media_type: MIME type of image148"""149150class AudioUrl(FileUrl):151"""Audio file URL with format and media type."""152def __init__(153self,154url: str,155*,156media_type: AudioMediaType | None = None157):158"""159Create audio URL.160161Parameters:162- url: URL to audio file163- media_type: MIME type of audio164"""165166class VideoUrl(FileUrl):167"""Video file URL with format and media type."""168def __init__(169self,170url: str,171*,172media_type: VideoMediaType | None = None173):174"""175Create video URL.176177Parameters:178- url: URL to video file179- media_type: MIME type of video180"""181182class DocumentUrl(FileUrl):183"""Document file URL with format."""184def __init__(185self,186url: str,187*,188media_type: DocumentMediaType | None = None189):190"""191Create document URL.192193Parameters:194- url: URL to document file195- media_type: MIME type of document196"""197198class BinaryContent:199"""Binary file content with format and media type."""200def __init__(201self,202data: bytes,203media_type: str,204*,205filename: str | None = None206):207"""208Create binary content.209210Parameters:211- data: Binary file data212- media_type: MIME type of content213- filename: Optional filename214"""215```216217### Media Type Definitions218219Type definitions for supported media formats.220221```python { .api }222AudioMediaType = Literal[223'audio/mpeg',224'audio/wav',225'audio/ogg',226'audio/mp4',227'audio/webm',228'audio/flac'229]230231ImageMediaType = Literal[232'image/jpeg',233'image/png',234'image/gif',235'image/webp',236'image/svg+xml',237'image/bmp'238]239240VideoMediaType = Literal[241'video/mp4',242'video/webm',243'video/ogg',244'video/avi',245'video/mov',246'video/wmv'247]248249DocumentMediaType = Literal[250'application/pdf',251'text/plain',252'text/html',253'text/markdown',254'application/msword',255'application/vnd.openxmlformats-officedocument.wordprocessingml.document'256]257258AudioFormat = Literal['mp3', 'wav', 'ogg', 'mp4', 'webm', 'flac']259ImageFormat = Literal['jpeg', 'png', 'gif', 'webp', 'svg', 'bmp']260VideoFormat = Literal['mp4', 'webm', 'ogg', 'avi', 'mov', 'wmv']261DocumentFormat = Literal['pdf', 'txt', 'html', 'md', 'doc', 'docx']262```263264### User Content Types265266Types of content that can be included in user messages.267268```python { .api }269UserContent = (270str |271ImageUrl |272AudioUrl |273VideoUrl |274DocumentUrl |275BinaryContent276)277```278279### Tool Return Handling280281Structured tool return objects for complex tool outputs.282283```python { .api }284class ToolReturn:285"""286Structured tool return with content.287"""288def __init__(289self,290content: Any,291*,292metadata: dict[str, Any] | None = None293):294"""295Create tool return.296297Parameters:298- content: Return content from tool299- metadata: Optional metadata about the return300"""301```302303### Streaming Events304305Event types for streaming responses and real-time updates.306307```python { .api }308class PartStartEvent:309"""New part started event."""310part: ModelResponsePart311kind: Literal['part-start']312313class PartDeltaEvent:314"""Part delta update event."""315delta: ModelResponsePartDelta316kind: Literal['part-delta']317318class FinalResultEvent:319"""Final result ready event."""320result: Any321kind: Literal['final-result']322323class FunctionToolCallEvent:324"""Function tool call event."""325tool_name: str326args: dict[str, Any]327tool_id: str | None328kind: Literal['function-tool-call']329330class FunctionToolResultEvent:331"""Function tool result event."""332tool_name: str333result: Any334tool_id: str | None335kind: Literal['function-tool-result']336337class BuiltinToolCallEvent:338"""Built-in tool call event."""339tool_name: str340args: dict[str, Any]341tool_id: str | None342kind: Literal['builtin-tool-call']343344class BuiltinToolResultEvent:345"""Built-in tool result event."""346tool_name: str347result: Any348tool_id: str | None349kind: Literal['builtin-tool-result']350351ModelResponseStreamEvent = (352PartStartEvent |353PartDeltaEvent354)355356HandleResponseEvent = (357FunctionToolCallEvent |358FunctionToolResultEvent |359BuiltinToolCallEvent |360BuiltinToolResultEvent361)362363AgentStreamEvent = (364ModelResponseStreamEvent |365HandleResponseEvent |366FinalResultEvent367)368```369370### Delta Types for Streaming371372Delta update types for streaming responses.373374```python { .api }375class TextPartDelta:376"""Text part delta update."""377content: str378kind: Literal['text']379380class ThinkingPartDelta:381"""Thinking part delta update."""382content: str383kind: Literal['thinking']384385class ToolCallPartDelta:386"""Tool call part delta update."""387tool_name: str | None388args: dict[str, Any] | None389tool_id: str | None390kind: Literal['tool-call']391392ModelResponsePartDelta = (393TextPartDelta |394ThinkingPartDelta |395ToolCallPartDelta396)397```398399## Usage Examples400401### Basic Text Messages402403```python404from pydantic_ai import Agent405406agent = Agent(model='gpt-4', system_prompt='You are helpful.')407408# Simple text interaction409result = agent.run_sync('Hello, how are you?')410print(result.data)411```412413### Images in Messages414415```python416from pydantic_ai import Agent, ImageUrl417418agent = Agent(419model='gpt-4-vision-preview',420system_prompt='You can analyze images.'421)422423# Send image with message424image = ImageUrl('https://example.com/image.jpg', alt='A sample image')425result = agent.run_sync(['Describe this image:', image])426print(result.data)427```428429### Multiple Media Types430431```python432from pydantic_ai import Agent, ImageUrl, AudioUrl, DocumentUrl433434agent = Agent(435model='gpt-4-turbo',436system_prompt='You can process multiple media types.'437)438439# Mix of text and media440content = [441'Please analyze these files:',442ImageUrl('https://example.com/chart.png'),443AudioUrl('https://example.com/recording.mp3'),444DocumentUrl('https://example.com/report.pdf')445]446447result = agent.run_sync(content)448```449450### Binary Content451452```python453from pydantic_ai import Agent, BinaryContent454455agent = Agent(model='gpt-4-vision-preview')456457# Load image file as binary458with open('image.jpg', 'rb') as f:459image_data = f.read()460461binary_image = BinaryContent(462data=image_data,463media_type='image/jpeg',464filename='image.jpg'465)466467result = agent.run_sync(['Analyze this image:', binary_image])468```469470### Message History471472```python473from pydantic_ai import Agent474from pydantic_ai.messages import ModelRequest, UserPromptPart475476agent = Agent(model='gpt-4')477478# Create message history479message_history = [480ModelRequest([481UserPromptPart('What is the capital of France?')482])483]484485# Continue conversation with history486result = agent.run_sync(487'What about Germany?',488message_history=message_history489)490```491492### Streaming with Events493494```python495from pydantic_ai import Agent496497agent = Agent(model='gpt-4')498499async def stream_example():500stream = await agent.run_stream('Tell me a story')501502async for event in stream:503if event.kind == 'part-delta':504print(event.delta.content, end='', flush=True)505elif event.kind == 'final-result':506print(f"\n\nFinal result: {event.result}")507break508509# Run streaming example510import asyncio511asyncio.run(stream_example())512```