final-agent-course / agent.py
jjvelezo's picture
Update agent.py
a9e9116 verified
raw
history blame
2.96 kB
import requests
import urllib.parse
from bs4 import BeautifulSoup
class DuckDuckGoAgent:
def __init__(self):
print("DuckDuckGoAgent initialized.")
self.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
}
self.gemini_api_key = None # Opcional: pon aquí tu clave si usas Gemini
def get_duckduckgo_answer(self, query: str) -> str:
search_query = urllib.parse.quote(query)
url = f"https://api.duckduckgo.com/?q={search_query}&format=json&no_html=1&skip_disambig=1"
try:
response = requests.get(url, timeout=10)
if response.status_code == 200:
data = response.json()
if data.get('AbstractText'):
return data['AbstractText'][:200]
else:
return self.scrape_duckduckgo(query) # Fallback
else:
return self.scrape_duckduckgo(query)
except Exception as e:
print(f"Error in API: {e}")
return self.scrape_duckduckgo(query)
def scrape_duckduckgo(self, query: str) -> str:
print("Using fallback: scraping HTML results.")
try:
response = requests.post(
"https://html.duckduckgo.com/html/",
data={"q": query},
headers=self.headers,
timeout=10
)
soup = BeautifulSoup(response.text, "html.parser")
snippets = soup.select(".result__snippet")
for s in snippets:
text = s.get_text().strip()
if text:
return text[:200]
return "No se encontró una respuesta adecuada en DuckDuckGo."
except Exception as e:
print(f"Scraping error: {e}")
return self.call_gemini_backup(query)
def call_gemini_backup(self, prompt: str) -> str:
if not self.gemini_api_key:
return "Error al contactar con DuckDuckGo."
try:
response = requests.post(
"https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent",
headers={"Content-Type": "application/json"},
params={"key": self.gemini_api_key},
json={"contents": [{"parts": [{"text": prompt}]}]},
timeout=15
)
if response.status_code == 200:
data = response.json()
text = data["candidates"][0]["content"]["parts"][0]["text"]
return text.strip()[:200]
else:
return "Error con Gemini 2.0."
except Exception as e:
print(f"Gemini fallback error: {e}")
return "Error al contactar con DuckDuckGo."
def __call__(self, question: str) -> str:
print(f"Agent received question: {question[:50]}...")
return self.get_duckduckgo_answer(question)