Create tools.py
#181
by
oniwaka
- opened
tools.py
ADDED
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# tools.py
|
2 |
+
import requests
|
3 |
+
import os
|
4 |
+
from langchain_core.tools import tool
|
5 |
+
from duckduckgo_search import DDGS
|
6 |
+
from langchain_community.tools import PythonREPLTool
|
7 |
+
|
8 |
+
import config
|
9 |
+
|
10 |
+
# --- Strumenti per l'API del Corso ---
|
11 |
+
|
12 |
+
@tool
|
13 |
+
def get_all_questions():
|
14 |
+
"""
|
15 |
+
Recupera l'elenco di tutte le domande disponibili per la valutazione finale.
|
16 |
+
Da usare solo una volta all'inizio per ottenere i task_id.
|
17 |
+
"""
|
18 |
+
try:
|
19 |
+
response = requests.get(f"{config.BASE_API_URL}/questions", headers=config.HEADERS)
|
20 |
+
response.raise_for_status()
|
21 |
+
return response.json()
|
22 |
+
except requests.exceptions.RequestException as e:
|
23 |
+
return f"Errore API durante il recupero delle domande: {e}"
|
24 |
+
|
25 |
+
@tool
|
26 |
+
def download_file_by_task_id(task_id: str) -> str:
|
27 |
+
"""
|
28 |
+
Scarica un file associato a uno specifico task_id.
|
29 |
+
L'input deve essere il task_id.
|
30 |
+
Salva il file localmente e restituisce il percorso del file scaricato.
|
31 |
+
Usare questo strumento quando la domanda richiede di analizzare un file.
|
32 |
+
"""
|
33 |
+
try:
|
34 |
+
# Crea la directory 'downloads' se non esiste
|
35 |
+
if not os.path.exists('downloads'):
|
36 |
+
os.makedirs('downloads')
|
37 |
+
|
38 |
+
response = requests.get(f"{config.BASE_API_URL}/files/{task_id}", headers=config.HEADERS)
|
39 |
+
response.raise_for_status()
|
40 |
+
|
41 |
+
# Estrai il nome del file dagli header se possibile, altrimenti usa un nome di default
|
42 |
+
content_disposition = response.headers.get('content-disposition')
|
43 |
+
if content_disposition:
|
44 |
+
try:
|
45 |
+
filename = content_disposition.split('filename=')[1].strip('"')
|
46 |
+
except IndexError:
|
47 |
+
filename = f"{task_id}_file" # Fallback
|
48 |
+
else:
|
49 |
+
filename = f"{task_id}_file"
|
50 |
+
|
51 |
+
file_path = os.path.join('downloads', filename)
|
52 |
+
with open(file_path, 'wb') as f:
|
53 |
+
f.write(response.content)
|
54 |
+
|
55 |
+
return f"File per il task_id '{task_id}' scaricato con successo in '{file_path}'. Contenuto del file:\n---\n{response.content.decode('utf-8', errors='ignore')[:2000]}\n---"
|
56 |
+
except requests.exceptions.RequestException as e:
|
57 |
+
return f"Errore API durante il download del file per task_id {task_id}: {e}"
|
58 |
+
except Exception as e:
|
59 |
+
return f"Errore durante il salvataggio del file per task_id {task_id}: {e}"
|
60 |
+
|
61 |
+
|
62 |
+
@tool
|
63 |
+
def submit_answer(task_id: str, answer: str) -> str:
|
64 |
+
"""
|
65 |
+
Invia la risposta finale per un dato task_id.
|
66 |
+
Prende come input il task_id e la stringa della risposta.
|
67 |
+
La risposta deve essere esatta, senza prefissi o formattazione extra.
|
68 |
+
"""
|
69 |
+
payload = {
|
70 |
+
"task_id": task_id,
|
71 |
+
"submitted_answer": answer,
|
72 |
+
"username": config.HF_USERNAME
|
73 |
+
}
|
74 |
+
try:
|
75 |
+
response = requests.post(f"{config.BASE_API_URL}/submit", headers=config.HEADERS, json=payload)
|
76 |
+
response.raise_for_status()
|
77 |
+
return f"Risposta per {task_id} inviata con successo: {response.json()}"
|
78 |
+
except requests.exceptions.RequestException as e:
|
79 |
+
return f"Errore API durante l'invio della risposta per {task_id}: {e}"
|
80 |
+
|
81 |
+
# --- Strumenti Generici ---
|
82 |
+
|
83 |
+
@tool
|
84 |
+
def web_search(query: str) -> str:
|
85 |
+
"""
|
86 |
+
Esegue una ricerca web utilizzando DuckDuckGo per trovare informazioni aggiornate
|
87 |
+
o dati non presenti nel contesto. Utilizza questo strumento quando la domanda
|
88 |
+
riguarda eventi recenti, fatti specifici, o richiede conoscenza esterna.
|
89 |
+
L'input Γ¨ la query di ricerca.
|
90 |
+
"""
|
91 |
+
with DDGS() as ddgs:
|
92 |
+
results = [r for r in ddgs.text(query, max_results=5)]
|
93 |
+
return "\n".join([f"Fonte: {r['href']}\nSnippet: {r['body']}" for r in results]) if results else "Nessun risultato trovato."
|
94 |
+
|
95 |
+
# Strumento per calcoli e esecuzione codice
|
96 |
+
python_interpreter = PythonREPLTool()
|