Update api.py
Browse files
api.py
CHANGED
|
@@ -1,19 +1,47 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
from
|
| 4 |
-
import shutil
|
| 5 |
|
| 6 |
-
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
shutil.copyfileobj(file.file, buffer)
|
| 12 |
-
load_vectorstore("document.pdf")
|
| 13 |
-
return {"message": "File indexed successfully."}
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
| 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": []}
|