Designing Agentic Systems with LangChain
Dilini K. Sumanapala, PhD
Founder & AI Engineer, Genverv, Ltd.







from langgraph.graph import MessagesState, START, END# Use MessagesState to define the state of the stopping function def should_continue(state: MessagesState):# Get the last message from the state last_message = state["messages"][-1]# Check if the last message includes tool calls if last_message.tool_calls: return "tools"# End the conversation if no tool calls are present return END
# Extract the last message from the history def call_model(state: MessagesState):last_message = state["messages"][-1]# If the last message has tool calls, return the tool's response if isinstance(last_message, AIMessage) and last_message.tool_calls:# Return the messages from the tool call return {"messages": [AIMessage(content=last_message.tool_calls[0]["response"])]}# Otherwise, proceed with a regular LLM response return {"messages": [model_with_tools.invoke(state["messages"])]}
workflow = StateGraph(MessagesState)
workflow = StateGraph(MessagesState)# Add nodes for chatbot and tools workflow.add_node("chatbot", call_model) workflow.add_node("tools", tool_node)

workflow = StateGraph(MessagesState)# Add nodes for chatbot and tools workflow.add_node("chatbot", call_model) workflow.add_node("tools", tool_node)# Connect the START node to the chatbot workflow.add_edge(START, "chatbot")

workflow = StateGraph(MessagesState)# Add nodes for chatbot and tools workflow.add_node("chatbot", call_model) workflow.add_node("tools", tool_node)# Connect the START node to the chatbot workflow.add_edge(START, "chatbot")# Define conditions, then loop back to chatbot workflow.add_conditional_edges("chatbot", should_continue, ["tools", END])

workflow = StateGraph(MessagesState)# Add nodes for chatbot and tools workflow.add_node("chatbot", call_model) workflow.add_node("tools", tool_node)# Connect the START node to the chatbot workflow.add_edge(START, "chatbot")# Define conditions, then loop back to chatbot workflow.add_conditional_edges("chatbot", should_continue, ["tools", END])workflow.add_edge("tools", "chatbot")

# Set up memory and compile the workflow memory = MemorySaver()app = workflow.compile( checkpointer=memory)display(Image(app.get_graph() .draw_mermaid_png()))
Designing Agentic Systems with LangChain