File size: 2,023 Bytes
51ce63b
 
bb68426
efbfb8b
51ce63b
bb68426
efbfb8b
bb68426
 
 
51ce63b
efbfb8b
51ce63b
 
 
efbfb8b
 
 
 
bb68426
 
51ce63b
efbfb8b
 
 
 
 
 
 
 
 
bb68426
efbfb8b
 
 
 
51ce63b
efbfb8b
 
51ce63b
efbfb8b
 
51ce63b
 
bb68426
51ce63b
 
 
 
bb68426
 
51ce63b
 
 
efbfb8b
 
 
51ce63b
bb68426
 
 
51ce63b
efbfb8b
 
 
 
51ce63b
efbfb8b
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import gradio as gr
import faiss
import numpy as np
import json
import os
import requests
from sentence_transformers import SentenceTransformer

# Load embedding model
embed_model = SentenceTransformer("all-MiniLM-L6-v2")

# Load your data
with open("texts.json", "r") as f:
    texts = json.load(f)

index = faiss.read_index("faiss_index.bin")
text_embeddings = embed_model.encode(texts)

# API info
API_KEY = os.environ.get("OPENROUTER_API_KEY")
MODEL = "deepseek/deepseek-chat-v3-0324:free"

def get_relevant_context(question, top_k=3, threshold=0.6):
    question_embedding = embed_model.encode([question])
    distances, indices = index.search(np.array(question_embedding), top_k)
    
    context = []
    for i, dist in zip(indices[0], distances[0]):
        if dist < threshold:
            context.append(texts[i])
    return context

def chat_with_data(message, history):
    context = get_relevant_context(message)
    if not context:
        return "❌ Sorry, I can only help with topics related to LogiqCurve."

    context_text = "\n".join(context)
    prompt = f"You are a helpful assistant for LogiqCurve. Use only the following context:\n\n{context_text}\n\nUser: {message}"

    messages = [{"role": "system", "content": "You are a helpful assistant that only uses provided context."}]
    messages.append({"role": "user", "content": prompt})

    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }

    payload = {
        "model": MODEL,
        "messages": messages
    }

    try:
        res = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload)
        res.raise_for_status()
        reply = res.json()["choices"][0]["message"]["content"]
    except Exception as e:
        reply = f"❌ Error: {e}"

    return reply

gr.ChatInterface(
    fn=chat_with_data,
    title="LogiqCurve Assistant",
    description="Ask anything about LogiqCurve (based on website data only)",
    theme="soft"
).launch()