yoshizen commited on
Commit
3d40110
·
verified ·
1 Parent(s): 064457a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +132 -362
app.py CHANGED
@@ -1,415 +1,185 @@
1
  """
2
- Simplified application file for the GAIA-Ready AI Agent web interface
3
 
4
- This is a standalone version that doesn't depend on memory_system or reasoning_system modules.
5
- It creates and launches a Gradio interface for a basic agent using smolagents directly.
6
  """
7
 
8
  import os
9
  import sys
 
 
10
  import gradio as gr
11
- from typing import Dict, Any, List, Optional
12
-
13
- # Ensure all necessary modules are installed
14
- try:
15
- from smolagents import Agent, InferenceClientModel, Tool
16
- except ImportError:
17
- import subprocess
18
- subprocess.check_call(["pip", "install", "smolagents"])
19
- from smolagents import Agent, InferenceClientModel, Tool
20
-
21
- # Import optimized prompts if available
22
- try:
23
- from optimized_prompts import get_enhanced_system_prompt
24
- USING_OPTIMIZED_PROMPTS = True
25
- except ImportError:
26
- print("Warning: Could not import optimized prompts.")
27
- print("The agent will use default prompts.")
28
- USING_OPTIMIZED_PROMPTS = False
29
 
30
  # Check if running in Hugging Face Spaces
31
  IS_HF_SPACES = os.environ.get("SPACE_ID") is not None
32
 
33
- # Define tool functions
34
- def web_search_function(query: str) -> str:
35
- """
36
- Search the web for information
37
-
38
- Args:
39
- query: Search query
40
-
41
- Returns:
42
- Search results
43
- """
44
- return f"Searching for: {query}\n\nThis is a placeholder for web search results. In a real implementation, this would connect to a search API."
45
-
46
- def web_page_content_function(url: str) -> str:
47
- """
48
- Fetch and extract content from a web page
49
-
50
- Args:
51
- url: URL of the web page
52
-
53
- Returns:
54
- Extracted content
55
- """
56
- return f"Extracting content from: {url}\n\nThis is a placeholder for web page content. In a real implementation, this would fetch and extract content from the URL."
57
-
58
- def calculator_function(expression: str) -> str:
59
- """
60
- Perform mathematical calculations
61
-
62
- Args:
63
- expression: Mathematical expression to evaluate
64
-
65
- Returns:
66
- Result of the calculation
67
- """
68
- try:
69
- result = eval(expression)
70
- return f"Expression: {expression}\nResult: {result}"
71
- except Exception as e:
72
- return f"Error evaluating expression: {str(e)}"
73
-
74
- def image_analyzer_function(image_url: str) -> str:
75
- """
76
- Analyze image content
77
-
78
- Args:
79
- image_url: URL of the image to analyze
80
-
81
- Returns:
82
- Analysis of the image
83
- """
84
- return f"Analyzing image: {image_url}\n\nThis is a placeholder for image analysis. In a real implementation, this would analyze the image content."
85
-
86
- def python_executor_function(code: str) -> str:
87
- """
88
- Execute Python code
89
-
90
- Args:
91
- code: Python code to execute
92
-
93
- Returns:
94
- Result of the code execution
95
- """
96
- try:
97
- # Create a dictionary to capture output
98
- output_capture = {}
99
-
100
- # Redirect stdout to capture print statements
101
- import io
102
- from contextlib import redirect_stdout
103
-
104
- f = io.StringIO()
105
- with redirect_stdout(f):
106
- # Execute the code in a safe environment
107
- exec_globals = {
108
- "__builtins__": __builtins__,
109
- "print": print,
110
- "input": lambda x: x # Mock input function
111
- }
112
- exec(code, exec_globals)
113
-
114
- # Get the captured output
115
- output = f.getvalue()
116
-
117
- return f"Code execution result:\n\n{output}"
118
- except Exception as e:
119
- return f"Error executing code: {str(e)}"
120
-
121
- def text_processor_function(operation: str, text: str) -> str:
122
- """
123
- Process and analyze text
124
-
125
- Args:
126
- operation: Operation to perform (summarize, analyze_sentiment, extract_keywords)
127
- text: Text to process
128
-
129
- Returns:
130
- Processed text
131
- """
132
- if operation == "summarize":
133
- return f"Summary of text: This is a placeholder for text summarization."
134
- elif operation == "analyze_sentiment":
135
- return f"Sentiment analysis: This is a placeholder for sentiment analysis."
136
- elif operation == "extract_keywords":
137
- return f"Keywords: This is a placeholder for keyword extraction."
138
- else:
139
- return f"Unknown operation: {operation}"
140
-
141
- def file_manager_function(operation: str, filename: str, content: str = "") -> str:
142
- """
143
- Save and load data from files
144
-
145
- Args:
146
- operation: Operation to perform (save, load)
147
- filename: Name of the file
148
- content: Content to save (for save operation)
149
-
150
- Returns:
151
- Operation result
152
- """
153
- if operation == "save":
154
- return f"Saved content to {filename}: This is a placeholder for file saving."
155
- elif operation == "load":
156
- return f"Loaded content from {filename}: This is a placeholder for file loading."
157
- else:
158
- return f"Unknown operation: {operation}"
159
-
160
- class SimpleGAIAAgent:
161
  """
162
- Simplified GAIA-Ready AI Agent without memory and reasoning systems
163
  """
