Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
PyPI

pydantic-ai 0.4.3

pip install pydantic-ai

Latest version

Released:

Agent Framework / shim to use Pydantic with LLMs

Verified details

These details have beenverified by PyPI
Project links
Owner
GitHub Statistics
Maintainers
Avatar for dmontagu from gravatar.comdmontaguAvatar for samuelcolvin from gravatar.comsamuelcolvin

Unverified details

These details havenot been verified by PyPI
Project links
Meta

Project description

PydanticAI
Agent Framework / shim to use Pydantic with LLMs
CICoveragePyPIversionslicenseJoin Slack

Documentation:ai.pydantic.dev


PydanticAI is a Python agent framework designed to make it less painful to build production grade applications with Generative AI.

FastAPI revolutionized web development by offering an innovative and ergonomic design, built on the foundation ofPydantic.

Similarly, virtually every agent framework and LLM library in Python uses Pydantic, yet when we began to use LLMs inPydantic Logfire, we couldn't find anything that gave us the same feeling.

We built PydanticAI with one simple aim: to bring that FastAPI feeling to GenAI app development.

Why use PydanticAI

  • Built by the Pydantic TeamBuilt by the team behindPydantic (the validation layer of the OpenAI SDK, the Anthropic SDK, LangChain, LlamaIndex, AutoGPT, Transformers, CrewAI, Instructor and many more).

  • Model-agnosticSupports OpenAI, Anthropic, Gemini, Deepseek, Ollama, Groq, Cohere, and Mistral, and there is a simple interface to implement support forother models.

  • Pydantic Logfire IntegrationSeamlesslyintegrates withPydantic Logfire for real-time debugging, performance monitoring, and behavior tracking of your LLM-powered applications.

  • Type-safeDesigned to maketype checking as powerful and informative as possible for you.

  • Python-centric DesignLeverages Python's familiar control flow and agent composition to build your AI-driven projects, making it easy to apply standard Python best practices you'd use in any other (non-AI) project.

  • Structured ResponsesHarnesses the power ofPydantic tovalidate and structure model outputs, ensuring responses are consistent across runs.

  • Dependency Injection SystemOffers an optionaldependency injection system to provide data and services to your agent'ssystem prompts,tools andoutput validators.This is useful for testing and eval-driven iterative development.

  • Streamed ResponsesProvides the ability tostream LLM outputs continuously, with immediate validation, ensuring rapid and accurate outputs.

  • Graph SupportPydantic Graph provides a powerful way to define graphs using typing hints, this is useful in complex applications where standard control flow can degrade to spaghetti code.

Hello World Example

Here's a minimal example of PydanticAI:

frompydantic_aiimportAgent# Define a very simple agent including the model to use, you can also set the model when running the agent.agent=Agent('google-gla:gemini-1.5-flash',# Register a static system prompt using a keyword argument to the agent.# For more complex dynamically-generated system prompts, see the example below.system_prompt='Be concise, reply with one sentence.',)# Run the agent synchronously, conducting a conversation with the LLM.# Here the exchange should be very short: PydanticAI will send the system prompt and the user query to the LLM,# the model will return a text response. See below for a more complex run.result=agent.run_sync('Where does "hello world" come from?')print(result.output)"""The first known use of "hello, world" was in a 1974 textbook about the C programming language."""

(This example is complete, it can be run "as is")

Not very interesting yet, but we can easily add "tools", dynamic system prompts, and structured responses to build more powerful agents.

Tools & Dependency Injection Example

Here is a concise example using PydanticAI to build a support agent for a bank:

(Better documented examplein the docs)

