You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/agents.md
+61-61Lines changed: 61 additions & 61 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -119,6 +119,67 @@ print(result2.data)
119
119
120
120
_(This example is complete, it can be run "as is")_
121
121
122
+
## Type safe by design {#static-type-checking}
123
+
124
+
PydanticAI is designed to work well with static type checkers, like mypy and pyright.
125
+
126
+
!!! tip "Typing is (somewhat) optional"
127
+
PydanticAI is designed to make type checking as useful as possible for you if you choose to use it, but you don't have to use types everywhere all the time.
128
+
129
+
That said, because PydanticAI uses Pydantic, and Pydantic uses type hints as the definition for schema and validation, some types (specifically type hints on parameters to tools, and the `result_type` arguments to [`Agent`][pydantic_ai.Agent]) are used at runtime.
130
+
131
+
We (the library developers) have messed up if type hints are confusing you more than they're help you, if you find this, please create an [issue](https://github.com/pydantic/pydantic-ai/issues) explaining what's annoying you!
132
+
133
+
In particular, agents are generic in both the type of their dependencies and the type of results they return, so you can use the type hints to ensure you're using the right types.
result = agent.run_sync('Does their name start with "A"?', deps=User('Adam'))
165
+
foobar(result.data) # (3)!
166
+
```
167
+
168
+
1. The agent is defined as expecting an instance of `User` as `deps`.
169
+
2. But here `add_user_name` is defined as taking a `str` as the dependency, not a `User`.
170
+
3. Since the agent is defined as returning a `bool`, this will raise a type error since `foobar` expects `bytes`.
171
+
172
+
Running `mypy` on this will give the following output:
173
+
174
+
```bash
175
+
➤ uv run mypy type_mistakes.py
176
+
type_mistakes.py:18: error: Argument 1 to "system_prompt" of "Agent" has incompatible type"Callable[[RunContext[str]], str]"; expected "Callable[[RunContext[User]], str]" [arg-type]
177
+
type_mistakes.py:28: error: Argument 1 to "foobar" has incompatible type"bool"; expected "bytes" [arg-type]
178
+
Found 2 errors in 1 file (checked 1 source file)
179
+
```
180
+
181
+
Running `pyright` would identify the same issues.
182
+
122
183
## System Prompts
123
184
124
185
System prompts might seem simple at first glance since they're just strings (or sequences of strings that are concatenated), but crafting the right system prompt is key to getting the model to behave as you want.
@@ -514,64 +575,3 @@ else:
514
575
1. Define a tool that will raise `ModelRetry` repeatedly in this case.
515
576
516
577
_(This example is complete, it can be run "as is")_
517
-
518
-
## Static Type Checking
519
-
520
-
PydanticAI is designed to work well with static type checkers, like mypy and pyright.
521
-
522
-
!!! tip "mypy vs. pyright"
523
-
[mypy](https://github.com/python/mypy) and [pyright](https://github.com/microsoft/pyright) are both static type checkers for Python.
524
-
525
-
Mypy was the first and is still generally considered the default, in part because it was developed parly by Guido van Rossum, the creator of Python.
526
-
527
-
Pyright is generally faster and more sophisticated. It is develoepd by Eric Trout for use in VSCode, since that's its primary use case, it's terminal output is more verbose and harder to read than that of mypy.
528
-
529
-
In particular, agents are generic in both the type of their dependencies and the type of results they return, so you can use the type hints to ensure you're using the right types.
Copy file name to clipboardExpand all lines: docs/index.md
+31-50Lines changed: 31 additions & 50 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -10,10 +10,10 @@ PydanticAI is a Python Agent Framework designed to make it less painful to build
10
10
11
11
## Why use PydanticAI
12
12
13
-
* Built by the team behind Pydantic (the validation layer of the OpenAI SDK, the Anthropic SDK, LangChain, LlamaIndex, AutoGPT, Transformers, Instructor and many more)
14
-
* Model-agnostic — currently both OpenAI, Gemini, and Groq are supported, Anthropic [is coming soon](https://github.com/pydantic/pydantic-ai/issues/63). And there is a simple interface to implement support for other models.
15
-
* Type-safe
16
-
* Control flow and composing agents is done with vanilla python, allowing you to make use of the same Python development best practices you'd use in any other (non-AI) project
13
+
* Built by the team behind Pydantic (the validation layer of the OpenAI SDK, the Anthropic SDK, LangChain, LlamaIndex, AutoGPT, Transformers, CrewAI, Instructor and many more)
14
+
* Model-agnostic — currently OpenAI, Gemini, and Groq are supported, Anthropic [is coming soon](https://github.com/pydantic/pydantic-ai/issues/63). And there is a simple interface to implement support for other models.
15
+
*[Type-safe](agents.md#static-type-checking)
16
+
* Control flow and agent composition is done with vanilla Python, allowing you to make use of the same Python development best practices you'd use in any other (non-AI) project
17
17
*[Structured response](results.md#structured-result-validation) validation with Pydantic
18
18
*[Streamed responses](results.md#streamed-results), including validation of streamed _structured_ responses with Pydantic
19
19
* Novel, type-safe [dependency injection system](dependencies.md), useful for testing and eval-driven iterative development
@@ -124,66 +124,47 @@ async def main():
124
124
125
125
1. This [agent](agents.md) will act as first-tier support in a bank. Agents are generic in the type of dependencies they accept and the type of result they return. In this case, the support agent has type `#!python Agent[SupportDependencies, SupportResult]`.
126
126
2. Here we configure the agent to use [OpenAI's GPT-4o model](api/models/openai.md), you can also set the model when running the agent.
127
-
3. The `SupportDependencies` dataclass is used to pass data, connections, and logic into the model that will be needed when running [system prompt](agents.md#system-prompts) and [tool](agents.md#function-tools) functions. PydanticAI's system of dependency injection provides a type-safe way to customise the behavior of your agents, and can be especially useful when running unit tests and evals.
127
+
3. The `SupportDependencies` dataclass is used to pass data, connections, and logic into the model that will be needed when running [system prompt](agents.md#system-prompts) and [tool](agents.md#function-tools) functions. PydanticAI's system of dependency injection provides a [type-safe](agents.md#static-type-checking) way to customise the behavior of your agents, and can be especially useful when running [unit tests](testing-evals.md) and evals.
128
128
4. Static [system prompts](agents.md#system-prompts) can be registered with the [`system_prompt` keyword argument][pydantic_ai.Agent.__init__] to the agent.
129
129
5. Dynamic [system prompts](agents.md#system-prompts) can be registered with the [`@agent.system_prompt`][pydantic_ai.Agent.system_prompt] decorator, and can make use of dependency injection. Dependencies are carried via the [`RunContext`][pydantic_ai.dependencies.RunContext] argument, which is parameterized with the `deps_type` from above. If the type annotation here is wrong, static type checkers will catch it.
130
-
6.[Tools](agents.md#function-tools) let you register "tools" which the LLM may call while responding to a user. Again, dependencies are carried via [`RunContext`][pydantic_ai.dependencies.RunContext], and any other arguments become the tool schema passed to the LLM. Pydantic is used to validate these arguments, and errors are passed back to the LLM so it can retry.
130
+
6.[`tool`](agents.md#function-tools) let you register functions which the LLM may call while responding to a user. Again, dependencies are carried via [`RunContext`][pydantic_ai.dependencies.RunContext], and any other arguments become the tool schema passed to the LLM. Pydantic is used to validate these arguments, and errors are passed back to the LLM so it can retry.
131
131
7. The docstring of a tool is also passed to the LLM as the description of the tool. Parameter descriptions are [extracted](agents.md#function-tools-and-schema) from the docstring and added to the tool schema sent to the LLM.
132
132
8.[Run the agent](agents.md#running-agents) asynchronously, conducting a conversation with the LLM until a final response is reached. Even in this fairly simple case, the agent will exchange multiple messages with the LLM as tools are called to retrieve a result.
133
133
9. The response from the agent will, be guaranteed to be a `SupportResult`, if validation fails [reflection](agents.md#reflection-and-self-correction) will mean the agent is prompted to try again.
134
134
10. The result will be validated with Pydantic to guarantee it is a `SupportResult`, since the agent is generic, it'll also be typed as a `SupportResult` to aid with static type checking.
135
-
11. In a real use case, you'd add many more tools and a longer system prompt to the agent to extend the context it's equipped with and support it can provide.
135
+
11. In a real use case, you'd add more tools and a longer system prompt to the agent to extend the context it's equipped with and support it can provide.
136
136
12. This is a simple sketch of a database connection, used to keep the example short and readable. In reality, you'd be connecting to an external database (e.g. PostgreSQL) to get information about customers.
137
-
13. This [Pydantic](https://docs.pydantic.dev) model is used to constrain the structured data returned by the agent. From this simple definition, Pydantic builds the JSON Schema that tells the LLM how to return the data, and performs validation to guarantee the data is correct at the end of the conversation.
138
-
139
-
To help make things more clear, here is a diagram of what is happening in the `#!python await support_agent.run('What is my balance?', deps=deps)` call within `main`:
140
-
```mermaid
141
-
sequenceDiagram
142
-
participant DatabaseConn
143
-
participant Agent
144
-
participant LLM
145
-
146
-
Note over Agent: Dynamic system prompt<br>add_customer_name()
147
-
Agent ->> DatabaseConn: Retrieve customer name
148
-
activate DatabaseConn
149
-
DatabaseConn -->> Agent: "John"
150
-
deactivate DatabaseConn
151
-
152
-
Note over Agent: User query
153
-
154
-
Agent ->> LLM: Request<br>System: "You are a support agent..."<br>System: "The customer's name is John"<br>User: "What is my balance?"
13. This [Pydantic](https://docs.pydantic.dev) model is used to constrain the structured data returned by the agent. From this simple definition, Pydantic builds the JSON Schema that tells the LLM how to return the data, and performs validation to guarantee the data is correct at the end of the run.
179
138
180
139
!!! tip "Complete `bank_support.py` example"
181
140
The code included here is incomplete for the sake of brevity (the definition of `DatabaseConn` is missing); you can find the complete `bank_support.py` example [here](examples/bank-support.md).
182
141
142
+
## Instrumentation with Pydantic Logfire
143
+
144
+
To understand the flow of the above runs, we can watch the agent in action using Pydantic Logfire.
145
+
146
+
To do this, we need to set up logfire, and add the following to our code:
147
+
148
+
```py title="bank_support_with_logfire.py"
149
+
import logfire
150
+
151
+
logfire.configure() # (1)!
152
+
logfire.instrument_asyncpg() # (2)!
153
+
```
154
+
155
+
1. Configure logfire, this will fail if not project is set up.
156
+
2. In our demo, `DatabaseConn` uses [`asyncpg`]() to connect to a PostgreSQL database, so [`logfire.instrument_asyncpg()`](https://magicstack.github.io/asyncpg/current/) is used to log the database queries.
157
+
158
+
That's enough to get the following view of your agent in action:
0 commit comments