GoodLuckChuck commited on
Commit
80457a6
·
verified ·
1 Parent(s): 02f87d0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +425 -537
app.py CHANGED
@@ -1,281 +1,141 @@
1
- from llama_index.llms.openai import OpenAI
2
- from llama_index.core.agent.workflow import AgentWorkflow
3
- from llama_index.core.tools import FunctionTool
4
- import asyncio
5
- import json
6
- from typing import Optional, Dict, Any, List, Union
7
  import os
8
- from datetime import datetime
9
- import yt_dlp
10
- import whisper
11
- import tempfile
 
12
  import re
13
- import aiohttp
14
- from dotenv import load_dotenv
15
  import math
 
16
  import operator
17
- from llama_index.core.workflow import (
18
- Event,
19
- Workflow,
20
- StopEvent
21
- )
22
- from enum import Enum
23
-
24
- # Update the input document path
25
- INPUT_DOC_PATH = "/home/nik/HF FINAL MAIN/response_1747248836022.json"
26
- OUTPUT_DOC_PATH = "/home/nik/HF FINAL MAIN/agent_answers.jsonl"
27
-
28
- SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template:
29
- FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
30
- If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise.
31
- If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise.
32
- If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string."""
33
-
34
- # Load environment variables
35
- load_dotenv()
36
- SERPER_API_KEY = os.getenv('SERPER_API_KEY')
37
-
38
- def extract_youtube_url(text: str) -> Optional[str]:
39
- """Extract YouTube URL from text if present."""
40
- # Regular expressions for different YouTube URL formats
41
- youtube_patterns = [
42
- r'https?://(?:www\.)?youtube\.com/watch\?v=[\w-]+',
43
- r'https?://(?:www\.)?youtube\.com/v/[\w-]+',
44
- r'https?://youtu\.be/[\w-]+',
45
- r'https?://(?:www\.)?youtube\.com/embed/[\w-]+',
46
- ]
47
-
48
- for pattern in youtube_patterns:
49
- match = re.search(pattern, text)
50
- if match:
51
- return match.group(0)
52
- return None
53
 
54
- class YouTubeAnalyzer:
55
- def __init__(self):
56
- self.model = whisper.load_model("base")
57
- self.ydl_opts = {
58
- 'format': 'bestaudio/best',
59
- 'postprocessors': [{
60
- 'key': 'FFmpegExtractAudio',
61
- 'preferredcodec': 'mp3',
62
- 'preferredquality': '192',
63
- }],
64
- }
65
 
66
- def get_video_info(self, url: str) -> Dict[str, Any]:
67
- """Get basic information about the video."""
68
- with yt_dlp.YoutubeDL({'quiet': True}) as ydl:
69
- try:
70
- info = ydl.extract_info(url, download=False)
71
- return {
72
- 'title': info.get('title', ''),
73
- 'description': info.get('description', ''),
74
- 'duration': info.get('duration', 0),
75
- 'view_count': info.get('view_count', 0),
76
- 'upload_date': info.get('upload_date', ''),
77
- }
78
- except Exception as e:
79
- return {'error': f"Error fetching video info: {str(e)}"}
80
-
81
- def get_transcript(self, url: str) -> str:
82
- """Download video audio and transcribe it."""
83
- try:
84
- with tempfile.TemporaryDirectory() as temp_dir:
85
- print(f"Starting video download: {url}")
86
- self.ydl_opts['outtmpl'] = os.path.join(temp_dir, '%(title)s.%(ext)s')
87
-
88
- # Download audio
89
- with yt_dlp.YoutubeDL(self.ydl_opts) as ydl:
90
- info = ydl.extract_info(url, download=True)
91
- audio_file = os.path.join(temp_dir, f"{info['title']}.mp3")
92
- print(f"Audio downloaded successfully: {audio_file}")
93
-
94
- # Transcribe audio
95
- print("Starting transcription...")
96
- result = self.model.transcribe(audio_file)
97
- print("Transcription completed successfully")
98
- return result["text"]
99
- except Exception as e:
100
- print(f"Detailed error in transcript generation: {str(e)}")
101
- return f"Error transcribing video: {str(e)}"
102
-
103
- async def analyze_youtube_video(url: str) -> Dict[str, Any]:
104
- """Analyze a YouTube video and return information and transcript."""
105
- print(f"Analyzing YouTube video: {url}")
106
- analyzer = YouTubeAnalyzer()
107
-
108
- # Get video information
109
- info = analyzer.get_video_info(url)
110
-
111
- # Get transcript if video info was successfully retrieved
112
- if 'error' not in info:
113
- transcript = analyzer.get_transcript(url)
114
- info['transcript'] = transcript
115
- print("Successfully analyzed video and generated transcript")
116
- else:
117
- print(f"Error analyzing video: {info.get('error')}")
118
-
119
- return info
120
 
121
- def save_response_to_jsonl(response: Dict[str, str], output_file: str):
122
- """Save response to a JSONL file."""
123
- try:
124
- json_line = json.dumps(response, ensure_ascii=False)
125
- with open(output_file, 'a', encoding='utf-8') as f:
126
- f.write(json_line + '\n')
127
- print(f"Response saved to {output_file}")
128
- except Exception as e:
129
- print(f"Error saving response: {str(e)}")
130
 
131
- def load_document(file_path: str) -> List[Dict[str, Any]]:
132
- """Load and parse the JSON document."""
133
- try:
134
- with open(file_path, 'r', encoding='utf-8') as f:
135
- document = json.load(f)
136
- if isinstance(document, list):
137
- return document
138
- return [document] # Convert single document to list
139
- except Exception as e:
140
- print(f"Error loading document: {str(e)}")
141
- return []
142
 
143
- async def serper_search(query: str) -> str:
144
- """
145
- Perform a web search using Serper API.
146
- Returns formatted search results as a string.
147
- """
148
- if not SERPER_API_KEY:
149
- return "Error: Serper API key not found in environment variables"
150
 
151
- url = "https://google.serper.dev/search"
152
- headers = {
153
- 'X-API-KEY': SERPER_API_KEY,
154
- 'Content-Type': 'application/json'
155
- }
156
- payload = {
157
- 'q': query,
158
- 'num': 5 # Number of results to return
 
 
159
  }
160
-
161
- try:
162
- async with aiohttp.ClientSession() as session:
163
- async with session.post(url, headers=headers, json=payload) as response:
164
- if response.status == 200:
165
- data = await response.json()
166
-
167
- # Format the results
168
- results = []
169
-
170
- # Process organic results
171
- if 'organic' in data:
172
- for result in data['organic']:
173
- title = result.get('title', '')
174
- snippet = result.get('snippet', '')
175
- results.append(f"Title: {title}\nSnippet: {snippet}\n")
176
-
177
- # Process knowledge graph if available
178
- if 'knowledgeGraph' in data:
179
- kg = data['knowledgeGraph']
180
- if 'title' in kg:
181
- results.append(f"Knowledge Graph: {kg['title']}\n{kg.get('description', '')}\n")
182
-
183
- # Join all results
184
- return "\n".join(results) if results else "No results found"
185
- else:
186
- return f"Error: API returned status code {response.status}"
187
- except Exception as e:
188
- return f"Error performing search: {str(e)}"
189
-
190
- async def web_search_tool(query: str, max_retries: int = 3, delay: float = 1.0) -> str:
191
- """Search the web for information using Serper with retry logic and rate limiting."""
192
- print(f"Searching web for: {query}")
193
 
194
- for attempt in range(max_retries):
 
 
 
 
 
195
  try:
196
- results = await serper_search(query)
197
- print("Search completed")
198
- return results
 
 
 
 
 
 
 
 
 
 
199
  except Exception as e:
200
- print(f"Search attempt {attempt + 1}/{max_retries} failed: {str(e)}")
201
- if attempt < max_retries - 1:
202
- await asyncio.sleep(delay * (attempt + 1)) # Exponential backoff
203
- else:
204
- return f"Search failed after {max_retries} attempts"
205
-
206
- def format_response(task_id: str, answer: str) -> Dict[str, str]:
207
- """Format the response in the required JSON-line structure."""
208
- return {
209
- "task_id": task_id,
210
- "model_answer": answer.strip()
211
- }
212
 
213
- def truncate_text(text: str, max_tokens: int = 4000) -> str:
214
- """Roughly truncate text to stay within token limit."""
215
- # Approximate tokens (rough estimate: 4 chars = 1 token)
216
- chars_per_token = 4
217
- max_chars = max_tokens * chars_per_token
218
- if len(text) > max_chars:
219
- return text[:max_chars] + "..."
220
- return text
221
-
222
- def get_answer(question: str, llm, search_results: str, video_info: Optional[Dict[str, Any]] = None) -> str:
223
- """Get direct answer from the model with token management."""
224
- # Truncate search results and video information
225
- truncated_search = truncate_text(search_results, 2000)
226
-
227
- context = f"Question: {question}\n\nWeb search results:\n{truncated_search}\n"
228
 
229
- if video_info:
230
- # Truncate video information
231
- truncated_transcript = truncate_text(video_info.get('transcript', ''), 3000)
232
- truncated_description = truncate_text(video_info.get('description', ''), 500)
233
-
234
- context += f"""
235
- Video Information:
236
- Title: {video_info.get('title', '')}
237
- Description: {truncated_description}
238
- Transcript: {truncated_transcript}
239
- """
240
-
241
- thinking_prompt = f"""
242
- Based on this information:
243
- {context}
244
-
245
- Provide ONLY the answer with no explanation. The answer should be just a number or as few words as possible.
246
- """
247
-
248
- return llm.complete(thinking_prompt).strip()
249
 
250
- class ResponseManager:
251
- def __init__(self, output_file: str):
252
- self.output_file = output_file
253
- self.current_task_id = 0
254
-
255
- # Create new file or clear existing one
256
- with open(self.output_file, 'w', encoding='utf-8') as f:
257
- f.write('')
258
-
259
- def get_next_task_id(self) -> str:
260
- """Generate the next task ID in the format task_id_#"""
261
- self.current_task_id += 1
262
- return f"task_id_{self.current_task_id}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263
 
