Frazer2810 commited on
Commit
aea7869
·
verified ·
1 Parent(s): fc6592e

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +23 -19
agent.py CHANGED
@@ -1,6 +1,7 @@
1
- """LangGraph Agent – retry 5s, 30s, 60s; senza Supabase"""
2
 
3
- import os, time
 
4
  from dotenv import load_dotenv
5
  from langgraph.graph import START, StateGraph, MessagesState
6
  from langgraph.prebuilt import ToolNode, tools_condition
@@ -93,28 +94,28 @@ tools = [
93
  # --------------------------------------------------------------------------- #
94
  # Retry parameters #
95
  # --------------------------------------------------------------------------- #
96
- RETRY_DELAYS = [0, 5, 30, 60] # secondi: tentativo 0, 1, 2, 3
97
  MAX_ATTEMPTS = len(RETRY_DELAYS)
98
 
99
  # --------------------------------------------------------------------------- #
100
  # Build LangGraph #
101
  # --------------------------------------------------------------------------- #
102
  def build_graph(provider: str = "groq"):
103
- """Return a LangGraph graph with explicit retry logic (5s, 30s, 60s)."""
104
 
105
  # ----------- LLM selection -------------------------------------------- #
106
  if provider == "google":
107
- llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)
108
 
109
  elif provider == "groq":
110
- llm = ChatGroq(
111
  model="qwen-qwq-32b",
112
  temperature=0,
113
- max_retries=0, # disabilitiamo i retry interni
114
  )
115
 
116
  elif provider == "huggingface":
117
- llm = ChatHuggingFace(
118
  llm=HuggingFaceEndpoint(
119
  url="https://api-inference.huggingface.co/models/Meta-DeepLearning/llama-2-7b-chat-hf",
120
  temperature=0,
@@ -123,13 +124,13 @@ def build_graph(provider: str = "groq"):
123
  else:
124
  raise ValueError("Invalid provider. Choose 'google', 'groq' or 'huggingface'.")
125
 
126
- llm_with_tools = llm.bind_tools(tools)
127
 
128
  # ---------------- Retry wrapper -------------------------------------- #
129
  def invoke_with_retry(messages):
130
  last_err = None
131
  for attempt, delay in enumerate(RETRY_DELAYS):
132
- if delay > 0:
133
  print(f"[Retry {attempt}/{MAX_ATTEMPTS-1}] waiting {delay}s")
134
  time.sleep(delay)
135
  try:
@@ -138,9 +139,8 @@ def build_graph(provider: str = "groq"):
138
  err_text = str(e)
139
  if ("503" in err_text or "Service Unavailable" in err_text) and attempt < MAX_ATTEMPTS - 1:
140
  last_err = e
141
- continue # passa al prossimo tentativo
142
- raise # altro errore o ultimi tentativo esaurito
143
- # se per qualche motivo esce dal loop senza raise
144
  raise last_err or RuntimeError("Unknown error during LLM invocation")
145
 
146
  # ---------------- Nodes ---------------------------------------------- #
@@ -159,13 +159,17 @@ def build_graph(provider: str = "groq"):
159
 
160
  return builder.compile()
161
 
 
162
  # --------------------------------------------------------------------------- #
163
- # Test rapido #
164
  # --------------------------------------------------------------------------- #
165
  if __name__ == "__main__":
166
- g = build_graph(provider="groq")
167
- q = "When was a picture of St. Thomas Aquinas first added to the Wikipedia page on the Principle of double effect?"
168
- msgs = [HumanMessage(content=q)]
169
- res = g.invoke({"messages": msgs})
170
- for m in res["messages"]:
 
 
 
171
  m.pretty_print()
 
1
+ """LangGraph Agent – retry 5s, 30s, 60s; senza Supabase (fix ‘ll’)."""
2
 
3
+ import os
4
+ import time
5
  from dotenv import load_dotenv
6
  from langgraph.graph import START, StateGraph, MessagesState
7
  from langgraph.prebuilt import ToolNode, tools_condition
 
94
  # --------------------------------------------------------------------------- #
95
  # Retry parameters #
96
  # --------------------------------------------------------------------------- #
97
+ RETRY_DELAYS = [0, 5, 30, 60] # 4 tentativi complessivi
98
  MAX_ATTEMPTS = len(RETRY_DELAYS)
99
 
100
  # --------------------------------------------------------------------------- #
101
  # Build LangGraph #
102
  # --------------------------------------------------------------------------- #
103
  def build_graph(provider: str = "groq"):
104
+ """Return a LangGraph graph with custom retry logic."""
105
 
106
  # ----------- LLM selection -------------------------------------------- #
107
  if provider == "google":
108
+ llm_selected = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)
109
 
110
  elif provider == "groq":
111
+ llm_selected = ChatGroq(
112
  model="qwen-qwq-32b",
113
  temperature=0,
114
+ max_retries=0, # gestiamo noi i retry
115
  )
116
 
117
  elif provider == "huggingface":
118
+ llm_selected = ChatHuggingFace(
119
  llm=HuggingFaceEndpoint(
120
  url="https://api-inference.huggingface.co/models/Meta-DeepLearning/llama-2-7b-chat-hf",
121
  temperature=0,
 
124
  else:
125
  raise ValueError("Invalid provider. Choose 'google', 'groq' or 'huggingface'.")
126
 
127
+ llm_with_tools = llm_selected.bind_tools(tools)
128
 
129
  # ---------------- Retry wrapper -------------------------------------- #
130
  def invoke_with_retry(messages):
131
  last_err = None
132
  for attempt, delay in enumerate(RETRY_DELAYS):
133
+ if delay:
134
  print(f"[Retry {attempt}/{MAX_ATTEMPTS-1}] waiting {delay}s")
135
  time.sleep(delay)
136
  try:
 
139
  err_text = str(e)
140
  if ("503" in err_text or "Service Unavailable" in err_text) and attempt < MAX_ATTEMPTS - 1:
141
  last_err = e
142
+ continue # retry
143
+ raise # altro errore o tentativi finiti
 
144
  raise last_err or RuntimeError("Unknown error during LLM invocation")
145
 
146
  # ---------------- Nodes ---------------------------------------------- #
 
159
 
160
  return builder.compile()
161
 
162
+
163
  # --------------------------------------------------------------------------- #
164
+ # Stand-alone test #
165
  # --------------------------------------------------------------------------- #
166
  if __name__ == "__main__":
167
+ graph = build_graph(provider="groq")
168
+ question = (
169
+ "When was a picture of St. Thomas Aquinas first added to the Wikipedia "
170
+ "page on the Principle of double effect?"
171
+ )
172
+ msgs = [HumanMessage(content=question)]
173
+ result = graph.invoke({"messages": msgs})
174
+ for m in result["messages"]:
175
  m.pretty_print()