Spaces:
Sleeping
Sleeping
Update agent.py
Browse files
agent.py
CHANGED
@@ -1,32 +1,75 @@
|
|
1 |
import requests
|
2 |
import urllib.parse
|
|
|
3 |
|
4 |
class DuckDuckGoAgent:
|
5 |
def __init__(self):
|
6 |
print("DuckDuckGoAgent initialized.")
|
7 |
-
|
|
|
|
|
|
|
|
|
8 |
def get_duckduckgo_answer(self, query: str) -> str:
|
9 |
-
# Crear una consulta de búsqueda para DuckDuckGo
|
10 |
search_query = urllib.parse.quote(query)
|
11 |
url = f"https://api.duckduckgo.com/?q={search_query}&format=json&no_html=1&skip_disambig=1"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
|
|
|
|
|
|
22 |
else:
|
23 |
-
return "
|
24 |
-
|
|
|
25 |
return "Error al contactar con DuckDuckGo."
|
26 |
|
27 |
def __call__(self, question: str) -> str:
|
28 |
-
print(f"Agent received question
|
29 |
-
|
30 |
-
answer = self.get_duckduckgo_answer(question)
|
31 |
-
print(f"Agent returning answer: {answer}")
|
32 |
-
return answer
|
|
|
1 |
import requests
|
2 |
import urllib.parse
|
3 |
+
from bs4 import BeautifulSoup
|
4 |
|
5 |
class DuckDuckGoAgent:
|
6 |
def __init__(self):
|
7 |
print("DuckDuckGoAgent initialized.")
|
8 |
+
self.headers = {
|
9 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
|
10 |
+
}
|
11 |
+
self.gemini_api_key = None # Opcional: pon aquí tu clave si usas Gemini
|
12 |
+
|
13 |
def get_duckduckgo_answer(self, query: str) -> str:
|
|
|
14 |
search_query = urllib.parse.quote(query)
|
15 |
url = f"https://api.duckduckgo.com/?q={search_query}&format=json&no_html=1&skip_disambig=1"
|
16 |
+
|
17 |
+
try:
|
18 |
+
response = requests.get(url, timeout=10)
|
19 |
+
if response.status_code == 200:
|
20 |
+
data = response.json()
|
21 |
+
if data.get('AbstractText'):
|
22 |
+
return data['AbstractText'][:200]
|
23 |
+
else:
|
24 |
+
return self.scrape_duckduckgo(query) # Fallback
|
25 |
+
else:
|
26 |
+
return self.scrape_duckduckgo(query)
|
27 |
+
except Exception as e:
|
28 |
+
print(f"Error in API: {e}")
|
29 |
+
return self.scrape_duckduckgo(query)
|
30 |
+
|
31 |
+
def scrape_duckduckgo(self, query: str) -> str:
|
32 |
+
print("Using fallback: scraping HTML results.")
|
33 |
+
try:
|
34 |
+
response = requests.post(
|
35 |
+
"https://html.duckduckgo.com/html/",
|
36 |
+
data={"q": query},
|
37 |
+
headers=self.headers,
|
38 |
+
timeout=10
|
39 |
+
)
|
40 |
+
soup = BeautifulSoup(response.text, "html.parser")
|
41 |
+
snippets = soup.select(".result__snippet")
|
42 |
+
for s in snippets:
|
43 |
+
text = s.get_text().strip()
|
44 |
+
if text:
|
45 |
+
return text[:200]
|
46 |
+
return "No se encontró una respuesta adecuada en DuckDuckGo."
|
47 |
+
except Exception as e:
|
48 |
+
print(f"Scraping error: {e}")
|
49 |
+
return self.call_gemini_backup(query)
|
50 |
+
|
51 |
+
def call_gemini_backup(self, prompt: str) -> str:
|
52 |
+
if not self.gemini_api_key:
|
53 |
+
return "Error al contactar con DuckDuckGo."
|
54 |
|
55 |
+
try:
|
56 |
+
response = requests.post(
|
57 |
+
"https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent",
|
58 |
+
headers={"Content-Type": "application/json"},
|
59 |
+
params={"key": self.gemini_api_key},
|
60 |
+
json={"contents": [{"parts": [{"text": prompt}]}]},
|
61 |
+
timeout=15
|
62 |
+
)
|
63 |
+
if response.status_code == 200:
|
64 |
+
data = response.json()
|
65 |
+
text = data["candidates"][0]["content"]["parts"][0]["text"]
|
66 |
+
return text.strip()[:200]
|
67 |
else:
|
68 |
+
return "Error con Gemini 2.0."
|
69 |
+
except Exception as e:
|
70 |
+
print(f"Gemini fallback error: {e}")
|
71 |
return "Error al contactar con DuckDuckGo."
|
72 |
|
73 |
def __call__(self, question: str) -> str:
|
74 |
+
print(f"Agent received question: {question[:50]}...")
|
75 |
+
return self.get_duckduckgo_answer(question)
|
|
|
|
|
|