Thiết kế Hệ thống Agentic với LangChain
Dilini K. Sumanapala, PhD
Founder & AI Engineer, Genverv, Ltd.







from langgraph.graph import MessagesState, START, END# Dùng MessagesState để định nghĩa trạng thái của hàm dừng def should_continue(state: MessagesState):# Lấy tin nhắn cuối từ trạng thái last_message = state["messages"][-1]# Kiểm tra tin nhắn cuối có chứa lệnh gọi công cụ không if last_message.tool_calls: return "tools"# Kết thúc hội thoại nếu không có lệnh gọi công cụ return END
# Trích xuất tin nhắn cuối từ lịch sử def call_model(state: MessagesState):last_message = state["messages"][-1]# Nếu tin nhắn cuối có lệnh gọi công cụ, trả về phản hồi của công cụ if isinstance(last_message, AIMessage) and last_message.tool_calls:# Trả về các tin nhắn từ lệnh gọi công cụ return {"messages": [AIMessage(content=last_message.tool_calls[0]["response"])]}# Ngược lại, tiếp tục với phản hồi LLM thông thường return {"messages": [model_with_tools.invoke(state["messages"])]}
workflow = StateGraph(MessagesState)
workflow = StateGraph(MessagesState)# Thêm node cho chatbot và công cụ workflow.add_node("chatbot", call_model) workflow.add_node("tools", tool_node)

workflow = StateGraph(MessagesState)# Thêm node cho chatbot và công cụ workflow.add_node("chatbot", call_model) workflow.add_node("tools", tool_node)# Nối node START với chatbot workflow.add_edge(START, "chatbot")

workflow = StateGraph(MessagesState)# Thêm node cho chatbot và công cụ workflow.add_node("chatbot", call_model) workflow.add_node("tools", tool_node)# Nối node START với chatbot workflow.add_edge(START, "chatbot")# Xác định điều kiện, rồi lặp về chatbot workflow.add_conditional_edges("chatbot", should_continue, ["tools", END])

workflow = StateGraph(MessagesState)# Thêm node cho chatbot và công cụ workflow.add_node("chatbot", call_model) workflow.add_node("tools", tool_node)# Nối node START với chatbot workflow.add_edge(START, "chatbot")# Xác định điều kiện, rồi lặp về chatbot workflow.add_conditional_edges("chatbot", should_continue, ["tools", END])workflow.add_edge("tools", "chatbot")

# Thiết lập bộ nhớ và biên dịch quy trình memory = MemorySaver()app = workflow.compile( checkpointer=memory)display(Image(app.get_graph() .draw_mermaid_png()))
Thiết kế Hệ thống Agentic với LangChain