Spaces:
Running
Running
File size: 14,100 Bytes
6eb18bd 8cd38e1 6eb18bd 73fe8bf fa9b0ff 37de9ff 7796e82 6eb18bd 99ab6db 504cb17 99ab6db 504cb17 99ab6db 6eb18bd 8cd38e1 d1ee765 8cd38e1 6eb18bd 5b32958 50f11a3 6eb18bd ff4bb22 d1ee765 6eb18bd 8cd38e1 6eb18bd 8cd38e1 6eb18bd 8cd38e1 6eb18bd 8cd38e1 d1ee765 8cd38e1 6eb18bd ff4bb22 8cd38e1 ff4bb22 d1ee765 b86f9f3 8cd38e1 b86f9f3 9949077 8cd38e1 9949077 b86f9f3 9949077 b86f9f3 9949077 b86f9f3 9949077 b86f9f3 d1ee765 b86f9f3 8cd38e1 b86f9f3 d1ee765 ff4bb22 6eb18bd ff4bb22 5046f64 ff4bb22 d1ee765 4d0fd9f 8b4f299 605dde8 8b4f299 4d0fd9f b91ea24 d1ee765 ff4bb22 d1ee765 ff4bb22 80b7494 ff4bb22 8cd38e1 ff4bb22 8cd38e1 ff4bb22 8cd38e1 ff4bb22 8cd38e1 8b4f299 4d0fd9f 5046f64 8cd38e1 933fed8 8b4f299 4d0fd9f 8cd38e1 4d0fd9f 5046f64 8cd38e1 933fed8 8b4f299 4d0fd9f 8cd38e1 4d0fd9f 5046f64 8cd38e1 933fed8 8b4f299 8cd38e1 d1ee765 8b4f299 5046f64 8cd38e1 933fed8 8b4f299 605dde8 4d0fd9f b86f9f3 8cd38e1 b86f9f3 d1ee765 8cd38e1 ff4bb22 8cd38e1 ff4bb22 8cd38e1 b86f9f3 ff4bb22 8cd38e1 b91ea24 8cd38e1 ff4bb22 b91ea24 8cd38e1 d1ee765 ff4bb22 8cd38e1 4d0fd9f 8cd38e1 5046f64 8cd38e1 6eb18bd 8cd38e1 d1ee765 8cd38e1 d1ee765 8cd38e1 b86f9f3 933fed8 8cd38e1 b91ea24 5046f64 b91ea24 ff4bb22 b9819a1 ff4bb22 b9819a1 | 1 2 3 4 5 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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 | import gradio as gr
import requests
import os
import json
# ============================================
# TEST-BEFEHLE FÜR PULLDOWNS
# ============================================
PATCH_COMMANDS = [
#("📄 Patch: Lese test1.py", "!patch scope:file type:read_file filepath:agent/app/projekte/bild/test1.py"),
("📄 Patch: Lese appbild2.py", "!patch scope:file type:read_file filepath:agent/app/projekte/bild/appbild2.py"),
#("📄 Patch: Lese Backup", "!patch scope:file type:read_file filepath:agent/app/projekte/bild/test1.py.bak"),
("📄 Patch: Lese Backup", "!patch scope:file type:read_file filepath:agent/app/projekte/bild/appbild2.py.bak"),
("📄 Patch: Lese JSON", "!patch scope:file type:read_file filepath:memory/agent_memory.json"),
("🔄 Patch: Ersetze 'Tag' mit 'Regenwetter'", "!patch scope:file type:find_and_replace filepath:agent/app/projekte/bild/test1.py find:Tag replace:Regenwetter"),
("📝 Patch: Ersetze Zeile 1", "!patch scope:file type:replace_line filepath:agent/app/projekte/bild/test1.py line:1 content:Nein, ist es nicht da die Sonne nicht scheint!"),
("➕ Patch: Einfügen nach 'Tag'", "!patch scope:file type:insert_after filepath:agent/app/projekte/bild/test1.py search_text:Tag insert_text:Hallo!"),
]
MEMORY_COMMANDS = [
("🧠 Memory: Ähnliche Fehler suchen", "!memory query ImportError: No module named 'xyz'"),
("📊 Memory: Statistik anzeigen", "!memory stats"),
("➕ Memory: Neuen Eintrag hinzufügen", "!memory add \"ImportError\" \"pip install package\""),
]
MODULAR_COMMANDS = [
("🔧 Modular: Kopieren sort_coordinates", "!modular extract /app/agent/app/projekte/bild/appbild2.py sort_coordinates"),
#("🔧 Modular: Kopieren sort_coordinates", "!modular extract agent/app/projekte/bild/appbild2.py sort_coordinates"),
("🔧 Modular: Kopieren+Löschen+Import", "!modular extract /app/agent/app/projekte/bild/appbild2.py sort_coordinates --remove"),
#("🔧 Modular: Kopieren+Löschen+Import", "!modular extract agent/app/projekte/bild/appbild2.py sort_coordinates --remove"),
("🔧 Modular: Kopieren+Löschen+Import+Wunsch", "!modular extract /app/agent/app/projekte/bild/appbild2.py sort_coordinates bildmod --remove"),
("🔧 Modular: Extrahiere ganze Datei", "!modular extract agent/appbild.py"),
("📊 Modular: Status anzeigen", "!modular status"),
("📋 Modular: Alle Module listen", "!modular list"),
("ℹ️ Modular: Info zu AgentClient", "!modular info AgentClient"),
("🔗 Modular: Zeige Abhängigkeiten", "!modular dependencies AgentClient"),
("📤 Modular: Exportiere als JSON", "!modular export AgentClient --format json"),
]
# ============================================
# ANALYZE-BEFEHLE (kurze Antworten, kein Code)
# ============================================
ANALYZE_COMMANDS = [
("🔍 Analyze: Kurze Dateianalyse", "!analyse /app/agent/app/projekte/bild/appbild2.py"),
("🔍 Analyze: Kurze Funktion/Methode", "!analyse /app/agent/app/projekte/bild/appbild2.py sort_coordinates"),
]
# ============================================
# AGENT-CLIENT (für Tests)
# ============================================
class AgentClient:
def __init__(self, project_name):
self.project = project_name
self.agent_url = os.getenv("AGENT_URL", "https://astridkraft-KI-Agent.hf.space")
self.api_key = os.getenv("AGENT_API_KEY", "test-key-123")
self.timeout = 10
def test_connection(self):
"""Testet die Verbindung zum Agenten (GET /api/health)"""
try:
response = requests.get(
f"{self.agent_url}/api/health",
timeout=5
)
if response.status_code == 200:
data = response.json()
return {
"success": True,
"message": f"✅ Verbunden!",
"data": data
}
else:
return {
"success": False,
"message": f"❌ Fehler {response.status_code}: {response.text}"
}
except requests.exceptions.ConnectionError:
return {
"success": False,
"message": "❌ Agent nicht erreichbar (Connection Error)"
}
except Exception as e:
return {
"success": False,
"message": f"❌ Fehler: {str(e)}"
}
def test_chat(self, message):
"""Testet den Chat-Endpoint (POST /api/chat)"""
try:
response = requests.post(
f"{self.agent_url}/api/chat",
json={
"project": self.project,
"message": message,
"api_key": self.api_key
},
timeout=self.timeout
)
if response.status_code == 200:
data = response.json()
return {
"success": True,
"message": data.get("response", "Keine Antwort"),
"full_response": data
}
else:
return {
"success": False,
"message": f"❌ Fehler {response.status_code}: {response.text}"
}
except Exception as e:
return {
"success": False,
"message": f"❌ Fehler: {str(e)}"
}
# ============================================
# ANALYZE-METHODE
# ============================================
def test_analyze(self, query):
"""Testet den Analyze-Endpoint"""
try:
response = requests.post(
f"{self.agent_url}/api/analyze",
json={
"project": self.project,
"query": query,
"api_key": self.api_key
},
timeout=self.timeout
)
if response.status_code == 200:
data = response.json()
return {
"success": True,
"message": data.get("response", "Keine Antwort"),
"full_response": data
}
else:
return {
"success": False,
"message": f"❌ Fehler {response.status_code}: {response.text}"
}
except Exception as e:
return {
"success": False,
"message": f"❌ Fehler: {str(e)}"
}
# Agent initialisieren
agent = AgentClient("bildgenerierung")
# ============================================
# TEST-FUNKTIONEN
# ============================================
def test_health():
"""Testet Health-Endpoint"""
result = agent.test_connection()
if result["success"]:
return f"""{result['message']}
Agent-Status: {result['data'].get('status', 'unbekannt')}
Projekte: {', '.join(result['data'].get('projects', []))}
Agent URL: {agent.agent_url}"""
else:
return result["message"]
def test_chat(message, chat_history):
"""Testet Chat-Endpoint und sammelt Verlauf"""
if not message:
return chat_history, "" # Keine Änderung
# Prüfen ob es ein Analyze-Befehl ist
if message.strip().startswith("!analyze"):
result = agent.test_analyze(message)
else:
result = agent.test_chat(message)
# Chat-Verlauf formatieren
if result["success"]:
response_text = f"👤 Du: {message}\n\n🤖 Agent: {result['message']}\n\n---\n"
else:
response_text = f"👤 Du: {message}\n\n❌ Fehler: {result['message']}\n\n---\n"
# Zum Verlauf hinzufügen (neueste unten)
new_history = chat_history + response_text if chat_history else response_text
return new_history, "" # Verlauf zurückgeben und Input leeren
# Funktion zum Einfügen des ausgewählten Befehls ins Chat-Feld
def insert_command(choice):
"""Extrahiert den Befehl aus der Auswahl und fügt ihn ins Chat-Feld ein"""
if choice and ":" in choice:
parts = choice.split(" ", 1)
if len(parts) > 1:
for cmd_list in [PATCH_COMMANDS, MEMORY_COMMANDS, MODULAR_COMMANDS, ANALYZE_COMMANDS]:
for display, command in cmd_list:
if display == choice:
return command
return ""
# Funktion zum Zurücksetzen des Chat-Verlaufs
def clear_history():
"""Leert den Chat-Verlauf"""
return ""
# ============================================
# GRADIO UI
# ============================================
css = """
#col-container {
margin: 0 auto;
max-width: 800px;
}
.status-box {
background: #f5f5f5;
padding: 15px;
border-radius: 8px;
font-family: monospace;
white-space: pre-wrap;
height: 400px;
overflow-y: auto;
}
.success { color: green; }
.error { color: red; }
.dropdown-row {
display: flex;
gap: 10px;
margin-bottom: 15px;
flex-wrap: wrap;
}
.analyze-dropdown {
border-left: 4px solid #ff6b6b;
}
.health-box {
margin-top: 20px;
border-top: 2px solid #e0e0e0;
padding-top: 20px;
}
.button-row {
display: flex;
gap: 10px;
margin-bottom: 10px;
}
"""
with gr.Blocks(css=css, title="🧪 Agent-API Tester") as demo:
gr.Markdown("""
# 🧪 Agent-API Test-Tool
Testet die Verbindung zum zentralen Agenten-Space:
""")
with gr.Column(elem_id="col-container"):
# Agent-Info
with gr.Row():
gr.Markdown(f"""
**Agent-URL:** `{agent.agent_url}`
**Projekt:** `{agent.project}`
**API-Key:** `{agent.api_key}`
""")
gr.Markdown("---")
# Vier Pulldown-Menüs für Testbefehle
gr.Markdown("### 📋 Testbefehle auswählen:")
with gr.Row(elem_classes="dropdown-row"):
patch_dropdown = gr.Dropdown(
choices=[cmd[0] for cmd in PATCH_COMMANDS],
label="!patch Befehle",
info="Patch-Operationen auf test.py",
value=None,
interactive=True,
scale=1
)
memory_dropdown = gr.Dropdown(
choices=[cmd[0] for cmd in MEMORY_COMMANDS],
label="!memory Befehle",
info="Memory-Operationen auf agent_memory.json",
value=None,
interactive=True,
scale=1
)
modular_dropdown = gr.Dropdown(
choices=[cmd[0] for cmd in MODULAR_COMMANDS],
label="!modular Befehle",
info="Modular-System Befehle",
value=None,
interactive=True,
scale=1
)
# Analyze Dropdown
analyze_dropdown = gr.Dropdown(
choices=[cmd[0] for cmd in ANALYZE_COMMANDS],
label="🔍 !analyze Befehle",
info="Analyse-Befehle",
value=None,
interactive=True,
scale=1,
elem_classes="analyze-dropdown"
)
gr.Markdown("---")
# Chat-Verlauf (JETZT MIT VERLAUF)
chat_output = gr.Textbox(
label="Chat-Verlauf",
lines=15,
interactive=False,
elem_classes="status-box"
)
# Chat-Input und Buttons
with gr.Row():
chat_input = gr.Textbox(
label="Deine Nachricht",
placeholder="z.B. Hallo Agent, wie geht's? Oder Befehl aus Pulldown auswählen...",
lines=2,
scale=4
)
with gr.Column(scale=1):
chat_btn = gr.Button("📤 Senden", variant="primary")
clear_btn = gr.Button("🗑️ Verlauf löschen", variant="secondary")
gr.Markdown("---")
# Health-Test
with gr.Row(elem_classes="health-box"):
health_btn = gr.Button("🔍 Health-Endpoint testen", variant="secondary", size="lg")
health_output = gr.Textbox(
label="Health-Response",
lines=5,
interactive=False,
elem_classes="status-box"
)
# Event Handler für Pulldowns
patch_dropdown.change(
fn=insert_command,
inputs=[patch_dropdown],
outputs=[chat_input]
)
memory_dropdown.change(
fn=insert_command,
inputs=[memory_dropdown],
outputs=[chat_input]
)
modular_dropdown.change(
fn=insert_command,
inputs=[modular_dropdown],
outputs=[chat_input]
)
analyze_dropdown.change(
fn=insert_command,
inputs=[analyze_dropdown],
outputs=[chat_input]
)
# Event Handler für Chat
chat_btn.click(
fn=test_chat,
inputs=[chat_input, chat_output],
outputs=[chat_output, chat_input]
)
# Enter-Taste im Chat-Input
chat_input.submit(
fn=test_chat,
inputs=[chat_input, chat_output],
outputs=[chat_output, chat_input]
)
# Verlauf löschen
clear_btn.click(
fn=clear_history,
inputs=[],
outputs=[chat_output]
)
# Health-Button
health_btn.click(
fn=test_health,
inputs=[],
outputs=[health_output]
)
if __name__ == "__main__":
demo.launch(
css=css, # CSS hier in launch() übergeben
share=True, # Share-Link erstellen
server_name="0.0.0.0", # Auf allen Interfaces lauschen
server_port=7860
) |