AI Personal Learning
and practical guidance

PydanticAI:使用Pydantic构建生成式AI应用,让构建生产级AI应用更加简单

General Introduction

PydanticAI是一个基于Pydantic的Python代理框架,旨在简化生成式AI应用的开发。它由Pydantic团队开发,支持多种模型(如OpenAI、Gemini、Groq等),并提供类型安全的控制流和代理组合。PydanticAI通过结构化响应验证和流式响应,确保生成式AI应用的高效性和可靠性。其独特的依赖注入系统有助于测试和迭代开发,并集成了Logfire用于调试和监控应用性能。PydanticAI目前处于早期测试阶段,API可能会有变动,欢迎用户反馈。

 

Function List

  • Multi-model support:兼容OpenAI、Gemini、Groq等多种生成式AI模型。
  • 类型安全:使用Pydantic进行结构化响应验证,确保数据类型安全。
  • 依赖注入系统:提供类型安全的依赖注入,便于测试和迭代开发。
  • Streaming Response:支持流式响应和验证,提高应用响应速度和可靠性。
  • Logfire集成:用于调试和监控生成式AI应用的性能和行为。
  • 简单接口:提供简洁的接口,便于扩展和集成其他模型。

 

Using Help

Installation process

  1. 安装PydanticAI:确保Python版本为3.9及以上,使用以下命令安装PydanticAI:
   pip install pydantic-ai
  1. Installation of dependencies:PydanticAI依赖于一些核心库和LLM API,安装时会自动处理这些依赖。

Guidelines for use

创建简单代理

  1. 定义代理:创建一个简单的代理并指定使用的模型。
   from pydantic_ai import Agent
agent = Agent(
'gemini-1.5-flash',
system_prompt='Be concise, reply with one sentence.',
)
  1. Running Agents:同步运行代理,进行简单的对话。
   result = agent.run_sync('Where does "hello world" come from?')
print(result.data)

复杂代理示例

  1. 定义依赖和结果模型:使用Pydantic定义依赖和结果模型。
   from dataclasses import dataclass
from pydantic import BaseModel, Field
from pydantic_ai import Agent, RunContext
from bank_database import DatabaseConn
@dataclass
class SupportDependencies:
customer_id: int
db: DatabaseConn
class SupportResult(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)
  1. 创建支持代理:定义系统提示和工具函数。
   support_agent = Agent(
'openai:gpt-4o',
deps_type=SupportDependencies,
result_type=SupportResult,
system_prompt=(
'You are a support agent in our bank, give the '
'customer support and judge the risk level of their query.'
),
)
@support_agent.system_prompt
async def add_customer_name(ctx: RunContext[SupportDependencies]) -> str:
customer_name = await ctx.deps.db.customer_name(id=ctx.deps.customer_id)
return f"The customer's name is {customer_name!r}"
@support_agent.tool
async def customer_balance(ctx: RunContext[SupportDependencies], include_pending: bool) -> float:
"""Returns the customer's current account balance."""
return await ctx.deps.db.customer_balance(id=ctx.deps.customer_id, include_pending=include_pending)
  1. 运行支持代理:使用定义的依赖运行代理。
   async def main():
deps = SupportDependencies(customer_id=123, db=DatabaseConn())
result = await support_agent.run('What is my balance?', deps=deps)
print(result.data)
# 输出示例:support_advice='Hello John, your current account balance, including pending transactions, is $123.45.' block_card=False risk=1
result = await support_agent.run('I just lost my card!', deps=deps)
print(result.data)
# 输出示例:support_advice="I'm sorry to hear that, John. Your card has been blocked for security reasons." block_card=True risk=7

Debugging and Monitoring

PydanticAI集成了Logfire,用于调试和监控生成式AI应用的性能和行为。通过Logfire,可以实时查看代理运行情况,分析响应数据,优化应用性能。

反馈和改进

PydanticAI目前处于早期测试阶段,API可能会有变动。用户在使用过程中遇到任何问题或有改进建议,欢迎通过GitHub提交反馈。


AI Easy Learning

The layman's guide to getting started with AI

Help you learn how to utilize AI tools at a low cost and from a zero base.AI, like office software, is an essential skill for everyone. Mastering AI will give you an edge in your job search and half the effort in your future work and studies.

View Details>
May not be reproduced without permission:Chief AI Sharing Circle " PydanticAI:使用Pydantic构建生成式AI应用,让构建生产级AI应用更加简单

Chief AI Sharing Circle

Chief AI Sharing Circle specializes in AI learning, providing comprehensive AI learning content, AI tools and hands-on guidance. Our goal is to help users master AI technology and explore the unlimited potential of AI together through high-quality content and practical experience sharing. Whether you are an AI beginner or a senior expert, this is the ideal place for you to gain knowledge, improve your skills and realize innovation.

Contact Us
en_USEnglish