工作流与智能体的编排模式及工具运行时状态访问
资料对比了工作流与智能体两种编排方式,并介绍提示链、并行化、编排者-工作者三种模式,以及工具如何通过ToolRuntime读取状态与上下文。
本指南审查共同的工作流程和代理模式。 - 工作流有预先设定的代码路径,并被设计为按一定顺序运行. - 代理是动态的,定义了自己的流程和工具使用.  LangGraph在构建代理和工作流程时提供一些好处,包括: [持久性](<https://docs.langchain.com/oss/python/langgraph/persistence>), [流线](<https://docs.langchain.com/oss/python/langgraph/streaming>),并支持调试以及 [部署](<https://docs.langchain.com/oss/python/langgraph/deploy>). 追踪和比较这些工作流程模式 [LangSmith](<https://smith.langchain.com/?utm_source=docs&utm_medium=cta&utm_campaign=langsmith-signup&utm_content=oss-langgraph-workflows-agents>)。跟踪 [追踪快速启动](<https://docs.langchain.com/langsmith/trace-with-langgraph>) 来查看数据如何通过每个步骤。我们建议您也设置 [LangSmith 引擎](<https://docs.langchain.com/langsmith/engine>) 用来监测你的踪迹 发现问题 并提出解决方案 ## 设置 要构建工作流程或代理,您可以使用 [任何聊天模式](<https://docs.langchain.com/oss/python/integrations/chat>) 支持结构化输出和工具调用。以下示例使用Anthropic: 1. 安装依赖性 : ``` pip install langchain_core langchain-anthropic langgraph ``` 2. 初始化 LLM : ``` import os import getpass from langchain_anthropic import ChatAnthropic def _set_env(var: str): if not os.environ.get(var): os.environ[var] = getpass.getpass(f"{var}: ") _set_env("ANTHROPIC_API_KEY") llm = ChatAnthropic(model="claude-sonnet-4-6") ``` ## 有限责任和扩充 工作流程和代理系统以LLMs为基础,并添加各种增强功能. [工具调用](<https://docs.langchain.com/oss/python/langchain/tools>), [结构化产出](<https://docs.langchain.com/oss/python/langchain/structured-output>),以及 [短期内存](<https://docs.langchain.com/oss/python/langchain/short-term-memory>) 是一些适合您需要的 LLMS 的选项 。  ``` # Schema for structured output from pydantic import BaseModel, Field class SearchQuery(BaseModel): search_query: str | None = Field( default=None, description="Query that is optimized web search." ) justification: str | None = Field( default=None, description="Why this query is relevant to the user's request." ) # Augment the LLM with schema for structured output structured_llm = llm.with_structured_output(SearchQuery) # Invoke the augmented LLM output = structured_llm.invoke("How does Calcium CT score relate to high cholesterol?") print(output) # The model returns an instance of SearchQuery. # Define a tool def multiply(a: int, b: int) -> int: return a * b # Augment the LLM with tools llm_with_tools = llm.bind_tools([multiply]) # Invoke the LLM with input that triggers the tool call msg = llm_with_tools.invoke("What is 2 times 3?") print(msg.tool_calls) # The model returns a request to call the tool. ``` ## 快速链条 快速链化是指每次LLM呼叫都会处理前一次呼叫的输出。它常用于执行定义明确的任务,这些任务可以细分为较小的,可核查的步骤。一些例子包括: - 将文件翻译成不同的语言 - 验证生成的内容是否一致  ``` from typing_extensions import TypedDict from langgraph.graph import StateGraph, START, END from IPython.display import Image, display # Graph state class State(TypedDict): topic: str joke: str improved_joke: str final_joke: str # Nodes def generate_joke(state: State): """First LLM call to generate initial joke""" msg = llm.invoke(f"Write a short joke about {state['topic']}") return {"joke": msg.content} def check_punchline(state: State): """Gate function to check if the joke has a punchline""" # Simple check - does the joke contain "?" or "!" if "?" in state["joke"] or "!" in state["joke"]: return "Pass" return "Fail" def improve_joke(state: State): """Second LLM call to improve the joke""" msg = llm.invoke(f"Make this joke funnier by adding wordplay: {state['joke']}") return {"improved_joke": msg.content} def polish_joke(state: State): """Third LLM call for final polish""" msg = llm.invoke(f"Add a surprising twist to this joke: {state['improved_joke']}") return {"final_joke": msg.content} # Build workflow workflow = StateGraph(State) # Add nodes workflow.add_node("generate_joke", generate_joke) workflow.add_node("improve_joke", improve_joke) workflow.add_node("polish_joke", polish_joke) # Add edges to connect nodes workflow.add_edge(START, "generate_joke") workflow.add_conditional_edges( "generate_joke", check_punchline, {"Fail": "improve_joke", "Pass": END} ) workflow.add_edge("improve_joke", "polish_joke") workflow.add_edge("polish_joke", END) # Compile chain = workflow.compile() # Show workflow display(Image(chain.get_graph().draw_mermaid_png())) # Invoke state = chain.invoke({"topic": "cats"}) print("Initial joke:") print(state["joke"]) print("\n--- --- ---\n") if "improved_joke" in state: print("Improved joke:") print(state["improved_joke"]) print("\n--- --- ---\n") print("Final joke:") print(state["final_joke"]) else: print("Final joke:") print(state["joke"]) ``` ## 平行化 并行化的同时, LLMs 也同时对任务进行工作。 这样做的方式有的是通过同时运行多个独立的子任务, 有的是通过多次运行相同的任务来检查不同的输出。 并行化通常用于: - 将子任务分开并平行运行,这样可以提高速度 - 多次运行任务以检查不同的输出, 从而增强信心 一些例子包括: - 运行一个处理关键字文档的子任务, 以及检查格式化错误的第二个子任务 - 根据不同标准,如引用次数、使用来源数量和来源质量,多次对文档进行精确度评分  ``` # Graph state class State(TypedDict): topic: str joke: str story: str poem: str combined_output: str # Nodes def call_llm_1(state: State): """First LLM call to generate initial joke""" msg = llm.invoke(f"Write a joke about {state['topic']}") return {"joke": msg.content} def call_llm_2(state: State): """Second LLM call to generate story""" msg = llm.invoke(f"Write a story about {state['topic']}") return {"story": msg.content} def call_llm_3(state: State): """Third LLM call to generate poem""" msg = llm.invoke(f"Write a poem about {state['topic']}") return {"poem": msg.content} def aggregator(state: State): """Combine the joke, story and poem into a single output""" combined = f"Here's a story, joke, and poem about {state['topic']}!\n\n" combined += f"STORY:\n{state['story']}\n\n" combined += f"JOKE:\n{state['joke']}\n\n" combined += f"POEM:\n{state['poem']}" return {"combined_output": combined} # Build workflow parallel_builder = StateGraph(State) # Add nodes parallel_builder.add_node("call_llm_1", call_llm_1) parallel_builder.add_node("call_llm_2", call_llm_2) parallel_builder.add_node("call_llm_3", call_llm_3) parallel_builder.add_node("aggregator", aggregator) # Add edges to connect nodes parallel_builder.add_edge(START, "call_llm_1") parallel_builder.add_edge(START, "call_llm_2") parallel_builder.add_edge(START, "call_llm_3") parallel_builder.add_edge("call_llm_1", "aggregator") parallel_builder.add_edge("call_llm_2", "aggregator") parallel_builder.add_edge("call_llm_3", "aggregator") parallel_builder.add_edge("aggregator", END) parallel_workflow = parallel_builder.compile() # Show workflow display(Image(parallel_workflow.get_graph().draw_mermaid_png())) # Invoke state = parallel_workflow.invoke({"topic": "cats"}) print(state["combined_output"]) ``` ## 运行 运行工作流程处理输入,然后引导它们执行特定环境的任务。这使得您可以定义复杂任务的专门流程。例如,为回答产品相关问题而构建的工作流程可能首先处理问题类型,然后将请求引导到定价、退款、回报等具体流程中。  ``` from typing_extensions import Literal from langchain.messages import HumanMessage, SystemMessage # Schema for structured output to use as routing logic class Route(BaseModel): step: Literal["poem", "story", "joke"] = Field( None, description="The next step in the routing process" ) # Augment the LLM with schema for structured output router = llm.with_structured_output(Route) # State class State(TypedDict): input: str decision: str output: str # Nodes def llm_call_1(state: State): """Write a story""" result = llm.invoke(state["input"]) return {"output": result.content} def llm_call_2(state: State): """Write a joke""" result = llm.invoke(state["input"]) return {"output": result.content} def llm_call_3(state: State): """Write a poem""" result = llm.invoke(state["input"]) return {"output": result.content} def llm_call_router(state: State): """Route the input to the appropriate node""" # Run the augmented LLM with structured output to serve as routing logic decision = router.invoke( [ SystemMessage( content="Route the input to story, joke, or poem based on the user's request." ), HumanMessage(content=state["input"]), ] ) return {"decision": decision.step} # Conditional edge function to route to the appropriate node def route_decision(state: State): # Return the node name you want to visit next if state["decision"] == "story": return "llm_call_1" elif state["decision"] == "joke": return "llm_call_2" elif state["decision"] == "poem": return "llm_call_3" # Build workflow router_builder = StateGraph(State) # Add nodes router_builder.add_node("llm_call_1", llm_call_1) router_builder.add_node("llm_call_2", llm_call_2) router_builder.add_node("llm_call_3", llm_call_3) router_builder.add_node("llm_call_router", llm_call_router) # Add edges to connect nodes router_builder.add_edge(START, "llm_call_router") router_builder.add_conditional_edges( "llm_call_router", route_decision, { # Name returned by route_decision : Name of next node to visit "llm_call_1": "llm_call_1", "llm_call_2": "llm_call_2", "llm_call_3": "llm_call_3", }, ) router_builder.add_edge("llm_call_1", END) router_builder.add_edge("llm_call_2", END) router_builder.add_edge("llm_call_3", END) # Compile workflow router_workflow = router_builder.compile() # Show the workflow display(Image(router_workflow.get_graph().draw_mermaid_png())) # Invoke state = router_workflow.invoke({"input": "Write me a joke about cats"}) print(state["output"]) ``` ## 兽医 -- -- 工人 在一个管弦乐-工作组合中,管弦乐: - 将任务细分为子任务 - 代表工人的分任务 - 将工人产出合成最终结果  Orchestrator-Worker工作流程提供了更大的灵活性,在子任务无法预先界定时经常被使用. [平行化](<https://docs.langchain.com/oss/python/langgraph/workflows-agents#parallelization>)。这与编写代码或需要更新多个文件内容的工作流程是常见的。例如,需要更新多个 Python 库的安装指令的工作流程可能会使用这种模式。 ``` from typing import Annotated, List import operator # Schema for structured output to use in planning class Section(BaseModel): name: str = Field( description="Name for this section of the report.", ) description: str = Field( description="Brief overview of the main topics and concepts to be covered in this section.", ) class Sections(BaseModel): sections: List[Section] = Field( description="Sections of the report.", ) # Augment the LLM with schema for structured output planner = llm.with_structured_output(Sections) ``` ### 在LangGraph中创造工人 Orchestrator-worker工作流程很常见,LangGraph对其有内置支持. The. `Send` API 允许您动态创建工人节点并发送特定输入。 每个工人都有自己的状态, 所有的工人输出都写入一个共享的状态密钥, 由管弦乐手图访问。 这使管弦乐手能够访问所有工人输出, 并可以将其合成最终输出。 下面的例子比起一个段落列表, 并使用 `Send` API向每个工人发送一节. ``` from langgraph.types import Send # Graph state class State(TypedDict): topic: str # Report topic sections: list[Section] # List of report sections completed_sections: Annotated[ list, operator.add ] # All workers write to this key in parallel final_report: str # Final report # Worker state class WorkerState(TypedDict): section: Section completed_sections: Annotated[list, operator.add] # Nodes def orchestrator(state: State): """Orchestrator that generates a plan for the report""" # Generate queries report_sections = planner.invoke( [ SystemMessage(content="Generate a plan for the report."), HumanMessage(content=f"Here is the report topic: {state['topic']}"), ] ) return {"sections": report_sections.sections} def llm_call(state: WorkerState): """Worker writes a section of the report""" # Generate section section = llm.invoke( [ SystemMessage( content="Write a report section following the provided name and description. Include no preamble for each section. Use markdown formatting." ), HumanMessage( content=f"Here is the section name: {state['section'].name} and description: {state['section'].description}" ), ] ) # Write the updated section to completed sections return {"completed_sections": [section.content]} def synthesizer(state: State): """Synthesize full report from sections""" # List of completed sections completed_sections = state["completed_sections"] # Format completed section to str to use as context for final sections completed_report_sections = "\n\n---\n\n".join(completed_sections) return {"final_report": completed_report_sections} # Conditional edge function to create llm_call workers that each write a section of the report def assign_workers(state: State): """Assign a worker to each section in the plan""" # Kick off section writing in parallel via Send() API return [Send("llm_call", {"section": s}) for s in state["sections"]] # Build workflow orchestrator_worker_builder = StateGraph(State) # Add the nodes orchestrator_worker_builder.add_node("orchestrator", orchestrator) orchestrator_worker_builder.add_node("llm_call", llm_call) orchestrator_worker_builder.add_node("synthesizer", synthesizer) # Add edges to connect nodes orchestrator_worker_builder.add_edge(START, "orchestrator") orchestrator_worker_builder.add_conditional_edges( "orchestrator", assign_workers, ["llm_call"] ) orchestrator_worker_builder.add_edge("llm_call", "synthesizer") orchestrator_worker_builder.add_edge("synthesizer", END) # Compile the workflow orchestrator_worker = orchestrator_worker_builder.compile() # Show the workflow display(Image(orchestrator_worker.get_graph().draw_mermaid_png())) # Invoke state = orchestrator_worker.invoke({"topic": "Create a report on LLM scaling laws"}) from IPython.display import Markdown Markdown(state["final_report"]) ``` ## 评价者-优化者 在评价-优化工作流程中,一个LLM呼叫生成一个响应,另一个则评价该响应。 [human-in-the-loop](<https://docs.langchain.com/oss/python/langgraph/interrupts>) 确定响应需要的精细化, 反馈和响应被重新创建。 这个循环一直持续到生成一个可接受的响应。 当任务有特定的成功标准时, 通常会使用评估员- 优化工作流程, 但需要重复来达到这个标准。 例如, 在两种语言之间翻译文本时并不总是完全匹配。可能需要一些迭代才能产生两种语言中具有相同含义的译文.  ``` # Graph state class State(TypedDict): joke: str topic: str feedback: str funny_or_not: str # Schema for structured output to use in evaluation class Feedback(BaseModel): grade: Literal["funny", "not funny"] = Field( description="Decide if the joke is funny or not.", ) feedback: str = Field( description="If the joke is not funny, provide feedback on how to improve it.", ) # Augment the LLM with schema for structured output evaluator = llm.with_structured_output(Feedback) # Nodes def llm_call_generator(state: State): """LLM generates a joke""" if state.get("feedback"): msg = llm.invoke( f"Write a joke about {state['topic']} but take into account the feedback: {state['feedback']}" ) else: msg = llm.invoke(f"Write a joke about {state['topic']}") return {"joke": msg.content} def llm_call_evaluator(state: State): """LLM evaluates the joke""" grade = evaluator.invoke(f"Grade the joke {state['joke']}") return {"funny_or_not": grade.grade, "feedback": grade.feedback} # Conditional edge function to route back to joke generator or end based upon feedback from the evaluator def route_joke(state: State): """Route back to joke generator or end based upon feedback from the evaluator""" if state["funny_or_not"] == "funny": return "Accepted" elif state["funny_or_not"] == "not funny": return "Rejected + Feedback" # Build workflow optimizer_builder = StateGraph(State) # Add the nodes optimizer_builder.add_node("llm_call_generator", llm_call_generator) optimizer_builder.add_node("llm_call_evaluator", llm_call_evaluator) # Add edges to connect nodes optimizer_builder.add_edge(START, "llm_call_generator") optimizer_builder.add_edge("llm_call_generator", "llm_call_evaluator") optimizer_builder.add_conditional_edges( "llm_call_evaluator", route_joke, { # Name returned by route_joke : Name of next node to visit "Accepted": END, "Rejected + Feedback": "llm_call_generator", }, ) # Compile the workflow optimizer_workflow = optimizer_builder.compile() # Show the workflow display(Image(optimizer_workflow.get_graph().draw_mermaid_png())) # Invoke state = optimizer_workflow.invoke({"topic": "Cats"}) print(state["joke"]) ``` ## 探员 代理通常作为LLM执行,使用 [工具](<https://docs.langchain.com/oss/python/langchain/tools>)。它们运行在连续的反馈循环中,并在问题和解决方案无法预测的情况下使用。代理比工作流程更具自主权,并且可以决定它们使用的工具和如何解决问题。您仍然可以定义可用的工具集和代理行为指南。  要从特工开始,看 [快速启动](<https://docs.langchain.com/oss/python/langchain/quickstart>) 或读更多关于 [他们的工作方式](<https://docs.langchain.com/oss/python/langchain/agents>) 在LangChain中 。 使用工具 ``` from langchain.tools import tool # Define tools @tool def multiply(a: int, b: int) -> int: """Multiply `a` and `b`. Args: a: First int b: Second int """ return a * b @tool def add(a: int, b: int) -> int: """Adds `a` and `b`. Args: a: First int b: Second int """ return a + b @tool def divide(a: int, b: int) -> float: """Divide `a` and `b`. Args: a: First int b: Second int """ return a / b # Augment the LLM with tools tools = [add, multiply, divide] tools_by_name = {tool.name: tool for tool in tools} llm_with_tools = llm.bind_tools(tools) ``` ``` from langgraph.graph import MessagesState from langchain.messages import SystemMessage, HumanMessage, ToolMessage # Nodes def llm_call(state: MessagesState): """LLM decides whether to call a tool or not""" return { "messages": [ llm_with_tools.invoke( [ SystemMessage( content="You are a helpful assistant tasked with performing arithmetic on a set of inputs." ) ] + state["messages"] ) ] } def tool_node(state: MessagesState): """Performs the tool call""" result = [] for tool_call in state["messages"][-1].tool_calls: tool = tools_by_name[tool_call["name"]] observation = tool.invoke(tool_call["args"]) result.append(ToolMessage(content=observation, tool_call_id=tool_call["id"])) return {"messages": result} # Conditional edge function to route to the tool node or end based upon whether the LLM made a tool call def should_continue(state: MessagesState) -> Literal["tool_node", END]: """Decide if we should continue the loop or stop based upon whether the LLM made a tool call""" messages = state["messages"] last_message = messages[-1] # If the LLM makes a tool call, then perform an action if last_message.tool_calls: return "tool_node" # Otherwise, we stop (reply to the user) return END # Build workflow agent_builder = StateGraph(MessagesState) # Add nodes agent_builder.add_node("llm_call", llm_call) agent_builder.add_node("tool_node", tool_node) # Add edges to connect nodes agent_builder.add_edge(START, "llm_call") agent_builder.add_conditional_edges( "llm_call", should_continue, ["tool_node", END] ) agent_builder.add_edge("tool_node", "llm_call") # Compile the agent agent = agent_builder.compile() # Show the agent display(Image(agent.get_graph(xray=True).draw_mermaid_png())) # Invoke messages = [HumanMessage(content="Add 3 and 4.")] messages = agent.invoke({"messages": messages}) for m in messages["messages"]: m.pretty_print() ``` ### ToolNode [`ToolNode`](<https://reference.langchain.com/python/langgraph/agents/#langgraph.prebuilt.tool_node.ToolNode>) 是一个在 LangGraph 工作流程中执行工具的预建节点。它处理并行的工具执行、错误处理和状态自动注入。使用 [`ToolNode`](<https://reference.langchain.com/python/langgraph/agents/#langgraph.prebuilt.tool_node.ToolNode>) 当您需要精细控制您的图形如何执行工具时。 这是许多 LangGraph 代理模式中赋予工具执行权力的构件 。 ``` from langchain.tools import tool from langgraph.prebuilt import ToolNode from langgraph.graph import MessagesState, StateGraph @tool def search(query: str) -> str: """Search for information.""" return f"Results for: {query}" @tool def calculator(expression: str) -> str: """Evaluate a math expression.""" return str(eval(expression)) builder = StateGraph(MessagesState) builder.add_node("tools", ToolNode([search, calculator])) # ... add other nodes and edges graph = builder.compile() ``` #### 从工具获取图表状态和上下文 工具执行 `ToolNode` 接收模型生成的参数作为其第一个参数。要读取模型未生成的图形侧面数据,请使用其中一种选项: - 在 Python 中,从注入的语境读取状态和运行范围 [`ToolRuntime`](<https://reference.langchain.com/python/langchain/tools/#langchain.tools.ToolRuntime>) 参数。 - 在 JavaScript 中,从工具的第二个参数读取状态和运行范围上下文,键入为 [`ToolRuntime`](<https://reference.langchain.com/python/langchain/tools/#langchain.tools.ToolRuntime>). 工具只能访问传递到您的状态值 `ToolNode`时 `ToolNode` 直接添加为 a `StateGraph` 节点,该输入是当前图形状态。如果引用 `ToolNode` 在工具需要自定义状态字段时, 手动从另一个节点传递完整状态 。 例如, `tool_node.invoke(state)` 或 时 间 `toolNode.invoke(state, config)` 暴露整个状态,而只经过 `{"messages": state["messages"]}` 或 时 间 `{ messages: state.messages }` 只会暴露 `messages`. ``` from dataclasses import dataclass from langchain.messages import AIMessage from langchain.tools import ToolRuntime, tool from langgraph.graph import MessagesState, START, StateGraph from langgraph.prebuilt import ToolNode class State(MessagesState): user_id: str @dataclass class Context: organization_id: str @tool def get_user_info(runtime: ToolRuntime[Context, State]) -> str: """Look up user information.""" # Read the current graph state passed to the ToolNode. user_id = runtime.state["user_id"] # Read explicit per-run values that are not part of graph state. organization_id = runtime.context.organization_id return f"User {user_id} in organization {organization_id}" builder = StateGraph(State, context_schema=Context) builder.add_node("tools", ToolNode([get_user_info])) builder.add_edge(START, "tools") graph = builder.compile() result = graph.invoke( { "messages": [ AIMessage( content="", tool_calls=[ { "name": "get_user_info", "args": {}, "id": "call_user_info", } ], ) ], "user_id": "user_123", }, context=Context(organization_id="org_456"), ) ``` ## 查看示例跟踪 为这个例子打开一个公开的 LangSmith 运行. --- [连接这些文件](<https://docs.langchain.com/use-these-docs>) 通过 MCP 向您选择的代理提供实时答案。 [在 GitHub 上编辑此页面](<https://github.com/langchain-ai/docs/edit/main/src/oss/langgraph/workflows-agents.mdx>) 或 时 间 [提交一个问题](<https://github.com/langchain-ai/docs/issues/new/choose>). 这页有用吗?
查看原始来源