Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# app.py (Gradio version for Hugging Face Spaces)
|
2 |
+
import gradio as gr
|
3 |
+
import openai
|
4 |
+
import threading
|
5 |
+
import time
|
6 |
+
import numpy as np
|
7 |
+
import faiss
|
8 |
+
import os
|
9 |
+
import pickle
|
10 |
+
from openai.embeddings_utils import get_embedding, cosine_similarity
|
11 |
+
|
12 |
+
# === CONFIG ===
|
13 |
+
openai.api_key = os.environ.get("OPENAI_API_KEY")
|
14 |
+
EMBEDDING_MODEL = "text-embedding-ada-002"
|
15 |
+
CHAT_MODEL = "gpt-4o-mini"
|
16 |
+
|
17 |
+
# === MEMORY ===
|
18 |
+
memory_data = []
|
19 |
+
try:
|
20 |
+
memory_index = faiss.read_index("memory.index")
|
21 |
+
with open("memory.pkl", "rb") as f:
|
22 |
+
memory_data = pickle.load(f)
|
23 |
+
except:
|
24 |
+
memory_index = faiss.IndexFlatL2(1536)
|
25 |
+
|
26 |
+
# === SYSTEM PROMPTS ===
|
27 |
+
AGENT_PROMPT = "You are a helpful agent in an ongoing dialogue. Respond meaningfully."
|
28 |
+
OVERSEER_PROMPT = "You are the Overseer agent. Monitor Agent A and B, learn, and intervene when appropriate."
|
29 |
+
|
30 |
+
conversation = []
|
31 |
+
auto_mode = False
|
32 |
+
|
33 |
+
# === AGENT ===
|
34 |
+
def chat_completion(system, messages):
|
35 |
+
try:
|
36 |
+
response = openai.ChatCompletion.create(
|
37 |
+
model=CHAT_MODEL,
|
38 |
+
messages=[{"role": "system", "content": system}] + messages,
|
39 |
+
temperature=0.7
|
40 |
+
)
|
41 |
+
return response.choices[0].message.content.strip()
|
42 |
+
except Exception as e:
|
43 |
+
return f"[Error: {e}]"
|
44 |
+
|
45 |
+
# === FAISS EMBED ===
|
46 |
+
def embed_and_store(text):
|
47 |
+
try:
|
48 |
+
vec = get_embedding(text, engine=EMBEDDING_MODEL)
|
49 |
+
memory_index.add(np.array([vec], dtype='float32'))
|
50 |
+
memory_data.append(text)
|
51 |
+
with open("memory.pkl", "wb") as f:
|
52 |
+
pickle.dump(memory_data, f)
|
53 |
+
faiss.write_index(memory_index, "memory.index")
|
54 |
+
except Exception as e:
|
55 |
+
print(f"Embed error: {e}")
|
56 |
+
|
57 |
+
# === CONVERSATION ===
|
58 |
+
def step():
|
59 |
+
global conversation
|
60 |
+
turn = len(conversation)
|
61 |
+
agent = "Agent A" if turn % 2 == 0 else "Agent B"
|
62 |
+
msgs = [{"role": "assistant", "content": m['text']} for m in conversation]
|
63 |
+
reply = chat_completion(AGENT_PROMPT, msgs)
|
64 |
+
conversation.append({"agent": agent, "text": reply})
|
65 |
+
embed_and_store(reply)
|
66 |
+
return format_convo(), ""
|
67 |
+
|
68 |
+
def format_convo():
|
69 |
+
return "\n".join([f"**{m['agent']}**: {m['text']}" for m in conversation])
|
70 |
+
|
71 |
+
# === OVERSEER ===
|
72 |
+
def overseer_respond(query):
|
73 |
+
try:
|
74 |
+
qvec = get_embedding(query, engine=EMBEDDING_MODEL)
|
75 |
+
sims = cosine_similarity(qvec, [get_embedding(m, engine=EMBEDDING_MODEL) for m in memory_data])
|
76 |
+
top_idxs = np.argsort(sims)[-3:][::-1]
|
77 |
+
context = "\n".join([memory_data[i] for i in top_idxs])
|
78 |
+
msgs = [{"role": "user", "content": f"Context:\n{context}\nQuestion:{query}"}]
|
79 |
+
return chat_completion(OVERSEER_PROMPT, msgs)
|
80 |
+
except Exception as e:
|
81 |
+
return f"[Overseer Error: {e}]"
|
82 |
+
|
83 |
+
# === AUTO LOOP ===
|
84 |
+
def auto_loop():
|
85 |
+
global auto_mode
|
86 |
+
while auto_mode:
|
87 |
+
step()
|
88 |
+
time.sleep(5)
|
89 |
+
|
90 |
+
# === GRADIO UI ===
|
91 |
+
with gr.Blocks() as demo:
|
92 |
+
gr.Markdown("# 🤖 Tri-Agent Conversational AI (Hugging Face Edition)")
|
93 |
+
with gr.Row():
|
94 |
+
convo_display = gr.Markdown(value="")
|
95 |
+
step_btn = gr.Button("Manual Step")
|
96 |
+
auto_btn = gr.Button("Toggle Auto Mode")
|
97 |
+
|
98 |
+
with gr.Accordion("🧠 Overseer Panel", open=False):
|
99 |
+
qbox = gr.Textbox(label="Ask the Overseer")
|
100 |
+
overseer_out = gr.Textbox(label="Overseer's Response")
|
101 |
+
|
102 |
+
def toggle_auto():
|
103 |
+
global auto_mode
|
104 |
+
auto_mode = not auto_mode
|
105 |
+
if auto_mode:
|
106 |
+
threading.Thread(target=auto_loop, daemon=True).start()
|
107 |
+
return "Auto Mode: ON" if auto_mode else "Auto Mode: OFF"
|
108 |
+
|
109 |
+
step_btn.click(step, outputs=[convo_display, overseer_out])
|
110 |
+
qbox.submit(overseer_respond, inputs=qbox, outputs=overseer_out)
|
111 |
+
auto_btn.click(toggle_auto, outputs=auto_btn)
|
112 |
+
|
113 |
+
demo.launch()
|