Sanyam0605 commited on
Commit
13cd012
·
verified ·
1 Parent(s): ef74603

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +8 -206
app.py CHANGED
@@ -3,217 +3,25 @@ import gradio as gr
3
  import requests
4
  import inspect
5
  import pandas as pd
6
- from core_agent import GAIAAgent
7
- from smolagents import (
8
- CodeAgent,
9
- DuckDuckGoSearchTool,
10
- TransformersModel,
11
- OpenAIServerModel,
12
- PythonInterpreterTool,
13
- tool
14
- )
15
 
16
- # Debug function to show available environment variables
17
- def debug_environment():
18
- """Print available environment variables related to API keys (with values hidden)"""
19
- debug_vars = [
20
- "HF_API_TOKEN", "HUGGINGFACEHUB_API_TOKEN",
21
- "OPENAI_API_KEY", "XAI_API_KEY",
22
- "AGENT_MODEL_TYPE", "AGENT_MODEL_ID",
23
- "AGENT_TEMPERATURE", "AGENT_VERBOSE"
24
- ]
25
-
26
- print("=== DEBUG: Environment Variables ===")
27
- for var in debug_vars:
28
- if os.environ.get(var):
29
- # Hide actual values for security
30
- print(f"{var}: [SET]")
31
- else:
32
- print(f"{var}: [NOT SET]")
33
- print("===================================")
34
 
35
  # (Keep Constants as is)
36
  # --- Constants ---
37
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
38
 
39
- # --- Basic Agent Definition ---
40
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
41
  class BasicAgent:
42
  def __init__(self):
43
  print("BasicAgent initialized.")
44
-
45
- # Call debug function to show available environment variables
46
- debug_environment()
47
-
48
- # Initialize the GAIAAgent with local execution
49
- try:
50
- # Load environment variables if dotenv is available
51
- try:
52
- import dotenv
53
- dotenv.load_dotenv()
54
- print("Loaded environment variables from .env file")
55
- except ImportError:
56
- print("python-dotenv not installed, continuing with environment as is")
57
-
58
- # Try to load API keys from environment
59
- # Check both HF_API_TOKEN and HUGGINGFACEHUB_API_TOKEN (HF Spaces uses HF_API_TOKEN)
60
- hf_token = os.environ.get("HF_API_TOKEN") or os.environ.get("HUGGINGFACEHUB_API_TOKEN")
61
- openai_key = os.environ.get("OPENAI_API_KEY")
62
- xai_key = os.environ.get("XAI_API_KEY")
63
-
64
- # If we have at least one API key, use a model-based approach
65
- if hf_token or openai_key or xai_key:
66
- # Default model parameters - read directly from environment
67
- model_type = os.environ.get("AGENT_MODEL_TYPE", "OpenAIServerModel")
68
- model_id = os.environ.get("AGENT_MODEL_ID", "gpt-4o")
69
- temperature = float(os.environ.get("AGENT_TEMPERATURE", "0.2"))
70
- verbose = os.environ.get("AGENT_VERBOSE", "false").lower() == "true"
71
-
72
- print(f"Agent config - Model Type: {model_type}, Model ID: {model_id}")
73
-
74
- try:
75
- if model_type == "GeminiModel":
76
- gemini_api_key = os.environ.get("GEMINI_API_KEY")
77
- if not gemini_api_key:
78
- raise ValueError("No Gemini API key provided. Please set GEMINI_API_KEY environment variable.")
79
- self.gaia_agent = GAIAAgent(
80
- model_type="GeminiModel",
81
- model_id=model_id,
82
- api_key=gemini_api_key,
83
- temperature=temperature,
84
- executor_type="local",
85
- verbose=verbose
86
- )
87
- print("Using Google Gemini model")
88
- elif xai_key:
89
- # Use X.AI API with OpenAIServerModel
90
- api_base = os.environ.get("XAI_API_BASE", "https://api.x.ai/v1")
91
- self.gaia_agent = GAIAAgent(
92
- model_type="OpenAIServerModel",
93
- model_id="grok-3-latest", # X.AI's model
94
- api_key=xai_key,
95
- api_base=api_base,
96
- temperature=temperature,
97
- executor_type="local",
98
- verbose=verbose
99
- )
100
- print(f"Using OpenAIServerModel with X.AI API at {api_base}")
101
- elif model_type == "TransformersModel":
102
- # Use local transformers model
103
- print(f"Loading local model: {model_id}")
104
- self.gaia_agent = GAIAAgent(
105
- model_type="TransformersModel",
106
- model_id=model_id,
107
- temperature=temperature,
108
- executor_type="local",
109
- verbose=verbose
110
- )
111
- print(f"Using TransformersModel with model_id: {model_id}")
112
- elif model_type == "HfApiModel" and hf_token:
113
- # Use Hugging Face API
114
- self.gaia_agent = GAIAAgent(
115
- model_type="HfApiModel",
116
- model_id=model_id,
117
- api_key=hf_token,
118
- temperature=temperature,
119
- executor_type="local",
120
- verbose=verbose
121
- )
122
- print(f"Using HfApiModel with model_id: {model_id}")
123
- elif openai_key:
124
- # Default to OpenAI API
125
- api_base = os.environ.get("AGENT_API_BASE")
126
- kwargs = {
127
- "model_type": "OpenAIServerModel",
128
- "model_id": model_id,
129
- "api_key": openai_key,
130
- "temperature": temperature,
131
- "executor_type": "local",
132
- "verbose": verbose
133
- }
134
- if api_base:
135
- kwargs["api_base"] = api_base
136
- print(f"Using custom API base: {api_base}")
137
-
138
- self.gaia_agent = GAIAAgent(**kwargs)
139
- print(f"Using OpenAIServerModel with model_id: {model_id}")
140
- else:
141
- # Fallback to using whatever token we have
142
- print("WARNING: Using fallback initialization with available token")
143
- if hf_token:
144
- self.gaia_agent = GAIAAgent(
145
- model_type="HfApiModel",
146
- model_id="mistralai/Mistral-7B-Instruct-v0.2",
147
- api_key=hf_token,
148
- temperature=temperature,
149
- executor_type="local",
150
- verbose=verbose
151
- )
152
- elif openai_key:
153
- self.gaia_agent = GAIAAgent(
154
- model_type="OpenAIServerModel",
155
- model_id="gpt-3.5-turbo",
156
- api_key=openai_key,
157
- temperature=temperature,
158
- executor_type="local",
159
- verbose=verbose
160
- )
161
- else:
162
- self.gaia_agent = GAIAAgent(
163
- model_type="OpenAIServerModel",
164
- model_id="grok-3-latest",
165
- api_key=xai_key,
166
- api_base=os.environ.get("XAI_API_BASE", "https://api.x.ai/v1"),
167
- temperature=temperature,
168
- executor_type="local",
169
- verbose=verbose
170
- )
171
- except ImportError as ie:
172
- # Handle OpenAI module errors specifically
173
- if "openai" in str(ie).lower() and hf_token:
174
- print(f"OpenAI module error: {ie}. Falling back to HfApiModel.")
175
- self.gaia_agent = GAIAAgent(
176
- model_type="HfApiModel",
177
- model_id="mistralai/Mistral-7B-Instruct-v0.2",
178
- api_key=hf_token,
179
- temperature=temperature,
180
- executor_type="local",
181
- verbose=verbose
182
- )
183
- print(f"Using HfApiModel with model_id: mistralai/Mistral-7B-Instruct-v0.2 (fallback)")
184
- else:
185
- raise
186
- else:
187
- # No API keys available, log the error
188
- print("ERROR: No API keys found. Please set at least one of these environment variables:")
189
- print("- HUGGINGFACEHUB_API_TOKEN or HF_API_TOKEN")
190
- print("- OPENAI_API_KEY")
191
- print("- XAI_API_KEY")
192
- self.gaia_agent = None
193
- print("WARNING: No API keys found. Agent will not be able to answer questions.")
194
-
195
- except Exception as e:
196
- print(f"Error initializing GAIAAgent: {e}")
197
- self.gaia_agent = None
198
- print("WARNING: Failed to initialize agent. Falling back to basic responses.")
199
-
200
  def __call__(self, question: str) -> str:
