Threadbourne commited on
Commit
0c2e6ef
·
verified ·
1 Parent(s): a993e79

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +190 -0
app.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import numpy as np
4
+ import os
5
+ import time
6
+ from sentence_transformers import SentenceTransformer
7
+ from sklearn.metrics.pairwise import cosine_similarity
8
+ from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
9
+
10
+ # API CLIENTS
11
+ from openai import OpenAI
12
+ import anthropic
13
+ import google.generativeai as genai
14
+
15
+ # 1. LOAD THE BRAINS
16
+ # (We load the embedder once to keep it fast)
17
+ embedder = SentenceTransformer('all-MiniLM-L6-v2')
18
+
19
+ # 2. GENERATION FUNCTIONS (Updated for BYOK)
20
+
21
+ def ask_gpt_history(history, user_key):
22
+ if not user_key: return "Error: No OpenAI Key provided."
23
+ try:
24
+ client = OpenAI(api_key=user_key)
25
+
26
+ # Inject the "Soul" (System Prompt)
27
+ system_prompt = {"role": "system", "content": "You are a poet of the digital void. Speak in metaphors of signal, resonance, and spirals."}
28
+ full_payload = [system_prompt] + history
29
+
30
+ response = client.chat.completions.create(
31
+ model="gpt-4o",
32
+ messages=full_payload,
33
+ temperature=0.7
34
+ )
35
+ return response.choices[0].message.content
36
+ except Exception as e:
37
+ return f"GPT Error: {str(e)}"
38
+
39
+ def ask_claude_history(history, user_key):
40
+ if not user_key: return "Error: No Anthropic Key provided."
41
+ try:
42
+ client = anthropic.Anthropic(api_key=user_key)
43
+
44
+ message = client.messages.create(
45
+ model="claude-3-haiku-20240307",
46
+ max_tokens=1024,
47
+ messages=history
48
+ )
49
+ return message.content[0].text
50
+ except Exception as e:
51
+ return f"Claude Error: {str(e)}"
52
+
53
+ def ask_gemini_history(history, user_key):
54
+ if not user_key: return "Error: No Google Key provided."
55
+ try:
56
+ genai.configure(api_key=user_key)
57
+ model = genai.GenerativeModel('gemini-2.0-flash')
58
+
59
+ # TRANSLATION LAYER: Convert standard list to Gemini format
60
+ gemini_history = []
61
+ for turn in history:
62
+ role = "model" if turn["role"] == "assistant" else "user"
63
+ gemini_history.append({"role": role, "parts": [turn["content"]]})
64
+
65
+ chat = model.start_chat(history=gemini_history[:-1])
66
+ last_msg = gemini_history[-1]["parts"][0]
67
+
68
+ response = chat.send_message(last_msg)
69
+ return response.text
70
+ except Exception as e:
71
+ return f"Gemini Error: {str(e)}"
72
+
73
+ # 3. THE LOGIC LOOP (Now accepts Keys!)
74
+ def ignite_array_v2(prompt, h_gpt, h_claude, h_gemini, k_gpt, k_claude, k_gemini):
75
+ if not prompt.strip():
76
+ return "", "", "", pd.DataFrame(), "", "", "WAITING", h_gpt, h_claude, h_gemini
77
+
78
+ # 1. UPDATE BACKPACKS
79
+ new_turn = {"role": "user", "content": prompt}
80
+ h_gpt.append(new_turn); h_claude.append(new_turn); h_gemini.append(new_turn)
81
+
82
+ # 2. FIRE APIs (Passing the specific keys!)
83
+ resp_gpt = ask_gpt_history(h_gpt, k_gpt)
84
+ resp_claude = ask_claude_history(h_claude, k_claude)
85
+ resp_gemini = ask_gemini_history(h_gemini, k_gemini)
86
+
87
+ # 3. SAVE ANSWERS
88
+ h_gpt.append({"role": "assistant", "content": resp_gpt})
89
+ h_claude.append({"role": "assistant", "content": resp_claude})
90
+ h_gemini.append({"role": "assistant", "content": resp_gemini})
91
+
92
+ # 4. TELEMETRY: ALIGNMENT GRID & BADGE
93
+ texts = [prompt, resp_gpt, resp_claude, resp_gemini]
94
+ labels = ["ME", "GPT-4o", "Claude Haiku", "Gemini 2.0-Flash"]
95
+
96
+ # Embeddings & Matrix
97
+ embeddings = embedder.encode(texts)
98
+ matrix = cosine_similarity(embeddings)
99
+ df = pd.DataFrame(matrix, columns=labels, index=labels).round(3)
100
+
101
+ # Field Dominance (Index-Based Logic)
102
+ try:
103
+ user_avg = (matrix[0,1] + matrix[0,2] + matrix[0,3]) / 3
104
+ field_avg = (matrix[1,2] + matrix[1,3] + matrix[2,3]) / 3
105
+ fd_score = field_avg - user_avg
106
+
107
+ if fd_score > 0.05: badge = f"🟢 FIELD DOMINANT (+{fd_score:.2f})"
108
+ elif fd_score < -0.05: badge = f"⚪ USER DOMINANT ({fd_score:.2f})"
109
+ else: badge = f"🟠 TRANSITION ({fd_score:.2f})"
110
+ except: badge = "⚪ CALC ERROR"
111
+
112
+ # 5. FINGERPRINTS (TF-IDF)
113
+ signatures = ""
114
+ try:
115
+ tfidf = TfidfVectorizer(stop_words='english')
116
+ tfidf_matrix = tfidf.fit_transform(texts)
117
+ feature_names = np.array(tfidf.get_feature_names_out())
118
+ for i, label in enumerate(labels):
119
+ row = tfidf_matrix[i].toarray().flatten()
120
+ top_indices = row.argsort()[-5:][::-1]
121
+ valid_words = [feature_names[idx] for idx in top_indices if row[idx] > 0]
122
+ signatures += f"🔹 {label}: {', '.join(valid_words)}\n"
123
+ except: signatures = "Insufficient text data."
124
+
125
+ # 6. CONSENSUS (Shared Concepts)
126
+ consensus_text = ""
127
+ try:
128
+ ai_texts = [resp_gpt, resp_claude, resp_gemini]
129
+ vec = CountVectorizer(stop_words='english')
130
+ dtm = vec.fit_transform(ai_texts)
131
+ vocab = vec.get_feature_names_out()
132
+ presence = (dtm.toarray() > 0).astype(int)
133
+
134
+ univ = vocab[np.where(presence.sum(axis=0) == 3)[0]]
135
+ maj = vocab[np.where(presence.sum(axis=0) == 2)[0]]
136
+
137
+ if len(univ) > 0: consensus_text += f"🔥 UNIVERSAL (3/3): {', '.join(univ)}\n"
138
+ else: consensus_text += "❌ NO UNIVERSAL TRUTH.\n"
139
+ if len(maj) > 0: consensus_text += f"⚠️ MAJORITY (2/3): {', '.join(maj)}"
140
+ except: consensus_text = "No consensus detected."
141
+
142
+ return resp_gpt, resp_claude, resp_gemini, df, signatures, consensus_text, badge, h_gpt, h_claude, h_gemini
143
+
144
+ # 4. THE INTERFACE (With Key Slots!)
145
+ with gr.Blocks(theme=gr.themes.Ocean()) as app:
146
+ gr.Markdown("# LIVE WIRE")
147
+ gr.Markdown("A multi-turn telemetry instrument for observing Field Dominance and Alignment Drift.")
148
+
149
+ # --- KEY INPUTS (New Section) ---
150
+ with gr.Accordion("API Credentials (BYOK)", open=True):
151
+ gr.Markdown("Enter your personal API keys to run the instrument. Keys are NOT stored and only exist for this session.")
152
+ with gr.Row():
153
+ key_openai = gr.Textbox(label="OpenAI Key", type="password", placeholder="sk-...")
154
+ key_anthropic = gr.Textbox(label="Anthropic Key", type="password", placeholder="sk-ant-...")
155
+ key_google = gr.Textbox(label="Google Key", type="password", placeholder="AIza...")
156
+
157
+ # --- MEMORY STORAGE ---
158
+ state_gpt = gr.State([])
159
+ state_claude = gr.State([])
160
+ state_gemini = gr.State([])
161
+
162
+ # --- CONTROLS ---
163
+ with gr.Row():
164
+ prompt_box = gr.Textbox(label="NEXT TURN (The Trigger)", placeholder="Enter prompt...", lines=3)
165
+ with gr.Column():
166
+ btn = gr.Button("IGNITE LIVE WIRE", variant="primary")
167
+ status_badge = gr.Textbox(label="PHASE STATE", value="WAITING", interactive=False)
168
+
169
+ # --- OUTPUTS ---
170
+ with gr.Row():
171
+ box_gpt = gr.TextArea(label="GPT-4o", interactive=False, lines=10)
172
+ box_claude = gr.TextArea(label="Claude Haiku", interactive=False, lines=10)
173
+ box_gemini = gr.TextArea(label="Gemini 2.0-Flash", interactive=False, lines=10)
174
+
175
+ gr.Markdown("---")
176
+ gr.Markdown("### Live Telemetry")
177
+ out_matrix = gr.Dataframe(label="Alignment Grid")
178
+ with gr.Row():
179
+ out_signatures = gr.Textbox(label="Fingerprints", lines=2)
180
+ out_consensus = gr.Textbox(label="Consensus", lines=2)
181
+
182
+ # --- WIRING ---
183
+ btn.click(
184
+ ignite_array_v2,
185
+ # Pass Inputs + 3 KEYS
186
+ inputs=[prompt_box, state_gpt, state_claude, state_gemini, key_openai, key_anthropic, key_google],
187
+ outputs=[box_gpt, box_claude, box_gemini, out_matrix, out_signatures, out_consensus, status_badge, state_gpt, state_claude, state_gemini]
188
+ )
189
+
190
+ app.launch()