Spaces:
Sleeping
Sleeping
Alternative to Duck
Browse files- tools/http_search.py +60 -0
tools/http_search.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, Any
|
| 2 |
+
from smolagents.tools import Tool
|
| 3 |
+
import requests
|
| 4 |
+
import json
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class HttpSearchTool(Tool):
|
| 8 |
+
name = "http_search"
|
| 9 |
+
description = (
|
| 10 |
+
"Appelle une API HTTP de recherche et renvoie un résumé lisible des résultats. "
|
| 11 |
+
"Configure l'URL de base et le paramètre de requête dans le code."
|
| 12 |
+
)
|
| 13 |
+
inputs = {
|
| 14 |
+
"query": {
|
| 15 |
+
"type": "string",
|
| 16 |
+
"description": "La requête de recherche à envoyer à l'API HTTP.",
|
| 17 |
+
}
|
| 18 |
+
}
|
| 19 |
+
output_type = "string"
|
| 20 |
+
|
| 21 |
+
def __init__(self, base_url: str, query_param: str = "q", extra_params: Dict[str, Any] = None, headers: Dict[str, str] = None):
|
| 22 |
+
"""
|
| 23 |
+
Args:
|
| 24 |
+
base_url: URL de l'API de recherche (ex: 'https://api.serpapi.com/search').
|
| 25 |
+
query_param: nom du paramètre utilisé pour la requête (ex: 'q', 'query', ...).
|
| 26 |
+
extra_params: dict de paramètres fixes à ajouter à chaque requête (clé API, type de moteur, etc.).
|
| 27 |
+
headers: headers HTTP à envoyer (optionnels).
|
| 28 |
+
"""
|
| 29 |
+
super().__init__()
|
| 30 |
+
self.base_url = base_url
|
| 31 |
+
self.query_param = query_param
|
| 32 |
+
self.extra_params = extra_params or {}
|
| 33 |
+
self.headers = headers or {}
|
| 34 |
+
|
| 35 |
+
def forward(self, query: str) -> str:
|
| 36 |
+
params = {self.query_param: query}
|
| 37 |
+
params.update(self.extra_params)
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
resp = requests.get(self.base_url, params=params, headers=self.headers, timeout=20)
|
| 41 |
+
resp.raise_for_status()
|
| 42 |
+
except Exception as e:
|
| 43 |
+
return f"Erreur lors de l'appel HTTP à l'API de recherche : {e}"
|
| 44 |
+
|
| 45 |
+
# On suppose une réponse JSON
|
| 46 |
+
try:
|
| 47 |
+
data = resp.json()
|
| 48 |
+
except Exception:
|
| 49 |
+
# Si ce n'est pas du JSON, on renvoie le texte brut tronqué
|
| 50 |
+
text = resp.text
|
| 51 |
+
if len(text) > 1000:
|
| 52 |
+
text = text[:997] + "..."
|
| 53 |
+
return f"Réponse non JSON de l'API :\n{text}"
|
| 54 |
+
|
| 55 |
+
# Résumé générique, l'agent pourra ensuite analyser le JSON plus finement si besoin
|
| 56 |
+
pretty = json.dumps(data, indent=2, ensure_ascii=False)
|
| 57 |
+
if len(pretty) > 2000:
|
| 58 |
+
pretty = pretty[:1997] + "..."
|
| 59 |
+
|
| 60 |
+
return f"Résultats bruts de l'API HTTP pour la requête \"{query}\" :\n{pretty}"
|