201
  print(f"Agent received question (first 50 chars): {question[:50]}...")
202
-
203
- # Check if we have a functioning GAIA agent
204
- if self.gaia_agent:
205
- try:
206
- # Process the question using the GAIA agent
207
- answer = self.gaia_agent.answer_question(question)
208
- print(f"Agent generated answer: {answer[:50]}..." if len(answer) > 50 else f"Agent generated answer: {answer}")
209
- return answer
210
- except Exception as e:
211
- print(f"Error processing question: {e}")
212
- # Fall back to a simple response on error
213
- return "An error occurred while processing your question. Please check the agent logs for details."
214
- else:
215
- # We don't have a valid agent, provide a basic response
216
- return "The agent is not properly initialized. Please check your API keys and configuration."
217
 
218
  def run_and_submit_all( profile: gr.OAuthProfile | None):
219
  """
@@ -237,12 +45,6 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
237
  # 1. Instantiate Agent ( modify this part to create your agent)
238
  try:
239
  agent = BasicAgent()
240
-
241
- # Check if agent is properly initialized
242
- if not agent.gaia_agent:
243
- print("ERROR: Agent was not properly initialized")
244
- return "ERROR: Agent was not properly initialized. Check the logs for details on missing API keys or configuration.", None
245
-
246
  except Exception as e:
247
  print(f"Error instantiating agent: {e}")
248
  return f"Error initializing agent: {e}", None
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, FinalAnswerTool, LiteLLMModel
 
 
 
 
 
 
 
 
7
 
8
+
9
+ model = LiteLLMModel(model_id="gemini/gemini-2.0-flash-lite", api_key=os.getenv('GEMINI_API_KEY'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  # (Keep Constants as is)
12
  # --- Constants ---
13
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
14
 
15
+
 
16
  class BasicAgent:
17
  def __init__(self):
18
  print("BasicAgent initialized.")
19
+ self.agent = CodeAgent(tools=[DuckDuckGoSearchTool()], model=model)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  def __call__(self, question: str) -> str:
21
  print(f"Agent received question (first 50 chars): {question[:50]}...")
22
+ fixed_answer = self.agent.run(question)
23
+ print(f"Agent returning fixed answer: {fixed_answer}")
24
+ return fixed_answer
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
  def run_and_submit_all( profile: gr.OAuthProfile | None):
27
  """
 
45
  # 1. Instantiate Agent ( modify this part to create your agent)
46
  try:
47
  agent = BasicAgent()
 
 
 
 
 
 
48
  except Exception as e:
49
  print(f"Error instantiating agent: {e}")
50
  return f"Error initializing agent: {e}", None