Skip to content
Draft
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
6 changes: 5 additions & 1 deletion backend/app/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,9 @@
from app.api.chat import router as chat_router
from app.api.auth import router as auth_router
from app.api.retrieve import router as retrieve_router
from app.api.conversations import router as conversations_router

__all__ = ["health_router", "upload_router", "documents_router", "chat_router", "auth_router", "retrieve_router"]
__all__ = [
"health_router", "upload_router", "documents_router", "chat_router",
"auth_router", "retrieve_router", "conversations_router",
]
310 changes: 261 additions & 49 deletions backend/app/api/chat.py

Large diffs are not rendered by default.

158 changes: 158 additions & 0 deletions backend/app/api/conversations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
"""
Conversation CRUD.

Thin by design: every handler validates, calls one service function, and turns a
`None` or `False` result into 404.

On 404 vs 403 — a conversation that belongs to another user answers exactly like
one that does not exist. Returning 403 would confirm that the id is real and
someone else's, which is a membership oracle: an attacker could enumerate valid
conversation ids without ever reading one. The service layer makes this the
default by folding `user_id` into every WHERE clause, so a handler cannot forget.
"""

from __future__ import annotations

import logging

from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.dependencies import get_current_user, get_db
from app.database.models import User
from app.schemas.conversation import (
ConversationCreate,
ConversationDetailOut,
ConversationImportRequest,
ConversationImportResult,
ConversationOut,
ConversationPage,
ConversationPatch,
MessageFeedbackPatch,
MessageOut,
)
from app.services import conversation_service

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/conversations", tags=["Conversations"])

_NOT_FOUND = "Conversation not found."


