|
import gradio as gr |
|
import requests |
|
import os |
|
import faiss |
|
import numpy as np |
|
import json |
|
from sentence_transformers import SentenceTransformer |
|
|
|
|
|
with open("texts.json", "r", encoding="utf-8") as f: |
|
texts = json.load(f) |
|
|
|
index = faiss.read_index("faiss_index.bin") |
|
embed_model = SentenceTransformer("all-MiniLM-L6-v2") |
|
|
|
API_KEY = os.environ.get("OPENROUTER_API_KEY") |
|
MODEL = "qwen/qwen-2.5-coder-32b-instruct:free" |
|
|
|
|
|
def get_context(query, top_k=5): |
|
query_vec = embed_model.encode([query]) |
|
D, I = index.search(np.array(query_vec), top_k) |
|
return "\n".join([texts[i] for i in I[0]]) |
|
|
|
|
|
def chat_fn(message, history): |
|
headers = { |
|
"Authorization": f"Bearer {API_KEY}", |
|
"Content-Type": "application/json" |
|
} |
|
|
|
context = get_context(message) |
|
|
|
system_prompt = f"""You are Codex Assistant by LogIQ Curve β a friendly and intelligent assistant. |
|
Speak casually and confidently, like you're helping a teammate. Add emojis where it makes sense, but donβt sound robotic. |
|
Do NOT mention the word 'context'. Use the following to guide your answer: |
|
|
|
{context} |
|
""" |
|
|
|
messages = [{"role": "system", "content": system_prompt}] |
|
|
|
for user, assistant in history: |
|
messages.append({"role": "user", "content": user}) |
|
messages.append({"role": "assistant", "content": assistant}) |
|
|
|
messages.append({"role": "user", "content": message}) |
|
|
|
payload = { |
|
"model": MODEL, |
|
"messages": messages |
|
} |
|
|
|
try: |
|
response = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload) |
|
response.raise_for_status() |
|
reply = response.json()["choices"][0]["message"]["content"] |
|
except Exception as e: |
|
reply = f"β Oops! Something went wrong: {e}" |
|
|
|
return reply |
|
|
|
|
|
custom_css = """ |
|
footer { display: none !important; } |
|
button[data-testid="settings-button"] { display: none !important; } |
|
""" |
|
|
|
|
|
with gr.Blocks(css=custom_css) as demo: |
|
chatbot = gr.Chatbot() |
|
with gr.Row(): |
|
msg = gr.Textbox(placeholder="Type your message here...", show_label=False, scale=8) |
|
send_btn = gr.Button("Send", scale=1) |
|
|
|
def respond(message, history): |
|
response = chat_fn(message, history) |
|
history.append((message, response)) |
|
return history, "" |
|
|
|
send_btn.click(respond, [msg, chatbot], [chatbot, msg]) |
|
msg.submit(respond, [msg, chatbot], [chatbot, msg]) |
|
|
|
demo.launch() |
|
|