164
- def __init__(self, api_key: str = None):
165
  """
166
- Initialize the simplified GAIA agent
167
 
168
  Args:
169
- api_key: API key for Hugging Face Inference API
 
170
  """
171
- # Initialize the LLM model
172
  self.api_key = api_key or os.environ.get("HF_API_KEY", "")
173
- self.model = InferenceClientModel(
174
- model_id="mistralai/Mixtral-8x7B-Instruct-v0.1",
175
- api_key=self.api_key
176
- )
177
-
178
- # Define tools
179
- self.tools = [
180
- Tool(
181
- name="web_search",
182
- description="Search the web for information",
183
- function=web_search_function
184
- ),
185
- Tool(
186
- name="web_page_content",
187
- description="Fetch and extract content from a web page",
188
- function=web_page_content_function
189
- ),
190
- Tool(
191
- name="calculator",
192
- description="Perform mathematical calculations",
193
- function=calculator_function
194
- ),
195
- Tool(
196
- name="image_analyzer",
197
- description="Analyze image content",
198
- function=image_analyzer_function
199
- ),
200
- Tool(
201
- name="python_executor",
202
- description="Execute Python code",
203
- function=python_executor_function
204
- ),
205
- Tool(
206
- name="text_processor",
207
- description="Process and analyze text",
208
- function=text_processor_function
209
- ),
210
- Tool(
211
- name="file_manager",
212
- description="Save and load data from files",
213
- function=file_manager_function
214
- )
215
- ]
216
 
217
  # System prompt
218
- if USING_OPTIMIZED_PROMPTS:
219
- self.system_prompt = get_enhanced_system_prompt("general query")
220
- else:
221
- self.system_prompt = """
222
- You are an advanced AI assistant designed to solve complex tasks from the GAIA benchmark.
223
- You have access to various tools that can help you solve these tasks.
224
-
225
- Always follow the Think-Act-Observe workflow:
226
- 1. Think: Carefully analyze the task and plan your approach
227
- 2. Act: Use appropriate tools to gather information or perform actions
228
- 3. Observe: Analyze the results of your actions and adjust your approach
229
-
230
- Available tools:
231
- - web_search: Search the web for information
232
- - web_page_content: Extract content from specific web pages
233
- - calculator: Perform mathematical calculations
234
- - image_analyzer: Analyze image content
235
- - python_executor: Run Python code for complex operations
236
- - text_processor: Process and analyze text (summarize, analyze_sentiment, extract_keywords)
237
- - file_manager: Save and load data from files (save, load)
238
-
239
- For complex tasks:
240
- - Break them down into smaller, manageable steps
241
- - Keep track of your progress and intermediate results
242
- - Verify each step before moving to the next
243
- - Always double-check your final answer
244
-
245
- Always verify your answers before submitting them.
246
  """
