Skip to content

Commit 49d2829

Browse files
authored
Let almost all types used in docs examples be imported directly from pydantic_ai (#2736)
1 parent 1311f2c commit 49d2829

39 files changed

+278
-224
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: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ import asyncio
116116
from collections.abc import AsyncIterable
117117
from datetime import date
118118

119-
from pydantic_ai import Agent
119+
from pydantic_ai import Agent, RunContext
120120
from pydantic_ai.messages import (
121121
AgentStreamEvent,
122122
FinalResultEvent,
@@ -128,7 +128,6 @@ from pydantic_ai.messages import (
128128
ThinkingPartDelta,
129129
ToolCallPartDelta,
130130
)
131-
from pydantic_ai.tools import RunContext
132131

133132
weather_agent = Agent(
134133
'openai:gpt-4o',
@@ -215,10 +214,10 @@ Unlike `run_stream()`, it always runs the agent graph to completion even if text
215214
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.
216215

217216
```python {title="run_events.py" requires="run_stream_events.py"}
218-
from run_stream_events import weather_agent, event_stream_handler, output_messages
219-
220217
import asyncio
221218

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

223222
async def main():
224223
user_prompt = 'What will the weather be like in Paris on Tuesday?'
@@ -395,7 +394,7 @@ import asyncio
395394
from dataclasses import dataclass
396395
from datetime import date
397396

398-
from pydantic_ai import Agent
397+
from pydantic_ai import Agent, RunContext
399398
from pydantic_ai.messages import (
400399
FinalResultEvent,
401400
FunctionToolCallEvent,
@@ -406,7 +405,6 @@ from pydantic_ai.messages import (
406405
ThinkingPartDelta,
407406
ToolCallPartDelta,
408407
)
409-
from pydantic_ai.tools import RunContext
410408

411409

412410
@dataclass
@@ -548,9 +546,7 @@ You can apply these settings by passing the `usage_limits` argument to the `run{
548546
Consider the following example, where we limit the number of response tokens:
549547

550548
```py
551-
from pydantic_ai import Agent
552-
from pydantic_ai.exceptions import UsageLimitExceeded
553-
from pydantic_ai.usage import UsageLimits
549+
from pydantic_ai import Agent, UsageLimitExceeded, UsageLimits
554550

555551
agent = Agent('anthropic:claude-3-5-sonnet-latest')
556552

@@ -578,9 +574,7 @@ Restricting the number of requests can be useful in preventing infinite loops or
578574
```py
579575
from typing_extensions import TypedDict
580576

581-
from pydantic_ai import Agent, ModelRetry
582-
from pydantic_ai.exceptions import UsageLimitExceeded
583-
from pydantic_ai.usage import UsageLimits
577+
from pydantic_ai import Agent, ModelRetry, UsageLimitExceeded, UsageLimits
584578

585579

586580
class NeverOutputType(TypedDict):
@@ -636,9 +630,8 @@ For example, if you'd like to set the `temperature` setting to `0.0` to ensure l
636630
you can do the following:
637631

638632
```py
639-
from pydantic_ai import Agent
633+
from pydantic_ai import Agent, ModelSettings
640634
from pydantic_ai.models.openai import OpenAIChatModel
641-
from pydantic_ai.settings import ModelSettings
642635

643636
# 1. Model-level defaults
644637
model = OpenAIChatModel(

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/common-tools.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ Here's an example of how you can use the Tavily search tool with an agent:
106106
```py {title="tavily_search.py" test="skip"}
107107
import os
108108

109-
from pydantic_ai.agent import Agent
109+
from pydantic_ai import Agent
110110
from pydantic_ai.common_tools.tavily import tavily_search_tool
111111

112112
api_key = os.getenv('TAVILY_API_KEY')

docs/direct.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,13 +40,14 @@ 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

47+
from pydantic_ai import ToolDefinition
4648
from pydantic_ai.direct import model_request
4749
from pydantic_ai.messages import ModelRequest
4850
from pydantic_ai.models import ModelRequestParameters
49-
from pydantic_ai.tools import ToolDefinition
5051

5152

5253
class Divide(BaseModel):

docs/evals.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,11 +58,11 @@ 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
6563

64+
from simple_eval_dataset import dataset
65+
6666
dataset.add_evaluator(IsInstance(type_name='str')) # (1)!
6767

6868

@@ -619,11 +619,11 @@ You can also write datasets as JSON files:
619619
```python {title="generate_dataset_example_json.py" requires="generate_dataset_example.py"}
620620
from pathlib import Path
621621

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

625+
from generate_dataset_example import AnswerOutput, MetadataType, QuestionInputs
626+
627627

628628
async def main():
629629
dataset = await generate_dataset( # (1)!

docs/logfire.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ from opentelemetry.sdk.trace import TracerProvider
226226
from opentelemetry.sdk.trace.export import BatchSpanProcessor
227227
from opentelemetry.trace import set_tracer_provider
228228

229-
from pydantic_ai.agent import Agent
229+
from pydantic_ai import Agent
230230

231231
os.environ['OTEL_EXPORTER_OTLP_ENDPOINT'] = 'http://localhost:4318'
232232
exporter = OTLPSpanExporter()
@@ -296,7 +296,7 @@ By default, the global `TracerProvider` and `EventLoggerProvider` are used. Thes
296296
from opentelemetry.sdk._events import EventLoggerProvider
297297
from opentelemetry.sdk.trace import TracerProvider
298298

299-
from pydantic_ai.agent import Agent, InstrumentationSettings
299+
from pydantic_ai import Agent, InstrumentationSettings
300300

301301
instrumentation_settings = InstrumentationSettings(
302302
tracer_provider=TracerProvider(),
@@ -322,7 +322,7 @@ agent = Agent(model)
322322
### Excluding binary content
323323

324324
```python {title="excluding_binary_content.py"}
325-
from pydantic_ai.agent import Agent, InstrumentationSettings
325+
from pydantic_ai import Agent, InstrumentationSettings
326326

327327
instrumentation_settings = InstrumentationSettings(include_binary_content=False)
328328

@@ -338,7 +338,7 @@ For privacy and security reasons, you may want to monitor your agent's behavior
338338
When `include_content=False` is set, Pydantic AI will exclude sensitive content from OpenTelemetry events, including user prompts and model completions, tool call arguments and responses, and any other message content.
339339

340340
```python {title="excluding_sensitive_content.py"}
341-
from pydantic_ai.agent import Agent
341+
from pydantic_ai import Agent
342342
from pydantic_ai.models.instrumented import InstrumentationSettings
343343

344344
instrumentation_settings = InstrumentationSettings(include_content=False)

docs/mcp/client.md

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -174,10 +174,9 @@ call needs.
174174
```python {title="mcp_process_tool_call.py"}
175175
from typing import Any
176176

177-
from pydantic_ai import Agent
177+
from pydantic_ai import Agent, RunContext
178178
from pydantic_ai.mcp import CallToolFunc, MCPServerStdio, ToolResult
179179
from pydantic_ai.models.test import TestModel
180-
from pydantic_ai.tools import RunContext
181180

182181

183182
async def process_tool_call(
@@ -245,29 +244,29 @@ parameter that lets you pass your own pre-configured
245244
[`httpx.AsyncClient`](https://www.python-httpx.org/async/).
246245

247246
```python {title="mcp_custom_tls_client.py"}
248-
import httpx
249247
import ssl
250248

249+
import httpx
250+
251251
from pydantic_ai import Agent
252252
from pydantic_ai.mcp import MCPServerSSE
253253

254-
255254
# Trust an internal / self-signed CA
256-
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')
257256

258257
# OPTIONAL: if the server requires **mutual TLS** load your client certificate
259-
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',)
260259

261260
http_client = httpx.AsyncClient(
262261
verify=ssl_ctx,
263262
timeout=httpx.Timeout(10.0),
264263
)
265264

266265
server = MCPServerSSE(
267-
url="http://localhost:3001/sse",
266+
url='http://localhost:3001/sse',
268267
http_client=http_client, # (1)!
269268
)
270-
agent = Agent("openai:gpt-4o", toolsets=[server])
269+
agent = Agent('openai:gpt-4o', toolsets=[server])
271270

272271
async def main():
273272
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/message-history.md

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -402,9 +402,8 @@ History processors can optionally accept a [`RunContext`][pydantic_ai.tools.RunC
402402
additional information about the current run, such as dependencies, model information, and usage statistics:
403403

404404
```python {title="context_aware_processor.py"}
405-
from pydantic_ai import Agent
405+
from pydantic_ai import Agent, RunContext
406406
from pydantic_ai.messages import ModelMessage
407-
from pydantic_ai.tools import RunContext
408407

409408

410409
def context_aware_processor(

0 commit comments

Comments
 (0)