返回 MCP 目录
public公开dns本地运行

mcp-run-python

PydanticAI是由Pydantic团队开发的Python代理框架,旨在简化基于生成式AI的生产级应用开发。它支持多种AI模型,集成Pydantic验证和结构化输出,提供依赖注入系统、流式响应和图形支持,并与Pydantic Logfire无缝集成,适用于类型安全、高效的AI应用构建。

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的使用方法,请参考示例文档

help

运行方式说明

cloud

托管运行

托管运行通常表示这个 MCP Server 由服务方环境承载,用户一般按页面提供的连接方式或授权流程接入,不需要在本地长期启动一个 MCP 进程

  1. 打开服务方连接页
  2. 完成授权或复制端点
  3. 在 MCP 客户端中连接
terminal

本地运行 / 其它方式

本地运行通常需要用户在自己的电脑或服务器上安装依赖,把 server_config 复制到 MCP 客户端,并按 env_schema 补齐环境变量、密钥或其它配置

  1. 复制 server_config
  2. 安装所需依赖
  3. 补齐环境变量后重启客户端