diff --git a/docs/examples/chat-app.md b/docs/examples/chat-app.md index 97330987..3af5719a 100644 --- a/docs/examples/chat-app.md +++ b/docs/examples/chat-app.md @@ -8,10 +8,12 @@ Demonstrates: * reusing chat history * serializing messages +* streaming responses This demonstrates storing chat history between requests and using it to give the model context for new responses. -Most of the complex logic here is in `chat_app.html` which includes the page layout and JavaScript to handle the chat. +Most of the complex logic here is between `chat_app.py` which streams the response to the browser, +and `chat_app.ts` which renders messages in the browser. ## Running the Example @@ -27,10 +29,20 @@ TODO screenshot. ## Example Code +Python code that runs the chat app: + ```py title="chat_app.py" #! pydantic_ai_examples/chat_app.py ``` +Simple HTML page to render the app: + ```html title="chat_app.html" #! pydantic_ai_examples/chat_app.html ``` + +TypeScript to handle rendering the messages, to keep this simple (and at the risk of offending frontend developers) the typescript code is passed to the browser as plain text and transpiled in the browser. + +```ts title="chat_app.ts" +#! pydantic_ai_examples/chat_app.ts +``` diff --git a/pydantic_ai/result.py b/pydantic_ai/result.py index ee6de72b..73b327ed 100644 --- a/pydantic_ai/result.py +++ b/pydantic_ai/result.py @@ -3,6 +3,7 @@ from abc import ABC, abstractmethod from collections.abc import AsyncIterator from dataclasses import dataclass +from datetime import datetime from typing import Generic, TypeVar, cast import logfire_api @@ -273,6 +274,10 @@ def cost(self) -> Cost: """ return self.cost_so_far + self._stream_response.cost() + def timestamp(self) -> datetime: + """Get the timestamp of the response.""" + return self._stream_response.timestamp() + async def validate_structured_result( self, message: messages.ModelStructuredResponse, *, allow_partial: bool = False ) -> ResultData: diff --git a/pydantic_ai_examples/chat_app.html b/pydantic_ai_examples/chat_app.html index 20be83ae..da626cde 100644 --- a/pydantic_ai_examples/chat_app.html +++ b/pydantic_ai_examples/chat_app.html @@ -58,71 +58,24 @@