workflow_Agent.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from langgraph.graph import StateGraph , START , END
  2. from langgraph.prebuilt import ToolNode, tools_condition
  3. from Agents import AgentState , agent_analyseur , agent_executor , tools , agent_reporter
  4. from langchain_core.messages import AIMessage , ToolMessage
  5. # 1. Initialisation du graphe avec l'état personnalisé
  6. workflow = StateGraph(AgentState)
  7. # 2. Ajout des nœuds
  8. workflow.add_node("analyseur", agent_analyseur)
  9. workflow.add_node("executor", agent_executor)
  10. workflow.add_node("reporter", agent_reporter)
  11. workflow.add_node("tools", ToolNode(tools))
  12. # 3. Définition des arêtes stables
  13. workflow.add_edge(START, "analyseur")
  14. workflow.add_edge("analyseur", "executor")
  15. workflow.add_edge("reporter", END)
  16. # 4. Logique de routage personnalisée
  17. def router(state: AgentState):
  18. messages = state["messages"]
  19. last_message = messages[-1]
  20. # CAS 1 : L'agent demande un outil
  21. if hasattr(last_message, "tool_calls") and last_message.tool_calls:
  22. return "tools"
  23. # CAS 2 : Analyse du retour de l'outil
  24. if isinstance(last_message, ToolMessage):
  25. content_upper = last_message.content.upper()
  26. # On détecte ton marqueur spécifique ou le mot "ERROR"
  27. if "ERREUR PYTHON" in content_upper or "ERROR" in content_upper:
  28. print("--- LOG : Erreur détectée, renvoi à l'exécuteur pour correction ---")
  29. return "executor"
  30. # Si pas d'erreur, on peut passer à la synthèse
  31. return "reporter"
  32. # CAS 3 : Par défaut
  33. return "reporter"
  34. # On applique la condition sur l'executor
  35. workflow.add_conditional_edges(
  36. "executor",
  37. router,
  38. {"tools": "tools", "reporter": "reporter"}
  39. )
  40. workflow.add_conditional_edges(
  41. "tools" ,
  42. router ,
  43. {"executor": "executor", "reporter": "reporter"}
  44. )
  45. # 5. Compilation
  46. app = workflow.compile()
  47. # Pour sauvegarder l'image du workflow
  48. with open("graph_workflow.png", "wb") as f:
  49. f.write(app.get_graph().draw_mermaid_png())
  50. print("Graphique du workflow généré sous : graph_workflow.png")