mirxakamran893's picture
Update app.py
efbfb8b verified
raw
history blame
2.02 kB
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()