File size: 1,549 Bytes
836bc0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
48
import os
from datetime import datetime
from supabase import create_client, Client
import requests

SUPABASE_URL = os.getenv("SUPABASE_URL")
SUPABASE_KEY = os.getenv("SUPABASE_KEY")

supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)

def get_geo_location(ip: str) -> str:
    """
    Fetch approximate geo-location for the given IP address.
    Returns 'Unknown' if lookup fails.
    """
    try:
        if ip.startswith("127.") or ip == "localhost":
            return "Localhost"
        resp = requests.get(f"https://ipapi.co/{ip}/country_name/", timeout=3)
        if resp.status_code == 200:
            return resp.text.strip() or "Unknown"
    except Exception:
        pass
    return "Unknown"

def log_query(document_source: str, question: str, answer: str,
              ip_address: str, response_time: float,
              user_agent: str = None):
    """
    Store a question-answer log in Supabase with geo-location and user-agent.
    """
    now_str = datetime.utcnow().isoformat()
    geo_location = get_geo_location(ip_address)

    try:
        supabase.table("qa_logs").insert({
            "document_source": document_source,
            "question": question,
            "answer": answer,
            "ip_address": ip_address,
            "geo_location": geo_location,
            "user_agent": user_agent or "Unknown",
            "response_time_sec": round(response_time, 2),
            "created_at": now_str
        }).execute()
    except Exception as e:
        print(f"Failed to log query to Supabase: {e}")