murphynetworks commited on
Commit
c288490
·
1 Parent(s): 8e01d85

Add direct agent implementation with tool support

Browse files

- Implemented DirectAgent class with tool-calling capabilities
- Added web search, web browsing, file reading, calculation, and Excel analysis tools
- Implemented API testing and integration scripts
- Added retry logic for API rate limiting
- Added proper file attachment handling

direct_agent_fixed.py ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import os
3
+ import json
4
+ import time
5
+ import requests
6
+ import pandas as pd
7
+ from openai import OpenAI
8
+ from bs4 import BeautifulSoup
9
+ from dotenv import load_dotenv
10
+
11
+ # Load environment variables
12
+ load_dotenv()
13
+
14
+ class WebSearchTool:
15
+ def run(self, query):
16
+ try:
17
+ # Use a search engine API to get results
18
+ response = requests.get(
19
+ f"https://www.google.com/search?q={query}",
20
+ headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"}
21
+ )
22
+ response.raise_for_status()
23
+
24
+ soup = BeautifulSoup(response.text, 'html.parser')
25
+ search_results = []
26
+
27
+ # Extract search results
28
+ for result in soup.select(".tF2Cxc"):
29
+ title = result.select_one(".DKV0Md").text if result.select_one(".DKV0Md") else ""
30
+ link = result.select_one("a")["href"] if result.select_one("a") else ""
31
+ snippet = result.select_one(".VwiC3b").text if result.select_one(".VwiC3b") else ""
32
+
33
+ if title and link:
34
+ search_results.append({
35
+ "title": title,
36
+ "link": link,
37
+ "snippet": snippet
38
+ })
39
+
40
+ # Format results into a readable string
41
+ if search_results:
42
+ formatted_results = "\n\n".join([
43
+ f"Title: {r['title']}\nURL: {r['link']}\nSnippet: {r['snippet']}"
44
+ for r in search_results[:5] # Limit to top 5 results
45
+ ])
46
+ return f"Search results for '{query}':\n\n{formatted_results}"
47
+ else:
48
+ return f"No results found for '{query}'."
49
+
50
+ except Exception as e:
51
+ return f"Error searching the web: {str(e)}"
52
+
53
+ class WebBrowseTool:
54
+ def run(self, url):
55
+ try:
56
+ headers = {
57
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"
58
+ }
59
+ response = requests.get(url, headers=headers, timeout=10)
60
+ response.raise_for_status()
61
+
62
+ soup = BeautifulSoup(response.text, 'html.parser')
63
+
64
+ # Remove script and style elements
65
+ for script in soup(["script", "style"]):
66
+ script.extract()
67
+
68
+ # Get text
69
+ text = soup.get_text()
70
+
71
+ # Clean up text: break into lines and remove leading and trailing space
72
+ lines = (line.strip() for line in text.splitlines())
73
+ chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
74
+ text = '\n'.join(chunk for chunk in chunks if chunk)
75
+
76
+ # Limit text length to avoid LLM context limitations
77
+ if len(text) > 8000:
78
+ text = text[:8000] + "...\n[Content truncated due to length]"
79
+
80
+ return f"Content from {url}:\n\n{text}"
81
+
82
+ except Exception as e:
83
+ return f"Error accessing {url}: {str(e)}"
84
+
85
+ class ReadFileTool:
86
+ def run(self, file_path):
87
+ try:
88
+ if not os.path.exists(file_path):
89
+ return f"Error: File not found at {file_path}"
90
+
91
+ with open(file_path, 'rb') as f:
92
+ content = f.read()
93
+
94
+ # Try to decode as text
95
+ try:
96
+ text_content = content.decode('utf-8')
97
+ return f"Content of {file_path}:\n\n{text_content}"
98
+ except UnicodeDecodeError:
99
+ # If it's not text, just return info about the binary file
100
+ return f"Binary file {file_path}, size: {len(content)} bytes"
101
+
102
+ except Exception as e:
103
+ return f"Error reading file: {str(e)}"
104
+
105
+ class CalculateTool:
106
+ def run(self, expression):
107
+ try:
108
+ # Be very careful with eval - in production this should be replaced with a safer alternative
109
+ result = eval(expression, {"__builtins__": {}})
110
+ return f"Result: {result}"
111
+ except Exception as e:
112
+ return f"Error calculating '{expression}': {str(e)}"
113
+
114
+ class AnalyzeExcelTool:
115
+ def run(self, file_path, query):
116
+ try:
117
+ if not os.path.exists(file_path):
118
+ return f"Error: File not found at {file_path}"
119
+
120
+ # Read the Excel file
121
+ try:
122
+ df = pd.read_excel(file_path)
123
+ except Exception as e:
124
+ # Try with different engine if default fails
125
+ try:
126
+ df = pd.read_excel(file_path, engine='openpyxl')
127
+ except Exception as e2:
128
+ try:
129
+ df = pd.read_excel(file_path, engine='xlrd')
130
+ except Exception as e3:
131
+ return f"Error reading Excel file: {str(e)}, {str(e2)}, {str(e3)}"
132
+
133
+ # Basic info about the Excel file
134
+ file_info = f"Excel file contains {len(df.columns)} columns and {len(df)} rows.\n"
135
+ file_info += f"Columns: {', '.join(df.columns.tolist())}\n"
136
+
137
+ # Sample of the data
138
+ sample = df.head(5).to_string()
139
+
140
+ # Try to answer specific query about the data
141
+ query_lower = query.lower()
142
+
143
+ # Handle sum queries
144
+ if "sum" in query_lower or "total" in query_lower:
145
+ # Try to identify which column(s) to sum based on the query
146
+ numeric_cols = df.select_dtypes(include=['number']).columns.tolist()
147
+
148
+ column_sums = {}
149
+ for col in numeric_cols:
150
+ column_sums[col] = df[col].sum()
151
+
152
+ sums_info = "Sum of numeric columns:\n"
153
+ for col, total in column_sums.items():
154
+ sums_info += f"Sum of {col}: {total}\n"
155
+
156
+ return f"{file_info}\n\n{sample}\n\n{sums_info}"
157
+
158
+ # Handle filter queries
159
+ elif "filter" in query_lower or "where" in query_lower or "only" in query_lower:
160
+ # This is a simple example - in a real implementation,
161
+ # you would use NLP to understand the filter conditions
162
+ filter_info = "To filter data, please specify the exact column and condition."
163
+ return f"{file_info}\n\n{sample}\n\n{filter_info}"
164
+
165
+ # Default response with file overview
166
+ else:
167
+ return f"{file_info}\n\nSample data:\n{sample}"
168
+
169
+ except Exception as e:
170
+ return f"Error analyzing Excel file: {str(e)}"
171
+
172
+ class DirectAgent:
173
+ def __init__(self, openrouter_api_key=None, model=None):
174
+ self.api_key = openrouter_api_key or os.getenv("OPENROUTER_API_KEY")
175
+ self.model = model or os.getenv("OPENROUTER_MODEL", "anthropic/claude-3-5-sonnet")
176
+
177
+ if not self.api_key:
178
+ raise ValueError("OpenRouter API key not provided and OPENROUTER_API_KEY not set in environment variables.")
179
+
180
+ # Initialize client
181
+ self.client = OpenAI(
182
+ base_url="https://openrouter.ai/api/v1",
183
+ api_key=self.api_key,
184
+ default_headers={
185
+ "HTTP-Referer": "https://github.com/neuralconfig/agents-course",
186
+ "X-Title": "Agent Evaluation"
187
+ }
188
+ )
189
+
190
+ # Initialize tools
191
+ self.tools = {
192
+ "web_search": WebSearchTool(),
193
+ "web_browse": WebBrowseTool(),
194
+ "read_file": ReadFileTool(),
195
+ "calculate": CalculateTool(),
196
+ "analyze_excel": AnalyzeExcelTool()
197
+ }
198
+
199
+ # Tool descriptions for the LLM
200
+ self.tool_descriptions = [
201
+ {
202
+ "type": "function",
203
+ "function": {
204
+ "name": "web_search",
205
+ "description": "Search the web for information on a given query.",
206
+ "parameters": {
207
+ "type": "object",
208
+ "properties": {
209
+ "query": {
210
+ "type": "string",
211
+ "description": "The search query"
212
+ }
213
+ },
214
+ "required": ["query"]
215
+ }
216
+ }
217
+ },
218
+ {
219
+ "type": "function",
220
+ "function": {
221
+ "name": "web_browse",
222
+ "description": "Visit a webpage and extract its content.",
223
+ "parameters": {
224
+ "type": "object",
225
+ "properties": {
226
+ "url": {
227
+ "type": "string",
228
+ "description": "The URL of the webpage to visit"
229
+ }
230
+ },
231
+ "required": ["url"]
232
+ }
233
+ }
234
+ },
235
+ {
236
+ "type": "function",
237
+ "function": {
238
+ "name": "read_file",
239
+ "description": "Read the content of a file.",
240
+ "parameters": {
241
+ "type": "object",
242
+ "properties": {
243
+ "file_path": {
244
+ "type": "string",
245
+ "description": "The path to the file to read"
246
+ }
247
+ },
248
+ "required": ["file_path"]
249
+ }
250
+ }
251
+ },
252
+ {
253
+ "type": "function",
254
+ "function": {
255
+ "name": "calculate",
256
+ "description": "Perform a calculation.",
257
+ "parameters": {
258
+ "type": "object",
259
+ "properties": {
260
+ "expression": {
261
+ "type": "string",
262
+ "description": "Mathematical expression to evaluate"
263
+ }
264
+ },
265
+ "required": ["expression"]
266
+ }
267
+ }
268
+ },
269
+ {
270
+ "type": "function",
271
+ "function": {
272
+ "name": "analyze_excel",
273
+ "description": "Analyze an Excel file and extract data.",
274
+ "parameters": {
275
+ "type": "object",
276
+ "properties": {
277
+ "file_path": {
278
+ "type": "string",
279
+ "description": "Path to the Excel file"
280
+ },
281
+ "query": {
282
+ "type": "string",
283
+ "description": "What analysis to perform on the data"
284
+ }
285
+ },
286
+ "required": ["file_path", "query"]
287
+ }
288
+ }
289
+ }
290
+ ]
291
+
292
+ # System message
293
+ self.system_message = """You are a helpful AI assistant designed to answer questions accurately.
294
+
295
+ When presented with a question:
296
+ 1. Think carefully about what is being asked
297
+ 2. Use the provided tools when necessary to gather accurate information
298
+ 3. Provide clear, concise answers based on the information available
299
+ 4. Always present your final answer directly without adding 'FINAL ANSWER:' or similar phrases
300
+ 5. If you use research or external information, incorporate it naturally into your response
301
+
302
+ Be precise and focus only on answering the question asked. Do not add disclaimers, avoid hallucinating information, and acknowledge when you don't know something."""
303
+
304
+ def _handle_tool_call(self, tool_calls):
305
+ results = []
306
+
307
+ for tool_call in tool_calls:
308
+ function_name = tool_call.function.name
309
+
310
+ try:
311
+ function_args = json.loads(tool_call.function.arguments)
312
+ except Exception as e:
313
+ results.append({
314
+ "tool_call_id": tool_call.id,
315
+ "function_name": function_name,
316
+ "result": f"Error parsing arguments: {str(e)}"
317
+ })
318
+ continue
319
+
320
+ if function_name in self.tools:
321
+ try:
322
+ # Call the appropriate tool with the arguments
323
+ if function_name == "analyze_excel":
324
+ result = self.tools[function_name].run(
325
+ function_args.get("file_path", ""),
326
+ function_args.get("query", "")
327
+ )
328
+ else:
329
+ # For all other tools, just pass the first argument
330
+ first_arg = list(function_args.values())[0] if function_args else ""
331
+ result = self.tools[function_name].run(first_arg)
332
+
333
+ results.append({
334
+ "tool_call_id": tool_call.id,
335
+ "function_name": function_name,
336
+ "result": result
337
+ })
338
+ except Exception as e:
339
+ results.append({
340
+ "tool_call_id": tool_call.id,
341
+ "function_name": function_name,
342
+ "result": f"Error executing tool {function_name}: {str(e)}"
343
+ })
344
+ else:
345
+ results.append({
346
+ "tool_call_id": tool_call.id,
347
+ "function_name": function_name,
348
+ "result": f"Tool {function_name} not found"
349
+ })
350
+
351
+ return results
352
+
353
+ def _call_openrouter_with_retry(self, messages, max_retries=5):
354
+ """Call the OpenRouter API with retry logic for rate limits."""
355
+ retry_count = 0
356
+ base_delay = 2 # Start with a 2-second delay
357
+
358
+ while retry_count < max_retries:
359
+ try:
360
+ # Call the API
361
+ response = self.client.chat.completions.create(
362
+ model=self.model,
363
+ messages=messages,
364
+ tools=self.tool_descriptions,
365
+ tool_choice="auto"
366
+ )
367
+
368
+ # Check for error object directly in the response
369
+ if hasattr(response, 'error') and response.error:
370
+ error_code = response.error.get('code')
371
+ error_msg = response.error.get('message', '')
372
+
373
+ # If it's a rate limit error, retry
374
+ if error_code == 429 or "rate limit" in error_msg.lower():
375
+ retry_count += 1
376
+ delay = base_delay * (2 ** retry_count) # Exponential backoff
377
+ print(f"Rate limit hit. Retrying in {delay} seconds...")
378
+ time.sleep(delay)
379
+ continue
380
+
381
+ # If we got a valid response, return it
382
+ return response
383
+
384
+ except Exception as e:
385
+ error_msg = str(e).lower()
386
+
387
+ # If it's a rate limit error, retry
388
+ if "429" in error_msg or "rate limit" in error_msg:
389
+ retry_count += 1
390
+ delay = base_delay * (2 ** retry_count) # Exponential backoff
391
+ print(f"Rate limit hit. Retrying in {delay} seconds...")
392
+ time.sleep(delay)
393
+ else:
394
+ # For other errors, raise immediately
395
+ raise
396
+
397
+ # If we've exhausted retries, raise an exception
398
+ raise Exception(f"Failed after {max_retries} retries due to rate limits")
399
+
400
+ def __call__(self, question, context=None):
401
+ """Run the agent on a question and return the answer."""
402
+ # Add context about any files if provided
403
+ if context and "file_path" in context:
404
+ question += f"\n\nAttached file information: {context.get('file_name', '')}"
405
+ question += f"\nYou can access this file using the read_file tool with the path: {context.get('file_path')}"
406
+
407
+ messages = [
408
+ {"role": "system", "content": self.system_message},
409
+ {"role": "user", "content": question}
410
+ ]
411
+
412
+ max_steps = 5 # Limit the number of iterations for safety
413
+
414
+ for step in range(max_steps):
415
+ print(f"Step {step+1}/{max_steps}")
416
+
417
+ try:
418
+ # Call the API with retry logic
419
+ response = self._call_openrouter_with_retry(messages)
420
+
421
+ # Debug info
422
+ print(f"Response received, type: {type(response)}")
423
+
424
+ # Get the response message - with improved error handling
425
+ if not hasattr(response, 'choices') or not response.choices:
426
+ print("Error: No choices in response")
427
+ print(f"Full response: {response}")
428
+ return "Error: Invalid response from OpenRouter API - no choices returned"
429
+
430
+ # Check if response.choices[0] exists and has a message
431
+ if len(response.choices) == 0 or not hasattr(response.choices[0], 'message'):
432
+ print("Error: No message in first choice")
433
+ print(f"Full response: {response}")
434
+ return "Error: Invalid response from OpenRouter API - no message in first choice"
435
+
436
+ message = response.choices[0].message
437
+ messages.append(message)
438
+
439
+ # Check if there are tool calls
440
+ if hasattr(message, 'tool_calls') and message.tool_calls:
441
+ print(f"Tool calls detected: {len(message.tool_calls)}")
442
+
443
+ # Execute the tool calls
444
+ tool_results = self._handle_tool_call(message.tool_calls)
445
+
446
+ # Add the tool results to the messages
447
+ for result in tool_results:
448
+ tool_message = {
449
+ "role": "tool",
450
+ "tool_call_id": result["tool_call_id"],
451
+ "content": result["result"]
452
+ }
453
+ messages.append(tool_message)
454
+ print(f"Tool {result['function_name']} executed")
455
+ else:
456
+ # No more tool calls, we have the final answer
457
+ if not hasattr(message, 'content'):
458
+ print("Error: Message has no content attribute")
459
+ return "Error: Invalid response from OpenRouter API - message has no content"
460
+
461
+ return message.content
462
+
463
+ except Exception as e:
464
+ print(f"Error in step {step+1}: {str(e)}")
465
+
466
+ # Try to recover and continue with what we have
467
+ if messages and len(messages) > 2:
468
+ last_message = messages[-1]
469
+ if isinstance(last_message, dict) and 'content' in last_message:
470
+ return f"Encountered an error but got partial response: {last_message['content']}"
471
+ elif hasattr(last_message, 'content') and last_message.content:
472
+ return f"Encountered an error but got partial response: {last_message.content}"
473
+
474
+ return f"Error during processing: {str(e)}"
475
+
476
+ # If we've reached the maximum number of steps, return the last message
477
+ if messages and len(messages) > 1:
478
+ last_message = messages[-1]
479
+ if isinstance(last_message, dict) and 'content' in last_message:
480
+ return last_message['content']
481
+ elif hasattr(last_message, 'content') and last_message.content:
482
+ return last_message.content
483
+
484
+ return "Error: Reached maximum steps without getting a final answer"
485
+
486
+ # Test code
487
+ if __name__ == "__main__":
488
+ # Get model from environment variables or default to Claude
489
+ model = os.getenv("OPENROUTER_MODEL", "anthropic/claude-3-5-sonnet")
490
+ print(f"\n=== Testing with model from .env: {model} ===\n")
491
+
492
+ # Create the agent with the model from .env
493
+ agent = DirectAgent()
494
+
495
+ # Test questions
496
+ questions = [
497
+ "What is the capital of France?",
498
+ "What is 25 * 4 + 10?",
499
+ "What is the largest mammal on Earth?"
500
+ ]
501
+
502
+ # Test each question
503
+ for question in questions:
504
+ print(f"\nQuestion: {question}")
505
+ try:
506
+ answer = agent(question)
507
+ print(f"\nAnswer: {answer}")
508
+ except Exception as e:
509
+ print(f"\nError: {str(e)}")
510
+
511
+ print("\n=== Testing complete ===")
direct_integration.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Integration script that connects our DirectAgent to the app.py submission system.
4
+ """
5
+ import os
6
+ import json
7
+ import requests
8
+ import tempfile
9
+ from pathlib import Path
10
+ import gradio as gr
11
+ from direct_agent_fixed import DirectAgent
12
+ from dotenv import load_dotenv
13
+
14
+ # Load environment variables
15
+ load_dotenv()
16
+
17
+ # URLs for the evaluation API
18
+ QUESTIONS_URL = "https://agents-course-unit4-scoring.hf.space/questions"
19
+ SUBMIT_URL = "https://agents-course-unit4-scoring.hf.space/submit"
20
+
21
+ # Username and code link for submission
22
+ USERNAME = os.getenv("USERNAME", "YOUR_USERNAME_HERE")
23
+ CODE_LINK = os.getenv("CODE_LINK", "YOUR_CODE_LINK_HERE")
24
+
25
+ def download_file(url, task_id):
26
+ """Download a file from a URL and save it to a temporary location."""
27
+ try:
28
+ response = requests.get(url)
29
+ response.raise_for_status()
30
+
31
+ # Create a temporary file with the right extension
32
+ file_extension = Path(url).suffix.lower()
33
+
34
+ # If no extension or weird extension, try to guess from content-type
35
+ if not file_extension:
36
+ content_type = response.headers.get('content-type', '')
37
+ if 'excel' in content_type or 'spreadsheet' in content_type:
38
+ file_extension = '.xlsx'
39
+ elif 'csv' in content_type:
40
+ file_extension = '.csv'
41
+
42
+ # Create temporary file with correct extension
43
+ with tempfile.NamedTemporaryFile(delete=False, suffix=file_extension) as temp_file:
44
+ temp_file.write(response.content)
45
+ temp_file_path = temp_file.name
46
+
47
+ # Get the original filename from the URL
48
+ filename = Path(url).name
49
+
50
+ return {
51
+ "file_path": temp_file_path,
52
+ "file_name": filename,
53
+ "task_id": task_id
54
+ }
55
+
56
+ except Exception as e:
57
+ return {"error": f"Error downloading file: {str(e)}"}
58
+
59
+ def fetch_questions():
60
+ """Fetch questions from the evaluation API."""
61
+ try:
62
+ response = requests.get(QUESTIONS_URL)
63
+ response.raise_for_status()
64
+ questions = response.json()
65
+ # Check if the response is a list (as expected) or something else
66
+ if not isinstance(questions, list):
67
+ return {"error": f"Unexpected API response format: {questions}"}
68
+ return questions
69
+ except Exception as e:
70
+ return {"error": f"Error fetching questions: {str(e)}"}
71
+
72
+ def run_agent_on_questions(questions):
73
+ """Run the agent on each question and collect answers."""
74
+ agent = DirectAgent()
75
+ answers = []
76
+
77
+ for i, question in enumerate(questions):
78
+ task_id = question["task_id"]
79
+ question_text = question["question"]
80
+ print(f"\nProcessing question {i+1}/{len(questions)} (Task ID: {task_id})")
81
+
82
+ # Check if there's a file URL
83
+ file_context = None
84
+ if "file_url" in question and question["file_url"]:
85
+ file_info = download_file(question["file_url"], task_id)
86
+ if "error" not in file_info:
87
+ file_context = file_info
88
+ print(f"Downloaded file: {file_info['file_name']}")
89
+
90
+ # Run the agent on the question
91
+ try:
92
+ answer = agent(question_text, context=file_context)
93
+ print(f"Answer: {answer[:100]}..." if len(answer) > 100 else f"Answer: {answer}")
94
+
95
+ answers.append({
96
+ "task_id": task_id,
97
+ "submitted_answer": answer
98
+ })
99
+
100
+ # Clean up any temporary files
101
+ if file_context and "file_path" in file_context:
102
+ try:
103
+ os.unlink(file_context["file_path"])
104
+ except:
105
+ pass
106
+
107
+ except Exception as e:
108
+ print(f"Error running agent on question {task_id}: {str(e)}")
109
+ # Still add the error message as the answer
110
+ answers.append({
111
+ "task_id": task_id,
112
+ "submitted_answer": f"Error generating answer: {str(e)}"
113
+ })
114
+
115
+ return answers
116
+
117
+ def submit_answers(answers):
118
+ """Submit answers to the evaluation API."""
119
+ try:
120
+ submission = {
121
+ "username": USERNAME,
122
+ "agent_code": CODE_LINK,
123
+ "answers": answers
124
+ }
125
+
126
+ response = requests.post(SUBMIT_URL, json=submission)
127
+ response.raise_for_status()
128
+ return response.json()
129
+ except Exception as e:
130
+ return {"error": f"Error submitting answers: {str(e)}"}
131
+
132
+ def run_full_evaluation():
133
+ """Run the full evaluation process: fetch questions, run agent, submit answers."""
134
+ # 1. Fetch questions
135
+ print("Fetching questions...")
136
+ questions = fetch_questions()
137
+
138
+ if isinstance(questions, dict) and "error" in questions:
139
+ return questions["error"]
140
+
141
+ print(f"Received {len(questions)} questions")
142
+
143
+ # 2. Run agent on questions
144
+ print("\nRunning agent on questions...")
145
+ answers = run_agent_on_questions(questions)
146
+
147
+ # 3. Submit answers
148
+ print("\nSubmitting answers...")
149
+ submission_response = submit_answers(answers)
150
+
151
+ if "error" in submission_response:
152
+ return submission_response["error"]
153
+
154
+ # 4. Return result
155
+ return submission_response
156
+
157
+ def create_interface():
158
+ """Create a Gradio interface for running the evaluation."""
159
+ with gr.Blocks() as interface:
160
+ gr.Markdown("# Agent Evaluation Interface")
161
+
162
+ with gr.Row():
163
+ username_input = gr.Textbox(label="Username", value=USERNAME)
164
+ code_link_input = gr.Textbox(label="Code Link", value=CODE_LINK)
165
+
166
+ with gr.Row():
167
+ run_button = gr.Button("Run Evaluation")
168
+ status = gr.Textbox(label="Status")
169
+
170
+ with gr.Row():
171
+ results = gr.JSON(label="Results")
172
+
173
+ def update_env_and_run(username, code_link):
174
+ global USERNAME, CODE_LINK
175
+ USERNAME = username
176
+ CODE_LINK = code_link
177
+
178
+ return "Running evaluation...", None
179
+
180
+ def run_evaluation():
181
+ result = run_full_evaluation()
182
+ return "Evaluation complete", result
183
+
184
+ run_button.click(
185
+ fn=update_env_and_run,
186
+ inputs=[username_input, code_link_input],
187
+ outputs=[status, results]
188
+ ).then(
189
+ fn=run_evaluation,
190
+ inputs=None,
191
+ outputs=[status, results]
192
+ )
193
+
194
+ return interface
195
+
196
+ if __name__ == "__main__":
197
+ # Check if we should run with UI or headless
198
+ import sys
199
+
200
+ if len(sys.argv) > 1 and sys.argv[1] == "--headless":
201
+ # Run in headless mode (just run the evaluation)
202
+ print("Running in headless mode")
203
+ result = run_full_evaluation()
204
+ print("\nFinal result:")
205
+ print(json.dumps(result, indent=2))
206
+ else:
207
+ # Run with the UI
208
+ interface = create_interface()
209
+ interface.launch(share=False)
test_api_question.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Script to fetch a question from the evaluation API and test it with our agent.
4
+ """
5
+ import os
6
+ import json
7
+ import requests
8
+ import argparse
9
+ from test_question import test_question_with_file
10
+ from dotenv import load_dotenv
11
+
12
+ # Load environment variables
13
+ load_dotenv()
14
+
15
+ # URL for the evaluation API
16
+ QUESTIONS_URL = "https://agents-course-unit4-scoring.hf.space/questions"
17
+
18
+ def fetch_questions():
19
+ """Fetch questions from the evaluation API."""
20
+ try:
21
+ response = requests.get(QUESTIONS_URL)
22
+ response.raise_for_status()
23
+ questions = response.json()
24
+ # Check if the response is a list (as expected) or something else
25
+ if not isinstance(questions, list):
26
+ return {"error": f"Unexpected API response format: {questions}"}
27
+ return questions
28
+ except Exception as e:
29
+ return {"error": f"Error fetching questions: {str(e)}"}
30
+
31
+ def list_questions():
32
+ """List all available questions from the API."""
33
+ questions = fetch_questions()
34
+
35
+ if isinstance(questions, dict) and "error" in questions:
36
+ print(questions["error"])
37
+ return
38
+
39
+ print(f"Found {len(questions)} questions:\n")
40
+
41
+ for i, question in enumerate(questions):
42
+ task_id = question["task_id"]
43
+ question_text = question["question"]
44
+ has_file = "file_url" in question and question["file_url"] is not None
45
+
46
+ # Truncate long questions
47
+ if len(question_text) > 100:
48
+ question_text = question_text[:97] + "..."
49
+
50
+ file_info = f"[Has file: {question['file_url']}]" if has_file else "[No file]"
51
+ print(f"{i+1}. Task ID: {task_id} {file_info}\n Question: {question_text}\n")
52
+
53
+ def test_question_by_index(index):
54
+ """Test a specific question from the API by its index."""
55
+ questions = fetch_questions()
56
+
57
+ if isinstance(questions, dict) and "error" in questions:
58
+ print(questions["error"])
59
+ return
60
+
61
+ if not 1 <= index <= len(questions):
62
+ print(f"Invalid index. Please choose a number between 1 and {len(questions)}.")
63
+ return
64
+
65
+ question = questions[index - 1]
66
+ task_id = question["task_id"]
67
+ question_text = question["question"]
68
+ file_url = question.get("file_url")
69
+
70
+ print(f"Testing question {index} (Task ID: {task_id})")
71
+
72
+ # Test the question
73
+ test_question_with_file(question_text, file_url)
74
+
75
+ def main():
76
+ parser = argparse.ArgumentParser(description="Test questions from the evaluation API")
77
+ parser.add_argument("--list", "-l", action="store_true", help="List all available questions")
78
+ parser.add_argument("--question", "-q", type=int, help="Test a specific question by index")
79
+
80
+ args = parser.parse_args()
81
+
82
+ if args.list:
83
+ list_questions()
84
+ elif args.question:
85
+ test_question_by_index(args.question)
86
+ else:
87
+ parser.print_help()
88
+
89
+ if __name__ == "__main__":
90
+ main()
test_question.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Test script to run the agent on a single question.
4
+ """
5
+ import os
6
+ import json
7
+ import requests
8
+ import tempfile
9
+ from pathlib import Path
10
+ import argparse
11
+ from direct_agent_fixed import DirectAgent
12
+ from dotenv import load_dotenv
13
+
14
+ # Load environment variables
15
+ load_dotenv()
16
+
17
+ def download_file(url):
18
+ """Download a file from a URL and save it to a temporary location."""
19
+ try:
20
+ response = requests.get(url)
21
+ response.raise_for_status()
22
+
23
+ # Create a temporary file with the right extension
24
+ file_extension = Path(url).suffix.lower()
25
+
26
+ # If no extension or weird extension, try to guess from content-type
27
+ if not file_extension:
28
+ content_type = response.headers.get('content-type', '')
29
+ if 'excel' in content_type or 'spreadsheet' in content_type:
30
+ file_extension = '.xlsx'
31
+ elif 'csv' in content_type:
32
+ file_extension = '.csv'
33
+
34
+ # Create temporary file with correct extension
35
+ with tempfile.NamedTemporaryFile(delete=False, suffix=file_extension) as temp_file:
36
+ temp_file.write(response.content)
37
+ temp_file_path = temp_file.name
38
+
39
+ # Get the original filename from the URL
40
+ filename = Path(url).name
41
+
42
+ print(f"Downloaded file: {filename}")
43
+ print(f"Saved to: {temp_file_path}")
44
+
45
+ return {
46
+ "file_path": temp_file_path,
47
+ "file_name": filename
48
+ }
49
+
50
+ except Exception as e:
51
+ print(f"Error downloading file: {str(e)}")
52
+ return None
53
+
54
+ def test_question_with_file(question, file_url=None):
55
+ """Test a question with an optional file attachment."""
56
+ # Initialize agent
57
+ agent = DirectAgent()
58
+
59
+ # Download file if URL provided
60
+ file_context = None
61
+ if file_url:
62
+ file_context = download_file(file_url)
63
+
64
+ # Run the agent on the question
65
+ print(f"\nQuestion: {question}")
66
+ print("\nRunning agent...\n")
67
+
68
+ answer = agent(question, context=file_context)
69
+
70
+ print("\n" + "=" * 50)
71
+ print("ANSWER:")
72
+ print(answer)
73
+ print("=" * 50)
74
+
75
+ # Clean up temporary file
76
+ if file_context and "file_path" in file_context:
77
+ try:
78
+ os.unlink(file_context["file_path"])
79
+ print(f"Deleted temporary file: {file_context['file_path']}")
80
+ except Exception as e:
81
+ print(f"Error deleting temporary file: {str(e)}")
82
+
83
+ return answer
84
+
85
+ def get_sample_questions():
86
+ """Return a list of sample questions for testing."""
87
+ return [
88
+ {
89
+ "id": 1,
90
+ "question": "What is the capital of France?",
91
+ "file_url": None
92
+ },
93
+ {
94
+ "id": 2,
95
+ "question": "What is 25 * 4 + 10?",
96
+ "file_url": None
97
+ },
98
+ {
99
+ "id": 3,
100
+ "question": "What is the largest mammal on Earth?",
101
+ "file_url": None
102
+ }
103
+ ]
104
+
105
+ def main():
106
+ parser = argparse.ArgumentParser(description="Test the agent on a single question")
107
+ parser.add_argument("--question", "-q", type=str, help="The question to test")
108
+ parser.add_argument("--file", "-f", type=str, help="URL to a file attachment (optional)")
109
+ parser.add_argument("--sample", "-s", type=int, help="Use a sample question (1, 2, or 3)")
110
+
111
+ args = parser.parse_args()
112
+
113
+ if args.sample:
114
+ samples = get_sample_questions()
115
+ if 1 <= args.sample <= len(samples):
116
+ sample = samples[args.sample - 1]
117
+ test_question_with_file(sample["question"], sample["file_url"])
118
+ else:
119
+ print(f"Sample number must be between 1 and {len(samples)}")
120
+ elif args.question:
121
+ test_question_with_file(args.question, args.file)
122
+ else:
123
+ parser.print_help()
124
+
125
+ if __name__ == "__main__":
126
+ main()