Update app.py
Browse files
app.py
CHANGED
|
@@ -1,70 +1,110 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
def
|
| 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 |
-
stream=True,
|
| 31 |
-
temperature=temperature,
|
| 32 |
-
top_p=top_p,
|
| 33 |
-
):
|
| 34 |
-
choices = message.choices
|
| 35 |
-
token = ""
|
| 36 |
-
if len(choices) and choices[0].delta.content:
|
| 37 |
-
token = choices[0].delta.content
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
|
|
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
| 45 |
"""
|
| 46 |
-
chatbot = gr.ChatInterface(
|
| 47 |
-
respond,
|
| 48 |
-
type="messages",
|
| 49 |
-
additional_inputs=[
|
| 50 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
| 51 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
| 52 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
| 53 |
-
gr.Slider(
|
| 54 |
-
minimum=0.1,
|
| 55 |
-
maximum=1.0,
|
| 56 |
-
value=0.95,
|
| 57 |
-
step=0.05,
|
| 58 |
-
label="Top-p (nucleus sampling)",
|
| 59 |
-
),
|
| 60 |
-
],
|
| 61 |
-
)
|
| 62 |
-
|
| 63 |
-
with gr.Blocks() as demo:
|
| 64 |
-
with gr.Sidebar():
|
| 65 |
-
gr.LoginButton()
|
| 66 |
-
chatbot.render()
|
| 67 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
-
|
| 70 |
-
demo.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import sqlite3
|
| 3 |
+
import torch
|
| 4 |
+
import os
|
| 5 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 6 |
+
from peft import PeftModel
|
| 7 |
|
| 8 |
+
# --- TEIL 1: Die Dummy-Datenbank ---
|
| 9 |
+
DB_PATH = "dummy_database.db"
|
| 10 |
|
| 11 |
+
def setup_db():
|
| 12 |
+
"""Erstellt die Datenbank bei jedem Neustart frisch (ideal für Demos)"""
|
| 13 |
+
if os.path.exists(DB_PATH):
|
| 14 |
+
os.remove(DB_PATH) # Aufräumen für sauberen Start
|
| 15 |
+
|
| 16 |
+
conn = sqlite3.connect(DB_PATH)
|
| 17 |
+
cursor = conn.cursor()
|
| 18 |
+
cursor.execute("""
|
| 19 |
+
CREATE TABLE employees (
|
| 20 |
+
id INTEGER PRIMARY KEY,
|
| 21 |
+
name TEXT,
|
| 22 |
+
department TEXT,
|
| 23 |
+
salary INTEGER,
|
| 24 |
+
hire_date DATE
|
| 25 |
+
)
|
| 26 |
+
""")
|
| 27 |
+
employees = [
|
| 28 |
+
(1, 'Alice Smith', 'Sales', 55000, '2021-01-15'),
|
| 29 |
+
(2, 'Bob Jones', 'Engineering', 85000, '2020-03-10'),
|
| 30 |
+
(3, 'Charlie Brown', 'Sales', 48000, '2022-06-23'),
|
| 31 |
+
(4, 'Diana Prince', 'Engineering', 92000, '2019-11-05'),
|
| 32 |
+
(5, 'Evan Wright', 'HR', 45000, '2021-09-30')
|
| 33 |
+
]
|
| 34 |
+
cursor.executemany('INSERT INTO employees VALUES (?,?,?,?,?)', employees)
|
| 35 |
+
conn.commit()
|
| 36 |
+
conn.close()
|
| 37 |
+
print("✅ Datenbank initialisiert.")
|
| 38 |
|
| 39 |
+
# --- TEIL 2: Der Agent ---
|
| 40 |
+
class SQLAgent:
|
| 41 |
+
def __init__(self):
|
| 42 |
+
print("⏳ Lade Modell (CPU)... das dauert ca. 1 Minute...")
|
| 43 |
+
BASE_MODEL = "Qwen/Qwen2.5-1.5B-Instruct"
|
| 44 |
+
ADAPTER_ID = "manuelaschrittwieser/Qwen2.5-SQL-Assistant-Prod"
|
| 45 |
|
| 46 |
+
self.tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
|
| 47 |
+
# WICHTIG: Auf CPU nutzen wir float32 statt 4-bit, da stabiler
|
| 48 |
+
base_model = AutoModelForCausalLM.from_pretrained(
|
| 49 |
+
BASE_MODEL,
|
| 50 |
+
device_map="cpu",
|
| 51 |
+
torch_dtype=torch.float32
|
| 52 |
+
)
|
| 53 |
+
self.model = PeftModel.from_pretrained(base_model, ADAPTER_ID)
|
| 54 |
|
| 55 |
+
def process_query(self, user_question):
|
| 56 |
+
# 1. SQL Generieren
|
| 57 |
+
schema = "CREATE TABLE employees (id INTEGER, name TEXT, department TEXT, salary INTEGER, hire_date DATE)"
|
| 58 |
+
messages = [
|
| 59 |
+
{"role": "system", "content": "You are a SQL expert. Output only the SQL query."},
|
| 60 |
+
{"role": "user", "content": f"{schema}\nQuestion: {user_question}"}
|
| 61 |
+
]
|
| 62 |
+
prompt = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 63 |
+
inputs = self.tokenizer(prompt, return_tensors="pt") # Kein .to("cuda") da CPU
|
| 64 |
+
|
| 65 |
+
with torch.no_grad():
|
| 66 |
+
outputs = self.model.generate(**inputs, max_new_tokens=100)
|
| 67 |
+
|
| 68 |
+
full_text = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 69 |
+
if "assistant" in full_text:
|
| 70 |
+
sql_query = full_text.split("assistant")[-1].strip()
|
| 71 |
+
else:
|
| 72 |
+
sql_query = full_text
|
| 73 |
|
| 74 |
+
# 2. SQL Ausführen
|
| 75 |
+
try:
|
| 76 |
+
conn = sqlite3.connect(DB_PATH)
|
| 77 |
+
cursor = conn.cursor()
|
| 78 |
+
cursor.execute(sql_query)
|
| 79 |
+
results = cursor.fetchall()
|
| 80 |
+
conn.close()
|
| 81 |
+
|
| 82 |
+
# Formatierung der Antwort
|
| 83 |
+
return f"🧠 Gedanke (SQL):\n{sql_query}\n\n📊 Ergebnis aus Datenbank:\n{results}"
|
| 84 |
+
except Exception as e:
|
| 85 |
+
return f"❌ Fehler: {e}\n\nVersuchter SQL: {sql_query}"
|
| 86 |
|
| 87 |
+
# Initialisierung beim Start des Servers
|
| 88 |
+
setup_db()
|
| 89 |
+
agent = SQLAgent()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
+
# --- TEIL 3: Die UI (Gradio Chat Interface) ---
|
| 92 |
+
def chat_response(message, history):
|
| 93 |
+
return agent.process_query(message)
|
| 94 |
|
| 95 |
+
description = """
|
| 96 |
+
# 🤖 SQL Agent
|
| 97 |
+
This agent translates your questions into SQL and **executes them directly on a test database**.
|
| 98 |
+
* Table: `employees` (name, department, salary, hire_date)
|
| 99 |
+
* Try it: "Who earns more than 80000?"
|
| 100 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
demo = gr.ChatInterface(
|
| 103 |
+
fn=chat_response,
|
| 104 |
+
title="Autonomous SQL Agent",
|
| 105 |
+
description=description,
|
| 106 |
+
examples=["Show me all employees in Sales.", "Who earns the most?", "Count the employees in Engineering."],
|
| 107 |
+
type="messages"
|
| 108 |
+
)
|
| 109 |
|
| 110 |
+
demo.launch()
|
|
|