264
- def save_response(self, answer: str):
265
- """Save a response with auto-generated task ID"""
266
- response = {
267
- "task_id": self.get_next_task_id(),
268
- "model_answer": answer.strip()
269
  }
270
-
271
- # Write response in JSON Lines format
272
- with open(self.output_file, 'a', encoding='utf-8') as f:
273
- f.write(json.dumps(response, ensure_ascii=False) + '\n')
274
-
275
- return response
276
 
277
- class Calculator:
278
  def __init__(self):
 
279
  self.operations = {
280
  '+': operator.add,
281
  '-': operator.sub,
@@ -285,315 +145,343 @@ class Calculator:
285
  'sqrt': math.sqrt,
286
  'abs': abs
287
  }
288
-
289
- def calculate(self, expression: str) -> Union[float, str]:
290
- """
291
- Safely evaluate a mathematical expression.
292
- Returns result or error message if invalid.
293
- """
294
  try:
295
- # Convert expression to Python-safe math expression
296
  safe_expr = self._prepare_expression(expression)
297
  result = eval(safe_expr, {"__builtins__": None}, self.operations)
298
  return float(result)
299
  except Exception as e:
300
  return f"Error: {str(e)}"
301
-
302
  def _prepare_expression(self, expression: str) -> str:
303
- """Prepare expression for safe evaluation."""
304
- # Remove any dangerous characters or functions
305
  safe_chars = set("0123456789+-*/^(). ")
