Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import faiss
|
3 |
+
import numpy as np
|
4 |
+
import json
|
5 |
+
from sentence_transformers import SentenceTransformer
|
6 |
+
import os
|
7 |
+
|
8 |
+
# Load your content and index
|
9 |
+
with open("texts.json", "r") as f:
|
10 |
+
texts = json.load(f)
|
11 |
+
|
12 |
+
index = faiss.read_index("faiss_index.bin")
|
13 |
+
|
14 |
+
# Load embedding model
|
15 |
+
embed_model = SentenceTransformer("all-MiniLM-L6-v2")
|
16 |
+
|
17 |
+
# Helper to retrieve relevant chunks
|
18 |
+
def retrieve_chunks(query, k=5):
|
19 |
+
query_emb = embed_model.encode([query])
|
20 |
+
D, I = index.search(np.array(query_emb), k)
|
21 |
+
return [texts[i] for i in I[0] if i < len(texts)]
|
22 |
+
|
23 |
+
# Main chatbot function
|
24 |
+
def rag_chatbot(message, history, request: gr.Request):
|
25 |
+
user_header = request.headers.get("X-Source", "")
|
26 |
+
if user_header == "wordpress":
|
27 |
+
# RAG logic for WordPress embed
|
28 |
+
context_chunks = retrieve_chunks(message)
|
29 |
+
context = "\n".join(context_chunks)
|
30 |
+
if not context.strip():
|
31 |
+
return "❌ I'm sorry, I can only assist with questions related to LogiqCurve.com."
|
32 |
+
prompt = f"Answer based ONLY on this content:\n{context}\n\nQuestion: {message}"
|
33 |
+
else:
|
34 |
+
# Public fallback (general AI)
|
35 |
+
prompt = message
|
36 |
+
|
37 |
+
# Use OpenRouter API
|
38 |
+
headers = {
|
39 |
+
"Authorization": f"Bearer {os.environ.get('OPENROUTER_API_KEY')}",
|
40 |
+
"Content-Type": "application/json"
|
41 |
+
}
|
42 |
+
|
43 |
+
payload = {
|
44 |
+
"model": "deepseek/deepseek-chat-v3-0324:free",
|
45 |
+
"messages": [
|
46 |
+
{"role": "system", "content": "You are a helpful assistant."},
|
47 |
+
{"role": "user", "content": prompt}
|
48 |
+
]
|
49 |
+
}
|
50 |
+
|
51 |
+
try:
|
52 |
+
import requests
|
53 |
+
res = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload)
|
54 |
+
res.raise_for_status()
|
55 |
+
return res.json()["choices"][0]["message"]["content"]
|
56 |
+
except Exception as e:
|
57 |
+
return f"❌ API Error: {e}"
|
58 |
+
|
59 |
+
# Gradio interface
|
60 |
+
iface = gr.ChatInterface(
|
61 |
+
fn=rag_chatbot,
|
62 |
+
title="LogiqCurve WordPress Assistant",
|
63 |
+
description="Answers only based on the content of LogiqCurve.com",
|
64 |
+
theme="soft"
|
65 |
+
)
|
66 |
+
|
67 |
+
iface.launch()
|