hhhhmmmm commited on
Commit
415d3e5
·
verified ·
1 Parent(s): 81917a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -7
app.py CHANGED
@@ -1,23 +1,120 @@
1
  import os
2
  import gradio as gr
3
  import requests
4
- import inspect
5
  import pandas as pd
 
 
 
 
 
 
 
 
6
 
7
  # (Keep Constants as is)
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  # --- Basic Agent Definition ---
12
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
13
  class BasicAgent:
14
  def __init__(self):
15
  print("BasicAgent initialized.")
16
- def __call__(self, question: str) -> str:
17
- print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  def run_and_submit_all( profile: gr.OAuthProfile | None):
23
  """
@@ -80,7 +177,8 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
80
  print(f"Skipping item with missing task_id or question: {item}")
81
  continue
82
  try:
83
- submitted_answer = agent(question_text)
 
84
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
86
  except Exception as e:
 
1
  import os
2
  import gradio as gr
3
  import requests
 
4
  import pandas as pd
5
+ from langchain.agents import AgentExecutor, create_react_agent
6
+ from langchain.tools import tool
7
+ from langchain.prompts import PromptTemplate
8
+ from langchain_openai import ChatOpenAI # OpenAI-compatible for Groq API
9
+ from ddgs import DDGS # Updated DuckDuckGo Search
10
+ from dotenv import load_dotenv
11
+ import re
12
+ import json
13
 
14
  # (Keep Constants as is)
15
  # --- Constants ---
16
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
17
 
18
+ # --- Define Tools ---
19
+ @tool
20
+ def python_code_executor(code: str) -> str:
21
+ """Execute Python code and return the result as a string. Use for calculations or data processing."""
22
+ try:
23
+ local_vars = {}
24
+ exec(code, {}, local_vars)
25
+ return str(local_vars.get("result", "No result defined. Set 'result' variable."))
26
+ except Exception as e:
27
+ return f"Error: {str(e)}"
28
+
29
+ @tool
30
+ def download_file(url: str) -> str:
31
+ """Download a file from URL and return its content (text if possible)."""
32
+ try:
33
+ response = requests.get(url, timeout=10)
34
+ response.raise_for_status()
35
+ return response.text[:1000] # Truncate for brevity
36
+ except Exception as e:
37
+ return f"Error downloading: {str(e)}"
38
+
39
+ @tool
40
+ def duckduckgo_search(query: str) -> str:
41
+ """Perform a DuckDuckGo search and return top results as a short summary."""
42
+ try:
43
+ with DDGS() as ddgs:
44
+ results = list(ddgs.text(query, max_results=3))
45
+ if not results:
46
+ return "No good results found."
47
+ return json.dumps([{"title": r["title"], "snippet": r["body"]} for r in results])
48
+ except Exception as e:
49
+ return f"Search error: {str(e)}"
50
+
51
  # --- Basic Agent Definition ---
52
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
53
  class BasicAgent:
54
  def __init__(self):
55
  print("BasicAgent initialized.")
56
+ llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)
57
+ tools = [duckduckgo_search, python_code_executor, download_file]
58
+ # Prompt for short, exact answers (GAIA-style) with required ReAct variables
59
+ prompt_template = PromptTemplate.from_template("""
60
+ You are an AI agent solving GAIA benchmark tasks. Use tools if needed (web search, code execution, file download).
61
+
62
+ You have access to the following tools:
63
+ {tools}
64
+
65
+ Use the following format:
66
+
67
+ Question: the input question you must answer
68
+ Thought: you should always think about what to do
69
+ Action: the action to take, should be one of [{tool_names}]
70
+ Action Input: the input to the action
71
+ Observation: the result of the action
72
+ ... (this Thought/Action/Action Input/Observation can repeat N times)
73
+ Thought: I now know the final answer
74
+ Final Answer: the final answer to the original input question
75
+
76
+ Begin!
77
+
78
+ Question: {question}
79
+ File content (if any): {file_content}
80
+
81
+ Reason step-by-step, but return ONLY the final answer as a short string (e.g., a number or phrase). No explanations, no extra text.
82
+ {agent_scratchpad}
83
+ """)
84
+
85
+ agent = create_react_agent(llm, tools, prompt_template)
86
+ self.agent_executor = AgentExecutor(
87
+ agent=agent,
88
+ tools=tools,
89
+ verbose=True, # Set to False for production to reduce logs
90
+ max_iterations=10 # Limit for efficiency
91
+ )
92
+
93
+ def __call__(self, question: str, task_id: str = None, api_url: str = DEFAULT_API_URL) -> str:
94
+ print(f"Agent processing question: {question[:50]}...")
95
+
96
+ # Fetch file if task involves one
97
+ file_content = ""
98
+ if task_id:
99
+ file_url = f"{api_url}/files/{task_id}"
100
+ try:
101
+ response = requests.get(file_url, timeout=10)
102
+ file_content = response.text[:1000] if response.ok else ""
103
+ except Exception as e:
104
+ print(f"File fetch error for {task_id}: {e}")
105
+ pass
106
+
107
+ try:
108
+ response = self.agent_executor.invoke({"question": question, "file_content": file_content})
109
+ # Parse to ensure shortness
110
+ short_answer = re.search(r'(?s)(.*)', response["output"]).group(1).strip()
111
+ if len(short_answer) > 50: # Enforce brevity
112
+ short_answer = short_answer[:50] + "... (truncated)"
113
+ print(f"Agent returning short answer: {short_answer}")
114
+ return short_answer
115
+ except Exception as e:
116
+ print(f"Agent error: {e}")
117
+ return "Error"
118
 
119
  def run_and_submit_all( profile: gr.OAuthProfile | None):
120
  """
 
177
  print(f"Skipping item with missing task_id or question: {item}")
178
  continue
179
  try:
180
+ #submitted_answer = agent(question_text)
181
+ submitted_answer = agent(question_text, task_id=task_id)
182
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
183
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
184
  except Exception as e: