Backup #1499

ID1499
Dateipfad/var/www/dev.campus.systemische-tools.de/src/UseCases/Chat/ExportChatSessionUseCase.php
Version7
Typ modified
Größe4.7 KB
Hash321a4c1ff5837d063544b1d5b6fa78f45b79179367a666a9ab9bd52f977aed9b
Datum2025-12-25 17:32:44
Geändert vonclaude-code-hook
GrundClaude Code Pre-Hook Backup vor Edit-Operation
Datei existiert Ja

Dateiinhalt

<?php

declare(strict_types=1);

namespace UseCases\Chat;

// @responsibility: Exportiert Chat-Sessions als Markdown oder JSON

use Domain\Repository\ChatMessageRepositoryInterface;
use Domain\Repository\ChatSessionRepositoryInterface;

final class ExportChatSessionUseCase
{
    public function __construct(
        private ChatSessionRepositoryInterface $sessionRepo,
        private ChatMessageRepositoryInterface $messageRepo
    ) {
    }

    /**
     * Export session as Markdown.
     */
    public function exportAsMarkdown(string $uuid): ?string
    {
        $session = $this->sessionRepo->findByUuid($uuid);

        if ($session === null) {
            return null;
        }

        $messages = $this->messageRepo->findBySessionId($session->getId() ?? 0);
        $title = $session->getTitle() ?? 'Chat';
        $date = date('d.m.Y H:i');
        $model = $session->getModel();

        $md = "# {$title}\n";
        $md .= "*Exportiert am {$date}*\n";
        $md .= "*Modell: {$model}*\n\n";
        $md .= "---\n\n";

        $questionNum = 0;
        foreach ($messages as $msg) {
            if ($msg->role()->isUser()) {
                $questionNum++;
                $md .= "## Frage {$questionNum}\n\n";
                $md .= $msg->content()->value() . "\n\n";
            } else {
                $md .= "## Antwort {$questionNum}\n\n";
                $md .= $msg->content()->value() . "\n\n";

                $sources = $msg->metadata()->sources() ?? [];
                if (!empty($sources)) {
                    $md .= "**Quellen:**\n";
                    foreach ($sources as $source) {
                        $sourceData = is_string($source) ? json_decode($source, true) : $source;
                        if (!is_array($sourceData)) {
                            continue;
                        }
                        $sourceTitle = $sourceData['title'] ?? 'Unbekannt';
                        $score = isset($sourceData['score']) ? round((float) $sourceData['score'] * 100) . '%' : '';
                        $collection = isset($sourceData['collection']) ? "[{$sourceData['collection']}] " : '';
                        $md .= "- {$collection}{$sourceTitle} ({$score})\n";
                    }
                    $md .= "\n";
                }

                $md .= "---\n\n";
            }
        }

        return $md;
    }

    /**
     * Export session as JSON.
     *
     * @return array<string, mixed>|null
     */
    public function exportAsJson(string $uuid): ?array
    {
        $session = $this->sessionRepo->findByUuid($uuid);

        if ($session === null) {
            return null;
        }

        $messages = $this->messageRepo->findBySessionId($session->getId() ?? 0);

        $exportMessages = [];
        foreach ($messages as $msg) {
            $exportMsg = [
                'role' => $msg->getRole()->value,
                'content' => $msg->getContent(),
                'created_at' => $msg->getCreatedAt()->format('Y-m-d H:i:s'),
            ];

            if ($msg->getRole()->isAssistant()) {
                $sources = $msg->getSources() ?? [];
                $parsedSources = [];
                foreach ($sources as $source) {
                    $parsedSources[] = is_string($source) ? json_decode($source, true) : $source;
                }
                $exportMsg['sources'] = $parsedSources;
                $exportMsg['tokens'] = [
                    'input' => $msg->getTokensInput() ?? 0,
                    'output' => $msg->getTokensOutput() ?? 0,
                ];
                $exportMsg['model'] = $msg->getModel();
            }

            $exportMessages[] = $exportMsg;
        }

        return [
            'session' => [
                'uuid' => $session->getUuid(),
                'title' => $session->getTitle() ?? 'Chat',
                'created_at' => $session->getCreatedAt()->format('Y-m-d H:i:s'),
                'model' => $session->getModel(),
                'collections' => $session->getCollections(),
            ],
            'messages' => $exportMessages,
            'exported_at' => date('c'),
        ];
    }

    /**
     * Generate filename for export.
     */
    public function generateFilename(string $uuid, string $format): string
    {
        $session = $this->sessionRepo->findByUuid($uuid);
        $title = $session?->getTitle() ?? 'chat';

        // Sanitize title for filename
        $title = preg_replace('/[^a-zA-Z0-9äöüÄÖÜß\-_\s]/u', '', $title) ?? '';
        $title = preg_replace('/\s+/', '-', trim($title)) ?? '';
        $title = mb_substr($title, 0, 50);

        if ($title === '') {
            $title = 'chat';
        }

        $date = date('Y-m-d');
        $ext = $format === 'json' ? 'json' : 'md';

        return "chat-{$title}-{$date}.{$ext}";
    }
}

Vollständig herunterladen

Aktionen

Herunterladen

Andere Versionen dieser Datei

ID Version Typ Größe Datum
1843 9 modified 4.7 KB 2025-12-27 23:21
1840 8 modified 4.7 KB 2025-12-27 23:21
1499 7 modified 4.7 KB 2025-12-25 17:32
1498 6 modified 4.7 KB 2025-12-25 17:32
1141 5 modified 4.7 KB 2025-12-25 09:44
1140 4 modified 4.5 KB 2025-12-25 09:43
1139 3 modified 4.3 KB 2025-12-25 09:43
843 2 modified 4.5 KB 2025-12-23 08:17
714 1 modified 4.4 KB 2025-12-23 07:55

← Zurück zur Übersicht