Frazer2810 commited on
Commit
a074039
·
verified ·
1 Parent(s): 9dc857d

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +18 -79
agent.py CHANGED
@@ -1,6 +1,6 @@
1
- """LangGraph Agent – versione senza Supabase"""
2
 
3
- import os
4
  from dotenv import load_dotenv
5
  from langgraph.graph import START, StateGraph, MessagesState
6
  from langgraph.prebuilt import ToolNode, tools_condition
@@ -8,10 +8,7 @@ from langgraph.prebuilt import ToolNode, tools_condition
8
  # LLM providers
9
  from langchain_google_genai import ChatGoogleGenerativeAI
10
  from langchain_groq import ChatGroq
11
- from langchain_huggingface import (
12
- ChatHuggingFace,
13
- HuggingFaceEndpoint,
14
- )
15
 
16
  # Tools & loaders
17
  from langchain_community.tools.tavily_search import TavilySearchResults
@@ -19,29 +16,26 @@ from langchain_community.document_loaders import WikipediaLoader, ArxivLoader
19
  from langchain_core.messages import SystemMessage, HumanMessage
20
  from langchain_core.tools import tool
21
 
22
- load_dotenv() # carica eventuali variabili dal file .env
23
 
24
  # --------------------------------------------------------------------------- #
25
- # TOOL: operazioni aritmetiche #
26
  # --------------------------------------------------------------------------- #
27
  @tool
28
  def multiply(a: int, b: int) -> int:
29
  """Multiply two integers and return the product."""
30
  return a * b
31
 
32
-
33
  @tool
34
  def add(a: int, b: int) -> int:
35
  """Add two integers and return the sum."""
36
  return a + b
37
 
38
-
39
  @tool
40
  def subtract(a: int, b: int) -> int:
41
  """Subtract the second integer from the first and return the difference."""
42
  return a - b
43
 
44
-
45
  @tool
46
  def divide(a: int, b: int) -> float:
47
  """Divide a by b and return the quotient (error if b == 0)."""
@@ -49,16 +43,11 @@ def divide(a: int, b: int) -> float:
49
  raise ValueError("Cannot divide by zero.")
50
  return a / b
51
 
52
-
53
  @tool
54
  def modulus(a: int, b: int) -> int:
55
  """Return the remainder of the division of a by b."""
56
  return a % b
57
 
58
-
59
- # --------------------------------------------------------------------------- #
60
- # TOOL: Wikipedia #
61
- # --------------------------------------------------------------------------- #
62
  @tool
63
  def wiki_search(query: str) -> str:
64
  """Search Wikipedia (max 2 docs) and return formatted content."""
@@ -69,10 +58,6 @@ def wiki_search(query: str) -> str:
69
  for d in docs
70
  )
71
 
72
-
73
- # --------------------------------------------------------------------------- #
74
- # TOOL: Tavily web search #
75
- # --------------------------------------------------------------------------- #
76
  @tool
77
  def web_search(query: str) -> str:
78
  """Perform a web search with Tavily (max 3 docs) and return formatted content."""
@@ -83,10 +68,6 @@ def web_search(query: str) -> str:
83
  for d in docs
84
  )
85
 
86
-
87
- # --------------------------------------------------------------------------- #
88
- # TOOL: ArXiv #
89
- # --------------------------------------------------------------------------- #
90
  @tool
91
  def arxiv_search(query: str) -> str:
92
  """Search ArXiv (max 3 docs) and return first 1000 characters per paper."""
@@ -97,7 +78,6 @@ def arxiv_search(query: str) -> str:
97
  for d in docs
98
  )
99
 
100
-
101
  # --------------------------------------------------------------------------- #
102
  # System prompt #
103
  # --------------------------------------------------------------------------- #
@@ -105,67 +85,26 @@ with open("system_prompt.txt", "r", encoding="utf-8") as f:
105
  system_prompt = f.read()
106
  sys_msg = SystemMessage(content=system_prompt)
107
 
108
- # --------------------------------------------------------------------------- #
109
- # Lista tool #
110
- # --------------------------------------------------------------------------- #
111
  tools = [
112
- multiply,
113
- add,
114
- subtract,
115
- divide,
116
- modulus,
117
- wiki_search,
118
- web_search,
119
- arxiv_search,
120
  ]
121
 
 
 
 
 
 
 
122
  # --------------------------------------------------------------------------- #
123
  # Build LangGraph #
124
  # --------------------------------------------------------------------------- #
125
  def build_graph(provider: str = "groq"):
