samim2024 commited on
Commit
9dd1247
·
verified ·
1 Parent(s): 6c3a044

Update api.py

Browse files
Files changed (1) hide show
  1. api.py +43 -15
api.py CHANGED
@@ -1,19 +1,47 @@
1
- # api.py
2
- from fastapi import FastAPI, UploadFile, File, Form
3
- from model import load_vectorstore, ask_question
4
- import shutil
5
 
6
- app = FastAPI()
7
 
8
- @app.post("/upload")
9
- async def upload(file: UploadFile = File(...)):
10
- with open("document.pdf", "wb") as buffer:
11
- shutil.copyfileobj(file.file, buffer)
12
- load_vectorstore("document.pdf")
13
- return {"message": "File indexed successfully."}
14
 
15
- @app.post("/ask")
16
- async def ask(question: str = Form(...)):
17
- answer = ask_question(question)
18
- return {"question": question, "answer": answer}
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import aiohttp
3
+ from dotenv import load_dotenv
 
4
 
5
+ load_dotenv()
6
 
7
+ async def query_rag_api(question):
8
+ """
9
+ Asynchronously query the RAG API for answer and contexts.
 
 
 
10
 
11
+ Args:
12
+ question (str): The user's question.
 
 
13
 
14
+ Returns:
15
+ dict: Answer, contexts, or error message.
16
+
17
+ Note:
18
+ Replace API_ENDPOINT with the actual endpoint of your Hugging Face Space
19
+ (e.g., https://<your-space-id>.hf.space/ask) after deployment.
20
+ """
21
+ # Placeholder - REPLACE with your Space's endpoint
22
+ API_ENDPOINT = "https://huggingface.co/spaces/samim2024/testing:8000/ask" # Update to Space URL post-deployment
23
+ api_key = os.getenv("HUGGINGFACEHUB_API_TOKEN")
24
+
25
+ if not api_key:
26
+ return {"error": "HUGGINGFACEHUB_API_TOKEN not set", "answer": "", "contexts": []}
27
+
28
+ headers = {"Content-Type": "application/json"}
29
+ payload = {"question": question}
30
+
31
+ try:
32
+ async with aiohttp.ClientSession() as session:
33
+ async with session.post(
34
+ API_ENDPOINT,
35
+ json=payload,
36
+ headers=headers,
37
+ timeout=10
38
+ ) as response:
39
+ response_dict = await response.json()
40
+ if response_dict.get("error"):
41
+ return {"error": response_dict["error"], "answer": "", "contexts": []}
42
+ return {
43
+ "answer": response_dict.get("answer", ""),
44
+ "contexts": response_dict.get("contexts", [])
45
+ }
46
+ except Exception as e:
47
+ return {"error": f"API call failed: {str(e)}", "answer": "", "contexts": []}