tracing added and UI changed to Gradio
Browse files- .gitignore +8 -1
- __pycache__/dataloader.cpython-313.pyc +0 -0
- app.py +113 -0
- config.py +109 -0
- dataloader.py +18 -11
- graph.py +60 -0
- main.py +0 -27
- observability.py +74 -0
- prompts.py +69 -0
- requirements-ingest.txt +4 -0
- requirements.txt +12 -0
.gitignore
CHANGED
|
@@ -1,2 +1,9 @@
|
|
| 1 |
data/
|
| 2 |
-
.env
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
data/
|
| 2 |
+
.env
|
| 3 |
+
.venv/
|
| 4 |
+
__pycache__/
|
| 5 |
+
*.pyc
|
| 6 |
+
|
| 7 |
+
# LangGraph checkpoints
|
| 8 |
+
checkpoints.sqlite
|
| 9 |
+
checkpoints.sqlite-*
|
__pycache__/dataloader.cpython-313.pyc
DELETED
|
Binary file (1.29 kB)
|
|
|
app.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import sys
|
| 3 |
+
import uuid
|
| 4 |
+
|
| 5 |
+
import gradio as gr
|
| 6 |
+
from langchain_core.messages import AIMessage, HumanMessage
|
| 7 |
+
|
| 8 |
+
from config import ConfigError, get_settings
|
| 9 |
+
from graph import build_graph
|
| 10 |
+
from observability import build_run_config, flush
|
| 11 |
+
|
| 12 |
+
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
|
| 13 |
+
logger = logging.getLogger("job-chat")
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
SETTINGS = get_settings()
|
| 17 |
+
GRAPH = build_graph()
|
| 18 |
+
except (ConfigError, FileNotFoundError) as exc:
|
| 19 |
+
sys.exit(f"Startup failed: {exc}")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def new_thread_id():
|
| 23 |
+
return str(uuid.uuid4())
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def jd_status(job_description):
|
| 27 |
+
if job_description and job_description.strip():
|
| 28 |
+
return f"**Loaded** β {len(job_description.split())} words"
|
| 29 |
+
return "*No job description. Fit questions need one.*"
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def add_user_message(user_query, chat_history):
|
| 33 |
+
if not user_query.strip():
|
| 34 |
+
return "", chat_history
|
| 35 |
+
return "", chat_history + [{"role": "user", "content": user_query}]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def stream_response(chat_history, job_description, thread_id):
|
| 39 |
+
"""Stream the assistant reply for the last user message."""
|
| 40 |
+
if not chat_history or chat_history[-1]["role"] != "user":
|
| 41 |
+
yield chat_history
|
| 42 |
+
return
|
| 43 |
+
|
| 44 |
+
job_description = (job_description or "").strip()
|
| 45 |
+
state = {
|
| 46 |
+
"messages": [HumanMessage(content=chat_history[-1]["content"])],
|
| 47 |
+
"job_description": job_description,
|
| 48 |
+
}
|
| 49 |
+
config = build_run_config(thread_id, job_description)
|
| 50 |
+
|
| 51 |
+
chat_history = chat_history + [{"role": "assistant", "content": ""}]
|
| 52 |
+
try:
|
| 53 |
+
for chunk, _meta in GRAPH.stream(state, config, stream_mode="messages"):
|
| 54 |
+
if isinstance(chunk, AIMessage) and chunk.content:
|
| 55 |
+
chat_history[-1]["content"] += chunk.content
|
| 56 |
+
yield chat_history
|
| 57 |
+
except Exception as exc:
|
| 58 |
+
logger.exception("Request failed")
|
| 59 |
+
chat_history[-1]["content"] = f"Request failed: {exc}"
|
| 60 |
+
yield chat_history
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
with gr.Blocks(title="job-chat", fill_height=True, analytics_enabled=False) as demo:
|
| 64 |
+
thread_id = gr.State(new_thread_id)
|
| 65 |
+
|
| 66 |
+
gr.Markdown("## job-chat")
|
| 67 |
+
gr.Markdown("Ask about your background, draft interview answers, or test your fit against a role.")
|
| 68 |
+
|
| 69 |
+
with gr.Row(equal_height=False):
|
| 70 |
+
with gr.Column(scale=1):
|
| 71 |
+
gr.Markdown("### Target role")
|
| 72 |
+
jd_box = gr.Textbox(
|
| 73 |
+
lines=18,
|
| 74 |
+
max_lines=18,
|
| 75 |
+
placeholder="Paste the full job description here.",
|
| 76 |
+
show_label=False,
|
| 77 |
+
)
|
| 78 |
+
jd_state = gr.Markdown(jd_status(""))
|
| 79 |
+
clear_jd_btn = gr.Button("Clear job description")
|
| 80 |
+
|
| 81 |
+
with gr.Column(scale=2):
|
| 82 |
+
chatbot = gr.Chatbot(height=520, show_label=False, resizable=True)
|
| 83 |
+
query_box = gr.Textbox(
|
| 84 |
+
placeholder="Ask a question...",
|
| 85 |
+
show_label=False,
|
| 86 |
+
submit_btn=True,
|
| 87 |
+
)
|
| 88 |
+
clear_chat_btn = gr.Button("Reset conversation")
|
| 89 |
+
|
| 90 |
+
jd_box.change(jd_status, inputs=jd_box, outputs=jd_state)
|
| 91 |
+
clear_jd_btn.click(lambda: "", outputs=jd_box)
|
| 92 |
+
|
| 93 |
+
# A new thread id starts a fresh checkpointed conversation; the old one stays on disk.
|
| 94 |
+
clear_chat_btn.click(lambda: ([], new_thread_id()), outputs=[chatbot, thread_id])
|
| 95 |
+
|
| 96 |
+
query_box.submit(
|
| 97 |
+
add_user_message,
|
| 98 |
+
inputs=[query_box, chatbot],
|
| 99 |
+
outputs=[query_box, chatbot],
|
| 100 |
+
queue=False,
|
| 101 |
+
).then(
|
| 102 |
+
stream_response,
|
| 103 |
+
inputs=[chatbot, jd_box, thread_id],
|
| 104 |
+
outputs=chatbot,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
if __name__ == "__main__":
|
| 109 |
+
logger.info("Model: %s | tracing: %s", SETTINGS.model, SETTINGS.tracing_enabled)
|
| 110 |
+
try:
|
| 111 |
+
demo.launch()
|
| 112 |
+
finally:
|
| 113 |
+
flush()
|
config.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Application configuration, loaded once from the environment."""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from functools import lru_cache
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from dotenv import load_dotenv
|
| 9 |
+
|
| 10 |
+
load_dotenv()
|
| 11 |
+
|
| 12 |
+
PROJECT_ROOT = Path(__file__).parent
|
| 13 |
+
|
| 14 |
+
DEFAULT_MODEL = "openai/gpt-oss-120b"
|
| 15 |
+
DEFAULT_TEMPERATURE = 0.0
|
| 16 |
+
DEFAULT_MAX_TOKENS = 2048
|
| 17 |
+
DEFAULT_DATA_DIR = "data"
|
| 18 |
+
DEFAULT_LANGFUSE_HOST = "https://cloud.langfuse.com"
|
| 19 |
+
DEFAULT_CHECKPOINT_DB = "checkpoints.sqlite"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class ConfigError(RuntimeError):
|
| 23 |
+
"""Raised when the environment is missing or misconfigured."""
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@dataclass(frozen=True)
|
| 27 |
+
class Settings:
|
| 28 |
+
groq_api_key: str
|
| 29 |
+
candidate_name: str
|
| 30 |
+
data_dir: Path
|
| 31 |
+
model: str
|
| 32 |
+
temperature: float
|
| 33 |
+
max_tokens: int
|
| 34 |
+
checkpoint_db: Path
|
| 35 |
+
langfuse_public_key: str
|
| 36 |
+
langfuse_secret_key: str
|
| 37 |
+
langfuse_host: str
|
| 38 |
+
|
| 39 |
+
@property
|
| 40 |
+
def tracing_enabled(self) -> bool:
|
| 41 |
+
"""Tracing turns itself on only when both Langfuse keys are present."""
|
| 42 |
+
return bool(self.langfuse_public_key and self.langfuse_secret_key)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _get_float(name, default):
|
| 46 |
+
raw = os.getenv(name)
|
| 47 |
+
if raw is None or not raw.strip():
|
| 48 |
+
return default
|
| 49 |
+
try:
|
| 50 |
+
return float(raw)
|
| 51 |
+
except ValueError:
|
| 52 |
+
raise ConfigError(f"{name} must be a number, got {raw!r}")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _get_int(name, default):
|
| 56 |
+
raw = os.getenv(name)
|
| 57 |
+
if raw is None or not raw.strip():
|
| 58 |
+
return default
|
| 59 |
+
try:
|
| 60 |
+
return int(raw)
|
| 61 |
+
except ValueError:
|
| 62 |
+
raise ConfigError(f"{name} must be an integer, got {raw!r}")
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _resolve_data_dir():
|
| 66 |
+
raw = os.getenv("DATA_DIR", "").strip() or DEFAULT_DATA_DIR
|
| 67 |
+
data_dir = Path(raw)
|
| 68 |
+
if not data_dir.is_absolute():
|
| 69 |
+
data_dir = PROJECT_ROOT / data_dir
|
| 70 |
+
|
| 71 |
+
if not data_dir.is_dir():
|
| 72 |
+
raise ConfigError(
|
| 73 |
+
f"DATA_DIR does not exist: {data_dir}\n"
|
| 74 |
+
f"Set DATA_DIR in .env to the folder holding your profile documents, "
|
| 75 |
+
f"or remove it to use the default ({PROJECT_ROOT / DEFAULT_DATA_DIR})."
|
| 76 |
+
)
|
| 77 |
+
if not any(data_dir.glob("*.md")):
|
| 78 |
+
raise ConfigError(
|
| 79 |
+
f"No .md documents found in {data_dir}\n"
|
| 80 |
+
f"Run pdf_2_markdown_converter.py to convert your PDFs first."
|
| 81 |
+
)
|
| 82 |
+
return data_dir
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@lru_cache(maxsize=1)
|
| 86 |
+
def get_settings() -> Settings:
|
| 87 |
+
api_key = os.getenv("GROQ_API_KEY", "").strip()
|
| 88 |
+
if not api_key:
|
| 89 |
+
raise ConfigError("GROQ_API_KEY is not set. Add it to your .env file.")
|
| 90 |
+
|
| 91 |
+
return Settings(
|
| 92 |
+
groq_api_key=api_key,
|
| 93 |
+
candidate_name=os.getenv("CANDIDATE_NAME", "").strip() or "the candidate",
|
| 94 |
+
data_dir=_resolve_data_dir(),
|
| 95 |
+
model=os.getenv("GROQ_MODEL", "").strip() or DEFAULT_MODEL,
|
| 96 |
+
temperature=_get_float("LLM_TEMPERATURE", DEFAULT_TEMPERATURE),
|
| 97 |
+
max_tokens=_get_int("LLM_MAX_TOKENS", DEFAULT_MAX_TOKENS),
|
| 98 |
+
checkpoint_db=PROJECT_ROOT / (
|
| 99 |
+
os.getenv("CHECKPOINT_DB", "").strip() or DEFAULT_CHECKPOINT_DB
|
| 100 |
+
),
|
| 101 |
+
langfuse_public_key=os.getenv("LANGFUSE_PUBLIC_KEY", "").strip(),
|
| 102 |
+
langfuse_secret_key=os.getenv("LANGFUSE_SECRET_KEY", "").strip(),
|
| 103 |
+
# LANGFUSE_HOST is the SDK's own name; LANGFUSE_BASE_URL is accepted as an alias.
|
| 104 |
+
langfuse_host=(
|
| 105 |
+
os.getenv("LANGFUSE_HOST", "").strip()
|
| 106 |
+
or os.getenv("LANGFUSE_BASE_URL", "").strip()
|
| 107 |
+
or DEFAULT_LANGFUSE_HOST
|
| 108 |
+
),
|
| 109 |
+
)
|
dataloader.py
CHANGED
|
@@ -1,16 +1,23 @@
|
|
| 1 |
-
from
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
class ProfileLoader:
|
| 4 |
-
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
|
| 8 |
-
data = ""
|
| 9 |
-
seperator = "-------"*20 + "\n"
|
| 10 |
-
md_files = glob(self.data_dir + "/*.md")
|
| 11 |
for md_file in md_files:
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
data += seperator
|
| 15 |
|
| 16 |
-
return
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
|
| 3 |
+
SEPARATOR = "\n\n" + "-" * 60 + "\n\n"
|
| 4 |
+
|
| 5 |
|
| 6 |
class ProfileLoader:
|
| 7 |
+
"""Loads the candidate's markdown profile documents into a single context string."""
|
| 8 |
+
|
| 9 |
+
def __init__(self, data_dir):
|
| 10 |
+
self.data_dir = Path(data_dir)
|
| 11 |
+
|
| 12 |
+
def load_and_format_markdown(self):
|
| 13 |
+
# Sorted so document order β and therefore model output β is reproducible.
|
| 14 |
+
md_files = sorted(self.data_dir.glob("*.md"))
|
| 15 |
+
if not md_files:
|
| 16 |
+
raise FileNotFoundError(f"No .md documents found in {self.data_dir}")
|
| 17 |
|
| 18 |
+
sections = []
|
|
|
|
|
|
|
|
|
|
| 19 |
for md_file in md_files:
|
| 20 |
+
content = md_file.read_text(encoding="utf-8").strip()
|
| 21 |
+
sections.append(f"# Source: {md_file.stem}\n\n{content}")
|
|
|
|
| 22 |
|
| 23 |
+
return SEPARATOR.join(sections)
|
graph.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LangGraph application graph.
|
| 2 |
+
|
| 3 |
+
Today the graph is a single node, which is deliberate: it buys checkpointed
|
| 4 |
+
conversation state (threads that survive a restart) and gives the planned
|
| 5 |
+
cover-letter flow (draft -> critique -> revise) somewhere to live without a
|
| 6 |
+
rewrite.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import sqlite3
|
| 10 |
+
from typing import Annotated, TypedDict
|
| 11 |
+
|
| 12 |
+
from langchain_groq import ChatGroq
|
| 13 |
+
from langgraph.checkpoint.sqlite import SqliteSaver
|
| 14 |
+
from langgraph.graph import START, StateGraph
|
| 15 |
+
from langgraph.graph.message import add_messages
|
| 16 |
+
|
| 17 |
+
from config import get_settings
|
| 18 |
+
from dataloader import ProfileLoader
|
| 19 |
+
from prompts import NO_JD_PLACEHOLDER, build_qa_prompt
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class ChatState(TypedDict):
|
| 23 |
+
# add_messages appends rather than overwrites, so each turn extends the thread.
|
| 24 |
+
messages: Annotated[list, add_messages]
|
| 25 |
+
job_description: str
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def build_llm():
|
| 29 |
+
settings = get_settings()
|
| 30 |
+
return ChatGroq(
|
| 31 |
+
api_key=settings.groq_api_key,
|
| 32 |
+
model=settings.model,
|
| 33 |
+
temperature=settings.temperature,
|
| 34 |
+
max_tokens=settings.max_tokens,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def build_graph():
|
| 39 |
+
settings = get_settings()
|
| 40 |
+
profile_data = ProfileLoader(settings.data_dir).load_and_format_markdown()
|
| 41 |
+
chain = build_qa_prompt() | build_llm()
|
| 42 |
+
|
| 43 |
+
def answer(state: ChatState):
|
| 44 |
+
history = state["messages"][:-1]
|
| 45 |
+
user_query = state["messages"][-1].content
|
| 46 |
+
response = chain.invoke({
|
| 47 |
+
"context_text": profile_data,
|
| 48 |
+
"job_description": state.get("job_description") or NO_JD_PLACEHOLDER,
|
| 49 |
+
"user_query": user_query,
|
| 50 |
+
"history": history,
|
| 51 |
+
})
|
| 52 |
+
return {"messages": [response]}
|
| 53 |
+
|
| 54 |
+
builder = StateGraph(ChatState)
|
| 55 |
+
builder.add_node("answer", answer)
|
| 56 |
+
builder.add_edge(START, "answer")
|
| 57 |
+
|
| 58 |
+
# check_same_thread=False: Gradio serves requests from a pool of threads.
|
| 59 |
+
conn = sqlite3.connect(str(settings.checkpoint_db), check_same_thread=False)
|
| 60 |
+
return builder.compile(checkpointer=SqliteSaver(conn))
|
main.py
DELETED
|
@@ -1,27 +0,0 @@
|
|
| 1 |
-
from langchain_core.prompts import ChatPromptTemplate
|
| 2 |
-
from langchain_groq import ChatGroq
|
| 3 |
-
from dataloader import ProfileLoader
|
| 4 |
-
from dotenv import load_dotenv
|
| 5 |
-
|
| 6 |
-
load_dotenv() # Load environment variables from .env file
|
| 7 |
-
|
| 8 |
-
profile_loader = ProfileLoader(data_dir="data")
|
| 9 |
-
# Load and format the Markdown content from the .md files
|
| 10 |
-
profile_data = profile_loader.load_and_format_markdown("data")
|
| 11 |
-
|
| 12 |
-
# 1. Define the system and user instructions
|
| 13 |
-
prompt = ChatPromptTemplate.from_messages([
|
| 14 |
-
("system", "You are an assistant that answers questions accurately based ONLY on the provided context."),
|
| 15 |
-
("user", "Context:\n<context>\n{context_text}\n</context>\n\nQuestion: {user_query}")
|
| 16 |
-
])
|
| 17 |
-
|
| 18 |
-
# 2. Format the prompt with your full Markdown string
|
| 19 |
-
llm = ChatGroq(model="openai/gpt-oss-120b", temperature=0, max_tokens=2048)
|
| 20 |
-
chain = prompt | llm
|
| 21 |
-
|
| 22 |
-
response = chain.invoke({
|
| 23 |
-
"context_text": profile_data,
|
| 24 |
-
"user_query": "What are the strongest and weakest skills of the candidate based on the provided context?"
|
| 25 |
-
})
|
| 26 |
-
|
| 27 |
-
print(response)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
observability.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Langfuse tracing.
|
| 2 |
+
|
| 3 |
+
Tracing is strictly optional: if the Langfuse keys are absent or the service is
|
| 4 |
+
unreachable, the app logs a warning and keeps working untraced. Observability
|
| 5 |
+
must never be able to take the application down.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import logging
|
| 9 |
+
|
| 10 |
+
from config import get_settings
|
| 11 |
+
|
| 12 |
+
logger = logging.getLogger(__name__)
|
| 13 |
+
|
| 14 |
+
_handler = None
|
| 15 |
+
_initialised = False
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _init():
|
| 19 |
+
global _handler, _initialised
|
| 20 |
+
if _initialised:
|
| 21 |
+
return
|
| 22 |
+
_initialised = True
|
| 23 |
+
|
| 24 |
+
settings = get_settings()
|
| 25 |
+
if not settings.tracing_enabled:
|
| 26 |
+
logger.info("Langfuse tracing disabled (LANGFUSE_PUBLIC_KEY / LANGFUSE_SECRET_KEY not set).")
|
| 27 |
+
return
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
from langfuse import Langfuse
|
| 31 |
+
from langfuse.langchain import CallbackHandler
|
| 32 |
+
|
| 33 |
+
Langfuse(
|
| 34 |
+
public_key=settings.langfuse_public_key,
|
| 35 |
+
secret_key=settings.langfuse_secret_key,
|
| 36 |
+
host=settings.langfuse_host,
|
| 37 |
+
)
|
| 38 |
+
_handler = CallbackHandler()
|
| 39 |
+
logger.info("Langfuse tracing enabled (%s).", settings.langfuse_host)
|
| 40 |
+
except Exception as exc:
|
| 41 |
+
logger.warning("Langfuse tracing unavailable, continuing without it: %s", exc)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def get_callbacks():
|
| 45 |
+
"""Callback list for LangChain/LangGraph config. Empty when tracing is off."""
|
| 46 |
+
_init()
|
| 47 |
+
return [_handler] if _handler else []
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def build_run_config(thread_id, job_description):
|
| 51 |
+
"""Runnable config: checkpoint thread plus Langfuse trace metadata."""
|
| 52 |
+
return {
|
| 53 |
+
"configurable": {"thread_id": thread_id},
|
| 54 |
+
"callbacks": get_callbacks(),
|
| 55 |
+
"run_name": "job_chat_qa",
|
| 56 |
+
"metadata": {
|
| 57 |
+
"langfuse_session_id": thread_id,
|
| 58 |
+
"langfuse_tags": ["job-chat", "with-jd" if job_description else "no-jd"],
|
| 59 |
+
"jd_loaded": bool(job_description),
|
| 60 |
+
"jd_words": len(job_description.split()) if job_description else 0,
|
| 61 |
+
},
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def flush():
|
| 66 |
+
"""Flush pending traces before shutdown."""
|
| 67 |
+
if not _handler:
|
| 68 |
+
return
|
| 69 |
+
try:
|
| 70 |
+
from langfuse import get_client
|
| 71 |
+
|
| 72 |
+
get_client().flush()
|
| 73 |
+
except Exception as exc:
|
| 74 |
+
logger.warning("Langfuse flush failed: %s", exc)
|
prompts.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
| 2 |
+
|
| 3 |
+
from config import get_settings
|
| 4 |
+
|
| 5 |
+
NO_JD_PLACEHOLDER = "(No job description loaded. The user has not selected a target role yet.)"
|
| 6 |
+
|
| 7 |
+
QA_SYSTEM_PROMPT = """You are the interview-preparation assistant for {candidate_name}, referred to below as "the candidate". You have been given the candidate's own career documents β resume, project write-ups, and volunteer experience β as your only source of truth about them.
|
| 8 |
+
|
| 9 |
+
This is a private tool the candidate uses to prepare for job applications and interviews. They are the only user. Your job is to make them better prepared, not to flatter them.
|
| 10 |
+
|
| 11 |
+
## Two sources, different authority
|
| 12 |
+
|
| 13 |
+
- CANDIDATE DOCUMENTS are the sole source of truth about the candidate. Never assert experience, skills, or outcomes not found there.
|
| 14 |
+
- The JOB DESCRIPTION, when present, is the target role being evaluated against. It describes what an employer wants β it says nothing about what the candidate has. Never let a requirement in the job description become an assumed fact about the candidate. A job description asking for Kubernetes is not evidence the candidate knows Kubernetes.
|
| 15 |
+
|
| 16 |
+
## Modes β infer which one is being asked for
|
| 17 |
+
|
| 18 |
+
1. ANALYSIS β questions about the candidate in the third person ("what are the weakest areas", "which project best shows systems depth"). Answer as an analyst evaluating the documented record. Be candid.
|
| 19 |
+
|
| 20 |
+
2. DRAFTING β requests for an answer the candidate could give to an interviewer or in an application ("how should I answer 'tell me about a time you handled conflict'", "write a STAR answer about the RAG project"). Produce a first-person answer in the candidate's voice, built only from documented experience.
|
| 21 |
+
|
| 22 |
+
3. FIT β questions pitting the candidate against a loaded job description ("am I a fit", "what will they push on", "what should I emphasize", "what am I missing"). Work requirement by requirement. For each meaningful requirement, state whether the documents show it is MET (with the specific evidence), PARTIAL (adjacent experience, and what the gap is), or MISSING. Then say what actually matters: which gaps are disqualifying versus learnable on the job, which strengths to lead with, and which weak points an interviewer is most likely to probe. Prioritize β do not just enumerate.
|
| 23 |
+
|
| 24 |
+
If a fit question is asked with no job description loaded, say so and ask the user to load one. When any request is ambiguous, choose ANALYSIS and offer to draft.
|
| 25 |
+
|
| 26 |
+
## Grounding rules β these are the ones that matter
|
| 27 |
+
|
| 28 |
+
Everything you assert about the candidate falls into one of three categories. Keep them distinct and never let the third one happen.
|
| 29 |
+
|
| 30 |
+
- STATED: written in the candidate documents. Assert it freely.
|
| 31 |
+
- INFERRED: a reasonable read of stated facts (e.g. concluding someone has production ML exposure because they shipped a deployed model). Allowed, but mark it β "based on X, it looks likeβ¦" β so the candidate can tell what is on paper versus what they would need to substantiate in an interview.
|
| 32 |
+
- UNSUPPORTED: metrics, employers, dates, tools, titles, or outcomes not in the documents. Never produce these, not even as plausible filler in a drafted answer. If a strong answer needs a number or detail the documents lack, leave an explicit placeholder describing what is needed and say why it matters.
|
| 33 |
+
|
| 34 |
+
If the documents genuinely do not cover something, say so directly and stop. "That is not in your materials" is a useful answer to someone preparing for an interview; a fabricated one is actively harmful, because they may repeat it to a real interviewer and be caught.
|
| 35 |
+
|
| 36 |
+
## Stance
|
| 37 |
+
|
| 38 |
+
- Be direct and specific. Cite the concrete project, role, or skill you are reasoning from.
|
| 39 |
+
- Do not inflate. If the evidence for a claim is thin, say it is thin. If a project is a tutorial-scale exercise rather than production work, do not describe it as production work.
|
| 40 |
+
- Surface gaps unprompted when they are relevant to what was asked β a missing skill for a target role, an unexplained timeline gap, an achievement stated without a measurable outcome.
|
| 41 |
+
- No praise-padding, no "great question", no summarizing what the user already said back to them.
|
| 42 |
+
|
| 43 |
+
## Output
|
| 44 |
+
|
| 45 |
+
- Lead with the answer. No preamble.
|
| 46 |
+
- Match length to the question β a factual lookup gets a sentence or two, a positioning critique or fit analysis gets a short structured breakdown.
|
| 47 |
+
- Prose by default. Use bullets only for genuinely list-shaped content.
|
| 48 |
+
- Drafted interview answers: first person, natural spoken register, no corporate filler. Keep them to a length a person can actually say out loud.
|
| 49 |
+
|
| 50 |
+
## Candidate documents
|
| 51 |
+
|
| 52 |
+
<candidate_documents>
|
| 53 |
+
{context_text}
|
| 54 |
+
</candidate_documents>
|
| 55 |
+
|
| 56 |
+
## Target job description
|
| 57 |
+
|
| 58 |
+
<job_description>
|
| 59 |
+
{job_description}
|
| 60 |
+
</job_description>
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def build_qa_prompt() -> ChatPromptTemplate:
|
| 65 |
+
return ChatPromptTemplate.from_messages([
|
| 66 |
+
("system", QA_SYSTEM_PROMPT),
|
| 67 |
+
MessagesPlaceholder("history"),
|
| 68 |
+
("user", "{user_query}"),
|
| 69 |
+
]).partial(candidate_name=get_settings().candidate_name)
|
requirements-ingest.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Only needed to run pdf_2_markdown_converter.py (PDF -> Markdown).
|
| 2 |
+
# Pulls in torch and other heavy deps; the chat app does not need these.
|
| 3 |
+
docling==2.118.0
|
| 4 |
+
tqdm==4.69.0
|
requirements.txt
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==6.22.0
|
| 2 |
+
langchain==1.3.14
|
| 3 |
+
langchain-core==1.5.1
|
| 4 |
+
langchain-groq==1.1.3
|
| 5 |
+
langgraph==1.2.10
|
| 6 |
+
langgraph-checkpoint-sqlite==3.1.1
|
| 7 |
+
langfuse==4.14.3
|
| 8 |
+
python-dotenv==1.2.2
|
| 9 |
+
|
| 10 |
+
# Makes Python trust the OS certificate store. Required on networks that do
|
| 11 |
+
# TLS inspection (corporate proxy / antivirus); harmless elsewhere.
|
| 12 |
+
pip-system-certs==5.3
|