Spaces:
Runtime error

AIM-V / app.py
sgfernandes's picture
space: add OpenAI quota fallback -> extractive TF-IDF answer
a2f30c4
Raw History Blame Contribute Delete
7.02 kB
"""Hugging Face Space app for AIM-V (Gradio).
Usage:
- Add this repo's files to a new Space (LBL-BIA/AIM-V).
- Set `OPENAI_API_KEY` in the Space settings (Secrets).
- The Space will install `requirements.txt` and run this app.
"""
from pathlib import Path
import os
import json
import gradio as gr
import chromadb
from chromadb.config import Settings
from chromadb.utils import embedding_functions
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import openai
from openai import OpenAI
import traceback
import sys
ROOT = Path(__file__).resolve().parent
PROC = ROOT / "data" / "processed"
CHROMA_DIR = PROC / "chroma"
CHROMA_DIR.mkdir(parents=True, exist_ok=True)
def load_corpus():
path = PROC / "corpus.jsonl"
if not path.exists():
return []
corpus = [json.loads(l) for l in open(path, encoding="utf-8")]
return corpus
def get_chroma_collection(api_key: str):
ef = embedding_functions.OpenAIEmbeddingFunction(api_key=api_key, model_name="text-embedding-3-small")
# Wrap client creation in try/except to allow migration/deprecation errors to bubble
client = chromadb.Client(Settings(chroma_db_impl="duckdb+parquet", persist_directory=str(CHROMA_DIR)))
col = client.get_or_create_collection(name="itv_reports", embedding_function=ef)
return client, col
def tfidf_retriever(corpus, query, k=3):
# corpus: list of dicts with 'id' and 'text'
docs = [d['text'] for d in corpus]
ids = [d['id'] for d in corpus]
if not docs:
return []
vect = TfidfVectorizer(stop_words='english').fit(docs + [query])
doc_vecs = vect.transform(docs)
q_vec = vect.transform([query])
sims = cosine_similarity(q_vec, doc_vecs).flatten()
idxs = sims.argsort()[::-1][:k]
assembled = []
for i in idxs:
assembled.append({'id': ids[i], 'text': docs[i], 'meta': {}})
return assembled
def ensure_embeddings(collection):
if collection.count() == 0:
corpus = load_corpus()
if not corpus:
return
ids = [d["id"] for d in corpus]
docs = [d["text"] for d in corpus]
metas = [{"title": d.get("title", "")} for d in corpus]
collection.add(ids=ids, documents=docs, metadatas=metas)
def retrieve_with_chroma(collection, query: str, k: int = 3):
res = collection.query(query_texts=[query], n_results=k)
docs = res.get("documents", [[]])[0]
metadatas = res.get("metadatas", [[]])[0]
ids = res.get("ids", [[]])[0]
assembled = []
for i, doc in enumerate(docs):
meta = metadatas[i] if i < len(metadatas) else {}
sid = ids[i] if i < len(ids) else str(i)
assembled.append({"id": sid, "text": doc, "meta": meta})
return assembled
def build_system_prompt():
return (
"You are an expert Measurement & Verification analyst. Use ONLY the provided context. "
"Cite sources as [source:id]. If you cannot answer from context, say 'I don't know'. Be concise."
)
def answer(query: str):
try:
openai_key = os.getenv("OPENAI_API_KEY")
if not openai_key:
return "OPENAI_API_KEY not set in Space. Set it in Settings -> Secrets."
# Try Chroma first; if Chroma raises a migration/deprecation error, fall back to TF-IDF
hits = []
try:
client, collection = get_chroma_collection(openai_key)
ensure_embeddings(collection)
hits = retrieve_with_chroma(collection, query, k=3)
except Exception as chroma_exc:
# Detect the specific migration/deprecation guidance in the error text
msg = str(chroma_exc)
if 'deprecated configuration of Chroma' in msg or 'chroma-migrate' in msg or 'New Clients' in msg:
# Use simple TF-IDF fallback over the corpus
corpus = load_corpus()
hits = tfidf_retriever(corpus, query, k=3)
else:
# Re-raise for other unexpected chroma errors
raise
context_parts = [f"[source:{h['id']}] {h['text'][:2000]}" for h in hits]
context = "\n\n---\n\n".join(context_parts)
system_prompt = build_system_prompt()
user_message = f"Context:\n{context}\n\nQuestion:\n{query}\n\nAnswer and cite sources."
# Use the new OpenAI client API with a quota fallback
client = OpenAI(api_key=openai_key)
try:
resp = client.chat.completions.create(
model=os.getenv("OPENAI_MODEL", "gpt-4o"),
messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_message}],
max_tokens=512,
temperature=0.0,
)
return resp.choices[0].message.content.strip()
except Exception as oe:
# Detect quota/429 errors and fall back to local extractive answer
msg = str(oe).lower()
if 'insufficient_quota' in msg or 'quota' in msg or 'rate limit' in msg or '429' in msg:
corpus_local = load_corpus()
if not corpus_local:
return "OpenAI quota exceeded and no local corpus available to provide an extractive answer."
extract_hits = tfidf_retriever(corpus_local, query, k=3)
parts = []
for h in extract_hits:
text = h.get('text', '')
snippet = text.strip().replace('\n', ' ')[:1000]
parts.append(f"[source:{h.get('id')}] {snippet}")
extractive = "\n\n".join(parts)
return (
"OpenAI quota exceeded; returning an extractive answer from the local corpus:\n\n"
+ extractive
)
# re-raise other exceptions
raise
except Exception as e:
tb = traceback.format_exc()
# Print to stdout/stderr so the Space logs capture the traceback
print("Error in answer():", file=sys.stderr)
print(tb, file=sys.stderr)
# Return a readable error to the UI so we can debug without opaque Gradio errors
short = str(e)
return f"Error: {short}\n\nTraceback (first 1000 chars):\n{tb[:1000]}"
def main():
corpus = load_corpus()
if not corpus:
hint = "No corpus found. Upload `corpus.jsonl` into data/processed/ or run ingestion locally and push the file."
else:
hint = f"Loaded {len(corpus)} documents."
with gr.Blocks() as demo:
gr.Markdown("# AIM-V — ITV M&V Assistant (RAG)")
gr.Markdown(hint)
with gr.Row():
q = gr.Textbox(label="Question", placeholder="Ask about M&V or these reports")
btn = gr.Button("Ask")
out = gr.Textbox(label="Answer", lines=12)
def on_ask(query_text):
return answer(query_text)
btn.click(on_ask, inputs=q, outputs=out)
demo.launch()
if __name__ == '__main__':
main()