229 lines
No EOL
8.1 KiB
Python
229 lines
No EOL
8.1 KiB
Python
"""
|
|
Test-Skript für den ChatManager-Workflow mit simulierten Datei-Uploads.
|
|
Demonstriert den vollständigen Workflow von Datei-Upload bis Chat-Ausführung.
|
|
"""
|
|
|
|
import asyncio
|
|
import base64
|
|
import logging
|
|
import os
|
|
import sys
|
|
from typing import Dict, Any, List, Tuple
|
|
from datetime import datetime
|
|
|
|
# Logging konfigurieren
|
|
logging.basicConfig(
|
|
level=logging.DEBUG,
|
|
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
|
|
handlers=[logging.StreamHandler()]
|
|
)
|
|
logger = logging.getLogger("test_workflow")
|
|
|
|
# Pfad zum Projektverzeichnis hinzufügen
|
|
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
|
|
# Module importieren
|
|
from modules.lucydom_interface import get_lucydom_interface
|
|
from modules.chat import get_chat_manager
|
|
|
|
async def create_test_files(mandate_id: int, user_id: int) -> Tuple[int, int]:
|
|
"""
|
|
Erstellt eine Textdatei und ein Bild für Tests und lädt sie in die Datenbank hoch.
|
|
|
|
Args:
|
|
mandate_id: ID des Mandanten
|
|
user_id: ID des Benutzers
|
|
|
|
Returns:
|
|
Tuple mit (text_file_id, image_file_id)
|
|
"""
|
|
logger.info("Erstelle Test-Dateien...")
|
|
|
|
lucy_interface = get_lucydom_interface(mandate_id, user_id)
|
|
|
|
# Textdatei erstellen
|
|
text_content = """
|
|
Dies ist eine Test-Textdatei für den ChatManager-Workflow.
|
|
Sie enthält einige Informationen zum Testen der Dokumentverarbeitung.
|
|
|
|
Der ChatManager sollte in der Lage sein, diese Datei zu verarbeiten
|
|
und daraus relevante Informationen zu extrahieren.
|
|
|
|
Diese Datei dient als Beispiel für Text-basierte Dokumente, die in einem
|
|
Chat-Workflow verwendet werden können.
|
|
"""
|
|
text_file_bytes = text_content.encode('utf-8')
|
|
text_file = lucy_interface.save_uploaded_file(text_file_bytes, "test_document.txt")
|
|
text_file_id = text_file["id"]
|
|
logger.info(f"Textdatei erstellt mit ID: {text_file_id}")
|
|
|
|
# Create a simple test image using PIL
|
|
try:
|
|
from PIL import Image
|
|
import io
|
|
|
|
# Create a 100x100 red image
|
|
img = Image.new('RGB', (100, 100), color = 'red')
|
|
|
|
# Save to BytesIO
|
|
img_bytes = io.BytesIO()
|
|
img.save(img_bytes, format='PNG')
|
|
img_bytes = img_bytes.getvalue()
|
|
|
|
# Upload to database
|
|
image_file = lucy_interface.save_uploaded_file(img_bytes, "test_image.png")
|
|
image_file_id = image_file["id"]
|
|
logger.info(f"Bilddatei erstellt mit ID: {image_file_id}")
|
|
|
|
except ImportError:
|
|
# Fallback to the original method if PIL is not available
|
|
png_data = bytes([
|
|
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, # PNG Header
|
|
# ... rest of your PNG data ...
|
|
])
|
|
|
|
with open("./test_img_orig.png", 'wb') as f:
|
|
f.write(png_data)
|
|
|
|
image_file = lucy_interface.save_uploaded_file(png_data, "test_image.png")
|
|
image_file_id = image_file["id"]
|
|
logger.info(f"Bilddatei erstellt mit ID: {image_file_id}")
|
|
|
|
return text_file_id, image_file_id
|
|
|
|
|
|
|
|
async def run_chat_workflow(mandate_id: int, user_id: int, file_ids: List[int]) -> Dict[str, Any]:
|
|
"""
|
|
Führt einen Chat-Workflow mit gegebenen Datei-IDs aus.
|
|
|
|
Args:
|
|
mandate_id: ID des Mandanten
|
|
user_id: ID des Benutzers
|
|
file_ids: Liste der Datei-IDs
|
|
|
|
Returns:
|
|
Das Workflow-Ergebnis
|
|
"""
|
|
logger.info(f"Starte Chat-Workflow mit Dateien: {file_ids}")
|
|
|
|
# ChatManager initialisieren
|
|
chat_manager = get_chat_manager(mandate_id, user_id)
|
|
|
|
# Benutzeranfrage erstellen
|
|
user_input = {
|
|
"message": "Analysiere bitte die hochgeladenen Dateien und erkläre mir deren Inhalt.",
|
|
"additional_fileids": file_ids
|
|
}
|
|
|
|
# Chat-Workflow ausführen
|
|
workflow_result = await chat_manager.chat_run(user_input)
|
|
logger.info(f"Workflow abgeschlossen mit ID: {workflow_result['id']}")
|
|
|
|
return workflow_result
|
|
|
|
def analyze_workflow_result(workflow: Dict[str, Any]) -> None:
|
|
"""
|
|
Analysiert und gibt Informationen über das Workflow-Ergebnis aus.
|
|
|
|
Args:
|
|
workflow: Das Workflow-Ergebnis
|
|
"""
|
|
logger.info("Analysiere Workflow-Ergebnis:")
|
|
logger.info(f"Workflow-ID: {workflow['id']}")
|
|
logger.info(f"Status: {workflow['status']}")
|
|
logger.info(f"Anzahl Nachrichten: {len(workflow.get('messages', []))}")
|
|
|
|
for i, message in enumerate(workflow.get('messages', [])):
|
|
logger.info(f"Nachricht {i+1}:")
|
|
logger.info(f" Rolle: {message.get('role', 'unbekannt')}")
|
|
|
|
# Nur die ersten 100 Zeichen des Inhalts anzeigen
|
|
content = message.get('content', '')
|
|
content_preview = content[:100] + '...' if len(content) > 100 else content
|
|
logger.info(f" Inhalt: {content_preview}")
|
|
|
|
# Dokumente in der Nachricht anzeigen
|
|
documents = message.get('documents', [])
|
|
logger.info(f" Dokumente: {len(documents)}")
|
|
for j, doc in enumerate(documents):
|
|
doc_id = doc.get('id', 'keine ID')
|
|
file_id = doc.get('file_id', 'keine file_id')
|
|
logger.info(f" Dokument {j+1}: ID={doc_id}, File-ID={file_id}")
|
|
|
|
# Informationen über Inhalte
|
|
contents = doc.get('contents', [])
|
|
for k, content in enumerate(contents):
|
|
content_name = content.get('name', 'kein Name')
|
|
content_type = content.get('content_type', 'unbekannt')
|
|
logger.info(f" Inhalt {k+1}: {content_name} ({content_type})")
|
|
|
|
# Log-Einträge anzeigen
|
|
logger.info(f"Logs: {len(workflow.get('logs', []))}")
|
|
for i, log in enumerate(workflow.get('logs', []))[:10]: # Begrenzung auf 10 Logs
|
|
log_type = log.get('type', 'info')
|
|
log_message = log.get('message', '')
|
|
log_message_preview = log_message[:100] + '...' if len(log_message) > 100 else log_message
|
|
logger.info(f" Log {i+1} [{log_type}]: {log_message_preview}")
|
|
|
|
async def cleanup_test_files(mandate_id: int, user_id: int, file_ids: List[int]) -> None:
|
|
"""
|
|
Bereinigt die erstellten Testdateien.
|
|
|
|
Args:
|
|
mandate_id: ID des Mandanten
|
|
user_id: ID des Benutzers
|
|
file_ids: Liste der zu löschenden Datei-IDs
|
|
"""
|
|
logger.info("Beginne Bereinigung der Testdateien...")
|
|
|
|
lucy_interface = get_lucydom_interface(mandate_id, user_id)
|
|
|
|
for file_id in file_ids:
|
|
try:
|
|
success = lucy_interface.delete_file(file_id)
|
|
if success:
|
|
logger.info(f"Datei mit ID {file_id} erfolgreich gelöscht")
|
|
else:
|
|
logger.warning(f"Fehler beim Löschen der Datei mit ID {file_id}")
|
|
except Exception as e:
|
|
logger.error(f"Fehler beim Löschen der Datei mit ID {file_id}: {str(e)}")
|
|
|
|
logger.info("Bereinigung abgeschlossen")
|
|
|
|
async def main():
|
|
"""
|
|
Hauptfunktion, die den gesamten Testprozess steuert.
|
|
"""
|
|
# Testparameter
|
|
MANDATE_ID = 1 # Test-Mandanten-ID
|
|
USER_ID = 1 # Test-Benutzer-ID
|
|
CLEANUP = True # Bereinigung nach dem Test
|
|
|
|
try:
|
|
logger.info("=== Test-Workflow für ChatManager gestartet ===")
|
|
|
|
# Schritt 1: Testdateien erstellen
|
|
text_file_id, image_file_id = await create_test_files(MANDATE_ID, USER_ID)
|
|
file_ids = [text_file_id, image_file_id]
|
|
|
|
# Schritt 2: Chat-Workflow ausführen
|
|
workflow_result = await run_chat_workflow(MANDATE_ID, USER_ID, file_ids)
|
|
|
|
# Schritt 3: Ergebnis analysieren
|
|
analyze_workflow_result(workflow_result)
|
|
|
|
# Schritt 4: Optional bereinigen
|
|
if CLEANUP:
|
|
await cleanup_test_files(MANDATE_ID, USER_ID, file_ids)
|
|
|
|
logger.info("=== Test-Workflow erfolgreich abgeschlossen ===")
|
|
|
|
except Exception as e:
|
|
logger.error(f"Fehler im Test-Workflow: {str(e)}", exc_info=True)
|
|
logger.info("=== Test-Workflow mit Fehler beendet ===")
|
|
|
|
if __name__ == "__main__":
|
|
# Event-Loop für asyncio erstellen und Hauptfunktion ausführen
|
|
loop = asyncio.get_event_loop()
|
|
loop.run_until_complete(main()) |