Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
"""
|
| 2 |
-
OpenRouter Chatbot –
|
| 3 |
Run: gradio app.py
|
| 4 |
"""
|
| 5 |
|
|
@@ -23,8 +23,6 @@ OPENROUTER_API_KEY = os.getenv(
|
|
| 23 |
def fetch_models() -> list[str]:
|
| 24 |
"""
|
| 25 |
Restituisce la lista completa di modelli offerti da OpenRouter.
|
| 26 |
-
Il decorator @lru_cache la memorizza in cache per tutta la durata
|
| 27 |
-
del processo (si aggiorna solo al riavvio del container).
|
| 28 |
"""
|
| 29 |
headers = {"Authorization": f"Bearer {OPENROUTER_API_KEY}"}
|
| 30 |
try:
|
|
@@ -41,18 +39,32 @@ def fetch_models() -> list[str]:
|
|
| 41 |
gr.Warning(f"Impossibile scaricare l’elenco modelli: {e}")
|
| 42 |
return ["openai/gpt-4-turbo"] # fallback statico
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
# ------------------------------------------------------------------
|
| 45 |
# Funzione di chiamata al modello
|
| 46 |
# ------------------------------------------------------------------
|
| 47 |
-
def chat_with_openrouter(prompt: str, model: str):
|
| 48 |
headers = {
|
| 49 |
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
|
| 50 |
"Content-Type": "application/json"
|
| 51 |
}
|
| 52 |
|
|
|
|
|
|
|
| 53 |
payload = {
|
| 54 |
"model": model,
|
| 55 |
-
"messages":
|
| 56 |
"max_tokens": 4096,
|
| 57 |
"temperature": 0.7,
|
| 58 |
}
|
|
@@ -65,19 +77,24 @@ def chat_with_openrouter(prompt: str, model: str):
|
|
| 65 |
timeout=60
|
| 66 |
)
|
| 67 |
resp.raise_for_status()
|
| 68 |
-
|
|
|
|
|
|
|
| 69 |
except Exception as e:
|
| 70 |
-
|
|
|
|
|
|
|
| 71 |
|
| 72 |
# ------------------------------------------------------------------
|
| 73 |
-
# Interfaccia Gradio
|
| 74 |
# ------------------------------------------------------------------
|
| 75 |
def build_interface():
|
| 76 |
models = fetch_models()
|
| 77 |
|
| 78 |
-
with gr.Blocks(title="NotExistChatter –
|
| 79 |
-
gr.Markdown("🤖project Adam
|
| 80 |
-
gr.Markdown("
|
|
|
|
| 81 |
with gr.Row():
|
| 82 |
model_dropdown = gr.Dropdown(
|
| 83 |
choices=models,
|
|
@@ -87,6 +104,15 @@ def build_interface():
|
|
| 87 |
interactive=True
|
| 88 |
)
|
| 89 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
prompt_box = gr.Textbox(
|
| 91 |
label="Prompt",
|
| 92 |
placeholder="Scrivi qui il tuo messaggio...",
|
|
@@ -94,28 +120,33 @@ def build_interface():
|
|
| 94 |
max_lines=10
|
| 95 |
)
|
| 96 |
|
| 97 |
-
output_box = gr.Textbox(
|
| 98 |
-
label="Risposta",
|
| 99 |
-
interactive=False,
|
| 100 |
-
lines=15,
|
| 101 |
-
max_lines=20
|
| 102 |
-
)
|
| 103 |
-
|
| 104 |
send_btn = gr.Button("Invia", variant="primary")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
send_btn.click(
|
| 106 |
fn=chat_with_openrouter,
|
| 107 |
-
inputs=[prompt_box, model_dropdown],
|
| 108 |
-
outputs=output_box
|
| 109 |
)
|
| 110 |
|
| 111 |
prompt_box.submit(
|
| 112 |
fn=chat_with_openrouter,
|
| 113 |
-
inputs=[prompt_box, model_dropdown],
|
| 114 |
-
outputs=output_box
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
)
|
| 116 |
|
| 117 |
return demo
|
| 118 |
|
| 119 |
-
#
|
|
|
|
|
|
|
| 120 |
if __name__ == "__main__":
|
| 121 |
-
build_interface().launch()
|
|
|
|
| 1 |
"""
|
| 2 |
+
OpenRouter Chatbot – con storico conversazione
|
| 3 |
Run: gradio app.py
|
| 4 |
"""
|
| 5 |
|
|
|
|
| 23 |
def fetch_models() -> list[str]:
|
| 24 |
"""
|
| 25 |
Restituisce la lista completa di modelli offerti da OpenRouter.
|
|
|
|
|
|
|
| 26 |
"""
|
| 27 |
headers = {"Authorization": f"Bearer {OPENROUTER_API_KEY}"}
|
| 28 |
try:
|
|
|
|
| 39 |
gr.Warning(f"Impossibile scaricare l’elenco modelli: {e}")
|
| 40 |
return ["openai/gpt-4-turbo"] # fallback statico
|
| 41 |
|
| 42 |
+
# ------------------------------------------------------------------
|
| 43 |
+
# Funzione per formattare la cronologia
|
| 44 |
+
# ------------------------------------------------------------------
|
| 45 |
+
def format_history(history: list) -> str:
|
| 46 |
+
output = ""
|
| 47 |
+
for msg in history:
|
| 48 |
+
if msg["role"] == "user":
|
| 49 |
+
output += f"🧑💻 **Tu**:\n{msg['content']}\n\n"
|
| 50 |
+
elif msg["role"] == "assistant":
|
| 51 |
+
output += f"🤖 **Assistente**:\n{msg['content']}\n\n"
|
| 52 |
+
return output.strip()
|
| 53 |
+
|
| 54 |
# ------------------------------------------------------------------
|
| 55 |
# Funzione di chiamata al modello
|
| 56 |
# ------------------------------------------------------------------
|
| 57 |
+
def chat_with_openrouter(prompt: str, model: str, history: list):
|
| 58 |
headers = {
|
| 59 |
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
|
| 60 |
"Content-Type": "application/json"
|
| 61 |
}
|
| 62 |
|
| 63 |
+
history.append({"role": "user", "content": prompt})
|
| 64 |
+
|
| 65 |
payload = {
|
| 66 |
"model": model,
|
| 67 |
+
"messages": history,
|
| 68 |
"max_tokens": 4096,
|
| 69 |
"temperature": 0.7,
|
| 70 |
}
|
|
|
|
| 77 |
timeout=60
|
| 78 |
)
|
| 79 |
resp.raise_for_status()
|
| 80 |
+
reply = resp.json()["choices"][0]["message"]["content"]
|
| 81 |
+
history.append({"role": "assistant", "content": reply})
|
| 82 |
+
return history, format_history(history)
|
| 83 |
except Exception as e:
|
| 84 |
+
error_msg = f"❌ Errore: {e}"
|
| 85 |
+
history.append({"role": "assistant", "content": error_msg})
|
| 86 |
+
return history, format_history(history)
|
| 87 |
|
| 88 |
# ------------------------------------------------------------------
|
| 89 |
+
# Interfaccia Gradio con memoria
|
| 90 |
# ------------------------------------------------------------------
|
| 91 |
def build_interface():
|
| 92 |
models = fetch_models()
|
| 93 |
|
| 94 |
+
with gr.Blocks(title="NotExistChatter – Chat con memoria") as demo:
|
| 95 |
+
gr.Markdown("## 🤖 project Adam – Chat dinamica")
|
| 96 |
+
gr.Markdown("Usa **qualsiasi modello** di OpenRouter con cronologia visibile.")
|
| 97 |
+
|
| 98 |
with gr.Row():
|
| 99 |
model_dropdown = gr.Dropdown(
|
| 100 |
choices=models,
|
|
|
|
| 104 |
interactive=True
|
| 105 |
)
|
| 106 |
|
| 107 |
+
reset_btn = gr.Button("🔁 Nuova conversazione")
|
| 108 |
+
|
| 109 |
+
output_box = gr.Textbox(
|
| 110 |
+
label="Conversazione",
|
| 111 |
+
interactive=False,
|
| 112 |
+
lines=20,
|
| 113 |
+
max_lines=40
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
prompt_box = gr.Textbox(
|
| 117 |
label="Prompt",
|
| 118 |
placeholder="Scrivi qui il tuo messaggio...",
|
|
|
|
| 120 |
max_lines=10
|
| 121 |
)
|
| 122 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
send_btn = gr.Button("Invia", variant="primary")
|
| 124 |
+
|
| 125 |
+
# Stato della cronologia
|
| 126 |
+
chat_history = gr.State([])
|
| 127 |
+
|
| 128 |
send_btn.click(
|
| 129 |
fn=chat_with_openrouter,
|
| 130 |
+
inputs=[prompt_box, model_dropdown, chat_history],
|
| 131 |
+
outputs=[chat_history, output_box]
|
| 132 |
)
|
| 133 |
|
| 134 |
prompt_box.submit(
|
| 135 |
fn=chat_with_openrouter,
|
| 136 |
+
inputs=[prompt_box, model_dropdown, chat_history],
|
| 137 |
+
outputs=[chat_history, output_box]
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
reset_btn.click(
|
| 141 |
+
fn=lambda: ([], ""),
|
| 142 |
+
inputs=[],
|
| 143 |
+
outputs=[chat_history, output_box]
|
| 144 |
)
|
| 145 |
|
| 146 |
return demo
|
| 147 |
|
| 148 |
+
# ------------------------------------------------------------------
|
| 149 |
+
# Avvio app
|
| 150 |
+
# ------------------------------------------------------------------
|
| 151 |
if __name__ == "__main__":
|
| 152 |
+
build_interface().launch()
|