testing / api.py
samim2024's picture
Update api.py
9dd1247 verified
raw
history blame
1.62 kB
import os
import aiohttp
from dotenv import load_dotenv
load_dotenv()
async def query_rag_api(question):
"""
Asynchronously query the RAG API for answer and contexts.
Args:
question (str): The user's question.
Returns:
dict: Answer, contexts, or error message.
Note:
Replace API_ENDPOINT with the actual endpoint of your Hugging Face Space
(e.g., https://<your-space-id>.hf.space/ask) after deployment.
"""
# Placeholder - REPLACE with your Space's endpoint
API_ENDPOINT = "https://huggingface.co/spaces/samim2024/testing:8000/ask" # Update to Space URL post-deployment
api_key = os.getenv("HUGGINGFACEHUB_API_TOKEN")
if not api_key:
return {"error": "HUGGINGFACEHUB_API_TOKEN not set", "answer": "", "contexts": []}
headers = {"Content-Type": "application/json"}
payload = {"question": question}
try:
async with aiohttp.ClientSession() as session:
async with session.post(
API_ENDPOINT,
json=payload,
headers=headers,
timeout=10
) as response:
response_dict = await response.json()
if response_dict.get("error"):
return {"error": response_dict["error"], "answer": "", "contexts": []}
return {
"answer": response_dict.get("answer", ""),
"contexts": response_dict.get("contexts", [])
}
except Exception as e:
return {"error": f"API call failed: {str(e)}", "answer": "", "contexts": []}