fromdataclassesimportdataclassfrompydanticimportBaseModel,Fieldfrompydantic_aiimportAgent,RunContextfrombank_databaseimportDatabaseConn# SupportDependencies is used to pass data, connections, and logic into the model that will be needed when running# system prompt and tool functions. Dependency injection provides a type-safe way to customise the behavior of your agents.@dataclassclassSupportDependencies:customer_id:intdb:DatabaseConn# This pydantic model defines the structure of the output returned by the agent.classSupportOutput(BaseModel):support_advice:str=Field(description='Advice returned to the customer')block_card:bool=Field(description="Whether to block the customer's card")risk:int=Field(description='Risk level of query',ge=0,le=10)# This agent will act as first-tier support in a bank.# Agents are generic in the type of dependencies they accept and the type of output they return.# In this case, the support agent has type `Agent[SupportDependencies, SupportOutput]`.support_agent=Agent('openai:gpt-4o',deps_type=SupportDependencies,# The response from the agent will, be guaranteed to be a SupportOutput,# if validation fails the agent is prompted to try again.output_type=SupportOutput,system_prompt=('You are a support agent in our bank, give the ''customer support and judge the risk level of their query.'),)# Dynamic system prompts can make use of dependency injection.# Dependencies are carried via the `RunContext` argument, which is parameterized with the `deps_type` from above.# If the type annotation here is wrong, static type checkers will catch it.@support_agent.system_promptasyncdefadd_customer_name(ctx:RunContext[SupportDependencies])->str:customer_name=awaitctx.deps.db.customer_name(id=ctx.deps.customer_id)returnf"The customer's name is{customer_name!r}"# `tool` let you register functions which the LLM may call while responding to a user.# Again, dependencies are carried via `RunContext`, 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.@support_agent.toolasyncdefcustomer_balance(ctx:RunContext[SupportDependencies],include_pending:bool)->float:"""Returns the customer's current account balance."""# The docstring of a tool is also passed to the LLM as the description of the tool.# Parameter descriptions are extracted from the docstring and added to the parameter schema sent to the LLM.balance=awaitctx.deps.db.customer_balance(id=ctx.deps.customer_id,include_pending=include_pending,)returnbalance...# In a real use case, you'd add more tools and a longer system promptasyncdefmain():deps=SupportDependencies(customer_id=123,db=DatabaseConn())# Run the agent 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 an output.result=awaitsupport_agent.run('What is my balance?',deps=deps)# The `result.output` will be validated with Pydantic to guarantee it is a `SupportOutput`. Since the agent is generic,# it'll also be typed as a `SupportOutput` to aid with static type checking.print(result.output)"""    support_advice='Hello John, your current account balance, including pending transactions, is $123.45.' block_card=False risk=1    """result=awaitsupport_agent.run('I just lost my card!',deps=deps)print(result.output)"""    support_advice="I'm sorry to hear that, John. We are temporarily blocking your card to prevent unauthorized transactions." block_card=True risk=8    """

Next Steps

To try PydanticAI yourself, follow the instructionsin the examples.

Read thedocs to learn more about building applications with PydanticAI.

Read theAPI Reference to understand PydanticAI's interface.

Project details

Verified details

These details have beenverified by PyPI
Project links
Owner
GitHub Statistics
Maintainers
Avatar for dmontagu from gravatar.comdmontaguAvatar for samuelcolvin from gravatar.comsamuelcolvin

Unverified details

These details havenot been verified by PyPI
Project links
Meta

Release historyRelease notifications |RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more aboutinstalling packages.

Source Distribution

pydantic_ai-0.4.3.tar.gz (41.4 MBview details)

UploadedSource

Built Distribution

pydantic_ai-0.4.3-py3-none-any.whl (10.1 kBview details)

UploadedPython 3

File details

Details for the filepydantic_ai-0.4.3.tar.gz.

File metadata

  • Download URL:pydantic_ai-0.4.3.tar.gz
  • Upload date:
  • Size: 41.4 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for pydantic_ai-0.4.3.tar.gz
AlgorithmHash digest
SHA256c469145af1cd4cf0ad031bfe703b86dd38beee7c2d399482f8b12f738a8cd2b0
MD5d7a12b1068615d2813dbe34328a448e4
BLAKE2b-256b3457a4b717a9c77a1d7d1c406c5acac4c7f0400def99c2c57d5dffa7bcafbe1

See more details on using hashes here.

Provenance

The following attestation bundles were made forpydantic_ai-0.4.3.tar.gz:

Publisher:ci.yml on pydantic/pydantic-ai

Attestations:Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the filepydantic_ai-0.4.3-py3-none-any.whl.

File metadata

  • Download URL:pydantic_ai-0.4.3-py3-none-any.whl
  • Upload date:
  • Size: 10.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for pydantic_ai-0.4.3-py3-none-any.whl
AlgorithmHash digest
SHA256b2700a730bd42a6f295570789b0a33f456b229a119f612b10da23171a4fff8c2
MD51654e4add54f8278192f8d3775e22866
BLAKE2b-2563c77624351aa51527271cb522bf9f0908c8b10f79f7d2cb1da94b6ca15c26216

See more details on using hashes here.

Provenance

The following attestation bundles were made forpydantic_ai-0.4.3-py3-none-any.whl:

Publisher:ci.yml on pydantic/pydantic-ai

Attestations:Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security SponsorDatadog MonitoringFastly CDNGoogle Download AnalyticsPingdom MonitoringSentry Error loggingStatusPage Status page

[8]ページ先頭

©2009-2025 Movatter.jp