使用 LangChain 设计 Agentic 系统
Dilini K. Sumanapala, PhD
Founder & AI Engineer, Genverv, Ltd.







from langgraph.graph import MessagesState, START, END# 使用 MessagesState 定义停止函数的状态 def should_continue(state: MessagesState):# 从状态中获取最后一条消息 last_message = state["messages"][-1]# 检查最后一条消息是否包含工具调用 if last_message.tool_calls: return "tools"# 若无工具调用则结束对话 return END
# 从历史中取出最后一条消息 def call_model(state: MessagesState):last_message = state["messages"][-1]# 若最后一条消息含工具调用,则返回工具的响应 if isinstance(last_message, AIMessage) and last_message.tool_calls:# 返回工具调用产生的消息 return {"messages": [AIMessage(content=last_message.tool_calls[0]["response"])]}# 否则,走常规 LLM 响应 return {"messages": [model_with_tools.invoke(state["messages"])]}
workflow = StateGraph(MessagesState)
workflow = StateGraph(MessagesState)# 为聊天机器人和工具添加节点 workflow.add_node("chatbot", call_model) workflow.add_node("tools", tool_node)

workflow = StateGraph(MessagesState)# 为聊天机器人和工具添加节点 workflow.add_node("chatbot", call_model) workflow.add_node("tools", tool_node)# 将 START 节点连接到聊天机器人 workflow.add_edge(START, "chatbot")

workflow = StateGraph(MessagesState)# 为聊天机器人和工具添加节点 workflow.add_node("chatbot", call_model) workflow.add_node("tools", tool_node)# 将 START 节点连接到聊天机器人 workflow.add_edge(START, "chatbot")# 定义条件,然后回到聊天机器人 workflow.add_conditional_edges("chatbot", should_continue, ["tools", END])

workflow = StateGraph(MessagesState)# 为聊天机器人和工具添加节点 workflow.add_node("chatbot", call_model) workflow.add_node("tools", tool_node)# 将 START 节点连接到聊天机器人 workflow.add_edge(START, "chatbot")# 定义条件,然后回到聊天机器人 workflow.add_conditional_edges("chatbot", should_continue, ["tools", END])workflow.add_edge("tools", "chatbot")

# 设置内存并编译工作流 memory = MemorySaver()app = workflow.compile( checkpointer=memory)display(Image(app.get_graph() .draw_mermaid_png()))
使用 LangChain 设计 Agentic 系统