@router.get("", response_model=ConversationPage)
async def list_conversations(
limit: int = Query(default=30, ge=1, le=100),
offset: int = Query(default=0, ge=0),
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""One page of the signed-in user's conversations, pinned first."""
items, total = await conversation_service.list_conversations(
db, current_user.id, limit=limit, offset=offset
)
return ConversationPage(
items=[ConversationOut.model_validate(c) for c in items],
total=total,
limit=limit,
offset=offset,
has_more=offset + len(items) < total,
)


@router.post("/import", response_model=ConversationImportResult)
async def import_conversations(
payload: ConversationImportRequest,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""
One-time migration of chats that were saved in the browser's localStorage.

Declared before `/{conversation_id}` so the literal path wins the match. The
200-conversation cap lives in the request schema, which means an oversized
body is rejected by validation before any database work starts.

Deliberately not idempotent: the client deletes its legacy key only after a
2xx, and calling this twice with the same payload duplicates the threads.
"""
imported, skipped = await conversation_service.import_conversations(
db, current_user.id, payload.conversations
)
return ConversationImportResult(imported=imported, skipped=skipped)


@router.post("", response_model=ConversationOut, status_code=status.HTTP_201_CREATED)
async def create_conversation(
payload: ConversationCreate,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
conversation = await conversation_service.create_conversation(
db, current_user.id, title=payload.title, mode=payload.mode
)
return ConversationOut.model_validate(conversation)


@router.get("/{conversation_id}", response_model=ConversationDetailOut)
async def get_conversation(
conversation_id: str,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""The conversation and every message in it, oldest first."""
conversation = await conversation_service.get_conversation_with_messages(
db, current_user.id, conversation_id
)
if conversation is None:
raise HTTPException(status_code=404, detail=_NOT_FOUND)
return ConversationDetailOut.model_validate(conversation)


@router.patch("/{conversation_id}", response_model=ConversationOut)
async def patch_conversation(
conversation_id: str,
payload: ConversationPatch,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""Rename, pin/unpin, or switch mode. Unset fields are left alone."""
conversation = await conversation_service.update_conversation(
db, current_user.id, conversation_id, payload
)
if conversation is None:
raise HTTPException(status_code=404, detail=_NOT_FOUND)
return ConversationOut.model_validate(conversation)


@router.delete("/{conversation_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_conversation(
conversation_id: str,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""Delete a conversation and its messages (ON DELETE CASCADE)."""
deleted = await conversation_service.delete_conversation(
db, current_user.id, conversation_id
)
if not deleted:
raise HTTPException(status_code=404, detail=_NOT_FOUND)
return Response(status_code=status.HTTP_204_NO_CONTENT)


@router.patch(
"/{conversation_id}/messages/{message_id}/feedback", response_model=MessageOut
)
async def patch_message_feedback(
conversation_id: str,
message_id: str,
payload: MessageFeedbackPatch,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""Set or clear the thumb on one message. `{"feedback": null}` clears it."""
message = await conversation_service.set_message_feedback(
db, current_user.id, conversation_id, message_id, payload.feedback
)
if message is None:
raise HTTPException(status_code=404, detail="Message not found.")
return MessageOut.model_validate(message)
18 changes: 18 additions & 0 deletions backend/app/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,24 @@ def async_database_url(self) -> str:
llm_api_key: str = ""
ollama_base_url: str = "http://localhost:11434"

# Conversation memory (Phase 8)
# How many prior turns (one turn = a user message and the assistant reply to it)
# are replayed to the provider. Older turns are dropped first.
chat_history_turns: int = 6
# History gets its own budget, deliberately separate from llm_max_context_tokens.
# Sharing one budget would let a long conversation crowd out retrieved passages,
# which is the opposite of what a document assistant should do under pressure.
chat_history_max_tokens: int = 1000
# Query condensing: rewrite an elliptical follow-up into a standalone search query.
chat_query_rewrite: bool = True
chat_query_rewrite_max_tokens: int = 80
# Kept well under llm_timeout -- condensing sits in front of retrieval, so its
# timeout is added to every follow-up's time-to-first-token. On expiry the raw
# message is used instead, which is a worse query but not a failed request.
chat_query_rewrite_timeout: float = 6.0
# Upper bound on the one-time localStorage import. Mirrored in the request schema.
chat_import_max_conversations: int = 200

# Authentication. Set a strong value in Railway/Vercel environments.
auth_secret: str = DEV_AUTH_SECRET
auth_cookie_name: str = "docuquery_session"
Expand Down
84 changes: 83 additions & 1 deletion backend/app/database/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
from datetime import datetime, timezone
from typing import TYPE_CHECKING

from sqlalchemy import String, Integer, DateTime, Text, Enum as SAEnum, ForeignKey, JSON
from sqlalchemy import (
Boolean, String, Integer, DateTime, Text, Enum as SAEnum, ForeignKey, Index, JSON, text,
)
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column, relationship
from pgvector.sqlalchemy import Vector

Expand All @@ -23,6 +26,10 @@ class User(Base):
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False
)

conversations: Mapped[list["Conversation"]] = relationship(
"Conversation", back_populates="user", cascade="all, delete-orphan"
)


class ProcessingStatus(str, enum.Enum):
uploaded = "uploaded"
Expand All @@ -31,6 +38,81 @@ class ProcessingStatus(str, enum.Enum):
failed = "failed"


def _now() -> datetime:
return datetime.now(timezone.utc)


class Conversation(Base):
"""A saved chat thread. Owned by exactly one user; deleting the user removes it."""

__tablename__ = "conversations"
__table_args__ = (
# The sidebar query is "this user's threads, most recently touched first".
# A composite index with updated_at descending serves it without a sort.
Index("ix_conversations_user_id_updated_at", "user_id", text("updated_at DESC")),
)

id: Mapped[str] = mapped_column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
user_id: Mapped[str] = mapped_column(
String, ForeignKey("users.id", ondelete="CASCADE"), nullable=False
)
title: Mapped[str] = mapped_column(String(200), nullable=False, default="New Chat")
mode: Mapped[str] = mapped_column(String(16), nullable=False, default="docuquery")
pinned: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, default=_now
)
# Bumped explicitly whenever a message is appended -- `onupdate` only fires when
# some column of this row is itself written, and appending a message does not.
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, default=_now, onupdate=_now
)

user: Mapped["User"] = relationship("User", back_populates="conversations")
messages: Mapped[list["Message"]] = relationship(
"Message",
back_populates="conversation",
cascade="all, delete-orphan",
order_by="Message.created_at",
)


class Message(Base):
"""
One turn in a conversation.

`status` records how the row came to exist, which matters because an assistant
message is written by a background stream that the client can abandon:

complete the stream finished and the whole answer is here
partial the client disconnected mid-stream; `content` is what was generated
error generation failed; `content` holds whatever preceded the failure
"""

__tablename__ = "messages"
__table_args__ = (
Index("ix_messages_conversation_id_created_at", "conversation_id", "created_at"),
)

id: Mapped[str] = mapped_column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
conversation_id: Mapped[str] = mapped_column(
String, ForeignKey("conversations.id", ondelete="CASCADE"), nullable=False
)
role: Mapped[str] = mapped_column(String(16), nullable=False)
content: Mapped[str] = mapped_column(Text, nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False, default="complete")
mode: Mapped[str | None] = mapped_column(String(16), nullable=True)
model: Mapped[str | None] = mapped_column(String(120), nullable=True)
citations: Mapped[list | None] = mapped_column(JSONB, nullable=True)
steps: Mapped[list | None] = mapped_column(JSONB, nullable=True)
feedback: Mapped[str | None] = mapped_column(String(8), nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, default=_now
)

conversation: Mapped["Conversation"] = relationship("Conversation", back_populates="messages")


class Document(Base):
__tablename__ = "documents"

Expand Down
Loading
Loading