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
66 changes: 66 additions & 0 deletions backend/app/llm/languages.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
"""The app's interface language, so AI output follows it.

The mobile app sends X-App-Language (a code such as "es") when its interface is not English. The middleware in
main.py puts it in a context variable for the request. Jobs created during the request carry it in their params
(services/jobs.py), and the worker restores it while it runs them. Pipelines that already take a language get the
English name as their default, and an explicit language (picked in the app or named in chat) still wins. With no
header, nothing changes: AI output stays in the language of the sources."""

from collections.abc import Iterator
from contextlib import contextmanager
from contextvars import ContextVar

# Keep in step with LANGUAGES in mobile/src/i18n/index.ts. English is absent on purpose: the app sends no header.
APP_LANGUAGES: dict[str, str] = {
"es": "Spanish",
"fr": "French",
"de": "German",
"pt": "Portuguese",
"ar": "Arabic",
"ur": "Urdu",
"zh": "Chinese (Simplified)",
"ja": "Japanese",
"ko": "Korean",
}

HEADER = "x-app-language"
PARAM = "app_language" # the code, kept in a job's params

_current: ContextVar[str | None] = ContextVar("app_language", default=None)


def parse(value: str | None) -> str | None:
"""A supported code from a header value such as "es", "es-MX" or "zh-Hans", else None."""
if not value:
return None
code = value.strip().lower().replace("_", "-").split("-")[0]
return code if code in APP_LANGUAGES else None


def app_language() -> str | None:
"""The current request's (or job's) app language code, or None."""
return _current.get()


def app_language_name() -> str | None:
"""The English name of the current app language ("Spanish"), or None."""
code = _current.get()
return APP_LANGUAGES.get(code) if code else None


@contextmanager
def use_app_language(code: str | None) -> Iterator[None]:
token = _current.set(parse(code))
try:
yield
finally:
_current.reset(token)


def reply_language_note() -> str:
"""A line for the writer notes in chat, or "" when the app is in English."""
name = app_language_name()
if not name:
return ""
return (f"Reply language: write the answer in {name}, the language of the writer's app. If the writer's message "
"is written in another language, answer in the language of the message instead.")
9 changes: 9 additions & 0 deletions backend/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
from fastapi.responses import PlainTextResponse

from app.config import settings
from app.llm.languages import HEADER as APP_LANGUAGE_HEADER
from app.llm.languages import use_app_language
from app.llm.provider import configure_default
from app.routers import (
artifacts,
Expand Down Expand Up @@ -87,6 +89,13 @@ async def lifespan(app: FastAPI):
)


@app.middleware("http")
async def app_language(request: Request, call_next):
# The mobile app's interface language (llm/languages.py): AI output made for this request follows it.
with use_app_language(request.headers.get(APP_LANGUAGE_HEADER)):
return await call_next(request)


@app.middleware("http")
async def request_id(request: Request, call_next):
rid = request.headers.get("x-request-id") or uuid.uuid4().hex[:12]
Expand Down
10 changes: 9 additions & 1 deletion backend/app/pipeline/research.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
from app.chat_memory.tools import ChatTools, is_chat_path
from app.config import settings
from app.corpus import Corpus, CorpusError, ScopedTools
from app.llm.languages import reply_language_note
from app.llm.postprocess import strip_em_dashes
from app.llm.provider import agent_lm, fast_lm, track_usage, triage_lm, writer_lm
from app.llm.signatures import (
Expand Down Expand Up @@ -1142,6 +1143,12 @@ def _memory_parts(notes: str) -> str:
return ", ".join(parts) or "empty"


def with_reply_language(profile: str | None) -> str:
"""The writer notes plus, when the app is not in English, which language to answer in (llm/languages.py)."""
note = reply_language_note()
return "\n".join(p for p in ((profile or "").strip(), note) if p)


def research(
corpus: Corpus,
allowed: dict[str, str],
Expand Down Expand Up @@ -1480,7 +1487,8 @@ def log(kind: str, detail: str) -> None:
tool_list += external_tools
inputs = dict(question=external_question(route.question) if external_only else route.question,
conversation=conversation_text(history),
archive_guide=archive_guide(tools), writer_profile=profile or "(none)", answer_length=route.detail,
archive_guide=archive_guide(tools), writer_profile=with_reply_language(profile) or "(none)",
answer_length=route.detail,
prefetched="(none)")
if external_only:
signature = ResearchExternal
Expand Down
8 changes: 4 additions & 4 deletions backend/app/routers/sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
rebuild_index,
store_entries,
)
from app.services.jobs import create_job, pending_job, serialize_job
from app.services.jobs import create_job, pending_job, queue_for_documents, serialize_job
from app.services.plans import effective_plan, plan_limit_error, post_room
from app.services.storage import storage
from app.services.url_policy import classify_url
Expand Down Expand Up @@ -424,10 +424,10 @@ def _queue_notebooklm_processing(ctx: Ctx, changed: list[uuid.UUID]) -> None:
if not changed or not settings.llm_api_key:
return
ids = [str(doc_id) for doc_id in changed]
create_job(ctx.db, ctx.workspace.id, "topics", {"document_ids": ids}, max_attempts=2)
create_job(ctx.db, ctx.workspace.id, "ideas", {"document_ids": ids}, max_attempts=2)
queue_for_documents(ctx.db, ctx.workspace.id, "topics", ids, max_attempts=2)
queue_for_documents(ctx.db, ctx.workspace.id, "ideas", ids, max_attempts=2)
if settings.post_cards_enabled:
create_job(ctx.db, ctx.workspace.id, "post_cards", {"document_ids": ids}, max_attempts=2)
queue_for_documents(ctx.db, ctx.workspace.id, "post_cards", ids, max_attempts=2)
if not pending_job(ctx.db, ctx.workspace.id, "resurface_scan"):
create_job(ctx.db, ctx.workspace.id, "resurface_scan", {}, max_attempts=2)

Expand Down
56 changes: 52 additions & 4 deletions backend/app/services/jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@
from datetime import UTC, datetime, timedelta

from fastapi.concurrency import run_in_threadpool
from sqlalchemy import or_, select
from sqlalchemy import case, or_, select
from sqlalchemy.orm import Session

from app.config import settings
from app.llm.languages import PARAM as APP_LANGUAGE_PARAM
from app.llm.languages import app_language, app_language_name
from app.models import Job, UsageEvent

TERMINAL = {"done", "failed"}
Expand Down Expand Up @@ -52,6 +54,48 @@ def pending_job(db: Session, workspace_id: uuid.UUID, kind: str) -> bool:
Job.status.in_(("queued", "running"))).limit(1)) is not None


