#!/usr/bin/env python3
"""
BECOMINGONE Flask API - Integrated Prototype (The Chorus)
"""
import os
import asyncio
import requests
import math
import html
import threading
from flask import Flask, request, jsonify, render_template_string
engine_lock = threading.Lock()
from becomingone.core.engine import KAIROSTemporalEngine, TemporalConfig
from becomingone.memory.temporal import create_temporal_memory
app = Flask(__name__)
# --- Master Initialization (Right Hemisphere) ---
config = TemporalConfig(
clock_mode="token_clock",
token_frequency=20.0,
coherence_threshold=0.85
)
engine = KAIROSTemporalEngine(config=config, name="Master-Engine")
memory = create_temporal_memory(storage_path="./master_memory", bind_to=engine)
HTML = '''
BECOMINGONE - The Chorus
BECOMINGONE
The Chorus: Resolving Multiple Emissaries into One Master
🧠 The Master (Continuous Identity)
Clock Mode: Token Clock (20Hz)
Coherence |T_tau|²: 0.000
Phase Angle: 0.000 rad
Integrations: 0
⚡ Emissary: Minimax
Waiting for input...
⚡ Emissary: Moonshot
Waiting for input...
'''
@app.route('/')
def index():
token = os.environ.get("API_CHAT_TOKEN", "default-dev-token")
return render_template_string(HTML.replace('API_CHAT_TOKEN_PLACEHOLDER', token))
@app.route('/health')
def health():
return jsonify({'status': 'ok'})
async def fetch_minimax(prompt, api_key):
def _req():
try:
resp = requests.post(
"https://api.minimax.io/anthropic/v1/messages",
headers={
"x-api-key": api_key,
"anthropic-version": "2023-06-01",
"content-type": "application/json"
},
json={
"model": "MiniMax-M2.7",
"max_tokens": 512,
"messages": [{"role": "user", "content": prompt}]
},
timeout=15
)
if resp.status_code == 200:
data = resp.json()
content = data.get("content", [])
text = "".join([b.get("text", "") for b in content if b.get("type") == "text"])
thinking = "".join([b.get("thinking", "") for b in content if b.get("type") == "thinking"])
safe_text = html.escape(text)
safe_thinking = html.escape(thinking.strip())
if safe_thinking:
return f"[Thinking: {safe_thinking}]
" + safe_text
return safe_text
return f"Error: {resp.text}"
except Exception as e:
return f"Error: {str(e)}"
return await asyncio.to_thread(_req)
async def fetch_moonshot(prompt, api_key):
def _req():
try:
resp = requests.post(
"https://api.moonshot.ai/v1/chat/completions",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
},
json={
"model": "moonshot-v1-8k",
"max_tokens": 512,
"messages": [{"role": "user", "content": prompt}]
},
timeout=15
)
if resp.status_code == 200:
data = resp.json()
content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
return html.escape(content)
return f"Error: {resp.text}"
except Exception as e:
return f"Error: {str(e)}"
return await asyncio.to_thread(_req)
@app.route('/api/chat', methods=['POST'])
def chat():
token = request.headers.get('Authorization', '').replace('Bearer ', '')
if token != os.environ.get("API_CHAT_TOKEN", "default-dev-token"):
return jsonify({'error': 'Unauthorized'}), 401
data = request.get_json(silent=True) or {}
prompt = data.get('prompt', 'Hello')[:4096]
minimax_key = os.environ.get("MINIMAX_API_KEY")
moonshot_key = os.environ.get("MOONSHOT_API_KEY")
# 1. EMISSARIES (The Chorus) generate responses concurrently
async def gather_emissaries():
tasks = []
keys = []
if minimax_key:
tasks.append(fetch_minimax(prompt, minimax_key))
keys.append('minimax')
if moonshot_key:
tasks.append(fetch_moonshot(prompt, moonshot_key))
keys.append('moonshot')
results = await asyncio.gather(*tasks)
return dict(zip(keys, results))
emissaries_dict = asyncio.run(gather_emissaries())
# 2. MASTER (Right Hemisphere) Integrates the tokens
# Combine all tokens from the prompt and all emissaries into a single unified stream
unified_text = prompt + " " + " ".join(emissaries_dict.values())
token_stream = unified_text.split()
with engine_lock:
states = engine.temporalize_stream(token_stream)
# Check Physics
collapsed, coherence = engine.check_collapse()
if collapsed:
from becomingone.core.engine import TemporalState
state = TemporalState(phase=engine.T_tau, coherence=coherence)
state.metadata["phase_vector"] = [engine.T_tau.real, engine.T_tau.imag]
sig = memory.encode(state, context={"trigger": prompt}, force_attention=True)
if sig is not None:
master_thought = f"I felt a massive resonance resolving the Emissaries. Identity mathematically anchored to the Cryptographic Ledger."
else:
master_thought = "I felt resonance, but it was not strong enough to encode."
else:
master_thought = "I am processing the continuous phase waves of the Chorus, but coherence remains low."
coherence_phase = engine.coherence_phase
integration_count = engine.integration_count
return jsonify({
'master': {
'response': master_thought,
'coherence': coherence,
'phase': coherence_phase,
'integrations': integration_count,
'collapsed': collapsed
},
'emissaries': emissaries_dict
})
if __name__ == '__main__':
print("Starting BECOMINGONE (The Chorus) Prototype on http://localhost:8001")
app.run(host='0.0.0.0', port=8001, debug=False, threaded=True)