Spaces:
Runtime error
Runtime error
Update app.py
Browse files12345678910111213141516171819202122232412345678910112627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102121314151617181920212223242526272829303132333435import osimport loggingfrom contextlib import asynccontextmanagerfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import HTMLResponsefrom pydantic import BaseModelimport cohereimport chromadbfrom chromadb.config import Settingsfrom sentence_transformers import SentenceTransformer
# 1. Setup Logging (Essential for professional apps)logging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
# 2. Configuration & ClientsCOHERE_API_KEY = os.getenv("COHERE_API_KEY")CHROMA_PATH = "./chroma_db" # Persistent storage directory
if not COHERE_API_KEY: raise ValueError("Missing COHERE_API_KEY environment variable")
co = cohere.Client(COHERE_API_KEY) from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import HTMLResponse from pydantic import BaseModel import cohere from chromadb import Client from sentence_transformers import SentenceTransformer import os
# -------------------- # App setup # -------------------- app = FastAPI()
app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"] )
# -------------------- # Clients & models # -------------------- co = cohere.Client(os.getenv("COHERE_API_KEY"))
client = Client() # HF-compatible (no folders) collection = client.get_or_create_collection(name="docs")
embed_model = SentenceTransformer("all-MiniLM-L6-v2")db_client = chromadb.PersistentClient(path=CHROMA_PATH)
# 3. Lifespan for efficient startup/shutdown@asynccontextmanagerasync def lifespan(app: FastAPI): logger.info("Starting up: Initializing database...") collection = db_client.get_or_create_collection(name="bakery_docs") # Professional Ingestion: Batching + Only if empty if collection.count() == 0: docs = [ "Welcome to my bakery. We sell cookies and cakes.", "Our delivery policy: we deliver within 2 days in Karachi.", "Contact us at info@example.com for queries." ] # Batch encode instead of a loop for 10x speedup embeddings = embed_model.encode(docs).tolist() ids = [str(i) for i in range(len(docs))] collection.add(documents=docs, embeddings=embeddings, ids=ids) logger.info(f"Ingested {len(docs)} documents.") yield logger.info("Shutting down...")
app = FastAPI(lifespan=lifespan)
app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
# 4. Schemasclass Query(BaseModel): message: str
# 5. Routes@app.get("/", response_class=HTMLResponse)async def serve_ui(): try: with open("index.html", "r", encoding="utf-8") as f: return f.read() except FileNotFoundError: return "UI file not found. Ensure index.html is in the root folder."
@app.post("/chat")async def chat(query: Query): try: # Get collection instance collection = db_client.get_collection(name="bakery_docs") # Retrieval query_emb = embed_model.encode(query.message).tolist() results = collection.query(query_embeddings=[query_emb], n_results=2) context = "\n".join(results["documents"][0]) if results["documents"] else "No context found."
# Professional Prompting: System instructions to prevent "I don't know" or off-topic rants system_message = ( "You are a professional, friendly assistant for a bakery in Karachi. " "Use the provided context to answer questions. If the answer is not in the context, " "politely say you don't know and offer to contact support at info@example.com." )
# Cohere API Call with error handling response = co.chat( model="command-r7b-12-2024", message=f"Context:\n{context}\n\nQuestion: {query.message}", preamble=system_message # Sets the "Persona" )
return {"reply": response.text, "context_used": context}
except Exception as e: logger.error(f"Error in /chat: {str(e)}") raise HTTPException(status_code=500, detail="Internal Server Error")
# -------------------- # One-time ingestion # -------------------- docs = [ "Welcome to my bakery. We sell cookies and cakes.", "Our delivery policy: we deliver within 2 days in Karachi.", "Contact us at info@example.com for queries." ]
if collection.count() == 0: for i, doc in enumerate(docs): emb = embed_model.encode(doc).tolist() collection.add( documents=[doc], embeddings=[emb], ids=[str(i)] )
# -------------------- # Schemas # -------------------- class Query(BaseModel): message: str
# -------------------- # Routes # -------------------- @app.get("/", response_class=HTMLResponse) def serve_ui(): with open("index.html", "r", encoding="utf-8") as f: return f.read()
@app.post("/chat") def chat(query: Query): query_emb = embed_model.encode(query.message).tolist()
results = collection.query( query_embeddings=[query_emb], n_results=3 )
context_docs = results["documents"][0] context = "\n".join(context_docs)
prompt = f""" Use the context below to answer the question.
Context: {context}
Question: {query.message} """
response = co.chat( model="command-r7b-12-2024", message=prompt )
return {"reply": response.text} app.py+34-101