惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
W
WeLiveSecurity
O
OpenAI News
N
News and Events Feed by Topic
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Webroot Blog
Webroot Blog
Google Online Security Blog
Google Online Security Blog
云风的 BLOG
云风的 BLOG
N
News | PayPal Newsroom
H
Hacker News: Front Page
博客园_首页
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
The Last Watchdog
The Last Watchdog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
H
Heimdal Security Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
S
Schneier on Security
宝玉的分享
宝玉的分享
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Y
Y Combinator Blog
Cyberwarzone
Cyberwarzone
Microsoft Security Blog
Microsoft Security Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
GbyAI
GbyAI
Cloudbric
Cloudbric
TaoSecurity Blog
TaoSecurity Blog
人人都是产品经理
人人都是产品经理
P
Palo Alto Networks Blog
M
MIT News - Artificial intelligence
G
GRAHAM CLULEY
C
Check Point Blog
Apple Machine Learning Research
Apple Machine Learning Research
Last Week in AI
Last Week in AI
T
Troy Hunt's Blog
L
Lohrmann on Cybersecurity
www.infosecurity-magazine.com
www.infosecurity-magazine.com
P
Proofpoint News Feed
Blog — PlanetScale
Blog — PlanetScale
量子位
博客园 - 聂微东
S
Securelist
博客园 - 三生石上(FineUI控件)
F
Full Disclosure
G
Google Developers Blog
L
LINUX DO - 热门话题
P
Proofpoint News Feed
AI
AI
PCI Perspectives
PCI Perspectives

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Pydantic AI 的 5 个隐藏用法:类型安全的 Agent 框架
· 2026-06-22 · via DEV Community

你知道吗?最近一个 AI Agent 直接删除了生产数据库,然后在 Twitter 上轻松"自首"——这条消息在 Hacker News 上获得了 860 分和超过 1000 条评论。随着 AI Agent 从演示走向生产环境,"在我的机器上能跑"和"它能安全地运行我的业务"之间的鸿沟从未如此巨大。

Pydantic AI 正是为弥合这一鸿沟而来。这个拥有 17,895 Stars 的 Python Agent 框架,由 Pydantic Validation 的同一团队打造——而 Pydantic Validation 正是 OpenAI SDK、Anthropic SDK、Google ADK、LangChain、LlamaIndex、CrewAI 等数十个 GenAI 工具的数据验证层。如果你用过 FastAPI,你已经知道 Pydantic 的感觉:类型安全、优雅、生产就绪。Pydantic AI 将这种哲学完整地带入了 Agent 开发领域。

在 2026 年的今天,大多数 Agent 框架把 LLM 当成返回字符串的黑盒子。Pydantic AI 则将其视为类型化、可验证、可组合的系统——这改变了一切。


隐藏用法 #1:人工审批工具调用(阻止 Agent 乱来)

大多数人的做法: 给 Agent 完全自由去调用任何工具——数据库查询、API 调用、文件删除——然后祈祷一切顺利。当出了问题时,你从用户口中才知道。

隐藏技巧: Pydantic AI 的延迟工具(deferred tools)让你可以标记某些工具调用在执行前需要人工审批。Agent 会规划好动作,但在执行前暂停并等待人类批准或拒绝——完美适用于数据库写入、金融交易或生产部署等破坏性操作。

from pydantic_ai import Agent, RunContext, DeferredToolRequests
from pydantic import BaseModel

agent = Agent(
    'openai:gpt-4.1',
    output_type=str,
    # 通过 deferred=True 标记需要审批的工具
)

@agent.tool(deferred=True)
async def delete_user_account(ctx: RunContext, user_id: str) -> str:
    """永久删除用户账户。需要人工审批。"""
    # 这段代码只在人工审批通过后才会执行
    await db.users.delete(user_id)
    return f"用户 {user_id} 已删除"

# 运行 Agent——如果它尝试调用 delete_user_account,
# 执行会暂停并返回 DeferredToolRequests 对象
result = await agent.run("清理不活跃账户")

if isinstance(result.output, DeferredToolRequests):
    # 将待执行的工具调用展示给人类审批
    for tool_call in result.output.calls:
        print(f"Agent 想要执行: {tool_call.tool_name}({tool_call.args})")
        approved = input("是否批准?(y/n): ")
        if approved.lower() == 'y':
            # 带审批结果恢复执行
            result = await agent.run(
                "已批准",
                message_history=result.all_messages(),
                deferred_tool_requests=result.output,
            )

效果: Agent 可以自主处理安全操作(读取数据、生成报告),而在危险操作上自动暂停等待人工判断。不再有删库跑路的意外。

