Spaces:
Running
Running
Update agent.py
Browse files
agent.py
CHANGED
@@ -1,3 +1,4 @@
|
|
|
|
1 |
import requests
|
2 |
import urllib.parse
|
3 |
from bs4 import BeautifulSoup
|
@@ -6,9 +7,8 @@ class DuckDuckGoAgent:
|
|
6 |
def __init__(self):
|
7 |
print("DuckDuckGoAgent initialized.")
|
8 |
self.headers = {
|
9 |
-
"User-Agent": "Mozilla/5.0
|
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)
|
@@ -18,14 +18,16 @@ class DuckDuckGoAgent:
|
|
18 |
response = requests.get(url, timeout=10)
|
19 |
if response.status_code == 200:
|
20 |
data = response.json()
|
21 |
-
if data
|
22 |
return data['AbstractText'][:200]
|
23 |
else:
|
24 |
-
|
|
|
25 |
else:
|
|
|
26 |
return self.scrape_duckduckgo(query)
|
27 |
except Exception as e:
|
28 |
-
print(f"Error
|
29 |
return self.scrape_duckduckgo(query)
|
30 |
|
31 |
def scrape_duckduckgo(self, query: str) -> str:
|
@@ -43,33 +45,49 @@ class DuckDuckGoAgent:
|
|
43 |
text = s.get_text().strip()
|
44 |
if text:
|
45 |
return text[:200]
|
46 |
-
|
|
|
47 |
except Exception as e:
|
48 |
print(f"Scraping error: {e}")
|
49 |
-
return self.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
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 "
|
69 |
except Exception as e:
|
70 |
-
print(f"
|
71 |
-
return "Error al contactar con
|
72 |
|
73 |
def __call__(self, question: str) -> str:
|
74 |
-
print(f"Agent received question: {question[:50]}...")
|
75 |
-
|
|
|
|
|
|
1 |
+
import os
|
2 |
import requests
|
3 |
import urllib.parse
|
4 |
from bs4 import BeautifulSoup
|
|
|
7 |
def __init__(self):
|
8 |
print("DuckDuckGoAgent initialized.")
|
9 |
self.headers = {
|
10 |
+
"User-Agent": "Mozilla/5.0"
|
11 |
}
|
|
|
12 |
|
13 |
def get_duckduckgo_answer(self, query: str) -> str:
|
14 |
search_query = urllib.parse.quote(query)
|
|
|
18 |
response = requests.get(url, timeout=10)
|
19 |
if response.status_code == 200:
|
20 |
data = response.json()
|
21 |
+
if 'AbstractText' in data and data['AbstractText']:
|
22 |
return data['AbstractText'][:200]
|
23 |
else:
|
24 |
+
print("No abstract found, falling back to scraping.")
|
25 |
+
return self.scrape_duckduckgo(query)
|
26 |
else:
|
27 |
+
print(f"DuckDuckGo API failed: {response.status_code}")
|
28 |
return self.scrape_duckduckgo(query)
|
29 |
except Exception as e:
|
30 |
+
print(f"Error contacting DuckDuckGo API: {e}")
|
31 |
return self.scrape_duckduckgo(query)
|
32 |
|
33 |
def scrape_duckduckgo(self, query: str) -> str:
|
|
|
45 |
text = s.get_text().strip()
|
46 |
if text:
|
47 |
return text[:200]
|
48 |
+
print("No useful snippets found, using Hugging Face LLM.")
|
49 |
+
return self.call_huggingface_llm(query)
|
50 |
except Exception as e:
|
51 |
print(f"Scraping error: {e}")
|
52 |
+
return self.call_huggingface_llm(query)
|
53 |
+
|
54 |
+
def call_huggingface_llm(self, prompt: str) -> str:
|
55 |
+
hf_api_key = os.getenv("HF_API_TOKEN")
|
56 |
+
model = "mistralai/Mistral-7B-Instruct-v0.1"
|
57 |
+
|
58 |
+
if not hf_api_key:
|
59 |
+
return "Error: Hugging Face API Token no configurado."
|
60 |
+
|
61 |
+
url = f"https://api-inference.huggingface.co/models/{model}"
|
62 |
+
headers = {
|
63 |
+
"Authorization": f"Bearer {hf_api_key}",
|
64 |
+
"Content-Type": "application/json"
|
65 |
+
}
|
66 |
+
|
67 |
+
payload = {
|
68 |
+
"inputs": prompt,
|
69 |
+
"parameters": {
|
70 |
+
"max_new_tokens": 200,
|
71 |
+
"temperature": 0.7
|
72 |
+
}
|
73 |
+
}
|
74 |
|
|
|
|
|
|
|
|
|
75 |
try:
|
76 |
+
response = requests.post(url, headers=headers, json=payload, timeout=30)
|
77 |
+
response.raise_for_status()
|
78 |
+
output = response.json()
|
79 |
+
if isinstance(output, list) and "generated_text" in output[0]:
|
80 |
+
return output[0]["generated_text"].strip()[:200]
|
81 |
+
elif isinstance(output, dict) and "error" in output:
|
82 |
+
return f"HF LLM error: {output['error']}"
|
|
|
|
|
|
|
|
|
83 |
else:
|
84 |
+
return "No se pudo obtener respuesta del LLM."
|
85 |
except Exception as e:
|
86 |
+
print(f"Error en Hugging Face LLM: {e}")
|
87 |
+
return "Error al contactar con el modelo Hugging Face."
|
88 |
|
89 |
def __call__(self, question: str) -> str:
|
90 |
+
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
91 |
+
answer = self.get_duckduckgo_answer(question)
|
92 |
+
print(f"Agent returning answer: {answer}")
|
93 |
+
return answer
|