Skip to content

Commit bf0eb18

Browse files
committed
Auto-sort imports and require single quotes in docs examples
1 parent 2d4281d commit bf0eb18

24 files changed

+162
-127
lines changed

docs/ag-ui.md

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -43,24 +43,24 @@ This example uses [`run_ag_ui()`][pydantic_ai.ag_ui.run_ag_ui] and performs its
4343
This can be modified to work with any web framework.
4444

4545
```py {title="run_ag_ui.py"}
46+
import json
47+
from http import HTTPStatus
48+
4649
from ag_ui.core import RunAgentInput
4750
from fastapi import FastAPI
48-
from http import HTTPStatus
4951
from fastapi.requests import Request
5052
from fastapi.responses import Response, StreamingResponse
5153
from pydantic import ValidationError
52-
import json
5354

5455
from pydantic_ai import Agent
55-
from pydantic_ai.ag_ui import run_ag_ui, SSE_CONTENT_TYPE
56-
56+
from pydantic_ai.ag_ui import SSE_CONTENT_TYPE, run_ag_ui
5757

5858
agent = Agent('openai:gpt-4.1', instructions='Be fun!')
5959

6060
app = FastAPI()
6161

6262

63-
@app.post("/")
63+
@app.post('/')
6464
async def run_agent(request: Request) -> Response:
6565
accept = request.headers.get('accept', SSE_CONTENT_TYPE)
6666
try:
@@ -97,12 +97,11 @@ from starlette.responses import Response
9797
from pydantic_ai import Agent
9898
from pydantic_ai.ag_ui import handle_ag_ui_request
9999

100-
101100
agent = Agent('openai:gpt-4.1', instructions='Be fun!')
102101

103102
app = FastAPI()
104103

105-
@app.post("/")
104+
@app.post('/')
106105
async def run_agent(request: Request) -> Response:
107106
return await handle_ag_ui_request(agent, request)
108107
```

