Update veryfinal.py
Browse files- veryfinal.py +48 -58
veryfinal.py
CHANGED
@@ -1,4 +1,4 @@
|
|
1 |
-
"""Enhanced LangGraph + Agno Hybrid Agent System
|
2 |
|
3 |
import os
|
4 |
import time
|
@@ -31,6 +31,7 @@ from agno.models.google import Gemini
|
|
31 |
from agno.tools.tavily import TavilyTools
|
32 |
from agno.memory.agent import AgentMemory
|
33 |
from agno.storage.sqlite import SqliteStorage
|
|
|
34 |
|
35 |
load_dotenv()
|
36 |
|
@@ -64,17 +65,28 @@ gemini_limiter = PerformanceRateLimiter(28, "Gemini")
|
|
64 |
groq_limiter = PerformanceRateLimiter(28, "Groq")
|
65 |
nvidia_limiter = PerformanceRateLimiter(4, "NVIDIA")
|
66 |
|
67 |
-
# Create Agno agents with SQLite storage
|
68 |
def create_agno_agents():
|
|
|
69 |
storage = SqliteStorage(
|
70 |
table_name="agent_sessions",
|
71 |
db_file="tmp/agent_sessions.db",
|
72 |
auto_upgrade_schema=True
|
73 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
74 |
math_agent = Agent(
|
75 |
name="MathSpecialist",
|
76 |
model=Groq(
|
77 |
-
|
78 |
api_key=os.getenv("GROQ_API_KEY"),
|
79 |
temperature=0
|
80 |
),
|
@@ -82,21 +94,17 @@ def create_agno_agents():
|
|
82 |
instructions=[
|
83 |
"Solve math problems with precision",
|
84 |
"Show step-by-step calculations",
|
85 |
-
"Use calculation tools as needed",
|
86 |
"Finish with: FINAL ANSWER: [result]"
|
87 |
],
|
88 |
-
|
89 |
-
|
90 |
-
create_user_memories=True,
|
91 |
-
create_session_summary=True
|
92 |
-
),
|
93 |
show_tool_calls=False,
|
94 |
markdown=False
|
95 |
)
|
96 |
research_agent = Agent(
|
97 |
name="ResearchSpecialist",
|
98 |
model=Gemini(
|
99 |
-
|
100 |
api_key=os.getenv("GOOGLE_API_KEY"),
|
101 |
temperature=0
|
102 |
),
|
@@ -104,7 +112,6 @@ def create_agno_agents():
|
|
104 |
instructions=[
|
105 |
"Conduct thorough research using available tools",
|
106 |
"Synthesize information from multiple sources",
|
107 |
-
"Provide comprehensive, well-cited answers",
|
108 |
"Finish with: FINAL ANSWER: [answer]"
|
109 |
],
|
110 |
tools=[
|
@@ -116,11 +123,8 @@ def create_agno_agents():
|
|
116 |
format="markdown"
|
117 |
)
|
118 |
],
|
119 |
-
|
120 |
-
|
121 |
-
create_user_memories=True,
|
122 |
-
create_session_summary=True
|
123 |
-
),
|
124 |
show_tool_calls=False,
|
125 |
markdown=False
|
126 |
)
|
@@ -144,7 +148,7 @@ def subtract(a: int, b: int) -> int:
|
|
144 |
|
145 |
@tool
|
146 |
def divide(a: int, b: int) -> float:
|
147 |
-
"""Divide two numbers
|
148 |
if b == 0:
|
149 |
raise ValueError("Cannot divide by zero.")
|
150 |
return a / b
|
@@ -199,7 +203,6 @@ def setup_faiss():
|
|
199 |
print(f"FAISS setup failed: {e}")
|
200 |
return None
|
201 |
|
202 |
-
# State definition
|
203 |
class EnhancedAgentState(TypedDict):
|
204 |
messages: Annotated[List[HumanMessage|AIMessage], operator.add]
|
205 |
query: str
|
@@ -208,7 +211,6 @@ class EnhancedAgentState(TypedDict):
|
|
208 |
perf: Dict[str,Any]
|
209 |
agno_resp: str
|
210 |
|
211 |
-
# Hybrid system combining LangGraph and Agno
|
212 |
class HybridLangGraphAgnoSystem:
|
213 |
def __init__(self):
|
214 |
self.agno = create_agno_agents()
|
@@ -279,51 +281,39 @@ class HybridLangGraphAgnoSystem:
|
|
279 |
g.add_node("agno_research",agno_research)
|
280 |
g.add_node("lg_retrieval",lg_retrieval)
|
281 |
g.add_node("agno_general",agno_general)
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
for n in ["lg_math","agno_research","lg_retrieval","agno_general"]:
|
288 |
-
|
289 |
return g.compile(checkpointer=MemorySaver())
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
|
304 |
-
}
|
305 |
except Exception as e:
|
306 |
return {"answer":f"Error: {e}","performance_metrics":{},"provider_used":"Error"}
|
307 |
|
308 |
-
def build_graph(provider: str
|
309 |
-
""
|
310 |
-
Build and return the StateGraph for the requested provider.
|
311 |
-
- "hybrid" returns the HybridLangGraphAgnoSystem graph.
|
312 |
-
- "groq", "google", "nvidia" all fall back to the hybrid graph.
|
313 |
-
"""
|
314 |
-
if provider == "hybrid":
|
315 |
-
return HybridLangGraphAgnoSystem().graph
|
316 |
-
elif provider in ("groq", "google", "nvidia"):
|
317 |
-
# Simply reuse the hybrid graph under these names
|
318 |
return HybridLangGraphAgnoSystem().graph
|
319 |
-
|
320 |
-
raise ValueError(f"Only 'hybrid', 'groq', 'google', or 'nvidia' supported (got '{provider}')")
|
321 |
-
|
322 |
|
323 |
-
|
324 |
-
|
325 |
-
graph=build_graph()
|
326 |
msgs=[HumanMessage(content="What are the names of the US presidents who were assassinated?")]
|
327 |
-
|
328 |
for m in res["messages"]:
|
329 |
-
|
|
|
1 |
+
"""Enhanced LangGraph + Agno Hybrid Agent System"""
|
2 |
|
3 |
import os
|
4 |
import time
|
|
|
31 |
from agno.tools.tavily import TavilyTools
|
32 |
from agno.memory.agent import AgentMemory
|
33 |
from agno.storage.sqlite import SqliteStorage
|
34 |
+
from agno.memory.v2.db.sqlite import SqliteMemoryDb # Correct import for memory DB
|
35 |
|
36 |
load_dotenv()
|
37 |
|
|
|
65 |
groq_limiter = PerformanceRateLimiter(28, "Groq")
|
66 |
nvidia_limiter = PerformanceRateLimiter(4, "NVIDIA")
|
67 |
|
68 |
+
# Create Agno agents with corrected SQLite storage and memory
|
69 |
def create_agno_agents():
|
70 |
+
# 1. Storage for the agent's overall state (conversations, etc.)
|
71 |
storage = SqliteStorage(
|
72 |
table_name="agent_sessions",
|
73 |
db_file="tmp/agent_sessions.db",
|
74 |
auto_upgrade_schema=True
|
75 |
)
|
76 |
+
# 2. A separate database for the agent's memory
|
77 |
+
memory_db = SqliteMemoryDb(db_file="tmp/agent_memory.db")
|
78 |
+
|
79 |
+
# 3. The AgentMemory object, which uses the memory_db
|
80 |
+
agent_memory = AgentMemory(
|
81 |
+
db=memory_db, # Pass the SqliteMemoryDb here
|
82 |
+
create_user_memories=True,
|
83 |
+
create_session_summary=True
|
84 |
+
)
|
85 |
+
|
86 |
math_agent = Agent(
|
87 |
name="MathSpecialist",
|
88 |
model=Groq(
|
89 |
+
model="llama-3.3-70b-versatile",
|
90 |
api_key=os.getenv("GROQ_API_KEY"),
|
91 |
temperature=0
|
92 |
),
|
|
|
94 |
instructions=[
|
95 |
"Solve math problems with precision",
|
96 |
"Show step-by-step calculations",
|
|
|
97 |
"Finish with: FINAL ANSWER: [result]"
|
98 |
],
|
99 |
+
storage=storage, # Use SqliteStorage for the agent's persistence
|
100 |
+
memory=agent_memory, # Use the configured AgentMemory
|
|
|
|
|
|
|
101 |
show_tool_calls=False,
|
102 |
markdown=False
|
103 |
)
|
104 |
research_agent = Agent(
|
105 |
name="ResearchSpecialist",
|
106 |
model=Gemini(
|
107 |
+
model="gemini-2.0-flash-lite",
|
108 |
api_key=os.getenv("GOOGLE_API_KEY"),
|
109 |
temperature=0
|
110 |
),
|
|
|
112 |
instructions=[
|
113 |
"Conduct thorough research using available tools",
|
114 |
"Synthesize information from multiple sources",
|
|
|
115 |
"Finish with: FINAL ANSWER: [answer]"
|
116 |
],
|
117 |
tools=[
|
|
|
123 |
format="markdown"
|
124 |
)
|
125 |
],
|
126 |
+
storage=storage, # Use the same storage for persistence
|
127 |
+
memory=agent_memory, # Use the same memory configuration
|
|
|
|
|
|
|
128 |
show_tool_calls=False,
|
129 |
markdown=False
|
130 |
)
|
|
|
148 |
|
149 |
@tool
|
150 |
def divide(a: int, b: int) -> float:
|
151 |
+
"""Divide two numbers."""
|
152 |
if b == 0:
|
153 |
raise ValueError("Cannot divide by zero.")
|
154 |
return a / b
|
|
|
203 |
print(f"FAISS setup failed: {e}")
|
204 |
return None
|
205 |
|
|
|
206 |
class EnhancedAgentState(TypedDict):
|
207 |
messages: Annotated[List[HumanMessage|AIMessage], operator.add]
|
208 |
query: str
|
|
|
211 |
perf: Dict[str,Any]
|
212 |
agno_resp: str
|
213 |
|
|
|
214 |
class HybridLangGraphAgnoSystem:
|
215 |
def __init__(self):
|
216 |
self.agno = create_agno_agents()
|
|
|
281 |
g.add_node("agno_research",agno_research)
|
282 |
g.add_node("lg_retrieval",lg_retrieval)
|
283 |
g.add_node("agno_general",agno_general)
|
284 |
+
g.set_entry_point("router")
|
285 |
+
g.add_conditional_edges("router",pick,{
|
286 |
+
"lg_math":"lg_math","agno_research":"agno_research",
|
287 |
+
"lg_retrieval":"lg_retrieval","agno_general":"agno_general"
|
288 |
+
})
|
289 |
for n in ["lg_math","agno_research","lg_retrieval","agno_general"]:
|
290 |
+
g.add_edge(n,"END")
|
291 |
return g.compile(checkpointer=MemorySaver())
|
292 |
+
def process_query(self, q: str) -> Dict[str,Any]:
|
293 |
+
state={
|
294 |
+
"messages":[HumanMessage(content=q)],
|
295 |
+
"query":q,"agent_type":"","final_answer":"",
|
296 |
+
"perf":{},"agno_resp":""
|
297 |
+
}
|
298 |
+
cfg={"configurable":{"thread_id":f"hyb_{hash(q)}"}}
|
299 |
+
try:
|
300 |
+
out=self.graph.invoke(state,cfg)
|
301 |
+
return {
|
302 |
+
"answer":out["final_answer"],
|
303 |
+
"performance_metrics":out["perf"],
|
304 |
+
"provider_used":out["perf"].get("prov")
|
305 |
+
}
|
|
|
306 |
except Exception as e:
|
307 |
return {"answer":f"Error: {e}","performance_metrics":{},"provider_used":"Error"}
|
308 |
|
309 |
+
def build_graph(provider: str="hybrid"):
|
310 |
+
if provider=="hybrid":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
311 |
return HybridLangGraphAgnoSystem().graph
|
312 |
+
raise ValueError("Only 'hybrid' supported")
|
|
|
|
|
313 |
|
314 |
+
if __name__ == "__main__":
|
315 |
+
graph=build_graph()
|
|
|
316 |
msgs=[HumanMessage(content="What are the names of the US presidents who were assassinated?")]
|
317 |
+
res=graph.invoke({"messages":msgs},{"configurable":{"thread_id":"test"}})
|
318 |
for m in res["messages"]:
|
319 |
+
m.pretty_print()
|