Spaces:
Sleeping
Sleeping
Quincy Hsieh commited on
Commit ·
035ac6d
1
Parent(s): b818d09
Add token count and explanation
Browse filesFiles changed (2)
- app.py+55-11
- prompts/rag_prompt.txt+6
17 unmodified lines181920212223232 unmodified lines25625725825926026126226326426526626710 unmodified lines27827928028128228328433 unmodified lines31831932032132232332432532632732832933033133233333433533633733833934034134234334434534674 unmodified lines42142242342442542642735 unmodified lines46346446546646746846947047147247347447547647726 unmodified lines50450550650750850951017 unmodified linesimport osimport jsonimport loggingfrom pathlib import Pathfrom typing import Optional232 unmodified linesreturn contextsdef call_llm(prompt: str) -> str:"""Make a call to the LLM via Azure Foundry (GPT-5).Calls the Azure OpenAI-compatible chat/completions endpoint.Endpoint URL is loaded from config.json; API key from AZURE_API_KEY env var."""headers = {"api-key": AZURE_API_KEY,10 unmodified linesresp = http_requests.post(LLM_ENDPOINT_URL, headers=headers, json=payload, timeout=60)resp.raise_for_status()data = resp.json()return data["choices"][0]["message"]["content"].strip()except http_requests.exceptions.HTTPError as e:logger.error(f"LLM API call failed: {e} — {resp.text}")raise HTTPException(status_code=503, detail=f"LLM service unavailable: {str(e)}")33 unmodified lines2. Retrieve relevant context from vector store3. Build augmented prompt with context4. Call LLM to generate answer5. Return answer with source metadata"""# Step 1: Retrieve relevant document chunkscontexts = retrieve_relevant_context(query, top_k=top_k)if not contexts:return {"answer": "No documents have been ingested yet. Please upload documents first.","sources": [],"query": query,}# Step 2: Build the augmented promptprompt = build_rag_prompt(query, contexts)# Step 3: Generate answer from LLManswer = call_llm(prompt)# Step 4: Return structured responsereturn {"answer": answer,"sources": [{"source": ctx["source"], "score": ctx["similarity_score"]} for ctx in contexts],"query": query,}74 unmodified linesReturns:- answer (str): The generated answer- sources (list): Source documents used for context- query (str): The original query"""logger.info(f"Query received: {request.query}")result = rag_query(request.query, top_k=request.top_k)35 unmodified lines# Step 6: Gradio UI for Interactive Demo# ---------------------------------------------------------------------------def gradio_query(question: str) -> str:"""Handle queries from the Gradio chat interface."""if not question.strip():return "Please enter a question."result = rag_query(question)sources_text = "\n".join(f" - {s['source']} (relevance: {s['score']:.2f})" for s in result["sources"])return f"{result['answer']}\n\n📚 Sources:\n{sources_text}" if result["sources"] else result["answer"]def gradio_ingest(text: str, source_name: str) -> str:26 unmodified lines)query_button = gr.Button("Ask", variant="primary")query_output = gr.Textbox(label="Answer", lines=8, interactive=False)query_button.click(fn=gradio_query, inputs=query_input, outputs=query_output)with gr.Tab("📄 Ingest Documents"):gr.Markdown("Add new documents to the knowledge base.")17 unmodified lines18192021222324232 unmodified lines25725825926026126226326426526626726826927010 unmodified lines28128228328428528628728828933 unmodified lines32332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537674 unmodified lines45145245345445545645745845935 unmodified lines49549649749849950050150250350450550650750850951051151251326 unmodified lines54054154254354454554654754854955055155255355417 unmodified linesimport osimport jsonimport loggingimport timefrom pathlib import Pathfrom typing import Optional232 unmodified linesreturn contextsdef call_llm(prompt: str) -> dict:"""Make a call to the LLM via Azure Foundry (GPT-5).Calls the Azure OpenAI-compatible chat/completions endpoint.Endpoint URL is loaded from config.json; API key from AZURE_API_KEY env var.Returns a dict with 'content' (str) and 'total_tokens' (int)."""headers = {"api-key": AZURE_API_KEY,10 unmodified linesresp = http_requests.post(LLM_ENDPOINT_URL, headers=headers, json=payload, timeout=60)resp.raise_for_status()data = resp.json()content = data["choices"][0]["message"]["content"].strip()total_tokens = data.get("usage", {}).get("total_tokens", 0)return {"content": content, "total_tokens": total_tokens}except http_requests.exceptions.HTTPError as e:logger.error(f"LLM API call failed: {e} — {resp.text}")raise HTTPException(status_code=503, detail=f"LLM service unavailable: {str(e)}")33 unmodified lines2. Retrieve relevant context from vector store3. Build augmented prompt with context4. Call LLM to generate answer5. Return answer with source metadata, explanation, token count, and timing"""start_time = time.perf_counter()# Step 1: Retrieve relevant document chunkscontexts = retrieve_relevant_context(query, top_k=top_k)if not contexts:elapsed_ms = round((time.perf_counter() - start_time) * 1000, 2)return {"answer": "No documents have been ingested yet. Please upload documents first.","sources": [],"explanation": "No documents found in the vector store to retrieve context from.","total_token": 0,"run_time_in_ms": elapsed_ms,}# Step 2: Build the augmented promptprompt = build_rag_prompt(query, contexts)# Step 3: Generate answer from LLMllm_result = call_llm(prompt)raw_content = llm_result["content"]total_token = llm_result["total_tokens"]# Parse structured JSON response from LLM (handle markdown code fences)json_str = raw_content.strip()if json_str.startswith("```"):json_str = json_str.split("\n", 1)[-1]json_str = json_str.rsplit("```", 1)[0].strip()try:parsed = json.loads(json_str)answer = parsed["answer"]explanation = parsed["explanation"]except (json.JSONDecodeError, KeyError):answer = raw_contentexplanation = "LLM did not return a structured explanation."elapsed_ms = round((time.perf_counter() - start_time) * 1000, 2)# Step 4: Return structured responsereturn {"answer": answer,"sources": [{"source": ctx["source"], "score": ctx["similarity_score"]} for ctx in contexts],"explanation": explanation,"total_token": total_token,"run_time_in_ms": elapsed_ms,}74 unmodified linesReturns:- answer (str): The generated answer- sources (list): Source documents used for context- explanation (str): Explanation of the retrieval and answer logic- total_token (int): Total token count from the LLM call- run_time_in_ms (float): Pipeline execution time in milliseconds"""logger.info(f"Query received: {request.query}")result = rag_query(request.query, top_k=request.top_k)35 unmodified lines# Step 6: Gradio UI for Interactive Demo# ---------------------------------------------------------------------------def gradio_query(question: str) -> tuple[str, str, str, str]:"""Handle queries from the Gradio chat interface."""if not question.strip():return "Please enter a question.", "", "", ""result = rag_query(question)sources_text = "\n".join(f" - {s['source']} (relevance: {s['score']:.2f})" for s in result["sources"])answer = f"{result['answer']}\n\n📚 Sources:\n{sources_text}" if result["sources"] else result["answer"]explanation = result.get("explanation", "")token_info = str(result.get("total_token", 0))run_time = f"{result.get('run_time_in_ms', 0)} ms"return answer, explanation, token_info, run_timedef gradio_ingest(text: str, source_name: str) -> str:26 unmodified lines)query_button = gr.Button("Ask", variant="primary")query_output = gr.Textbox(label="Answer", lines=8, interactive=False)query_explanation = gr.Textbox(label="Explanation", lines=3, interactive=False)with gr.Row():query_tokens = gr.Textbox(label="Total Tokens", interactive=False)query_runtime = gr.Textbox(label="Run Time", interactive=False)query_button.click(fn=gradio_query,inputs=query_input,outputs=[query_output, query_explanation, query_tokens, query_runtime],)with gr.Tab("📄 Ingest Documents"):gr.Markdown("Add new documents to the knowledge base.")
1 unmodified line2345671 unmodified lineIf the context does not contain enough information to answer, say "I don't have enough information to answer this question."Always be concise and factual.Context:{context}1 unmodified line23456789101112131 unmodified lineIf the context does not contain enough information to answer, say "I don't have enough information to answer this question."Always be concise and factual.You MUST respond in valid JSON with exactly two fields:- "answer": your concise factual answer to the question- "explanation": a brief explanation of your reasoning, describing which parts of the context you used and why they led to your answerDo NOT include any text outside the JSON object.Context:{context}
app.py+55-11
prompts/rag_prompt.txt+6