docs/agents.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -214,10 +214,10 @@ Unlike `run_stream()`, it always runs the agent graph to completion even if text
214214
To get the best of both worlds, at the expense of some additional complexity, you can use [`agent.iter()`][pydantic_ai.agent.AbstractAgent.iter] as described in the next section, which lets you [iterate over the agent graph](#iterating-over-an-agents-graph) and [stream both events and output](#streaming-all-events-and-output) at every step.
215215

216216
```python {title="run_events.py" requires="run_stream_events.py"}
217-
from run_stream_events import weather_agent, event_stream_handler, output_messages
218-
219217
import asyncio
220218

219+
from run_stream_events import event_stream_handler, output_messages, weather_agent
220+
221221

222222
async def main():
223223
user_prompt = 'What will the weather be like in Paris on Tuesday?'

docs/cli.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,13 @@ Both `Agent.to_cli()` and `Agent.to_cli_sync()` support a `message_history` para
115115

116116
```python {title="agent_with_history.py" test="skip"}
117117
from pydantic_ai import Agent
118-
from pydantic_ai.messages import ModelMessage, ModelRequest, ModelResponse, UserPromptPart, TextPart
118+
from pydantic_ai.messages import (
119+
ModelMessage,
120+
ModelRequest,
121+
ModelResponse,
122+
TextPart,
123+
UserPromptPart,
124+
)
119125

120126
agent = Agent('openai:gpt-4.1')
121127

docs/direct.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,9 @@ You can also use the direct API to work with function/tool calling.
4040
Even here we can use Pydantic to generate the JSON schema for the tool:
4141

4242
```python
43+
from typing import Literal
44+
4345
from pydantic import BaseModel
44-
from typing_extensions import Literal
4546

4647
from pydantic_ai import ToolDefinition
4748
from pydantic_ai.direct import model_request

docs/evals.md

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,9 @@ Pydantic Evals includes several built-in evaluators and allows you to create cus
5858
```python {title="simple_eval_evaluator.py" requires="simple_eval_dataset.py"}
5959
from dataclasses import dataclass
6060

61-
from simple_eval_dataset import dataset
62-
6361
from pydantic_evals.evaluators import Evaluator, EvaluatorContext
6462
from pydantic_evals.evaluators.common import IsInstance
63+
from simple_eval_dataset import dataset
6564

6665
dataset.add_evaluator(IsInstance(type_name='str')) # (1)!
6766

@@ -620,7 +619,6 @@ You can also write datasets as JSON files:
620619
from pathlib import Path
621620

622621
from generate_dataset_example import AnswerOutput, MetadataType, QuestionInputs
623-
624622
from pydantic_evals import Dataset
625623
from pydantic_evals.generation import generate_dataset
626624

docs/mcp/client.md

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -244,29 +244,29 @@ parameter that lets you pass your own pre-configured
244244
[`httpx.AsyncClient`](https://www.python-httpx.org/async/).
245245

246246
```python {title="mcp_custom_tls_client.py"}
247-
import httpx
248247
import ssl
249248

249+
import httpx
250+
250251
from pydantic_ai import Agent
251252
from pydantic_ai.mcp import MCPServerSSE
252253

253-
254254
# Trust an internal / self-signed CA
255-
ssl_ctx = ssl.create_default_context(cafile="/etc/ssl/private/my_company_ca.pem")
255+
ssl_ctx = ssl.create_default_context(cafile='/etc/ssl/private/my_company_ca.pem')
256256

257257
# OPTIONAL: if the server requires **mutual TLS** load your client certificate
258-
ssl_ctx.load_cert_chain(certfile="/etc/ssl/certs/client.crt", keyfile="/etc/ssl/private/client.key",)
258+
ssl_ctx.load_cert_chain(certfile='/etc/ssl/certs/client.crt', keyfile='/etc/ssl/private/client.key',)
259259

260260
http_client = httpx.AsyncClient(
261261
verify=ssl_ctx,
262262
timeout=httpx.Timeout(10.0),
263263
)
264264

265265
server = MCPServerSSE(
266-
url="http://localhost:3001/sse",
266+
url='http://localhost:3001/sse',
267267
http_client=http_client, # (1)!
268268
)
269-
agent = Agent("openai:gpt-4o", toolsets=[server])
269+
agent = Agent('openai:gpt-4o', toolsets=[server])
270270

271271
async def main():
272272
async with agent:

docs/mcp/server.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,12 @@ from typing import Any
102102
from mcp import ClientSession, StdioServerParameters
103103
from mcp.client.stdio import stdio_client
104104
from mcp.shared.context import RequestContext
105-
from mcp.types import CreateMessageRequestParams, CreateMessageResult, ErrorData, TextContent
105+
from mcp.types import (
106+
CreateMessageRequestParams,
107+
CreateMessageResult,
108+
ErrorData,
109+
TextContent,
110+
)
106111

107112

108113
async def sampling_callback(

docs/multi-agent-applications.md

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ You'll generally want to pass [`ctx.usage`][pydantic_ai.RunContext.usage] to the
2222
Agent delegation doesn't need to use the same model for each agent. If you choose to use different models within a run, calculating the monetary cost from the final [`result.usage()`][pydantic_ai.agent.AgentRunResult.usage] of the run will not be possible, but you can still use [`UsageLimits`][pydantic_ai.usage.UsageLimits] to avoid unexpected costs.
2323

2424
```python {title="agent_delegation_simple.py"}
25-
from pydantic_ai import Agent, RunContext, UsageLimits
25+
from pydantic_ai import Agent, RunContext, UsageLimits
2626

2727
joke_selection_agent = Agent( # (1)!
2828
'openai:gpt-4o',
@@ -180,7 +180,7 @@ Here agents don't need to use the same deps.
180180
Here we show two agents used in succession, the first to find a flight and the second to extract the user's seat preference.
181181

182182
```python {title="programmatic_handoff.py"}
183-
from typing import Literal, Union
183+
from typing import Literal
184184

185185
from pydantic import BaseModel, Field
186186
from rich.prompt import Prompt
@@ -197,9 +197,9 @@ class Failed(BaseModel):
197197
"""Unable to find a satisfactory choice."""
198198

199199

200-
flight_search_agent = Agent[None, Union[FlightDetails, Failed]]( # (1)!
200+
flight_search_agent = Agent[None, FlightDetails | Failed]( # (1)!
201201
'openai:gpt-4o',
202-
output_type=Union[FlightDetails, Failed], # type: ignore
202+
output_type=FlightDetails | Failed, # type: ignore
203203
system_prompt=(
204204
'Use the "flight_search" tool to find a flight '
205205
'from the given origin to the given destination.'
@@ -210,7 +210,7 @@ flight_search_agent = Agent[None, Union[FlightDetails, Failed]]( # (1)!
210210
@flight_search_agent.tool # (2)!
211211
async def flight_search(
212212
ctx: RunContext[None], origin: str, destination: str
213-
) -> Union[FlightDetails, None]:
213+
) -> FlightDetails | None:
214214
# in reality, this would call a flight search API or
215215
# use a browser to scrape a flight search website
216216
return FlightDetails(flight_number='AK456')
@@ -219,8 +219,8 @@ async def flight_search(
219219
usage_limits = UsageLimits(request_limit=15) # (3)!
220220

221221

222-
async def find_flight(usage: RunUsage) -> Union[FlightDetails, None]: # (4)!
223-
message_history: Union[list[ModelMessage], None] = None
222+
async def find_flight(usage: RunUsage) -> FlightDetails | None: # (4)!
223+
message_history: list[ModelMessage] | None = None
224224
for _ in range(3):
225225
prompt = Prompt.ask(
226226
'Where would you like to fly from and to?',
@@ -245,9 +245,9 @@ class SeatPreference(BaseModel):
245245

246246

247247
# This agent is responsible for extracting the user's seat selection
248-
seat_preference_agent = Agent[None, Union[SeatPreference, Failed]]( # (5)!
248+
seat_preference_agent = Agent[None, SeatPreference | Failed]( # (5)!
249249
'openai:gpt-4o',
250-
output_type=Union[SeatPreference, Failed], # type: ignore
250+
output_type=SeatPreference | Failed, # type: ignore
251251
system_prompt=(
252252
"Extract the user's seat preference. "
253253
'Seats A and F are window seats. '
@@ -258,7 +258,7 @@ seat_preference_agent = Agent[None, Union[SeatPreference, Failed]]( # (5)!
258258

259259

260260
async def find_seat(usage: RunUsage) -> SeatPreference: # (6)!
261-
message_history: Union[list[ModelMessage], None] = None
261+
message_history: list[ModelMessage] | None = None
262262
while True:
263263
answer = Prompt.ask('What seat would you like?')
264264

docs/output.md

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -313,9 +313,8 @@ Native Output mode uses a model's native "Structured Outputs" feature (aka "JSON
313313
To use this mode, you can wrap the output type(s) in the [`NativeOutput`][pydantic_ai.output.NativeOutput] marker class that also lets you specify a `name` and `description` if the name and docstring of the type or function are not sufficient.
314314

315315
```python {title="native_output.py" requires="tool_output.py"}
316-
from tool_output import Fruit, Vehicle
317-
318316
from pydantic_ai import Agent, NativeOutput
317+
from tool_output import Fruit, Vehicle
319318

320319
agent = Agent(
321320
'openai:gpt-4o',
@@ -346,9 +345,9 @@ To use this mode, you can wrap the output type(s) in the [`PromptedOutput`][pyda
346345

347346
```python {title="prompted_output.py" requires="tool_output.py"}
348347
from pydantic import BaseModel
349-
from tool_output import Vehicle
350348

351349
from pydantic_ai import Agent, PromptedOutput
350+
from tool_output import Vehicle
352351

353352

354353
class Device(BaseModel):
@@ -399,19 +398,19 @@ from pydantic_ai import Agent, StructuredDict
399398

400399
HumanDict = StructuredDict(
401400
{
402-
"type": "object",
403-
"properties": {
404-
"name": {"type": "string"},
405-
"age": {"type": "integer"}
401+
'type': 'object',
402+
'properties': {
403+
'name': {'type': 'string'},
404+
'age': {'type': 'integer'}
406405
},
407-
"required": ["name", "age"]
406+
'required': ['name', 'age']
408407
},
409-
name="Human",
410-
description="A human with a name and age",
408+
name='Human',
409+
description='A human with a name and age',
411410
)
412411

413412
agent = Agent('openai:gpt-4o', output_type=HumanDict)
414-
result = agent.run_sync("Create a person")
413+
result = agent.run_sync('Create a person')
415414
#> {'name': 'John Doe', 'age': 30}
416415
```
417416

@@ -546,7 +545,7 @@ Here's an example of streaming a user profile as it's built:
546545
```python {title="streamed_user_profile.py" line_length="120"}
547546
from datetime import date
548547

549-
from typing_extensions import TypedDict, NotRequired
548+
from typing_extensions import NotRequired, TypedDict
550549

551550
from pydantic_ai import Agent
552551

0 commit comments

Comments
 (0)