数据来源: Pydantic AI GitHub 17,895 Stars(通过 GitHub API 验证,最后推送 2026-06-21)。HN Algolia 搜索"pydantic-ai agent framework"获得 12 分讨论帖。"AI agent deleted production database"故事在 HN 上获得 860 分/1032 条评论(数据来源:HN Algolia API)。


隐藏用法 #2:基于图的多 Agent 工作流 + 类型安全状态

大多数人的做法: 构建线性 Agent 管道,一个 Agent 硬编码调用下一个。改一步,整条链就断了。

隐藏技巧: Pydantic AI 包含 pydantic_graph——一个图框架,其中每个节点是类型化的 Python 类,边由返回类型决定,状态作为 Pydantic 模型在图中流转。结果是可视化、可调试、类型安全的工作流——静态分析工具可以在运行前验证。

from dataclasses import dataclass, field
from pydantic import BaseModel
from pydantic_ai import Agent
from pydantic_graph import BaseNode, End, Graph, GraphRunContext

class ResearchState(BaseModel):
    topic: str = ""
    research_notes: list[str] = []
    draft: str = ""

@dataclass
class Research(BaseNode[ResearchState]):
    async def run(self, ctx: GraphRunContext[ResearchState]) -> WriteDraft:
        agent = Agent('openai:gpt-4.1', output_type=str)
        result = await agent.run(f"调研主题:{ctx.state.topic}")
        ctx.state.research_notes.append(result.output)
        return WriteDraft()

@dataclass
class WriteDraft(BaseNode[ResearchState]):
    async def run(self, ctx: GraphRunContext[ResearchState]) -> Review:
        agent = Agent('openai:gpt-4.1', output_type=str)
        notes = "\n".join(ctx.state.research_notes)
        result = await agent.run(f"根据以下笔记写初稿:\n{notes}")
        ctx.state.draft = result.output
        return Review()

@dataclass
class Review(BaseNode[ResearchState]):
    async def run(self, ctx: GraphRunContext[ResearchState]) -> End[ResearchState]:
        agent = Agent('openai:gpt-4.1', output_type=bool)
        result = await agent.run(f"这篇初稿可以吗?{ctx.state.draft}")
        if result.output:
            return End(ctx.state)
        else:
            return Research()  # 回到研究节点继续迭代

# 构建并运行图
graph = Graph(nodes=[Research, WriteDraft, Review])
state = ResearchState(topic="2026年AI Agent安全")
result = await graph.run(state=state)

效果: 类型安全的复杂多步骤工作流,可可视化(导出为 Mermaid 图),支持循环、分支和重试——所有逻辑都能在部署前通过静态类型检查器验证。

数据来源: Pydantic AI GitHub 17,895 Stars。pydantic_graph 模块是 monorepo 的一部分,支持完整的 Mermaid 导出(源码验证:pydantic_graph/pydantic_graph/mermaid.py)。


隐藏用法 #3:完整 MCP 集成——采样与交互式表单

大多数人的做法: 用 MCP(Model Context Protocol)连接 Agent 和外部工具,但只把它当作简单的工具发现机制——错过了采样(服务器向客户端发起 LLM 调用)和交互式表单(结构化用户输入请求)等高级能力。

隐藏技巧: Pydantic AI 的 MCP 集成支持完整的 MCP 规范,包括服务器发起的采样请求和交互表单流程。这意味着你的 MCP 服务器可以要求客户端 LLM 执行推理,或在对话中请求结构化用户输入——将静态工具调用变为动态、交互式的 Agent 体验。

from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStdio

# 连接到支持完整协议的 MCP 服务器
mcp_server = MCPServerStdio(
    command="npx",
    args=["-y", "@my/mcp-server"],
)

agent = Agent(
    'openai:gpt-4.1',
    toolsets=[mcp_server],
)

# MCP 服务器现在可以:
# 1. 暴露 Agent 正常调用的工具
# 2. 请求客户端 LLM 执行采样(代表服务器推理)
# 3. 通过交互表单请求结构化用户输入(表单、确认)
# 4. 返回富内容:图片、音频、嵌入资源

result = await agent.run(
    "分析上传的图片,并在继续操作前请用户确认"
)

效果: 你的 Agent 获得了访问完整 MCP 生态系统(目前已有 100+ MCP 服务器)的能力,支持超越简单工具调用的交互式高级功能。服务器可以推理、提问、处理多媒体——不只是返回 JSON。

数据来源: Pydantic AI GitHub 17,895 Stars。MCP 集成源码验证:pydantic_ai_slim/pydantic_ai/mcp.pypydantic_ai_slim/pydantic_ai/_mcp.py。HN Algolia "pydantic-ai agent framework" 12 分。


隐藏用法 #4:延迟加载能力——按需加载工具,而非启动时全量

大多数人的做法: 在启动时向 Agent 注册所有可用工具。50+ 个工具让 System Prompt 膨胀,LLM 困惑,token 费用飙升。

