Diseño de sistemas agénticos con LangChain
Dilini K. Sumanapala, PhD
Founder & AI Engineer, Genverv, Ltd.







from langgraph.graph import MessagesState, START, END# Usa MessagesState para definir el estado de la función de parada def should_continue(state: MessagesState):# Obtén el último mensaje del estado last_message = state["messages"][-1]# Comprueba si el último mensaje incluye llamadas a herramientas if last_message.tool_calls: return "tools"# Termina la conversación si no hay llamadas a herramientas return END
# Extrae el último mensaje del historial def call_model(state: MessagesState):last_message = state["messages"][-1]# Si el último mensaje tiene llamadas a herramientas, devuelve la respuesta de la herramienta if isinstance(last_message, AIMessage) and last_message.tool_calls:# Devuelve los mensajes de la llamada a la herramienta return {"messages": [AIMessage(content=last_message.tool_calls[0]["response"])]}# En caso contrario, continúa con una respuesta normal del LLM return {"messages": [model_with_tools.invoke(state["messages"])]}
workflow = StateGraph(MessagesState)
workflow = StateGraph(MessagesState)# Añade nodos para el chatbot y las herramientas workflow.add_node("chatbot", call_model) workflow.add_node("tools", tool_node)

workflow = StateGraph(MessagesState)# Añade nodos para el chatbot y las herramientas workflow.add_node("chatbot", call_model) workflow.add_node("tools", tool_node)# Conecta el nodo START con el chatbot workflow.add_edge(START, "chatbot")

workflow = StateGraph(MessagesState)# Añade nodos para el chatbot y las herramientas workflow.add_node("chatbot", call_model) workflow.add_node("tools", tool_node)# Conecta el nodo START con el chatbot workflow.add_edge(START, "chatbot")# Define condiciones y vuelve al chatbot workflow.add_conditional_edges("chatbot", should_continue, ["tools", END])

workflow = StateGraph(MessagesState)# Añade nodos para el chatbot y las herramientas workflow.add_node("chatbot", call_model) workflow.add_node("tools", tool_node)# Conecta el nodo START con el chatbot workflow.add_edge(START, "chatbot")# Define condiciones y vuelve al chatbot workflow.add_conditional_edges("chatbot", should_continue, ["tools", END])workflow.add_edge("tools", "chatbot")

# Configura la memoria y compila el flujo memory = MemorySaver()app = workflow.compile( checkpointer=memory)display(Image(app.get_graph() .draw_mermaid_png()))
Diseño de sistemas agénticos con LangChain