MickyWin22 commited on
Commit
c75fc46
·
verified ·
1 Parent(s): 1a4236f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -60
app.py CHANGED
@@ -38,87 +38,74 @@ def file_reader(file_path: str) -> str:
38
  except Exception as e:
39
  return f"Error reading or processing file '{file_path}': {e}"
40
 
41
- # --- Agent Class (Now using a free Open-Source LLM) ---
42
  class GaiaSmolAgent:
43
  def __init__(self):
44
- #print("Initializing GaiaSmolAgent with a free Open-Source LLM via Groq...")
 
 
 
 
 
 
45
  api_key = os.getenv("GEMINI_API_KEY")
46
  if not api_key:
47
  raise ValueError("API key 'GEMINI_API_KEY' not found in environment secrets.")
48
 
49
- #model = InferenceClientModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct", provider="together")
50
-
51
-
52
- self.planner_model = LiteLLMModel(
53
- #model_id="groq/llama3-8b-8192",
54
- model_id="gemini/gemini-1.5-pro-latest",
55
  api_key=api_key,
56
  temperature=0.0,
 
57
  )
58
 
59
- # Initialize the agent with the tools it can use.
60
- self.executor_agent = CodeAgent(
61
- model=self.planner_model,
62
- tools=[file_reader, DuckDuckGoSearchTool()],
63
- add_base_tools=True, # Provides a python interpreter
64
- )
65
- print("GaiaSmolAgent initialized successfully.")
66
-
67
- def _generate_script(self, question: str) -> str:
68
- """Generates a self-contained Python script to answer the question."""
69
- print(f"Generating script for question: {question[:100]}...")
70
-
71
- prompt = f"""
72
- You are an expert Python programmer. Your task is to write a single, self-contained Python script to answer the user's question.
73
 
74
- You have access to the following functions which are pre-imported and ready to use:
75
- - `duck_duck_go_search(query: str) -> str`: Searches the web and returns a string with the results.
76
- - `file_reader(file_path: str) -> str`: Reads a file and returns its contents as a string.
77
 
78
- CRITICAL INSTRUCTIONS:
79
- 1. Your output must be ONLY the Python code for the script. Do not add any explanation or markdown formatting like ```python.
80
- 2. The script MUST end with a call to a function `final_answer(answer: str)`.
81
- 3. The `answer` passed to `final_answer` must be a single, concise string.
82
- 4. All logic, including processing the string outputs from the tools, must be included in this single script. State is preserved within the script.
83
 
84
- Question: "{question}"
85
-
86
- Example for "What is the capital of France?":
87
- search_result = duck_duck_go_search("capital of France")
88
- # In a real scenario, you would parse this string to find the answer.
89
- # For this example, we'll just summarize the string.
90
- answer = "Based on the search, the capital is likely Paris." # Replace with actual logic
91
- final_answer(answer)
92
-
93
- Now, write the Python script to answer the user's question.
94
  """
95
- messages = [{"role": "user", "content": [{"type": "text", "text": prompt}]}]
96
- response_object = self.planner_model.generate(messages)
97
-
98
- # --- THIS IS THE FIX ---
99
- # The response is an object, not a string. We need to access its .content attribute.
100
- response_content = response_object.content
101
-
102
- if "```python" in response_content:
103
- response_content = response_content.split("```python")[1].split("```")[0].strip()
104
-
105
- print(f"--- Generated Script ---\n{response_content}\n------------------------")
106
- return response_content
107
 
108
  def __call__(self, question: str) -> str:
109
- """Generates and executes a single script to answer the question."""
110
- print(f"Agent received question: {question[:100]}...")
111
-
 
 
112
  try:
113
- script_to_execute = self._generate_script(question)
114
- final_answer = self.executor_agent.run(script_to_execute)
115
-
116
  except Exception as e:
117
  print(f"FATAL AGENT ERROR: An exception occurred during agent execution: {e}")
118
- print(traceback.format_exc()) # Print the full traceback for debugging
119
  return f"FATAL AGENT ERROR: {e}"
120
 
121
- print(f"Agent returning final answer: {final_answer}")
122
  return str(final_answer)
123
 
