Nitinguleria commited on
Commit
ce7c692
Β·
verified Β·
1 Parent(s): a3d6ae7

Update app.py

Browse files

updated with langgraph

Files changed (1) hide show
  1. app.py +75 -52
app.py CHANGED
@@ -3,6 +3,11 @@ import gradio as gr
3
  import requests
4
  import inspect
5
  import pandas as pd
 
 
 
 
 
6
 
7
  # (Keep Constants as is)
8
  # --- Constants ---
@@ -14,74 +19,92 @@ from smolagent import Agent, Tool
14
  from duckduckgo_search import ddg
15
  import sympy
16
  import re
 
17
 
18
- class WikipediaSearchTool(Tool):
19
- name = "wikipedia_search"
20
- description = "Searches for answers using Wikipedia"
 
 
21
 
22
- def use(self, input: str) -> str:
23
- results = ddg(input, max_results=3)
24
- if results:
25
- return results[0]["body"]
26
- return "No information found."
 
27
 
28
- class MathSolverTool(Tool):
29
- name = "math_solver"
30
- description = "Solves math expressions and equations"
 
 
 
 
31
 
32
- def use(self, input: str) -> str:
33
- try:
34
- expression = sympy.sympify(input)
35
- result = expression.evalf()
36
- return str(result)
37
- except Exception as e:
38
- return f"Math Error: {e}"
39
 
40
- class CodeExecutionTool(Tool):
41
- name = "python_executor"
42
- description = "Executes Python code snippets and returns output"
43
 
44
- def use(self, input: str) -> str:
45
- try:
46
- local_vars = {}
47
- exec(f"result = {input}", {}, local_vars)
48
- return str(local_vars["result"])
49
- except Exception as e:
50
- return f"Code Error: {e}"
51
 
52
- def classify_question(q: str) -> str:
53
- q_lower = q.lower()
54
- if any(keyword in q_lower for keyword in ["solve", "evaluate", "calculate", "math"]):
55
  return "math"
56
- elif any(keyword in q_lower for keyword in ["code", "python", "return", "function"]):
57
  return "code"
58
- elif any(keyword in q_lower for keyword in ["who", "what", "where", "when", "why", "how", "capital", "invented"]):
59
  return "search"
60
  else:
61
- return "default"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  class BasicAgent:
64
  def __init__(self):
65
- self.agent = Agent(
66
- tools=[
67
- WikipediaSearchTool(),
68
- MathSolverTool(),
69
- CodeExecutionTool(),
70
- ]
71
- )
72
 
73
  def __call__(self, question: str) -> str:
74
- category = classify_question(question)
75
- print(f"Routing question: {question[:50]}... -> [{category}]")
76
-
77
- if category == "math":
78
- return MathSolverTool().use(question)
79
- elif category == "code":
80
- return CodeExecutionTool().use(question)
81
- elif category == "search":
82
- return WikipediaSearchTool().use(question)
83
- else:
84
- return self.agent.run(question)
85
 
86
 
87
  def run_and_submit_all( profile: gr.OAuthProfile | None):
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ import sympy
7
+ import re
8
+ from duckduckgo_search import ddg
9
+ from langgraph.graph import StateGraph, END
10
+ from typing import TypedDict
11
 
12
  # (Keep Constants as is)
13
  # --- Constants ---
 
19
  from duckduckgo_search import ddg
20
  import sympy
21
  import re
22
+ # --- Tools ---
23
 
24
+ def wikipedia_search_tool(input: str) -> str:
25
+ results = ddg(input, max_results=3)
26
+ if results:
27
+ return results[0]["body"]
28
+ return "No information found."
29
 
30
+ def math_solver_tool(input: str) -> str:
31
+ try:
32
+ expr = sympy.sympify(input)
33
+ return str(expr.evalf())
34
+ except Exception as e:
35
+ return f"Math Error: {e}"
36
 
37
+ def code_execution_tool(input: str) -> str:
38
+ try:
39
+ local_vars = {}
40
+ exec(f"result = {input}", {}, local_vars)
41
+ return str(local_vars["result"])
42
+ except Exception as e:
43
+ return f"Code Error: {e}"
44
 
45
+ # --- State definition ---
 
 
 
 
 
 
46
 
47
+ class AgentState(TypedDict):
48
+ question: str
49
+ response: str
50
 
51
+ # --- Routing logic ---
 
 
 
 
 
 
52
 
53
+ def route_question(state: AgentState) -> str:
54
+ q = state["question"].lower()
55
+ if any(k in q for k in ["solve", "calculate", "evaluate", "math", "=", "^"]):
56
  return "math"
57
+ elif any(k in q for k in ["code", "python", "return", "function"]):
58
  return "code"
59
+ elif any(k in q for k in ["what", "who", "when", "where", "why", "capital", "invented"]):
60
  return "search"
61
  else:
62
+ return "search"
63
+
64
+ # --- LangGraph graph setup ---
65
+
66
+ builder = StateGraph(AgentState)
67
+
68
+ @builder.node()
69
+ def math_node(state: AgentState) -> AgentState:
70
+ return {"question": state["question"], "response": math_solver_tool(state["question"])}
71
+
72
+ @builder.node()
73
+ def code_node(state: AgentState) -> AgentState:
74
+ return {"question": state["question"], "response": code_execution_tool(state["question"])}
75
+
76
+ @builder.node()
77
+ def search_node(state: AgentState) -> AgentState:
78
+ return {"question": state["question"], "response": wikipedia_search_tool(state["question"])}
79
+
80
+ @builder.multi_choice()
81
+ def router(state: AgentState) -> str:
82
+ return route_question(state)
83
+
84
+ builder.set_entry_point("router", router)
85
+ builder.add_node("math", math_node)
86
+ builder.add_node("code", code_node)
87
+ builder.add_node("search", search_node)
88
+ builder.add_conditional_edges("router", {
89
+ "math": "math",
90
+ "code": "code",
91
+ "search": "search"
92
+ })
93
+ builder.add_edge("math", END)
94
+ builder.add_edge("code", END)
95
+ builder.add_edge("search", END)
96
+
97
+ app_graph = builder.compile()
98
 
99
  class BasicAgent:
100
  def __init__(self):
101
+ print("LangGraph Agent initialized.")
 
 
 
 
 
 
102
 
103
  def __call__(self, question: str) -> str:
104
+ state = {"question": question, "response": ""}
105
+ result = app_graph.invoke(state)
106
+ return result["response"]
107
+
 
 
 
 
 
 
 
108
 
109
 
110
  def run_and_submit_all( profile: gr.OAuthProfile | None):