Spaces:
Running
Running
Merge branch 'dev' into admin-metrics
Browse files- .env.example +18 -0
- CODE_OF_CONDUCT.md +85 -0
- SECURITY.md +26 -0
- backend/app/auth.py +28 -1
- backend/app/config.py +6 -0
- backend/app/database.py +31 -2
- backend/app/models.py +16 -0
- backend/app/rag/agent.py +17 -0
- backend/app/rag/embeddings.py +19 -2
- backend/app/rag/retriever.py +12 -0
- backend/app/rag/tracing.py +102 -0
- backend/app/routes/auth.py +39 -1
- backend/app/schemas.py +23 -0
- backend/requirements.txt +1 -0
- bots/discord/README.md +37 -0
- bots/discord/bot.py +68 -0
- bots/discord/requirements.txt +2 -0
- frontend/package-lock.json +11 -0
- frontend/package.json +1 -0
- frontend/src/app/globals.css +29 -0
- frontend/src/app/layout.tsx +15 -7
- frontend/src/components/auth/ApiKeyManager.tsx +158 -0
- frontend/src/components/chat/SourceCard.tsx +114 -71
- frontend/src/components/layout/Header.tsx +32 -26
- frontend/src/components/layout/ThemeProvider.tsx +8 -0
- frontend/src/components/layout/ThemeToggle.tsx +31 -0
.env.example
CHANGED
|
@@ -91,6 +91,24 @@ HF_TOKEN=your_huggingface_token_here
|
|
| 91 |
# Optional — defaults to 1024
|
| 92 |
# LLM_MAX_NEW_TOKENS=1024
|
| 93 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
# ── Embeddings (Optional — defaults shown)──────────────────────────────────────────────
|
| 95 |
|
| 96 |
# SentenceTransformer model ID for generating document embeddings.
|
|
|
|
| 91 |
# Optional — defaults to 1024
|
| 92 |
# LLM_MAX_NEW_TOKENS=1024
|
| 93 |
|
| 94 |
+
# ── LangSmith Tracing (Optional) ────────────────────────
|
| 95 |
+
|
| 96 |
+
# Enable LangSmith tracing for the backend RAG pipeline.
|
| 97 |
+
# Optional — defaults to False
|
| 98 |
+
# LANGSMITH_TRACING=False
|
| 99 |
+
|
| 100 |
+
# LangSmith API key.
|
| 101 |
+
# Optional — only needed when LANGSMITH_TRACING=True
|
| 102 |
+
# LANGSMITH_API_KEY=
|
| 103 |
+
|
| 104 |
+
# LangSmith API endpoint.
|
| 105 |
+
# Optional — defaults to "https://api.smith.langchain.com"
|
| 106 |
+
# LANGSMITH_ENDPOINT=https://api.smith.langchain.com
|
| 107 |
+
|
| 108 |
+
# LangSmith project name used for traced runs.
|
| 109 |
+
# Optional — defaults to "pdf-assistant-rag"
|
| 110 |
+
# LANGSMITH_PROJECT=pdf-assistant-rag
|
| 111 |
+
|
| 112 |
# ── Embeddings (Optional — defaults shown)──────────────────────────────────────────────
|
| 113 |
|
| 114 |
# SentenceTransformer model ID for generating document embeddings.
|
CODE_OF_CONDUCT.md
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Contributor Covenant Code of Conduct
|
| 2 |
+
|
| 3 |
+
## Our Pledge
|
| 4 |
+
|
| 5 |
+
We as members, contributors, and leaders pledge to make participation in our
|
| 6 |
+
community a harassment-free experience for everyone, regardless of age, body
|
| 7 |
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
| 8 |
+
identity and expression, level of experience, education, socio-economic status,
|
| 9 |
+
nationality, personal appearance, race, religion, or sexual identity
|
| 10 |
+
and orientation.
|
| 11 |
+
|
| 12 |
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
| 13 |
+
diverse, inclusive, and healthy community.
|
| 14 |
+
|
| 15 |
+
## Our Standards
|
| 16 |
+
|
| 17 |
+
Examples of behavior that contributes to a positive environment for our
|
| 18 |
+
community include:
|
| 19 |
+
|
| 20 |
+
* Demonstrating empathy and kindness toward other people
|
| 21 |
+
* Being respectful of differing opinions, viewpoints, and experiences
|
| 22 |
+
* Giving and gracefully accepting constructive feedback
|
| 23 |
+
* Accepting responsibility and apologizing to those affected by our mistakes,
|
| 24 |
+
and learning from the experience
|
| 25 |
+
* Focusing on what is best not just for us as individuals, but for the
|
| 26 |
+
overall community
|
| 27 |
+
|
| 28 |
+
Examples of unacceptable behavior include:
|
| 29 |
+
|
| 30 |
+
* The use of sexualized language or imagery, and sexual attention or
|
| 31 |
+
advances of any kind
|
| 32 |
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
| 33 |
+
* Public or private harassment
|
| 34 |
+
* Publishing others' private information, such as a physical or email
|
| 35 |
+
address, without their explicit permission
|
| 36 |
+
* Other conduct which could reasonably be considered inappropriate in a
|
| 37 |
+
professional setting
|
| 38 |
+
|
| 39 |
+
## Enforcement Responsibilities
|
| 40 |
+
|
| 41 |
+
Community leaders are responsible for clarifying and enforcing our standards of
|
| 42 |
+
acceptable behavior and will take appropriate and fair corrective action in
|
| 43 |
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
| 44 |
+
or harmful.
|
| 45 |
+
|
| 46 |
+
Community leaders have the right and responsibility to remove, edit, or reject
|
| 47 |
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
| 48 |
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
| 49 |
+
decisions when appropriate.
|
| 50 |
+
|
| 51 |
+
## Scope
|
| 52 |
+
|
| 53 |
+
This Code of Conduct applies within all community spaces, and also applies when
|
| 54 |
+
an individual is officially representing the community in public spaces.
|
| 55 |
+
Examples of representing our community include using an official e-mail address,
|
| 56 |
+
posting via an official social media account, or acting as an appointed
|
| 57 |
+
representative at an online or offline event.
|
| 58 |
+
|
| 59 |
+
## Enforcement
|
| 60 |
+
|
| 61 |
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
| 62 |
+
reported to the community leaders responsible for enforcement.
|
| 63 |
+
All complaints will be reviewed and investigated promptly and fairly.
|
| 64 |
+
|
| 65 |
+
All community leaders are obligated to respect the privacy and security of the
|
| 66 |
+
reporter of any incident.
|
| 67 |
+
|
| 68 |
+
## Attribution
|
| 69 |
+
|
| 70 |
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
| 71 |
+
version 2.1, available at
|
| 72 |
+
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
| 73 |
+
|
| 74 |
+
Community Impact Guidelines were inspired by
|
| 75 |
+
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
| 76 |
+
|
| 77 |
+
For answers to common questions about this code of conduct, see the FAQ at
|
| 78 |
+
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available
|
| 79 |
+
at [https://www.contributor-covenant.org/translations][translations].
|
| 80 |
+
|
| 81 |
+
[homepage]: https://www.contributor-covenant.org
|
| 82 |
+
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
| 83 |
+
[Mozilla CoC]: https://github.com/mozilla/diversity
|
| 84 |
+
[FAQ]: https://www.contributor-covenant.org/faq
|
| 85 |
+
[translations]: https://www.contributor-covenant.org/translations
|
SECURITY.md
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Security Policy
|
| 2 |
+
|
| 3 |
+
## Supported Versions
|
| 4 |
+
|
| 5 |
+
Currently, the following branches and versions of PDF-Assistant-RAG are supported with security updates.
|
| 6 |
+
|
| 7 |
+
| Version | Supported |
|
| 8 |
+
| ------- | ------------------ |
|
| 9 |
+
| `dev` | :white_check_mark: |
|
| 10 |
+
| `main` | :white_check_mark: |
|
| 11 |
+
| < 1.0 | :x: |
|
| 12 |
+
|
| 13 |
+
## Reporting a Vulnerability
|
| 14 |
+
|
| 15 |
+
We take the security of our users and their data very seriously. If you discover a security vulnerability in this project, please **do not** report it by creating a public GitHub issue.
|
| 16 |
+
|
| 17 |
+
Instead, please privately report it by emailing the repository owner directly.
|
| 18 |
+
|
| 19 |
+
When reporting a vulnerability, please include:
|
| 20 |
+
* A detailed description of the vulnerability.
|
| 21 |
+
* The steps required to reproduce the vulnerability.
|
| 22 |
+
* Any potential impact or risk to users.
|
| 23 |
+
|
| 24 |
+
We will acknowledge your email within 48 hours and work with you to understand and resolve the issue. We aim to fix critical security issues as fast as possible and will credit you in the release notes if you wish.
|
| 25 |
+
|
| 26 |
+
Thank you for helping keep this project secure!
|
backend/app/auth.py
CHANGED
|
@@ -67,12 +67,39 @@ def decode_token(token: str, token_type: str = "access") -> Optional[str]:
|
|
| 67 |
|
| 68 |
# ── FastAPI Dependencies ─────────────────────────────
|
| 69 |
|
|
|
|
|
|
|
| 70 |
def get_current_user(
|
| 71 |
credentials: HTTPAuthorizationCredentials = Depends(security),
|
| 72 |
db: Session = Depends(get_db),
|
| 73 |
) -> User:
|
| 74 |
-
"""Dependency: extract and validate user from JWT bearer token."""
|
| 75 |
token = credentials.credentials
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
user_id = decode_token(token)
|
| 77 |
|
| 78 |
if not user_id:
|
|
|
|
| 67 |
|
| 68 |
# ── FastAPI Dependencies ─────────────────────────────
|
| 69 |
|
| 70 |
+
import hashlib
|
| 71 |
+
|
| 72 |
def get_current_user(
|
| 73 |
credentials: HTTPAuthorizationCredentials = Depends(security),
|
| 74 |
db: Session = Depends(get_db),
|
| 75 |
) -> User:
|
| 76 |
+
"""Dependency: extract and validate user from JWT bearer token or API key."""
|
| 77 |
token = credentials.credentials
|
| 78 |
+
|
| 79 |
+
# Check if token is an API key
|
| 80 |
+
if token.startswith("rag_"):
|
| 81 |
+
hashed = hashlib.sha256(token.encode("utf-8")).hexdigest()
|
| 82 |
+
from app.models import ApiKey
|
| 83 |
+
api_key = db.query(ApiKey).filter(ApiKey.hashed_key == hashed).first()
|
| 84 |
+
if not api_key:
|
| 85 |
+
raise HTTPException(
|
| 86 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 87 |
+
detail="Invalid API key",
|
| 88 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
api_key.last_used = datetime.now(timezone.utc)
|
| 92 |
+
db.commit()
|
| 93 |
+
|
| 94 |
+
user = api_key.user
|
| 95 |
+
if not user:
|
| 96 |
+
raise HTTPException(
|
| 97 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 98 |
+
detail="User not found for this API key",
|
| 99 |
+
)
|
| 100 |
+
return user
|
| 101 |
+
|
| 102 |
+
# Otherwise, process as JWT
|
| 103 |
user_id = decode_token(token)
|
| 104 |
|
| 105 |
if not user_id:
|
backend/app/config.py
CHANGED
|
@@ -56,6 +56,12 @@ class Settings(BaseSettings):
|
|
| 56 |
LLM_TEMPERATURE: float = 0.3
|
| 57 |
SUMMARY_MAX_TOKENS: int = 512
|
| 58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
# ── Reranker ─────────────────────────────────────────
|
| 60 |
RERANKER_MODEL: str = "cross-encoder/ms-marco-MiniLM-L-6-v2"
|
| 61 |
# ── Vision / Image captioning ─────────────────────
|
|
|
|
| 56 |
LLM_TEMPERATURE: float = 0.3
|
| 57 |
SUMMARY_MAX_TOKENS: int = 512
|
| 58 |
|
| 59 |
+
# ── LangSmith Tracing (optional) ─────────────────────
|
| 60 |
+
LANGSMITH_TRACING: bool = False
|
| 61 |
+
LANGSMITH_API_KEY: str = ""
|
| 62 |
+
LANGSMITH_ENDPOINT: str = "https://api.smith.langchain.com"
|
| 63 |
+
LANGSMITH_PROJECT: str = "pdf-assistant-rag"
|
| 64 |
+
|
| 65 |
# ── Reranker ─────────────────────────────────────────
|
| 66 |
RERANKER_MODEL: str = "cross-encoder/ms-marco-MiniLM-L-6-v2"
|
| 67 |
# ── Vision / Image captioning ─────────────────────
|
backend/app/database.py
CHANGED
|
@@ -3,11 +3,13 @@ SQLAlchemy database setup with SQLite.
|
|
| 3 |
Uses synchronous SQLAlchemy for simplicity and compatibility.
|
| 4 |
"""
|
| 5 |
import os
|
| 6 |
-
|
|
|
|
| 7 |
from sqlalchemy.orm import sessionmaker, declarative_base
|
| 8 |
from app.config import get_settings
|
| 9 |
|
| 10 |
settings = get_settings()
|
|
|
|
| 11 |
|
| 12 |
# ── Ensure data directory exists ─────────────────────
|
| 13 |
db_path = settings.DATABASE_URL.replace("sqlite:///", "")
|
|
@@ -34,7 +36,34 @@ def get_db():
|
|
| 34 |
db.close()
|
| 35 |
|
| 36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
def init_db():
|
| 38 |
-
"""Create all tables on startup."""
|
| 39 |
from app import models # noqa: F401 — import to register models
|
| 40 |
Base.metadata.create_all(bind=engine)
|
|
|
|
|
|
| 3 |
Uses synchronous SQLAlchemy for simplicity and compatibility.
|
| 4 |
"""
|
| 5 |
import os
|
| 6 |
+
import logging
|
| 7 |
+
from sqlalchemy import create_engine, inspect, text
|
| 8 |
from sqlalchemy.orm import sessionmaker, declarative_base
|
| 9 |
from app.config import get_settings
|
| 10 |
|
| 11 |
settings = get_settings()
|
| 12 |
+
logger = logging.getLogger(__name__)
|
| 13 |
|
| 14 |
# ── Ensure data directory exists ─────────────────────
|
| 15 |
db_path = settings.DATABASE_URL.replace("sqlite:///", "")
|
|
|
|
| 36 |
db.close()
|
| 37 |
|
| 38 |
|
| 39 |
+
def _migrate_schema():
|
| 40 |
+
"""Apply schema migrations for existing databases (SQLite-compatible).
|
| 41 |
+
|
| 42 |
+
SQLAlchemy's ``create_all`` only creates new tables and does **not**
|
| 43 |
+
add missing columns to existing tables. This helper fills that gap
|
| 44 |
+
for non-destructive changes such as new nullable columns.
|
| 45 |
+
"""
|
| 46 |
+
inspector = inspect(engine)
|
| 47 |
+
existing_columns = {c["name"] for c in inspector.get_columns("users")}
|
| 48 |
+
|
| 49 |
+
migrations = [
|
| 50 |
+
("users", "hf_token", "ALTER TABLE users ADD COLUMN hf_token VARCHAR(255)"),
|
| 51 |
+
]
|
| 52 |
+
|
| 53 |
+
for table, column, ddl in migrations:
|
| 54 |
+
if column not in existing_columns:
|
| 55 |
+
try:
|
| 56 |
+
with engine.begin() as conn:
|
| 57 |
+
conn.execute(text(ddl))
|
| 58 |
+
logger.info("Migration: added column %s.%s", table, column)
|
| 59 |
+
except Exception:
|
| 60 |
+
logger.warning(
|
| 61 |
+
"Migration skipped (may already exist): %s.%s", table, column
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
def init_db():
|
| 66 |
+
"""Create all tables on startup and apply schema migrations."""
|
| 67 |
from app import models # noqa: F401 — import to register models
|
| 68 |
Base.metadata.create_all(bind=engine)
|
| 69 |
+
_migrate_schema()
|
backend/app/models.py
CHANGED
|
@@ -22,10 +22,26 @@ class User(Base):
|
|
| 22 |
is_admin = Column(Boolean, default=False)
|
| 23 |
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
| 24 |
last_login = Column(DateTime, nullable=True, index=True)
|
|
|
|
| 25 |
|
| 26 |
# Relationships
|
| 27 |
documents = relationship("Document", back_populates="owner", cascade="all, delete-orphan")
|
| 28 |
messages = relationship("ChatMessage", back_populates="user", cascade="all, delete-orphan")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
|
| 31 |
class Document(Base):
|
|
|
|
| 22 |
is_admin = Column(Boolean, default=False)
|
| 23 |
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
| 24 |
last_login = Column(DateTime, nullable=True, index=True)
|
| 25 |
+
hf_token = Column(String(255), nullable=True)
|
| 26 |
|
| 27 |
# Relationships
|
| 28 |
documents = relationship("Document", back_populates="owner", cascade="all, delete-orphan")
|
| 29 |
messages = relationship("ChatMessage", back_populates="user", cascade="all, delete-orphan")
|
| 30 |
+
api_keys = relationship("ApiKey", back_populates="user", cascade="all, delete-orphan")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class ApiKey(Base):
|
| 34 |
+
__tablename__ = "api_keys"
|
| 35 |
+
|
| 36 |
+
id = Column(String, primary_key=True, default=generate_uuid)
|
| 37 |
+
user_id = Column(String, ForeignKey("users.id"), nullable=False, index=True)
|
| 38 |
+
key_prefix = Column(String(10), nullable=False)
|
| 39 |
+
hashed_key = Column(String(255), nullable=False, unique=True, index=True)
|
| 40 |
+
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
| 41 |
+
last_used = Column(DateTime, nullable=True)
|
| 42 |
+
|
| 43 |
+
# Relationships
|
| 44 |
+
user = relationship("User", back_populates="api_keys")
|
| 45 |
|
| 46 |
|
| 47 |
class Document(Base):
|
backend/app/rag/agent.py
CHANGED
|
@@ -10,6 +10,7 @@ from huggingface_hub import InferenceClient
|
|
| 10 |
from app.config import get_settings
|
| 11 |
from app.rag.retriever import retrieve
|
| 12 |
from app.rag.prompts import SYSTEM_PROMPT, RAG_PROMPT_TEMPLATE, GREETING_PROMPT
|
|
|
|
| 13 |
|
| 14 |
logger = logging.getLogger(__name__)
|
| 15 |
settings = get_settings()
|
|
@@ -65,6 +66,14 @@ def _chat_messages(system: str, user_content: str) -> list:
|
|
| 65 |
]
|
| 66 |
|
| 67 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
def generate_answer(
|
| 69 |
question: str,
|
| 70 |
user_id: str,
|
|
@@ -145,6 +154,14 @@ def generate_answer(
|
|
| 145 |
return {"answer": answer, "sources": sources}
|
| 146 |
|
| 147 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
def generate_answer_stream(
|
| 149 |
question: str,
|
| 150 |
user_id: str,
|
|
|
|
| 10 |
from app.config import get_settings
|
| 11 |
from app.rag.retriever import retrieve
|
| 12 |
from app.rag.prompts import SYSTEM_PROMPT, RAG_PROMPT_TEMPLATE, GREETING_PROMPT
|
| 13 |
+
from app.rag.tracing import trace_function
|
| 14 |
|
| 15 |
logger = logging.getLogger(__name__)
|
| 16 |
settings = get_settings()
|
|
|
|
| 66 |
]
|
| 67 |
|
| 68 |
|
| 69 |
+
@trace_function(
|
| 70 |
+
"generate_answer",
|
| 71 |
+
metadata_factory=lambda question, user_id, document_id=None: {
|
| 72 |
+
"user_id": user_id,
|
| 73 |
+
"document_id": document_id,
|
| 74 |
+
"llm_model": settings.LLM_MODEL,
|
| 75 |
+
},
|
| 76 |
+
)
|
| 77 |
def generate_answer(
|
| 78 |
question: str,
|
| 79 |
user_id: str,
|
|
|
|
| 154 |
return {"answer": answer, "sources": sources}
|
| 155 |
|
| 156 |
|
| 157 |
+
@trace_function(
|
| 158 |
+
"generate_answer_stream",
|
| 159 |
+
metadata_factory=lambda question, user_id, document_id=None: {
|
| 160 |
+
"user_id": user_id,
|
| 161 |
+
"document_id": document_id,
|
| 162 |
+
"llm_model": settings.LLM_MODEL,
|
| 163 |
+
},
|
| 164 |
+
)
|
| 165 |
def generate_answer_stream(
|
| 166 |
question: str,
|
| 167 |
user_id: str,
|
backend/app/rag/embeddings.py
CHANGED
|
@@ -6,6 +6,7 @@ import logging
|
|
| 6 |
from typing import List
|
| 7 |
from langchain_huggingface import HuggingFaceEmbeddings
|
| 8 |
from app.config import get_settings
|
|
|
|
| 9 |
|
| 10 |
logger = logging.getLogger(__name__)
|
| 11 |
settings = get_settings()
|
|
@@ -36,10 +37,26 @@ def get_embedding_model() -> HuggingFaceEmbeddings:
|
|
| 36 |
def embed_texts(texts: List[str]) -> List[List[float]]:
|
| 37 |
"""Embed a batch of texts into vectors."""
|
| 38 |
model = get_embedding_model()
|
| 39 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
|
| 42 |
def embed_query(query: str) -> List[float]:
|
| 43 |
"""Embed a single query string."""
|
| 44 |
model = get_embedding_model()
|
| 45 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
from typing import List
|
| 7 |
from langchain_huggingface import HuggingFaceEmbeddings
|
| 8 |
from app.config import get_settings
|
| 9 |
+
from app.rag.tracing import trace_call
|
| 10 |
|
| 11 |
logger = logging.getLogger(__name__)
|
| 12 |
settings = get_settings()
|
|
|
|
| 37 |
def embed_texts(texts: List[str]) -> List[List[float]]:
|
| 38 |
"""Embed a batch of texts into vectors."""
|
| 39 |
model = get_embedding_model()
|
| 40 |
+
return trace_call(
|
| 41 |
+
"embed_texts",
|
| 42 |
+
lambda: model.embed_documents(texts),
|
| 43 |
+
run_type="embedding",
|
| 44 |
+
metadata={
|
| 45 |
+
"embedding_model": settings.EMBEDDING_MODEL,
|
| 46 |
+
"text_count": len(texts),
|
| 47 |
+
},
|
| 48 |
+
)
|
| 49 |
|
| 50 |
|
| 51 |
def embed_query(query: str) -> List[float]:
|
| 52 |
"""Embed a single query string."""
|
| 53 |
model = get_embedding_model()
|
| 54 |
+
return trace_call(
|
| 55 |
+
"embed_query",
|
| 56 |
+
lambda: model.embed_query(query),
|
| 57 |
+
run_type="embedding",
|
| 58 |
+
metadata={
|
| 59 |
+
"embedding_model": settings.EMBEDDING_MODEL,
|
| 60 |
+
"query_length": len(query),
|
| 61 |
+
},
|
| 62 |
+
)
|
backend/app/rag/retriever.py
CHANGED
|
@@ -5,6 +5,7 @@ import logging
|
|
| 5 |
from typing import List, Dict, Any, Optional
|
| 6 |
from app.config import get_settings
|
| 7 |
from app.rag.embeddings import embed_query
|
|
|
|
| 8 |
from app.rag.vectorstore import query_chunks
|
| 9 |
|
| 10 |
logger = logging.getLogger(__name__)
|
|
@@ -31,6 +32,17 @@ def get_reranker():
|
|
| 31 |
return _reranker if _reranker != "disabled" else None
|
| 32 |
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
def retrieve(
|
| 35 |
query: str,
|
| 36 |
user_id: str,
|
|
|
|
| 5 |
from typing import List, Dict, Any, Optional
|
| 6 |
from app.config import get_settings
|
| 7 |
from app.rag.embeddings import embed_query
|
| 8 |
+
from app.rag.tracing import trace_function
|
| 9 |
from app.rag.vectorstore import query_chunks
|
| 10 |
|
| 11 |
logger = logging.getLogger(__name__)
|
|
|
|
| 32 |
return _reranker if _reranker != "disabled" else None
|
| 33 |
|
| 34 |
|
| 35 |
+
@trace_function(
|
| 36 |
+
"retrieve",
|
| 37 |
+
metadata_factory=lambda query, user_id, document_id=None: {
|
| 38 |
+
"user_id": user_id,
|
| 39 |
+
"document_id": document_id,
|
| 40 |
+
"embedding_model": settings.EMBEDDING_MODEL,
|
| 41 |
+
"reranker_model": settings.RERANKER_MODEL,
|
| 42 |
+
"top_k_retrieval": settings.TOP_K_RETRIEVAL,
|
| 43 |
+
"top_k_rerank": settings.TOP_K_RERANK,
|
| 44 |
+
},
|
| 45 |
+
)
|
| 46 |
def retrieve(
|
| 47 |
query: str,
|
| 48 |
user_id: str,
|
backend/app/rag/tracing.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Optional LangSmith tracing helpers for the RAG pipeline.
|
| 3 |
+
Safe to import even when LangSmith is not installed or configured.
|
| 4 |
+
"""
|
| 5 |
+
import logging
|
| 6 |
+
import os
|
| 7 |
+
from functools import wraps
|
| 8 |
+
from typing import Any, Callable, Optional
|
| 9 |
+
|
| 10 |
+
from app.config import get_settings
|
| 11 |
+
|
| 12 |
+
logger = logging.getLogger(__name__)
|
| 13 |
+
settings = get_settings()
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
from langsmith import traceable as _langsmith_traceable
|
| 17 |
+
except Exception: # pragma: no cover - optional dependency safety
|
| 18 |
+
_langsmith_traceable = None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def configure_langsmith() -> bool:
|
| 22 |
+
"""Configure LangSmith environment variables when tracing is enabled."""
|
| 23 |
+
if not settings.LANGSMITH_TRACING:
|
| 24 |
+
return False
|
| 25 |
+
|
| 26 |
+
if not settings.LANGSMITH_API_KEY:
|
| 27 |
+
logger.warning("LangSmith tracing enabled but LANGSMITH_API_KEY is not set; tracing disabled.")
|
| 28 |
+
return False
|
| 29 |
+
|
| 30 |
+
os.environ["LANGSMITH_TRACING"] = "true"
|
| 31 |
+
os.environ["LANGSMITH_API_KEY"] = settings.LANGSMITH_API_KEY
|
| 32 |
+
os.environ["LANGSMITH_ENDPOINT"] = settings.LANGSMITH_ENDPOINT
|
| 33 |
+
os.environ["LANGSMITH_PROJECT"] = settings.LANGSMITH_PROJECT
|
| 34 |
+
return _langsmith_traceable is not None
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
LANGSMITH_ENABLED = configure_langsmith()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _sanitize_metadata(metadata: Optional[dict[str, Any]]) -> dict[str, Any]:
|
| 41 |
+
return {key: value for key, value in (metadata or {}).items() if value is not None}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _build_traceable(name: str, run_type: str, metadata: Optional[dict[str, Any]] = None):
|
| 45 |
+
"""Build a LangSmith traceable decorator safely across versions."""
|
| 46 |
+
if _langsmith_traceable is None:
|
| 47 |
+
return None
|
| 48 |
+
|
| 49 |
+
sanitized = _sanitize_metadata(metadata)
|
| 50 |
+
try:
|
| 51 |
+
return _langsmith_traceable(
|
| 52 |
+
name=name,
|
| 53 |
+
run_type=run_type,
|
| 54 |
+
metadata=sanitized or None,
|
| 55 |
+
)
|
| 56 |
+
except TypeError:
|
| 57 |
+
return _langsmith_traceable(name=name, run_type=run_type)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def trace_call(
|
| 61 |
+
name: str,
|
| 62 |
+
fn: Callable[..., Any],
|
| 63 |
+
*args: Any,
|
| 64 |
+
run_type: str = "chain",
|
| 65 |
+
metadata: Optional[dict[str, Any]] = None,
|
| 66 |
+
**kwargs: Any,
|
| 67 |
+
) -> Any:
|
| 68 |
+
"""Execute a callable with LangSmith tracing when available."""
|
| 69 |
+
if not LANGSMITH_ENABLED:
|
| 70 |
+
return fn(*args, **kwargs)
|
| 71 |
+
|
| 72 |
+
decorator = _build_traceable(name, run_type, metadata)
|
| 73 |
+
if decorator is None:
|
| 74 |
+
return fn(*args, **kwargs)
|
| 75 |
+
|
| 76 |
+
traced_fn = decorator(fn)
|
| 77 |
+
return traced_fn(*args, **kwargs)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def trace_function(
|
| 81 |
+
name: str,
|
| 82 |
+
*,
|
| 83 |
+
run_type: str = "chain",
|
| 84 |
+
metadata_factory: Optional[Callable[..., dict[str, Any]]] = None,
|
| 85 |
+
) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
|
| 86 |
+
"""Decorator wrapper that becomes a no-op when LangSmith is disabled."""
|
| 87 |
+
def decorator(fn: Callable[..., Any]) -> Callable[..., Any]:
|
| 88 |
+
@wraps(fn)
|
| 89 |
+
def wrapped(*args: Any, **kwargs: Any) -> Any:
|
| 90 |
+
metadata = metadata_factory(*args, **kwargs) if metadata_factory else None
|
| 91 |
+
return trace_call(
|
| 92 |
+
name,
|
| 93 |
+
fn,
|
| 94 |
+
*args,
|
| 95 |
+
run_type=run_type,
|
| 96 |
+
metadata=metadata,
|
| 97 |
+
**kwargs,
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
return wrapped
|
| 101 |
+
|
| 102 |
+
return decorator
|
backend/app/routes/auth.py
CHANGED
|
@@ -11,7 +11,7 @@ from sqlalchemy.orm import Session
|
|
| 11 |
from sqlalchemy import select
|
| 12 |
from app.config import get_settings
|
| 13 |
from app.database import get_db
|
| 14 |
-
from app.models import User
|
| 15 |
from app.schemas import (
|
| 16 |
GoogleLoginRequest,
|
| 17 |
RefreshRequest,
|
|
@@ -23,6 +23,8 @@ from app.schemas import (
|
|
| 23 |
UserResponse,
|
| 24 |
UserUpdate,
|
| 25 |
UserUpdateResponse,
|
|
|
|
|
|
|
| 26 |
)
|
| 27 |
from app.auth import hash_password, verify_password, create_access_token, create_refresh_token, get_current_user, decode_token
|
| 28 |
|
|
@@ -383,6 +385,42 @@ def update_password(payload:UpdatePassword,
|
|
| 383 |
db.rollback()
|
| 384 |
raise HTTPException(status_code=400, detail="Database error")
|
| 385 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 386 |
@router.get("/config")
|
| 387 |
def get_auth_config():
|
| 388 |
"""Return public configuration for auth providers"""
|
|
|
|
| 11 |
from sqlalchemy import select
|
| 12 |
from app.config import get_settings
|
| 13 |
from app.database import get_db
|
| 14 |
+
from app.models import User, ApiKey
|
| 15 |
from app.schemas import (
|
| 16 |
GoogleLoginRequest,
|
| 17 |
RefreshRequest,
|
|
|
|
| 23 |
UserResponse,
|
| 24 |
UserUpdate,
|
| 25 |
UserUpdateResponse,
|
| 26 |
+
ApiKeyResponse,
|
| 27 |
+
ApiKeyCreateResponse,
|
| 28 |
)
|
| 29 |
from app.auth import hash_password, verify_password, create_access_token, create_refresh_token, get_current_user, decode_token
|
| 30 |
|
|
|
|
| 385 |
db.rollback()
|
| 386 |
raise HTTPException(status_code=400, detail="Database error")
|
| 387 |
|
| 388 |
+
from typing import List
|
| 389 |
+
import hashlib
|
| 390 |
+
|
| 391 |
+
@router.post("/api-keys", response_model=ApiKeyCreateResponse, status_code=status.HTTP_201_CREATED)
|
| 392 |
+
def create_api_key(user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
| 393 |
+
"""Create a new API key for the authenticated user."""
|
| 394 |
+
raw_key = "rag_" + secrets.token_urlsafe(32)
|
| 395 |
+
hashed_key = hashlib.sha256(raw_key.encode("utf-8")).hexdigest()
|
| 396 |
+
|
| 397 |
+
api_key = ApiKey(
|
| 398 |
+
user_id=user.id,
|
| 399 |
+
key_prefix=raw_key[:10],
|
| 400 |
+
hashed_key=hashed_key,
|
| 401 |
+
)
|
| 402 |
+
db.add(api_key)
|
| 403 |
+
db.commit()
|
| 404 |
+
db.refresh(api_key)
|
| 405 |
+
|
| 406 |
+
return {"key": raw_key, "api_key": api_key}
|
| 407 |
+
|
| 408 |
+
@router.get("/api-keys", response_model=List[ApiKeyResponse])
|
| 409 |
+
def list_api_keys(user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
| 410 |
+
"""List all API keys for the authenticated user."""
|
| 411 |
+
return db.query(ApiKey).filter(ApiKey.user_id == user.id).all()
|
| 412 |
+
|
| 413 |
+
@router.delete("/api-keys/{key_id}", status_code=status.HTTP_204_NO_CONTENT)
|
| 414 |
+
def delete_api_key(key_id: str, user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
| 415 |
+
"""Revoke an API key."""
|
| 416 |
+
api_key = db.query(ApiKey).filter(ApiKey.id == key_id, ApiKey.user_id == user.id).first()
|
| 417 |
+
if not api_key:
|
| 418 |
+
raise HTTPException(status_code=404, detail="API key not found")
|
| 419 |
+
|
| 420 |
+
db.delete(api_key)
|
| 421 |
+
db.commit()
|
| 422 |
+
return None
|
| 423 |
+
|
| 424 |
@router.get("/config")
|
| 425 |
def get_auth_config():
|
| 426 |
"""Return public configuration for auth providers"""
|
backend/app/schemas.py
CHANGED
|
@@ -53,11 +53,17 @@ class RefreshRequest(BaseModel):
|
|
| 53 |
refresh_token: str
|
| 54 |
|
| 55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
class UserResponse(BaseModel):
|
| 57 |
id: str
|
| 58 |
username: str
|
| 59 |
email: str
|
| 60 |
is_admin: bool
|
|
|
|
| 61 |
created_at: datetime
|
| 62 |
|
| 63 |
class Config:
|
|
@@ -154,5 +160,22 @@ class ChatHistoryResponse(BaseModel):
|
|
| 154 |
document_id: Optional[str] = None
|
| 155 |
|
| 156 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
# Rebuild models for forward references
|
| 158 |
TokenResponse.model_rebuild()
|
|
|
|
| 53 |
refresh_token: str
|
| 54 |
|
| 55 |
|
| 56 |
+
class HFTokenUpdate(BaseModel):
|
| 57 |
+
"""Request schema for updating the user's HuggingFace token."""
|
| 58 |
+
hf_token: str
|
| 59 |
+
|
| 60 |
+
|
| 61 |
class UserResponse(BaseModel):
|
| 62 |
id: str
|
| 63 |
username: str
|
| 64 |
email: str
|
| 65 |
is_admin: bool
|
| 66 |
+
hf_token: Optional[str] = None
|
| 67 |
created_at: datetime
|
| 68 |
|
| 69 |
class Config:
|
|
|
|
| 160 |
document_id: Optional[str] = None
|
| 161 |
|
| 162 |
|
| 163 |
+
# ── ApiKeys ─────────────────────────────────────────────
|
| 164 |
+
|
| 165 |
+
class ApiKeyResponse(BaseModel):
|
| 166 |
+
id: str
|
| 167 |
+
key_prefix: str
|
| 168 |
+
created_at: datetime
|
| 169 |
+
last_used: Optional[datetime] = None
|
| 170 |
+
|
| 171 |
+
class Config:
|
| 172 |
+
from_attributes = True
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
class ApiKeyCreateResponse(BaseModel):
|
| 176 |
+
key: str
|
| 177 |
+
api_key: ApiKeyResponse
|
| 178 |
+
|
| 179 |
+
|
| 180 |
# Rebuild models for forward references
|
| 181 |
TokenResponse.model_rebuild()
|
backend/requirements.txt
CHANGED
|
@@ -31,6 +31,7 @@ langchain
|
|
| 31 |
langchain-community
|
| 32 |
langchain-huggingface
|
| 33 |
langchain-text-splitters
|
|
|
|
| 34 |
|
| 35 |
# Embeddings & ML
|
| 36 |
sentence-transformers
|
|
|
|
| 31 |
langchain-community
|
| 32 |
langchain-huggingface
|
| 33 |
langchain-text-splitters
|
| 34 |
+
langsmith
|
| 35 |
|
| 36 |
# Embeddings & ML
|
| 37 |
sentence-transformers
|
bots/discord/README.md
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Discord RAG Bot
|
| 2 |
+
|
| 3 |
+
This bot connects to the PDF-Assistant-RAG backend to answer questions based on your uploaded documents, directly from Discord.
|
| 4 |
+
|
| 5 |
+
## Setup
|
| 6 |
+
|
| 7 |
+
1. Install dependencies:
|
| 8 |
+
```bash
|
| 9 |
+
pip install -r requirements.txt
|
| 10 |
+
```
|
| 11 |
+
|
| 12 |
+
2. Create a Discord Bot on the [Discord Developer Portal](https://discord.com/developers/applications):
|
| 13 |
+
- Go to "Bot" tab and enable **Message Content Intent**.
|
| 14 |
+
- Copy the bot token.
|
| 15 |
+
- Invite the bot to your server via the OAuth2 URL Generator (check `bot` scope and `Send Messages` permission).
|
| 16 |
+
|
| 17 |
+
3. Generate an API Key from your PDF-Assistant-RAG profile dashboard.
|
| 18 |
+
|
| 19 |
+
4. Set the environment variables and run:
|
| 20 |
+
```bash
|
| 21 |
+
export DISCORD_TOKEN="your-discord-bot-token"
|
| 22 |
+
export RAG_API_KEY="rag_your-api-key"
|
| 23 |
+
|
| 24 |
+
# Optional: set API_URL if backend is not running on localhost:8000
|
| 25 |
+
# export API_URL="http://localhost:8000/api/v1"
|
| 26 |
+
|
| 27 |
+
python bot.py
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
## Usage
|
| 31 |
+
In a Discord channel where the bot is present, simply use the `!ask` command:
|
| 32 |
+
|
| 33 |
+
```
|
| 34 |
+
!ask Summarize the latest uploaded report for me
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
The bot will query the backend API using your personal API key and reply with the generated answer.
|
bots/discord/bot.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import discord
|
| 3 |
+
import requests
|
| 4 |
+
from discord.ext import commands
|
| 5 |
+
|
| 6 |
+
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
|
| 7 |
+
API_URL = os.getenv("API_URL", "http://localhost:8000/api/v1")
|
| 8 |
+
RAG_API_KEY = os.getenv("RAG_API_KEY")
|
| 9 |
+
|
| 10 |
+
if not DISCORD_TOKEN or not RAG_API_KEY:
|
| 11 |
+
print("Error: DISCORD_TOKEN and RAG_API_KEY must be set in environment variables.")
|
| 12 |
+
exit(1)
|
| 13 |
+
|
| 14 |
+
intents = discord.Intents.default()
|
| 15 |
+
intents.message_content = True
|
| 16 |
+
bot = commands.Bot(command_prefix="!", intents=intents)
|
| 17 |
+
|
| 18 |
+
@bot.event
|
| 19 |
+
async def on_ready():
|
| 20 |
+
print(f"Logged in as {bot.user.name} ({bot.user.id})")
|
| 21 |
+
print("Ready to answer questions via '!ask <question>'")
|
| 22 |
+
|
| 23 |
+
@bot.command(name="ask")
|
| 24 |
+
async def ask_rag(ctx, *, question: str):
|
| 25 |
+
"""Ask the RAG Assistant a question. Example: !ask What is in my documents?"""
|
| 26 |
+
loading_msg = await ctx.send("🤔 Thinking...")
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
headers = {
|
| 30 |
+
"Authorization": f"Bearer {RAG_API_KEY}",
|
| 31 |
+
"Content-Type": "application/json"
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
# We can also support document_id if we want, but for now we do global ask.
|
| 35 |
+
payload = {"question": question}
|
| 36 |
+
|
| 37 |
+
response = requests.post(
|
| 38 |
+
f"{API_URL}/chat/ask",
|
| 39 |
+
json=payload,
|
| 40 |
+
headers=headers,
|
| 41 |
+
timeout=30 # Give the RAG backend some time to process
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
if response.status_code == 200:
|
| 45 |
+
data = response.json()
|
| 46 |
+
answer = data.get("answer", "No answer provided.")
|
| 47 |
+
|
| 48 |
+
if len(answer) > 2000:
|
| 49 |
+
# Discord has a 2000 character limit per message
|
| 50 |
+
chunks = [answer[i:i+2000] for i in range(0, len(answer), 2000)]
|
| 51 |
+
await loading_msg.edit(content=chunks[0])
|
| 52 |
+
for chunk in chunks[1:]:
|
| 53 |
+
await ctx.send(chunk)
|
| 54 |
+
else:
|
| 55 |
+
await loading_msg.edit(content=answer)
|
| 56 |
+
else:
|
| 57 |
+
await loading_msg.edit(content=f"⚠️ Error from RAG API: `{response.status_code}`")
|
| 58 |
+
print(f"API Error: {response.text}")
|
| 59 |
+
|
| 60 |
+
except requests.exceptions.RequestException as e:
|
| 61 |
+
await loading_msg.edit(content=f"❌ Failed to connect to backend API.")
|
| 62 |
+
print(f"Request Error: {e}")
|
| 63 |
+
except Exception as e:
|
| 64 |
+
await loading_msg.edit(content=f"❌ An unexpected error occurred.")
|
| 65 |
+
print(f"Error: {e}")
|
| 66 |
+
|
| 67 |
+
if __name__ == "__main__":
|
| 68 |
+
bot.run(DISCORD_TOKEN)
|
bots/discord/requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
discord.py==2.3.2
|
| 2 |
+
requests==2.31.0
|
frontend/package-lock.json
CHANGED
|
@@ -13,6 +13,7 @@
|
|
| 13 |
"clsx": "^2.1.1",
|
| 14 |
"lucide-react": "^1.8.0",
|
| 15 |
"next": "16.2.4",
|
|
|
|
| 16 |
"pdfjs-dist": "^5.6.205",
|
| 17 |
"react": "19.2.4",
|
| 18 |
"react-dom": "19.2.4",
|
|
@@ -8691,6 +8692,16 @@
|
|
| 8691 |
}
|
| 8692 |
}
|
| 8693 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8694 |
"node_modules/next/node_modules/postcss": {
|
| 8695 |
"version": "8.4.31",
|
| 8696 |
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz",
|
|
|
|
| 13 |
"clsx": "^2.1.1",
|
| 14 |
"lucide-react": "^1.8.0",
|
| 15 |
"next": "16.2.4",
|
| 16 |
+
"next-themes": "^0.4.6",
|
| 17 |
"pdfjs-dist": "^5.6.205",
|
| 18 |
"react": "19.2.4",
|
| 19 |
"react-dom": "19.2.4",
|
|
|
|
| 8692 |
}
|
| 8693 |
}
|
| 8694 |
},
|
| 8695 |
+
"node_modules/next-themes": {
|
| 8696 |
+
"version": "0.4.6",
|
| 8697 |
+
"resolved": "https://registry.npmjs.org/next-themes/-/next-themes-0.4.6.tgz",
|
| 8698 |
+
"integrity": "sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA==",
|
| 8699 |
+
"license": "MIT",
|
| 8700 |
+
"peerDependencies": {
|
| 8701 |
+
"react": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc",
|
| 8702 |
+
"react-dom": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc"
|
| 8703 |
+
}
|
| 8704 |
+
},
|
| 8705 |
"node_modules/next/node_modules/postcss": {
|
| 8706 |
"version": "8.4.31",
|
| 8707 |
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz",
|
frontend/package.json
CHANGED
|
@@ -16,6 +16,7 @@
|
|
| 16 |
"clsx": "^2.1.1",
|
| 17 |
"lucide-react": "^1.8.0",
|
| 18 |
"next": "16.2.4",
|
|
|
|
| 19 |
"pdfjs-dist": "^5.6.205",
|
| 20 |
"react": "19.2.4",
|
| 21 |
"react-dom": "19.2.4",
|
|
|
|
| 16 |
"clsx": "^2.1.1",
|
| 17 |
"lucide-react": "^1.8.0",
|
| 18 |
"next": "16.2.4",
|
| 19 |
+
"next-themes": "^0.4.6",
|
| 20 |
"pdfjs-dist": "^5.6.205",
|
| 21 |
"react": "19.2.4",
|
| 22 |
"react-dom": "19.2.4",
|
frontend/src/app/globals.css
CHANGED
|
@@ -83,6 +83,35 @@
|
|
| 83 |
--sidebar-ring: oklch(0.65 0.2 265);
|
| 84 |
}
|
| 85 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
.light {
|
| 87 |
--background: oklch(0.985 0 0);
|
| 88 |
--foreground: oklch(0.145 0 0);
|
|
|
|
| 83 |
--sidebar-ring: oklch(0.65 0.2 265);
|
| 84 |
}
|
| 85 |
|
| 86 |
+
.dark {
|
| 87 |
+
--background: oklch(0.145 0 0);
|
| 88 |
+
--foreground: oklch(0.985 0 0);
|
| 89 |
+
--card: oklch(0.178 0 0);
|
| 90 |
+
--card-foreground: oklch(0.985 0 0);
|
| 91 |
+
--popover: oklch(0.178 0 0);
|
| 92 |
+
--popover-foreground: oklch(0.985 0 0);
|
| 93 |
+
--primary: oklch(0.65 0.2 265);
|
| 94 |
+
--primary-foreground: oklch(0.985 0 0);
|
| 95 |
+
--secondary: oklch(0.22 0 0);
|
| 96 |
+
--secondary-foreground: oklch(0.985 0 0);
|
| 97 |
+
--muted: oklch(0.22 0 0);
|
| 98 |
+
--muted-foreground: oklch(0.6 0 0);
|
| 99 |
+
--accent: oklch(0.55 0.18 265);
|
| 100 |
+
--accent-foreground: oklch(0.985 0 0);
|
| 101 |
+
--destructive: oklch(0.704 0.191 22.216);
|
| 102 |
+
--border: oklch(1 0 0 / 10%);
|
| 103 |
+
--input: oklch(1 0 0 / 12%);
|
| 104 |
+
--ring: oklch(0.65 0.2 265);
|
| 105 |
+
--sidebar: oklch(0.12 0 0);
|
| 106 |
+
--sidebar-foreground: oklch(0.985 0 0);
|
| 107 |
+
--sidebar-primary: oklch(0.65 0.2 265);
|
| 108 |
+
--sidebar-primary-foreground: oklch(0.985 0 0);
|
| 109 |
+
--sidebar-accent: oklch(0.22 0 0);
|
| 110 |
+
--sidebar-accent-foreground: oklch(0.985 0 0);
|
| 111 |
+
--sidebar-border: oklch(1 0 0 / 8%);
|
| 112 |
+
--sidebar-ring: oklch(0.65 0.2 265);
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
.light {
|
| 116 |
--background: oklch(0.985 0 0);
|
| 117 |
--foreground: oklch(0.145 0 0);
|
frontend/src/app/layout.tsx
CHANGED
|
@@ -3,6 +3,7 @@ import { Inter } from "next/font/google";
|
|
| 3 |
import "./globals.css";
|
| 4 |
import { AuthProvider } from "@/lib/auth";
|
| 5 |
import { TooltipProvider } from "@/components/ui/tooltip";
|
|
|
|
| 6 |
|
| 7 |
const inter = Inter({
|
| 8 |
variable: "--font-sans",
|
|
@@ -23,14 +24,21 @@ export default function RootLayout({
|
|
| 23 |
children: React.ReactNode;
|
| 24 |
}>) {
|
| 25 |
return (
|
| 26 |
-
<html lang="en" className={`${inter.variable}
|
| 27 |
<body className="min-h-full flex flex-col bg-background text-foreground">
|
| 28 |
-
<
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
</body>
|
| 34 |
</html>
|
| 35 |
);
|
| 36 |
-
}
|
|
|
|
| 3 |
import "./globals.css";
|
| 4 |
import { AuthProvider } from "@/lib/auth";
|
| 5 |
import { TooltipProvider } from "@/components/ui/tooltip";
|
| 6 |
+
import { ThemeProvider } from "@/components/layout/ThemeProvider";
|
| 7 |
|
| 8 |
const inter = Inter({
|
| 9 |
variable: "--font-sans",
|
|
|
|
| 24 |
children: React.ReactNode;
|
| 25 |
}>) {
|
| 26 |
return (
|
| 27 |
+
<html lang="en" className={`${inter.variable} h-full antialiased`} suppressHydrationWarning>
|
| 28 |
<body className="min-h-full flex flex-col bg-background text-foreground">
|
| 29 |
+
<ThemeProvider
|
| 30 |
+
attribute="class"
|
| 31 |
+
defaultTheme="dark"
|
| 32 |
+
enableSystem={false}
|
| 33 |
+
disableTransitionOnChange
|
| 34 |
+
>
|
| 35 |
+
<AuthProvider>
|
| 36 |
+
<TooltipProvider>
|
| 37 |
+
{children}
|
| 38 |
+
</TooltipProvider>
|
| 39 |
+
</AuthProvider>
|
| 40 |
+
</ThemeProvider>
|
| 41 |
</body>
|
| 42 |
</html>
|
| 43 |
);
|
| 44 |
+
}
|
frontend/src/components/auth/ApiKeyManager.tsx
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"use client";
|
| 2 |
+
|
| 3 |
+
import { useState, useEffect } from "react";
|
| 4 |
+
import { Button } from "@/components/ui/button";
|
| 5 |
+
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
|
| 6 |
+
import { api } from "@/lib/api";
|
| 7 |
+
import { Key, Plus, Trash2, Copy, Check } from "lucide-react";
|
| 8 |
+
|
| 9 |
+
interface ApiKey {
|
| 10 |
+
id: string;
|
| 11 |
+
key_prefix: string;
|
| 12 |
+
created_at: string;
|
| 13 |
+
last_used: string | null;
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
export default function ApiKeyManager() {
|
| 17 |
+
const [keys, setKeys] = useState<ApiKey[]>([]);
|
| 18 |
+
const [newKey, setNewKey] = useState<string | null>(null);
|
| 19 |
+
const [loading, setLoading] = useState(false);
|
| 20 |
+
const [copied, setCopied] = useState(false);
|
| 21 |
+
|
| 22 |
+
const fetchKeys = async () => {
|
| 23 |
+
try {
|
| 24 |
+
setLoading(true);
|
| 25 |
+
const data = await api.get<ApiKey[]>("/api/v1/auth/api-keys");
|
| 26 |
+
setKeys(data || []);
|
| 27 |
+
} catch (err) {
|
| 28 |
+
console.error("Failed to load API keys", err);
|
| 29 |
+
} finally {
|
| 30 |
+
setLoading(false);
|
| 31 |
+
}
|
| 32 |
+
};
|
| 33 |
+
|
| 34 |
+
useEffect(() => {
|
| 35 |
+
const timer = setTimeout(() => {
|
| 36 |
+
fetchKeys();
|
| 37 |
+
}, 0);
|
| 38 |
+
return () => clearTimeout(timer);
|
| 39 |
+
}, []);
|
| 40 |
+
|
| 41 |
+
const generateKey = async () => {
|
| 42 |
+
try {
|
| 43 |
+
setLoading(true);
|
| 44 |
+
const data = await api.post<{ key: string; api_key: ApiKey }>("/api/v1/auth/api-keys");
|
| 45 |
+
setNewKey(data.key);
|
| 46 |
+
setKeys((prev) => [...prev, data.api_key]);
|
| 47 |
+
} catch (err) {
|
| 48 |
+
console.error("Failed to generate API key", err);
|
| 49 |
+
} finally {
|
| 50 |
+
setLoading(false);
|
| 51 |
+
}
|
| 52 |
+
};
|
| 53 |
+
|
| 54 |
+
const revokeKey = async (id: string) => {
|
| 55 |
+
if (!confirm("Are you sure you want to revoke this key? Any integrations using it will immediately break.")) return;
|
| 56 |
+
|
| 57 |
+
try {
|
| 58 |
+
await api.delete(`/api/v1/auth/api-keys/${id}`);
|
| 59 |
+
setKeys((prev) => prev.filter((k) => k.id !== id));
|
| 60 |
+
} catch (err) {
|
| 61 |
+
console.error("Failed to revoke API key", err);
|
| 62 |
+
}
|
| 63 |
+
};
|
| 64 |
+
|
| 65 |
+
const copyToClipboard = () => {
|
| 66 |
+
if (newKey) {
|
| 67 |
+
navigator.clipboard.writeText(newKey);
|
| 68 |
+
setCopied(true);
|
| 69 |
+
setTimeout(() => setCopied(false), 2000);
|
| 70 |
+
}
|
| 71 |
+
};
|
| 72 |
+
|
| 73 |
+
return (
|
| 74 |
+
<Dialog onOpenChange={(open) => { if (!open) setNewKey(null); }}>
|
| 75 |
+
<DialogTrigger
|
| 76 |
+
render={
|
| 77 |
+
<button className="flex w-full cursor-pointer items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors hover:bg-accent hover:text-accent-foreground">
|
| 78 |
+
<Key className="mr-2 h-4 w-4" />
|
| 79 |
+
<span>API Keys</span>
|
| 80 |
+
</button>
|
| 81 |
+
}
|
| 82 |
+
/>
|
| 83 |
+
<DialogContent className="max-w-2xl sm:rounded-2xl border-border/40 p-6 md:p-8 bg-background/95 backdrop-blur-xl shadow-2xl">
|
| 84 |
+
|
| 85 |
+
<DialogHeader>
|
| 86 |
+
<DialogTitle className="text-2xl font-bold tracking-tight">API Keys</DialogTitle>
|
| 87 |
+
<p className="text-sm text-muted-foreground mt-1.5">
|
| 88 |
+
Manage API keys to access the RAG engine programmatically from your own applications or scripts.
|
| 89 |
+
</p>
|
| 90 |
+
</DialogHeader>
|
| 91 |
+
|
| 92 |
+
{newKey && (
|
| 93 |
+
<div className="my-6 p-5 border border-primary/20 bg-primary/5 rounded-xl space-y-3 animate-in fade-in zoom-in-95 duration-300">
|
| 94 |
+
<h4 className="font-semibold text-primary flex items-center gap-2">
|
| 95 |
+
<Key className="w-4 h-4" /> Save your new API key
|
| 96 |
+
</h4>
|
| 97 |
+
<p className="text-sm text-muted-foreground">
|
| 98 |
+
Please copy this key and store it somewhere safe. For security reasons, you will <strong>never</strong> be able to view it again.
|
| 99 |
+
</p>
|
| 100 |
+
<div className="flex items-center gap-2 mt-2">
|
| 101 |
+
<code className="flex-1 bg-background/80 border border-border/50 px-4 py-2.5 rounded-lg text-sm font-mono break-all text-foreground shadow-inner">
|
| 102 |
+
{newKey}
|
| 103 |
+
</code>
|
| 104 |
+
<Button onClick={copyToClipboard} variant={copied ? "default" : "secondary"} className="shrink-0 shadow-sm">
|
| 105 |
+
{copied ? <Check className="w-4 h-4 mr-2" /> : <Copy className="w-4 h-4 mr-2" />}
|
| 106 |
+
{copied ? "Copied!" : "Copy"}
|
| 107 |
+
</Button>
|
| 108 |
+
</div>
|
| 109 |
+
</div>
|
| 110 |
+
)}
|
| 111 |
+
|
| 112 |
+
<div className="space-y-4 mt-6">
|
| 113 |
+
<div className="flex items-center justify-between">
|
| 114 |
+
<h3 className="text-sm font-medium text-foreground/80 uppercase tracking-wider">Active Keys</h3>
|
| 115 |
+
<Button onClick={generateKey} disabled={loading} size="sm" className="rounded-full shadow-sm hover:shadow-md transition-shadow">
|
| 116 |
+
<Plus className="w-4 h-4 mr-1.5" />
|
| 117 |
+
Generate New Key
|
| 118 |
+
</Button>
|
| 119 |
+
</div>
|
| 120 |
+
|
| 121 |
+
<div className="rounded-xl border border-border/50 bg-card overflow-hidden shadow-sm">
|
| 122 |
+
{keys.length === 0 ? (
|
| 123 |
+
<div className="p-8 text-center text-sm text-muted-foreground bg-muted/20">
|
| 124 |
+
<Key className="w-8 h-8 mx-auto mb-3 opacity-20" />
|
| 125 |
+
You don't have any API keys yet.
|
| 126 |
+
</div>
|
| 127 |
+
) : (
|
| 128 |
+
<div className="divide-y divide-border/50">
|
| 129 |
+
{keys.map((key) => (
|
| 130 |
+
<div key={key.id} className="flex items-center justify-between p-4 hover:bg-muted/30 transition-colors group">
|
| 131 |
+
<div className="space-y-1">
|
| 132 |
+
<div className="font-mono text-sm font-medium tracking-tight">
|
| 133 |
+
{key.key_prefix}••••••••••••••••••••••
|
| 134 |
+
</div>
|
| 135 |
+
<div className="text-xs text-muted-foreground flex gap-4">
|
| 136 |
+
<span>Created: {new Date(key.created_at).toLocaleDateString()}</span>
|
| 137 |
+
<span>Last used: {key.last_used ? new Date(key.last_used).toLocaleDateString() : "Never"}</span>
|
| 138 |
+
</div>
|
| 139 |
+
</div>
|
| 140 |
+
<Button
|
| 141 |
+
variant="ghost"
|
| 142 |
+
size="icon"
|
| 143 |
+
onClick={() => revokeKey(key.id)}
|
| 144 |
+
className="text-destructive/70 hover:text-destructive hover:bg-destructive/10 opacity-0 group-hover:opacity-100 transition-all"
|
| 145 |
+
title="Revoke key"
|
| 146 |
+
>
|
| 147 |
+
<Trash2 className="w-4 h-4" />
|
| 148 |
+
</Button>
|
| 149 |
+
</div>
|
| 150 |
+
))}
|
| 151 |
+
</div>
|
| 152 |
+
)}
|
| 153 |
+
</div>
|
| 154 |
+
</div>
|
| 155 |
+
</DialogContent>
|
| 156 |
+
</Dialog>
|
| 157 |
+
);
|
| 158 |
+
}
|
frontend/src/components/chat/SourceCard.tsx
CHANGED
|
@@ -4,7 +4,14 @@ import { useState } from "react";
|
|
| 4 |
import type { SourceChunk } from "@/store/chat-store";
|
| 5 |
import { Badge } from "@/components/ui/badge";
|
| 6 |
import { Button } from "@/components/ui/button";
|
| 7 |
-
import {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
interface Props {
|
| 10 |
sources: SourceChunk[];
|
|
@@ -13,89 +20,125 @@ interface Props {
|
|
| 13 |
|
| 14 |
export default function SourceCard({ sources = [], onPageClick }: Props) {
|
| 15 |
const [expanded, setExpanded] = useState(false);
|
|
|
|
| 16 |
|
| 17 |
if (sources.length === 0) return null;
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
return (
|
| 20 |
<div className="rounded-lg border border-border/50 bg-card/50 overflow-hidden">
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
variant="secondary"
|
| 44 |
-
className="text-[10px] h-5 cursor-pointer hover:bg-primary/20 transition-colors"
|
| 45 |
-
onClick={() => onPageClick(src.page + 1)}
|
| 46 |
-
>
|
| 47 |
-
p.{src.page + 1} • {src.confidence}%
|
| 48 |
-
</Badge>
|
| 49 |
-
))}
|
| 50 |
-
</div>
|
| 51 |
-
)}
|
| 52 |
-
|
| 53 |
-
{/* ── Expanded: Full source cards ─────────────── */}
|
| 54 |
-
{expanded && (
|
| 55 |
-
<div className="border-t border-border/30">
|
| 56 |
-
{sources.map((src, i) => (
|
| 57 |
-
<div
|
| 58 |
-
key={i}
|
| 59 |
-
className="px-3 py-2.5 border-b border-border/20 last:border-b-0 hover:bg-accent/20 transition-colors"
|
| 60 |
-
>
|
| 61 |
-
<div className="flex items-center justify-between mb-1.5">
|
| 62 |
-
<div className="flex items-center gap-2">
|
| 63 |
-
<span className="text-[10px] font-medium text-muted-foreground">
|
| 64 |
-
{src.filename}
|
| 65 |
-
</span>
|
| 66 |
-
<Badge variant="outline" className="text-[9px] h-4 px-1.5">
|
| 67 |
-
Page {src.page + 1}
|
| 68 |
-
</Badge>
|
| 69 |
<Badge
|
| 70 |
variant="secondary"
|
| 71 |
-
className=
|
| 72 |
-
|
| 73 |
-
? "text-emerald-400 bg-emerald-400/10"
|
| 74 |
-
: src.confidence >= 50
|
| 75 |
-
? "text-yellow-400 bg-yellow-400/10"
|
| 76 |
-
: "text-muted-foreground"
|
| 77 |
-
}`}
|
| 78 |
>
|
| 79 |
-
{src.confidence}%
|
| 80 |
</Badge>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
</div>
|
| 82 |
-
<
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
onClick={() => onPageClick(src.page + 1)}
|
| 87 |
>
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
</div>
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
</div>
|
| 96 |
-
))}
|
| 97 |
-
</div>
|
| 98 |
-
)}
|
| 99 |
</div>
|
| 100 |
);
|
| 101 |
}
|
|
|
|
| 4 |
import type { SourceChunk } from "@/store/chat-store";
|
| 5 |
import { Badge } from "@/components/ui/badge";
|
| 6 |
import { Button } from "@/components/ui/button";
|
| 7 |
+
import {
|
| 8 |
+
Tooltip,
|
| 9 |
+
TooltipContent,
|
| 10 |
+
TooltipTrigger,
|
| 11 |
+
} from "@/components/ui/tooltip";
|
| 12 |
+
import { ChevronDown, ChevronUp, FileText, Eye, TextQuote } from "lucide-react";
|
| 13 |
+
|
| 14 |
+
const EXCERPT_THRESHOLD = 200;
|
| 15 |
|
| 16 |
interface Props {
|
| 17 |
sources: SourceChunk[];
|
|
|
|
| 20 |
|
| 21 |
export default function SourceCard({ sources = [], onPageClick }: Props) {
|
| 22 |
const [expanded, setExpanded] = useState(false);
|
| 23 |
+
const [excerptOpen, setExcerptOpen] = useState<Set<number>>(new Set());
|
| 24 |
|
| 25 |
if (sources.length === 0) return null;
|
| 26 |
|
| 27 |
+
const toggleExcerpt = (i: number) => {
|
| 28 |
+
const next = new Set(excerptOpen);
|
| 29 |
+
if (next.has(i)) {
|
| 30 |
+
next.delete(i);
|
| 31 |
+
} else {
|
| 32 |
+
next.add(i);
|
| 33 |
+
}
|
| 34 |
+
setExcerptOpen(next);
|
| 35 |
+
};
|
| 36 |
+
|
| 37 |
return (
|
| 38 |
<div className="rounded-lg border border-border/50 bg-card/50 overflow-hidden">
|
| 39 |
+
{/* ── Header ──────────────────────────────────── */}
|
| 40 |
+
<button
|
| 41 |
+
onClick={() => setExpanded(!expanded)}
|
| 42 |
+
className="w-full flex items-center justify-between px-3 py-2 text-xs hover:bg-accent/30 transition-colors"
|
| 43 |
+
>
|
| 44 |
+
<span className="flex items-center gap-1.5 text-muted-foreground">
|
| 45 |
+
<FileText className="w-3.5 h-3.5" />
|
| 46 |
+
{sources.length} source{sources.length > 1 ? "s" : ""} cited
|
| 47 |
+
</span>
|
| 48 |
+
{expanded ? (
|
| 49 |
+
<ChevronUp className="w-3.5 h-3.5 text-muted-foreground" />
|
| 50 |
+
) : (
|
| 51 |
+
<ChevronDown className="w-3.5 h-3.5 text-muted-foreground" />
|
| 52 |
+
)}
|
| 53 |
+
</button>
|
| 54 |
|
| 55 |
+
{/* ── Collapsed: Mini badges with hover preview ── */}
|
| 56 |
+
{!expanded && (
|
| 57 |
+
<div className="px-3 pb-2 flex flex-wrap gap-1">
|
| 58 |
+
{sources.map((src, i) => (
|
| 59 |
+
<Tooltip key={i}>
|
| 60 |
+
<TooltipTrigger className="inline-flex">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
<Badge
|
| 62 |
variant="secondary"
|
| 63 |
+
className="text-[10px] h-5 cursor-pointer hover:bg-primary/20 transition-colors"
|
| 64 |
+
onClick={() => onPageClick(src.page + 1)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
>
|
| 66 |
+
p.{src.page + 1} • {src.confidence}%
|
| 67 |
</Badge>
|
| 68 |
+
</TooltipTrigger>
|
| 69 |
+
<TooltipContent
|
| 70 |
+
side="top"
|
| 71 |
+
align="center"
|
| 72 |
+
className="max-w-xs p-2"
|
| 73 |
+
>
|
| 74 |
+
<p className="text-[11px] leading-relaxed line-clamp-6">
|
| 75 |
+
{src.text}
|
| 76 |
+
</p>
|
| 77 |
+
</TooltipContent>
|
| 78 |
+
</Tooltip>
|
| 79 |
+
))}
|
| 80 |
+
</div>
|
| 81 |
+
)}
|
| 82 |
+
|
| 83 |
+
{/* ── Expanded: Full source cards ─────────────── */}
|
| 84 |
+
{expanded && (
|
| 85 |
+
<div className="border-t border-border/30">
|
| 86 |
+
{sources.map((src, i) => (
|
| 87 |
+
<div
|
| 88 |
+
key={i}
|
| 89 |
+
className="px-3 py-2.5 border-b border-border/20 last:border-b-0 hover:bg-accent/20 transition-colors"
|
| 90 |
+
>
|
| 91 |
+
<div className="flex items-center justify-between mb-1.5">
|
| 92 |
+
<div className="flex items-center gap-2">
|
| 93 |
+
<span className="text-[10px] font-medium text-muted-foreground">
|
| 94 |
+
{src.filename}
|
| 95 |
+
</span>
|
| 96 |
+
<Badge variant="outline" className="text-[9px] h-4 px-1.5">
|
| 97 |
+
Page {src.page + 1}
|
| 98 |
+
</Badge>
|
| 99 |
+
<Badge
|
| 100 |
+
variant="secondary"
|
| 101 |
+
className={`text-[9px] h-4 px-1.5 ${
|
| 102 |
+
src.confidence >= 80
|
| 103 |
+
? "text-emerald-400 bg-emerald-400/10"
|
| 104 |
+
: src.confidence >= 50
|
| 105 |
+
? "text-yellow-400 bg-yellow-400/10"
|
| 106 |
+
: "text-muted-foreground"
|
| 107 |
+
}`}
|
| 108 |
+
>
|
| 109 |
+
{src.confidence}% match
|
| 110 |
+
</Badge>
|
| 111 |
+
</div>
|
| 112 |
+
<Button
|
| 113 |
+
variant="ghost"
|
| 114 |
+
size="sm"
|
| 115 |
+
className="h-6 px-2 text-[10px]"
|
| 116 |
+
onClick={() => onPageClick(src.page + 1)}
|
| 117 |
+
>
|
| 118 |
+
<Eye className="w-3 h-3 mr-1" />
|
| 119 |
+
View
|
| 120 |
+
</Button>
|
| 121 |
</div>
|
| 122 |
+
<p
|
| 123 |
+
className={`text-[11px] text-muted-foreground leading-relaxed ${
|
| 124 |
+
excerptOpen.has(i) ? "" : "line-clamp-3"
|
| 125 |
+
}`}
|
|
|
|
| 126 |
>
|
| 127 |
+
{src.text}
|
| 128 |
+
</p>
|
| 129 |
+
{src.text.length > EXCERPT_THRESHOLD && (
|
| 130 |
+
<button
|
| 131 |
+
onClick={() => toggleExcerpt(i)}
|
| 132 |
+
className="mt-1.5 flex items-center gap-1 text-[10px] text-primary/70 hover:text-primary transition-colors"
|
| 133 |
+
>
|
| 134 |
+
<TextQuote className="w-3 h-3" />
|
| 135 |
+
{excerptOpen.has(i) ? "Hide excerpt" : "Show excerpt"}
|
| 136 |
+
</button>
|
| 137 |
+
)}
|
| 138 |
</div>
|
| 139 |
+
))}
|
| 140 |
+
</div>
|
| 141 |
+
)}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
</div>
|
| 143 |
);
|
| 144 |
}
|
frontend/src/components/layout/Header.tsx
CHANGED
|
@@ -22,7 +22,10 @@ import {
|
|
| 22 |
Shield,
|
| 23 |
Sun,
|
| 24 |
} from "lucide-react";
|
| 25 |
-
import {
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
interface HeaderProps {
|
| 28 |
sidebarOpen: boolean;
|
|
@@ -31,22 +34,18 @@ interface HeaderProps {
|
|
| 31 |
onToggleViewer: () => void;
|
| 32 |
}
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
export default function Header({ sidebarOpen, onToggleSidebar, viewerOpen, onToggleViewer }: HeaderProps) {
|
| 35 |
const { user, logout } = useAuth();
|
| 36 |
const router = useRouter();
|
| 37 |
-
const
|
|
|
|
| 38 |
|
| 39 |
-
const
|
| 40 |
-
|
| 41 |
-
if (isDark) {
|
| 42 |
-
html.classList.remove("dark");
|
| 43 |
-
html.classList.add("light");
|
| 44 |
-
} else {
|
| 45 |
-
html.classList.remove("light");
|
| 46 |
-
html.classList.add("dark");
|
| 47 |
-
}
|
| 48 |
-
setIsDark(!isDark);
|
| 49 |
-
};
|
| 50 |
|
| 51 |
const handleLogout = () => {
|
| 52 |
logout();
|
|
@@ -75,20 +74,27 @@ export default function Header({ sidebarOpen, onToggleSidebar, viewerOpen, onTog
|
|
| 75 |
{viewerOpen ? <PanelRightClose className="w-4 h-4" /> : <PanelRightOpen className="w-4 h-4" />}
|
| 76 |
</Button>
|
| 77 |
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
| 81 |
|
| 82 |
<DropdownMenu>
|
| 83 |
-
<DropdownMenuTrigger
|
| 84 |
-
|
| 85 |
-
<
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
<div className="px-3 py-2">
|
| 93 |
<p className="text-sm font-medium">{user?.username}</p>
|
| 94 |
<p className="text-xs text-muted-foreground truncate">{user?.email}</p>
|
|
@@ -110,4 +116,4 @@ export default function Header({ sidebarOpen, onToggleSidebar, viewerOpen, onTog
|
|
| 110 |
</div>
|
| 111 |
</header>
|
| 112 |
);
|
| 113 |
-
}
|
|
|
|
| 22 |
Shield,
|
| 23 |
Sun,
|
| 24 |
} from "lucide-react";
|
| 25 |
+
import { useSyncExternalStore } from "react";
|
| 26 |
+
import { useTheme } from "next-themes";
|
| 27 |
+
import ApiKeyManager from "@/components/auth/ApiKeyManager";
|
| 28 |
+
|
| 29 |
|
| 30 |
interface HeaderProps {
|
| 31 |
sidebarOpen: boolean;
|
|
|
|
| 34 |
onToggleViewer: () => void;
|
| 35 |
}
|
| 36 |
|
| 37 |
+
const subscribe = () => () => {};
|
| 38 |
+
const getSnapshot = () => true;
|
| 39 |
+
const getServerSnapshot = () => false;
|
| 40 |
+
|
| 41 |
export default function Header({ sidebarOpen, onToggleSidebar, viewerOpen, onToggleViewer }: HeaderProps) {
|
| 42 |
const { user, logout } = useAuth();
|
| 43 |
const router = useRouter();
|
| 44 |
+
const { theme, setTheme } = useTheme();
|
| 45 |
+
const mounted = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); // ← replaces useState + useEffect
|
| 46 |
|
| 47 |
+
const isDark = theme === "dark";
|
| 48 |
+
const toggleTheme = () => setTheme(isDark ? "light" : "dark");
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
const handleLogout = () => {
|
| 51 |
logout();
|
|
|
|
| 74 |
{viewerOpen ? <PanelRightClose className="w-4 h-4" /> : <PanelRightOpen className="w-4 h-4" />}
|
| 75 |
</Button>
|
| 76 |
|
| 77 |
+
{mounted && (
|
| 78 |
+
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={toggleTheme} title={isDark ? "Light mode" : "Dark mode"}>
|
| 79 |
+
{isDark ? <Sun className="w-4 h-4" /> : <Moon className="w-4 h-4" />}
|
| 80 |
+
</Button>
|
| 81 |
+
)}
|
| 82 |
|
| 83 |
<DropdownMenu>
|
| 84 |
+
<DropdownMenuTrigger
|
| 85 |
+
render={
|
| 86 |
+
<button className="flex items-center h-8 gap-2 px-2 rounded-md hover:bg-accent transition-colors cursor-pointer">
|
| 87 |
+
<Avatar className="w-6 h-6">
|
| 88 |
+
<AvatarFallback className="text-[10px] bg-primary/20 text-primary">
|
| 89 |
+
{user?.username?.slice(0, 2).toUpperCase() || "U"}
|
| 90 |
+
</AvatarFallback>
|
| 91 |
+
</Avatar>
|
| 92 |
+
<span className="text-sm hidden sm:inline">{user?.username}</span>
|
| 93 |
+
</button>
|
| 94 |
+
}
|
| 95 |
+
/>
|
| 96 |
+
|
| 97 |
+
<DropdownMenuContent align="end" className="w-56">
|
| 98 |
<div className="px-3 py-2">
|
| 99 |
<p className="text-sm font-medium">{user?.username}</p>
|
| 100 |
<p className="text-xs text-muted-foreground truncate">{user?.email}</p>
|
|
|
|
| 116 |
</div>
|
| 117 |
</header>
|
| 118 |
);
|
| 119 |
+
}
|
frontend/src/components/layout/ThemeProvider.tsx
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"use client";
|
| 2 |
+
|
| 3 |
+
import { ThemeProvider as NextThemesProvider } from "next-themes";
|
| 4 |
+
import { type ThemeProviderProps } from "next-themes";
|
| 5 |
+
|
| 6 |
+
export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
|
| 7 |
+
return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
|
| 8 |
+
}
|
frontend/src/components/layout/ThemeToggle.tsx
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"use client";
|
| 2 |
+
|
| 3 |
+
import { useTheme } from "next-themes";
|
| 4 |
+
import { useSyncExternalStore } from "react";
|
| 5 |
+
import { Sun, Moon } from "lucide-react";
|
| 6 |
+
|
| 7 |
+
// useSyncExternalStore with identical server/client snapshots = no hydration mismatch
|
| 8 |
+
const subscribe = () => () => {};
|
| 9 |
+
const getSnapshot = () => true;
|
| 10 |
+
const getServerSnapshot = () => false;
|
| 11 |
+
|
| 12 |
+
export function ThemeToggle() {
|
| 13 |
+
const { theme, setTheme } = useTheme();
|
| 14 |
+
const mounted = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
| 15 |
+
|
| 16 |
+
if (!mounted) return null;
|
| 17 |
+
|
| 18 |
+
return (
|
| 19 |
+
<button
|
| 20 |
+
onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
|
| 21 |
+
aria-label="Toggle theme"
|
| 22 |
+
className="rounded-md p-2 transition-colors hover:bg-gray-100 dark:hover:bg-gray-800"
|
| 23 |
+
>
|
| 24 |
+
{theme === "dark" ? (
|
| 25 |
+
<Sun className="h-5 w-5 text-yellow-400" />
|
| 26 |
+
) : (
|
| 27 |
+
<Moon className="h-5 w-5 text-gray-700" />
|
| 28 |
+
)}
|
| 29 |
+
</button>
|
| 30 |
+
);
|
| 31 |
+
}
|