Mehedi2 commited on
Commit
4655d76
·
verified ·
1 Parent(s): 4f53bbc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -40
app.py CHANGED
@@ -1,8 +1,10 @@
1
  import os
2
- import re
3
- import json
4
  import requests
 
5
  import pandas as pd
 
 
6
  from pathlib import Path
7
  from typing import Optional
8
  from dotenv import load_dotenv
@@ -11,16 +13,16 @@ from langgraph.prebuilt import create_react_agent
11
  from langchain_core.messages import HumanMessage
12
  from langchain_core.tools import tool
13
  from langchain_openai import ChatOpenAI
14
- import inspect
15
 
16
  load_dotenv()
17
 
 
18
 
19
  class OpenRouterLLM(ChatOpenAI):
20
  """Custom OpenRouter LLM wrapper for LangGraph"""
21
 
22
  def __init__(self, model: str = "deepseek/deepseek-v3.1-terminus", **kwargs):
23
- api_key = os.getenv("OPENROUTER_API_KEY") or os.getenv("agentkey")
24
  super().__init__(
25
  model=model,
26
  openai_api_key=api_key,
@@ -28,12 +30,10 @@ class OpenRouterLLM(ChatOpenAI):
28
  **kwargs
29
  )
30
 
31
-
32
  # ------------------ TOOLS ------------------
33
 
34
  @tool
35
  def search_web(query: str) -> str:
36
- """Search the web using DuckDuckGo for current information."""
37
  try:
38
  search_url = f"https://api.duckduckgo.com/?q={query}&format=json&no_html=1&skip_disambig=1"
39
  response = requests.get(search_url, timeout=10)
@@ -51,10 +51,8 @@ def search_web(query: str) -> str:
51
  except Exception as e:
52
  return f"Search error: {str(e)}"
53
 
54
-
55
  @tool
56
  def search_wikipedia(query: str) -> str:
57
- """Search Wikipedia for factual information."""
58
  try:
59
  search_url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + query.replace(" ", "_")
60
  response = requests.get(search_url, timeout=10)
@@ -66,10 +64,8 @@ def search_wikipedia(query: str) -> str:
66
  except Exception as e:
67
  return f"Wikipedia search error: {str(e)}"
68
 
69
-
70
  @tool
71
  def execute_python(code: str) -> str:
72
- """Execute Python code and return the result."""
73
  try:
