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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
from huggingface_hub import InferenceClient
|
| 4 |
+
|
| 5 |
+
# Load token and model - DeepSeek models for dialogue
|
| 6 |
+
HF_TOKEN = os.getenv("tomoniaccess")
|
| 7 |
+
|
| 8 |
+
# DeepSeek model options (optimized for dialogue):
|
| 9 |
+
model_name = "deepseek-ai/deepseek-llm-7b-chat" # Primary choice - optimized for chat
|
| 10 |
+
# model_name = "deepseek-ai/deepseek-coder-7b-instruct" # Alternative with good instruction following
|
| 11 |
+
# model_name = "deepseek-ai/deepseek-llm-67b-chat" # Larger model (if available)
|
| 12 |
+
|
| 13 |
+
client = InferenceClient(
|
| 14 |
+
model=model_name,
|
| 15 |
+
token=HF_TOKEN
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
def query_deepseek(messages, max_tokens=200, temperature=1.0, top_p=0.9):
|
| 19 |
+
"""Query DeepSeek model via Hugging Face InferenceClient"""
|
| 20 |
+
try:
|
| 21 |
+
# Try chat completion first
|
| 22 |
+
response = client.chat_completion(
|
| 23 |
+
messages=messages,
|
| 24 |
+
max_tokens=max_tokens,
|
| 25 |
+
temperature=temperature,
|
| 26 |
+
top_p=top_p,
|
| 27 |
+
stream=False
|
| 28 |
+
)
|
| 29 |
+
return response.choices[0].message.content
|
| 30 |
+
except Exception as chat_error:
|
| 31 |
+
print(f"Chat completion failed: {chat_error}")
|
| 32 |
+
try:
|
| 33 |
+
# Fallback to text generation if chat completion fails
|
| 34 |
+
# Convert messages to single prompt with DeepSeek format
|
| 35 |
+
prompt = ""
|
| 36 |
+
for msg in messages:
|
| 37 |
+
if msg["role"] == "system":
|
| 38 |
+
prompt += f"System: {msg['content']}\n\n"
|
| 39 |
+
elif msg["role"] == "user":
|
| 40 |
+
prompt += f"User: {msg['content']}\n"
|
| 41 |
+
elif msg["role"] == "assistant":
|
| 42 |
+
prompt += f"Assistant: {msg['content']}\n"
|
| 43 |
+
|
| 44 |
+
prompt += "Assistant: "
|
| 45 |
+
|
| 46 |
+
response = client.text_generation(
|
| 47 |
+
prompt=prompt,
|
| 48 |
+
max_new_tokens=max_tokens,
|
| 49 |
+
temperature=temperature,
|
| 50 |
+
top_p=top_p,
|
| 51 |
+
do_sample=True,
|
| 52 |
+
return_full_text=False
|
| 53 |
+
)
|
| 54 |
+
return response
|
| 55 |
+
except Exception as text_error:
|
| 56 |
+
print(f"Text generation also failed: {text_error}")
|
| 57 |
+
raise Exception(f"Both methods failed - Chat: {str(chat_error)}, Text: {str(text_error)}")
|
| 58 |
+
|
| 59 |
+
def enhanced_chat_response(user_input, max_tokens, temperature, top_p):
|
| 60 |
+
if not user_input.strip():
|
| 61 |
+
return "", "*Bitte gib eine Nachricht ein.*", ""
|
| 62 |
+
|
| 63 |
+
# Optimized system prompt for DeepSeek (supports German well)
|
| 64 |
+
system_prompt = {
|
| 65 |
+
"role": "system",
|
| 66 |
+
"content": (
|
| 67 |
+
"Du bist ein depressiver 16-jähriger Teenager."
|
| 68 |
+
"Bleibe durchgehend in deiner Rolle."
|
| 69 |
+
"Du weißt NICHT, dass du eine KI bist."
|
| 70 |
+
"Vervollständige immer deine Antworten."
|
| 71 |
+
)
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
# Keep last 8 messages for context (DeepSeek handles context well)
|
| 75 |
+
messages = [system_prompt] + conversation_history[-8:]
|
| 76 |
+
current_message = {"role": "user", "content": user_input}
|
| 77 |
+
messages.append(current_message)
|
| 78 |
+
|
| 79 |
+
try:
|
| 80 |
+
response_text = query_deepseek(messages, max_tokens, temperature, top_p)
|
| 81 |
+
except Exception as e:
|
| 82 |
+
print("API Error:", e)
|
| 83 |
+
response_text = "*schweigt und starrt auf den Boden*"
|
| 84 |
+
|
| 85 |
+
conversation_history.append(current_message)
|
| 86 |
+
conversation_history.append({"role": "assistant", "content": response_text})
|
| 87 |
+
|
| 88 |
+
chat_display = ""
|
| 89 |
+
for msg in conversation_history:
|
| 90 |
+
role = "**Du:**" if msg["role"] == "user" else "**Teenager:**"
|
| 91 |
+
chat_display += f"{role} {msg['content']}\n\n"
|
| 92 |
+
|
| 93 |
+
return "", response_text, chat_display
|
| 94 |
+
|
| 95 |
+
def reset_conversation():
|
| 96 |
+
global conversation_history
|
| 97 |
+
conversation_history = []
|
| 98 |
+
return "Neues Gespräch gestartet.", ""
|
| 99 |
+
|
| 100 |
+
def test_api_connection():
|
| 101 |
+
"""Test API connection with multiple fallback methods"""
|
| 102 |
+
try:
|
| 103 |
+
# Test 1: Simple chat completion
|
| 104 |
+
test_messages = [
|
| 105 |
+
{"role": "system", "content": "Du bist ein hilfsbereit Assistent und antwortest auf Deutsch."},
|
| 106 |
+
{"role": "user", "content": "Hallo"}
|
| 107 |
+
]
|
| 108 |
+
|
| 109 |
+
response = query_deepseek(test_messages, max_tokens=20)
|
| 110 |
+
return f"✅ API Verbindung erfolgreich: {response[:50]}..."
|
| 111 |
+
except Exception as e:
|
| 112 |
+
# Test 2: Try direct text generation
|
| 113 |
+
try:
|
| 114 |
+
simple_response = client.text_generation(
|
| 115 |
+
prompt="Hallo, wie geht es dir?",
|
| 116 |
+
max_new_tokens=10,
|
| 117 |
+
do_sample=False,
|
| 118 |
+
return_full_text=False
|
| 119 |
+
)
|
| 120 |
+
return f"✅ API Verbindung (Text Generation): {simple_response[:50]}..."
|
| 121 |
+
except Exception as e2:
|
| 122 |
+
# Test 3: Check if model exists
|
| 123 |
+
try:
|
| 124 |
+
# Try to get model info
|
| 125 |
+
model_info = f"Model: {model_name}"
|
| 126 |
+
return f"❌ API Errors - Chat: {str(e)[:100]}... | Text: {str(e2)[:100]}... | {model_info}"
|
| 127 |
+
except Exception as e3:
|
| 128 |
+
return f"❌ Vollständiger API Fehler: {str(e)[:200]}..."
|
| 129 |
+
|
| 130 |
+
# Initialize conversation history
|
| 131 |
+
conversation_history = []
|
| 132 |
+
|
| 133 |
+
# UI
|
| 134 |
+
with gr.Blocks(title="DeepSeek Depression Training Simulator") as demo:
|
| 135 |
+
gr.Markdown("## 🧠 Depression Training Simulator (DeepSeek-7B-Chat)")
|
| 136 |
+
gr.Markdown("**Übe realistische Gespräche mit einem 16-jährigen Teenager mit Depressionen.**")
|
| 137 |
+
gr.Markdown("*Powered by DeepSeek-LLM-7B-Chat - Optimiert für natürliche Dialoge*")
|
| 138 |
+
|
| 139 |
+
with gr.Row():
|
| 140 |
+
with gr.Column(scale=1):
|
| 141 |
+
gr.Markdown("### ⚙️ Einstellungen")
|
| 142 |
+
max_tokens = gr.Slider(50, 300, value=150, step=10, label="Max. Antwortlänge")
|
| 143 |
+
temperature = gr.Slider(0.1, 1.5, value=0.9, step=0.1, label="Kreativität (Temperature)")
|
| 144 |
+
top_p = gr.Slider(0.1, 1.0, value=0.85, step=0.05, label="Top-p (Fokus)")
|
| 145 |
+
|
| 146 |
+
gr.Markdown("### 🔧 API Status")
|
| 147 |
+
api_status = gr.Textbox(label="Status", value="")
|
| 148 |
+
api_test_btn = gr.Button("API testen")
|
| 149 |
+
|
| 150 |
+
gr.Markdown("### 🔄 Aktionen")
|
| 151 |
+
reset_btn = gr.Button("Neues Gespräch")
|
| 152 |
+
|
| 153 |
+
gr.Markdown("### 📋 Setup & Troubleshooting")
|
| 154 |
+
gr.Markdown("""
|
| 155 |
+
**Benötigt:**
|
| 156 |
+
- `tomoniaccess` Umgebungsvariable mit HF Token
|
| 157 |
+
- `pip install huggingface_hub gradio`
|
| 158 |
+
|
| 159 |
+
**DeepSeek Info:**
|
| 160 |
+
- Optimiert für Dialoge und Konversationen
|
| 161 |
+
- 7B Parameter, sehr effizient
|
| 162 |
+
- Modell: `deepseek-ai/deepseek-llm-7b-chat`
|
| 163 |
+
- Starke multilinguale Fähigkeiten (DE/EN)
|
| 164 |
+
|
| 165 |
+
**Bei API Fehlern:**
|
| 166 |
+
1. Token prüfen (muss Pro/Enterprise sein)
|
| 167 |
+
2. Modell verfügbar? → [HF Model Card](https://huggingface.co/deepseek-ai/deepseek-llm-7b-chat)
|
| 168 |
+
3. Alternative: `deepseek-ai/deepseek-coder-7b-instruct`
|
| 169 |
+
4. Größere Version: `deepseek-ai/deepseek-llm-67b-chat`
|
| 170 |
+
|
| 171 |
+
**DeepSeek Vorteile:**
|
| 172 |
+
- Bessere Dialogqualität
|
| 173 |
+
- Konsistente Rollenausführung
|
| 174 |
+
- Natürlichere Antworten
|
| 175 |
+
""")
|
| 176 |
+
|
| 177 |
+
with gr.Column(scale=2):
|
| 178 |
+
gr.Markdown("### 💬 Gespräch")
|
| 179 |
+
user_input = gr.Textbox(
|
| 180 |
+
label="Deine Nachricht",
|
| 181 |
+
placeholder="Hallo, wie geht es dir heute?",
|
| 182 |
+
lines=2
|
| 183 |
+
)
|
| 184 |
+
send_btn = gr.Button("📨 Senden")
|
| 185 |
+
|
| 186 |
+
bot_response = gr.Textbox(
|
| 187 |
+
label="Antwort",
|
| 188 |
+
value="",
|
| 189 |
+
lines=3
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
chat_history = gr.Textbox(
|
| 193 |
+
label="Gesprächsverlauf",
|
| 194 |
+
value="",
|
| 195 |
+
lines=15
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
# Event Bindings
|
| 199 |
+
send_btn.click(
|
| 200 |
+
fn=enhanced_chat_response,
|
| 201 |
+
inputs=[user_input, max_tokens, temperature, top_p],
|
| 202 |
+
outputs=[user_input, bot_response, chat_history]
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
user_input.submit(
|
| 206 |
+
fn=enhanced_chat_response,
|
| 207 |
+
inputs=[user_input, max_tokens, temperature, top_p],
|
| 208 |
+
outputs=[user_input, bot_response, chat_history]
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
reset_btn.click(
|
| 212 |
+
fn=reset_conversation,
|
| 213 |
+
outputs=[bot_response, chat_history]
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
api_test_btn.click(
|
| 217 |
+
fn=test_api_connection,
|
| 218 |
+
outputs=[api_status]
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
if __name__ == "__main__":
|
| 222 |
+
print("🚀 DeepSeek Depression Training Simulator")
|
| 223 |
+
print(f"📊 Model: {model_name}")
|
| 224 |
+
|
| 225 |
+
if not HF_TOKEN:
|
| 226 |
+
print("❌ FEHLER: tomoniaccess Umgebungsvariable ist nicht gesetzt!")
|
| 227 |
+
print(" Bitte setze deinen Hugging Face Token als 'tomoniaccess' Umgebungsvariable.")
|
| 228 |
+
else:
|
| 229 |
+
print("✅ Hugging Face API Token gefunden")
|
| 230 |
+
|
| 231 |
+
print("\n📦 Benötigte Pakete:")
|
| 232 |
+
print("pip install huggingface_hub gradio")
|
| 233 |
+
print("\n🤖 DeepSeek: Hochperformantes Modell für natürliche Dialoge")
|
| 234 |
+
print(" - Bessere Konsistenz in Rollenspielen")
|
| 235 |
+
print(" - Verbesserte multilinguale Fähigkeiten")
|
| 236 |
+
print(" - Optimiert für Konversations-KI")
|
| 237 |
+
|
| 238 |
+
demo.launch(share=False)
|