SuperAPI AI 工具集

langchain-fundamentals

智能体与模型

查看项目

更新于 10-29 04:37

技能介绍

用途

本技能聚焦 LangChain 中构建智能体的基础能力,核心是使用 create_agent() 创建智能体。create_agent() 是官方推荐的智能体构建方式,它负责处理智能体循环、工具执行与状态管理。内容同时提供 Python 与 TypeScript 两种语言的示例。

主要能力

1. 使用 create_agent 创建智能体

create_agent() 支持以下配置参数:

  • model:使用的 LLM,例如 "anthropic:claude-sonnet-4-5" 或模型实例。
  • tools:工具列表,例如 [search, calculator]。
  • system_prompt / systemPrompt:智能体指令,例如 "You are a helpful assistant"。
  • checkpointer:状态持久化,例如 MemorySaver()。
  • middleware:处理钩子,例如 Python 的 [HumanInTheLoopMiddleware] 或 TypeScript 的 [humanInTheLoopMiddleware({...})]。

Python 示例使用 from langchain.agents import create_agent 与 from langchain_core.tools import tool,通过 @tool 装饰器定义工具,调用 agent.invoke() 并读取 result["messages"][-1].content。

TypeScript 示例使用 import { createAgent } from "langchain"、import { tool } from "@langchain/core/tools" 与 zod,通过 tool() 函数定义工具,调用 await agent.invoke() 并读取 result.messages[result.messages.length - 1].content。

2. 定义工具

工具是智能体可以调用的函数。Python 使用 @tool 装饰器,TypeScript 使用 tool() 函数。示例中定义了 get_weather 与 add 工具,工具描述需清晰具体,并说明参数含义。

3. 中间件

中间件拦截智能体循环,用于添加人工审批、错误处理、日志等。资料强调深入理解中间件对生产级智能体至关重要:

  • 使用 HumanInTheLoopMiddleware(Python)/ humanInTheLoopMiddleware(TypeScript)实现审批工作流。
  • 使用 @wrap_tool_call(Python)/ createMiddleware(TypeScript)实现自定义钩子。

关键导入:

  • Python:from langchain.agents.middleware import HumanInTheLoopMiddleware, wrap_tool_call
  • TypeScript:import { humanInTheLoopMiddleware, createMiddleware } from "langchain"

关键模式:

  • HITL:middleware=[HumanInTheLoopMiddleware(interrupt_on={"dangerous_tool": True})],需要 checkpointer 与 thread_id。
  • 中断后恢复:agent.invoke(Command(resume={"decisions": [{"type": "approve"}]}), config=config)。
  • 自定义中间件:@wrap_tool_call 装饰器(Python)或 createMiddleware({ wrapToolCall: ... })(TypeScript)。

4. 结构化输出

可通过 response_format 或 with_structured_output() 获取带类型、经过校验的响应。

  • 方式一:智能体结构化输出,create_agent(model="gpt-4.1", tools=[search], response_format=ContactInfo),结果读取 result["structured_response"]。
  • 方式二:模型级结构化输出(无需智能体),model.with_structured_output(ContactInfo)。

Python 使用 Pydantic 的 BaseModel 与 Field 定义结构;TypeScript 使用 zod 定义结构,并调用 model.withStructuredOutput(ContactInfo)。

5. 模型配置

create_agent 接受模型字符串(如 "anthropic:claude-sonnet-4-5"、"openai:gpt-4.1")或模型实例以进行自定义设置,例如 ChatAnthropic(model="claude-sonnet-4-5", temperature=0)。

使用方式与常见错误对照

资料给出了多组错误与正确写法对照:

  • 工具描述:应清晰具体并包含 Args 说明,避免模糊描述。
  • 状态持久化:需添加 checkpointer 与 thread_id,否则智能体在多次调用之间会遗忘信息。
  • 迭代限制:应在 config 中设置 recursion_limit(Python)/ recursionLimit(TypeScript),避免无限循环。
  • 结果读取:应从结果字典/对象中读取 messages,而非直接访问 result.content。

适用场景

适用于需要构建 LangChain 智能体、定义工具、实现人工审批与错误处理、获取结构化输出,以及需要跨调用保持会话状态的开发场景。

限制

资料未提供该技能的安装命令、收费方式、平台支持范围或性能效果等信息,暂未提供。