migrating-langchain-to-pydantic-ai
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMigrate LangChain, LangGraph, and Deep Agents to Pydantic AI
将 LangChain、LangGraph 和 Deep Agents 迁移到 Pydantic AI
Preserve behavior, not framework shape. Migrate the smallest behaviorally complete slice and leave application infrastructure outside that slice unchanged. LangChain, LangGraph, and Deep Agents are one source ecosystem; Pydantic AI, , and Pydantic AI Harness are the matching target ecosystem, and this skill maps across all of it.
pydantic_graph保留行为,而非框架形态。迁移最小但行为完整的切片,并保持该切片之外的应用基础架构不变。LangChain、LangGraph 和 Deep Agents 属于同一个源生态;Pydantic AI、 和 Pydantic AI Harness 是对应的目标生态,本 skill 覆盖整个生态之间的映射。
pydantic_graphWork from the running application
从实际运行的应用入手
- Read repository instructions, dependency files, tests, and the actual runtime entrypoints. Identify the installed LangChain, LangGraph, Deep Agents, Pydantic AI, and Harness versions.
- Trace one representative request through prompts, retrieval, model and tool calls, state, persistence, interrupts, emitted events, tracing/metrics callbacks, and the public result. Inspect every caller and sibling endpoint that consumes the migrated component; a narrow implementation slice can still have several public contracts. Include keyword parameter names and the sync, async, callback, and streaming forms callers actually use. Record only contracts those paths actually use.
- Run the cheapest useful baseline. When the migration surface is broad or unclear, search dependency files and source for ,
langchain,langgraph, andlangsmith, then confirm findings against imports, factories, and call sites. Resolve wheredeepagentscomes from: the upstream package and a vendored copy that reproduces its contracts both count as Deep Agents.create_deep_agent - Classify the slice before choosing a target:
- Chain or LCEL pipeline: keep deterministic retrieval and transformation in plain Python; use a Pydantic AI agent only where a model/tool loop adds value.
- LangChain agent: normally use one reusable with typed dependencies, tools, and outputs.
pydantic_ai.Agent - Direct LangGraph workflow: use plain async Python for simple fixed control flow, or when explicit typed nodes and branching remain useful. Treat persistence as a separate design decision.
pydantic_graph - Deep Agents harness: bundles file tools, shell execution, subagent delegation, summarization, skills, memory, permissions, prompt caching, and approval middleware on top of the LangChain agent loop, and a harness profile can add or hide more. Migrate the loop with the LangChain mappings, then map each bundled feature the slice actually uses to a Harness capability, a core primitive, or an application service with Deep Agents Mapping. Inventory implicit defaults the application code never mentions.
create_deep_agent - Product runtime: retain queues, configured database backends, sandboxes, auth, schedulers, webhooks, tracing, and transport adapters unless the user placed them in scope. Extend an existing application seam before creating a parallel persistence or provider subsystem.
- Add or preserve deterministic characterization tests, then migrate one vertical slice behind the existing public boundary.
- Run the original tests and focused parity tests. Classify each observed contract by its evidence; never describe the migration as one-to-one merely because the happy path or trace shape looks similar.
Read Concept Mapping for the detected source features. Read Deep Agents Mapping whenever is in the slice. Read Semantic Gaps only for state, middleware, retries, approval, concurrency, streaming, or other behavior where similar-looking APIs may differ. Use Workaround Recipes after a concrete gap is identified, not as a mandatory checklist. Read Logfire Verification when adding observability, comparing source and target runs, or debugging a semantic difference. Read Verification and Cutover before a production cutover.
deepagents- 阅读仓库说明、依赖文件、测试以及实际的运行时入口。确定已安装的 LangChain、LangGraph、Deep Agents、Pydantic AI 和 Harness 版本。
- 追踪一个代表性请求所经过的提示词、检索、模型与工具调用、状态、持久化、中断、发出事件、追踪/指标回调以及最终公共结果。检查所有调用方以及消费已迁移组件的同级端点;即使实现切片范围很窄,也可能涉及多个公共契约。记录调用方实际使用的关键字参数名称,以及同步、异步、回调和流式形式。只记录这些路径实际使用的契约。
- 运行成本最低且有价值的基线。当迁移范围较广或不明确时,在依赖文件和源代码中搜索 、
langchain、langgraph和langsmith,然后通过 imports、factories 和调用点确认搜索结果。查明deepagents的来源:无论来自上游 package,还是来自复现其契约的 vendored 副本,都视为 Deep Agents。create_deep_agent - 在选择目标之前先对切片进行分类:
- Chain 或 LCEL pipeline: 将确定性的检索和转换保留在普通 Python 中;仅在模型/工具循环能够带来价值的地方使用 Pydantic AI Agent。
- LangChain Agent: 通常使用一个可复用的 ,并配备类型化 dependencies、tools 和 outputs。
pydantic_ai.Agent - 直接使用 LangGraph 的 workflow: 对于简单的固定控制流,使用普通异步 Python;如果显式类型化节点和分支仍然有价值,则使用 。将持久化视为独立的设计决策。
pydantic_graph - Deep Agents Harness: 在 LangChain Agent 循环之上捆绑了文件工具、shell 执行、subagent 委派、摘要、skills、memory、permissions、prompt 缓存和 approval 中间件,Harness profile 还可能添加或隐藏更多功能。先使用 LangChain 映射迁移循环,再根据 Deep Agents Mapping,将该切片实际使用的每项捆绑功能映射到 Harness 能力、核心原语或应用服务。盘点应用代码从未显式提及的隐式默认值。
create_deep_agent - 产品运行时: 除非用户将这些内容纳入范围,否则保留队列、已配置的数据库后端、sandboxes、auth、调度器、webhooks、追踪以及传输适配器。优先扩展现有应用接入点,而不是创建并行的持久化或 provider 子系统。
- 添加或保留确定性的特征化测试,然后在现有公共边界之后迁移一个垂直切片。
- 运行原始测试和聚焦的一致性测试。根据证据对每个观察到的契约进行分类;绝不能仅因为 happy path 或 trace 形状相似,就将迁移描述为一对一映射。
阅读 Concept Mapping,了解检测到的源功能。只要切片中包含 ,就阅读 Deep Agents Mapping。仅当涉及状态、中间件、重试、approval、并发、流式处理或其他可能存在语义差异的行为时,才阅读 Semantic Gaps。只有在确定具体差距之后,才使用 Workaround Recipes,不要将其当作强制执行的检查清单。添加可观测性、比较源实现与目标实现的运行结果或调试语义差异时,阅读 Logfire Verification。生产切换前,阅读 Verification and Cutover。
deepagentsExplain semantic differences
解释语义差异
When an observed source contract has no direct equivalent, explain it to the user before making a consequential design choice. State the source behavior, how the proposed Pydantic AI design differs, the user-visible or operational impact, and the available choices. Recommend one option and name its residual risk. Keep this proportional: do not turn ordinary import or naming changes into semantic warnings.
Do not stop at "unsupported." When nothing maps directly, recommend an existing core or Harness composition, a narrow adapter or application service, a new capability built from public primitives, or a core change, in that order of preference. Ask before choosing only when the options materially change behavior, architecture, public API, or scope.
当观察到的源契约没有直接对应项时,应在做出有重大影响的设计选择之前向用户解释。说明源行为、拟议的 Pydantic AI 设计有何不同、对用户可见行为或运行产生的影响,以及可选方案。推荐一种方案,并说明其剩余风险。警告程度应与风险相称:不要将普通的 import 或命名变更视为语义警告。
不要停在“不支持”这一点。当没有直接映射时,应依次优先推荐:现有的核心或 Harness 组合、窄适配器或应用服务、基于公共原语构建的新能力,或者对核心进行更改。只有当各选项会实质改变行为、架构、公共 API 或范围时,才需要先询问用户。
Match rigor to risk
使严谨程度与风险匹配
- For a stateless chain or ordinary agent port, focused characterization tests and a short residual-risk note are enough. Do not require a semantic-gap register or durability exercise for behavior the source does not have.
- For middleware, structured output transport, retrieval, tool retries, or streaming, probe the affected contract against the installed versions.
- For checkpointed graphs, interrupts, approvals, durable execution, concurrent fan-out, or external side effects, create a migration ledger. Separate dependencies, messages, workflow state, checkpoint state, and long-term memory. Fit those owners into the repository's existing backend-selection and service interfaces where possible. Test restart, replay, correlation, authorization, and idempotency only to the extent the source promises them.
- A dependency alone changes nothing. When the active slice calls
deepagentsor depends on its planning, filesystem, sandbox, skills, memory, subagent, permission, or deployment contracts, those are in-scope features with Harness or application owners, not a reason to stop. Files, sandboxes, permissions, subagents, and background work carry the same ledger and restart obligations as checkpointed graphs.create_deep_agent
- 对于无状态 chain 或普通 Agent 移植,聚焦的特征化测试和简短的剩余风险说明已经足够。不要强制要求源实现本身不具备的行为使用语义差距登记表或持久化演练。
- 对于中间件、结构化输出传输、检索、工具重试或流式处理,应针对已安装的版本探测受影响的契约。
- 对于带检查点的 graph、中断、approvals、持久化执行、并发 fan-out 或外部副作用,应建立迁移台账。分离 dependencies、messages、workflow state、checkpoint state 和长期记忆。尽可能将这些职责归属方纳入仓库现有的后端选择和服务接口。只需在源实现所承诺的范围内测试重启、重放、关联、授权和幂等性。
- 仅依赖 本身不会改变任何事情。当活动切片调用
deepagents,或依赖其 planning、filesystem、sandbox、skills、memory、subagents、permissions 或 deployment 契约时,这些功能即属于迁移范围,应由 Harness 或应用层责任方承接,而不是停止迁移的理由。文件、sandboxes、permissions、subagents 和后台工作与带检查点的 graph 承担相同的台账和重启义务。create_deep_agent
Pydantic AI defaults
Pydantic AI 默认原则
- Put authenticated identity, service clients, and configuration in typed dependencies, never model-chosen tool arguments.
- Strengthen observed unstable seams, not the whole application: parameterize the agent's dependency and output types, and validate terminal choices, persisted workflow records, and framework adapters. Preserve stable public wire shapes and do not invent types for paths outside the migrated slice.
- Preserve public request, response, error, and event shapes with a small adapter while callers migrate.
- Keep retrieval, storage, provider, and transport integrations in place when they are outside the requested slice. Transitional LangChain integrations are acceptable when named and bounded.
- Use Pydantic models for terminal structured output when that preserves the contract; retain an existing parser when changing the wire contract would expand the migration.
- Do not force an onto deterministic LCEL or
Agentonto everypydantic_graph.StateGraph - Inspect the installed Pydantic AI API before choosing model classes, provider transports, hooks, streaming methods, or durable integrations.
- Add only for observed harness behavior: planning, workspace files, shell or sandboxed execution, Agent Skills, memory notebooks, repository context, model-directed subagents, model-agnostic compaction, tool-output limits, guardrails, spend limits, or step persistence. Add capabilities one at a time, import each from its owning public submodule, treat
pydantic-ai-harnessas version-sensitive, and run an import-and-construction smoke test in the target environment. Harness composes onto the core agent loop; it is not a second runtime and does not replace application infrastructure.pydantic_ai_harness.experimental.* - When adding Pydantic AI, prefer a currently supported stable release. Use the newest compatible release unless that would expand the migration through an unrelated major/runtime upgrade; explain and pin any exception. Resolve the whole project from a clean environment and run an import probe because an existing environment can hide incompatible transitive versions. Prefer with only the required provider and integration extras when the dependency surface is bounded, and use the full distribution when its broader integrations are actually needed. Do not pin an older release merely to match a remembered example.
pydantic-ai-slim - If the source already uses LangSmith, Langfuse, or another observability system, do not replace it silently. Explain that Logfire is the first-party Pydantic AI integration and normally provides the most direct agent, model, tool, retry, error, usage, and timing experience. Contrast that with the continuity of retaining the current system, including its dashboards, alerts, evaluations, retention, and export pipeline; recommend a choice and obtain agreement before switching. Offer Logfire at application startup when no tracing system exists or the user chooses it, make content capture an explicit privacy decision, and keep executable contract tests as the authority for parity.
- 将通过认证的身份、服务客户端和配置放入类型化 dependencies,绝不能将其作为由模型选择的工具参数。
- 加强已观察到的不稳定边界,而不是整个应用:参数化 Agent 的 dependency 和 output 类型,并验证最终选择、持久化的 workflow 记录以及框架适配器。保持稳定的公共 wire 格式,不要为迁移切片之外的路径发明新类型。
- 在调用方迁移期间,使用小型适配器保持公共 request、response、error 和 event 格式。
- 当检索、存储、provider 和传输集成不在请求的切片范围内时,保持原样。过渡性的 LangChain 集成可以使用,但必须明确命名并限定范围。
- 当使用 Pydantic 模型能够保持契约时,应将其用于最终结构化输出;如果更改 wire 契约会扩大迁移范围,则保留现有 parser。
- 不要强行将 应用于确定性的 LCEL,也不要将
Agent应用于每个pydantic_graph。StateGraph - 在选择模型类、provider 传输层、hooks、流式方法或持久化集成之前,检查已安装的 Pydantic AI API。
- 仅针对已观察到的 Harness 行为添加 :planning、workspace 文件、shell 或 sandbox 执行、Agent Skills、memory notebooks、仓库上下文、模型驱动的 subagents、模型无关的 compaction、tool 输出限制、guardrails、spend limits 或 step persistence。一次添加一项能力,从各自所属的 public 子模块导入,将
pydantic-ai-harness视为对版本敏感,并在目标环境中运行导入与构造冒烟测试。Harness 组合在核心 Agent 循环之上;它不是第二个运行时,也不会取代应用基础架构。pydantic_ai_harness.experimental.* - 添加 Pydantic AI 时,优先使用当前受支持的稳定版本。除非使用最新兼容版本会通过无关的 major/runtime 升级扩大迁移范围,否则应使用最新兼容版本;对于任何例外,都应解释原因并进行固定。不要仅仅为了匹配记忆中的示例而固定旧版本。从干净环境解析整个项目并运行导入探测,因为现有环境可能掩盖不兼容的传递依赖版本。当依赖范围有限时,优先使用仅包含所需 provider 和 integration extras 的 ;只有确实需要更广泛的 integrations 时,才使用完整发行版。
pydantic-ai-slim - 如果源项目已经使用 LangSmith、Langfuse 或其他可观测性系统,不要在未说明的情况下将其替换。说明 Logfire 是 Pydantic AI 的一方集成,通常能够提供最直接的 Agent、模型、工具、重试、错误、用量和计时体验。将其与保留当前系统所具有的连续性进行对比,包括 dashboard、alert、evaluation、retention 和 export pipeline;推荐一种方案,并在切换前取得一致意见。当不存在追踪系统或用户选择使用 Logfire 时,可在应用启动时提供 Logfire。内容捕获应作为明确的隐私决策,并始终以可执行契约测试作为一致性的判定依据。
Completion
完成标准
The slice is complete when every observed contract is either preserved by an executable check, intentionally changed by an accepted decision, or explicitly not applicable. An untested contract is , not equivalent; an unresolved requested contract is unfinished work, not completion evidence. Constrain the slice or ask the user to accept the deferral. Remove LangChain, LangGraph, or Deep Agents dependencies only after no retained path needs them.
unverified当每个观察到的契约都满足以下条件之一时,切片即告完成:由可执行检查保持不变、经已接受的决策有意更改,或者被明确判定为不适用。未经测试的契约是 ,并不代表等效;尚未解决的请求契约代表工作尚未完成,而不是完成证据。应缩小切片范围,或请用户接受延期。只有当任何仍保留的路径都不再需要 LangChain、LangGraph 或 Deep Agents 依赖时,才能移除这些依赖。
unverified