Spaces:
Configuration error
Configuration error
feat
Browse filesFiles changed (22)
- .dockerignore+7
- .env.example+2
- .gitignore+5
- .python-versionAdded+1
- Dockerfile+18-5
- README.md+46-20
- frontend/index.htmlAdded+12
- frontend/package-lock.jsonAdded
- frontend/package.jsonAdded+23
- frontend/src/main.tsxAdded+804
- frontend/src/styles.cssAdded+856
- frontend/tsconfig.jsonAdded+21
- frontend/vite.config.tsAdded+16
- render.yamlAdded+23
- requirements.txt+4-2
- scripts/download_chunks.pyAdded+42
- server-8010.err.logAdded+91
- server-8010.logAdded
- src/__init__.pyAdded+1
- src/app.py+406-28
- src/server.pyAdded+197
- src/streamlit_app.pyDeleted-331
1 unmodified line2345671 unmodified line91011121 unmodified linevenvENVenv__pycache__*.py[cod].env1 unmodified line.streamlit.vscode.ideasrc/sermon_chunks.zip1 unmodified line234567891 unmodified line1112131415161718191 unmodified linevenvENVenvfrontend/node_modulesfrontend/dist__pycache__*.py[cod].env1 unmodified line.streamlit.vscode.ideasrc/sermonssrc/sermons_allsrc/sermon_chunks.pklsrc/sermon_chunks_backup.pklsrc/sermon_chunks.zipsrc/web
123456LLM_PROVIDER=groqGROQ_MODEL=llama-3.3-70b-versatileGROQ_API_KEY=replace-with-your-rotated-groq-keyGOOGLE_API_KEY=replace-with-your-google-keyPINECONE_API_KEY=replace-with-your-pinecone-key12345678APP_PASSWORD=replace-with-a-shared-passwordLLM_PROVIDER=groqGROQ_MODEL=llama-3.3-70b-versatileGROQ_API_KEY=replace-with-your-rotated-groq-keyGOOGLE_API_KEY=replace-with-your-google-keyPINECONE_API_KEY=replace-with-your-pinecone-keySERMON_CHUNKS_URL=replace-with-your-google-drive-or-direct-download-url
23 unmodified lines24252627282913 unmodified lines4344454647484923 unmodified linesvenv/ENV/env/# Environment Variables.env13 unmodified lines# Project specificsrc/sermons/src/sermons_all/src/sermon_chunks_backup.pklsrc/out.txtsrc/scratch_*23 unmodified lines242526272829303113 unmodified lines4546474849505152535423 unmodified linesvenv/ENV/env/frontend/node_modules/frontend/dist/# Environment Variables.env13 unmodified lines# Project specificsrc/sermons/src/sermons_all/src/sermon_chunks.pklsrc/sermon_chunks_backup.pklsrc/web/src/feedback_log.jsonlsrc/out.txtsrc/scratch_*
13.111235 unmodified lines91011121314151617181920FROM python:3.11-slimWORKDIR /app5 unmodified lines&& rm -rf /var/lib/apt/lists/*COPY requirements.txt ./COPY src/ ./src/RUN pip3 install -r requirements.txtEXPOSE 8501HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/healthENTRYPOINT ["streamlit", "run", "src/streamlit_app.py", "--server.port=8501", "--server.address=0.0.0.0"]12345678910111213145 unmodified lines2021222324252627282930313233FROM node:22-slim AS frontend-buildWORKDIR /app/frontendCOPY frontend/package*.json ./RUN npm installCOPY frontend/ ./RUN npm run buildFROM python:3.11-slimWORKDIR /app5 unmodified lines&& rm -rf /var/lib/apt/lists/*COPY requirements.txt ./RUN pip install --no-cache-dir -r requirements.txtCOPY src/ ./src/COPY scripts/ ./scripts/COPY --from=frontend-build /app/src/web ./src/webEXPOSE 8000HEALTHCHECK CMD curl --fail http://localhost:${PORT:-8000}/api/health || exit 1CMD ["sh", "-c", "python scripts/download_chunks.py && uvicorn src.server:api --host 0.0.0.0 --port ${PORT:-8000}"]
1234567891011121314151617181920---title: 7th Handleemoji: πcolorFrom: redcolorTo: redsdk: dockerapp_port: 8501tags:- streamlitpinned: falseshort_description: Streamlit template spacelicense: mit---# Welcome to Streamlit!Edit `/src/streamlit_app.py` to customize this app to your heart's desire. :heart:If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [communityforums](https://discuss.streamlit.io).12345678910111213141516171819202122232425262728293031323334353637383940414243444546# The 7th HandleProduction RAG app for grounded sermon research.## Architecture- FastAPI serves the API and built React assets.- React/Vite provides the dark monochrome chat UI.- Pinecone and BM25 provide hybrid retrieval.- Groq generates citation-bound answers.- `sermon_chunks.pkl` is downloaded at startup from `SERMON_CHUNKS_URL` when it is not present.## Required Environment```envAPP_PASSWORD=choose-a-shared-passwordLLM_PROVIDER=groqGROQ_MODEL=llama-3.3-70b-versatileGROQ_API_KEY=your-rotated-groq-keyPINECONE_API_KEY=your-pinecone-keySERMON_CHUNKS_URL=your-google-drive-or-direct-download-url```## Local Backend```bashpip install -r requirements.txtpython scripts/download_chunks.pyuvicorn src.server:api --host 0.0.0.0 --port 8000```## Local Frontend```bashcd frontendnpm installnpm run dev```Vite proxies `/api` requests to `http://localhost:8000`.## ProductionDeploy with Render as a Docker Web Service. The included `render.yaml` sets the Docker service, health check, and required environment variable names.The production container builds the React frontend, installs Python dependencies, downloads sermon chunks at startup, then starts Uvicorn on `$PORT`.
123456789101112<!doctype html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>The 7th Handle</title> </head> <body> <div id="root"></div> <script type="module" src="/src/main.tsx"></script> </body></html>1234567891011121314151617181920212223{ "name": "the-7th-handle-ui", "private": true, "version": "1.0.0", "type": "module", "scripts": { "dev": "vite --host 0.0.0.0", "build": "tsc && vite build", "preview": "vite preview --host 0.0.0.0" }, "dependencies": { "react": "^19.0.0", "react-dom": "^19.0.0", "react-markdown": "^10.0.0" }, "devDependencies": { "@types/react": "^19.0.0", "@types/react-dom": "^19.0.0", "@vitejs/plugin-react": "^5.0.0", "typescript": "^5.8.0", "vite": "^7.0.0" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804import React from "react";import { createRoot } from "react-dom/client";import ReactMarkdown from "react-markdown";import "./styles.css";
type AnswerMode = "Strict Mode" | "Study Mode" | "Summary Mode";type AppMode = "chat" | "conversation" | "search";type GroundingStatus = "supported" | "partial" | "insufficient" | "pending" | "unknown";
type SourceDoc = { source: string; paragraph: string | number; content: string; full_text?: string; retrieval_origin: string; retrieval_rank: string | number; messagehub_url: string;};
type Diagnostics = Record<string, unknown>;
type Message = { id: string; role: "user" | "assistant"; content: string; question?: string; appMode?: AppMode; answerMode?: AnswerMode; groundingStatus?: GroundingStatus; diagnostics?: Diagnostics; sources?: SourceDoc[]; pending?: boolean; loadingStage?: "Retrieving" | "Checking grounding" | "Generating";};
type SseEvent = { event: string; data: Record<string, unknown>;};
const PASSWORD_KEY = "the7thhandle.password";
const quickTopics = [ ["Seven Seals", "what are the seven seals? list each seal and state its events and meaning"], ["Seven Thunders", "what are the seven thunders?"], ["Serpent's Seed", "What is the relationship between the Serpent's Seed and Cain?"], ["Adoption", "Summarize the Adoption series."], ["Demonology", "Summarize the Demonology series."], ["Church Ages", "Summarize the seven church ages."],];
const modeOptions: Array<{ value: AppMode; title: string; description: string;}> = [ { value: "chat", title: "Chat", description: "Single-turn answers from retrieved sermon excerpts.", }, { value: "conversation", title: "Conversational", description: "Rewrites follow-ups into standalone retrieval questions.", }, { value: "search", title: "Search", description: "Find matching paragraphs without generation.", },];
function id() { return `${Date.now()}-${Math.random().toString(16).slice(2)}`;}
function getStoredPassword() { return sessionStorage.getItem(PASSWORD_KEY) || "";}
function App() { const [messages, setMessages] = React.useState<Message[]>([]); const [appMode, setAppMode] = React.useState<AppMode>("chat"); const [answerMode, setAnswerMode] = React.useState<AnswerMode>("Strict Mode"); const [sermonScope, setSermonScope] = React.useState(""); const [prompt, setPrompt] = React.useState(""); const [searchQuery, setSearchQuery] = React.useState(""); const [searchResults, setSearchResults] = React.useState<SourceDoc[]>([]); const [searchDiagnostics, setSearchDiagnostics] = React.useState<Diagnostics>({}); const [searchSearched, setSearchSearched] = React.useState(false); const [searchError, setSearchError] = React.useState(""); const [password, setPassword] = React.useState(getStoredPassword); const [passwordRequired, setPasswordRequired] = React.useState(true); const [authError, setAuthError] = React.useState(""); const [busy, setBusy] = React.useState(false); const promptInputRef = React.useRef<HTMLInputElement>(null); const searchInputRef = React.useRef<HTMLInputElement>(null);
React.useEffect(() => { fetch("/api/health") .then((res) => res.json()) .then((data) => setPasswordRequired(Boolean(data.password_required))) .catch(() => setPasswordRequired(true)); }, []);
const authenticated = !passwordRequired || Boolean(password); const activeMode = modeOptions.find((mode) => mode.value === appMode) || modeOptions[0];
function focusModeInput(mode: AppMode = appMode) { window.setTimeout(() => { if (mode === "search") { searchInputRef.current?.focus(); } else { promptInputRef.current?.focus(); } }, 0); }
function changeAppMode(mode: AppMode) { setAppMode(mode); focusModeInput(mode); }
async function submitQuestion(rawQuestion: string) { const question = rawQuestion.trim(); if (!question || busy) return; if (appMode === "search") { await submitSearch(question); return; }
setAuthError(""); setBusy(true); setPrompt("");
const userMessage: Message = { id: id(), role: "user", content: question, appMode }; const assistantId = id(); const assistantMessage: Message = { id: assistantId, role: "assistant", content: "", question, appMode, answerMode, groundingStatus: "pending", diagnostics: {}, sources: [], pending: true, loadingStage: "Retrieving", };
setMessages((current) => [...current, userMessage, assistantMessage]);
try { await runStreamingAnswer(question, assistantId, appMode === "conversation"); } catch (error) { const message = error instanceof Error ? error.message : "Request failed"; if (message.includes("401")) { sessionStorage.removeItem(PASSWORD_KEY); setPassword(""); setAuthError("Password rejected. Enter the current app password."); } patchMessage(assistantId, { content: `Request failed: ${message}`, groundingStatus: "insufficient", pending: false, loadingStage: undefined, }); } finally { setBusy(false); } }
function patchMessage(messageId: string, patch: Partial<Message>) { setMessages((current) => current.map((message) => (message.id === messageId ? { ...message, ...patch } : message)), ); }
function authHeaders(): Record<string, string> { return password ? { "X-App-Password": password } : {}; }
async function submitSearch(rawQuery: string) { const question = rawQuery.trim(); if (!question || busy) return;
setAuthError(""); setSearchError(""); setBusy(true); setSearchQuery(question); setSearchSearched(true); setSearchResults([]); setSearchDiagnostics({ stage: "Retrieving" });
try { const params = new URLSearchParams({ q: question }); const res = await fetch(`/api/search?${params.toString()}`, { headers: authHeaders(), }); if (!res.ok) throw new Error(`${res.status} ${res.statusText}`); const data = await res.json(); setSearchResults(data.results || []); setSearchDiagnostics({ source_count: data.results.length, debug_log: data.debug_log, query: data.query, }); } catch (error) { const message = error instanceof Error ? error.message : "Request failed"; if (message.includes("401")) { sessionStorage.removeItem(PASSWORD_KEY); setPassword(""); setAuthError("Password rejected. Enter the current app password."); } setSearchError(message); setSearchDiagnostics({}); } finally { setBusy(false); } }
function conversationHistory() { return messages .filter((message) => !message.pending && message.content.trim()) .slice(-8) .map((message) => { const codes = sourceCodesFromSources(message.sources || []); const sourceNote = codes.length ? `\nCITED_SERMONS: ${codes.join(", ")}` : ""; return { role: message.role, content: `${message.content}${sourceNote}`, }; }); }
async function runStreamingAnswer( question: string, assistantId: string, conversationMode: boolean, ) { const res = await fetch("/api/answer/stream", { method: "POST", headers: { "Content-Type": "application/json", ...authHeaders(), }, body: JSON.stringify({ question, answer_mode: answerMode, sermon_scope: sermonScope, conversation_mode: conversationMode, history: conversationMode ? conversationHistory() : [], }), }); if (!res.ok || !res.body) throw new Error(`${res.status} ${res.statusText}`);
let fullAnswer = ""; for await (const event of readSse(res.body)) { if (event.event === "metadata") { patchMessage(assistantId, { diagnostics: event.data.diagnostics as Diagnostics, sources: (event.data.sources as SourceDoc[]) || [], groundingStatus: (event.data.grounding_status as GroundingStatus) || "pending", loadingStage: "Checking grounding", }); } if (event.event === "token") { fullAnswer += String(event.data.text || ""); patchMessage(assistantId, { content: fullAnswer, loadingStage: "Generating" }); } if (event.event === "done") { patchMessage(assistantId, { content: String(event.data.answer || fullAnswer), diagnostics: event.data.diagnostics as Diagnostics, sources: (event.data.sources as SourceDoc[]) || [], groundingStatus: (event.data.grounding_status as GroundingStatus) || "unknown", pending: false, loadingStage: undefined, }); } if (event.event === "error") { throw new Error(String(event.data.detail || "Streaming failed")); } } }
function savePassword(value: string) { sessionStorage.setItem(PASSWORD_KEY, value); setPassword(value); setAuthError(""); }
return ( <main className={`app-shell mode-${appMode}`}> {passwordRequired && !authenticated ? ( <PasswordGate onSubmit={savePassword} error={authError} /> ) : null}
<aside className="rail"> <div className="brand"> <div className="label">The 7th Handle</div> <h1>Grounded sermon research</h1> <p>Generated answers stay tied to retrieved excerpts and visible references.</p> </div>
<div className="mode-block"> <span>Workspace</span> <div className="mode-grid" role="tablist" aria-label="Research mode"> {modeOptions.map((mode) => ( <button key={mode.value} type="button" role="tab" aria-selected={appMode === mode.value} className={appMode === mode.value ? "mode-card active" : "mode-card"} onClick={() => changeAppMode(mode.value)} > <strong>{mode.title}</strong> <small>{mode.description}</small> </button> ))} </div> </div>
<Control label="Answer mode"> <select value={answerMode} disabled={appMode === "search"} onChange={(event) => setAnswerMode(event.target.value as AnswerMode)} > <option>Strict Mode</option> <option>Study Mode</option> <option>Summary Mode</option> </select> </Control>
<Control label="Target sermon code"> <input value={sermonScope} disabled={appMode === "search"} onChange={(event) => setSermonScope(event.target.value)} placeholder="63-0324E" /> </Control>
<div className="quick-list"> <span>Quick topics</span> {quickTopics.map(([label, question]) => ( <button key={label} type="button" onClick={() => submitQuestion(question)}> {label} </button> ))} </div>
<button className="ghost" type="button" onClick={() => { setMessages([]); setSearchResults([]); setSearchDiagnostics({}); setSearchSearched(false); setSearchError(""); }} > Clear screen </button> {passwordRequired ? ( <button className="ghost" type="button" onClick={() => { sessionStorage.removeItem(PASSWORD_KEY); setPassword(""); }} > Lock app </button> ) : null} </aside>
<section className={appMode === "search" ? "chat-pane search-pane" : "chat-pane"}> <div className="top-stack"> <header className="topbar"> <div> <div className="label">{activeMode.title}</div> <h2>{modeHeading(appMode)}</h2> <p>{activeMode.description}</p> </div> <div className="api-pill">{passwordRequired ? "Protected" : "Local open"}</div> </header> {appMode !== "search" ? ( <div className={`mode-strip ${appMode === "conversation" ? "conversation-strip" : "chat-strip"}`}> {appMode === "conversation" ? "Conversation memory is on. Follow-up rewrites appear with the answer evidence." : "Single-turn chat. Each question retrieves fresh evidence without prior turns."} </div> ) : null} </div>
{appMode === "search" ? ( <SearchView query={searchQuery} results={searchResults} diagnostics={searchDiagnostics} searched={searchSearched} error={searchError} busy={busy} authenticated={authenticated} inputRef={searchInputRef} onQueryChange={setSearchQuery} onSearch={submitSearch} /> ) : ( <> <section className={`thread ${appMode === "conversation" ? "conversation-thread" : ""}`} aria-live="polite"> {messages.length === 0 ? <EmptyState mode={appMode} onPick={submitQuestion} /> : null} {messages.map((message) => ( <MessageCard key={message.id} message={message} /> ))} </section>
<form className={`composer ${appMode === "conversation" ? "conversation-composer" : ""}`} onSubmit={(event) => { event.preventDefault(); submitQuestion(prompt); }} > <input ref={promptInputRef} value={prompt} onChange={(event) => setPrompt(event.target.value)} placeholder={composerPlaceholder(appMode)} disabled={busy || !authenticated} /> <button type="submit" disabled={busy || !prompt.trim() || !authenticated}> {busy ? "Working" : "Ask"} </button> </form> </> )} </section> </main> );}
function modeHeading(mode: AppMode) { if (mode === "conversation") return "Ask follow-ups with visible rewriting"; if (mode === "search") return "Search the sermon archive"; return "Ask a grounded question";}
function composerPlaceholder(mode: AppMode) { if (mode === "conversation") return "Ask a follow-up..."; return "Ask a question...";}
function Control({ label, children }: { label: string; children: React.ReactNode }) { return ( <label className="control"> <span>{label}</span> {children} </label> );}
function PasswordGate({ onSubmit, error }: { onSubmit: (password: string) => void; error: string }) { const [value, setValue] = React.useState(""); return ( <div className="gate"> <form className="gate-panel" onSubmit={(event) => { event.preventDefault(); if (value.trim()) onSubmit(value.trim()); }} > <div className="label">Protected access</div> <h2>Enter the app password</h2> <p>This deployment is gated before it sends questions to the RAG API.</p> <input type="password" autoFocus value={value} onChange={(event) => setValue(event.target.value)} placeholder="App password" /> {error ? <div className="form-error">{error}</div> : null} <button type="submit">Unlock</button> </form> </div> );}
function SearchView({ query, results, diagnostics, searched, error, busy, authenticated, inputRef, onQueryChange, onSearch,}: { query: string; results: SourceDoc[]; diagnostics: Diagnostics; searched: boolean; error: string; busy: boolean; authenticated: boolean; inputRef: React.RefObject<HTMLInputElement | null>; onQueryChange: (value: string) => void; onSearch: (query: string) => void;}) { const debugLog = Array.isArray(diagnostics.debug_log) ? diagnostics.debug_log : []; return ( <section className="search-workspace" aria-live="polite"> <form className="search-form" onSubmit={(event) => { event.preventDefault(); onSearch(query); }} > <div className="search-input-row"> <input ref={inputRef} value={query} onChange={(event) => onQueryChange(event.target.value)} placeholder="Search exact words, sermon titles, dates, or topics..." disabled={busy || !authenticated} /> <button type="submit" disabled={busy || !query.trim() || !authenticated}> {busy ? "Searching" : "Search"} </button> </div> <div className="search-hints"> Try a phrase like <span>white horse</span>, a topic like <span>Serpent's Seed</span>, or a date code like <span>63-0318</span>. </div> </form>
{busy ? ( <div className="search-stage"> <LoadingStage stage="Retrieving" /> </div> ) : null}
{error ? <div className="search-error">Search failed: {error}</div> : null}
{!searched ? ( <div className="search-empty"> <div className="label">Archive search</div> <h2>Find paragraphs first, then open the source text.</h2> </div> ) : null}
{searched && !busy ? ( <div className="search-summary"> <strong>{results.length}</strong> <span>paragraphs</span> <strong>{distinctSourceCount(results)}</strong> <span>sermons</span> {debugLog.length ? <small>{debugLog.join(" - ")}</small> : null} </div> ) : null}
{searched && !busy && results.length ? <SearchResultGroups results={results} /> : null}
{searched && !busy && !results.length && !error ? ( <div className="search-empty"> <div className="label">No results</div> <h2>Try fewer words or a different sermon title.</h2> </div> ) : null} </section> );}
function SearchResultGroups({ results }: { results: SourceDoc[] }) { const groups = results.reduce<Record<string, SourceDoc[]>>((acc, source) => { const key = source.source || "Unknown source"; acc[key] = acc[key] || []; acc[key].push(source); return acc; }, {});
return ( <div className="search-results"> {Object.entries(groups).map(([source, items]) => ( <section className="search-result-group" key={source}> <div className="result-group-heading"> <h3>{source}</h3> <span>{items.length} paragraphs</span> </div> <div className="result-list"> {items.map((item, index) => ( <article className="result-card" key={`${source}-${item.paragraph}-${index}`}> <a href={item.messagehub_url || "#"} target="_blank" rel="noreferrer"> Para {item.paragraph || "-"} </a> <p>{item.full_text || item.content}</p> </article> ))} </div> </section> ))} </div> );}
function EmptyState({ mode, onPick }: { mode: AppMode; onPick: (question: string) => void }) { return ( <div className={mode === "conversation" ? "empty conversation-empty" : "empty"}> <div className="label">{mode === "conversation" ? "Conversation" : "Start with a grounded question"}</div> <h2>{mode === "conversation" ? "Follow up on the current thread." : "Choose a topic or ask directly."}</h2> <div className="empty-actions"> {quickTopics.slice(0, 3).map(([label, question]) => ( <button key={label} type="button" onClick={() => onPick(question)}> {label} </button> ))} </div> </div> );}
function MessageCard({ message }: { message: Message }) { return ( <article className={`message ${message.role}`}> <div className="avatar">{message.role === "user" ? "You" : "RAG"}</div> <div className="bubble"> {message.pending ? <LoadingStage stage={message.loadingStage || "Retrieving"} /> : null} <div className="message-content"> {message.role === "assistant" ? ( <ReactMarkdown>{message.content}</ReactMarkdown> ) : ( <p>{message.content}</p> )} </div> {message.role === "assistant" ? <EvidencePanel message={message} /> : null} </div> </article> );}
function LoadingStage({ stage }: { stage: NonNullable<Message["loadingStage"]> }) { return ( <div className="stage-line"> <span aria-hidden="true" /> {stage} </div> );}
function EvidencePanel({ message }: { message: Message }) { const diagnostics = message.diagnostics || {}; const sources = message.sources || []; const retrievalQuestion = typeof diagnostics.retrieval_question === "string" ? diagnostics.retrieval_question : ""; const showRetrievalQuestion = message.appMode === "conversation" && retrievalQuestion && normalizeText(retrievalQuestion) !== normalizeText(message.question || ""); return ( <div className="evidence"> {showRetrievalQuestion ? ( <div className="rewrite-card"> <span>Standalone retrieval question</span> <p>{retrievalQuestion}</p> </div> ) : null}
<div className="metrics"> <Metric label="Grounding" value={labelStatus(message.groundingStatus)} /> <Metric label="Excerpts" value={String(diagnostics.source_count ?? sources.length)} /> <Metric label="Sermons" value={String(diagnostics.distinct_sermon_count ?? "-")} /> <Metric label="Pinecone" value={String(diagnostics.pinecone_status ?? "unknown")} /> <Metric label="Latency" value={`${diagnostics.total_latency ?? "-"}s`} /> </div>
<details> <summary>References</summary> <GroupedSources sources={sources} /> </details>
<details> <summary>Advanced diagnostics</summary> <pre>{JSON.stringify({ diagnostics, sources }, null, 2)}</pre> </details> </div> );}
function Metric({ label, value }: { label: string; value: string }) { return ( <div className="metric"> <span>{label}</span> <strong>{value}</strong> </div> );}
function labelStatus(status: GroundingStatus | undefined) { if (status === "supported") return "Supported"; if (status === "partial") return "Partial"; if (status === "insufficient") return "Insufficient"; if (status === "pending") return "Pending"; return "Unknown";}
function normalizeText(value: string) { return value.replace(/\s+/g, " ").trim().toLowerCase();}
function sourceCodesFromSources(sources: SourceDoc[]) { const codes = new Set<string>(); for (const source of sources) { const match = source.source.match(/\b\d{2}-\d{4}[A-Z]?\b/i); if (match) codes.add(match[0].toUpperCase()); } return [...codes];}
function distinctSourceCount(sources: SourceDoc[]) { return new Set(sources.map((source) => source.source || "Unknown source")).size;}
function GroupedSources({ sources }: { sources: SourceDoc[] }) { if (!sources.length) return <div className="muted block">No source excerpts were returned.</div>; const groups = sources.reduce<Record<string, SourceDoc[]>>((acc, source) => { const key = source.source || "Unknown source"; acc[key] = acc[key] || []; acc[key].push(source); return acc; }, {});
return ( <div className="source-groups"> {Object.entries(groups).map(([source, items]) => ( <details key={source} className="source-group"> <summary> {source} <span>{items.length} excerpts</span> </summary> <div className="source-list"> {items.map((item, index) => ( <div className="source-item" key={`${source}-${item.paragraph}-${index}`}> <a href={item.messagehub_url || "#"} target="_blank" rel="noreferrer"> Para {item.paragraph || "-"} </a> <span> {item.retrieval_origin || "unknown"} - rank {item.retrieval_rank || "-"} </span> <p>{item.full_text || item.content}</p> </div> ))} </div> </details> ))} </div> );}
async function* readSse(stream: ReadableStream<Uint8Array>): AsyncGenerator<SseEvent> { const reader = stream.getReader(); const decoder = new TextDecoder(); let buffer = "";
while (true) { const { value, done } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const parts = buffer.split("\n\n"); buffer = parts.pop() || ""; for (const raw of parts) { const event = parseSse(raw); if (event) yield event; } }
if (buffer.trim()) { const event = parseSse(buffer); if (event) yield event; }}
function parseSse(raw: string): SseEvent | null { let event = "message"; const dataLines: string[] = []; for (const line of raw.split("\n")) { if (line.startsWith("event:")) event = line.slice(6).trim(); if (line.startsWith("data:")) dataLines.push(line.slice(5).trim()); } if (!dataLines.length) return null; return { event, data: JSON.parse(dataLines.join("\n")) };}
createRoot(document.getElementById("root")!).render(<App />);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856:root { color-scheme: dark; --bg: #0f0f10; --panel: #171719; --panel-2: #1d1d20; --panel-3: #242428; --text: #f2f2f3; --muted: #a7a7ac; --subtle: #73737a; --line: #303036; --line-strong: #4a4a52; --shadow: 0 24px 80px rgba(0, 0, 0, 0.45);}
* { box-sizing: border-box;}
html,body,#root { height: 100%; min-height: 100%;}
body { margin: 0; overflow: hidden; color: var(--text); background: var(--bg); font-family: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;}
button,input,select { font: inherit;}
button { cursor: pointer;}
.app-shell { display: grid; grid-template-columns: 300px minmax(0, 1fr); height: 100vh; min-height: 100vh; overflow: hidden;}
.rail { display: flex; flex-direction: column; gap: 18px; min-height: 0; overflow-y: auto; padding: 22px; border-right: 1px solid var(--line); background: #121214;}
.brand { display: grid; gap: 10px; padding-bottom: 8px;}
.label { color: var(--muted); font-size: 0.74rem; font-weight: 700; letter-spacing: 0.12em; text-transform: uppercase;}
h1,h2,p { margin: 0;}
h1 { max-width: 14rem; font-size: 1.55rem; line-height: 1.08; letter-spacing: 0;}
h2 { font-size: 1.45rem; line-height: 1.18; letter-spacing: 0;}
p { color: var(--muted); line-height: 1.55;}
.control { display: grid; gap: 8px; color: var(--muted); font-size: 0.86rem; font-weight: 650;}
.mode-block { display: grid; gap: 9px;}
.mode-block > span { color: var(--muted); font-size: 0.86rem; font-weight: 650;}
.mode-grid { display: grid; gap: 8px;}
.mode-card { display: grid; gap: 4px; width: 100%; padding: 11px; border: 1px solid var(--line); border-radius: 12px; color: var(--muted); background: var(--panel); text-align: left;}
.mode-card strong { color: var(--text); font-size: 0.95rem;}
.mode-card small { color: var(--muted); line-height: 1.35;}
.mode-card:hover,.mode-card.active { border-color: var(--line-strong); background: var(--panel-2);}
input,select { width: 100%; min-height: 42px; padding: 10px 12px; border: 1px solid var(--line); border-radius: 10px; color: var(--text); background: var(--panel); outline: none;}
input:focus,select:focus { border-color: var(--line-strong);}
input:disabled,select:disabled { color: var(--subtle); background: #141416;}
.quick-list { display: grid; gap: 8px;}
.quick-list span { color: var(--muted); font-size: 0.86rem; font-weight: 650;}
.quick-list button,.ghost,.empty-actions button { min-height: 40px; border: 1px solid var(--line); border-radius: 10px; color: var(--text); background: var(--panel); text-align: left;}
.quick-list button,.ghost { padding: 9px 11px;}
.quick-list button:hover,.ghost:hover,.empty-actions button:hover,.search-form button:hover { border-color: var(--line-strong); background: var(--panel-2);}
button:disabled { cursor: not-allowed; opacity: 0.48;}
.ghost { text-align: center;}
.chat-pane { display: grid; grid-template-rows: auto minmax(0, 1fr) auto; height: 100vh; min-width: 0; min-height: 0; overflow: hidden;}
.search-pane { grid-template-rows: auto minmax(0, 1fr);}
.top-stack { min-width: 0;}
.topbar { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 22px 26px; border-bottom: 1px solid var(--line); background: rgba(15, 15, 16, 0.92);}
.topbar p { max-width: 620px; margin-top: 5px; font-size: 0.92rem;}
.mode-strip { padding: 10px 26px; border-bottom: 1px solid var(--line); color: var(--muted); background: #101012; font-size: 0.9rem;}
.conversation-strip { border-bottom-style: dashed; background: #141416;}
.api-pill { flex: 0 0 auto; padding: 8px 10px; border: 1px solid var(--line); border-radius: 999px; color: var(--muted); background: var(--panel); font-size: 0.84rem;}
.thread { display: flex; flex-direction: column; gap: 18px; min-height: 0; overflow-y: auto; padding: 24px 26px;}
.mode-conversation .topbar { background: #121214;}
.conversation-thread { background: linear-gradient(90deg, rgba(255, 255, 255, 0.035) 1px, transparent 1px) 0 0 / 32px 32px, var(--bg);}
.conversation-empty { border-style: dashed;}
.empty { display: grid; gap: 16px; max-width: 780px; padding: 24px; border: 1px solid var(--line); border-radius: 16px; background: var(--panel); box-shadow: var(--shadow);}
.empty-actions { display: flex; flex-wrap: wrap; gap: 10px;}
.empty-actions button { padding: 9px 12px;}
.search-workspace { min-height: 0; overflow-y: auto; padding: 26px;}
.search-form { display: grid; gap: 10px; max-width: 1040px; padding: 18px; border: 1px solid var(--line); border-radius: 18px; background: var(--panel); box-shadow: var(--shadow);}
.search-input-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 10px;}
.search-input-row input { min-height: 58px; border-radius: 14px; font-size: 1.02rem;}
.search-form button { min-width: 112px; border: 1px solid var(--line-strong); border-radius: 14px; color: var(--bg); background: var(--text); font-weight: 750;}
.search-hints { color: var(--muted); font-size: 0.9rem;}
.search-hints span { color: var(--text);}
.search-stage,.search-error,.search-empty,.search-summary,.search-result-group { max-width: 1040px;}
.search-stage { margin-top: 16px;}
.search-error { margin-top: 16px; padding: 12px; border: 1px solid var(--line-strong); border-radius: 12px; color: var(--text); background: var(--panel-2);}
.search-empty { display: grid; gap: 8px; margin-top: 18px; padding: 20px; border: 1px solid var(--line); border-radius: 16px; background: #141416;}
.search-summary { display: flex; flex-wrap: wrap; align-items: baseline; gap: 8px; margin-top: 18px; padding: 12px 0; color: var(--muted);}
.search-summary strong { color: var(--text); font-size: 1.4rem;}
.search-summary small { flex-basis: 100%; color: var(--subtle);}
.search-results { display: grid; gap: 18px; margin-top: 6px; padding-bottom: 28px;}
.search-result-group { display: grid; gap: 10px; padding: 14px; border: 1px solid var(--line); border-radius: 16px; background: var(--panel);}
.result-group-heading { display: flex; align-items: baseline; justify-content: space-between; gap: 12px;}
.result-group-heading h3 { margin: 0; color: var(--text); font-size: 1rem; line-height: 1.35;}
.result-group-heading span { flex: 0 0 auto; color: var(--muted); font-size: 0.84rem;}
.result-list { display: grid; gap: 10px;}
.result-card { display: grid; gap: 8px; padding: 14px; border: 1px solid var(--line); border-radius: 12px; background: var(--panel-2);}
.result-card a { width: fit-content; color: var(--text); font-weight: 750; text-decoration: none;}
.result-card a:hover { text-decoration: underline;}
.result-card p { color: var(--muted); font-size: 0.95rem; line-height: 1.65; white-space: pre-wrap;}
.message { display: grid; grid-template-columns: 48px minmax(0, 1fr); gap: 12px; align-items: start;}
.avatar { display: grid; place-items: center; width: 48px; height: 36px; border: 1px solid var(--line); border-radius: 999px; color: var(--muted); background: var(--panel); font-size: 0.78rem; font-weight: 700;}
.bubble { max-width: 960px; padding: 16px; border: 1px solid var(--line); border-radius: 16px; background: var(--panel);}
.message.user .bubble { background: #141416;}
.message-content { color: var(--text); line-height: 1.62;}
.stage-line { display: inline-flex; align-items: center; gap: 8px; width: fit-content; margin-bottom: 10px; padding: 7px 10px; border: 1px solid var(--line); border-radius: 999px; color: var(--muted); background: #141416; font-size: 0.84rem; font-weight: 650;}
.stage-line span { width: 7px; height: 7px; border-radius: 999px; background: var(--muted); animation: stage-pulse 1s ease-in-out infinite;}
@keyframes stage-pulse { 0%, 100% { opacity: 0.4; }
50% { opacity: 1; }}
.message-content p,.message-content li { color: var(--text);}
.message-content h1,.message-content h2,.message-content h3 { margin: 12px 0 8px; font-size: 1.06rem; line-height: 1.3;}
.message-content ul,.message-content ol { padding-left: 20px;}
.muted { color: var(--muted);}
.block { display: block; padding: 12px;}
.evidence { display: grid; gap: 10px; margin-top: 16px;}
.rewrite-card { display: grid; gap: 6px; padding: 12px; border: 1px solid var(--line); border-radius: 12px; background: #141416;}
.rewrite-card span { color: var(--muted); font-size: 0.78rem; font-weight: 750; text-transform: uppercase; letter-spacing: 0.08em;}
.rewrite-card p { color: var(--text); font-size: 0.95rem;}
.metrics { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 8px;}
.metric { min-width: 0; padding: 10px; border: 1px solid var(--line); border-radius: 10px; background: var(--panel-2);}
.metric span,.source-item span { display: block; color: var(--muted); font-size: 0.76rem;}
.metric strong { display: block; margin-top: 4px; overflow: hidden; color: var(--text); font-size: 0.9rem; text-overflow: ellipsis; white-space: nowrap;}
details { border: 1px solid var(--line); border-radius: 12px; background: #141416;}
summary { padding: 11px 12px; color: var(--text); cursor: pointer; font-size: 0.92rem; font-weight: 700;}
.source-groups { display: grid; gap: 8px; padding: 0 10px 10px;}
.source-group { background: var(--panel);}
.source-group summary { color: var(--muted);}
.source-group summary span { color: var(--subtle); font-weight: 500;}
.source-list { display: grid; gap: 12px; padding: 0 10px 10px;}
.source-item { display: grid; gap: 8px; padding: 14px; border: 1px solid var(--line); border-radius: 10px; background: var(--panel-2);}
.source-item a { color: var(--text); font-weight: 700; text-decoration: none;}
.source-item a:hover { text-decoration: underline;}
.source-item p { color: var(--muted); font-size: 0.95rem; line-height: 1.65; white-space: pre-wrap;}
pre { max-height: 360px; margin: 0; overflow: auto; padding: 12px; border-top: 1px solid var(--line); color: var(--muted); background: #0d0d0e; font-size: 0.82rem;}
.composer { position: sticky; bottom: 0; z-index: 5; display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 10px; padding: 18px 26px 22px; border-top: 1px solid var(--line); background: rgba(15, 15, 16, 0.94);}
.composer input { min-height: 50px; border-radius: 14px;}
.composer button,.gate-panel button { min-width: 108px; border: 1px solid var(--line-strong); border-radius: 14px; color: var(--bg); background: var(--text); font-weight: 750;}
.composer button:disabled { cursor: wait; opacity: 0.45;}
.conversation-composer { background: #121214;}
.gate { position: fixed; inset: 0; z-index: 20; display: grid; place-items: center; padding: 20px; background: rgba(5, 5, 6, 0.82); backdrop-filter: blur(18px);}
.gate-panel { display: grid; gap: 14px; width: min(440px, 100%); padding: 24px; border: 1px solid var(--line-strong); border-radius: 18px; background: var(--panel); box-shadow: var(--shadow);}
.gate-panel button { min-height: 46px;}
.form-error { color: var(--text); padding: 10px; border: 1px solid var(--line-strong); border-radius: 10px; background: var(--panel-3);}
@media (max-width: 900px) { body { overflow: auto; }
.app-shell { grid-template-columns: 1fr; height: auto; overflow: visible; }
.rail { max-height: none; border-right: 0; border-bottom: 1px solid var(--line); }
.chat-pane { height: calc(100vh - 1px); }
.metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.search-workspace { padding: 18px; }}
@media (max-width: 620px) { .topbar, .thread, .composer { padding-left: 16px; padding-right: 16px; }
.message { grid-template-columns: 1fr; }
.avatar { width: fit-content; padding: 0 12px; }
.composer { grid-template-columns: 1fr; }
.search-input-row { grid-template-columns: 1fr; }
.search-form button { min-height: 46px; }
.composer button { min-height: 46px; }}123456789101112131415161718192021{ "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "lib": ["DOM", "DOM.Iterable", "ES2020"], "allowJs": false, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "module": "ESNext", "moduleResolution": "Node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx" }, "include": ["src"], "references": []}12345678910111213141516import { defineConfig } from "vite";import react from "@vitejs/plugin-react";
export default defineConfig({ plugins: [react()], build: { outDir: "../src/web", emptyOutDir: true, }, server: { port: 5173, proxy: { "/api": "http://localhost:8000", }, },});1234567891011121314151617181920212223services: - type: web name: the-7th-handle runtime: docker plan: starter healthCheckPath: /api/health envVars: - key: APP_PASSWORD sync: false - key: LLM_PROVIDER value: groq - key: GROQ_MODEL value: llama-3.3-70b-versatile - key: GROQ_API_KEY sync: false - key: PINECONE_API_KEY sync: false - key: SERMON_CHUNKS_URL sync: false - key: HF_HOME value: /app/.cache/huggingface - key: TRANSFORMERS_CACHE value: /app/.cache/huggingface7 unmodified lines8910111213147 unmodified linespinecone>=5.0.0rank_bm25python-dotenvstreamlittqdmpymupdfsentence_transformers7 unmodified lines89101112131415167 unmodified linespinecone>=5.0.0rank_bm25python-dotenvfastapiuvicorn[standard]gdowntqdmpymupdfsentence_transformers
123456789101112131415161718192021222324252627282930313233343536373839404142import osfrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]TARGET = ROOT / "src" / "sermon_chunks.pkl"
def main() -> None: if TARGET.exists() and TARGET.stat().st_size > 0: print(f"Using existing chunk file: {TARGET}") return
url = os.getenv("SERMON_CHUNKS_URL", "").strip() if not url: raise RuntimeError( "src/sermon_chunks.pkl is missing and SERMON_CHUNKS_URL is not set." )
TARGET.parent.mkdir(parents=True, exist_ok=True) tmp_path = TARGET.with_suffix(".pkl.download")
try: import gdown
output = gdown.download(url=url, output=str(tmp_path), quiet=False, fuzzy=True) if not output: raise RuntimeError("gdown did not return an output path.") except Exception as exc: if tmp_path.exists(): tmp_path.unlink() raise RuntimeError(f"Failed to download sermon chunks: {exc}") from exc
if not tmp_path.exists() or tmp_path.stat().st_size == 0: raise RuntimeError("Downloaded sermon chunk file is empty.")
tmp_path.replace(TARGET) print(f"Downloaded sermon chunks to: {TARGET}")
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091INFO: Started server process [40516]INFO: Waiting for application startup.INFO: Application startup complete.INFO: Uvicorn running on http://127.0.0.1:8010 (Press CTRL+C to quit)ERROR: Exception in ASGI applicationTraceback (most recent call last): File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\uvicorn\protocols\http\httptools_impl.py", line 421, in run_asgi result = await app( # type: ignore[func-returns-value] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\uvicorn\middleware\proxy_headers.py", line 56, in __call__ return await self.app(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\fastapi\applications.py", line 1159, in __call__ await super().__call__(scope, receive, send) File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\starlette\applications.py", line 90, in __call__ await self.middleware_stack(scope, receive, send) File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\starlette\middleware\errors.py", line 186, in __call__ raise exc File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\starlette\middleware\errors.py", line 164, in __call__ await self.app(scope, receive, _send) File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\starlette\middleware\cors.py", line 88, in __call__ await self.app(scope, receive, send) File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\starlette\middleware\exceptions.py", line 63, in __call__ await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\starlette\_exception_handler.py", line 53, in wrapped_app raise exc File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\starlette\_exception_handler.py", line 42, in wrapped_app await app(scope, receive, sender) File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\fastapi\middleware\asyncexitstack.py", line 18, in __call__ await self.app(scope, receive, send) File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\starlette\routing.py", line 660, in __call__ await self.middleware_stack(scope, receive, send) File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\starlette\routing.py", line 680, in app await route.handle(scope, receive, send) File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\starlette\routing.py", line 276, in handle await self.app(scope, receive, send) File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\fastapi\routing.py", line 134, in app await wrap_app_handling_exceptions(app, request)(scope, receive, send) File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\starlette\_exception_handler.py", line 53, in wrapped_app raise exc File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\starlette\_exception_handler.py", line 42, in wrapped_app await app(scope, receive, sender) File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\fastapi\routing.py", line 120, in app response = await f(request) ^^^^^^^^^^^^^^^^ File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\fastapi\routing.py", line 674, in app raw_response = await run_endpoint_function( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\fastapi\routing.py", line 330, in run_endpoint_function return await run_in_threadpool(dependant.call, **values) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\starlette\concurrency.py", line 32, in run_in_threadpool return await anyio.to_thread.run_sync(func) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\anyio\to_thread.py", line 63, in run_sync return await get_async_backend().run_sync_in_worker_thread( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\anyio\_backends\_asyncio.py", line 2518, in run_sync_in_worker_thread return await future ^^^^^^^^^^^^ File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\anyio\_backends\_asyncio.py", line 1002, in run result = context.run(func, *args) ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\src\server.py", line 134, in answer result = answer_question( ^^^^^^^^^^^^^^^^ File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\src\app.py", line 1020, in answer_question response = llm.invoke(prepared["prompt_text"]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\langchain_core\language_models\chat_models.py", line 395, in invoke self.generate_prompt( File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\langchain_core\language_models\chat_models.py", line 1025, in generate_prompt return self.generate(prompt_messages, stop=stop, callbacks=callbacks, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\langchain_core\language_models\chat_models.py", line 842, in generate self._generate_with_cache( File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\langchain_core\language_models\chat_models.py", line 1091, in _generate_with_cache result = self._generate( ^^^^^^^^^^^^^^^ File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\langchain_groq\chat_models.py", line 533, in _generate response = self.client.create(messages=message_dicts, **params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\groq\resources\chat\completions.py", line 461, in create return self._post( ^^^^^^^^^^^ File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\groq\_base_client.py", line 1242, in post return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Hp\Documents\Codex\7th-handle\7th_handle\venv\Lib\site-packages\groq\_base_client.py", line 1044, in request raise self._make_status_error_from_response(err.response) from Nonegroq.RateLimitError: Error code: 429 - {'error': {'message': 'Rate limit reached for model `llama-3.3-70b-versatile` in organization `org_01k1yk3zshf45vcjsnq5xh5ta4` service tier `on_demand` on tokens per minute (TPM): Limit 12000, Used 9219, Requested 2804. Please try again in 114.999999ms. Need more tokens? Upgrade to Dev Tier today at https://console.groq.com/settings/billing', 'type': 'tokens', 'code': 'rate_limit_exceeded'}}1
6 unmodified lines78910111213242 unmodified lines25625725825926026126238 unmodified lines30130230330430530683 unmodified lines39039139239339439570 unmodified lines46646746846947047147219 unmodified lines4924934944954964974983 unmodified lines50250350450550650750850951051151251351451551651751851952052113 unmodified lines53553653753853954054154253 unmodified lines59659759859960060111 unmodified lines61361461561661761861 unmodified lines6806816826836846856866876886896906916926936946956966976986997007017027037047057067077082 unmodified lines7117127137147157166 unmodified linesimport urllib.errorimport urllib.requestfrom functools import lru_cachefrom typing import Listfrom dotenv import load_dotenvfrom pinecone import Pinecone242 unmodified linesSTOPWORDS = {"the", "a", "an", "of", "in", "on", "at", "and", "to", "for", "with", "by"}38 unmodified linesreturn title_tokens.issubset(query_tokens)def detect_single_seal_title(query: str) -> str | None:query_clean = normalize_text(query)for alias, title in SINGLE_SEAL_ALIASES.items():83 unmodified linesselected.extend(rank_by_query_terms(other_docs, query)[:remaining])return selected[:max_docs]# ===============================# RETRIEVER# ===============================70 unmodified linestarget_code = extract_date_code(single_seal_title).upper()sermon_chunks = [d for d in chunksif source_matches_title(d.metadata.get("source", ""), title)]if sermon_chunks:seal_query = SERIES_QUERY_HINTS.get(target_code, query)19 unmodified lineselse:title_chunks = [d for d in chunksif sermon_title_matches(query, d.metadata.get("source", ""))]if title_chunks:if answer_mode == "Summary Mode":3 unmodified linesfor d in rank_by_query_terms(title_chunks, query)[:PRIORITY_K]:add_doc(d, "priority")for d in get_bm25_retriever().invoke(query):add_doc(d, "bm25")try:vec_docs = get_vector_store().as_retriever(search_kwargs={"k": VECTOR_K}).invoke(query)pinecone_status = "ok"for d in vec_docs:add_doc(d, "pinecone")except Exception as exc:pinecone_status = "failed"pinecone_error = str(exc)logger.warning("Pinecone vector search failed: %s", exc)final_docs = select_context_docs(results, query, answer_mode)distinct_sermons = {13 unmodified lines"pinecone_error": pinecone_error,"context_policy": answer_mode,"candidate_count": len(results),"max_context_docs": CONTEXT_POLICY.get(answer_mode, CONTEXT_POLICY["Strict Mode"])["max_docs"],}return final_docs, diagnostics53 unmodified linesANSWER:"""PROMPT = PromptTemplate(template=PROMPT_TEMPLATE,input_variables=["context_str", "question"],11 unmodified linesinput_variables=["page_content", "source", "paragraph"],)# ===============================# PUBLIC API# ===============================61 unmodified linesreturn "supported"def answer_question(question: str, answer_mode: str = "Strict Mode"):total_started_at = time.perf_counter()if answer_mode not in ANSWER_MODE_INSTRUCTIONS:answer_mode = "Strict Mode"docs, diagnostics = retrieve_documents_with_diagnostics(question, answer_mode=answer_mode)llm = get_llm()context_str = format_documents_for_context(docs)prompt_text = PROMPT_TEMPLATE.format(context_str=context_str,question=question,answer_mode_instructions=ANSWER_MODE_INSTRUCTIONS[answer_mode],)response = llm.invoke(prompt_text)answer = getattr(response, "content", str(response))grounding_status = classify_grounding(answer, docs)diagnostics["total_latency"] = round(time.perf_counter() - total_started_at, 3)diagnostics["answer_mode"] = answer_modediagnostics["llm_provider"] = LLM_PROVIDERdiagnostics["llm_model"] = GROQ_MODEL if LLM_PROVIDER == "groq" else GEMINI_MODELreturn {"answer": answer,"source_documents": docs,2 unmodified lines}def search_archives(query: str):"""Used by Search mode only.6 unmodified lines78910111213242 unmodified lines25625725825926026126226326426526626726826927027138 unmodified lines31031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434583 unmodified lines42943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248370 unmodified lines55455555655755855956019 unmodified lines5805815825835845855863 unmodified lines59059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862913 unmodified lines64364464564664764864965065153 unmodified lines70570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875911 unmodified lines77177277377477577677777877978078161 unmodified lines8438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979982 unmodified lines10011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310946 unmodified linesimport urllib.errorimport urllib.requestfrom functools import lru_cachefrom typing import Any, Iterator, Listfrom dotenv import load_dotenvfrom pinecone import Pinecone242 unmodified linesSTOPWORDS = {"the", "a", "an", "of", "in", "on", "at", "and", "to", "for", "with", "by","what", "who", "where", "when", "why", "how", "did", "does", "do", "is","are", "was", "were", "be", "been", "being", "about", "teach", "taught","said", "say", "says", "explain", "explained", "brother", "branham","william", "sermon", "sermons", "message", "messages", "summarize","summary", "list", "state", "meaning", "events", "relationship",}GENERIC_TITLE_TOKENS = {"know", "believe", "faith", "love", "life", "way", "truth", "word","god", "lord", "jesus", "christ", "christian", "church", "message",}38 unmodified linesreturn title_tokens.issubset(query_tokens)def explicit_title_lookup(query: str) -> bool:query_clean = normalize_text(query)if extract_query_sermon_code(query):return Truetitle_lookup_phrases = {"sermon called","message called","sermon titled","message titled","sermon named","message named","the sermon","the message","summarize","summary of",}return any(phrase in query_clean for phrase in title_lookup_phrases)def safe_sermon_title_matches(user_query: str, filename: str) -> bool:title_tokens = tokenize_meaningful(extract_sermon_title(filename))if not title_tokens:return Falseif len(title_tokens) == 1 and next(iter(title_tokens)) in GENERIC_TITLE_TOKENS:return Falseif len(title_tokens) < 2 and not explicit_title_lookup(user_query):return Falsereturn sermon_title_matches(user_query, filename)def detect_single_seal_title(query: str) -> str | None:query_clean = normalize_text(query)for alias, title in SINGLE_SEAL_ALIASES.items():83 unmodified linesselected.extend(rank_by_query_terms(other_docs, query)[:remaining])return selected[:max_docs]def query_support_terms(query: str) -> set[str]:terms = query_entity_tokens(query)return {term for term in termsif term not in STOPWORDS and not re.fullmatch(r"\d+", term)}def evaluate_retrieval_confidence(query: str,docs: List[Document],diagnostics: dict[str, Any],) -> dict[str, Any]:terms = query_support_terms(query)context = normalize_text(" ".join(doc.page_content for doc in docs))supported_terms = sorted(term for term in terms if term in context)missing_terms = sorted(terms - set(supported_terms))coverage = len(supported_terms) / len(terms) if terms else 1.0confidence = "supported"reason = "priority_or_supported_terms"should_refuse = Falseif not docs:confidence = "insufficient"reason = "no_documents"should_refuse = Trueelif diagnostics.get("priority_count", 0) > 0:confidence = "supported"reason = "priority_match"elif terms and missing_terms:confidence = "insufficient"reason = "missing_query_terms_without_priority_match"should_refuse = Trueelif diagnostics.get("source_count", 0) < 2:confidence = "partial"reason = "too_few_documents"return {"retrieval_confidence": confidence,"confidence_reason": reason,"should_refuse_generation": should_refuse,"query_terms": sorted(terms),"supported_query_terms": supported_terms,"missing_query_terms": missing_terms,"query_term_coverage": round(coverage, 3),}# ===============================# RETRIEVER# ===============================70 unmodified linestarget_code = extract_date_code(single_seal_title).upper()sermon_chunks = [d for d in chunksif source_matches_title(d.metadata.get("source", ""), single_seal_title)]if sermon_chunks:seal_query = SERIES_QUERY_HINTS.get(target_code, query)19 unmodified lineselse:title_chunks = [d for d in chunksif safe_sermon_title_matches(query, d.metadata.get("source", ""))]if title_chunks:if answer_mode == "Summary Mode":3 unmodified linesfor d in rank_by_query_terms(title_chunks, query)[:PRIORITY_K]:add_doc(d, "priority")max_context_docs = CONTEXT_POLICY.get(answer_mode, CONTEXT_POLICY["Strict Mode"])["max_docs"]if counts.get("priority", 0) < max_context_docs:for d in get_bm25_retriever().invoke(query):add_doc(d, "bm25")pre_vector_docs = select_context_docs(results, query, answer_mode)pre_vector_diagnostics = {"source_count": len(pre_vector_docs),"priority_count": sum(1 for d in pre_vector_docs if d.metadata.get("retrieval_origin") == "priority"),}pre_vector_confidence = evaluate_retrieval_confidence(query,pre_vector_docs,pre_vector_diagnostics,)if counts.get("priority", 0) > 0:pinecone_status = "skipped_priority_match"elif pre_vector_confidence.get("should_refuse_generation"):pinecone_status = "skipped_low_confidence"else:try:vec_docs = get_vector_store().as_retriever(search_kwargs={"k": VECTOR_K}).invoke(query)pinecone_status = "ok"for d in vec_docs:add_doc(d, "pinecone")except Exception as exc:pinecone_status = "failed"pinecone_error = str(exc)logger.warning("Pinecone vector search failed: %s", exc)final_docs = select_context_docs(results, query, answer_mode)distinct_sermons = {13 unmodified lines"pinecone_error": pinecone_error,"context_policy": answer_mode,"candidate_count": len(results),"max_context_docs": max_context_docs,}diagnostics.update(evaluate_retrieval_confidence(query, final_docs, diagnostics))return final_docs, diagnostics53 unmodified linesANSWER:"""CONVERSATIONAL_PROMPT_TEMPLATE = """You are a careful research assistant helping one person understand William Marrion Branham's sermons.Do not roleplay, impersonate, or speak as William Marrion Branham.Always refer to him in the third person as "Brother Branham" or "William Branham."RULES:- Be faithful to the sermons provided.- Use the conversation history only to understand what the user's latest question refers to.- Answer only from the provided context. Do not use outside knowledge.- If the context does not clearly support the answer, say: "The retrieved sermon excerpts do not give enough support to answer that safely."- If the context is partial, say what is supported and what is not supported.- Use a natural conversational tone, but do not preach or impersonate.- Phrase claims as "Brother Branham said/taught/explained..." when the context supports them.- Do not say "I testified," "my ministry," "my dear friend," or anything that makes the assistant sound like Brother Branham.- Include source references for important claims using this format: [source, Para paragraph].- Do not cite a source unless it appears in the provided context.- Keep direct quotes short. Prefer paraphrase with source references.ANSWER MODE:{answer_mode_instructions}CONVERSATION HISTORY:{conversation_history}CONTEXT:{context_str}LATEST QUESTION:{question}ANSWER:"""QUESTION_REWRITE_PROMPT_TEMPLATE = """Rewrite the user's latest question as a standalone search query for retrieving William Branham sermon excerpts.Use the conversation history only to resolve references like "it", "that", "he", "those", "the first one", or "explain more".Do not answer the question.Do not add doctrine or facts not present in the conversation.Return only the standalone question.CONVERSATION HISTORY:{conversation_history}LATEST QUESTION:{question}STANDALONE QUESTION:"""PROMPT = PromptTemplate(template=PROMPT_TEMPLATE,input_variables=["context_str", "question"],11 unmodified linesinput_variables=["page_content", "source", "paragraph"],)QUESTION_REWRITE_PROMPT = PromptTemplate(template=QUESTION_REWRITE_PROMPT_TEMPLATE,input_variables=["conversation_history", "question"],)# ===============================# PUBLIC API# ===============================61 unmodified linesreturn "supported"def format_conversation_history(history: List[dict[str, str]], max_messages: int = 8) -> str:rows = []for item in history[-max_messages:]:role = item.get("role", "").strip().lower()content = " ".join(item.get("content", "").split())if role not in {"user", "assistant"} or not content:continueif len(content) > 900:content = content[:900].rstrip() + "..."rows.append(f"{role.upper()}: {content}")return "\n".join(rows) if rows else "No prior conversation."def rewrite_conversational_question(question: str, history: List[dict[str, str]]) -> str:if not history:return questionprompt_text = QUESTION_REWRITE_PROMPT.format(conversation_history=format_conversation_history(history),question=question,)response = get_llm().invoke(prompt_text)rewritten = getattr(response, "content", str(response)).strip()return rewritten or questiondef normalize_answer_mode(answer_mode: str) -> str:if answer_mode not in ANSWER_MODE_INSTRUCTIONS:return "Strict Mode"return answer_modedef build_answer_prompt(question: str, answer_mode: str, docs: List[Document]) -> str:context_str = format_documents_for_context(docs)return PROMPT_TEMPLATE.format(context_str=context_str,question=question,answer_mode_instructions=ANSWER_MODE_INSTRUCTIONS[answer_mode],)def build_conversational_answer_prompt(question: str,retrieval_question: str,answer_mode: str,docs: List[Document],history: List[dict[str, str]],) -> str:context_str = format_documents_for_context(docs)latest_question = questionif retrieval_question != question:latest_question = f"{question}\n\nStandalone retrieval question: {retrieval_question}"return CONVERSATIONAL_PROMPT_TEMPLATE.format(context_str=context_str,conversation_history=format_conversation_history(history),question=latest_question,answer_mode_instructions=ANSWER_MODE_INSTRUCTIONS[answer_mode],)def add_generation_diagnostics(diagnostics: dict[str, Any],total_started_at: float,answer_mode: str,) -> dict[str, Any]:diagnostics["total_latency"] = round(time.perf_counter() - total_started_at, 3)diagnostics["answer_mode"] = answer_modediagnostics["llm_provider"] = LLM_PROVIDERdiagnostics["llm_model"] = GROQ_MODEL if LLM_PROVIDER == "groq" else GEMINI_MODELreturn diagnosticsdef build_refusal_result(diagnostics: dict[str, Any],total_started_at: float,answer_mode: str,) -> dict[str, Any]:diagnostics["retrieved_source_count"] = diagnostics.get("source_count", 0)diagnostics["retrieved_distinct_sermon_count"] = diagnostics.get("distinct_sermon_count", 0)diagnostics["source_count"] = 0diagnostics["distinct_sermon_count"] = 0diagnostics["sermons"] = []add_generation_diagnostics(diagnostics, total_started_at, answer_mode)return {"answer": UNSUPPORTED_ANSWER,"source_documents": [],"grounding_status": "insufficient","diagnostics": diagnostics,}def prepare_answer_context(question: str,answer_mode: str = "Strict Mode",history: List[dict[str, str]] | None = None,conversational: bool = False,) -> dict[str, Any]:total_started_at = time.perf_counter()answer_mode = normalize_answer_mode(answer_mode)history = history or []retrieval_question = (rewrite_conversational_question(question, history)if conversational and historyelse question)docs, diagnostics = retrieve_documents_with_diagnostics(retrieval_question,answer_mode=answer_mode,)diagnostics["retrieval_question"] = retrieval_questiondiagnostics["conversation_mode"] = conversationalif diagnostics.get("should_refuse_generation"):return {"answer_mode": answer_mode,"docs": [],"diagnostics": diagnostics,"prompt_text": "","total_started_at": total_started_at,"refusal_result": build_refusal_result(diagnostics, total_started_at, answer_mode),}return {"answer_mode": answer_mode,"docs": docs,"diagnostics": diagnostics,"prompt_text": (build_conversational_answer_prompt(question,retrieval_question,answer_mode,docs,history,)if conversationalelse build_answer_prompt(question, answer_mode, docs)),"total_started_at": total_started_at,"refusal_result": None,}def finalize_answer_result(answer: str,docs: List[Document],diagnostics: dict[str, Any],total_started_at: float,answer_mode: str,) -> dict[str, Any]:grounding_status = classify_grounding(answer, docs)add_generation_diagnostics(diagnostics, total_started_at, answer_mode)return {"answer": answer,"source_documents": docs,2 unmodified lines}def answer_question(question: str,answer_mode: str = "Strict Mode",history: List[dict[str, str]] | None = None,conversational: bool = False,):prepared = prepare_answer_context(question,answer_mode,history,conversational,)if prepared["refusal_result"] is not None:return prepared["refusal_result"]llm = get_llm()response = llm.invoke(prepared["prompt_text"])answer = getattr(response, "content", str(response))return finalize_answer_result(answer,prepared["docs"],prepared["diagnostics"],prepared["total_started_at"],prepared["answer_mode"],)def stream_answer_tokens(prompt_text: str) -> Iterator[str]:for chunk in get_llm().stream(prompt_text):text = getattr(chunk, "content", "")if isinstance(text, list):text = "".join(str(part) for part in text)if text:yield str(text)def stream_answer_question(question: str,answer_mode: str = "Strict Mode",history: List[dict[str, str]] | None = None,conversational: bool = False,) -> Iterator[dict[str, Any]]:prepared = prepare_answer_context(question,answer_mode,history,conversational,)if prepared["refusal_result"] is not None:result = prepared["refusal_result"]yield {"event": "metadata","data": {"sources": result["source_documents"],"diagnostics": result["diagnostics"],"grounding_status": result["grounding_status"],"answer_mode": prepared["answer_mode"],},}yield {"event": "token", "data": {"text": result["answer"]}}yield {"event": "done", "data": result}returnparts = []yield {"event": "metadata","data": {"sources": prepared["docs"],"diagnostics": prepared["diagnostics"],"grounding_status": "pending","answer_mode": prepared["answer_mode"],},}for token in stream_answer_tokens(prepared["prompt_text"]):parts.append(token)yield {"event": "token", "data": {"text": token}}answer = "".join(parts)result = finalize_answer_result(answer,prepared["docs"],prepared["diagnostics"],prepared["total_started_at"],prepared["answer_mode"],)yield {"event": "done", "data": result}def search_archives(query: str):"""Used by Search mode only.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197import hmacimport jsonimport osfrom pathlib import Pathfrom typing import Any, Iterable
from fastapi import FastAPI, HTTPException, Query, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import FileResponse, StreamingResponsefrom fastapi.staticfiles import StaticFilesfrom pydantic import BaseModel, Field
from .app import answer_question, search_archives, stream_answer_question
BASE_DIR = Path(__file__).resolve().parentWEB_DIR = BASE_DIR / "web"ANSWER_MODES = {"Strict Mode", "Study Mode", "Summary Mode"}APP_PASSWORD = os.getenv("APP_PASSWORD", "")
api = FastAPI(title="The 7th Handle API", version="1.0.0")
api.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=False, allow_methods=["GET", "POST"], allow_headers=["*"],)
class AnswerRequest(BaseModel): question: str = Field(..., min_length=1, max_length=4000) answer_mode: str = Field("Strict Mode") sermon_scope: str | None = Field(None, max_length=20) conversation_mode: bool = Field(False) history: list[dict[str, str]] = Field(default_factory=list)
def require_password(request: Request) -> None: if not APP_PASSWORD: return provided = request.headers.get("X-App-Password", "") if not hmac.compare_digest(provided, APP_PASSWORD): raise HTTPException(status_code=401, detail="Invalid app password.")
def normalize_mode(answer_mode: str) -> str: return answer_mode if answer_mode in ANSWER_MODES else "Strict Mode"
def sanitize_history(history: list[dict[str, str]]) -> list[dict[str, str]]: clean = [] for item in history[-8:]: role = str(item.get("role", "")).strip().lower() content = " ".join(str(item.get("content", "")).split()) if role not in {"user", "assistant"} or not content: continue clean.append({"role": role, "content": content[:1200]}) return clean
def messagehub_link(filename: str) -> str: if not filename: return "#" code = filename.replace(".pdf", "").replace(".PDF", "").strip().split()[0] return f"https://www.messagehub.info/en/read.do?ref_num={code}"
def serialize_doc(doc) -> dict[str, Any]: source = doc.metadata.get("source", "") paragraph_text = doc.page_content or "" return { "source": source, "paragraph": doc.metadata.get("paragraph", ""), "content": paragraph_text, "full_text": paragraph_text, "retrieval_origin": doc.metadata.get("retrieval_origin", "unknown"), "retrieval_rank": doc.metadata.get("retrieval_rank", ""), "messagehub_url": messagehub_link(source), }
def serialize_result(result: dict[str, Any], question: str, answer_mode: str) -> dict[str, Any]: sources = [serialize_doc(doc) for doc in result.get("source_documents", [])] return { "answer": result.get("answer", ""), "sources": sources, "grounding_status": result.get("grounding_status", "unknown"), "diagnostics": result.get("diagnostics", {}), "question": question, "answer_mode": answer_mode, }
def serialize_stream_data(data: dict[str, Any], question: str, answer_mode: str) -> dict[str, Any]: payload = dict(data) if "source_documents" in payload: payload["sources"] = [serialize_doc(doc) for doc in payload.pop("source_documents")] if "sources" in payload: payload["sources"] = [ serialize_doc(doc) if hasattr(doc, "metadata") else doc for doc in payload["sources"] ] payload.setdefault("question", question) payload.setdefault("answer_mode", answer_mode) return payload
def apply_sermon_scope(question: str, sermon_scope: str | None) -> str: scope = (sermon_scope or "").strip() if not scope: return question.strip() if scope.upper() in question.upper(): return question.strip() return f"{scope} {question.strip()}"
def sse(event: str, data: dict[str, Any]) -> str: return f"event: {event}\ndata: {json.dumps(data, ensure_ascii=True)}\n\n"
@api.get("/api/health")def health() -> dict[str, Any]: return {"status": "ok", "password_required": bool(APP_PASSWORD)}
@api.post("/api/answer")def answer(request: Request, payload: AnswerRequest) -> dict[str, Any]: require_password(request) mode = normalize_mode(payload.answer_mode) question = apply_sermon_scope(payload.question, payload.sermon_scope) try: result = answer_question( question, answer_mode=mode, history=sanitize_history(payload.history), conversational=payload.conversation_mode, ) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc return serialize_result(result, question, mode)
@api.post("/api/answer/stream")def answer_stream(request: Request, payload: AnswerRequest) -> StreamingResponse: require_password(request) mode = normalize_mode(payload.answer_mode) question = apply_sermon_scope(payload.question, payload.sermon_scope) history = sanitize_history(payload.history)
def events() -> Iterable[str]: try: for event in stream_answer_question( question, answer_mode=mode, history=history, conversational=payload.conversation_mode, ): yield sse( event["event"], serialize_stream_data(event["data"], question, mode), ) except Exception as exc: yield sse("error", {"detail": str(exc), "question": question, "answer_mode": mode})
return StreamingResponse(events(), media_type="text/event-stream")
@api.get("/api/search")def search( request: Request, q: str = Query(..., min_length=1, max_length=4000),) -> dict[str, Any]: require_password(request) docs, debug_log = search_archives(q) return { "query": q, "results": [serialize_doc(doc) for doc in docs], "debug_log": debug_log, }
if (WEB_DIR / "assets").exists(): api.mount("/assets", StaticFiles(directory=WEB_DIR / "assets"), name="assets")
@api.get("/")def index() -> FileResponse: return FileResponse(WEB_DIR / "index.html")
@api.get("/{path:path}")def spa_fallback(path: str) -> FileResponse: if path.startswith("api/"): raise HTTPException(status_code=404, detail="Not found") return FileResponse(WEB_DIR / "index.html")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331from collections import defaultdictimport jsonimport osimport time
import streamlit as st
st.set_page_config( page_title="Voice of the Sign", page_icon="π¦
", layout="wide", initial_sidebar_state="expanded",)
backend_loaded = Falsetry: from app import answer_question, search_archives
backend_loaded = Trueexcept Exception as e: st.error(f"Backend failed to load:\n\n{e}")
def messagehub_link(filename: str): if not filename: return "#"
name = filename.replace(".pdf", "").replace(".PDF", "").strip() code = name.split()[0] return f"https://www.messagehub.info/en/read.do?ref_num={code}"
def excerpt(text: str, length: int = 320) -> str: clean = " ".join((text or "").split()) if len(clean) <= length: return clean return clean[: length - 1].rstrip() + "..."
def grouped_sources(docs): groups = defaultdict(list) for doc in docs or []: groups[doc.metadata.get("source", "Unknown source")].append(doc) return groups
def render_grounding(status: str, diagnostics: dict): labels = { "supported": "Supported", "partial": "Partial", "insufficient": "Insufficient", } status_label = labels.get(status, "Unknown")
if status == "supported": st.success(f"Grounding: {status_label}") elif status == "partial": st.warning(f"Grounding: {status_label}") else: st.error(f"Grounding: {status_label}")
col1, col2, col3, col4, col5 = st.columns(5) col1.metric("Excerpts", diagnostics.get("source_count", 0)) col2.metric("Sermons", diagnostics.get("distinct_sermon_count", 0)) col3.metric("Pinecone", diagnostics.get("pinecone_status", "unknown")) col4.metric("Latency", f"{diagnostics.get('total_latency', 0)}s") col5.metric("Model", diagnostics.get("llm_model", "unknown"))
def render_references(docs): if not docs: st.info("No source excerpts were returned.") return
for source, source_docs in grouped_sources(docs).items(): with st.expander(f"{source} ({len(source_docs)} excerpts)", expanded=False): for doc in source_docs: para = doc.metadata.get("paragraph", "") origin = doc.metadata.get("retrieval_origin", "unknown") rank = doc.metadata.get("retrieval_rank", "") link = messagehub_link(source) st.markdown(f"[Para {para}]({link}) Β· origin: `{origin}` Β· rank: `{rank}`") st.caption(excerpt(doc.page_content)) st.divider()
def render_debug(docs, diagnostics): with st.expander("Advanced retrieval diagnostics", expanded=False): st.json(diagnostics) rows = [] for doc in docs or []: rows.append( { "rank": doc.metadata.get("retrieval_rank", ""), "origin": doc.metadata.get("retrieval_origin", ""), "source": doc.metadata.get("source", ""), "paragraph": doc.metadata.get("paragraph", ""), "excerpt": excerpt(doc.page_content, 180), } ) if rows: st.dataframe(rows, use_container_width=True, hide_index=True)
def render_assistant_metadata(msg): diagnostics = msg.get("diagnostics", {}) sources = msg.get("sources", []) grounding_status = msg.get("grounding_status", "unknown")
render_grounding(grounding_status, diagnostics) render_references(sources) render_debug(sources, diagnostics)
def append_user_message(content: str): st.session_state.chat_history.append( { "role": "user", "content": content, } )
def append_assistant_message(response: dict, answer_mode: str): st.session_state.chat_history.append( { "role": "assistant", "content": response.get("answer", ""), "sources": response.get("source_documents", []), "diagnostics": response.get("diagnostics", {}), "grounding_status": response.get("grounding_status", "unknown"), "answer_mode": answer_mode, } )
def log_feedback(msg: dict, rating: str): feedback_file = "feedback_log.json" log_entry = { "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"), "answer": msg.get("content", ""), "sources": [ { "source": doc.metadata.get("source", ""), "paragraph": doc.metadata.get("paragraph", ""), "content": doc.page_content[:300] + "..." } for doc in msg.get("sources", []) ], "diagnostics": msg.get("diagnostics", {}), "grounding_status": msg.get("grounding_status", "unknown"), "rating": rating } logs = [] if os.path.exists(feedback_file): try: with open(feedback_file, "r", encoding="utf-8") as f: logs = json.load(f) except Exception: pass logs.append(log_entry) with open(feedback_file, "w", encoding="utf-8") as f: json.dump(logs, f, indent=4)
st.markdown( """<style>html, body, [class*="css"] { font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;}
div[data-testid="stChatMessage"][data-test-role="assistant"] { border-left: 4px solid #D4AF37; background-color: rgba(212,175,55,0.045);}
.safety-note { padding: 12px 14px; border-left: 4px solid #D4AF37; background: rgba(212,175,55,0.07); border-radius: 6px; font-size: 0.92rem; margin-bottom: 12px;}
.topic-row button { min-height: 2.5rem;}
#MainMenu {visibility: hidden;}header {visibility: visible;}</style>""", unsafe_allow_html=True,)
if "chat_history" not in st.session_state: st.session_state.chat_history = []if "pending_prompt" not in st.session_state: st.session_state.pending_prompt = None
with st.sidebar: st.title("Controls") mode = st.radio( "Mode", ["Chat with The Message", "Search The Word"], index=0, label_visibility="collapsed", )
st.divider()
answer_mode = st.selectbox( "Answer mode", ["Strict Mode", "Study Mode", "Summary Mode"], index=0, help=( "Strict sends the best 8 excerpts. Study sends up to 14. " "Summary sends up to 20 and spreads sermon summaries across the source." ), )
sermon_scope = st.text_input( "Search within sermon code", placeholder="Example: 63-0324E", help="Optional. Adds a sermon code to the question for targeted retrieval.", ).strip()
st.divider() st.caption("Quick topics") topic_prompts = { "Seven Seals": "what are the seven seals? list each seal and state its events and meaning", "Seven Thunders": "what are the seven thunders?", "Serpent's Seed": "What is the relationship between the Serpent's Seed and Cain?", "Adoption": "Summarize the Adoption series.", "Demonology": "Summarize the Demonology series.", "Church Ages": "Summarize the seven church ages.", } for label, prompt_text in topic_prompts.items(): if st.button(label, use_container_width=True): st.session_state.pending_prompt = prompt_text st.rerun()
st.divider() if st.button("Clear Screen", use_container_width=True): st.session_state.chat_history = [] st.session_state.pending_prompt = None st.rerun()
st.title("The 7th Handle" if mode == "Chat with The Message" else "The Table")st.divider()
if not backend_loaded: st.stop()
if mode == "Chat with The Message": for msg in st.session_state.chat_history: with st.chat_message(msg["role"], avatar="π€" if msg["role"] == "user" else "π¦
"): st.markdown(msg["content"], unsafe_allow_html=False) if msg["role"] == "assistant": render_assistant_metadata(msg) # Render thumbs up / thumbs down feedback buttons for evaluating the response msg_idx = st.session_state.chat_history.index(msg) if f"feedback_{msg_idx}" not in st.session_state: st.session_state[f"feedback_{msg_idx}"] = None col1, col2, _ = st.columns([1, 1, 15]) with col1: if st.button("π", key=f"thumbs_up_{msg_idx}", help="Accurate, helpful, and properly grounded"): st.session_state[f"feedback_{msg_idx}"] = "thumbs_up" log_feedback(msg, "thumbs_up") st.toast("Response marked as helpful! Thanks.", icon="π") with col2: if st.button("π", key=f"thumbs_down_{msg_idx}", help="Inaccurate or poorly grounded"): st.session_state[f"feedback_{msg_idx}"] = "thumbs_down" log_feedback(msg, "thumbs_down") st.toast("Issue logged. We will review the grounding!", icon="π")
st.markdown( """<div class="safety-note">Answers are generated from retrieved sermon excerpts. Verify doctrinal conclusions against the cited source text.</div>""", unsafe_allow_html=True, )
prompt = st.session_state.pending_prompt st.session_state.pending_prompt = None typed_prompt = st.chat_input("Ask a question, or use a quick topic from the sidebar.") if typed_prompt: prompt = typed_prompt
if prompt: final_prompt = prompt if sermon_scope and sermon_scope.upper() not in final_prompt.upper(): final_prompt = f"{sermon_scope} {final_prompt}"
append_user_message(final_prompt) with st.spinner("Retrieving sermon excerpts and checking grounding..."): response = answer_question(final_prompt, answer_mode=answer_mode) append_assistant_message(response, answer_mode) st.rerun()
else: query = st.chat_input("Search for a keyword or phrase...")
if query: st.subheader(f"Results for: {query}")
with st.spinner("Scanning archives..."): docs, debug_log = search_archives(query)
with st.expander("Search diagnostics", expanded=False): for line in debug_log: st.write(line)
if not docs: st.info("No exact records found.") else: render_references(docs).dockerignore+7
.env.example+2
.gitignore+5
.python-versionAdded+1
Dockerfile+18-5
README.md+46-20
frontend/index.htmlAdded+12
frontend/package-lock.jsonAdded
frontend/package.jsonAdded+23
frontend/src/main.tsxAdded+804
frontend/src/styles.cssAdded+856
frontend/tsconfig.jsonAdded+21
frontend/vite.config.tsAdded+16
render.yamlAdded+23
requirements.txt+4-2
scripts/download_chunks.pyAdded+42
server-8010.err.logAdded+91
server-8010.logAdded
src/__init__.pyAdded+1
src/app.py+406-28
src/server.pyAdded+197
src/streamlit_app.pyDeleted-331