File size: 1,621 Bytes
9dd1247
 
 
f5eeece
9dd1247
f5eeece
9dd1247
 
 
f5eeece
9dd1247
 
f5eeece
9dd1247
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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": []}