Create rag_api_client.py
Browse files- rag_api_client.py +38 -0
rag_api_client.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import aiohttp
|
3 |
+
from dotenv import load_dotenv
|
4 |
+
from urllib.parse import urlencode
|
5 |
+
|
6 |
+
load_dotenv()
|
7 |
+
|
8 |
+
async def query_rag_api(question):
|
9 |
+
"""
|
10 |
+
Asynchronously query the RAG model via Streamlit endpoint.
|
11 |
+
|
12 |
+
Args:
|
13 |
+
question (str): The user's question.
|
14 |
+
|
15 |
+
Returns:
|
16 |
+
dict: Answer, contexts, or error message.
|
17 |
+
|
18 |
+
Note:
|
19 |
+
Replace API_ENDPOINT with your Space's URL (e.g., https://<your-space-id>.hf.space)
|
20 |
+
after deployment.
|
21 |
+
"""
|
22 |
+
# Placeholder - REPLACE with your Space's URL
|
23 |
+
API_ENDPOINT = "https://huggingface.co/spaces/samim2024/testing"
|
24 |
+
params = {"query": question}
|
25 |
+
url = f"{API_ENDPOINT}?{urlencode(params)}"
|
26 |
+
|
27 |
+
try:
|
28 |
+
async with aiohttp.ClientSession() as session:
|
29 |
+
async with session.get(url, timeout=10) as response:
|
30 |
+
response_dict = await response.json()
|
31 |
+
if response_dict.get("error"):
|
32 |
+
return {"error": response_dict["error"], "answer": "", "contexts": []}
|
33 |
+
return {
|
34 |
+
"answer": response_dict.get("answer", ""),
|
35 |
+
"contexts": response_dict.get("contexts", [])
|
36 |
+
}
|
37 |
+
except Exception as e:
|
38 |
+
return {"error": f"Query failed: {str(e)}", "answer": "", "contexts": []}
|