article
README
🚀 使用PydanticAI构建银行支持代理
本项目提供了使用PydanticAI构建银行支持代理的示例,涵盖依赖注入、动态系统提示和工具函数的定义,帮助你轻松满足各种业务需求。
🚀 快速开始
请参考以下链接以了解如何使用PydanticAI:
💻 使用示例
基础用法
1. 定义依赖项
from dataclasses import dataclass
from pydantic import BaseModel, Field
from pydantic_ai import Agent, RunContext
from bank_database import DatabaseConn
# 支持代理所需的依赖项,包括客户ID和数据库连接。
@dataclass
class SupportDependencies:
customer_id: int
db: DatabaseConn
2. 定义输出模型
# 输出模型用于定义支持代理返回的结果结构。
class SupportOutput(BaseModel):
support_advice: str = Field(description='建议提供给客户的信息')
block_card: bool = Field(description="是否需要阻止客户的卡片")
risk: int = Field(description='查询的风险等级', ge=0, le=10)
3. 定义支持代理
# 支持代理将作为银行的一线支持,处理客户查询。
support_agent = Agent(
'openai:gpt-4o',
deps_type=SupportDependencies,
output_type=SupportOutput,
system_prompt=(
'你是一位银行支持代理,请根据客户需求提供支持,并评估查询的风险等级。'
),
)
4. 定义动态系统提示
# 动态系统提示可以根据依赖项中的客户名称自定义响应。
@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"客户的姓名是 {customer_name!r}"
5. 定义工具函数
# 工具函数允许代理调用外部功能,如查询客户余额。
@support_agent.tool
async def customer_balance(
ctx: RunContext[SupportDependencies], include_pending: bool
) -> float:
"""返回客户的当前账户余额。"""
balance = await ctx.deps.db.customer_balance(
id=ctx.deps.customer_id,
include_pending=include_pending,
)
return balance
6. 使用代理处理查询
async def main():
deps = SupportDependencies(customer_id=123, db=DatabaseConn())
result = await support_agent.run('What is my balance?', deps=deps)
print(result.output)
# 示例输出:
# support_advice='您好,John先生,您当前的账户余额为 $123.45。' block_card=False risk=1
result = await support_agent.run('I just lost my card!', deps=deps)
print(result.output)
# 示例输出:
# support_advice="非常抱歉听到这个消息,John先生。为了防止未经授权的交易,我们暂时阻止了您的卡片使用。" block_card=True risk=8
🔚 总结
通过使用PydanticAI,您可以轻松地构建具有依赖注入、动态系统提示和工具函数的支持代理,以满足各种业务需求。希望这些示例能为您提供帮助!如需查看更多关于PydanticAI的使用方法,请参考示例文档。
Scan to contact