eugpal4 commited on
Commit
6bb1177
·
verified ·
1 Parent(s): 8c5c24b

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +70 -0
main.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import json
4
+ import requests
5
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, InferenceClientModel
6
+ from tools import duckduckgo_search, wikipedia_search, summarize_text, load_memory, save_memory
7
+
8
+
9
+ tokens = os.environ.get('HUGGINGFACEHUB_API_TOKEN')
10
+ print(tokens)
11
+
12
+ token = os.getenv('HF_HOME/token')
13
+ #Token di Autorizzazione (verifica ambiente)
14
+ token = 'HUGGINGFACEHUB_API_TOKEN'
15
+ if not token:
16
+ raise ValueError("Imposta la variabile d'ambiente HF_TOKEN")
17
+
18
+ # Scegli il modello
19
+ model = HfApiModel(model_id="google/flan-t5-base", token=token)
20
+
21
+ # Strumenti
22
+ tools = [DuckDuckGoSearchTool(), wikipedia_search]
23
+
24
+ agent = CodeAgent(
25
+ tools=tools,
26
+ model=model,
27
+ additional_authorized_imports=["requests", "bs4"]
28
+ )
29
+
30
+ def run_agent(query: str) -> str:
31
+ try:
32
+ memory = load_memory()
33
+ if query in memory:
34
+ return memory[query]
35
+
36
+ # Ricerca e sintesi
37
+ duck_text = duckduckgo_search(query, max_results=3)
38
+ wiki_text = wikipedia_search(query)
39
+
40
+ duck_summary = summarize_text(duck_text, max_length=150)
41
+ wiki_summary = summarize_text(wiki_text, max_length=150)
42
+
43
+ prompt = (
44
+ f"Domanda: {query}\n\n"
45
+ f"Informazioni sintetizzate da Wikipedia:\n{wiki_summary}\n\n"
46
+ f"Informazioni sintetizzate da DuckDuckGo:\n{duck_summary}\n\n"
47
+ "Fornisci una risposta sintetica e chiara."
48
+ )
49
+
50
+ # Verifica tipo modello e chiama generate con argomento corretto
51
+ if isinstance(model, InferenceClientModel):
52
+ messages = [
53
+ {"role": "system", "content": "Sei un assistente utile."},
54
+ {"role": "user", "content": prompt}
55
+ ]
56
+ response = model.generate(messages=messages)
57
+ else:
58
+ response = model.generate(prompt=prompt, max_new_tokens=200)
59
+
60
+ # Controllo per risposte vuote
61
+ if not response.strip():
62
+ response = "Non ho capito la domanda, per favore riprova."
63
+
64
+ memory[query] = response
65
+ save_memory(memory)
66
+
67
+ return response
68
+
69
+ except Exception as e:
70
+ return f"Errore durante l'esecuzione dell'agent: {str(e)}"