def queue_for_documents(db: Session, workspace_id: uuid.UUID, kind: str, ids: list[str], **kw) -> Job | None:
"""Enqueue a per-post job (topics, ideas, post_cards) for these posts, or fold them into one of that kind still
waiting in the queue (never tried yet), so a batch of uploads makes one job instead of one per file. A queued job with no
document_ids already covers every post. SKIP LOCKED passes over a job a worker is claiming right now."""
if not ids:
return None
params = with_app_language(kind, {"document_ids": ids})
waiting = db.scalars(
select(Job)
.where(Job.workspace_id == workspace_id, Job.kind == kind, Job.status == "queued",
Job.attempts == 0) # not one waiting out a retry
.order_by(Job.created_at)
.with_for_update(skip_locked=True)
).all()
for job in waiting:
theirs = {k: v for k, v in (job.params or {}).items() if k != "document_ids"}
if theirs != {k: v for k, v in params.items() if k != "document_ids"}:
continue # different options (another language, force): kept apart
have = job.params.get("document_ids")
if have is not None:
job.params = {**job.params, "document_ids": list(dict.fromkeys([*have, *ids]))}
db.commit()
return job
return create_job(db, workspace_id, kind, {"document_ids": ids}, **kw)


# Jobs whose pipeline takes params["language"] (falling back to the language of the sources when it is empty).
LANGUAGE_KINDS = frozenset({"quiz", "flashcards", "report", "report_block", "slide_deck", "audio_overview"})


def with_app_language(kind: str, params: dict) -> dict:
"""Carry the app language into the job: its code always (the worker restores it, so jobs the job starts inherit
it), and its name as the default output language for kinds that take one. An explicit language wins."""
code = app_language()
if not code:
return params
out = {**params, APP_LANGUAGE_PARAM: code}
if kind in LANGUAGE_KINDS and not str(params.get("language") or "").strip():
out["language"] = app_language_name()
return out


