walidsobhie-code commited on
Commit
35799ef
·
1 Parent(s): 3c29912

Fix search with DuckDuckGo API (proper JSON parsing)

Browse files
Files changed (1) hide show
  1. chat.py +18 -7
chat.py CHANGED
@@ -30,14 +30,24 @@ print(f"Settings: max_tokens={MAX_TOKENS}, temperature={TEMPERATURE}, top_p={TOP
30
  print("Commands: search:<query> - search the web, quit/exit - stop\n")
31
 
32
  def web_search(query, count=5):
33
- """Search the web using DuckDuckGo JSON API"""
34
  try:
35
- url = f"https://duckduckgo.com/?q={query}&format=json&no_redirect=1"
 
 
36
  headers = {"User-Agent": "Mozilla/5.0 (compatible; Stack29Bot/1.0)"}
37
  resp = requests.get(url, headers=headers, timeout=10)
38
- if resp.status_code == 200:
39
- return {"success": True, "results": [{"query": query, "source": "duckduckgo"}]}
40
- return {"success": False, "error": f"HTTP {resp.status_code}"}
 
 
 
 
 
 
 
 
41
  except Exception as e:
42
  return {"success": False, "error": str(e)}
43
 
@@ -56,8 +66,9 @@ while True:
56
  print("🔍 Searching...")
57
  result = web_search(query)
58
  if result["success"]:
59
- print(f"✅ Found results for: {query}")
60
- print(f" (Web search results would appear here)")
 
61
  else:
62
  print(f"❌ Search failed: {result['error']}")
63
  continue
 
30
  print("Commands: search:<query> - search the web, quit/exit - stop\n")
31
 
32
  def web_search(query, count=5):
33
+ """Search the web using DuckDuckGo API"""
34
  try:
35
+ import urllib.parse
36
+ encoded_q = urllib.parse.quote(query)
37
+ url = f"https://api.duckduckgo.com/?q={encoded_q}&format=json&no_redirect=1"
38
  headers = {"User-Agent": "Mozilla/5.0 (compatible; Stack29Bot/1.0)"}
39
  resp = requests.get(url, headers=headers, timeout=10)
40
+ data = resp.json()
41
+
42
+ results = []
43
+ if "RelatedTopics" in data:
44
+ for item in data["RelatedTopics"][:count]:
45
+ if "Text" in item:
46
+ results.append(item["Text"][:200])
47
+
48
+ if results:
49
+ return {"success": True, "results": results, "query": query}
50
+ return {"success": False, "error": "No results found"}
51
  except Exception as e:
52
  return {"success": False, "error": str(e)}
53
 
 
66
  print("🔍 Searching...")
67
  result = web_search(query)
68
  if result["success"]:
69
+ print(f"✅ Results for '{result['query']}':\n")
70
+ for i, r in enumerate(result["results"], 1):
71
+ print(f" {i}. {r}")
72
  else:
73
  print(f"❌ Search failed: {result['error']}")
74
  continue