247
-
248
- # Initialize the agent
249
- self.agent = Agent(
250
- model=self.model,
251
- tools=self.tools,
252
- system_prompt=self.system_prompt
253
- )
254
-
255
- def solve(self, query: str) -> str:
256
  """
257
- Solve a task using the agent
258
 
259
  Args:
260
- query: The user's query or task
261
 
262
  Returns:
263
- Agent's response
264
  """
265
  try:
266
- # Process the query
267
- response = self.agent.chat(query)
268
- return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
269
  except Exception as e:
270
- error_msg = f"Error solving task: {str(e)}"
271
- print(error_msg)
272
- return f"I'm sorry, I encountered an error while solving this task: {str(e)}"
273
 
274
 
275
- class AgentApp:
276
  """
277
- Gradio application for the GAIA-Ready AI Agent
 
 
 
278
  """
279
- def __init__(self):
280
- """
281
- Initialize the agent application
282
- """
283
- self.agent = None
284
- self.api_key = os.environ.get("HF_API_KEY", "")
285
-
286
- # Initialize the interface
287
- self.interface = self._create_interface()
288
 
289
- def _initialize_agent(self, api_key: str = "") -> str:
290
  """
291
- Initialize the agent with the provided API key
292
 
293
  Args:
294
- api_key: Hugging Face API key
295
-
 
296
  Returns:
297
- Initialization status message
298
  """
 
299
  if api_key:
300
- self.api_key = api_key
 
301
 
302
- try:
303
- self.agent = SimpleGAIAAgent(api_key=self.api_key)
304
- return "Agent initialized successfully!"
305
- except Exception as e:
306
- return f"Error initializing agent: {str(e)}"
 
307
 
308
- def _process_query(self, query: str, api_key: str = "") -> str:
309
- """
310
- Process a user query with the agent
 
 
 
 
 
 
 
 
 
 
311
 
312
- Args:
313
- query: The user's query
314
- api_key: Hugging Face API key (optional)
315
-
316
- Returns:
317
- Agent's response
318
- """
319
- # Initialize agent if not already initialized or if API key changed
320
- if self.agent is None or (api_key and api_key != self.api_key):
321
- init_message = self._initialize_agent(api_key)
322
- if "Error" in init_message:
323
- return init_message
324
 
325
- try:
326
- # Process the query
327
- return self.agent.solve(query)
328
- except Exception as e:
329
- error_message = f"Error processing query: {str(e)}"
330
- print(error_message)
331
- return error_message
332
-
333
- def _create_interface(self) -> gr.Blocks:
334
- """
335
- Create the Gradio interface
336
 
337
- Returns:
338
- Gradio Blocks interface
339
- """
340
- with gr.Blocks(title="GAIA-Ready AI Agent") as interface:
341
- gr.Markdown("# GAIA-Ready AI Agent")
342
- gr.Markdown("""
343
- This AI agent is designed to excel at the GAIA benchmark from the Hugging Face Agents Course.
344
- It implements the Think-Act-Observe workflow and includes tools for web search, calculation,
345
- image analysis, and code execution.
346
-
347
- Enter your query below and the agent will solve it step by step.
348
- """)
349
-
350
- api_key_input = gr.Textbox(
351
- label="Hugging Face API Key (optional)",
352
- placeholder="Enter your Hugging Face API key here...",
353
- type="password"
354
- )
355
-
356
- query_input = gr.Textbox(
357
- label="Your Query",
358
- placeholder="Enter your query here...",
359
- lines=3
360
- )
361
-
362
- submit_button = gr.Button("Submit")
363
-
364
- response_output = gr.Textbox(
365
- label="Agent Response",
366
- lines=15
367
- )
368
-
369
- # Sample queries
370
- gr.Markdown("### Sample Queries")
371
- sample_queries = [
372
- "What is the capital of France and what is its population? Also, calculate 15% of this population.",
373
- "Write a Python function to calculate the factorial of a number, then use it to find the factorial of 5.",
374
- "Compare and contrast renewable and non-renewable energy sources.",
375
- "Analyze this image: https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/800px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg"
376
- ]
377
-
378
- for query in sample_queries:
379
- sample_button = gr.Button(f"Try: {query[:50]}..." if len(query) > 50 else f"Try: {query}")
380
- sample_button.click(
381
- fn=lambda q=query: q,
382
- outputs=query_input
383
- )
384
-
385
- # Set up event handlers
386
- submit_button.click(
387
- fn=self._process_query,
388
- inputs=[query_input, api_key_input],
389
- outputs=response_output
390
- )
391
-
392
- # Add examples
393
- gr.Examples(
394
- examples=sample_queries,
395
- inputs=query_input
396
  )
