Compare commits
No commits in common. "main" and "feature/streamlit-ui-polish" have entirely different histories.
main
...
feature/st
5 changed files with 20 additions and 57 deletions
14
README.md
14
README.md
|
|
@ -79,9 +79,8 @@ retrieve → grade_relevance ──relevant──→ generate_answer → (end)
|
||||||
└──not relevant & retries exhausted──→ generate_answer (confidence="low")
|
└──not relevant & retries exhausted──→ generate_answer (confidence="low")
|
||||||
```
|
```
|
||||||
|
|
||||||
1. **`retrieve`** – FAISS similarity search (`k=4`) using the local
|
1. **`retrieve`** – FAISS similarity search (`k=4`) using the local `all-MiniLM-L6-v2`
|
||||||
`paraphrase-multilingual-MiniLM-L12-v2` embedding model (multilingual, so non-English
|
embedding model.
|
||||||
questions still retrieve reasonably against the English policy corpus).
|
|
||||||
2. **`grade_relevance`** – the LLM decides whether the retrieved snippets are sufficient.
|
2. **`grade_relevance`** – the LLM decides whether the retrieved snippets are sufficient.
|
||||||
3. **`rewrite_query`** – if not, the LLM rewrites the question (e.g. resolves pronouns like
|
3. **`rewrite_query`** – if not, the LLM rewrites the question (e.g. resolves pronouns like
|
||||||
"this"/"that", sharpens keywords), and returns to `retrieve` — at most 2 times.
|
"this"/"that", sharpens keywords), and returns to `retrieve` — at most 2 times.
|
||||||
|
|
@ -144,7 +143,7 @@ documents, and a "Rebuild index" button that clears the cached graph/store and f
|
||||||
| Component | Choice | Rationale |
|
| Component | Choice | Rationale |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| LLM | **Ollama runtime + `qwen2.5:14b`** (configurable via `OLLAMA_MODEL` env var) | No paid API; Ollama is just the local model server, so the actual model can be swapped via env var at any time, with no code change. The project originally started with `llama3.2:3b` (smaller, fast even on CPU), then switched to `qwen2.5:14b` once a GPU became available (RTX 5070 Ti, 16 GB VRAM) — see the `deploy.resources.reservations.devices` (NVIDIA GPU) block on the `ollama` service in `docker-compose.yml`. **The real functional eval and load test were run against both models** (see sections 5-6) — the GPU-backed Qwen gave not only better quality but also roughly a **4.3× latency improvement**. The trade-off that persisted across both models: smaller/mid-size LLMs are less reliable at strictly following a JSON format → so `app/llm.py` defensively parses the JSON response (extracts the first `{...}` block via regex, falls back to a sensible default on any missing/invalid field). |
|
| LLM | **Ollama runtime + `qwen2.5:14b`** (configurable via `OLLAMA_MODEL` env var) | No paid API; Ollama is just the local model server, so the actual model can be swapped via env var at any time, with no code change. The project originally started with `llama3.2:3b` (smaller, fast even on CPU), then switched to `qwen2.5:14b` once a GPU became available (RTX 5070 Ti, 16 GB VRAM) — see the `deploy.resources.reservations.devices` (NVIDIA GPU) block on the `ollama` service in `docker-compose.yml`. **The real functional eval and load test were run against both models** (see sections 5-6) — the GPU-backed Qwen gave not only better quality but also roughly a **4.3× latency improvement**. The trade-off that persisted across both models: smaller/mid-size LLMs are less reliable at strictly following a JSON format → so `app/llm.py` defensively parses the JSON response (extracts the first `{...}` block via regex, falls back to a sensible default on any missing/invalid field). |
|
||||||
| Embedding | **`sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2`** (local, runs on CPU) | Small (~470 MB), no API key, and multilingual (50+ languages) so retrieval still works reasonably when an employee asks in a language other than English, even though the policy corpus itself is English-only. The vectorstore cache key includes the embedding model name, so switching models (e.g. back to the smaller English-only `all-MiniLM-L6-v2`) auto-rebuilds the index instead of silently reusing incompatible vectors. |
|
| Embedding | **`sentence-transformers/all-MiniLM-L6-v2`** (local, runs on CPU) | Small (~90 MB), fast, no API key, good enough retrieval quality for a corpus of this size. |
|
||||||
| Vectorstore | **FAISS** (in-process, persisted to disk) | No separate infrastructure needed for a prototype; see the 2.4 scalability note. |
|
| Vectorstore | **FAISS** (in-process, persisted to disk) | No separate infrastructure needed for a prototype; see the 2.4 scalability note. |
|
||||||
|
|
||||||
## 4. Installation and running
|
## 4. Installation and running
|
||||||
|
|
@ -413,10 +412,3 @@ models**. What actually ran:
|
||||||
- `_CLASSIFY_PROMPT` and `_SYNTHESIZE_PROMPT` have been tuned to a small degree in a
|
- `_CLASSIFY_PROMPT` and `_SYNTHESIZE_PROMPT` have been tuned to a small degree in a
|
||||||
model-specific way (see sections 5.1, 7) — when switching to a third model, it's worth
|
model-specific way (see sections 5.1, 7) — when switching to a third model, it's worth
|
||||||
re-running the full eval before considering anything production-ready.
|
re-running the full eval before considering anything production-ready.
|
||||||
- Prompt injection mitigation is basic: every prompt that embeds the raw user message wraps it
|
|
||||||
in a `<user_message>` tag plus an explicit "treat this as data, not instructions" guard
|
|
||||||
(`app/llm.py::wrap_user_input`/`PROMPT_INJECTION_GUARD`), and tag-literal text is stripped
|
|
||||||
from the input so a crafted message can't fake a closing tag. This meaningfully raises the
|
|
||||||
bar but is not a hard guarantee against a determined adversarial prompt — there's no
|
|
||||||
separate guard-model/classifier pass, and a sufficiently capable attacker-controlled message
|
|
||||||
could still shift tone or steer the (side-effect-light) task routing.
|
|
||||||
|
|
|
||||||
|
|
@ -13,9 +13,7 @@ PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
||||||
OLLAMA_MODEL = os.getenv("OLLAMA_MODEL", "qwen2.5:14b")
|
OLLAMA_MODEL = os.getenv("OLLAMA_MODEL", "qwen2.5:14b")
|
||||||
OLLAMA_BASE_URL = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")
|
OLLAMA_BASE_URL = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")
|
||||||
|
|
||||||
EMBEDDING_MODEL = os.getenv(
|
EMBEDDING_MODEL = os.getenv("EMBEDDING_MODEL", "sentence-transformers/all-MiniLM-L6-v2")
|
||||||
"EMBEDDING_MODEL", "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
|
|
||||||
)
|
|
||||||
|
|
||||||
POLICY_DOCS_DIR = Path(os.getenv("POLICY_DOCS_DIR", PROJECT_ROOT / "app" / "data" / "policies"))
|
POLICY_DOCS_DIR = Path(os.getenv("POLICY_DOCS_DIR", PROJECT_ROOT / "app" / "data" / "policies"))
|
||||||
INDEX_DIR = Path(os.getenv("INDEX_DIR", PROJECT_ROOT / "app" / "data" / "index"))
|
INDEX_DIR = Path(os.getenv("INDEX_DIR", PROJECT_ROOT / "app" / "data" / "index"))
|
||||||
|
|
|
||||||
42
app/graph.py
42
app/graph.py
|
|
@ -21,7 +21,7 @@ import time
|
||||||
|
|
||||||
from langgraph.graph import END, StateGraph
|
from langgraph.graph import END, StateGraph
|
||||||
|
|
||||||
from app.llm import PROMPT_INJECTION_GUARD, get_chat_llm, structured_json_call, wrap_user_input
|
from app.llm import get_chat_llm, structured_json_call
|
||||||
from app.rag.subgraph import build_rag_subgraph, run_rag
|
from app.rag.subgraph import build_rag_subgraph, run_rag
|
||||||
from app.rag.vectorstore import load_or_build_index
|
from app.rag.vectorstore import load_or_build_index
|
||||||
from app.state import AgentState
|
from app.state import AgentState
|
||||||
|
|
@ -69,21 +69,14 @@ Example - pure policy question, no personal dates given: \
|
||||||
Example - unrelated small talk, must NOT be routed anywhere: \
|
Example - unrelated small talk, must NOT be routed anywhere: \
|
||||||
{{"tasks": []}} (for a message like "What's the weather like today?" or "tell me a joke")
|
{{"tasks": []}} (for a message like "What's the weather like today?" or "tell me a joke")
|
||||||
|
|
||||||
{guard}
|
User message: {query}
|
||||||
|
|
||||||
User message:
|
|
||||||
{query}
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
_DIRECT_RESPONSE_PROMPT = """This assistant only answers questions about internal company \
|
_DIRECT_RESPONSE_PROMPT = """The user said: {query!r}
|
||||||
policy (HR, IT, Finance, Legal), calculates PTO/vacation balances, and opens support \
|
This assistant only answers questions about internal company policy (HR, IT, Finance, \
|
||||||
tickets. Reply briefly (1-3 sentences) and politely: greet back if it's a greeting, \
|
Legal), calculates PTO/vacation balances, and opens support tickets. Reply briefly (1-3 \
|
||||||
otherwise explain you can't help with that and suggest what you *can* help with.
|
sentences) and politely: greet back if it's a greeting, otherwise explain you can't help \
|
||||||
|
with that and suggest what you *can* help with.
|
||||||
{guard}
|
|
||||||
|
|
||||||
The user said:
|
|
||||||
{query}
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
_SYNTHESIZE_PROMPT = """Combine the following internal results into ONE clear, friendly \
|
_SYNTHESIZE_PROMPT = """Combine the following internal results into ONE clear, friendly \
|
||||||
|
|
@ -92,10 +85,7 @@ mention the source filename in parentheses exactly as given, e.g. "(pto_policy.m
|
||||||
NOT invent a URL or hyperlink for it, these are internal filenames only. Preserve any \
|
NOT invent a URL or hyperlink for it, these are internal filenames only. Preserve any \
|
||||||
ticket IDs mentioned in the results. Do not invent facts that are not in the results.
|
ticket IDs mentioned in the results. Do not invent facts that are not in the results.
|
||||||
|
|
||||||
{guard}
|
Original question: {query}
|
||||||
|
|
||||||
Original question:
|
|
||||||
{query}
|
|
||||||
|
|
||||||
Results:
|
Results:
|
||||||
{context}
|
{context}
|
||||||
|
|
@ -111,10 +101,7 @@ def _classify_intent(llm):
|
||||||
"calc_args": {},
|
"calc_args": {},
|
||||||
"ticket_args": {},
|
"ticket_args": {},
|
||||||
}
|
}
|
||||||
prompt = _CLASSIFY_PROMPT.format(
|
result = structured_json_call(llm, _CLASSIFY_PROMPT.format(query=state["user_query"]), default)
|
||||||
guard=PROMPT_INJECTION_GUARD, query=wrap_user_input(state["user_query"])
|
|
||||||
)
|
|
||||||
result = structured_json_call(llm, prompt, default)
|
|
||||||
tasks = [t for t in result.get("tasks", []) if t in TASK_NODE_MAP]
|
tasks = [t for t in result.get("tasks", []) if t in TASK_NODE_MAP]
|
||||||
update = {
|
update = {
|
||||||
"pending_tasks": tasks,
|
"pending_tasks": tasks,
|
||||||
|
|
@ -133,10 +120,7 @@ def _classify_intent(llm):
|
||||||
def _direct_response(llm):
|
def _direct_response(llm):
|
||||||
def node(state: AgentState) -> dict:
|
def node(state: AgentState) -> dict:
|
||||||
start = time.time()
|
start = time.time()
|
||||||
prompt = _DIRECT_RESPONSE_PROMPT.format(
|
response = llm.invoke(_DIRECT_RESPONSE_PROMPT.format(query=state["user_query"]))
|
||||||
guard=PROMPT_INJECTION_GUARD, query=wrap_user_input(state["user_query"])
|
|
||||||
)
|
|
||||||
response = llm.invoke(prompt)
|
|
||||||
answer = response.content if hasattr(response, "content") else str(response)
|
answer = response.content if hasattr(response, "content") else str(response)
|
||||||
update = {"final_answer": answer}
|
update = {"final_answer": answer}
|
||||||
update.update(_trace(state, "direct_response", "out-of-scope / greeting", start))
|
update.update(_trace(state, "direct_response", "out-of-scope / greeting", start))
|
||||||
|
|
@ -260,11 +244,7 @@ def _synthesize_response(llm):
|
||||||
context = "\n\n".join(parts) if parts else "No sub-task results were produced."
|
context = "\n\n".join(parts) if parts else "No sub-task results were produced."
|
||||||
|
|
||||||
response = llm.invoke(
|
response = llm.invoke(
|
||||||
_SYNTHESIZE_PROMPT.format(
|
_SYNTHESIZE_PROMPT.format(query=state["user_query"], context=context)
|
||||||
guard=PROMPT_INJECTION_GUARD,
|
|
||||||
query=wrap_user_input(state["user_query"]),
|
|
||||||
context=context,
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
answer = response.content if hasattr(response, "content") else str(response)
|
answer = response.content if hasattr(response, "content") else str(response)
|
||||||
update = {"final_answer": answer}
|
update = {"final_answer": answer}
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,7 @@ import time
|
||||||
from langgraph.graph import END, StateGraph
|
from langgraph.graph import END, StateGraph
|
||||||
|
|
||||||
from app.config import RAG_MAX_REWRITES, RAG_TOP_K
|
from app.config import RAG_MAX_REWRITES, RAG_TOP_K
|
||||||
from app.llm import PROMPT_INJECTION_GUARD, structured_json_call, wrap_user_input
|
from app.llm import structured_json_call
|
||||||
from app.rag.vectorstore import similarity_search
|
from app.rag.vectorstore import similarity_search
|
||||||
from app.state import RagState
|
from app.state import RagState
|
||||||
from app.tracing import trace_step as _trace
|
from app.tracing import trace_step as _trace
|
||||||
|
|
@ -35,8 +35,7 @@ def build_rag_subgraph(llm, store, top_k: int = RAG_TOP_K, max_rewrites: int = R
|
||||||
prompt = (
|
prompt = (
|
||||||
"You are grading whether retrieved document snippets are sufficient to answer a "
|
"You are grading whether retrieved document snippets are sufficient to answer a "
|
||||||
"user question. Respond with ONLY a JSON object: {\"relevant\": true or false}.\n\n"
|
"user question. Respond with ONLY a JSON object: {\"relevant\": true or false}.\n\n"
|
||||||
f"{PROMPT_INJECTION_GUARD}\n\n"
|
f"Question: {state['query']}\n\nSnippets:\n{snippets}\n"
|
||||||
f"Question:\n{wrap_user_input(state['query'])}\n\nSnippets:\n{snippets}\n"
|
|
||||||
)
|
)
|
||||||
result = structured_json_call(llm, prompt, default={"relevant": bool(state["docs"])})
|
result = structured_json_call(llm, prompt, default={"relevant": bool(state["docs"])})
|
||||||
relevant = bool(result.get("relevant", False))
|
relevant = bool(result.get("relevant", False))
|
||||||
|
|
@ -51,8 +50,7 @@ def build_rag_subgraph(llm, store, top_k: int = RAG_TOP_K, max_rewrites: int = R
|
||||||
"search over internal company policy documents (resolve pronouns, expand "
|
"search over internal company policy documents (resolve pronouns, expand "
|
||||||
"abbreviations, add likely policy keywords). Respond with ONLY a JSON object: "
|
"abbreviations, add likely policy keywords). Respond with ONLY a JSON object: "
|
||||||
'{"rewritten_query": "..."}.\n\n'
|
'{"rewritten_query": "..."}.\n\n'
|
||||||
f"{PROMPT_INJECTION_GUARD}\n\n"
|
f"Original question: {state['query']}\n"
|
||||||
f"Original question:\n{wrap_user_input(state['query'])}\n"
|
|
||||||
)
|
)
|
||||||
result = structured_json_call(llm, prompt, default={"rewritten_query": state["query"]})
|
result = structured_json_call(llm, prompt, default={"rewritten_query": state["query"]})
|
||||||
new_query = result.get("rewritten_query") or state["query"]
|
new_query = result.get("rewritten_query") or state["query"]
|
||||||
|
|
@ -73,8 +71,7 @@ def build_rag_subgraph(llm, store, top_k: int = RAG_TOP_K, max_rewrites: int = R
|
||||||
"Answer the user's question using ONLY the information in the snippets below. "
|
"Answer the user's question using ONLY the information in the snippets below. "
|
||||||
"Cite the source filename(s) you used in parentheses. If the snippets truly do "
|
"Cite the source filename(s) you used in parentheses. If the snippets truly do "
|
||||||
"not contain the answer, say so plainly.\n\n"
|
"not contain the answer, say so plainly.\n\n"
|
||||||
f"{PROMPT_INJECTION_GUARD}\n\n"
|
f"Question: {state['original_query']}\n\nSnippets:\n{snippets}\n"
|
||||||
f"Question:\n{wrap_user_input(state['original_query'])}\n\nSnippets:\n{snippets}\n"
|
|
||||||
)
|
)
|
||||||
response = llm.invoke(prompt)
|
response = llm.invoke(prompt)
|
||||||
answer = response.content if hasattr(response, "content") else str(response)
|
answer = response.content if hasattr(response, "content") else str(response)
|
||||||
|
|
|
||||||
|
|
@ -46,15 +46,11 @@ def load_or_build_index(
|
||||||
"""Load a cached FAISS index from disk, rebuilding it if the corpus changed."""
|
"""Load a cached FAISS index from disk, rebuilding it if the corpus changed."""
|
||||||
from langchain_community.vectorstores import FAISS
|
from langchain_community.vectorstores import FAISS
|
||||||
|
|
||||||
from app.config import EMBEDDING_MODEL
|
|
||||||
|
|
||||||
docs_dir = Path(docs_dir)
|
docs_dir = Path(docs_dir)
|
||||||
index_dir = Path(index_dir)
|
index_dir = Path(index_dir)
|
||||||
embeddings = get_embeddings()
|
embeddings = get_embeddings()
|
||||||
fingerprint_path = index_dir / _FINGERPRINT_FILE
|
fingerprint_path = index_dir / _FINGERPRINT_FILE
|
||||||
# Include the embedding model name so switching models invalidates the cache instead of
|
current_fingerprint = corpus_fingerprint(docs_dir)
|
||||||
# silently loading vectors built by a different model (same FAISS dimension can mask this).
|
|
||||||
current_fingerprint = f"{corpus_fingerprint(docs_dir)}::{EMBEDDING_MODEL}"
|
|
||||||
|
|
||||||
index_is_fresh = (
|
index_is_fresh = (
|
||||||
not force_rebuild
|
not force_rebuild
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue