Add LLM chat integration with streaming responses via Ollama
Phase 4: Full chat system with SSE streaming, note-aware context, and conversation persistence. Backend: - Migration 0005: conversations + messages tables with FKs and indexes - Conversation/Message SQLAlchemy models with relationships - LLM service: ensure_model (auto-pull on startup), stream_chat (NDJSON), generate_completion, fetch_url_content (HTML stripping), build_context (keyword extraction, related note search, URL content injection) - Chat service: conversation CRUD, save_response_as_note, summarize_conversation_as_note - Chat routes blueprint: 9 endpoints including SSE streaming for messages, save/summarize as note, Ollama model listing - Auto-pull llama3.1 model on app startup (non-blocking) Frontend: - apiStreamPost: SSE client using fetch + ReadableStream - Chat Pinia store with streaming state management - ChatView: dedicated /chat page with conversation sidebar + message thread - ChatPanel: slide-out panel with contextNoteId from current route - ChatMessage: markdown-rendered message bubble with "Save as Note" action - Updated AppHeader with Chat nav link + panel toggle button - Updated App.vue to mount ChatPanel with route-derived context - Added /chat and /chat/:id routes Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,194 @@
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from collections.abc import AsyncGenerator
|
||||
|
||||
import httpx
|
||||
|
||||
from fabledassistant.config import Config
|
||||
from fabledassistant.services.notes import get_note, list_notes
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
STOP_WORDS = frozenset({
|
||||
"a", "an", "the", "is", "it", "to", "in", "for", "of", "and", "or",
|
||||
"on", "at", "by", "with", "from", "as", "be", "was", "were", "been",
|
||||
"are", "am", "do", "does", "did", "have", "has", "had", "will", "would",
|
||||
"can", "could", "shall", "should", "may", "might", "must", "that",
|
||||
"this", "these", "those", "i", "me", "my", "you", "your", "he", "she",
|
||||
"we", "they", "them", "his", "her", "its", "our", "their", "what",
|
||||
"which", "who", "whom", "how", "when", "where", "why", "not", "no",
|
||||
"but", "if", "so", "than", "too", "very", "just", "about", "up",
|
||||
})
|
||||
|
||||
|
||||
async def ensure_model(model: str) -> None:
|
||||
"""Check if model exists in Ollama, pull if missing."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10.0) as client:
|
||||
resp = await client.get(f"{Config.OLLAMA_URL}/api/tags")
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
names = {m["name"] for m in data.get("models", [])}
|
||||
# Check both with and without :latest tag
|
||||
if model in names or f"{model}:latest" in names:
|
||||
logger.info("Model '%s' already available", model)
|
||||
return
|
||||
except Exception:
|
||||
logger.warning("Failed to check Ollama models, attempting pull anyway")
|
||||
|
||||
logger.info("Pulling model '%s' from Ollama...", model)
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=600.0) as client:
|
||||
async with client.stream(
|
||||
"POST",
|
||||
f"{Config.OLLAMA_URL}/api/pull",
|
||||
json={"name": model},
|
||||
) as resp:
|
||||
resp.raise_for_status()
|
||||
async for line in resp.aiter_lines():
|
||||
if line.strip():
|
||||
status = json.loads(line)
|
||||
if "status" in status:
|
||||
logger.info("Pull %s: %s", model, status["status"])
|
||||
logger.info("Model '%s' pulled successfully", model)
|
||||
except Exception:
|
||||
logger.warning("Failed to pull model '%s' — chat may not work", model, exc_info=True)
|
||||
|
||||
|
||||
async def stream_chat(
|
||||
messages: list[dict], model: str
|
||||
) -> AsyncGenerator[str, None]:
|
||||
"""Stream chat completion from Ollama, yielding content chunks."""
|
||||
async with httpx.AsyncClient(timeout=httpx.Timeout(300.0, connect=10.0)) as client:
|
||||
async with client.stream(
|
||||
"POST",
|
||||
f"{Config.OLLAMA_URL}/api/chat",
|
||||
json={"model": model, "messages": messages, "stream": True},
|
||||
) as resp:
|
||||
resp.raise_for_status()
|
||||
async for line in resp.aiter_lines():
|
||||
if not line.strip():
|
||||
continue
|
||||
data = json.loads(line)
|
||||
chunk = data.get("message", {}).get("content", "")
|
||||
if chunk:
|
||||
yield chunk
|
||||
if data.get("done"):
|
||||
break
|
||||
|
||||
|
||||
async def generate_completion(messages: list[dict], model: str) -> str:
|
||||
"""Non-streaming chat completion, returns full response text."""
|
||||
async with httpx.AsyncClient(timeout=httpx.Timeout(300.0, connect=10.0)) as client:
|
||||
resp = await client.post(
|
||||
f"{Config.OLLAMA_URL}/api/chat",
|
||||
json={"model": model, "messages": messages, "stream": False},
|
||||
)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
return data.get("message", {}).get("content", "")
|
||||
|
||||
|
||||
async def fetch_url_content(url: str) -> str:
|
||||
"""Fetch a URL and return text content (HTML tags stripped)."""
|
||||
try:
|
||||
async with httpx.AsyncClient(
|
||||
timeout=15.0, follow_redirects=True, headers={"User-Agent": "FabledAssistant/1.0"}
|
||||
) as client:
|
||||
resp = await client.get(url)
|
||||
resp.raise_for_status()
|
||||
text = resp.text
|
||||
# Strip HTML tags
|
||||
text = re.sub(r"<script[^>]*>.*?</script>", "", text, flags=re.DOTALL)
|
||||
text = re.sub(r"<style[^>]*>.*?</style>", "", text, flags=re.DOTALL)
|
||||
text = re.sub(r"<[^>]+>", " ", text)
|
||||
# Collapse whitespace
|
||||
text = re.sub(r"\s+", " ", text).strip()
|
||||
# Truncate to reasonable size
|
||||
if len(text) > 4000:
|
||||
text = text[:4000] + "..."
|
||||
return text
|
||||
except Exception as e:
|
||||
logger.warning("Failed to fetch URL %s: %s", url, e)
|
||||
return f"[Failed to fetch URL: {url}]"
|
||||
|
||||
|
||||
def _extract_keywords(text: str) -> list[str]:
|
||||
"""Extract meaningful keywords from text for note search."""
|
||||
words = re.findall(r"\b[a-zA-Z]{3,}\b", text.lower())
|
||||
keywords = [w for w in words if w not in STOP_WORDS]
|
||||
# Deduplicate while preserving order
|
||||
seen: set[str] = set()
|
||||
unique = []
|
||||
for w in keywords:
|
||||
if w not in seen:
|
||||
seen.add(w)
|
||||
unique.append(w)
|
||||
return unique[:5]
|
||||
|
||||
|
||||
def _find_urls(text: str) -> list[str]:
|
||||
"""Find URLs in text."""
|
||||
return re.findall(r"https?://[^\s<>\"')\]]+", text)
|
||||
|
||||
|
||||
async def build_context(
|
||||
history: list[dict],
|
||||
current_note_id: int | None,
|
||||
user_message: str,
|
||||
) -> list[dict]:
|
||||
"""Build messages array for Ollama with system prompt and context."""
|
||||
system_parts = [
|
||||
"You are a helpful assistant integrated into a note-taking and task-tracking app called Fabled Assistant. "
|
||||
"Help users with their notes, tasks, and general questions. "
|
||||
"When note context is provided, use it to give relevant answers."
|
||||
]
|
||||
|
||||
# Include current note context if provided
|
||||
if current_note_id:
|
||||
note = await get_note(current_note_id)
|
||||
if note:
|
||||
system_parts.append(
|
||||
f"\n\n--- Current Note ---\n"
|
||||
f"Title: {note.title}\n"
|
||||
f"Content:\n{note.body}\n"
|
||||
f"--- End Note ---"
|
||||
)
|
||||
|
||||
# Search notes by keywords from user message
|
||||
keywords = _extract_keywords(user_message)
|
||||
if keywords:
|
||||
search_q = " ".join(keywords[:3])
|
||||
try:
|
||||
notes, _ = await list_notes(q=search_q, limit=3)
|
||||
if notes:
|
||||
snippets = []
|
||||
for n in notes:
|
||||
# Skip the current note (already included)
|
||||
if current_note_id and n.id == current_note_id:
|
||||
continue
|
||||
body_preview = n.body[:300] if n.body else ""
|
||||
snippets.append(f"- {n.title}: {body_preview}")
|
||||
if snippets:
|
||||
system_parts.append(
|
||||
"\n\n--- Related Notes ---\n"
|
||||
+ "\n".join(snippets)
|
||||
+ "\n--- End Related Notes ---"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Fetch URL content from user message
|
||||
urls = _find_urls(user_message)
|
||||
for url in urls[:2]: # Limit to 2 URLs
|
||||
content = await fetch_url_content(url)
|
||||
if content and not content.startswith("[Failed"):
|
||||
system_parts.append(
|
||||
f"\n\n--- Content from {url} ---\n{content}\n--- End URL Content ---"
|
||||
)
|
||||
|
||||
messages = [{"role": "system", "content": "".join(system_parts)}]
|
||||
messages.extend(history)
|
||||
messages.append({"role": "user", "content": user_message})
|
||||
return messages
|
||||
Reference in New Issue
Block a user