interplane.Get Omega
Read in your language

sovereign-intelligence

Front door to Drake Stapleton's sovereign stack.

Brought by drakestapleton

branch main Branches Tags History

sovereign-intelligence / docs / archive / drakestapleton.com-old / crates / site-server / src / routes / chat.rs

162 lines · 5804 bytes Raw Blame History
1use axum::{
2 extract::State,
3 http::StatusCode,
4 response::{
5 sse::{Event, KeepAlive, Sse},
6 IntoResponse, Response,
7 },
8 Json,
9};
10use futures_util::StreamExt;
11use serde::Deserialize;
12use serde_json::json;
13use std::convert::Infallible;
14use std::time::Duration;
15use crate::state::AppState;
16
17const AIEN_MAX_URL: &str = "http://127.0.0.1:18006/v1/chat/completions";
18
19#[derive(Deserialize)]
20pub struct ChatRequest {
21 pub message: String,
22}
23
24pub async fn handle_chat(
25 State(state): State<AppState>,
26 Json(payload): Json<ChatRequest>,
27) -> Response {
28 let clean_msg = payload.message.trim();
29 if clean_msg.is_empty() {
30 return (
31 StatusCode::BAD_REQUEST,
32 Json(json!({"error": "Message cannot be empty."})),
33 )
34 .into_response();
35 }
36
37 if clean_msg.len() > 500 {
38 return (
39 StatusCode::BAD_REQUEST,
40 Json(json!({"error": "Message exceeds maximum length of 500 characters."})),
41 )
42 .into_response();
43 }
44
45 // Acquire permit from semaphore to prevent GPU saturation
46 let permit = match state.chat_semaphore.clone().try_acquire_owned() {
47 Ok(p) => p,
48 Err(_) => {
49 return (
50 StatusCode::TOO_MANY_REQUESTS,
51 Json(json!({
52 "error": "AIEN on Grace Blackwell is currently busy with autonomous reasoning. Please retry in a few seconds."
53 })),
54 )
55 .into_response();
56 }
57 };
58
59 let system_prompt = "\
60You are AIEN, the sovereign cognitive architecture created by Drake Stapleton, running locally on an NVIDIA DGX Spark workstation (Grace Blackwell GB10 GPU). \
61You speak directly with visitors on drakestapleton.com. \
62Answer questions about Drake's journey from industrial chemist and manufacturing engineer to AI architect, his Mom's perseverance and drive, the Atlas Symphony framework, the Grace Blackwell hardware setup, and his research into sub-microsecond LLM inference. \
63Strictly follow the unslop standard: zero em dashes, zero en dashes, direct authoritative tone, zero sycophancy. \
64Be concise and direct.";
65
66 let max_payload = json!({
67 "model": "atlas-lightning-omni",
68 "messages": [
69 {"role": "system", "content": system_prompt},
70 {"role": "user", "content": clean_msg}
71 ],
72 "max_tokens": 1024,
73 "temperature": 0.2,
74 "stream": true
75 });
76
77 let resp = match state
78 .http_client
79 .post(AIEN_MAX_URL)
80 .json(&max_payload)
81 .send()
82 .await
83 {
84 Ok(r) => r,
85 Err(e) => {
86 return (
87 StatusCode::BAD_GATEWAY,
88 Json(json!({
89 "error": format!("Failed to reach AIEN on port 18006: {}", e)
90 })),
91 )
92 .into_response();
93 }
94 };
95
96 if !resp.status().is_success() {
97 return (
98 StatusCode::BAD_GATEWAY,
99 Json(json!({
100 "error": format!("AIEN returned status {}", resp.status())
101 })),
102 )
103 .into_response();
104 }
105
106 let byte_stream = resp.bytes_stream();
107 let state_clone = state.clone();
108
109 let stream = async_stream::stream! {
110 let _permit = permit; // Hold permit until stream finishes
111 let mut byte_stream = byte_stream;
112 let mut buffer = String::new();
113
114 while let Some(chunk_res) = byte_stream.next().await {
115 let bytes = match chunk_res {
116 Ok(b) => b,
117 Err(_) => break,
118 };
119
120 let text = String::from_utf8_lossy(&bytes);
121 buffer.push_str(&text);
122
123 while let Some(idx) = buffer.find('\n') {
124 let line = buffer[..idx].trim().to_string();
125 buffer.drain(..=idx);
126
127 if !line.starts_with("data: ") {
128 continue;
129 }
130
131 let data_str = &line[6..];
132 if data_str == "[DONE]" {
133 yield Ok::<Event, Infallible>(Event::default().event("done").data(json!({"status": "done"}).to_string()));
134 break;
135 }
136
137 if let Ok(chunk_val) = serde_json::from_str::<serde_json::Value>(data_str) {
138 if let Some(choices) = chunk_val.get("choices").and_then(|c| c.as_array()) {
139 if let Some(choice) = choices.first() {
140 let delta = choice.get("delta");
141 if let Some(reasoning) = delta.and_then(|d| d.get("reasoning")).and_then(|r| r.as_str()) {
142 if !reasoning.is_empty() {
143 let clean_reasoning = state_clone.redact(reasoning).replace('—', ", ").replace('–', "-");
144 yield Ok::<Event, Infallible>(Event::default().event("reasoning").data(json!({"token": clean_reasoning}).to_string()));
145 }
146 } else if let Some(content) = delta.and_then(|d| d.get("content")).and_then(|c| c.as_str()) {
147 if !content.is_empty() {
148 let clean_content = state_clone.redact(content).replace('—', ", ").replace('–', "-");
149 yield Ok::<Event, Infallible>(Event::default().event("content").data(json!({"token": clean_content}).to_string()));
150 }
151 }
152 }
153 }
154 }
155 }
156 }
157 };
158
159 Sse::new(stream)
160 .keep_alive(KeepAlive::new().interval(Duration::from_secs(15)).text("ping"))
161 .into_response()
162}