74
  safe_globals = {
75
  '__builtins__': {
@@ -95,10 +91,8 @@ def execute_python(code: str) -> str:
95
  except Exception as e:
96
  return f"Python execution error: {str(e)}"
97
 
98
-
99
  @tool
100
  def read_excel_file(file_path: str, sheet_name: Optional[str] = None) -> str:
101
- """Read an Excel file and return its contents as a formatted string."""
102
  try:
103
  file_path_obj = Path(file_path)
104
  if not file_path_obj.exists():
@@ -120,10 +114,8 @@ def read_excel_file(file_path: str, sheet_name: Optional[str] = None) -> str:
120
  except Exception as e:
121
  return f"Error reading Excel file: {str(e)}"
122
 
123
-
124
  @tool
125
  def read_text_file(file_path: str) -> str:
126
- """Read a text file and return its contents."""
127
  try:
128
  file_path_obj = Path(file_path)
129
  if not file_path_obj.exists():
@@ -139,14 +131,13 @@ def read_text_file(file_path: str) -> str:
139
  except Exception as e:
140
  return f"Error reading file: {str(e)}"
141
 
142
-
143
  # ------------------ GAIA AGENT ------------------
144
 
145
  class GaiaAgent:
146
- """LangGraph-based agent for GAIA tasks using OpenRouter DeepSeek"""
147
 
148
  def __init__(self):
149
- print("Initializing GaiaAgent with LangGraph and OpenRouter DeepSeek...")
150
  self.llm = OpenRouterLLM(
151
  model="deepseek/deepseek-v3.1-terminus",
152
  temperature=0.1,
@@ -154,8 +145,6 @@ class GaiaAgent:
154
  )
155
  self.tools = [search_web, search_wikipedia, execute_python, read_excel_file, read_text_file]
156
  prompt_modifier = self._get_system_prompt()
157
-
158
- # Detect correct kwarg for your LangGraph version
159
  sig = inspect.signature(create_react_agent)
160
  accepted = sig.parameters.keys()
161
  kwargs = {}
@@ -165,55 +154,76 @@ class GaiaAgent:
165
  kwargs["state_modifier"] = prompt_modifier
166
  elif "prompt" in accepted:
167
  kwargs["prompt"] = prompt_modifier
168
-
169
  self.agent = create_react_agent(self.llm, self.tools, **kwargs)
170
  print("GaiaAgent initialized successfully!")
171
 
172
  def _get_system_prompt(self) -> str:
173
- return """You are an advanced AI agent designed to answer complex questions...
174
- (keep your original system prompt here)"""
175
 
176
- def __call__(self, task_id: str, question: str) -> str:
177
  try:
178
- print(f"Processing task {task_id}: {question[:100]}...")
179
  messages = [HumanMessage(content=question)]
180
  result = self.agent.invoke({"messages": messages})
181
- final_message = result["messages"][-1]
182
- answer = final_message.content
183
  return self._clean_answer(answer)
184
  except Exception as e:
185
  return f"Agent error: {e}"
186
 
187
  def _clean_answer(self, answer: str) -> str:
188
- # same cleaning code as before
189
  answer = answer.strip()
190
  if "final answer:" in answer.lower():
191
  parts = re.split(r'final answer:', answer, flags=re.IGNORECASE)
192
  if len(parts) > 1:
193
  answer = parts[-1].strip()
194
- prefixes = ["The answer is", "Answer:", "Result:", "Solution:",
195
- "Based on", "Therefore", "In conclusion", "So the answer is"]
196
  for prefix in prefixes:
197
  if answer.lower().startswith(prefix.lower()):
198
  answer = answer[len(prefix):].strip()
199
  if answer.startswith(':'):
200
  answer = answer[1:].strip()
201
  break
202
- if len(answer.split()) <= 3:
203
- answer = answer.strip('"\'.')
204
  return answer
205
 
 
206
 
207
- # ------------------ ENTRYPOINT ------------------
208
 
209
- import gradio as gr
210
-
211
- agent = GaiaAgent()
 
 
212
 
213
- def run_agent(prompt: str) -> str:
214
- return agent("gaia_task", prompt)
 
 
215
 
216
- demo = gr.Interface(fn=run_agent, inputs="text", outputs="text", title="GAIA Agent")
 
 
 
 
217
 
218
- if __name__ == "__main__":
219
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
+ import gradio as gr
 
3
  import requests
4
+ import inspect
5
  import pandas as pd
6
+ import re
7
+ import json
8
  from pathlib import Path
9
  from typing import Optional
10
  from dotenv import load_dotenv
 
13
  from langchain_core.messages import HumanMessage
14
  from langchain_core.tools import tool
15
  from langchain_openai import ChatOpenAI
 
16
 
17
  load_dotenv()
18
 
19
+ # ------------------ CUSTOM LLM ------------------
20
 
21
  class OpenRouterLLM(ChatOpenAI):
22
  """Custom OpenRouter LLM wrapper for LangGraph"""
23
 
24
  def __init__(self, model: str = "deepseek/deepseek-v3.1-terminus", **kwargs):
25
+ api_key = os.getenv("OPENROUTER_API_KEY") or os.getenv("my_key")
26
  super().__init__(
27
  model=model,
28
  openai_api_key=api_key,
 
30
  **kwargs
31
  )
32
 
 
33
  # ------------------ TOOLS ------------------
34
 
35
  @tool
36
  def search_web(query: str) -> str:
 
37
  try:
38
  search_url = f"https://api.duckduckgo.com/?q={query}&format=json&no_html=1&skip_disambig=1"
39
  response = requests.get(search_url, timeout=10)
 
51
  except Exception as e:
52
  return f"Search error: {str(e)}"
53
 
 
54
  @tool
55
  def search_wikipedia(query: str) -> str:
 
56
  try:
57
  search_url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + query.replace(" ", "_")
58
  response = requests.get(search_url, timeout=10)
 
64
  except Exception as e:
65
  return f"Wikipedia search error: {str(e)}"
66
 
 
67
  @tool
68
  def execute_python(code: str) -> str:
 
69
  try:
70
  safe_globals = {
71
  '__builtins__': {
 
91
  except Exception as e:
92
  return f"Python execution error: {str(e)}"
93
 
 
94
  @tool
95
  def read_excel_file(file_path: str, sheet_name: Optional[str] = None) -> str:
 
96
  try:
97
  file_path_obj = Path(file_path)
98
  if not file_path_obj.exists():
 
114
  except Exception as e:
115
  return f"Error reading Excel file: {str(e)}"
116
 
 
117
  @tool
118
  def read_text_file(file_path: str) -> str:
 
119
  try:
120
  file_path_obj = Path(file_path)
121
  if not file_path_obj.exists():
 
131
  except Exception as e:
132
  return f"Error reading file: {str(e)}"
133
 
 
134
  # ------------------ GAIA AGENT ------------------
135
 
136
  class GaiaAgent:
137
+ """LangGraph-based agent using OpenRouter DeepSeek"""
138
 
139
  def __init__(self):
140
+ print("Initializing GaiaAgent...")
141
  self.llm = OpenRouterLLM(
142
  model="deepseek/deepseek-v3.1-terminus",
143
  temperature=0.1,
 
145
  )
146
  self.tools = [search_web, search_wikipedia, execute_python, read_excel_file, read_text_file]
147
  prompt_modifier = self._get_system_prompt()
 
 
148
  sig = inspect.signature(create_react_agent)
149
  accepted = sig.parameters.keys()
150
  kwargs = {}
 
154
  kwargs["state_modifier"] = prompt_modifier
155
  elif "prompt" in accepted:
156
  kwargs["prompt"] = prompt_modifier
 
157
  self.agent = create_react_agent(self.llm, self.tools, **kwargs)
158
  print("GaiaAgent initialized successfully!")
159
 
160
  def _get_system_prompt(self) -> str:
161
+ return """You are an advanced AI agent designed to answer complex questions.
162
+ Keep answers concise and factual where possible."""
163
 
164
+ def __call__(self, question: str) -> str:
165
  try:
 
166
  messages = [HumanMessage(content=question)]
167
  result = self.agent.invoke({"messages": messages})
168
+ answer = result["messages"][-1].content
 
169
  return self._clean_answer(answer)
170
  except Exception as e:
171
  return f"Agent error: {e}"
172
 
173
  def _clean_answer(self, answer: str) -> str:
 
174
  answer = answer.strip()
175
  if "final answer:" in answer.lower():
176
  parts = re.split(r'final answer:', answer, flags=re.IGNORECASE)
177
  if len(parts) > 1:
178
  answer = parts[-1].strip()
179
+ prefixes = ["The answer is", "Answer:", "Result:", "Solution:"]
 
180
  for prefix in prefixes:
181
  if answer.lower().startswith(prefix.lower()):
182
  answer = answer[len(prefix):].strip()
183
  if answer.startswith(':'):
184
  answer = answer[1:].strip()
185
  break
 
 
186
  return answer
187
 
188
+ # ------------------ RUN AND SUBMIT ------------------
189
 
190
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
191
 
192
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
193
+ if profile:
194
+ username = profile.username
195
+ else:
196
+ return "Please login to Hugging Face first.", None
197
 
198
+ space_id = os.getenv("SPACE_ID") or "your_space_username/your_space_name"
199
+ api_url = DEFAULT_API_URL
200
+ questions_url = f"{api_url}/questions"
201
+ submit_url = f"{api_url}/submit"
202
 
203
+ # Instantiate GaiaAgent
204
+ try:
205
+ agent = GaiaAgent()
206
+ except Exception as e:
207
+ return f"Error initializing GaiaAgent: {e}", None
208
 
209
+ # Fetch questions
210
+ try:
211
+ response = requests.get(questions_url, timeout=15)
212
+ response.raise_for_status()
213
+ questions_data = response.json()
214
+ except Exception as e:
215
+ return f"Error fetching questions: {e}", None
216
+
217
+ # Run agent on questions
218
+ answers_payload = []
219
+ results_log = []
220
+ for item in questions_data:
221
+ task_id = item.get("task_id")
222
+ question_text = item.get("question")
223
+ if not task_id or question_text is None:
224
+ continue
225
+ try:
226
+ submitted_answer = agent(question_text)
227
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
228
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
229
+ except Exception as e: