Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions backend/app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,10 @@ class Settings(BaseSettings):
llm_max_concurrent: int = 6 # model calls in flight at once across all jobs: quizzes and flashcards run two at a time per job
# GLM-5.x always reasons (it cannot be disabled); this sets how hard. low | high | max
llm_reasoning_effort: str = "low"
# Seconds before a model request is given up (LiteLLM's own default is 600). Chat calls use the shorter ones.
llm_timeout_seconds: float = 300.0
chat_llm_timeout_seconds: float = 90.0 # research agent and answer writer
chat_fast_timeout_seconds: float = 25.0 # triage, query expansion

# Corpus: posts as markdown files. R2 is the source of truth; each process keeps a disk cache.
corpus_cache_dir: str = ".corpus-cache"
Expand Down Expand Up @@ -159,6 +163,27 @@ class Settings(BaseSettings):
# then hold writers' text, so it is on only in development unless CHAT_CONTEXT_LOG=true. None follows ENV.
chat_context_log: bool | None = None

# Langfuse tracing for the notebook chat (app/observability/langfuse.py): one trace per message with every stage,
# the outcome code, user ratings and judge scores. Empty keys = off. LANGFUSE_HOST: cloud or a self-hosted URL.
langfuse_public_key: str = ""
langfuse_secret_key: str = ""
langfuse_host: str = ""
# Send only sizes, never writers' text (questions, answers, passages), unless this is false. Turn it off only
# with a self-hosted Langfuse.
langfuse_mask_text: bool = True
# Share of archive answers scored by the LLM judge in the worker (relevance, faithfulness, false refusals).
chat_judge_sample_rate: float = 0.2

# Retrieval (docs/plan: post cards + long context). CHAT_ROUTER replaces the keyword prefetch / fast path with
# tiers: Tier A puts the whole notebook in the prompt when it fits CHAT_FULL_NOTEBOOK_TOKENS, Tier B picks posts
# with card + passage BM25 up to CHAT_EVIDENCE_TOKENS, Tier C is the research agent when neither is answered.
chat_router: bool = False
chat_full_notebook_tokens: int = 60_000
chat_evidence_tokens: int = 30_000
chat_query_expansion: bool = True
# Post cards: one fast-model call per post at ingest (summary, topics, names, synonyms, questions it answers).
post_cards_enabled: bool = True

# ElevenLabs (premade voices by default; a consented clone can replace host A)
elevenlabs_api_key: str = ""
elevenlabs_model: str = "eleven_multilingual_v2"
Expand Down
167 changes: 142 additions & 25 deletions backend/app/corpus.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,59 @@

import hashlib
import json
import logging
import re
import threading
import time
import unicodedata
import uuid
from collections.abc import Iterator
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path, PurePosixPath

from sqlalchemy import text as sql

from app.config import settings
from app.db import engine
from app.services.storage import is_not_found
from app.services.storage import storage as default_storage

log = logging.getLogger(__name__)

MANIFEST = "manifest.json"
INDEX = "INDEX.md"
MAX_READ_LINES = 160
MAX_READ_CHARS = 12_000 # one read() result: a "line" is a whole paragraph, so lines alone do not bound it
MAX_SEARCH_HITS = 40
MAX_LINE_CHARS = 240
MAX_LINE_CHARS = 240 # a search hit shows this much of its line, centred on the match
LONG_LINE_CHARS = 1_500 # a paragraph longer than this is stored as several lines (cut at sentence ends)
CARDS_DIR = "cards" # post cards (app/pipeline/cards.py): cards/<post path>.json, never citable


def card_rel(post_rel: str) -> str:
return f"{CARDS_DIR}/{post_rel}.json"


_SENTENCE_END = re.compile(r"(?<=[.!?])\s+")


def split_long(paragraph: str, limit: int = LONG_LINE_CHARS) -> list[str]:
"""A long paragraph as several lines of at most about `limit` characters, cut at sentence ends, so a citation
points at a few sentences instead of a whole page (PDFs and transcripts often have no paragraph breaks).
Code blocks and anything already on several lines are kept as they are."""
if len(paragraph) <= limit or "\n" in paragraph or paragraph.startswith("```"):
return [paragraph]
out, piece = [], ""
for sentence in _SENTENCE_END.split(paragraph):
if piece and len(piece) + len(sentence) + 1 > limit:
out.append(piece)
piece = ""
piece = f"{piece} {sentence}" if piece else sentence
if piece:
out.append(piece)
return out