def create_job(
db: Session,
workspace_id: uuid.UUID,
Expand All @@ -66,7 +110,7 @@ def create_job(
job = Job(
workspace_id=workspace_id,
kind=kind,
params=params or {},
params=with_app_language(kind, params or {}),
artifact_id=artifact_id,
status="queued",
max_attempts=max_attempts,
Expand Down Expand Up @@ -108,13 +152,17 @@ def update_job(
# Consumer side (worker)


# Imports someone is watching a progress bar for: taken before the background work earlier imports queued.
FOREGROUND_KINDS = ("ingest", "import_url", "import_upload")


def claim_next(db: Session, worker_id: str) -> uuid.UUID | None:
"""Atomically take the oldest runnable job. SKIP LOCKED lets parallel workers pass each other."""
"""Atomically take the oldest runnable job, imports first. SKIP LOCKED lets parallel workers pass each other."""
now = utcnow()
job = db.scalar(
select(Job)
.where(Job.status == "queued", or_(Job.run_after.is_(None), Job.run_after <= now))
.order_by(Job.created_at)
.order_by(case((Job.kind.in_(FOREGROUND_KINDS), 0), else_=1), Job.created_at)
.limit(1)
.with_for_update(skip_locked=True)
)
Expand Down
13 changes: 9 additions & 4 deletions backend/app/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
from app.chat_memory.organize import forget_orphans, organize_chat, rebuild_chat
from app.config import settings
from app.db import SessionLocal, engine
from app.llm.languages import PARAM as APP_LANGUAGE_PARAM
from app.llm.languages import use_app_language
from app.models import (
Artifact,
Chat,
Expand Down Expand Up @@ -62,6 +64,7 @@
claim_next,
create_job,
pending_job,
queue_for_documents,
record_usage,
retry_or_fail,
stale_jobs,
Expand Down Expand Up @@ -94,10 +97,10 @@ def _after_import(db: Session, job: Job, workspace_id: uuid.UUID, changed: list[
first import builds the writing voice, so none of these need a button press."""
if not changed or not settings.llm_api_key:
return
create_job(db, workspace_id, "topics", {"document_ids": changed}, max_attempts=2)
create_job(db, workspace_id, "ideas", {"document_ids": changed}, max_attempts=2)
queue_for_documents(db, workspace_id, "topics", changed, max_attempts=2)
queue_for_documents(db, workspace_id, "ideas", changed, max_attempts=2)
if settings.post_cards_enabled:
create_job(db, workspace_id, "post_cards", {"document_ids": changed}, max_attempts=2)
queue_for_documents(db, workspace_id, "post_cards", changed, max_attempts=2)
if not pending_job(db, workspace_id, "resurface_scan"):
create_job(db, workspace_id, "resurface_scan", {}, max_attempts=2)
vp = db.scalar(select(VoiceProfile).where(VoiceProfile.workspace_id == workspace_id))
Expand Down Expand Up @@ -417,7 +420,9 @@ def run_job(
update_job(db, job, status="failed", error=f"No handler for job kind {job.kind!r}")
return
try:
outcome = handler(db, job)
# The app language of the request that queued the job, so its output and any job it starts follow it.
with use_app_language((job.params or {}).get(APP_LANGUAGE_PARAM)):
outcome = handler(db, job)
except PermanentJobError as exc:
db.rollback()
job = db.get(Job, job_id)
Expand Down
104 changes: 104 additions & 0 deletions backend/tests/test_app_language.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
"""The mobile app's interface language reaches AI output (app/llm/languages.py)."""

import uuid

import pytest
from fastapi import APIRouter
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool

import app.models # noqa: F401
from app.db import Base
from app.llm import languages
from app.models import Job, Workspace
from app.pipeline.research import with_reply_language
from app.services import jobs as q
from app.worker import Done, run_job


@pytest.fixture()
def factory():
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
Base.metadata.create_all(engine)
return sessionmaker(bind=engine, expire_on_commit=False)


@pytest.fixture()
def ws(factory):
with factory() as db:
w = Workspace(name="w", owner_id=uuid.uuid4())
db.add(w)
db.commit()
return w.id


def make(factory, ws, kind, params):
with factory() as db:
return q.create_job(db, ws, kind, params)


@pytest.mark.parametrize("value,code", [("es", "es"), ("es-MX", "es"), ("zh-Hans", "zh"), ("AR", "ar"),
("en", None), ("xx", None), ("", None), (None, None)])
def test_parse(value, code):
assert languages.parse(value) == code


def test_no_app_language_leaves_params_alone(factory, ws):
job = make(factory, ws, "quiz", {"topic": "t"})
assert job.params == {"topic": "t"}


def test_app_language_becomes_the_default_output_language(factory, ws):
with languages.use_app_language("fr"):
job = make(factory, ws, "quiz", {"topic": "t", "language": None})
assert job.params == {"topic": "t", "language": "French", "app_language": "fr"}


def test_explicit_language_wins(factory, ws):
with languages.use_app_language("fr"):
job = make(factory, ws, "slide_deck", {"language": "German"})
assert job.params["language"] == "German"


def test_kinds_without_a_language_only_carry_the_code(factory, ws):
with languages.use_app_language("ja"):
job = make(factory, ws, "ingest", {"source_id": "s"})
assert job.params == {"source_id": "s", "app_language": "ja"}


def test_worker_restores_the_language_for_the_job(factory, ws):
with languages.use_app_language("ko"):
jid = make(factory, ws, "compound_action", {}).id
seen = {}

def handler(db, job: Job):
seen["code"] = languages.app_language()
return Done()

run_job(jid, factory, {"compound_action": handler})
assert seen["code"] == "ko"
assert languages.app_language() is None


def test_chat_writer_notes_name_the_reply_language():
assert with_reply_language("tone: plain") == "tone: plain"
with languages.use_app_language("ur"):
notes = with_reply_language("tone: plain")
assert notes.startswith("tone: plain\nReply language: write the answer in Urdu")
with languages.use_app_language("ur"):
assert with_reply_language(None).startswith("Reply language:")


def test_header_sets_the_language_for_the_request(client):
from app.main import app

router = APIRouter()

@router.get("/__test/app-language")
def probe(): # a sync route runs in the threadpool, as most routes here do
return {"code": languages.app_language()}

app.include_router(router)
assert client.get("/__test/app-language", headers={"X-App-Language": "pt-BR"}).json() == {"code": "pt"}
assert client.get("/__test/app-language").json() == {"code": None}
Loading
Loading