File size: 1,908 Bytes
30b5e11 f3a56a5 30b5e11 f3a56a5 30b5e11 f3a56a5 30b5e11 f3a56a5 30b5e11 f3a56a5 30b5e11 f3a56a5 30b5e11 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
from tavily import TavilyClient
from duckduckgo_search import DDGS
import os
from dotenv import load_dotenv
load_dotenv()
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
def web_search(query: str):
results = []
images = []
# 1. TENTATIVE AVEC TAVILY
if TAVILY_API_KEY:
try:
print(f"🔍 Recherche Tavily pour : {query}")
tavily = TavilyClient(api_key=TAVILY_API_KEY)
res = tavily.search(
query=query,
max_results=5,
search_depth="advanced",
include_images=True
)
results = res.get('results', [])
images = res.get('images', [])
if len(results) >= 2:
return {"results": results, "images": images, "query": query, "source": "Tavily"}
except Exception as e:
print(f"⚠️ Tavily Error: {e}")
# 2. FALLBACK AVEC DUCKDUCKGO
print(f"🦆 Fallback DuckDuckGo pour : {query}")
try:
with DDGS() as ddgs:
ddg_gen = ddgs.text(query, max_results=5)
if ddg_gen:
for r in ddg_gen:
results.append({
"title": r.get('title'),
"content": r.get('body'),
"url": r.get('href')
})
try:
ddg_img_gen = ddgs.images(query, max_results=3)
if ddg_img_gen:
images = [img.get('image') for img in ddg_img_gen if img.get('image')]
except Exception:
pass
except Exception as e:
print(f"❌ DuckDuckGo Error: {e}")
return {
"results": results,
"images": images,
"query": query,
"source": "Fallback/DDG"
} |