Spaces:
Sleeping
Sleeping
Aissugur Kurganbekov Claude Opus 4.8 (1M context) commited on
Commit ·
f2f300a
1
Parent(s): 2695640
Add Fast / Thinking answer modes (per-request LLM toggle)
Browse files- Fast: extractive engine — instant, offline, free (no API key).
- Thinking: LLM reasons on the fly with Claude adaptive thinking
(thinking={"type":"adaptive"}, no temperature — correct for current models),
grounded in the same retrieved context with citations + abstention.
Transparently falls back to Fast when no API key is set, so it never breaks.
- AskRequest.mode ("fast"|"thinking", validated -> 422 on bad value); /ask
returns the engine that actually answered.
- Frontend: segmented Fast/Thinking toggle in the Ask view; mode passed to API.
- Thinking model default = claude-sonnet-4-6 (supports adaptive thinking).
- 21 tests pass incl. new thinking->fast fallback test.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- backend/.env.example +9 -11
- backend/app/answering.py +20 -11
- backend/app/config.py +15 -3
- backend/app/llm.py +39 -32
- backend/app/main.py +1 -1
- backend/app/schemas.py +3 -2
- backend/tests/test_answering.py +14 -1
- frontend/src/api.js +2 -2
- frontend/src/components/views/Ask.jsx +25 -2
- frontend/src/styles.css +32 -0
backend/.env.example
CHANGED
|
@@ -1,19 +1,17 @@
|
|
| 1 |
-
# Copy this file to ".env"
|
| 2 |
-
#
|
|
|
|
| 3 |
|
| 4 |
-
#
|
| 5 |
-
ANSWER_MODE=extractive
|
| 6 |
-
|
| 7 |
-
# LLM provider when ANSWER_MODE=llm: "openai" or "anthropic"
|
| 8 |
LLM_PROVIDER=anthropic
|
| 9 |
|
| 10 |
-
# API keys (only needed for
|
| 11 |
-
OPENAI_API_KEY=
|
| 12 |
ANTHROPIC_API_KEY=
|
|
|
|
| 13 |
|
| 14 |
-
#
|
| 15 |
-
|
| 16 |
-
|
| 17 |
|
| 18 |
# Retrieval tuning
|
| 19 |
TOP_K=4
|
|
|
|
| 1 |
+
# Copy this file to ".env" to enable "Thinking" mode. The app works fully
|
| 2 |
+
# WITHOUT any key: "Fast" mode (extractive) needs nothing, and "Thinking" mode
|
| 3 |
+
# automatically falls back to Fast when no key is present.
|
| 4 |
|
| 5 |
+
# Provider for Thinking mode: "anthropic" (Claude) or "openai"
|
|
|
|
|
|
|
|
|
|
| 6 |
LLM_PROVIDER=anthropic
|
| 7 |
|
| 8 |
+
# API keys (only needed for Thinking mode). Leave blank to stay on Fast.
|
|
|
|
| 9 |
ANTHROPIC_API_KEY=
|
| 10 |
+
OPENAI_API_KEY=
|
| 11 |
|
| 12 |
+
# Models used by Thinking mode (Sonnet 4.6 supports adaptive thinking).
|
| 13 |
+
ANTHROPIC_MODEL=claude-sonnet-4-6
|
| 14 |
+
OPENAI_MODEL=gpt-4o
|
| 15 |
|
| 16 |
# Retrieval tuning
|
| 17 |
TOP_K=4
|
backend/app/answering.py
CHANGED
|
@@ -99,15 +99,21 @@ def build_citations(scored: List[ScoredChunk], question: str) -> List[Citation]:
|
|
| 99 |
return citations
|
| 100 |
|
| 101 |
|
| 102 |
-
def answer_question(question: str, chunks: List[Chunk]):
|
| 103 |
-
"""Return (answer, abstained, mode, citations).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
scored = rank_chunks(question, chunks, top_k=config.TOP_K)
|
| 105 |
top_score = scored[0].score if scored else 0.0
|
| 106 |
|
| 107 |
# Anti-hallucination guard #1: the best evidence must clear a score floor.
|
| 108 |
if not scored or top_score < config.SCORE_THRESHOLD:
|
| 109 |
logger.info("Abstain (low score %.3f) for question: %s", top_score, question)
|
| 110 |
-
return config.ABSTAIN_MESSAGE, True,
|
| 111 |
|
| 112 |
# Anti-hallucination guard #2: term coverage. A genuine answer normally
|
| 113 |
# shares at least two distinct content words with the source. This stops a
|
|
@@ -126,18 +132,21 @@ def answer_question(question: str, chunks: List[Chunk]):
|
|
| 126 |
len(q_terms),
|
| 127 |
question,
|
| 128 |
)
|
| 129 |
-
return config.ABSTAIN_MESSAGE, True,
|
| 130 |
|
| 131 |
# Keep only chunks that carry real signal for the citations/context.
|
| 132 |
relevant = [s for s in scored if s.score >= config.SCORE_THRESHOLD] or scored[:1]
|
| 133 |
citations = build_citations(relevant, question)
|
| 134 |
|
| 135 |
-
#
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
answer = _focused_answer(question, [s.chunk for s in relevant])
|
| 143 |
-
return answer, False, "
|
|
|
|
| 99 |
return citations
|
| 100 |
|
| 101 |
|
| 102 |
+
def answer_question(question: str, chunks: List[Chunk], mode: str = "fast"):
|
| 103 |
+
"""Return (answer, abstained, mode, citations).
|
| 104 |
+
|
| 105 |
+
mode="fast" -> extractive engine (instant, offline, free).
|
| 106 |
+
mode="thinking" -> LLM reasons on the fly; falls back to fast if no API key
|
| 107 |
+
or the call fails. The returned mode reflects what actually
|
| 108 |
+
produced the answer ("fast" | "thinking").
|
| 109 |
+
"""
|
| 110 |
scored = rank_chunks(question, chunks, top_k=config.TOP_K)
|
| 111 |
top_score = scored[0].score if scored else 0.0
|
| 112 |
|
| 113 |
# Anti-hallucination guard #1: the best evidence must clear a score floor.
|
| 114 |
if not scored or top_score < config.SCORE_THRESHOLD:
|
| 115 |
logger.info("Abstain (low score %.3f) for question: %s", top_score, question)
|
| 116 |
+
return config.ABSTAIN_MESSAGE, True, mode, []
|
| 117 |
|
| 118 |
# Anti-hallucination guard #2: term coverage. A genuine answer normally
|
| 119 |
# shares at least two distinct content words with the source. This stops a
|
|
|
|
| 132 |
len(q_terms),
|
| 133 |
question,
|
| 134 |
)
|
| 135 |
+
return config.ABSTAIN_MESSAGE, True, mode, []
|
| 136 |
|
| 137 |
# Keep only chunks that carry real signal for the citations/context.
|
| 138 |
relevant = [s for s in scored if s.score >= config.SCORE_THRESHOLD] or scored[:1]
|
| 139 |
citations = build_citations(relevant, question)
|
| 140 |
|
| 141 |
+
# Thinking mode: let the LLM reason over the same grounded context.
|
| 142 |
+
if mode == "thinking":
|
| 143 |
+
contexts = [s.chunk.text for s in relevant]
|
| 144 |
+
llm_answer = llm.synthesize(question, contexts)
|
| 145 |
+
if llm_answer:
|
| 146 |
+
abstained = llm_answer.strip() == config.ABSTAIN_MESSAGE
|
| 147 |
+
return llm_answer, abstained, "thinking", ([] if abstained else citations)
|
| 148 |
+
# No key / call failed -> transparently fall back to the fast engine.
|
| 149 |
+
logger.info("Thinking unavailable; using fast (extractive) for: %s", question)
|
| 150 |
|
| 151 |
answer = _focused_answer(question, [s.chunk for s in relevant])
|
| 152 |
+
return answer, False, "fast", citations
|
backend/app/config.py
CHANGED
|
@@ -24,12 +24,24 @@ DATABASE_URL = f"sqlite:///{DB_PATH}"
|
|
| 24 |
SAMPLE_DOCS_DIR = BACKEND_DIR.parent / "sample_docs"
|
| 25 |
|
| 26 |
# Answer behaviour.
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
LLM_PROVIDER = os.getenv("LLM_PROVIDER", "anthropic").strip().lower()
|
| 29 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "").strip()
|
| 30 |
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY", "").strip()
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
# Retrieval tuning.
|
| 35 |
TOP_K = int(os.getenv("TOP_K", "4"))
|
|
|
|
| 24 |
SAMPLE_DOCS_DIR = BACKEND_DIR.parent / "sample_docs"
|
| 25 |
|
| 26 |
# Answer behaviour.
|
| 27 |
+
# Two request-time answer modes:
|
| 28 |
+
# "fast" -> extractive engine: instant, offline, free (no API key needed).
|
| 29 |
+
# "thinking" -> LLM reasons on the fly with adaptive thinking (needs an API
|
| 30 |
+
# key); automatically falls back to "fast" if no key is set.
|
| 31 |
+
ANSWER_MODE = os.getenv("ANSWER_MODE", "extractive").strip().lower() # legacy/health only
|
| 32 |
LLM_PROVIDER = os.getenv("LLM_PROVIDER", "anthropic").strip().lower()
|
| 33 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "").strip()
|
| 34 |
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY", "").strip()
|
| 35 |
+
|
| 36 |
+
# Model used by "thinking" mode (reasons with adaptive thinking on Anthropic).
|
| 37 |
+
ANTHROPIC_MODEL = os.getenv("ANTHROPIC_MODEL", "claude-sonnet-4-6").strip()
|
| 38 |
+
OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-4o").strip()
|
| 39 |
+
|
| 40 |
+
# True if any provider key is configured (so "thinking" mode is actually usable).
|
| 41 |
+
LLM_AVAILABLE = bool(
|
| 42 |
+
(LLM_PROVIDER == "anthropic" and ANTHROPIC_API_KEY)
|
| 43 |
+
or (LLM_PROVIDER == "openai" and OPENAI_API_KEY)
|
| 44 |
+
)
|
| 45 |
|
| 46 |
# Retrieval tuning.
|
| 47 |
TOP_K = int(os.getenv("TOP_K", "4"))
|
backend/app/llm.py
CHANGED
|
@@ -1,19 +1,29 @@
|
|
| 1 |
-
"""Optional LLM synthesis layer.
|
| 2 |
|
| 3 |
-
The app NEVER requires this.
|
| 4 |
-
we ask the model to answer strictly from the supplied
|
| 5 |
-
the abstain message when the context is insufficient.
|
| 6 |
-
package, bad key, network error)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
"""
|
|
|
|
| 8 |
from typing import List, Optional
|
| 9 |
|
| 10 |
from . import config
|
| 11 |
|
|
|
|
|
|
|
| 12 |
SYSTEM_PROMPT = (
|
| 13 |
"You are a careful financial-document assistant. Answer ONLY using the "
|
| 14 |
-
"provided context excerpts.
|
| 15 |
-
"
|
| 16 |
-
|
|
|
|
| 17 |
)
|
| 18 |
|
| 19 |
|
|
@@ -23,20 +33,36 @@ def _build_user_prompt(question: str, contexts: List[str]) -> str:
|
|
| 23 |
|
| 24 |
|
| 25 |
def synthesize(question: str, contexts: List[str]) -> Optional[str]:
|
| 26 |
-
"""Return an LLM answer string, or None to signal 'fall back to
|
| 27 |
-
if config.ANSWER_MODE != "llm":
|
| 28 |
-
return None
|
| 29 |
try:
|
| 30 |
if config.LLM_PROVIDER == "openai":
|
| 31 |
return _openai(question, contexts)
|
| 32 |
if config.LLM_PROVIDER == "anthropic":
|
| 33 |
return _anthropic(question, contexts)
|
| 34 |
except Exception as exc: # pragma: no cover - defensive
|
| 35 |
-
|
| 36 |
return None
|
| 37 |
return None
|
| 38 |
|
| 39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
def _openai(question: str, contexts: List[str]) -> Optional[str]:
|
| 41 |
if not config.OPENAI_API_KEY:
|
| 42 |
return None
|
|
@@ -51,23 +77,4 @@ def _openai(question: str, contexts: List[str]) -> Optional[str]:
|
|
| 51 |
{"role": "user", "content": _build_user_prompt(question, contexts)},
|
| 52 |
],
|
| 53 |
)
|
| 54 |
-
return (resp.choices[0].message.content or "").strip()
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
def _anthropic(question: str, contexts: List[str]) -> Optional[str]:
|
| 58 |
-
if not config.ANTHROPIC_API_KEY:
|
| 59 |
-
return None
|
| 60 |
-
import anthropic # lazy import
|
| 61 |
-
|
| 62 |
-
client = anthropic.Anthropic(api_key=config.ANTHROPIC_API_KEY)
|
| 63 |
-
resp = client.messages.create(
|
| 64 |
-
model=config.ANTHROPIC_MODEL,
|
| 65 |
-
max_tokens=400,
|
| 66 |
-
temperature=0,
|
| 67 |
-
system=SYSTEM_PROMPT,
|
| 68 |
-
messages=[
|
| 69 |
-
{"role": "user", "content": _build_user_prompt(question, contexts)},
|
| 70 |
-
],
|
| 71 |
-
)
|
| 72 |
-
parts = [block.text for block in resp.content if getattr(block, "type", "") == "text"]
|
| 73 |
-
return "".join(parts).strip()
|
|
|
|
| 1 |
+
"""Optional LLM synthesis layer for "thinking" mode.
|
| 2 |
|
| 3 |
+
The app NEVER requires this. When the user picks Thinking mode AND a provider key
|
| 4 |
+
is configured, we ask the model to reason and answer strictly from the supplied
|
| 5 |
+
context, replying with the abstain message when the context is insufficient.
|
| 6 |
+
Any failure (missing package, bad key, network error) returns None so the caller
|
| 7 |
+
falls back to the extractive Fast engine.
|
| 8 |
+
|
| 9 |
+
Anthropic path uses adaptive thinking (`thinking={"type": "adaptive"}`) — the
|
| 10 |
+
correct extended-thinking shape for current Claude models — so it genuinely
|
| 11 |
+
"thinks on the fly". Note: temperature must NOT be sent alongside adaptive
|
| 12 |
+
thinking on current models.
|
| 13 |
"""
|
| 14 |
+
import logging
|
| 15 |
from typing import List, Optional
|
| 16 |
|
| 17 |
from . import config
|
| 18 |
|
| 19 |
+
logger = logging.getLogger(__name__)
|
| 20 |
+
|
| 21 |
SYSTEM_PROMPT = (
|
| 22 |
"You are a careful financial-document assistant. Answer ONLY using the "
|
| 23 |
+
"provided context excerpts. Reason step by step, then give a short, factual "
|
| 24 |
+
"answer. Never invent numbers, dates, names, or company names. If the answer "
|
| 25 |
+
"is not clearly supported by the context, reply with exactly: "
|
| 26 |
+
f'"{config.ABSTAIN_MESSAGE}".'
|
| 27 |
)
|
| 28 |
|
| 29 |
|
|
|
|
| 33 |
|
| 34 |
|
| 35 |
def synthesize(question: str, contexts: List[str]) -> Optional[str]:
|
| 36 |
+
"""Return an LLM answer string, or None to signal 'fall back to Fast'."""
|
|
|
|
|
|
|
| 37 |
try:
|
| 38 |
if config.LLM_PROVIDER == "openai":
|
| 39 |
return _openai(question, contexts)
|
| 40 |
if config.LLM_PROVIDER == "anthropic":
|
| 41 |
return _anthropic(question, contexts)
|
| 42 |
except Exception as exc: # pragma: no cover - defensive
|
| 43 |
+
logger.warning("LLM synthesis failed, falling back to Fast: %s", exc)
|
| 44 |
return None
|
| 45 |
return None
|
| 46 |
|
| 47 |
|
| 48 |
+
def _anthropic(question: str, contexts: List[str]) -> Optional[str]:
|
| 49 |
+
if not config.ANTHROPIC_API_KEY:
|
| 50 |
+
return None
|
| 51 |
+
import anthropic # lazy import
|
| 52 |
+
|
| 53 |
+
client = anthropic.Anthropic(api_key=config.ANTHROPIC_API_KEY)
|
| 54 |
+
resp = client.messages.create(
|
| 55 |
+
model=config.ANTHROPIC_MODEL,
|
| 56 |
+
max_tokens=2048, # generous: must cover adaptive thinking + the answer
|
| 57 |
+
thinking={"type": "adaptive"}, # reason on the fly (no temperature with this)
|
| 58 |
+
system=SYSTEM_PROMPT,
|
| 59 |
+
messages=[{"role": "user", "content": _build_user_prompt(question, contexts)}],
|
| 60 |
+
)
|
| 61 |
+
# Take only the visible text blocks; thinking blocks are skipped.
|
| 62 |
+
parts = [b.text for b in resp.content if getattr(b, "type", "") == "text"]
|
| 63 |
+
return "".join(parts).strip() or None
|
| 64 |
+
|
| 65 |
+
|
| 66 |
def _openai(question: str, contexts: List[str]) -> Optional[str]:
|
| 67 |
if not config.OPENAI_API_KEY:
|
| 68 |
return None
|
|
|
|
| 77 |
{"role": "user", "content": _build_user_prompt(question, contexts)},
|
| 78 |
],
|
| 79 |
)
|
| 80 |
+
return (resp.choices[0].message.content or "").strip() or None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/app/main.py
CHANGED
|
@@ -208,7 +208,7 @@ def ask(req: AskRequest, db: Session = Depends(get_db)):
|
|
| 208 |
)
|
| 209 |
|
| 210 |
chunks = db.query(Chunk).filter(Chunk.document_id == document.id).all()
|
| 211 |
-
answer, abstained, mode, citations = answer_question(question, chunks)
|
| 212 |
logger.info(
|
| 213 |
"Ask doc=%d abstained=%s citations=%d q=%r",
|
| 214 |
document.id,
|
|
|
|
| 208 |
)
|
| 209 |
|
| 210 |
chunks = db.query(Chunk).filter(Chunk.document_id == document.id).all()
|
| 211 |
+
answer, abstained, mode, citations = answer_question(question, chunks, req.mode)
|
| 212 |
logger.info(
|
| 213 |
"Ask doc=%d abstained=%s citations=%d q=%r",
|
| 214 |
document.id,
|
backend/app/schemas.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
"""Pydantic request/response models for the API."""
|
| 2 |
from datetime import datetime
|
| 3 |
-
from typing import List, Optional
|
| 4 |
|
| 5 |
from pydantic import BaseModel, ConfigDict, Field
|
| 6 |
|
|
@@ -29,12 +29,13 @@ class DocumentOut(BaseModel):
|
|
| 29 |
class AskRequest(BaseModel):
|
| 30 |
document_id: int
|
| 31 |
question: str = Field(min_length=1, max_length=2000)
|
|
|
|
| 32 |
|
| 33 |
|
| 34 |
class AskResponse(BaseModel):
|
| 35 |
answer: str
|
| 36 |
abstained: bool
|
| 37 |
-
mode: str # "
|
| 38 |
citations: List[Citation]
|
| 39 |
|
| 40 |
|
|
|
|
| 1 |
"""Pydantic request/response models for the API."""
|
| 2 |
from datetime import datetime
|
| 3 |
+
from typing import List, Literal, Optional
|
| 4 |
|
| 5 |
from pydantic import BaseModel, ConfigDict, Field
|
| 6 |
|
|
|
|
| 29 |
class AskRequest(BaseModel):
|
| 30 |
document_id: int
|
| 31 |
question: str = Field(min_length=1, max_length=2000)
|
| 32 |
+
mode: Literal["fast", "thinking"] = "fast"
|
| 33 |
|
| 34 |
|
| 35 |
class AskResponse(BaseModel):
|
| 36 |
answer: str
|
| 37 |
abstained: bool
|
| 38 |
+
mode: str # what actually answered: "fast" or "thinking"
|
| 39 |
citations: List[Citation]
|
| 40 |
|
| 41 |
|
backend/tests/test_answering.py
CHANGED
|
@@ -16,7 +16,7 @@ def test_answerable_question_returns_grounded_answer_with_citation():
|
|
| 16 |
"What is the total amount due?", chunks
|
| 17 |
)
|
| 18 |
assert abstained is False
|
| 19 |
-
assert mode == "
|
| 20 |
assert "$2,413.98" in answer # verbatim value from the source
|
| 21 |
assert len(citations) >= 1
|
| 22 |
assert citations[0].document_name == "doc.txt"
|
|
@@ -48,3 +48,16 @@ def test_abstains_on_empty_document():
|
|
| 48 |
answer, abstained, _mode, citations = answer_question("anything?", [])
|
| 49 |
assert abstained is True
|
| 50 |
assert citations == []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
"What is the total amount due?", chunks
|
| 17 |
)
|
| 18 |
assert abstained is False
|
| 19 |
+
assert mode == "fast"
|
| 20 |
assert "$2,413.98" in answer # verbatim value from the source
|
| 21 |
assert len(citations) >= 1
|
| 22 |
assert citations[0].document_name == "doc.txt"
|
|
|
|
| 48 |
answer, abstained, _mode, citations = answer_question("anything?", [])
|
| 49 |
assert abstained is True
|
| 50 |
assert citations == []
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def test_thinking_mode_falls_back_to_fast_without_api_key():
|
| 54 |
+
# With no API key configured, Thinking mode must transparently fall back to
|
| 55 |
+
# the Fast (extractive) engine — still grounded, still cited, never broken.
|
| 56 |
+
chunks = [make_chunk(INVOICE)]
|
| 57 |
+
answer, abstained, mode, citations = answer_question(
|
| 58 |
+
"What is the total amount due?", chunks, mode="thinking"
|
| 59 |
+
)
|
| 60 |
+
assert abstained is False
|
| 61 |
+
assert mode == "fast" # fell back because no key
|
| 62 |
+
assert "$2,413.98" in answer
|
| 63 |
+
assert len(citations) >= 1
|
frontend/src/api.js
CHANGED
|
@@ -32,11 +32,11 @@ export const api = {
|
|
| 32 |
deleteDocument: (id) =>
|
| 33 |
fetch(`${BASE}/documents/${id}`, { method: "DELETE" }).then(handle),
|
| 34 |
|
| 35 |
-
ask: (document_id, question) =>
|
| 36 |
fetch(`${BASE}/ask`, {
|
| 37 |
method: "POST",
|
| 38 |
headers: { "Content-Type": "application/json" },
|
| 39 |
-
body: JSON.stringify({ document_id, question }),
|
| 40 |
}).then(handle),
|
| 41 |
|
| 42 |
history: (document_id) => {
|
|
|
|
| 32 |
deleteDocument: (id) =>
|
| 33 |
fetch(`${BASE}/documents/${id}`, { method: "DELETE" }).then(handle),
|
| 34 |
|
| 35 |
+
ask: (document_id, question, mode = "fast") =>
|
| 36 |
fetch(`${BASE}/ask`, {
|
| 37 |
method: "POST",
|
| 38 |
headers: { "Content-Type": "application/json" },
|
| 39 |
+
body: JSON.stringify({ document_id, question, mode }),
|
| 40 |
}).then(handle),
|
| 41 |
|
| 42 |
history: (document_id) => {
|
frontend/src/components/views/Ask.jsx
CHANGED
|
@@ -21,6 +21,7 @@ export default function Ask({ documents, demoSignal, onDemoConsumed }) {
|
|
| 21 |
const [history, setHistory] = useState([]);
|
| 22 |
const [loading, setLoading] = useState(false);
|
| 23 |
const [error, setError] = useState("");
|
|
|
|
| 24 |
const lastDemo = useRef(0);
|
| 25 |
|
| 26 |
// Default to the sample invoice for a deterministic demo, else the first doc.
|
|
@@ -49,7 +50,7 @@ export default function Ask({ documents, demoSignal, onDemoConsumed }) {
|
|
| 49 |
setLoading(true);
|
| 50 |
setResult(null);
|
| 51 |
try {
|
| 52 |
-
const res = await api.ask(Number(id), q.trim());
|
| 53 |
setResult(res);
|
| 54 |
await loadHistory(id);
|
| 55 |
} catch (err) {
|
|
@@ -118,6 +119,28 @@ export default function Ask({ documents, demoSignal, onDemoConsumed }) {
|
|
| 118 |
))}
|
| 119 |
</div>
|
| 120 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
<form
|
| 122 |
onSubmit={(e) => {
|
| 123 |
e.preventDefault();
|
|
@@ -134,7 +157,7 @@ export default function Ask({ documents, demoSignal, onDemoConsumed }) {
|
|
| 134 |
error={error || undefined}
|
| 135 |
/>
|
| 136 |
<Button variant="primary" type="submit" loading={loading} disabled={!question.trim()}>
|
| 137 |
-
{loading ? "Retrieving…" : "Ask"}
|
| 138 |
</Button>
|
| 139 |
</form>
|
| 140 |
|
|
|
|
| 21 |
const [history, setHistory] = useState([]);
|
| 22 |
const [loading, setLoading] = useState(false);
|
| 23 |
const [error, setError] = useState("");
|
| 24 |
+
const [mode, setMode] = useState("fast"); // "fast" (extractive) | "thinking" (LLM)
|
| 25 |
const lastDemo = useRef(0);
|
| 26 |
|
| 27 |
// Default to the sample invoice for a deterministic demo, else the first doc.
|
|
|
|
| 50 |
setLoading(true);
|
| 51 |
setResult(null);
|
| 52 |
try {
|
| 53 |
+
const res = await api.ask(Number(id), q.trim(), mode);
|
| 54 |
setResult(res);
|
| 55 |
await loadHistory(id);
|
| 56 |
} catch (err) {
|
|
|
|
| 119 |
))}
|
| 120 |
</div>
|
| 121 |
|
| 122 |
+
<span className="field-label">Answer mode</span>
|
| 123 |
+
<div className="segmented" role="tablist" aria-label="Answer mode">
|
| 124 |
+
<button
|
| 125 |
+
type="button"
|
| 126 |
+
className={mode === "fast" ? "seg active" : "seg"}
|
| 127 |
+
aria-pressed={mode === "fast"}
|
| 128 |
+
onClick={() => setMode("fast")}
|
| 129 |
+
>
|
| 130 |
+
⚡ Fast
|
| 131 |
+
<small>Instant · grounded snippet</small>
|
| 132 |
+
</button>
|
| 133 |
+
<button
|
| 134 |
+
type="button"
|
| 135 |
+
className={mode === "thinking" ? "seg active" : "seg"}
|
| 136 |
+
aria-pressed={mode === "thinking"}
|
| 137 |
+
onClick={() => setMode("thinking")}
|
| 138 |
+
>
|
| 139 |
+
🧠 Thinking
|
| 140 |
+
<small>LLM reasons · needs API key</small>
|
| 141 |
+
</button>
|
| 142 |
+
</div>
|
| 143 |
+
|
| 144 |
<form
|
| 145 |
onSubmit={(e) => {
|
| 146 |
e.preventDefault();
|
|
|
|
| 157 |
error={error || undefined}
|
| 158 |
/>
|
| 159 |
<Button variant="primary" type="submit" loading={loading} disabled={!question.trim()}>
|
| 160 |
+
{loading ? (mode === "thinking" ? "Thinking…" : "Retrieving…") : "Ask"}
|
| 161 |
</Button>
|
| 162 |
</form>
|
| 163 |
|
frontend/src/styles.css
CHANGED
|
@@ -588,6 +588,38 @@ code {
|
|
| 588 |
align-items: start;
|
| 589 |
}
|
| 590 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 591 |
.chips { display: flex; flex-wrap: wrap; gap: 10px; }
|
| 592 |
.chip {
|
| 593 |
display: flex;
|
|
|
|
| 588 |
align-items: start;
|
| 589 |
}
|
| 590 |
|
| 591 |
+
/* Fast / Thinking segmented control */
|
| 592 |
+
.segmented {
|
| 593 |
+
display: grid;
|
| 594 |
+
grid-template-columns: 1fr 1fr;
|
| 595 |
+
gap: 8px;
|
| 596 |
+
margin-bottom: 18px;
|
| 597 |
+
}
|
| 598 |
+
.seg {
|
| 599 |
+
display: flex;
|
| 600 |
+
flex-direction: column;
|
| 601 |
+
align-items: flex-start;
|
| 602 |
+
gap: 2px;
|
| 603 |
+
padding: 10px 14px;
|
| 604 |
+
border: 1px solid var(--border);
|
| 605 |
+
border-radius: var(--r-md);
|
| 606 |
+
background: var(--surface-1);
|
| 607 |
+
color: var(--text-dim);
|
| 608 |
+
font-size: 14px;
|
| 609 |
+
font-weight: 600;
|
| 610 |
+
font-family: inherit;
|
| 611 |
+
cursor: pointer;
|
| 612 |
+
transition: border-color 0.18s var(--ease), background 0.18s var(--ease), color 0.18s var(--ease);
|
| 613 |
+
}
|
| 614 |
+
.seg:hover { background: var(--surface-2); color: var(--text); }
|
| 615 |
+
.seg small { font-size: 11px; font-weight: 500; color: var(--text-faint); text-transform: none; letter-spacing: 0; }
|
| 616 |
+
.seg.active {
|
| 617 |
+
color: var(--text);
|
| 618 |
+
border-color: rgba(124, 139, 255, 0.55);
|
| 619 |
+
background: var(--accent-soft);
|
| 620 |
+
box-shadow: 0 0 0 1px rgba(124, 139, 255, 0.35) inset;
|
| 621 |
+
}
|
| 622 |
+
|
| 623 |
.chips { display: flex; flex-wrap: wrap; gap: 10px; }
|
| 624 |
.chip {
|
| 625 |
display: flex;
|