jjvelezo commited on
Commit
f51a39b
·
verified ·
1 Parent(s): c328ad6

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +23 -8
agent.py CHANGED
@@ -11,6 +11,10 @@ class DuckDuckGoAgent:
11
  }
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
 
@@ -18,19 +22,23 @@ class DuckDuckGoAgent:
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:
 
 
 
34
  print("Using fallback: scraping HTML results.")
35
  try:
36
  response = requests.post(
@@ -45,18 +53,21 @@ class DuckDuckGoAgent:
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 = {
@@ -81,13 +92,17 @@ class DuckDuckGoAgent:
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
 
11
  }
12
 
13
  def get_duckduckgo_answer(self, query: str) -> str:
14
+ """
15
+ Attempt to get an answer from the DuckDuckGo API.
16
+ If no abstract text is found, fall back to scraping.
17
+ """
18
  search_query = urllib.parse.quote(query)
19
  url = f"https://api.duckduckgo.com/?q={search_query}&format=json&no_html=1&skip_disambig=1"
20
 
 
22
  response = requests.get(url, timeout=10)
23
  if response.status_code == 200:
24
  data = response.json()
25
+ # If AbstractText exists and is non-empty, return it
26
  if 'AbstractText' in data and data['AbstractText']:
27
  return data['AbstractText'][:200]
28
  else:
29
  print("No abstract found, falling back to scraping.")
30
  return self.scrape_duckduckgo(query)
31
  else:
32
+ print(f"DuckDuckGo API failed with status: {response.status_code}")
33
  return self.scrape_duckduckgo(query)
34
  except Exception as e:
35
  print(f"Error contacting DuckDuckGo API: {e}")
36
  return self.scrape_duckduckgo(query)
37
 
38
  def scrape_duckduckgo(self, query: str) -> str:
39
+ """
40
+ Fallback to scraping DuckDuckGo search results if API fails or no abstract found.
41
+ """
42
  print("Using fallback: scraping HTML results.")
43
  try:
44
  response = requests.post(
 
53
  text = s.get_text().strip()
54
  if text:
55
  return text[:200]
56
+ print("No useful snippets found, falling back to Hugging Face LLM.")
57
  return self.call_huggingface_llm(query)
58
  except Exception as e:
59
+ print(f"Error scraping DuckDuckGo: {e}")
60
  return self.call_huggingface_llm(query)
61
 
62
  def call_huggingface_llm(self, prompt: str) -> str:
63
+ """
64
+ Fallback to Hugging Face LLM if DuckDuckGo API and scraping both fail.
65
+ """
66
  hf_api_key = os.getenv("HF_API_TOKEN")
67
  model = "mistralai/Mistral-7B-Instruct-v0.1"
68
 
69
  if not hf_api_key:
70
+ return "Error: Hugging Face API Token is not configured."
71
 
72
  url = f"https://api-inference.huggingface.co/models/{model}"
73
  headers = {
 
92
  elif isinstance(output, dict) and "error" in output:
93
  return f"HF LLM error: {output['error']}"
94
  else:
95
+ return "No response generated from Hugging Face LLM."
96
  except Exception as e:
97
+ print(f"Error contacting Hugging Face LLM: {e}")
98
+ return "Error contacting Hugging Face model."
99
 
100
  def __call__(self, question: str) -> str:
101
+ """
102
+ Main entry point for the agent to process a question.
103
+ It will first attempt DuckDuckGo, then fall back to scraping or Hugging Face LLM.
104
+ """
105
+ print(f"Agent received question: {question[:50]}...")
106
  answer = self.get_duckduckgo_answer(question)
107
  print(f"Agent returning answer: {answer}")
108
  return answer