306
- cleaned = ''.join(c for c in expression if c in safe_chars)
307
- return cleaned
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
308
 
309
- async def analyze_document(question: str, context: Optional[Dict[str, Any]] = None) -> Dict[str, str]:
310
- """Analyze question and produce answer in JSON-line format."""
311
- try:
312
- if not context or 'document' not in context:
313
- return {"error": "No document provided in context"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314
 
315
- document = context.get('document', {})
316
- question = document.get('question', '')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
317
 
318
- if not question:
319
- return {"error": "No question found in document"}
 
 
320
 
321
- calculator = Calculator()
322
- video_info = None
323
- search_results = ""
 
 
 
 
 
 
 
324
 
325
- # Check for YouTube URL in the question
326
- youtube_url = extract_youtube_url(question)
 
 
 
 
 
 
 
 
327
 
328
- # Try YouTube analysis first if URL exists
329
- if youtube_url:
330
- print(f"Processing YouTube video: {youtube_url}")
331
- try:
332
- video_info = await analyze_youtube_video(youtube_url)
333
- if 'error' in video_info:
334
- print(f"YouTube analysis failed, falling back to web search")
335
- # Modify question to search for video content
336
- video_search_query = f"transcript summary {youtube_url}"
337
- video_search_results = await web_search_tool(video_search_query)
338
- search_results += f"\nVideo-related search results:\n{video_search_results}"
339
- except Exception as e:
340
- print(f"Error in YouTube analysis: {str(e)}")
341
- # Fallback to web search
342
- video_search_query = f"transcript summary {youtube_url}"
343
- video_search_results = await web_search_tool(video_search_query)
344
- search_results += f"\nVideo-related search results:\n{video_search_results}"
345
 
346
- # Perform general web search
347
- try:
348
- general_search_results = await web_search_tool(question)
349
- search_results += f"\nGeneral search results:\n{general_search_results}"
350
- except Exception as e:
351
- print(f"Web search error: {str(e)}")
352
 
353
- # Check if question involves calculations
354
- if any(op in question for op in ['+', '-', '*', '/', '^']):
355
- # Extract numerical expression from question
356
- # This is a simple example - you might need more sophisticated parsing
357
- numbers = re.findall(r'[-+]?\d*\.?\d+', question)
358
- operators = re.findall(r'[\+\-\*\/\^]', question)
359
- if numbers and operators:
360
- expression = ''.join([f"{n}{o}" for n, o in zip(numbers, operators + [''])])
361
- calc_result = calculator.calculate(expression)
362
- search_results += f"\nCalculation result: {calc_result}"
363
 
364
- # Get answer using all available information
365
- answer = get_answer(question, llm, search_results, video_info)
 
 
366
 
367
- return {"answer": answer.strip()}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
368
 
 
 
 
369
  except Exception as e:
370
- return {"error": f"Error processing question: {str(e)}"}
 
 
 
 
 
371
 
372
- # initialize llm
373
- llm = OpenAI(
374
- model="gpt-4o",
375
- temperature=0,
376
- system_prompt=SYSTEM_PROMPT
377
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
378
 
379
- # initialize agent with web search and YouTube analysis capability
380
- agent = AgentWorkflow.from_tools_or_functions(
381
- [
382
- FunctionTool.from_defaults(analyze_document),
383
- FunctionTool.from_defaults(web_search_tool),
384
- FunctionTool.from_defaults(analyze_youtube_video),
385
- FunctionTool.from_defaults(Calculator().calculate)
386
- ],
387
- llm=llm
388
- )
389
 
390
- async def main():
391
- from llama_index.core.workflow import Context
392
- ctx = Context(agent)
393
-
394
- # Initialize response manager
395
- response_manager = ResponseManager(OUTPUT_DOC_PATH)
396
-
397
- # Load documents into context using the new path
398
- if os.path.exists(INPUT_DOC_PATH):
399
- documents = load_document(INPUT_DOC_PATH)
400
- if documents:
401
- # Process each question in the document
402
- for doc in documents:
403
- # Set current document in context
404
- await ctx.set('document', doc)
405
-
406
- try:
407
- # Get agent response
408
- agent_output = await agent.run(doc['question'], ctx=ctx)
409
-
410
- # Format and save response using the document's task_id
411
- response = {
412
- "task_id": doc['task_id'],
413
- "model_answer": str(agent_output).strip()
414
- }
415
-
416
- # Save to file and print
417
- with open(OUTPUT_DOC_PATH, 'a', encoding='utf-8') as f:
418
- f.write(json.dumps(response, ensure_ascii=False) + '\n')
419
- print(json.dumps(response))
420
-
421
- except Exception as e:
422
- error_response = {
423
- "task_id": doc.get('task_id', 'unknown'),
424
- "model_answer": f"Error processing question: {str(e)}"
425
- }
426
- with open(OUTPUT_DOC_PATH, 'a', encoding='utf-8') as f:
427
- f.write(json.dumps(error_response, ensure_ascii=False) + '\n')
428
- print(json.dumps(error_response))
429
- else:
430
- error_response = {
431
- "task_id": "error",
432
- "model_answer": "Failed to load document"
433
- }
434
- with open(OUTPUT_DOC_PATH, 'a', encoding='utf-8') as f:
435
- f.write(json.dumps(error_response, ensure_ascii=False) + '\n')
436
- print(json.dumps(error_response))
437
- else:
438
- error_response = {
439
- "task_id": "error",
440
- "model_answer": f"Document not found at {INPUT_DOC_PATH}"
441
- }
442
- with open(OUTPUT_DOC_PATH, 'a', encoding='utf-8') as f:
443
- f.write(json.dumps(error_response, ensure_ascii=False) + '\n')
444
- print(json.dumps(error_response))
445
 
446
- if __name__ == "__main__":
447
- asyncio.run(main())
448
-
449
- class QuestionType(Enum):
450
- YOUTUBE = "youtube"
451
- CALCULATION = "calculation"
452
- WEB_SEARCH = "web_search"
453
- MULTIPLE = "multiple"
454
-
455
- # Define our event classes
456
- class BaseEvent(Event):
457
- question: str
458
- task_id: str
459
- search_results: Optional[str] = None
460
- youtube_results: Optional[Dict[str, Any]] = None
461
- calculation_results: Optional[Dict[str, Any]] = None
462
- errors: List[str] = []
463
-
464
- class AgentStopEvent(StopEvent):
465
- answer: str # Use 'answer' instead of 'result' to avoid shadowing
466
-
467
- class AgentWorkflow(Workflow):
468
- def __init__(self, llm, verbose=False, max_search_attempts: int = 3):
469
- self.llm = llm
470
- self.calculator = Calculator()
471
- self.max_search_attempts = max_search_attempts
472
- super().__init__(verbose=verbose)
473
-
474
- async def process_question(self, ev: Event) -> AgentStopEvent:
475
- """Single step that processes the question and returns a StopEvent"""
476
  try:
477
- question = ev.input.get('question', '')
478
- task_id = ev.input.get('task_id', '')
479
-
480
- if not question:
481
- return AgentStopEvent(answer="No question provided")
482
-
483
- # Initialize results
484
- search_results = ""
485
- youtube_results = None
486
- calculation_results = None
487
- errors = []
488
-
489
- # Check for YouTube URL
490
- youtube_url = extract_youtube_url(question)
491
- if youtube_url:
492
- try:
493
- youtube_results = await analyze_youtube_video(youtube_url)
494
- if 'error' in youtube_results:
495
- errors.append(f"YouTube analysis failed: {youtube_results['error']}")
496
- # Fallback to web search
497
- video_search = await web_search_tool(f"transcript summary {youtube_url}")
498
- search_results += f"\nVideo search results:\n{video_search}"
499
- except Exception as e:
500
- errors.append(f"YouTube analysis error: {str(e)}")
501
-
502
- # Perform web search
503
- try:
504
- search_result = await web_search_tool(question)
505
- search_results += f"\nGeneral search results:\n{search_result}"
506
- except Exception as e:
507
- errors.append(f"Web search error: {str(e)}")
508
-
509
- # Check for calculations
510
- if any(op in question for op in ['+', '-', '*', '/', '^']):
511
- try:
512
- numbers = re.findall(r'[-+]?\d*\.?\d+', question)
513
- operators = re.findall(r'[\+\-\*\/\^]', question)
514
- if numbers and operators:
515
- expression = ''.join([f"{n}{o}" for n, o in zip(numbers, operators + [''])])
516
- calc_result = self.calculator.calculate(expression)
517
- calculation_results = {expression: calc_result}
518
- except Exception as e:
519
- errors.append(f"Calculation error: {str(e)}")
520
-
521
- # Generate answer
522
- context = f"Question: {question}\n\n"
523
-
524
- if search_results:
525
- context += f"Search Results:\n{truncate_text(search_results, 2000)}\n\n"
526
-
527
- if youtube_results:
528
- context += f"""
529
- Video Information:
530
- Title: {youtube_results.get('title', '')}
531
- Description: {truncate_text(youtube_results.get('description', ''), 500)}
532
- Transcript: {truncate_text(youtube_results.get('transcript', ''), 3000)}
533
- """
534
-
535
- if calculation_results:
536
- context += "Calculations:\n"
537
- for expr, result in calculation_results.items():
538
- context += f"{expr} = {result}\n"
539
 
540
- if errors:
541
- context += "\nErrors encountered:\n" + "\n".join(errors)
542
 
543
- prompt = f"""
544
- Based on this information:
545
- {context}
546
-
547
- Provide ONLY the answer with no explanation. The answer should be just a number or as few words as possible.
548
- If the information is insufficient or unclear, respond with 'Information not found'.
549
- """
 
 
 
 
 
 
 
 
 
550
 
551
- final_answer = self.llm.complete(prompt).strip()
552
-
553
- return AgentStopEvent(answer=final_answer)
554
 
555
- except Exception as e:
556
- return AgentStopEvent(answer=f"Error processing question: {str(e)}")
557
-
558
- # Update the process_questions function
559
- async def process_questions(input_path: str, output_path: str):
560
- llm = OpenAI(
561
- model="gpt-4",
562
- temperature=0,
563
- system_prompt=SYSTEM_PROMPT
564
  )
565
-
566
- workflow = AgentWorkflow(llm=llm, verbose=True)
567
-
568
- if os.path.exists(input_path):
569
- documents = load_document(input_path)
570
-
571
- for doc in documents:
572
- try:
573
- result = await workflow.run(
574
- input={
575
- 'question': doc['question'],
576
- 'task_id': doc['task_id']
577
- }
578
- )
579
-
580
- response = {
581
- "task_id": doc['task_id'],
582
- "model_answer": result.answer # Using answer instead of result
583
- }
584
-
585
- with open(output_path, 'a', encoding='utf-8') as f:
586
- f.write(json.dumps(response, ensure_ascii=False) + '\n')
587
- print(json.dumps(response))
588
-
589
- except Exception as e:
590
- error_response = {
591
- "task_id": doc.get('task_id', 'unknown'),
592
- "model_answer": f"Error processing question: {str(e)}"
593
- }
594
- with open(output_path, 'a', encoding='utf-8') as f:
595
- f.write(json.dumps(error_response, ensure_ascii=False) + '\n')
596
- print(json.dumps(error_response))
597
 
598
  if __name__ == "__main__":
599
- asyncio.run(process_questions(INPUT_DOC_PATH, OUTPUT_DOC_PATH))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
+ import gradio as gr
3
+ import requests
4
+ import inspect
5
+ import pandas as pd
6
+ import asyncio
7
  import re
8
+ import json
 
9
  import math
10
+ import logging
11
  import operator
12
+ import aiohttp
13
+ from typing import Optional, Dict, Any, List, Union
14
+ from dotenv import load_dotenv
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ # Import necessary components from smolagents
17
+ try:
18
+ from smolagents import CodeAgent, Tool, OpenAIServerModel
19
+ except ImportError:
20
+ # Handle if smolagents is not installed
21
+ pass
 
 
 
 
 
22
 
23
+ from datetime import datetime
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
+ # --- Constants ---
26
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
27
+ OUTPUT_DOC_PATH = "agent_answers.jsonl"
28
+ SCREENSHOTS_DIR = "screenshots"
 
 
 
 
 
29
 
30
+ # Configure logging
31
+ logging.basicConfig(
32
+ level=logging.INFO,
33
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
34
+ )
35
+ logger = logging.getLogger(__name__)
 
 
 
 
 
36
 
37
+ # Ensure screenshots directory exists
38
+ os.makedirs(SCREENSHOTS_DIR, exist_ok=True)
 
 
 
 
 
39
 
40
+ # --- Tool Definitions ---
41
+ class ImageRetrievalTool(Tool):
42
+ name = "image_retriever"
43
+ description = "Retrieves and processes images from web pages"
44
+
45
+ inputs = {
46
+ "url": {
47
+ "type": "string",
48
+ "description": "The URL of the image to retrieve"
49
+ }
50
  }
51
+ output_type = "object"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
+ def __init__(self):
54
+ super().__init__()
55
+ self.image_memory = {}
56
+ self.screenshot_count = 0
57
+
58
+ async def forward(self, url: str) -> Dict[str, Any]:
59
  try:
60
+ async with aiohttp.ClientSession() as session:
61
+ async with session.get(url) as response:
62
+ if response.status == 200:
63
+ image_data = await response.read()
64
+ image_id = f"image_{self.screenshot_count}"
65
+ self.image_memory[image_id] = {
66
+ 'data': image_data,
67
+ 'url': url,
68
+ 'timestamp': datetime.now().isoformat()
69
+ }
70
+ self.screenshot_count += 1
71
+ return {"image_id": image_id, "status": "success"}
72
+ return {"error": f"Failed to fetch image: {response.status}"}
73
  except Exception as e:
74
+ return {"error": f"Error retrieving image: {str(e)}"}
 
 
 
 
 
 
 
 
 
 
 
75
 
76
+ class WebSearchTool(Tool):
77
+ name = "web_search"
78
+ description = "Performs web searches using Serper API"
 
 
 
 
 
 
 
 
 
 
 
 
79
 
80
+ inputs = {
81
+ "query": {
82
+ "type": "string",
83
+ "description": "The search query to execute"
84
+ }
85
+ }
86
+ output_type = "string"
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
+ async def forward(self, query: str) -> str:
89
+ if not os.getenv('SERPER_API_KEY'):
90
+ return "Error: Serper API key not found"
91
+
92
+ url = "https://google.serper.dev/search"
93
+ headers = {
94
+ 'X-API-KEY': os.getenv('SERPER_API_KEY'),
95
+ 'Content-Type': 'application/json'
96
+ }
97
+ payload = {
98
+ 'q': query,
99
+ 'num': 5
100
+ }
101
+
102
+ try:
103
+ async with aiohttp.ClientSession() as session:
104
+ async with session.post(url, headers=headers, json=payload) as response:
105
+ if response.status == 200:
106
+ data = await response.json()
107
+ return self._format_results(data)
108
+ return f"Error: API returned status code {response.status}"
109
+ except Exception as e:
110
+ return f"Error performing search: {str(e)}"
111
+
112
+ def _format_results(self, data: Dict) -> str:
113
+ results = []
114
+ if 'organic' in data:
115
+ for result in data['organic']:
116
+ results.append(f"Title: {result.get('title', '')}\n"
117
+ f"Snippet: {result.get('snippet', '')}\n")
118
+ if 'knowledgeGraph' in data:
119
+ kg = data['knowledgeGraph']
120
+ if 'title' in kg:
121
+ results.append(f"Knowledge Graph: {kg['title']}\n"
122
+ f"{kg.get('description', '')}\n")
123
+ return "\n".join(results) if results else "No results found"
124
+
125
+ class CalculatorTool(Tool):
126
+ name = "calculator"
127
+ description = "Performs mathematical calculations"
128
 
129
+ inputs = {
130
+ "expression": {
131
+ "type": "string",
132
+ "description": "The mathematical expression to evaluate"
 
133
  }
134
+ }
135
+ output_type = "number"
 
 
 
 
136
 
 
137
  def __init__(self):
138
+ super().__init__()
139
  self.operations = {
140
  '+': operator.add,
141
  '-': operator.sub,
 
145
  'sqrt': math.sqrt,
146
  'abs': abs
147
  }
148
+
149
+ async def forward(self, expression: str) -> Union[float, str]:
 
 
 
 
150
  try:
 
151
  safe_expr = self._prepare_expression(expression)
152
  result = eval(safe_expr, {"__builtins__": None}, self.operations)
153
  return float(result)
154
  except Exception as e:
155
  return f"Error: {str(e)}"
156
+
157
  def _prepare_expression(self, expression: str) -> str:
 
 
158
  safe_chars = set("0123456789+-*/^(). ")
159
+ return ''.join(c for c in expression if c in safe_chars)
160
+
161
+ # --- Agent Definition ---
162
+ class QuestionAnsweringAgent(CodeAgent):
163
+ def __init__(self, model: Optional[OpenAIServerModel] = None):
164
+ tools = [
165
+ WebSearchTool(),
166
+ CalculatorTool(),
167
+ ImageRetrievalTool()
168
+ ]
169
+
170
+ if model is None:
171
+ model = OpenAIServerModel(model_id="gpt-4")
172
+
173
+ super().__init__(
174
+ tools=tools,
175
+ model=model,
176
+ additional_authorized_imports=["PIL"],
177
+ step_callbacks=[self._process_visual_memory],
178
+ max_steps=20,
179
+ verbosity_level=2
180
+ )
181
+
182
+ self.visual_memory = {}
183
+ self.step_count = 0
184
+ logger.info("QuestionAnsweringAgent initialized with all tools")
185
+
186
+ async def _process_visual_memory(self, step_num: int, description: str):
187
+ if hasattr(self, 'current_observation_images'):
188
+ self.visual_memory[step_num] = {
189
+ 'images': self.current_observation_images,
190
+ 'description': description,
191
+ 'timestamp': datetime.now().isoformat()
192
+ }
193
 
194
+ async def process_question(self, question_data: str) -> str:
195
+ try:
196
+ logger.info(f"Processing question: {question_data[:50]}...")
197
+ self.step_count += 1
198
+
199
+ plan = await self.plan_execution(question_data)
200
+ logger.info(f"Execution plan: {plan}")
201
+
202
+ search_results = await self.execute_tool(
203
+ "web_search",
204
+ {"query": question_data}
205
+ )
206
+
207
+ calc_result = None
208
+ if any(op in question_data for op in ['+', '-', '*', '/', '^']):
209
+ numbers = re.findall(r'[-+]?\d*\.?\d+', question_data)
210
+ operators = re.findall(r'[\+\-\*\/\^]', question_data)
211
+ if numbers and operators:
212
+ expression = ''.join([f"{n}{o}" for n, o in zip(numbers, operators + [''])])
213
+ calc_result = await self.execute_tool(
214
+ "calculator",
215
+ {"expression": expression}
216
+ )
217
+ logger.info(f"Calculation result: {calc_result}")
218
+
219
+ context = self._prepare_context(
220
+ question=question_data,
221
+ search_results=search_results,
222
+ calc_result=calc_result
223
+ )
224
 
225
+ response = self.model([
226
+ {"role": "system", "content": "You are a helpful AI assistant that provides accurate and concise answers based on the given context."},
227
+ {"role": "user", "content": context}
228
+ ])
229
+
230
+ answer_text = response.content if hasattr(response, 'content') else str(response)
231
+
232
+ logger.info(f"Generated answer for question")
233
+ return answer_text.strip()
234
+
235
+ except Exception as e:
236
+ logger.error(f"Error processing question: {str(e)}", exc_info=True)
237
+ return f"Error processing question: {str(e)}"
238
+
239
+ async def plan_execution(self, question: str) -> str:
240
+ prompt = f"""
241
+ Create a plan to answer the following question: {question}
242
+ Available tools:
243
+ - web_search: Search the web for information
244
+ - calculator: Perform mathematical calculations
245
+ """
246
 
247
+ response = self.model([
248
+ {"role": "system", "content": "You are a planning assistant. Create a step-by-step plan to answer the question."},
249
+ {"role": "user", "content": prompt}
250
+ ])
251
 
252
+ result = response.content if hasattr(response, 'content') else str(response)
253
+ return result.strip()
254
+
255
+ def _prepare_context(
256
+ self,
257
+ question: str,
258
+ search_results: str = "",
259
+ calc_result: Optional[Union[float, str]] = None
260
+ ) -> str:
261
+ context = f"Question: {question}\n\n"
262
 
263
+ if search_results:
264
+ context += f"Search Results:\n{search_results[:2000]}...\n\n"
265
+
266
+ if calc_result is not None:
267
+ context += f"Calculation Result: {calc_result}\n\n"
268
+
269
+ if self.visual_memory:
270
+ context += "\nVisual Information:\n"
271
+ for step, memory in self.visual_memory.items():
272
+ context += f"Step {step}: {memory['description']}\n"
273
 
274
+ return context
275
+
276
+ # Adapter to fit interface with original app.py
277
+ class ChuckAgent:
278
+ def __init__(self):
279
+ load_dotenv()
280
+ # Check for required environment variables
281
+ required_env_vars = [
282
+ 'OPENAI_API_KEY',
283
+ 'SERPER_API_KEY'
284
+ ]
 
 
 
 
 
 
285
 
286
+ missing_vars = [var for var in required_env_vars if not os.getenv(var)]
287
+ if missing_vars:
288
+ raise EnvironmentError(f"Missing required environment variables: {', '.join(missing_vars)}")
 
 
 
289
 
290
+ logger.info("Agent initialization started")
 
 
 
 
 
 
 
 
 
291
 
292
+ self.model = OpenAIServerModel(
293
+ model_id="gpt-4",
294
+ api_key=os.getenv('OPENAI_API_KEY')
295
+ )
296
 
297
+ self.agent = QuestionAnsweringAgent(model=self.model)
298
+ self.loop = asyncio.new_event_loop()
299
+ asyncio.set_event_loop(self.loop)
300
+ logger.info("Agent fully initialized")
301
+
302
+ def __call__(self, question: str) -> str:
303
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
304
+ try:
305
+ # Run the async process_question function in the event loop
306
+ answer = self.loop.run_until_complete(self.agent.process_question(question))
307
+ print(f"Agent returning answer (first 50 chars): {answer[:50]}...")
308
+ return answer
309
+ except Exception as e:
310
+ error_msg = f"Error running agent: {str(e)}"
311
+ print(error_msg)
312
+ return error_msg
313
+
314
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
315
+ """
316
+ Fetches all questions, runs the ChuckAgent on them, submits all answers,
317
+ and displays the results.
318
+ """
319
+ # --- Determine HF Space Runtime URL and Repo URL ---
320
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
321
+
322
+ if profile:
323
+ username= f"{profile.username}"
324
+ print(f"User logged in: {username}")
325
+ else:
326
+ print("User not logged in.")
327
+ return "Please Login to Hugging Face with the button.", None
328
+
329
+ api_url = DEFAULT_API_URL
330
+ questions_url = f"{api_url}/questions"
331
+ submit_url = f"{api_url}/submit"
332
 
333
+ # 1. Instantiate Agent (using our new ChuckAgent)
334
+ try:
335
+ agent = ChuckAgent()
336
  except Exception as e:
337
+ print(f"Error instantiating agent: {e}")
338
+ return f"Error initializing agent: {e}", None
339
+
340
+ # In the case of an app running as a hugging Face space, this link points toward your codebase
341
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
342
+ print(agent_code)
343
 
344
+ # 2. Fetch Questions
345
+ print(f"Fetching questions from: {questions_url}")
346
+ try:
347
+ response = requests.get(questions_url, timeout=15)
348
+ response.raise_for_status()
349
+ questions_data = response.json()
350
+ if not questions_data:
351
+ print("Fetched questions list is empty.")
352
+ return "Fetched questions list is empty or invalid format.", None
353
+ print(f"Fetched {len(questions_data)} questions.")
354
+ except requests.exceptions.RequestException as e:
355
+ print(f"Error fetching questions: {e}")
356
+ return f"Error fetching questions: {e}", None
357
+ except requests.exceptions.JSONDecodeError as e:
358
+ print(f"Error decoding JSON response from questions endpoint: {e}")
359
+ print(f"Response text: {response.text[:500]}")
360
+ return f"Error decoding server response for questions: {e}", None
361
+ except Exception as e:
362
+ print(f"An unexpected error occurred fetching questions: {e}")
363
+ return f"An unexpected error occurred fetching questions: {e}", None
364
+
365
+ # 3. Run your Agent
366
+ results_log = []
367
+ answers_payload = []
368
+ print(f"Running agent on {len(questions_data)} questions...")
369
+ for item in questions_data:
370
+ task_id = item.get("task_id")
371
+ question_text = item.get("question")
372
+ if not task_id or question_text is None:
373
+ print(f"Skipping item with missing task_id or question: {item}")
374
+ continue
375
+ try:
376
+ submitted_answer = agent(question_text)
377
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
378
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
379
+ except Exception as e:
380
+ print(f"Error running agent on task {task_id}: {e}")
381
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
382
 
383
+ if not answers_payload:
384
+ print("Agent did not produce any answers to submit.")
385
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
 
 
 
 
 
 
 
386
 
387
+ # 4. Prepare Submission
388
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
389
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
390
+ print(status_update)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
391
 
392
+ # 5. Submit
393
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
394
+ try:
395
+ response = requests.post(submit_url, json=submission_data, timeout=60)
396
+ response.raise_for_status()
397
+ result_data = response.json()
398
+ final_status = (
399
+ f"Submission Successful!\n"
400
+ f"User: {result_data.get('username')}\n"
401
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
402
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
403
+ f"Message: {result_data.get('message', 'No message received.')}"
404
+ )
405
+ print("Submission successful.")
406
+ results_df = pd.DataFrame(results_log)
407
+ return final_status, results_df
408
+ except requests.exceptions.HTTPError as e:
409
+ error_detail = f"Server responded with status {e.response.status_code}."
 
 
 
 
 
 
 
 
 
 
 
 
410
  try:
411
+ error_json = e.response.json()
412
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
413
+ except requests.exceptions.JSONDecodeError:
414
+ error_detail += f" Response: {e.response.text[:500]}"
415
+ status_message = f"Submission Failed: {error_detail}"
416
+ print(status_message)
417
+ results_df = pd.DataFrame(results_log)
418
+ return status_message, results_df
419
+ except requests.exceptions.Timeout:
420
+ status_message = "Submission Failed: The request timed out."
421
+ print(status_message)
422
+ results_df = pd.DataFrame(results_log)
423
+ return status_message, results_df
424
+ except requests.exceptions.RequestException as e:
425
+ status_message = f"Submission Failed: Network error - {e}"
426
+ print(status_message)
427
+ results_df = pd.DataFrame(results_log)
428
+ return status_message, results_df
429
+ except Exception as e:
430
+ status_message = f"An unexpected error occurred during submission: {e}"
431
+ print(status_message)
432
+ results_df = pd.DataFrame(results_log)
433
+ return status_message, results_df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
434
 
 
 
435
 
436
+ # --- Build Gradio Interface using Blocks ---
437
+ with gr.Blocks() as demo:
438
+ gr.Markdown("# Chuck Agent Evaluation Runner")
439
+ gr.Markdown(
440
+ """
441
+ **Instructions:**
442
+ 1. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
443
+ 2. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
444
+ ---
445
+ **Note:** The agent uses smolagents, OpenAI, and Serper API for searches. Make sure you have all required environment variables set:
446
+ - OPENAI_API_KEY
447
+ - SERPER_API_KEY
448
+ - HF_USERNAME
449
+ - AGENT_CODE
450
+ """
451
+ )
452
 
453
+ gr.LoginButton()
 
 
454
 
455
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
456
+
457
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
458
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
459
+
460
+ run_button.click(
461
+ fn=run_and_submit_all,
462
+ outputs=[status_output, results_table]
 
463
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
464
 
465
  if __name__ == "__main__":
466
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
467
+ # Check for SPACE_HOST and SPACE_ID at startup for information
468
+ space_host_startup = os.getenv("SPACE_HOST")
469
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
470
+
471
+ if space_host_startup:
472
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
473
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
474
+ else:
475
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
476
+
477
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
478
+ print(f"✅ SPACE_ID found: {space_id_startup}")
479
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
480
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
481
+ else:
482
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
483
+
484
+ print("-"*(60 + len(" App Starting ")) + "\n")
485
+
486
+ print("Launching Gradio Interface for Chuck Agent Evaluation...")
487
+ demo.launch(debug=True, share=False)