File size: 6,199 Bytes
2be316c
 
c8ea644
0beba87
 
 
 
aaac3c6
2be316c
0beba87
 
5173e79
 
5cc33f2
afe79f4
5cc33f2
6023b47
e801c72
6023b47
 
5cc33f2
0beba87
6023b47
ff09025
6023b47
5cc33f2
0beba87
5cc33f2
76aaa58
0beba87
76aaa58
0beba87
aaac3c6
 
 
 
 
2be316c
5cc33f2
ff09025
5cc33f2
aaac3c6
0beba87
5cc33f2
 
2be316c
5cc33f2
5173e79
5cc33f2
afe79f4
 
5cc33f2
afe79f4
 
aaac3c6
5173e79
 
0beba87
afe79f4
5173e79
5cc33f2
 
afe79f4
0beba87
 
afe79f4
0beba87
afe79f4
5cc33f2
afe79f4
5cc33f2
 
 
 
 
0beba87
 
5cc33f2
5173e79
6023b47
5cc33f2
0beba87
5cc33f2
 
5173e79
6a9d342
5173e79
0beba87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c3c945
0beba87
56963ec
0beba87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5cc33f2
afe79f4
5cc33f2
 
5173e79
 
ff09025
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import json
import asyncio
import os
import numpy as np
import gradio as gr
import plotly.graph_objects as go

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse

from huggingface_hub import InferenceClient

# ─────────────────────────────────────────────
# CONFIG
# ─────────────────────────────────────────────

MODEL_ID = "meta-llama/Llama-3.1-8B-Instruct"
HF_TOKEN = os.environ.get("HF_TOKEN")

if not HF_TOKEN:
    raise RuntimeError("HF_TOKEN missing.")

client = InferenceClient(model=MODEL_ID, token=HF_TOKEN)

# ─────────────────────────────────────────────
# FASTAPI
# ─────────────────────────────────────────────

api = FastAPI()

api.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# ─────────────────────────────────────────────
# CHAT ENDPOINT (UNCHANGED CORE)
# ─────────────────────────────────────────────

@api.post("/api/chat")
async def chat(request: Request):
    body = await request.json()
    messages = body.get("messages", [])

    async def event_stream():
        try:
            stream = client.chat.completions.create(
                model=MODEL_ID,
                messages=messages,
                max_tokens=512,
                temperature=0.7,
                stream=True,
            )

            full_text = ""

            for chunk in stream:
                try:
                    delta = chunk.choices[0].delta
                    if delta and delta.content:
                        full_text += delta.content

                        yield json.dumps({
                            "content": delta.content
                        }) + "\n"

                        await asyncio.sleep(0.01)

                except Exception:
                    continue

            yield json.dumps({
                "done": True,
                "full": full_text
            }) + "\n"

        except Exception as e:
            yield json.dumps({
                "error": str(e),
                "done": True
            }) + "\n"

    return StreamingResponse(event_stream(), media_type="application/x-ndjson")

# ─────────────────────────────────────────────
# CODETTE UI (GRADIO)
# ─────────────────────────────────────────────

CUSTOM_CSS = """
body {
    background: radial-gradient(circle at top, #14142b, #0b0b17);
    color: #e5e7eb;
}

.metric-box {
    background: rgba(20,20,40,0.7);
    border: 1px solid rgba(168,85,247,0.3);
    padding: 10px;
    border-radius: 10px;
    font-family: monospace;
    margin-bottom: 10px;
}

button {
    background: linear-gradient(135deg,#a855f7,#06b6d4) !important;
    border: none !important;
}
"""

def call_backend(message):

    import requests

    url = "http://localhost:7860/api/chat"

    response = requests.post(
        url,
        json={"messages": [{"role": "user", "content": message}]},
        stream=True,
    )

    full = ""

    for line in response.iter_lines():
        if not line:
            continue
        data = json.loads(line.decode())

        if "content" in data:
            full += data["content"]

    return full

def process(msg, history):

    if not msg.strip():
        return history, "", "", None

    history.append({"role": "user", "content": msg})

    response = call_backend(msg)

    history.append({"role": "assistant", "content": response})

    # simple metrics (can upgrade later)
    coherence = min(0.99, 0.6 + len(msg)/200)
    eta = 0.7

    metrics_html = f"""
    <div class="metric-box">
    Ξ“ Phase Coherence: {coherence:.4f}<br>
    Ξ· Ethical Alignment: {eta:.4f}<br>
    Risk: LOW
    </div>
    """

    fig = go.Figure()
    fig.add_trace(go.Scatter(
        x=[0,1,0],
        y=[0,1,1],
        mode='markers+text',
        text=["newton","empathy","quantum"]
    ))

    return history, "", metrics_html, fig

def create_ui():

    with gr.Blocks(title="Codette-Demo not the actual codette model") as demo:

        gr.Markdown("# Codette")

        with gr.Row():

            with gr.Column(scale=3):
                chat = gr.Chatbot(height=520)

                msg = gr.Textbox(
                    lines=2,
                    placeholder="Ask Codette..."
                )

                send = gr.Button("β–Ά")

            with gr.Column(scale=2):
                metrics = gr.HTML()
                graph = gr.Plot()

        def run(m, h):
            return process(m, h)

        send.click(
            run,
            [msg, chat],
            [chat, msg, metrics, graph]
        )

        msg.submit(
            run,
            [msg, chat],
            [chat, msg, metrics, graph]
        )

    return demo

# ─────────────────────────────────────────────
# COMBINE (IMPORTANT PART)
# ─────────────────────────────────────────────

app = gr.mount_gradio_app(api, create_ui(), path="/")

# ─────────────────────────────────────────────
# RUN
# ─────────────────────────────────────────────

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)