Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,19 +6,28 @@ import re
|
|
| 6 |
import time
|
| 7 |
import json
|
| 8 |
from bs4 import BeautifulSoup
|
| 9 |
-
from googlesearch import search
|
| 10 |
|
| 11 |
# Constants
|
| 12 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
|
|
| 13 |
|
| 14 |
-
# Pure LLM Agent
|
| 15 |
class PureLLMAgent:
|
| 16 |
-
def __init__(self):
|
| 17 |
self.model_url = "https://api-inference.huggingface.co/models/google/gemma-7b-it"
|
| 18 |
-
|
|
|
|
|
|
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
def query_model(self, prompt):
|
| 21 |
"""Query the public LLM API without authentication"""
|
|
|
|
|
|
|
| 22 |
try:
|
| 23 |
# This uses the public API which is rate-limited but doesn't need authentication
|
| 24 |
response = requests.post(
|
|
@@ -27,134 +36,153 @@ class PureLLMAgent:
|
|
| 27 |
headers={"Content-Type": "application/json"}
|
| 28 |
)
|
| 29 |
|
|
|
|
|
|
|
| 30 |
if response.status_code == 200:
|
| 31 |
result = response.json()
|
| 32 |
if isinstance(result, list) and len(result) > 0:
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
else:
|
| 36 |
-
|
| 37 |
return None
|
| 38 |
except Exception as e:
|
| 39 |
-
|
| 40 |
return None
|
| 41 |
|
| 42 |
-
def
|
| 43 |
-
"""
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
if youtube_match:
|
| 47 |
-
return youtube_match.group(5)
|
| 48 |
-
return None
|
| 49 |
-
|
| 50 |
-
def get_youtube_metadata(self, video_id):
|
| 51 |
-
"""Get YouTube video metadata using oEmbed API (no auth required)"""
|
| 52 |
-
try:
|
| 53 |
-
api_url = f"https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v={video_id}&format=json"
|
| 54 |
-
response = requests.get(api_url, timeout=10)
|
| 55 |
-
if response.status_code == 200:
|
| 56 |
-
return response.json()
|
| 57 |
-
return None
|
| 58 |
-
except Exception as e:
|
| 59 |
-
print(f"Error getting YouTube metadata: {e}")
|
| 60 |
-
return None
|
| 61 |
-
|
| 62 |
-
def google_search(self, query):
|
| 63 |
-
"""Perform Google search using googlesearch-python"""
|
| 64 |
try:
|
| 65 |
-
#
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
-
#
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
video_id = self.extract_youtube_video_id(url)
|
| 77 |
-
if video_id:
|
| 78 |
-
# Get video metadata
|
| 79 |
-
metadata = self.get_youtube_metadata(video_id)
|
| 80 |
-
if metadata:
|
| 81 |
-
youtube_results.append({
|
| 82 |
-
"title": metadata.get("title", ""),
|
| 83 |
-
"author": metadata.get("author_name", ""),
|
| 84 |
-
"description": metadata.get("description", ""),
|
| 85 |
-
"url": url,
|
| 86 |
-
"video_id": video_id
|
| 87 |
-
})
|
| 88 |
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
# Extract title
|
| 103 |
-
title = soup.title.string if soup.title else url
|
| 104 |
-
|
| 105 |
-
# Extract content (first few paragraphs)
|
| 106 |
-
paragraphs = []
|
| 107 |
-
for p in soup.find_all('p')[:3]:
|
| 108 |
-
text = p.get_text().strip()
|
| 109 |
-
if len(text) > 30: # Only substantial paragraphs
|
| 110 |
-
paragraphs.append(text)
|
| 111 |
-
|
| 112 |
-
content = " ".join(paragraphs)
|
| 113 |
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
results.append({
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
})
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
except Exception as e:
|
| 134 |
-
|
| 135 |
return []
|
| 136 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
def run(self, question):
|
| 138 |
try:
|
| 139 |
-
|
|
|
|
| 140 |
|
| 141 |
-
# 1. Try to get context from
|
| 142 |
-
search_results = self.
|
| 143 |
|
| 144 |
-
# 2. Process search results
|
| 145 |
search_context = ""
|
| 146 |
|
| 147 |
if search_results:
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
|
| 159 |
# 3. If search provided context, use LLM to get answer
|
| 160 |
if search_context:
|
|
@@ -183,6 +211,8 @@ VERY IMPORTANT: Be extremely concise. Answer with just the specific information
|
|
| 183 |
|
| 184 |
# Clean up the LLM answer (remove explanations, keep it brief)
|
| 185 |
if llm_answer:
|
|
|
|
|
|
|
| 186 |
# Remove "The answer is" and similar prefixes
|
| 187 |
llm_answer = re.sub(r'^(the answer is|answer:|i believe the answer is|the)[\s:]*', '', llm_answer, flags=re.IGNORECASE)
|
| 188 |
|
|
@@ -190,15 +220,20 @@ VERY IMPORTANT: Be extremely concise. Answer with just the specific information
|
|
| 190 |
llm_answer = llm_answer.split('\n')[0].split('.')[0].strip()
|
| 191 |
|
| 192 |
# Limit length
|
| 193 |
-
llm_answer
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
|
| 195 |
return llm_answer
|
| 196 |
|
| 197 |
# 4. No useful search results or LLM failure
|
|
|
|
| 198 |
return "Insufficient information"
|
| 199 |
|
| 200 |
except Exception as e:
|
| 201 |
-
|
| 202 |
return "Error processing question"
|
| 203 |
|
| 204 |
# Create agent instance
|
|
|
|
| 6 |
import time
|
| 7 |
import json
|
| 8 |
from bs4 import BeautifulSoup
|
|
|
|
| 9 |
|
| 10 |
# Constants
|
| 11 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 12 |
+
SERPER_API_KEY = "YOUR_SERPER_API_KEY" # Replace with your actual Serper API key
|
| 13 |
|
| 14 |
+
# Pure LLM Agent with Serper for Google Search
|
| 15 |
class PureLLMAgent:
|
| 16 |
+
def __init__(self, debug_mode=True):
|
| 17 |
self.model_url = "https://api-inference.huggingface.co/models/google/gemma-7b-it"
|
| 18 |
+
self.debug_mode = debug_mode
|
| 19 |
+
self.serper_api_key = SERPER_API_KEY
|
| 20 |
+
print("PureLLMAgent initialized - using Serper API for Google Search + LLM")
|
| 21 |
|
| 22 |
+
def debug_print(self, message):
|
| 23 |
+
"""Print debug messages if debug mode is enabled"""
|
| 24 |
+
if self.debug_mode:
|
| 25 |
+
print(f"DEBUG: {message}")
|
| 26 |
+
|
| 27 |
def query_model(self, prompt):
|
| 28 |
"""Query the public LLM API without authentication"""
|
| 29 |
+
self.debug_print(f"Sending prompt to LLM (first 100 chars): {prompt[:100]}...")
|
| 30 |
+
|
| 31 |
try:
|
| 32 |
# This uses the public API which is rate-limited but doesn't need authentication
|
| 33 |
response = requests.post(
|
|
|
|
| 36 |
headers={"Content-Type": "application/json"}
|
| 37 |
)
|
| 38 |
|
| 39 |
+
self.debug_print(f"LLM API status code: {response.status_code}")
|
| 40 |
+
|
| 41 |
if response.status_code == 200:
|
| 42 |
result = response.json()
|
| 43 |
if isinstance(result, list) and len(result) > 0:
|
| 44 |
+
answer = result[0].get("generated_text", "")
|
| 45 |
+
else:
|
| 46 |
+
answer = result.get("generated_text", "")
|
| 47 |
+
|
| 48 |
+
self.debug_print(f"Raw LLM response: {answer}")
|
| 49 |
+
return answer
|
| 50 |
else:
|
| 51 |
+
self.debug_print(f"API call failed: {response.status_code}, {response.text[:200]}")
|
| 52 |
return None
|
| 53 |
except Exception as e:
|
| 54 |
+
self.debug_print(f"Error calling LLM API: {e}")
|
| 55 |
return None
|
| 56 |
|
| 57 |
+
def serper_search(self, query):
|
| 58 |
+
"""Perform Google search using Serper API"""
|
| 59 |
+
self.debug_print(f"Searching Google via Serper API for: {query}")
|
| 60 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
try:
|
| 62 |
+
# Set up the Serper API request
|
| 63 |
+
serper_url = "https://google.serper.dev/search"
|
| 64 |
+
headers = {
|
| 65 |
+
'X-API-KEY': self.serper_api_key,
|
| 66 |
+
'Content-Type': 'application/json'
|
| 67 |
+
}
|
| 68 |
+
payload = {
|
| 69 |
+
'q': query,
|
| 70 |
+
'gl': 'us',
|
| 71 |
+
'hl': 'en',
|
| 72 |
+
'num': 5 # Number of results to return
|
| 73 |
+
}
|
| 74 |
|
| 75 |
+
# Make the request
|
| 76 |
+
response = requests.post(serper_url, headers=headers, json=payload, timeout=10)
|
| 77 |
+
self.debug_print(f"Serper API response code: {response.status_code}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
+
if response.status_code == 200:
|
| 80 |
+
search_data = response.json()
|
| 81 |
+
|
| 82 |
+
# Extract organic search results
|
| 83 |
+
results = []
|
| 84 |
+
|
| 85 |
+
# Process organic results
|
| 86 |
+
if 'organic' in search_data:
|
| 87 |
+
for item in search_data['organic'][:3]: # Take top 3 results
|
| 88 |
+
title = item.get('title', '')
|
| 89 |
+
snippet = item.get('snippet', '')
|
| 90 |
+
link = item.get('link', '')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
+
if snippet and link:
|
| 93 |
+
results.append({
|
| 94 |
+
'title': title,
|
| 95 |
+
'content': snippet,
|
| 96 |
+
'url': link
|
| 97 |
+
})
|
| 98 |
+
self.debug_print(f"Added organic result: {title}")
|
| 99 |
+
|
| 100 |
+
# Process answer box if available
|
| 101 |
+
if 'answerBox' in search_data:
|
| 102 |
+
answer_box = search_data['answerBox']
|
| 103 |
+
title = answer_box.get('title', 'Answer Box')
|
| 104 |
+
answer = answer_box.get('answer', '')
|
| 105 |
+
snippet = answer_box.get('snippet', '')
|
| 106 |
+
|
| 107 |
+
# Use the most informative part
|
| 108 |
+
content = answer if answer else snippet
|
| 109 |
+
|
| 110 |
+
if content:
|
| 111 |
results.append({
|
| 112 |
+
'title': title,
|
| 113 |
+
'content': content,
|
| 114 |
+
'url': answer_box.get('link', '')
|
| 115 |
})
|
| 116 |
+
self.debug_print(f"Added answer box: {title}")
|
| 117 |
+
|
| 118 |
+
# Process knowledge graph if available
|
| 119 |
+
if 'knowledgeGraph' in search_data:
|
| 120 |
+
kg = search_data['knowledgeGraph']
|
| 121 |
+
title = kg.get('title', 'Knowledge Graph')
|
| 122 |
+
description = kg.get('description', '')
|
| 123 |
+
|
| 124 |
+
if description:
|
| 125 |
+
results.append({
|
| 126 |
+
'title': title,
|
| 127 |
+
'content': description,
|
| 128 |
+
'url': kg.get('link', '')
|
| 129 |
+
})
|
| 130 |
+
self.debug_print(f"Added knowledge graph: {title}")
|
| 131 |
+
|
| 132 |
+
# Check if we have video results for video-related queries
|
| 133 |
+
if 'videos' in search_data and any(word in query.lower() for word in ["video", "youtube", "watch"]):
|
| 134 |
+
for video in search_data['videos'][:2]: # Take top 2 videos
|
| 135 |
+
title = video.get('title', '')
|
| 136 |
+
link = video.get('link', '')
|
| 137 |
+
|
| 138 |
+
if title and link:
|
| 139 |
+
results.append({
|
| 140 |
+
'title': f"Video: {title}",
|
| 141 |
+
'content': f"Video content: {title}",
|
| 142 |
+
'url': link
|
| 143 |
+
})
|
| 144 |
+
self.debug_print(f"Added video result: {title}")
|
| 145 |
+
|
| 146 |
+
self.debug_print(f"Total results collected: {len(results)}")
|
| 147 |
+
return results
|
| 148 |
+
else:
|
| 149 |
+
self.debug_print(f"Serper API error: {response.status_code} - {response.text}")
|
| 150 |
+
return []
|
| 151 |
+
|
| 152 |
except Exception as e:
|
| 153 |
+
self.debug_print(f"Error in Serper search: {e}")
|
| 154 |
return []
|
| 155 |
|
| 156 |
+
def extract_youtube_video_id(self, url):
|
| 157 |
+
"""Extract YouTube video ID from URL"""
|
| 158 |
+
youtube_regex = r'(youtu\.be\/|youtube\.com\/(watch\?(.*&)?v=|(embed|v)\/))([^?&"\'>]+)'
|
| 159 |
+
youtube_match = re.search(youtube_regex, url)
|
| 160 |
+
if youtube_match:
|
| 161 |
+
return youtube_match.group(5)
|
| 162 |
+
return None
|
| 163 |
+
|
| 164 |
def run(self, question):
|
| 165 |
try:
|
| 166 |
+
self.debug_print(f"\n==== PROCESSING QUESTION ====")
|
| 167 |
+
self.debug_print(f"Question: {question}")
|
| 168 |
|
| 169 |
+
# 1. Try to get context from Serper search
|
| 170 |
+
search_results = self.serper_search(question)
|
| 171 |
|
| 172 |
+
# 2. Process search results
|
| 173 |
search_context = ""
|
| 174 |
|
| 175 |
if search_results:
|
| 176 |
+
search_context = "\n\n".join([
|
| 177 |
+
f"Title: {r['title']}\nContent: {r['content']}\nURL: {r['url']}"
|
| 178 |
+
for r in search_results if r.get('content')
|
| 179 |
+
])
|
| 180 |
+
|
| 181 |
+
self.debug_print(f"Search context created (length: {len(search_context)})")
|
| 182 |
+
if search_context:
|
| 183 |
+
self.debug_print(f"Context excerpt: {search_context[:200]}...")
|
| 184 |
+
else:
|
| 185 |
+
self.debug_print("No usable context from search results")
|
| 186 |
|
| 187 |
# 3. If search provided context, use LLM to get answer
|
| 188 |
if search_context:
|
|
|
|
| 211 |
|
| 212 |
# Clean up the LLM answer (remove explanations, keep it brief)
|
| 213 |
if llm_answer:
|
| 214 |
+
original_answer = llm_answer
|
| 215 |
+
|
| 216 |
# Remove "The answer is" and similar prefixes
|
| 217 |
llm_answer = re.sub(r'^(the answer is|answer:|i believe the answer is|the)[\s:]*', '', llm_answer, flags=re.IGNORECASE)
|
| 218 |
|
|
|
|
| 220 |
llm_answer = llm_answer.split('\n')[0].split('.')[0].strip()
|
| 221 |
|
| 222 |
# Limit length
|
| 223 |
+
if len(llm_answer) > 200:
|
| 224 |
+
llm_answer = llm_answer[:200]
|
| 225 |
+
|
| 226 |
+
self.debug_print(f"Original LLM response: {original_answer}")
|
| 227 |
+
self.debug_print(f"Cleaned answer: {llm_answer}")
|
| 228 |
|
| 229 |
return llm_answer
|
| 230 |
|
| 231 |
# 4. No useful search results or LLM failure
|
| 232 |
+
self.debug_print("Returning 'Insufficient information' due to lack of context or LLM failure")
|
| 233 |
return "Insufficient information"
|
| 234 |
|
| 235 |
except Exception as e:
|
| 236 |
+
self.debug_print(f"Error in agent: {e}")
|
| 237 |
return "Error processing question"
|
| 238 |
|
| 239 |
# Create agent instance
|