from pydantic_ai import Agent agent = Agent( 'gemini-1.5-flash', system_prompt='Be concise, reply with one sentence.' ) result = agent.run_sync('Where does "hello world" come from?') print(result.data)
输出结果:The first known use of "hello, world" was in a 1974 textbook about the C programming language.
“The first known use of 'hello, world' was in a 1974 textbook about the C programming language.”
这展示了智能体如何提供事实性且简洁的答案。
工具与依赖注入示例:银行客户支持智能体示例
以下是使用PydanticAI为银行构建支持智能体的简单示例:
# 安装与依赖 python -m pydantic_ai_examples.bank_support from dataclasses import dataclass from pydantic import BaseModel, Field from pydantic_ai import Agent, RunContext classDatabaseConn: """这是用于示例的假数据库。 在实际应用中,你需要连接到外部数据库(例如PostgreSQL)以获取客户信息。 """ @classmethod asyncdefcustomer_name(cls, *, id: int) -> str | None: if id == 123: return'John' @classmethod asyncdefcustomer_balance(cls, *, id: int, include_pending: bool) -> float: if id == 123: return123.45 else: raise ValueError('Customer not found') @dataclass classSupportDependencies: customer_id: int db: DatabaseConn classSupportResult(BaseModel): support_advice: str = Field(description='Advice returned to the customer') block_card: bool = Field(description='Whether to block their') risk: int = Field(description='Risk level of query', ge=0, le=10) 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. ' "Reply using the customer's name." ), ) @support_agent.system_prompt asyncdefadd_customer_name(ctx: RunContext[SupportDependencies]) -> str: customer_name = await ctx.deps.db.customer_name(id=ctx.deps.customer_id) returnf"The customer's name is {customer_name!r}" @support_agent.tool asyncdefcustomer_balance( ctx: RunContext[SupportDependencies], include_pending: bool ) -> str: """Returns the customer's current account balance.""" balance = await ctx.deps.db.customer_balance( id=ctx.deps.customer_id, include_pending=include_pending, ) returnf'${balance:.2f}' deps = SupportDependencies(customer_id=123, db=DatabaseConn()) result = support_agent.run_sync('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 = support_agent.run_sync('I just lost my card!', deps=deps) print(result.data)
输出结果:support_advice="I'm sorry to hear that, John. We are temporarily blocking your card to prevent unauthorized transactions." block_card=True risk=8
Pydantic AI 十分重视验证环节,能够与主流大语言模型实现良好协作,并且开发出的工具非常契合实际生产需求。凭借这些优势,Pydantic AI 极有可能在未来成为开发者们常用的框架。它的验证机制有助于减少开发过程中的错误,与大语言模型的集成拓展了应用的功能边界,而生产级工具则为项目的顺利落地提供了有力保障。
但 Pydantic AI 也面临着挑战,它的成功依赖开发者的采用程度和持续创新能力。毕竟,在技术快速迭代的当下,只有不断进化,满足开发者日益增长的需求,才能在激烈的竞争中脱颖而出。
如果你已经很熟悉 Pydantic 的开发,那么 Pydantic AI 更像是一次自然的技术进阶。两者一脉相承,从 Pydantic 过渡到 Pydantic AI,上手难度低,还能借助新框架解锁更多 AI 开发的新可能。