124
  # --- Main Application Logic (Unchanged) ---
 
38
  except Exception as e:
39
  return f"Error reading or processing file '{file_path}': {e}"
40
 
41
+ # --- Agent Class ---
42
  class GaiaSmolAgent:
43
  def __init__(self):
44
+ """
45
+ Initializes the optimized agent.
46
+ Optimization 1: Use a faster LLM (Gemini 1.5 Flash) to reduce latency.
47
+ Optimization 2: Use a single, powerful agent with a detailed system prompt
48
+ to eliminate the slow two-step (plan -> execute) process.
49
+ """
50
+ print("Initializing Optimized GaiaSmolAgent...")
51
  api_key = os.getenv("GEMINI_API_KEY")
52
  if not api_key:
53
  raise ValueError("API key 'GEMINI_API_KEY' not found in environment secrets.")
54
 
55
+ # Use a faster, more cost-effective model optimized for speed.
56
+ model = LiteLLMModel(
57
+ model_id="gemini/gemini-1.5-flash-latest",
 
 
 
58
  api_key=api_key,
59
  temperature=0.0,
60
+ timeout=120.0, # Add a timeout to prevent hanging
61
  )
62
 
63
+ # A more sophisticated system prompt to guide the agent's reasoning.
64
+ # This improves its ability to handle complex GAIA questions.
65
+ system_prompt = """
66
+ You are an expert-level research assistant AI. Your sole purpose is to answer the user's question by breaking it down into logical steps and using the provided tools.
 
 
 
 
 
 
 
 
 
 
67
 
68
+ **Available Tools:**
69
+ - `duck_duck_go_search(query: str) -> str`: Use this to find information, file URLs, or anything on the web.
70
+ - `file_reader(file_path: str) -> str`: Use this to read the contents of a file from a local path or a web URL.
71
 
72
+ **Your Thought Process:**
73
+ 1. **Deconstruct the Goal:** Carefully analyze the question to understand what information is needed.
74
+ 2. **Formulate a Plan:** Think step-by-step about which tools to use in what order. For example, you might need to search for a URL first, then read the content of that URL.
75
+ 3. **Execute & Analyze:** Call the necessary tools. Carefully examine the output of each tool to extract the required facts. You can write Python code to process the data returned by the tools.
76
+ 4. **Synthesize the Answer:** Once you have gathered sufficient information, formulate a final, concise answer to the original question.
77
 
78
+ **CRITICAL INSTRUCTIONS:**
79
+ - Your final action MUST be a single call to the `final_answer(answer: str)` function.
80
+ - The `answer` argument must be a string containing only the definitive answer.
81
+ - All code you write is executed in a restricted Python environment. You can define variables and write logic to process the tool outputs before calling `final_answer`.
82
+ - Do not ask for clarification. Directly proceed to solve the problem.
 
 
 
 
 
83
  """
84
+
85
+ # Initialize a single, powerful agent instead of a planner/executor pair.
86
+ self.agent = CodeAgent(
87
+ model=model,
88
+ tools=[file_reader, DuckDuckGoSearchTool()],
89
+ system_prompt=system_prompt,
90
+ add_base_tools=True, # Provides the python interpreter and the final_answer function
91
+ )
92
+ print("Optimized GaiaSmolAgent initialized successfully.")
 
 
 
93
 
94
  def __call__(self, question: str) -> str:
95
+ """
96
+ Directly runs the agent to generate and execute a plan to answer the question.
97
+ This simplified single-call approach is faster and more efficient.
98
+ """
99
+ print(f"Optimized Agent received question: {question[:100]}...")
100
  try:
101
+ # The agent now internally handles the reasoning, code generation, and execution in one step.
102
+ final_answer = self.agent.run(question)
 
103
  except Exception as e:
104
  print(f"FATAL AGENT ERROR: An exception occurred during agent execution: {e}")
105
+ print(traceback.format_exc()) # Print full traceback for easier debugging
106
  return f"FATAL AGENT ERROR: {e}"
107
 
108
+ print(f"Optimized Agent returning final answer: {final_answer}")
109
  return str(final_answer)
110
 
111
  # --- Main Application Logic (Unchanged) ---