-
Notifications
You must be signed in to change notification settings - Fork 967
Add direct
public API
#1599
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Add direct
public API
#1599
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
6c18669
Add "low_level" public API
samuelcolvin 17155c8
fix tests
samuelcolvin faded9a
add instrumentation
samuelcolvin ba6edf6
adding docs
samuelcolvin 128273b
fix tests
samuelcolvin 41cb36e
feedback from alex
samuelcolvin f3fa208
fix logical conflicts
samuelcolvin 2e1afac
renaming "low_level" -> "direct"
samuelcolvin b98ecae
comments from Alex
samuelcolvin 92d7b1e
fix coverage
samuelcolvin d6a83e0
fix tool call test
samuelcolvin 49d7016
add logfire to title
samuelcolvin 3ddac57
Apply suggestions from code review
samuelcolvin c1bf165
Update docs/direct.md
alexmojaki dae83a1
Apply suggestions from code review (WIP)
alexmojaki fa1fdec
Merge branch 'main' of github.com:pydantic/pydantic-ai into low-level
alexmojaki 6932da7
fix
alexmojaki b7ccd41
add link to ModelRequest.user_text_prompt consistently
alexmojaki 60ea552
Merge branch 'main' into low-level
alexmojaki File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
# `pydantic_ai.direct` | ||
|
||
::: pydantic_ai.direct |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,160 @@ | ||
# Direct Model Requests | ||
|
||
The `direct` module provides low-level methods for making imperative requests to LLMs where the only abstraction is input and output schema translation, enabling you to use all models with the same API. | ||
|
||
These methods are thin wrappers around the [`Model`][pydantic_ai.models.Model] implementations, offering a simpler interface when you don't need the full functionality of an [`Agent`][pydantic_ai.Agent]. | ||
|
||
The following functions are available: | ||
|
||
- [`model_request`][pydantic_ai.direct.model_request]: Make a non-streamed async request to a model | ||
- [`model_request_sync`][pydantic_ai.direct.model_request_sync]: Make a non-streamed synchronous request to a model | ||
- [`model_request_stream`][pydantic_ai.direct.model_request_stream]: Make a streamed async request to a model | ||
|
||
## Basic Example | ||
|
||
Here's a simple example demonstrating how to use the direct API to make a basic request: | ||
|
||
```python title="direct_basic.py" | ||
from pydantic_ai.direct import model_request_sync | ||
from pydantic_ai.messages import ModelRequest | ||
|
||
# Make a synchronous request to the model | ||
model_response = model_request_sync( | ||
'anthropic:claude-3-5-haiku-latest', | ||
[ModelRequest.user_text_prompt('What is the capital of France?')] | ||
) | ||
|
||
print(model_response.parts[0].content) | ||
#> Paris | ||
print(model_response.usage) | ||
""" | ||
Usage(requests=1, request_tokens=56, response_tokens=1, total_tokens=57, details=None) | ||
""" | ||
``` | ||
|
||
_(This example is complete, it can be run "as is")_ | ||
|
||
## Advanced Example with Tool Calling | ||
|
||
You can also use the direct API to work with function/tool calling. | ||
|
||
Even here we can use Pydantic to generate the JSON schema for the tool: | ||
|
||
```python | ||
from pydantic import BaseModel | ||
from typing_extensions import Literal | ||
|
||
from pydantic_ai.direct import model_request | ||
from pydantic_ai.messages import ModelRequest | ||
from pydantic_ai.models import ModelRequestParameters | ||
from pydantic_ai.tools import ToolDefinition | ||
|
||
|
||
class Divide(BaseModel): | ||
"""Divide two numbers.""" | ||
|
||
numerator: float | ||
denominator: float | ||
on_inf: Literal['error', 'infinity'] = 'infinity' | ||
|
||
|
||
async def main(): | ||
# Make a request to the model with tool access | ||
model_response = await model_request( | ||
'openai:gpt-4.1-nano', | ||
[ModelRequest.user_text_prompt('What is 123 / 456?')], | ||
model_request_parameters=ModelRequestParameters( | ||
function_tools=[ | ||
ToolDefinition( | ||
name=Divide.__name__.lower(), | ||
description=Divide.__doc__ or '', | ||
parameters_json_schema=Divide.model_json_schema(), | ||
) | ||
], | ||
allow_text_output=True, # Allow model to either use tools or respond directly | ||
), | ||
) | ||
print(model_response) | ||
""" | ||
ModelResponse( | ||
parts=[ | ||
ToolCallPart( | ||
tool_name='divide', | ||
args={'numerator': '123', 'denominator': '456'}, | ||
tool_call_id='pyd_ai_2e0e396768a14fe482df90a29a78dc7b', | ||
part_kind='tool-call', | ||
) | ||
], | ||
usage=Usage( | ||
requests=1, | ||
request_tokens=55, | ||
response_tokens=7, | ||
total_tokens=62, | ||
details=None, | ||
), | ||
model_name='gpt-4.1-nano', | ||
timestamp=datetime.datetime(...), | ||
kind='response', | ||
) | ||
""" | ||
``` | ||
|
||
_(This example is complete, it can be run "as is" — you'll need to add `asyncio.run(main())` to run `main`)_ | ||
|
||
## When to Use the direct API vs Agent | ||
|
||
The direct API is ideal when: | ||
|
||
1. You need more direct control over model interactions | ||
2. You want to implement custom behavior around model requests | ||
3. You're building your own abstractions on top of model interactions | ||
|
||
For most application use cases, the higher-level [`Agent`][pydantic_ai.Agent] API provides a more convenient interface with additional features such as built-in tool execution, retrying, structured output parsing, and more. | ||
|
||
## OpenTelemetry or Logfire Instrumentation | ||
|
||
As with [agents][pydantic_ai.Agent], you can enable OpenTelemetry/Logfire instrumentation with just a few extra lines | ||
|
||
```python {title="direct_instrumented.py" hl_lines="1 6 7"} | ||
import logfire | ||
|
||
from pydantic_ai.direct import model_request_sync | ||
from pydantic_ai.messages import ModelRequest | ||
|
||
logfire.configure() | ||
logfire.instrument_pydantic_ai() | ||
|
||
# Make a synchronous request to the model | ||
model_response = model_request_sync( | ||
'anthropic:claude-3-5-haiku-latest', | ||
[ModelRequest.user_text_prompt('What is the capital of France?')], | ||
) | ||
|
||
print(model_response.parts[0].content) | ||
#> Paris | ||
``` | ||
|
||
_(This example is complete, it can be run "as is")_ | ||
|
||
You can also enable OpenTelemetry on a per call basis: | ||
|
||
```python {title="direct_instrumented.py" hl_lines="1 6 12"} | ||
import logfire | ||
|
||
from pydantic_ai.direct import model_request_sync | ||
from pydantic_ai.messages import ModelRequest | ||
|
||
logfire.configure() | ||
|
||
# Make a synchronous request to the model | ||
model_response = model_request_sync( | ||
'anthropic:claude-3-5-haiku-latest', | ||
[ModelRequest.user_text_prompt('What is the capital of France?')], | ||
instrument=True | ||
) | ||
|
||
print(model_response.parts[0].content) | ||
#> Paris | ||
``` | ||
|
||
See [Debugging and Monitoring](logfire.md) for more details, including how to instrument with plain OpenTelemetry without Logfire. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.