Spaces:
Runtime error
Runtime error
File size: 1,856 Bytes
be8a524 4f2bcc7 be8a524 4f2bcc7 be8a524 4f2bcc7 be8a524 d235af9 be8a524 4f2bcc7 be8a524 4f2bcc7 be8a524 4f2bcc7 be8a524 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | 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")
# -------------------- # 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} |