File size: 2,262 Bytes
c4b829b
 
 
 
d5ccf60
 
c4b829b
 
 
 
 
 
d5ccf60
 
 
 
 
 
 
 
c4b829b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5ccf60
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
import os
from langchain.tools import Tool
from serpapi import GoogleSearch
from dotenv import load_dotenv
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.tools import tool

# Carica le variabili d'ambiente se hai la chiave API in un file .env
load_dotenv()

SERPAPI_API_KEY = os.getenv("SERPAPI_API_KEY")

search_tool = TavilySearchResults(
    name="tavily_web_search", # Puoi personalizzare il nome se vuoi
    description="Esegue una ricerca web avanzata utilizzando Tavily per informazioni aggiornate e complete. Utile per domande complesse o che richiedono dati recenti. Può essere utile fare più ricerche modificando la query per ottenere risultati migliori.", # Descrizione per l'LLM
    max_results=5
)

@tool("serpapi_search_tool", parse_docstring=True)
def serpapi_search(query: str, num_results: int = 5, gl: str = "it", hl: str = "it") -> str:
    """
    Esegue una ricerca sul web utilizzando SerpAPI con Google Search e restituisce i risultati formattati.
    Questo tool ha un costo elevato, pertanto sono da preferire altri tool se disponibili.
    Richiamare questo tool soltanto in caso gli altri tool non siano stati soddisfacenti.

    Args:
        query: La query di ricerca.
        num_results: Il numero di risultati da restituire.
        gl: Codice del paese per la geolocalizzazione dei risultati (es. "it" per Italia).
        hl: Codice della lingua per i risultati della ricerca (es. "it" per Italiano).

    Returns:
        Una stringa formattata con i risultati della ricerca o un messaggio di errore.
    """
    if not SERPAPI_API_KEY:
        return "Errore: La variabile d'ambiente SERPAPI_API_KEY non è impostata."

    params = {
        "engine": "google",
        "q": query,
        "api_key": SERPAPI_API_KEY,
        "num": num_results,
        "gl": gl,
        "hl": hl
    }
    search = GoogleSearch(params)
    results = search.get_dict()
    organic_results = results.get("organic_results", [])

    if not organic_results:
        return f"Nessun risultato trovato per '{query}'."

    formatted_results = "\n\n".join([f"Title: {res.get('title')}\nLink: {res.get('link')}\nSnippet: {res.get('snippet')}" for res in organic_results])
    return formatted_results