_locks: dict[tuple[uuid.UUID, str], threading.Lock] = {}
# Posts only: when this process last brought a corpus in line with R2, and the manifest it saw (root -> (time, manifest)).
Expand Down Expand Up @@ -70,7 +106,7 @@ def render_post(*, title: str, url: str, published_at: datetime | None, source:
if heading:
lines += [f"## {heading}", ""]
for para in text.split("\n\n"):
lines += [para.strip(), ""]
lines += [*split_long(para.strip()), ""] # the pieces stay one paragraph (no blank line between)
return "\n".join(lines).rstrip() + "\n"


Expand Down Expand Up @@ -134,28 +170,70 @@ def _write_manifest(self, manifest: dict[str, str]) -> None:
self.root.mkdir(parents=True, exist_ok=True)
(self.root / MANIFEST).write_text(data, "utf-8")

@contextmanager
def _manifest_lock(self) -> Iterator[None]:
"""Serialise manifest read-modify-writes across processes. The API (deletes) and the worker (imports, cards,
chat memory) both rewrite manifest.json; `self._lock` only covers one process, and without this a writer that
read the manifest before another's delete wrote it back with the deleted files still listed. A Postgres
transaction advisory lock (works through Neon's transaction pooler) keyed on workspace + area; released when
the transaction ends. SQLite (tests, local dev) has one writer process anyway, so it is skipped there.
Callers hold `self._lock` first."""
if engine.dialect.name != "postgresql":
yield
return
digest = hashlib.blake2b(f"corpus:{self.workspace_id}:{self.area}".encode(), digest_size=8).digest()
with engine.begin() as conn:
conn.execute(sql("SET LOCAL lock_timeout = '60s'"))
conn.execute(sql("SELECT pg_advisory_xact_lock(:k)"), {"k": int.from_bytes(digest, "big", signed=True)})
yield

# Writes (worker)

def write_files(self, files: dict[str, str], remove: set[str] | None = None) -> None:
"""Write/replace files and update the manifest once. Values are file contents."""
with self._lock:
"""Write/replace files and update the manifest once. Values are file contents.

Objects are uploaded before the manifest lock is taken (a big import does not hold up a delete), then the
manifest is re-read and updated under the lock. Removed objects are deleted after the manifest stops listing
them, so a reader never sees a listed file that is already gone."""
written: dict[str, str] = {}
for rel, body in files.items():
rel = self.clean_rel(rel)
self.store.put_text(self._key(rel), body, "text/markdown; charset=utf-8")
written[rel] = body
with self._lock, self._manifest_lock():
manifest = self._read_manifest(remote=True)
for rel, text in files.items():
rel = self.clean_rel(rel)
self.store.put_text(self._key(rel), text, "text/markdown; charset=utf-8")
for rel, body in written.items():
local = self._local(rel)
local.parent.mkdir(parents=True, exist_ok=True)
local.write_text(text, "utf-8")
manifest[rel] = hashlib.sha256(text.encode()).hexdigest()
for rel in remove or set():
rel = self.clean_rel(rel)
local.write_text(body, "utf-8")
manifest[rel] = hashlib.sha256(body.encode()).hexdigest()
removing = {self.clean_rel(rel) for rel in remove or set()}
if self.area == "corpus": # a removed post takes its card with it
removing |= {card_rel(rel) for rel in removing if card_rel(rel) in manifest}
for rel in removing:
manifest.pop(rel, None)
self._write_manifest(manifest)
for rel in removing:
self.store.delete(self._key(rel))
self._local(rel).unlink(missing_ok=True)
self._write_manifest(manifest)
if self.area == "corpus":
_synced[str(self.root)] = (time.monotonic(), dict(manifest))

def _drop_missing(self, missing: set[str]) -> dict[str, str]:
"""Take entries whose object is gone out of the remote manifest (left there by an older lost update, or a
delete outside the app). Re-checked under the lock: an entry a writer has since fixed is kept."""
with self._manifest_lock():
manifest = self._read_manifest(remote=True)
gone = {rel for rel in missing if rel in manifest and not self.store.exists(self._key(rel))}
if gone:
for rel in gone:
manifest.pop(rel)
self.store.put_text(self._key(MANIFEST), json.dumps(manifest, sort_keys=True, indent=0),
"application/json")
log.warning("corpus %s/%s: dropped %d manifest entries with no object: %s",
self.workspace_id, self.area, len(gone), sorted(gone))
return manifest

# Sync (API / any reader)

def sync(self, need: tuple[str, ...] | list[str] = ()) -> dict[str, str]:
Expand All @@ -170,12 +248,24 @@ def sync(self, need: tuple[str, ...] | list[str] = ()) -> dict[str, str]:
with self._lock:
remote = self._read_manifest(remote=True)
local = self._read_manifest(remote=False)
missing: set[str] = set()
for rel, digest in remote.items():
path = self._local(rel)
if local.get(rel) == digest and path.exists():
continue
try:
data = self.store.get_bytes(self._key(rel))
except Exception as exc:
if not is_not_found(exc):
raise
missing.add(rel) # one listed-but-gone file must not fail every read in the workspace
continue
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(self.store.get_bytes(self._key(rel)))
path.write_bytes(data)
if missing:
self._drop_missing(missing)
# Not on disk now: leave them out of the local manifest so a later sync fetches any a writer restored.
remote = {rel: digest for rel, digest in remote.items() if rel not in missing}
for rel in set(local) - set(remote):
self._local(rel).unlink(missing_ok=True)
self.root.mkdir(parents=True, exist_ok=True)
Expand All @@ -196,6 +286,16 @@ def read_lines(self, rel: str) -> list[str]:
return path.read_text("utf-8").splitlines()


def _snippet(line: str, match: re.Match) -> str:
"""MAX_LINE_CHARS of the line around the match: a line can be a long paragraph whose match is far from its start."""
line = line.strip() if len(line) <= MAX_LINE_CHARS else line
if len(line) <= MAX_LINE_CHARS:
return line
start = max(0, min(match.start() - MAX_LINE_CHARS // 3, len(line) - MAX_LINE_CHARS))
text = line[start:start + MAX_LINE_CHARS].strip()
return ("..." if start > 0 else "") + text + ("..." if start + MAX_LINE_CHARS < len(line) else "")


class ScopedTools:
"""The agent's tools, restricted to an allowlist of files (a notebook's posts).

Expand Down Expand Up @@ -234,27 +334,36 @@ def list_files(self, contains: str = "") -> str:
def search(self, pattern: str, path: str = "") -> str:
"""Search post text with a case insensitive regular expression (like grep). Use `|` for
alternatives, e.g. `pric(e|ing)|paid tier|subscription cost`. Optionally limit to one `path`.
Returns `path:line: text` matches."""
Returns `path:line: text` matches, the posts with the most matches first."""
self.on_step("search", pattern)
try:
rx = re.compile(pattern, re.IGNORECASE)
except re.error:
rx = re.compile(re.escape(pattern), re.IGNORECASE)
targets = [self._check(path)] if path else list(self.allowed)
hits: list[Hit] = []
total = 0
by_post: dict[str, list[tuple[int, int, Hit]]] = {} # path -> (matches on the line, line, hit)
unavailable = 0
for rel in targets:
for n, line in enumerate(self.corpus.read_lines(rel), start=1):
if rx.search(line):
total += 1
if len(hits) < MAX_SEARCH_HITS:
hits.append(Hit(rel, n, line.strip()[:MAX_LINE_CHARS]))
if not hits:
return "No matches. Try synonyms or a broader pattern."
try:
lines = self.corpus.read_lines(rel)
except CorpusError: # one missing file must not fail the search over every other post
unavailable += 1
continue
for n, line in enumerate(lines, start=1):
found = list(rx.finditer(line))
if found:
by_post.setdefault(rel, []).append((len(found), n, Hit(rel, n, _snippet(line, found[0]))))
total = sum(len(v) for v in by_post.values())
note = f"\n({unavailable} post(s) could not be read right now)" if unavailable else ""
if not total:
return "No matches. Try synonyms or a broader pattern." + note
# Posts with more matching lines first (a post about the subject beats one that mentions it), lines in order.
ranked = sorted(by_post.values(), key=lambda v: (-len(v), -sum(m for m, _, _ in v)))
hits = [h for post in ranked for _, _, h in post][:MAX_SEARCH_HITS]
out = "\n".join(f"{h.path}:{h.line}: {h.text}" for h in hits)
if total > len(hits):
out += f"\n... {total - len(hits)} more matches. Narrow the pattern or pass a path."
return out
return out + note

def read(self, path: str, start_line: int = 1, end_line: int = 0) -> str:
"""Read a post with line numbers. Reads at most 160 lines per call; pass start_line and
Expand All @@ -264,8 +373,16 @@ def read(self, path: str, start_line: int = 1, end_line: int = 0) -> str:
start = max(1, start_line)
end = min(len(lines), end_line if end_line >= start else start + MAX_READ_LINES - 1)
end = min(end, start + MAX_READ_LINES - 1)
rows, used = [], 0
for n in range(start, end + 1):
row = f"{n}| {lines[n - 1]}"
if rows and used + len(row) > MAX_READ_CHARS: # stop before the result gets too big; page on from here
end = n - 1
break
rows.append(row[:MAX_READ_CHARS])
used += len(row) + 1
self.on_step("read", f"{self.allowed.get(rel, rel)} (lines {start} to {end})")
body = "\n".join(f"{n}| {lines[n - 1]}" for n in range(start, end + 1))
body = "\n".join(rows)
more = f"\n[{len(lines) - end} more lines]" if end < len(lines) else ""
return f"{rel} ({len(lines)} lines)\n{body}{more}"

Expand Down
15 changes: 13 additions & 2 deletions backend/app/llm/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,17 @@ def _extra_kwargs(effort: str | None) -> dict:
return {"extra_body": {"thinking": {"type": "enabled"}, "reasoning_effort": effort}}


def _build(model: str, *, effort: str | None, temperature: float | None, max_tokens: int | None) -> dspy.LM:
def _build(model: str, *, effort: str | None, temperature: float | None, max_tokens: int | None,
cache: bool = True, timeout: float | None = None) -> dspy.LM:
# timeout: LiteLLM's default is 600s, so one stuck request used to hold a chat for ten minutes.
return dspy.LM(
model,
api_base=settings.llm_api_base or None,
api_key=settings.llm_api_key or None,
temperature=settings.llm_temperature if temperature is None else temperature,
max_tokens=max_tokens or settings.llm_max_tokens,
cache=True,
cache=cache,
timeout=timeout or settings.llm_timeout_seconds,
**_extra_kwargs(effort),
)

Expand All @@ -47,6 +50,14 @@ def main_lm(effort: str | None = None) -> dspy.LM:
return _build(settings.llm_model, effort=effort, temperature=None, max_tokens=None)


@lru_cache
def agent_lm() -> dspy.LM:
"""The chat research agent: the main model, never cached (a retried question must not replay the same failing
steps) and with the chat's own timeout."""
return _build(settings.llm_model, effort=None, temperature=None, max_tokens=None, cache=False,
timeout=settings.chat_llm_timeout_seconds)


@lru_cache
def fast_lm() -> dspy.LM:
return _build(settings.llm_fast_model, effort="low", temperature=None, max_tokens=settings.llm_fast_max_tokens)
Expand Down
7 changes: 4 additions & 3 deletions backend/app/llm/signatures.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,10 @@ class CleanAndSegment(dspy.Signature):

class ResearchArchive(dspy.Signature):
__doc__ = """You are a research assistant working inside a writer's archive, which is a folder of markdown
posts. Find the answer by exploring the files, in this order. First call list_files to see which posts
exist; a post whose title matches the topic is often the best source. Then call search across the whole
archive (leave path empty; try several phrasings and synonyms) to locate relevant lines. Pass path to
posts. Start from the prefetched passages: when they answer the question, cite them directly. Otherwise call
search across the whole archive (leave path empty; try several phrasings and synonyms) to locate relevant
lines. Call list_files when you need to see which posts exist; a post whose title matches the topic is often
the best source. Pass path to
search only when the writer explicitly asks you to use one named post (for example "in the Neo4j post" or
"in that article"); otherwise never limit a search to one post, because a different post may be the best
source. Then read the surrounding lines before relying on them. When more than one post covers the topic,
Expand Down
Empty file.
Loading
Loading