397
 
398
- return interface
399
-
400
- def launch(self, share: bool = False) -> None:
401
- """
402
- Launch the Gradio interface
 
403
 
404
- Args:
405
- share: Whether to create a public link
406
- """
407
- self.interface.launch(share=share)
 
 
 
408
 
409
 
410
- # Create and launch the agent app
411
- app = AgentApp()
412
- interface = app.interface
413
 
414
  # For Hugging Face Spaces
415
  if __name__ == "__main__":
 
1
  """
2
+ Minimal Gradio interface for a simple AI assistant without smolagents
3
 
4
+ This is a standalone version that uses only Hugging Face Inference API directly.
5
+ It creates a simple Gradio interface for text generation.
6
  """
7
 
8
  import os
9
  import sys
10
+ import json
11
+ import requests
12
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  # Check if running in Hugging Face Spaces
15
  IS_HF_SPACES = os.environ.get("SPACE_ID") is not None
16
 
17
+ class MinimalAIAssistant:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  """
19
+ Minimal AI Assistant using Hugging Face Inference API directly
20
  """
21
+ def __init__(self, api_key=None, model_id="mistralai/Mixtral-8x7B-Instruct-v0.1"):
22
  """
23
+ Initialize the minimal AI assistant
24
 
25
  Args:
26
+ api_key: Hugging Face API key
27
+ model_id: Model ID to use
28
  """
 
29
  self.api_key = api_key or os.environ.get("HF_API_KEY", "")