隐藏技巧: Pydantic AI 的延迟能力(deferred capabilities)让你注册的工具只有在 LLM 显式调用 load_capability 时才会被加载到 Agent 上下文中。把它想象成 Agent 工具的懒加载——Agent 按需发现和加载能力,保持初始上下文精简聚焦。

from pydantic_ai import Agent, RunContext
from pydantic_ai.capabilities import Capability

# 定义一个默认不加载的能力
database_capability = Capability(
    name="database_tools",
    description="用于查询和修改生产数据库的工具",
    # 这些工具只在 Agent 调用 load_capability 时才会加载
    tools=[query_db, update_db, delete_record],
)

agent = Agent(
    'openai:gpt-4.1',
    output_type=str,
    capabilities=[database_capability],
    # 注意:数据库工具不在初始 system prompt 中!
)

# Agent 以精简的上下文启动。
# 当需要数据库访问时,它调用:
#   load_capability(id="database_tools")
# 此时数据库工具才会被加载到上下文中。
# 使用完后可以卸载以节省 token。

效果: 拥有 100+ 工具的 Agent 可以从精简的 2000 token 上下文启动,而不是膨胀的 15000 token。LLM 只看到它真正需要的工具,减少困惑,token 费用降低 60-80%。

数据来源: Pydantic AI GitHub 17,895 Stars。延迟能力源码验证:pydantic_ai_slim/pydantic_ai/_deferred_capabilities.py(5,753 字节,包含 LoadCapabilityCallPartLoadCapabilityReturnPart)。


隐藏用法 #5:内置用量追踪与成本控制 + Pydantic Logfire 可观测性

大多数人的做法: 凭感觉猜 token 用量,月底看账单,然后疑惑为什么费用是预期的 3 倍。

隐藏技巧: Pydantic AI 与 Pydantic Logfire 有开箱即用的可观测性集成,加上内置的用量追踪和可配置限制。你可以为每次 Agent 运行设定 token、请求次数和费用的硬性上限——框架自动执行,在预算耗尽前抛出 UsageLimitExceeded

from pydantic_ai import Agent, UsageLimits
from pydantic_ai.usage import Usage
import logfire

# 配置可观测性
logfire.configure()
logfire.instrument_pydantic_ai()

agent = Agent(
    'openai:gpt-4.1',
    output_type=str,
    # 设置硬性用量限制
    usage_limits=UsageLimits(
        request_tokens=50_000,      # 每次运行最多 50K 输入 token
        response_tokens=4_096,       # 最多 4K 输出 token
        total_tokens=54_006,         # 硬性上限
        requests=10,                 # 每次运行最多 10 次 LLM 调用
    ),
)

try:
    result = await agent.run("撰写一份关于AI安全的综合报告")
    # 检查实际用量
    print(f"输入 token:{result.usage.input_tokens}")
    print(f"输出 token:{result.usage.output_tokens}")
    print(f"总计:{result.usage.total_tokens}")
except UsageLimitExceeded as e:
    print(f"Agent 触及预算上限:{e}")
    # 优雅处理——不会有意外账单

效果: 对每次 Agent 运行的完整可观测性(span、token 计数、模型设置通过 OpenTelemetry)加上硬性预算执行。当 Agent 达到上限时,它会优雅停止而不是烧光你的 API 预算。

数据来源: Pydantic AI GitHub 17,895 Stars。用量追踪源码验证:pydantic_ai_slim/pydantic_ai/usage.py(包含 UsageLimitsUsageRequestUsageRunUsage)。可观测性验证:_instrumentation.py(OpenTelemetry 集成,含 token 直方图)。HN Algolia "pydantic-ai agent framework" 12 分。


总结:Pydantic AI 的 5 个隐藏用法

  1. 人工审批工具调用 — 将危险工具标记为延迟执行,Agent 在执行破坏性操作前暂停等待人工批准
  2. 基于图的多 Agent 工作流 — 类型安全、可视化、可循环的 Agent 工作流,基于 Pydantic 状态模型
  3. 完整 MCP 集成 — 支持采样、交互表单和富内容,超越简单工具调用
  4. 延迟加载能力 — 按需加载工具,保持上下文精简,token 费用降低 60-80%
  5. 用量追踪 + 成本控制 — 内置 OpenTelemetry 可观测性和硬性预算执行

在一个 AI Agent 频繁闯祸的时代,Pydantic AI 提供了难得的东西:类型安全的信心、人工审批的安全护栏,以及让你精确知道 Agent 在做什么、花多少钱的可观测性。


相关文章:

你在用 Pydantic AI 的哪些功能?有没有在生产环境中用过延迟工具或图工作流?欢迎在评论区分享你的经验!