如何在LangGraph工作流的节点中为LangChain模型集成web_search_preview工具
如何在LangGraph工作流的节点中为LangChain模型集成web_search_preview工具
我明白你遇到的问题——直接用OpenAI客户端调用web_search_preview完全正常,但把它集成到LangGraph的LangChain模型节点里就没反应了。咱们一步步拆解问题,搞定这个集成:
1. 先纠正模型工具绑定的错误
你之前尝试用model.bind_tools()但没保存返回的新模型实例,这是关键问题!LangChain的bind_tools()是返回一个带工具的新模型对象,不会修改原模型。所以正确的绑定方式应该是:
from langchain_openai import ChatOpenAI # 初始化基础模型 model = ChatOpenAI( model="gpt-4.1", temperature=0.3 ) # 绑定web_search_preview工具,保存为新的模型实例 model_with_tools = model.bind_tools(tools=[{"type": "web_search_preview"}])
2. 在LangGraph节点中使用带工具的模型
接下来修改你的conversation节点,使用这个绑定了工具的模型。另外要注意:模型返回的可能是工具调用请求,而不是直接的自然语言回复,所以你需要在工作流里处理这个调用逻辑——要么在节点内直接执行工具,要么在LangGraph里加分支让工具执行节点处理。
先看节点内的基础修改:
def conversation(state: AssistanceState) -> AssistanceState: user_profile = state.get("user_profile", {}) system_content = f""" Eres un asistente culinario experto... {user_profile} """ messages = [SystemMessage(content=system_content)] + state["messages"] # 使用绑定了工具的模型调用 response = model_with_tools.invoke(messages) return {"messages": [response]}
3. 处理工具调用的完整LangGraph工作流
现在模型会在需要的时候返回工具调用请求,但你需要让LangGraph实际执行这个调用并把结果喂回模型。这时候要做两件事:
- 定义一个工具执行节点
- 在图中添加分支逻辑,判断是否需要执行工具
第一步:定义工具执行节点
因为web_search_preview是OpenAI的内置工具,你可以直接用OpenAI客户端处理(和你之前的search_web_openai逻辑类似):
from langchain_core.messages import ToolMessage from langchain_openai import OpenAI # 执行web_search_preview工具的节点 def execute_web_search(state: AssistanceState) -> AssistanceState: # 提取模型返回的工具调用请求 last_msg = state["messages"][-1] tool_call = last_msg.tool_calls[0] query = tool_call["function"]["arguments"]["query"] # 调用OpenAI客户端执行搜索 client = OpenAI() search_response = client.responses.create( model="gpt-4.1", tools=[{"type": "web_search_preview"}], input=query ) # 把搜索结果包装成工具返回消息,添加到对话历史 tool_result = ToolMessage( content=str(search_response), tool_call_id=tool_call["id"] ) return {"messages": [tool_result]}
第二步:添加分支逻辑和构建完整的图
你需要一个判断函数,来决定下一步是执行工具还是直接结束对话:
from langgraph.graph import StateGraph, START, END # 判断是否需要执行工具 def should_call_tool(state: AssistanceState) -> str: last_message = state["messages"][-1] if hasattr(last_message, "tool_calls") and last_message.tool_calls: return "execute_tool" return END # 构建状态图 graph_builder = StateGraph(AssistanceState) # 添加节点 graph_builder.add_node("conversation", conversation) graph_builder.add_node("execute_tool", execute_web_search) # 添加边 graph_builder.add_edge(START, "conversation") graph_builder.add_conditional_edges( "conversation", should_call_tool, {"execute_tool": "execute_tool", END: END} ) graph_builder.add_edge("execute_tool", "conversation") # 初始化内存 memory = MemorySaver() graph = graph_builder.compile(checkpointer=memory)
关键注意点
- 绑定工具必须保存新实例:
bind_tools不会修改原模型,一定要用返回的新模型调用invoke - 处理工具调用循环:LangGraph需要知道什么时候执行工具,执行完后要把结果传回对话节点让模型继续生成回复
- 环境验证:确保你的LangChain、LangGraph和OpenAI SDK都是最新版本,避免兼容性问题
现在你可以测试这个工作流,模型会在需要的时候自动调用web_search_preview工具,执行后把结果整合到回复里。
内容来源于stack exchange
相关产品推荐
相关产品推荐

