|
import os |
|
import aiohttp |
|
from dotenv import load_dotenv |
|
from urllib.parse import urlencode |
|
|
|
load_dotenv() |
|
|
|
async def query_rag_api(question): |
|
""" |
|
Asynchronously query the RAG model via Streamlit endpoint. |
|
|
|
Args: |
|
question (str): The user's question. |
|
|
|
Returns: |
|
dict: Answer, contexts, or error message. |
|
|
|
Note: |
|
Replace API_ENDPOINT with your Space's URL (e.g., https://<your-space-id>.hf.space) |
|
after deployment. |
|
""" |
|
|
|
API_ENDPOINT = "https://huggingface.co/spaces/samim2024/testing" |
|
params = {"query": question} |
|
url = f"{API_ENDPOINT}?{urlencode(params)}" |
|
|
|
try: |
|
async with aiohttp.ClientSession() as session: |
|
async with session.get(url, 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"Query failed: {str(e)}", "answer": "", "contexts": []} |