126
- """Return a LangGraph graph without Supabase dependencies."""
127
- # ------------ LLM selection ------------------------------------------- #
 
128
  if provider == "google":
129
  llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)
130
- elif provider == "groq":
131
- llm = ChatGroq(model="qwen-qwq-32b", temperature=0)
132
- elif provider == "huggingface":
133
- llm = ChatHuggingFace(
134
- llm=HuggingFaceEndpoint(
135
- url="https://api-inference.huggingface.co/models/Meta-DeepLearning/llama-2-7b-chat-hf",
136
- temperature=0,
137
- )
138
- )
139
- else:
140
- raise ValueError("Invalid provider. Choose 'google', 'groq' or 'huggingface'.")
141
-
142
- llm_with_tools = llm.bind_tools(tools)
143
-
144
- # ------------------ Nodes -------------------------------------------- #
145
- def assistant(state: MessagesState):
146
- """Invoke LLM with system prompt prepended."""
147
- messages = [sys_msg] + state["messages"]
148
- return {"messages": [llm_with_tools.invoke(messages)]}
149
 
150
- # ------------------ Graph -------------------------------------------- #
151
- builder = StateGraph(MessagesState)
152
- builder.add_node("assistant", assistant)
153
- builder.add_node("tools", ToolNode(tools))
154
-
155
- builder.add_edge(START, "assistant")
156
- builder.add_conditional_edges("assistant", tools_condition)
157
- builder.add_edge("tools", "assistant")
158
-
159
- return builder.compile()
160
-
161
-
162
- # --------------------------------------------------------------------------- #
163
- # Test rapido #
164
- # --------------------------------------------------------------------------- #
165
- if __name__ == "__main__":
166
- graph = build_graph(provider="groq")
167
- question = "When was a picture of St. Thomas Aquinas first added to the Wikipedia page on the Principle of double effect?"
168
- messages = [HumanMessage(content=question)]
169
- result = graph.invoke({"messages": messages})
170
- for m in result["messages"]:
171
- m.pretty_print()
 
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
 
8
  # LLM providers
9
  from langchain_google_genai import ChatGoogleGenerativeAI
10
  from langchain_groq import ChatGroq
11
+ from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint
 
 
 
12
 
13
  # Tools & loaders
14
  from langchain_community.tools.tavily_search import TavilySearchResults
 
16
  from langchain_core.messages import SystemMessage, HumanMessage
17
  from langchain_core.tools import tool
18
 
19
+ load_dotenv()
20
 
21
  # --------------------------------------------------------------------------- #
22
+ # TOOLS #
23
  # --------------------------------------------------------------------------- #
24
  @tool
25
  def multiply(a: int, b: int) -> int:
26
  """Multiply two integers and return the product."""
27
  return a * b
28
 
 
29
  @tool
30
  def add(a: int, b: int) -> int:
31
  """Add two integers and return the sum."""
32
  return a + b
33
 
 
34
  @tool
35
  def subtract(a: int, b: int) -> int:
36
  """Subtract the second integer from the first and return the difference."""
37
  return a - b
38
 
 
39
  @tool
40
  def divide(a: int, b: int) -> float:
41
  """Divide a by b and return the quotient (error if b == 0)."""
 
43
  raise ValueError("Cannot divide by zero.")
44
  return a / b
45
 
 
46
  @tool
47
  def modulus(a: int, b: int) -> int:
48
  """Return the remainder of the division of a by b."""
49
  return a % b
50
 
 
 
 
 
51
  @tool
52
  def wiki_search(query: str) -> str:
53
  """Search Wikipedia (max 2 docs) and return formatted content."""
 
58
  for d in docs
59
  )
60
 
 
 
 
 
61
  @tool
62
  def web_search(query: str) -> str:
63
  """Perform a web search with Tavily (max 3 docs) and return formatted content."""
 
68
  for d in docs
69
  )
70
 
 
 
 
 
71
  @tool
72
  def arxiv_search(query: str) -> str:
73
  """Search ArXiv (max 3 docs) and return first 1000 characters per paper."""
 
78
  for d in docs
79
  )
80
 
 
81
  # --------------------------------------------------------------------------- #
82
  # System prompt #
83
  # --------------------------------------------------------------------------- #
 
85
  system_prompt = f.read()
86
  sys_msg = SystemMessage(content=system_prompt)
87
 
 
 
 
88
  tools = [
89
+ multiply, add, subtract, divide, modulus,
90
+ wiki_search, web_search, arxiv_search,
 
 
 
 
 
 
91
  ]
92
 
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
+ ll