openamer-max commited on
Commit
303addd
·
verified ·
1 Parent(s): c12b850

OpenAI-kompatible Schnittstelle fuer Desktop/Pro/Ultra

Browse files
Files changed (1) hide show
  1. app.py +221 -0
app.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenAmer-Server: eine OpenAI-kompatible Schnittstelle fuer die grossen Stufen.
2
+
3
+ Warum Umbau: die Web-App /app/ spricht ausschliesslich /v1/chat/completions. Der
4
+ bisherige Space bot nur Gradio-Endpunkte an, war also fuer die App unerreichbar.
5
+
6
+ Aufbau:
7
+ - FastAPI mit POST /v1/chat/completions und GET /v1/models
8
+ - Gradio-Oberflaeche bleibt, wird unter /ui einghaengt (fuer Menschen)
9
+ - ZeroGPU: @spaces.GPU teilt die GPU pro Anfrage zu
10
+
11
+ Stufen: Desktop (14,7B), Pro (24B), Ultra (32B) als Basis + eigener LoRA-Adapter.
12
+ Watch/Phone/Tab fehlen hier bewusst - fuer Phone und Tab gibt es keinen Adapter,
13
+ und fuer Watch laeuft ein eigener CPU-Space, der ohne Wartezeit antwortet.
14
+
15
+ Ehrlich in der Oberflaeche: der erste Aufruf einer Stufe laedt das Modell und
16
+ dauert rund eine Minute. Weitere Anfragen derselben Stufe sind schneller, solange
17
+ der Space wach bleibt.
18
+ """
19
+ import os
20
+ import time
21
+
22
+ import gradio as gr
23
+ import torch
24
+
25
+ try:
26
+ import spaces
27
+ except ImportError: # CPU-Fallback ausserhalb von ZeroGPU
28
+ class spaces:
29
+ @staticmethod
30
+ def GPU(*a, **k):
31
+ def huelle(f):
32
+ return f
33
+ return huelle
34
+
35
+ import json
36
+ from fastapi import FastAPI
37
+ from fastapi.responses import JSONResponse
38
+
39
+ STUFEN = {
40
+ "desktop": {
41
+ "anzeige": "Desktop (14,7B)",
42
+ "basis": "Qwen/Qwen2.5-14B-Instruct",
43
+ "adapter": "openamer-max/openamer-max-desktop-adapter",
44
+ "pruefstand": "44/45 (97,8 %)",
45
+ "groesse": "9,0 GB als Q4_K_M",
46
+ "ollama": "amersacirovic/openamer-max-desktop",
47
+ },
48
+ "pro": {
49
+ "anzeige": "Pro (24B)",
50
+ "basis": "mistralai/Mistral-Small-24B-Instruct-2501",
51
+ "adapter": "openamer-max/openamer-max-pro-adapter",
52
+ "pruefstand": "43/45 (95,6 %)",
53
+ "groesse": "13,4 GB als Q4_K_M",
54
+ "ollama": "amersacirovic/openamer-max-pro",
55
+ },
56
+ "ultra": {
57
+ "anzeige": "Ultra (32B)",
58
+ "basis": "Qwen/Qwen2.5-32B-Instruct",
59
+ "adapter": "openamer-max/openamer-max-ultra-adapter",
60
+ "pruefstand": "41/45 (91,1 %)",
61
+ "groesse": "19,9 GB als Q4_K_M",
62
+ "ollama": "amersacirovic/openamer-max-ultra",
63
+ },
64
+ }
65
+
66
+ SYSTEM = ("Du bist OpenAmer, ein lokaler KI-Assistent. Du antwortest knapp, sachlich und "
67
+ "auf Deutsch, wenn der Nutzer Deutsch schreibt. Du erfindest keine Zahlen, "
68
+ "Versionen oder Namen. Wenn du etwas nicht weisst, sagst du das.")
69
+
70
+ _geladen = {}
71
+
72
+
73
+ def _lade(schluessel):
74
+ """Laedt Basis + Adapter einmal und haelt sie im Speicher."""
75
+ if schluessel in _geladen:
76
+ return _geladen[schluessel]
77
+ from peft import PeftModel
78
+ from transformers import AutoModelForCausalLM, AutoTokenizer
79
+
80
+ info = STUFEN[schluessel]
81
+ tok = AutoTokenizer.from_pretrained(info["basis"])
82
+ kw = {"device_map": "auto", "torch_dtype": torch.float16}
83
+ if torch.cuda.is_available():
84
+ from transformers import BitsAndBytesConfig
85
+ kw["quantization_config"] = BitsAndBytesConfig(
86
+ load_in_4bit=True, bnb_4bit_compute_dtype=torch.float16,
87
+ bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True)
88
+ else:
89
+ kw["torch_dtype"] = torch.float32
90
+ kw["device_map"] = None
91
+ modell = AutoModelForCausalLM.from_pretrained(info["basis"], **kw)
92
+ modell = PeftModel.from_pretrained(modell, info["adapter"])
93
+ modell.eval()
94
+ _geladen[schluessel] = (modell, tok)
95
+ return _geladen[schluessel]
96
+
97
+
98
+ @spaces.GPU(duration=180)
99
+ def erzeuge(schluessel, nachrichten, max_tokens):
100
+ """Erzeugt eine Antwort. GPU wird pro Aufruf zugeteilt."""
101
+ modell, tok = _lade(schluessel)
102
+ text = tok.apply_chat_template(nachrichten, tokenize=False, add_generation_prompt=True)
103
+ eingabe = tok(text, return_tensors="pt").to(modell.device)
104
+ with torch.no_grad():
105
+ aus = modell.generate(**eingabe, max_new_tokens=int(max_tokens), do_sample=False,
106
+ temperature=None, top_p=None, top_k=None,
107
+ pad_token_id=tok.eos_token_id)
108
+ return tok.decode(aus[0][eingabe["input_ids"].shape[1]:], skip_special_tokens=True).strip()
109
+
110
+
111
+ # ------------------------------------------------------------------ OpenAI-Schicht
112
+ app = FastAPI(title="OpenAmer Server")
113
+
114
+
115
+ @app.get("/v1/models")
116
+ def modelle():
117
+ return {"object": "list",
118
+ "data": [{"id": k, "object": "model", "owned_by": "openamer",
119
+ "name": v["anzeige"]} for k, v in STUFEN.items()]}
120
+
121
+
122
+ @app.post("/v1/chat/completions")
123
+ def chat(anfrage: dict):
124
+ name = (anfrage.get("model") or "desktop").split("/")[-1].lower()
125
+ kurz = {"watch": "desktop", "phone": "desktop", "tab": "desktop",
126
+ "desktop-14b": "desktop"}.get(name, name)
127
+ if kurz not in STUFEN:
128
+ return JSONResponse(status_code=400, content={
129
+ "error": {"message": f"Unbekanntes Modell '{name}'. Verfuegbar: "
130
+ f"{', '.join(STUFEN)}", "type": "invalid_request_error"}})
131
+
132
+ nachrichten = anfrage.get("messages") or []
133
+ if not nachrichten:
134
+ return JSONResponse(status_code=400, content={
135
+ "error": {"message": "messages fehlt", "type": "invalid_request_error"}})
136
+ if not any(m.get("role") == "system" for m in nachrichten):
137
+ nachrichten = [{"role": "system", "content": SYSTEM}] + nachrichten
138
+
139
+ t0 = time.time()
140
+ try:
141
+ text = erzeuge(kurz, nachrichten, anfrage.get("max_tokens") or 256)
142
+ except Exception as e:
143
+ return JSONResponse(status_code=503, content={
144
+ "error": {"message": f"Stufe '{kurz}' konnte nicht laden: {str(e)[:180]}",
145
+ "type": "server_error"}})
146
+
147
+ prompt_zeichen = sum(len(m.get("content") or "") for m in nachrichten)
148
+ return {
149
+ "id": "chatcmpl-" + str(int(t0 * 1000)),
150
+ "object": "chat.completion",
151
+ "created": int(t0),
152
+ "model": kurz,
153
+ "choices": [{"index": 0, "finish_reason": "stop",
154
+ "message": {"role": "assistant", "content": text}}],
155
+ "usage": {"prompt_tokens": prompt_zeichen // 4,
156
+ "completion_tokens": max(1, len(text) // 4),
157
+ "total_tokens": (prompt_zeichen + len(text)) // 4},
158
+ "openamer": {"stufe": STUFEN[kurz]["anzeige"],
159
+ "pruefstand": STUFEN[kurz]["pruefstand"],
160
+ "dauer_s": round(time.time() - t0, 1)},
161
+ }
162
+
163
+
164
+ @app.get("/health")
165
+ def health():
166
+ return {"status": "ok", "stufen": list(STUFEN),
167
+ "geladen": list(_geladen), "gpu": torch.cuda.is_available()}
168
+
169
+
170
+ # ------------------------------------------------------------------ Oberflaeche
171
+ def antworte_ui(stufe, frage, tokens):
172
+ schluessel = {"Desktop (14,7B)": "desktop", "Pro (24B)": "pro",
173
+ "Ultra (32B)": "ultra"}.get(stufe, "desktop")
174
+ if not frage or not frage.strip():
175
+ return "Bitte eine Frage eingeben."
176
+ t0 = time.time()
177
+ try:
178
+ text = erzeuge(schluessel, [{"role": "system", "content": SYSTEM},
179
+ {"role": "user", "content": frage}], tokens)
180
+ except Exception as e:
181
+ return f"Fehler: {str(e)[:200]}"
182
+ return f"{text}\n\n— {STUFEN[schluessel]['anzeige']} · " \
183
+ f"{STUFEN[schluessel]['pruefstand']} · {time.time() - t0:.1f}s"
184
+
185
+
186
+ beschreibung = """
187
+ # OpenAmer-Server — kostenlos, ohne Schlüssel
188
+
189
+ Dieselbe Schnittstelle, die die Web-App nutzt: `POST /v1/chat/completions`.
190
+ Kein API-Key, kein Konto.
191
+
192
+ | Modell | Parameter | Prüfstand (45 Fälle) |
193
+ |---|---|---|
194
+ | desktop | 14,70B | 44/45 (97,8 %) |
195
+ | pro | 24,00B | 43/45 (95,6 %) |
196
+ | ultra | 32,00B | 41/45 (91,1 %) |
197
+
198
+ **Ehrlich:** Der erste Aufruf einer Stufe lädt das Modell — das dauert etwa eine
199
+ Minute. Danach antwortet dieselbe Stufe schneller, solange der Space wach bleibt.
200
+ Die kleinste Stufe (watch, 0,6B) läuft auf einem eigenen CPU-Server und antwortet
201
+ in Sekunden: dort gibt es keine Wartezeit.
202
+
203
+ ```bash
204
+ curl -X POST $URL/v1/chat/completions -H 'Content-Type: application/json' \\
205
+ -d '{"model":"desktop","messages":[{"role":"user","content":"Hallo"}]}'
206
+ ```
207
+ """
208
+
209
+ with gr.Blocks(title="OpenAmer-Server") as demo:
210
+ gr.Markdown(beschreibung)
211
+ with gr.Row():
212
+ stufe = gr.Dropdown(choices=list(v["anzeige"] for v in STUFEN.values()),
213
+ value="Desktop (14,7B)", label="Stufe")
214
+ tokens = gr.Slider(32, 256, value=96, step=32, label="Maximale Länge")
215
+ frage = gr.Textbox(label="Frage", placeholder="Was ist OpenAmer?", lines=2)
216
+ knopf = gr.Button("Antworten", variant="primary")
217
+ ausgabe = gr.Textbox(label="Antwort", lines=8)
218
+ knopf.click(antworte_ui, [stufe, frage, tokens], ausgabe)
219
+ frage.submit(antworte_ui, [stufe, frage, tokens], ausgabe)
220
+
221
+ app = gr.mount_gradio_app(app, demo, path="/ui")