This commit is contained in:
Team3
2026-06-01 14:27:00 +02:00
parent aedb44ac6e
commit bd4639b3aa
8 changed files with 454 additions and 9 deletions

View File

@@ -30,3 +30,4 @@ CLAUDE_CLI = "claude"
MODEL_GUIDE = "claude-opus-4-8" MODEL_GUIDE = "claude-opus-4-8"
MODEL_BAUSTEIN_GEN = "claude-sonnet-4-6" MODEL_BAUSTEIN_GEN = "claude-sonnet-4-6"
MODEL_BAUSTEIN_REWORK = "claude-sonnet-4-6" MODEL_BAUSTEIN_REWORK = "claude-sonnet-4-6"
MODEL_CHAT = "claude-sonnet-4-6"

View File

@@ -16,6 +16,7 @@ from config import (
MODEL_GUIDE, MODEL_GUIDE,
MODEL_BAUSTEIN_GEN, MODEL_BAUSTEIN_GEN,
MODEL_BAUSTEIN_REWORK, MODEL_BAUSTEIN_REWORK,
MODEL_CHAT,
STORAGE_DIR, STORAGE_DIR,
) )
from database import ( from database import (
@@ -556,6 +557,48 @@ def _build_topic_suggest_prompt(problem: str, existing_topics: list[str]) -> str
return template.replace("{problem}", problem).replace("{existing}", existing) return template.replace("{problem}", problem).replace("{existing}", existing)
def _build_guide_chat_prompt(topic: str, format_name: str, section: str, outline: str, messages: list[dict]) -> str:
transcript = "\n".join(
f"{'Nutzer' if m.get('role') == 'user' else 'Assistent'}: {m.get('content', '')}"
for m in messages
)
outline_block = outline.strip() or "(keine)"
section_block = section.strip() or "(kein Abschnitt erkannt)"
return f"""Du bist ein hilfreicher Tutor zum Lern-Guide "{topic}" (Format: {format_name}). Ein Leser stellt dir Fragen, während er den Guide liest.
GLIEDERUNG DES GUIDES:
{outline_block}
AKTUELLER ABSCHNITT, DEN DER LESER GERADE LIEST:
{section_block}
BISHERIGER CHAT-VERLAUF:
{transcript}
Antworte als Assistent auf die letzte Nutzer-Nachricht.
WICHTIG Antwortstil:
- KURZ und EINFACH: 13 Sätze, klare Sprache.
- Keine Einleitung, keine Wiederholung der Frage, kein Markdown-Drumherum.
- Beantworte nur die Frage; nutze den Abschnitt und die Gliederung als Kontext.
Gib NUR die Antwort aus, kein Präfix wie "Assistent:"."""
async def chat_with_guide(topic: str, format_name: str, section: str, outline: str, messages: list[dict]) -> str:
try:
prompt = _build_guide_chat_prompt(topic, format_name, section, outline, messages)
returncode, stdout, stderr = await _run_claude(
"chat-" + str(uuid.uuid4()), prompt, 120, tools=None, model=MODEL_CHAT
)
if returncode != 0:
return "Entschuldigung, das hat nicht geklappt. Bitte versuche es erneut."
reply = stdout.strip()
return reply or "Entschuldigung, ich habe keine Antwort erhalten."
except Exception:
return "Entschuldigung, das hat nicht geklappt. Bitte versuche es erneut."
async def suggest_topics(problem: str, existing_topics: list[str] | None = None) -> list[dict]: async def suggest_topics(problem: str, existing_topics: list[str] | None = None) -> list[dict]:
try: try:
prompt = _build_topic_suggest_prompt(problem, existing_topics or []) prompt = _build_topic_suggest_prompt(problem, existing_topics or [])

View File

@@ -75,3 +75,18 @@ class TopicSuggestRequest(BaseModel):
class TopicSuggestion(BaseModel): class TopicSuggestion(BaseModel):
title: str title: str
reason: str reason: str
class ChatMessage(BaseModel):
role: Literal["user", "assistant"]
content: str = Field(min_length=1, max_length=8000)
class GuideChatRequest(BaseModel):
section: str = Field(default="", max_length=20000)
outline: str = Field(default="", max_length=8000)
messages: list[ChatMessage] = Field(min_length=1)
class GuideChatResponse(BaseModel):
reply: str

View File

@@ -11,11 +11,12 @@ from database import (
create_baustein as db_create_baustein, list_bausteine, get_baustein, delete_baustein as db_delete_baustein, create_baustein as db_create_baustein, list_bausteine, get_baustein, delete_baustein as db_delete_baustein,
list_suggestions, get_suggestion, update_suggestion, delete_suggestion, list_suggestions, get_suggestion, update_suggestion, delete_suggestion,
) )
from generator import generate_guide, rework_guide, cancel_guide, generate_suggestions, generate_baustein_detail, rework_baustein, sort_bausteine, suggest_topics, is_suggestions_generating, is_sorting from generator import generate_guide, rework_guide, cancel_guide, generate_suggestions, generate_baustein_detail, rework_baustein, sort_bausteine, suggest_topics, chat_with_guide, is_suggestions_generating, is_sorting
from models import ( from models import (
GuideCreateRequest, GuideReworkRequest, GuideResponse, GuideCreateRequest, GuideReworkRequest, GuideResponse,
BausteinCreateRequest, BausteinReworkRequest, BausteinSortRequest, BausteinResponse, SuggestionResponse, BausteinCreateRequest, BausteinReworkRequest, BausteinSortRequest, BausteinResponse, SuggestionResponse,
TopicSuggestRequest, TopicSuggestion, TopicSuggestRequest, TopicSuggestion,
GuideChatRequest, GuideChatResponse,
) )
from paths import final_paths from paths import final_paths
@@ -89,6 +90,18 @@ async def rework(guide_id: str, req: GuideReworkRequest):
return {"ok": True} return {"ok": True}
@router.post("/guides/{guide_id}/chat", response_model=GuideChatResponse)
async def guide_chat(guide_id: str, req: GuideChatRequest):
guide = await get_guide(guide_id)
if guide is None:
raise HTTPException(404, "Guide nicht gefunden")
reply = await chat_with_guide(
guide["topic"], guide["format"], req.section, req.outline,
[m.model_dump() for m in req.messages],
)
return {"reply": reply}
@router.post("/guides/{guide_id}/cancel") @router.post("/guides/{guide_id}/cancel")
async def cancel(guide_id: str): async def cancel(guide_id: str):
cancelled = await cancel_guide(guide_id) cancelled = await cancel_guide(guide_id)

View File

@@ -8,6 +8,8 @@
"name": "frontend", "name": "frontend",
"version": "0.0.0", "version": "0.0.0",
"dependencies": { "dependencies": {
"dompurify": "^3.4.7",
"marked": "^18.0.4",
"vue": "^3.5.32" "vue": "^3.5.32"
}, },
"devDependencies": { "devDependencies": {
@@ -868,6 +870,13 @@
"tslib": "^2.4.0" "tslib": "^2.4.0"
} }
}, },
"node_modules/@types/trusted-types": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
"license": "MIT",
"optional": true
},
"node_modules/@vitejs/plugin-vue": { "node_modules/@vitejs/plugin-vue": {
"version": "6.0.7", "version": "6.0.7",
"resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-6.0.7.tgz", "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-6.0.7.tgz",
@@ -1260,6 +1269,15 @@
"node": ">=8" "node": ">=8"
} }
}, },
"node_modules/dompurify": {
"version": "3.4.7",
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.7.tgz",
"integrity": "sha512-2jBxDJY4RR06tQNy4w5FlFH7kfxsQZlufd0sbv+chfHCxeJwrFw2baUDsSwvBISD4K4RDbd0PTfy3uNXsR6siA==",
"license": "(MPL-2.0 OR Apache-2.0)",
"optionalDependencies": {
"@types/trusted-types": "^2.0.7"
}
},
"node_modules/electron-to-chromium": { "node_modules/electron-to-chromium": {
"version": "1.5.361", "version": "1.5.361",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.361.tgz", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.361.tgz",
@@ -1726,6 +1744,18 @@
"@jridgewell/sourcemap-codec": "^1.5.5" "@jridgewell/sourcemap-codec": "^1.5.5"
} }
}, },
"node_modules/marked": {
"version": "18.0.4",
"resolved": "https://registry.npmjs.org/marked/-/marked-18.0.4.tgz",
"integrity": "sha512-c/BTaKzg0G6ezQx97DAkYU7k0HM6ys0FqYeKBL6hlBByZwy+ycA1+f0vDdjMHKKeEjdgkx0GOv9Il6D+85cOqA==",
"license": "MIT",
"bin": {
"marked": "bin/marked.js"
},
"engines": {
"node": ">= 20"
}
},
"node_modules/mrmime": { "node_modules/mrmime": {
"version": "2.0.1", "version": "2.0.1",
"resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.1.tgz", "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.1.tgz",

View File

@@ -9,6 +9,8 @@
"preview": "vite preview" "preview": "vite preview"
}, },
"dependencies": { "dependencies": {
"dompurify": "^3.4.7",
"marked": "^18.0.4",
"vue": "^3.5.32" "vue": "^3.5.32"
}, },
"devDependencies": { "devDependencies": {

View File

@@ -44,6 +44,15 @@ export function htmlUrl(id) {
return `${BASE}/guides/${id}/html` return `${BASE}/guides/${id}/html`
} }
export async function chatGuide(id, { section, outline, messages }) {
const res = await fetch(`${BASE}/guides/${id}/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ section, outline, messages }),
})
return res.json()
}
export async function suggestTopics(problem) { export async function suggestTopics(problem) {
const res = await fetch(`${BASE}/topic-suggestions`, { const res = await fetch(`${BASE}/topic-suggestions`, {
method: 'POST', method: 'POST',

View File

@@ -1,6 +1,14 @@
<script setup> <script setup>
import { computed } from 'vue' import { computed, ref, nextTick } from 'vue'
import { htmlUrl } from '../api.js' import { marked } from 'marked'
import DOMPurify from 'dompurify'
import { htmlUrl, chatGuide } from '../api.js'
marked.setOptions({ breaks: true, gfm: true })
function renderMarkdown(text) {
return DOMPurify.sanitize(marked.parse(text || ''))
}
const props = defineProps({ const props = defineProps({
previewGuide: { type: Object, default: null }, previewGuide: { type: Object, default: null },
@@ -9,25 +17,142 @@ const props = defineProps({
const LANDSCAPE_FORMATS = ['OnePager', 'Cheatsheet'] const LANDSCAPE_FORMATS = ['OnePager', 'Cheatsheet']
const isLandscape = computed(() => LANDSCAPE_FORMATS.includes(props.previewGuide?.format)) const isLandscape = computed(() => LANDSCAPE_FORMATS.includes(props.previewGuide?.format))
const frameEl = ref(null)
function injectPadding(e) { function injectPadding(e) {
if (isLandscape.value) return if (isLandscape.value) return
const doc = e.target.contentDocument const doc = e.target.contentDocument
if (!doc) return if (!doc) return
const style = doc.createElement('style') const style = doc.createElement('style')
style.textContent = '@media screen { body { padding: 2.5rem 3rem; } }' style.textContent = `@media screen {
html { background: #f0f1f4; }
body {
zoom: 1.15;
max-width: 1000px;
margin: 0 auto;
padding: 2.5rem 3.5rem;
background: #fff;
box-shadow: 0 1px 8px rgba(0, 0, 0, 0.08);
}
}`
doc.head?.appendChild(style) doc.head?.appendChild(style)
} }
// --- Chat ---
const chatOpen = ref(false)
const messages = ref([])
const input = ref('')
const loading = ref(false)
const messagesEl = ref(null)
const inputEl = ref(null)
function openChat() {
chatOpen.value = true
}
function closeChat() {
chatOpen.value = false
messages.value = []
input.value = ''
}
function extractContext() {
try {
const doc = frameEl.value?.contentDocument
if (!doc) return { section: '', outline: '' }
const headings = Array.from(doc.querySelectorAll('h1, h2, h3'))
if (!headings.length) return { section: '', outline: '' }
const outline = headings.map((h) => h.innerText.trim()).filter(Boolean).join('\n')
// Aktuelle Überschrift = letzte, die oben im sichtbaren Bereich oder darüber liegt
let current = headings[0]
for (const h of headings) {
if (h.getBoundingClientRect().top <= 100) current = h
else break
}
const level = Number(current.tagName[1])
const idx = headings.indexOf(current)
let end = null
for (let i = idx + 1; i < headings.length; i++) {
if (Number(headings[i].tagName[1]) <= level) { end = headings[i]; break }
}
const range = doc.createRange()
range.setStartBefore(current)
if (end) range.setEndBefore(end)
else range.setEndAfter(doc.body.lastElementChild || doc.body)
const section = range.toString().trim().slice(0, 18000)
return { section, outline: outline.slice(0, 7000) }
} catch {
return { section: '', outline: '' }
}
}
async function scrollToBottom() {
await nextTick()
if (messagesEl.value) messagesEl.value.scrollTop = messagesEl.value.scrollHeight
}
async function send() {
const text = input.value.trim()
if (!text || loading.value || !props.previewGuide) return
messages.value.push({ role: 'user', content: text })
input.value = ''
loading.value = true
scrollToBottom()
try {
const { section, outline } = extractContext()
const res = await chatGuide(props.previewGuide.id, {
section,
outline,
messages: messages.value,
})
messages.value.push({ role: 'assistant', content: res.reply || '…' })
} catch {
messages.value.push({ role: 'assistant', content: 'Fehler bei der Anfrage.' })
} finally {
loading.value = false
scrollToBottom()
nextTick(() => inputEl.value?.focus())
}
}
</script> </script>
<template> <template>
<div class="detail"> <div class="detail">
<div class="preview" v-if="previewGuide"> <div class="preview" :class="{ landscape: isLandscape }" v-if="previewGuide">
<iframe :src="htmlUrl(previewGuide.id)" class="preview-frame" :class="{ landscape: isLandscape }" title="Guide-Vorschau" @load="injectPadding"></iframe> <iframe ref="frameEl" :src="htmlUrl(previewGuide.id)" class="preview-frame" :class="{ landscape: isLandscape }" title="Guide-Vorschau" @load="injectPadding"></iframe>
</div> </div>
<div class="empty-preview" v-else> <div class="empty-preview" v-else>
<p>Guide-Format anklicken um zu generieren oder Vorschau zu öffnen.</p> <p>Guide-Format anklicken um zu generieren oder Vorschau zu öffnen.</p>
</div> </div>
<button v-if="previewGuide && !chatOpen" class="chat-fab" title="Fragen zum Guide" @click="openChat">💬</button>
<div v-if="previewGuide && chatOpen" class="chat-panel">
<header class="chat-header">
<span>Fragen zum Guide</span>
<button class="chat-close" title="Chat beenden" @click="closeChat">×</button>
</header>
<div ref="messagesEl" class="chat-messages">
<p v-if="!messages.length" class="chat-hint">Stell eine Frage zum aktuellen Abschnitt.</p>
<template v-for="(m, i) in messages" :key="i">
<div v-if="m.role === 'assistant'" class="chat-msg assistant markdown" v-html="renderMarkdown(m.content)"></div>
<div v-else class="chat-msg user">{{ m.content }}</div>
</template>
<div v-if="loading" class="chat-msg assistant chat-typing">Denkt</div>
</div>
<div class="chat-input">
<textarea
ref="inputEl"
v-model="input"
placeholder="Frage stellen…"
@keydown.enter.exact.prevent="send"
></textarea>
<button :disabled="!input.trim() || loading" @click="send"></button>
</div>
</div>
</div> </div>
</template> </template>
@@ -42,10 +167,13 @@ function injectPadding(e) {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
padding: 2rem;
background: #f0f1f4; background: #f0f1f4;
} }
.preview.landscape {
padding: 2rem;
}
.preview-header { .preview-header {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
@@ -76,15 +204,14 @@ function injectPadding(e) {
.preview-frame { .preview-frame {
width: 100%; width: 100%;
max-width: 900px;
flex: 1; flex: 1;
border: none; border: none;
background: #fff; background: #fff;
box-shadow: 0 1px 8px rgba(0, 0, 0, 0.08);
} }
.preview-frame.landscape { .preview-frame.landscape {
max-width: 1180px; max-width: 1180px;
box-shadow: 0 1px 8px rgba(0, 0, 0, 0.08);
} }
.empty-preview { .empty-preview {
@@ -94,4 +221,209 @@ function injectPadding(e) {
height: 100%; height: 100%;
color: #5a6470; color: #5a6470;
} }
.chat-fab {
position: fixed;
right: 1.5rem;
bottom: 1.5rem;
width: 52px;
height: 52px;
border: none;
border-radius: 50%;
background: #6366f1;
color: #fff;
font-size: 1.4rem;
cursor: pointer;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.25);
z-index: 20;
}
.chat-fab:hover {
background: #4f46e5;
}
.chat-panel {
position: fixed;
right: 1.5rem;
bottom: 1.5rem;
width: 360px;
height: 500px;
max-height: calc(100vh - 3rem);
display: flex;
flex-direction: column;
background: #fff;
border: 1px solid #e2e5e9;
border-radius: 12px;
box-shadow: 0 4px 24px rgba(0, 0, 0, 0.18);
z-index: 20;
overflow: hidden;
}
.chat-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.6rem 0.9rem;
background: #6366f1;
color: #fff;
font-weight: 600;
font-size: 0.9rem;
}
.chat-close {
border: none;
background: none;
color: #fff;
font-size: 1.4rem;
line-height: 1;
cursor: pointer;
padding: 0 4px;
}
.chat-messages {
flex: 1;
overflow-y: auto;
padding: 0.9rem;
display: flex;
flex-direction: column;
gap: 8px;
}
.chat-hint {
color: #9aa3af;
font-size: 0.82rem;
text-align: center;
margin-top: 1rem;
}
.chat-msg {
max-width: 85%;
padding: 7px 11px;
border-radius: 12px;
font-size: 0.85rem;
line-height: 1.4;
white-space: pre-wrap;
word-break: break-word;
}
.chat-msg.user {
align-self: flex-end;
background: #6366f1;
color: #fff;
border-bottom-right-radius: 3px;
}
.chat-msg.assistant {
align-self: flex-start;
background: #f1f3f7;
color: #1a1a1a;
border-bottom-left-radius: 3px;
}
.chat-typing {
color: #9aa3af;
font-style: italic;
}
.chat-msg.markdown :deep(p) {
margin: 0 0 0.5em;
}
.chat-msg.markdown :deep(p:last-child) {
margin-bottom: 0;
}
.chat-msg.markdown :deep(ul),
.chat-msg.markdown :deep(ol) {
margin: 0.3em 0;
padding-left: 1.2em;
}
.chat-msg.markdown :deep(li) {
margin: 0.15em 0;
}
.chat-msg.markdown :deep(code) {
background: #e4e7ee;
padding: 1px 4px;
border-radius: 4px;
font-family: "SF Mono", Consolas, monospace;
font-size: 0.8em;
}
.chat-msg.markdown :deep(pre) {
background: #1e2330;
color: #e6e8ee;
padding: 8px 10px;
border-radius: 8px;
overflow-x: auto;
margin: 0.5em 0;
}
.chat-msg.markdown :deep(pre code) {
background: none;
padding: 0;
color: inherit;
font-size: 0.78em;
}
.chat-msg.markdown :deep(h1),
.chat-msg.markdown :deep(h2),
.chat-msg.markdown :deep(h3) {
font-size: 0.95em;
margin: 0.4em 0 0.2em;
}
.chat-msg.markdown :deep(a) {
color: #4f46e5;
}
.chat-msg.markdown :deep(table) {
border-collapse: collapse;
font-size: 0.95em;
}
.chat-msg.markdown :deep(th),
.chat-msg.markdown :deep(td) {
border: 1px solid #d8dde3;
padding: 2px 6px;
}
.chat-input {
display: flex;
gap: 6px;
padding: 0.6rem;
border-top: 1px solid #e2e5e9;
}
.chat-input textarea {
flex: 1;
resize: none;
height: 38px;
padding: 8px 10px;
border: 1px solid #d8dde3;
border-radius: 8px;
font-size: 0.85rem;
font-family: inherit;
outline: none;
}
.chat-input textarea:focus {
border-color: #6366f1;
}
.chat-input button {
width: 38px;
border: none;
border-radius: 8px;
background: #6366f1;
color: #fff;
font-size: 1rem;
cursor: pointer;
}
.chat-input button:disabled {
opacity: 0.4;
cursor: not-allowed;
}
</style> </style>