# State Machine Documentation for Backend Chat Workflow ## Overview Das Backend implementiert eine State Machine, die Benutzereingaben, Agenten-Workflows und die Kommunikation mit dem Frontend orchestriert. Die State Machine steuert Statusübergänge, Logging, Dokumentenmanagement und Fehlerbehandlung für robuste Multi-Agent-Workflows. ## Core Objects ### Workflow Object ```json { "id": "uuid-string", "mandateId": int, "userId": int, "name": "Workflow name", "startedAt": "ISO-datetime", "status": "string", // running, completed, failed, stopped "lastActivity": "ISO-datetime", "dataStats": { "bytesSent": int, "bytesReceived": int, "tokensUsed": int, "processingTime": float }, "currentRound": int, "messageIds": [ "string" ], "messages": [ /* WorkflowMessage */ ], "logs": [ /* WorkflowLog */ ] } ``` ### Message Object ```json { "id": "msg_uuid-string", "workflowId": "workflow-uuid", "parentMessageId": "string|null", "startedAt": "ISO-datetime", "finishedAt": "ISO-datetime|null", "sequenceNo": int, "status": "string", // first, step, last "role": "string", // user, assistant, system "dataStats": { /* optional */ }, "documents": [ /* Document */ ], "content": "string", "agentName": "string" } ``` ### Log Entry Object ```json { "id": "log_uuid-string", "workflowId": "workflow-uuid", "message": "string", "type": "string", // info, warning, error "timestamp": "ISO-datetime", "agentName": "string", "status": "string", // running, completed, failed, stopped "progress": int, // Optional, 0-100 "mandateId": int, "userId": int } ``` ### Document Object ```json { "id": "doc_uuid-string", "fileId": int, "name": "string", // Filename ohne Extension "ext": "string", // File Extension "data": "base64-encoded-string", // File-Inhalt "contents": [ /* ContentItem */ ] } ``` ### Content Item Object ```json { "sequenceNr": int, // Reihenfolge im Dokument "name": "string", "ext": "string", "contentType": "string", // mime type "data": "string|base64", // Originalinhalt "dataExtracted": "string", // Optional: AI-Extrakt "metadata": { "isText": boolean, "base64Encoded": boolean, "aiProcessed": boolean // Optional: weitere Metadaten }, "summary": "string" // AI-generierte Zusammenfassung } ``` ## State Machine Workflow ### 1. Workflow Initialization - **Trigger**: User message via `/api/workflows/start` oder `/api/workflows/start?id=string` - **Input**: `UserInputRequest` mit `prompt` und optional `listFileId` - **Prozess**: - Wenn `id` existiert und Workflow existiert: Workflow laden, `currentRound` inkrementieren, Status auf "running" - Sonst: Neuen Workflow anlegen, `currentRound`=1, Status "running" - **Logs**: "Workflow initialized" oder "Running workflow", progress 0% - **API**: 200 OK mit Workflow-ID, Fehler: 400/404/500 ### 2. Workflow Exception - **Trigger**: User stoppt Workflow via API oder Exception tritt auf - **Prozess**: - Bei Status=="stopped": Status auf "stopped", Log, `lastActivity` aktualisieren, sofort abbrechen - Bei Status=="failed": Status auf "failed", Log, `lastActivity` aktualisieren, sofort abbrechen - Sonst: Normal fortfahren - **Logs**: "Workflow failure reported", progress 100% - **API**: 200 OK bei Stop, 500 bei Exception ### 3. User Message Processing - **Prozess**: - User-Input wird als Message-Objekt mit Dokumenten gespeichert, Status "first" - Datei-Inhalte werden extrahiert (`getDocumentContents()`) - Statische Summaries für Content Items generieren - **State Changes**: - User-Message zu `workflow.messages` und `workflow.messageIds` hinzufügen - `workflow.lastActivity` aktualisieren - **Logs**: "Workflow processing started", progress 0% ### 4. Project Manager Analysis - **Prozess**: - Prompt für Project Manager AI generieren - Analyse und Workplan generieren - **Outputs**: - `objFinalDocuments`: Liste erwarteter Output-Dokumente - `objWorkplan`: Liste Agenten-Tasks - `objUserResponse`: Textantwort an User - `userLanguage`: Detektierte Sprache - **State Changes**: - Assistant-Message mit Status "step" speichern - User-Language im Interface setzen - **Logs**: "Analyzing request and planning work" (10%), "Work plan created" (25%) ### 5. Agent Execution - **Prozess** (für jeden Task im Workplan): - Input-Dokumente vorbereiten - Agent ausführen - Output-Dokumente speichern - Assistant-Message mit Status "step" speichern - **Logs**: "Running task X/Y: agentName" (30-90%) ### 6. Final Response Generation - **Prozess**: - Final-Message mit Review der gelieferten Dokumente erzeugen - Dokumente zum Workflow hinzufügen - **State Changes**: Final-Message mit Status "last" speichern - **Logs**: "Creating final response" (90%) ### 7. Workflow Completion - **Prozess**: - Workflow finalisieren, Status auf "completed" - `workflow.lastActivity` aktualisieren - **Logs**: "Workflow completed successfully" (100%) - **API**: Message mit Status "last" in Response, Status-Endpoint gibt "completed" zurück ### 8. Workflow Stopped - **Trigger**: `/api/workflows/{workflowId}/stop` - **Prozess**: - Workflow sofort stoppen, Status auf "stopped" - `lastActivity` aktualisieren - **Logs**: "Workflow stopped by user" (100%) - **API**: 200 OK ### 9. Workflow Failed - **Trigger**: Exception im Workflow - **Prozess**: - Fehler loggen, Status auf "failed" - `lastActivity` aktualisieren - **Logs**: Fehler-Log (100%) - **API**: Status-Endpoint gibt "failed" zurück ### 10. Workflow Resumption - **Trigger**: `/api/workflows/start?id={workflowId}` - **Prozess**: - Workflow laden, `currentRound` inkrementieren, Status auf "running" - Neue User-Message hinzufügen - **Logs**: "Resuming workflow, round {currentRound}" (0%) - **API**: wie Workflow-Init ### 11. Workflow Reset/Deletion - **Trigger**: `/api/workflows/{workflowId}` DELETE - **Prozess**: - Workflow und zugehörige Daten löschen - **Logs**: System-Log "workflow deleted" - **API**: 200 OK oder 404 ## API Endpoints und Polling Support ### Main Workflow Endpoints - `POST /api/workflows/start?id=string`: Startet neuen Workflow oder setzt fort - `POST /api/workflows/{workflowId}/stop`: Stoppt laufenden Workflow - `DELETE /api/workflows/{workflowId}`: Löscht Workflow - `GET /api/workflows/{workflowId}/status`: Holt Workflow-Status - `GET /api/workflows/{workflowId}/logs?id=string`: Holt Logs (optional ab ID) - `GET /api/workflows/{workflowId}/messages?id=string`: Holt Messages (optional ab ID) ### Document Management - `DELETE /api/workflows/{workflowId}/messages/{messageId}`: Löscht Message - `DELETE /api/workflows/{workflowId}/messages/{messageId}/files/{fileId}`: Entfernt Datei aus Message ### Backend Support für Frontend Polling - Selektive Datenübertragung via `id`-Parameter bei `/logs` und `/messages` - Logs enthalten Timestamp, Progress, Status - Messages enthalten Status ("first", "step", "last") - Status-Endpoint liefert nur Status und lastActivity - Caching für häufige Polling-Requests - Batch/Paging für große Log-/Message-Sets ## Dokumentenstruktur - `data`: base64-kodierter Originalinhalt - `contents`: Liste extrahierter Content Items - Agents können auf das Original und die extrahierten Inhalte zugreifen ## State Transitions ``` [null] → [running] // New workflow created [running] → [completed] // Workflow completes successfully [running] → [stopped] // User manually stops workflow [running] → [failed] // Error occurs during workflow [completed] → [running] // User continues workflow with new input (new round) [stopped] → [running] // User continues after manual stop (new round) [failed] → [running] // User retries workflow despite error (new round) [any] → [null] // Workflow deleted ``` ## Exception Handling - Status wird auf "failed" gesetzt bei Fehlern, Fehler werden im Log dokumentiert - Project Manager/Agenten-Outputs und Inputs werden für Debugging geloggt - HTTP-Fehler werden mit passendem Statuscode zurückgegeben - Fehlgeschlagene Agenten-Tasks werden geloggt, stoppen aber nicht den gesamten Workflow ## Special Notes 1. **Document Processing**: Datei-Uploads werden mit Content Extraction verarbeitet. 2. **AI Language Support**: Sprache wird erkannt und im Workflow gesetzt. 3. **Round Counting**: Jede Interaktion inkrementiert `currentRound`. 4. **Agent Registry**: Agents werden dynamisch geladen und registriert. 5. **Standardized Task Processing**: Alle Agents implementieren das gleiche Task-Interface.