30
+ self.model_id = model_id
31
+ self.api_url = f"https://api-inference.huggingface.co/models/{model_id}"
32
+ self.headers = {"Authorization": f"Bearer {self.api_key}"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
  # System prompt
35
+ self.system_prompt = """
36
+ You are an advanced AI assistant designed to help with various tasks.
37
+ You can answer questions, provide information, and assist with problem-solving.
38
+ Always be helpful, accurate, and concise in your responses.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  """
40
+
41
+ def query(self, prompt):
 
 
 
 
 
 
 
42
  """
43
+ Query the model with a prompt
44
 
45
  Args:
46
+ prompt: User prompt
47
 
48
  Returns:
49
+ Model response
50
  """
51
  try:
52
+ # Format the prompt with system message
53
+ formatted_prompt = f"{self.system_prompt}\n\nUser: {prompt}\n\nAssistant:"
54
+
55
+ # Prepare the payload
56
+ payload = {
57
+ "inputs": formatted_prompt,
58
+ "parameters": {
59
+ "max_new_tokens": 1024,
60
+ "temperature": 0.7,
61
+ "top_p": 0.95,
62
+ "do_sample": True
63
+ }
64
+ }
65
+
66
+ # Make the API request
67
+ response = requests.post(self.api_url, headers=self.headers, json=payload)
68
+
69
+ # Check for errors
70
+ if response.status_code != 200:
71
+ return f"Error: API returned status code {response.status_code}. {response.text}"
72
+
73
+ # Parse the response
74
+ result = response.json()
75
+
76
+ # Extract the generated text
77
+ if isinstance(result, list) and len(result) > 0:
78
+ generated_text = result[0].get("generated_text", "")
79
+ # Remove the prompt from the response
80
+ if generated_text.startswith(formatted_prompt):
81
+ generated_text = generated_text[len(formatted_prompt):].strip()
82
+ return generated_text
83
+ else:
84
+ return "Error: Unexpected response format from API"
85
+
86
  except Exception as e:
87
+ return f"Error querying model: {str(e)}"
 
 
88
 
89
 
90
+ def create_gradio_interface():
91
  """
92
+ Create a Gradio interface for the minimal AI assistant
93
+
94
+ Returns:
95
+ Gradio interface
96
  """
97
+ # Initialize the assistant
98
+ assistant = MinimalAIAssistant()
 
 
 
 
 
 
 
99
 
100
+ def process_query(query, api_key=""):
101
  """
102
+ Process a user query
103
 
104
  Args:
105
+ query: User query
106
+ api_key: Hugging Face API key (optional)
107
+
108
  Returns:
109
+ Assistant's response
110
  """
111
+ # Update API key if provided
112
  if api_key:
113
+ assistant.api_key = api_key
114
+ assistant.headers = {"Authorization": f"Bearer {api_key}"}
115
 
116
+ # Check if API key is set
117
+ if not assistant.api_key:
118
+ return "Error: No API key provided. Please enter your Hugging Face API key."
119
+
120
+ # Process the query
121
+ return assistant.query(query)
122
 
123
+ # Create the interface
124
+ with gr.Blocks(title="Minimal AI Assistant") as interface:
125
+ gr.Markdown("# Minimal AI Assistant")
126
+ gr.Markdown("""
127
+ This is a minimal AI assistant using the Hugging Face Inference API.
128
+ Enter your query below and the assistant will respond.
129
+ """)
130
+
131
+ api_key_input = gr.Textbox(
132
+ label="Hugging Face API Key",
133
+ placeholder="Enter your Hugging Face API key here...",
134
+ type="password"
135
+ )
136
 
137
+ query_input = gr.Textbox(
138
+ label="Your Query",
139
+ placeholder="Enter your query here...",
140
+ lines=3
141
+ )
 
 
 
 
 
 
 
142
 
143
+ submit_button = gr.Button("Submit")
 
 
 
 
 
 
 
 
 
 
144
 
145
+ response_output = gr.Textbox(
146
+ label="Assistant Response",
147
+ lines=15
148
+ )
149
+
150
+ # Sample queries
151
+ gr.Markdown("### Sample Queries")
152
+ sample_queries = [
153
+ "What is the capital of France?",
154
+ "Explain the concept of machine learning in simple terms.",
155
+ "Write a short poem about artificial intelligence."
156
+ ]
157
+
158
+ for query in sample_queries:
159
+ sample_button = gr.Button(f"Try: {query}")
160
+ sample_button.click(
161
+ fn=lambda q=query: q,
162
+ outputs=query_input
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  )
164
 
165
+ # Set up event handlers
166
+ submit_button.click(
167
+ fn=process_query,
168
+ inputs=[query_input, api_key_input],
169
+ outputs=response_output
170
+ )
171
 
172
+ # Add examples
173
+ gr.Examples(
174
+ examples=sample_queries,
175
+ inputs=query_input
176
+ )
177
+
178
+ return interface
179
 
180
 
181
+ # Create and launch the interface
182
+ interface = create_gradio_interface()
 
183
 
184
  # For Hugging Face Spaces
185
  if __name__ == "__main__":