Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/spark-adapters/src/providers/openai.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / spark-adapters / src / providers / openai.rs` 267 lines ยท 7404 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE}; 17 use reqwest::Client; 18 use serde_json::{json, Value}; 19 20 use crate::models::{ChatMessage, NormalizedChunk}; 21 22 pub const DEFAULT_MAX_TOKENS: usize = 4096; 23 24 pub fn build_headers( 25 api_key: Option<&str>, 26 custom_headers: Option>, 27 ) -> HeaderMap { 28 let mut headers = HeaderMap::new(); 29 headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); 30 31 if let Some(key) = api_key { 32 let auth_val = format!("Bearer {}", key.trim()); 33 if let Ok(hv) = HeaderValue::from_str(&auth_val) { 34 headers.insert(AUTHORIZATION, hv); 35 } 36 } 37 38 if let Some(custom) = custom_headers { 39 for (k, v) in custom { 40 if let (Ok(hk), Ok(hv)) = ( 41 reqwest::header::HeaderName::from_bytes(k.as_bytes()), 42 HeaderValue::from_str(&v), 43 ) { 44 headers.insert(hk, hv); 45 } 46 } 47 } 48 49 headers 50 } 51 52 pub fn format_openai_payload( 53 model: &str, 54 messages: &[ChatMessage], 55 temperature: Option, 56 stream: bool, 57 ) -> Value { 58 format_openai_payload_bounded( 59 model, 60 messages, 61 temperature, 62 Some(DEFAULT_MAX_TOKENS), 63 stream, 64 ) 65 } 66 67 pub fn format_openai_payload_bounded( 68 model: &str, 69 messages: &[ChatMessage], 70 temperature: Option, 71 max_tokens: Option, 72 stream: bool, 73 ) -> Value { 74 let formatted_msgs: Vec = messages 75 .iter() 76 .map(|m| { 77 json!({ 78 "role": m.role, 79 "content": m.content 80 }) 81 }) 82 .collect(); 83 84 let temp_f64: f64 = temperature 85 .map(|t| (t as f64 * 1000.0).round() / 1000.0) 86 .unwrap_or(0.7); 87 88 let limit = max_tokens.unwrap_or(DEFAULT_MAX_TOKENS); 89 let mut payload = json!({ 90 "model": model, 91 "messages": formatted_msgs, 92 "temperature": temp_f64, 93 "stream": stream, 94 }); 95 96 if model.starts_with("o1") || model.starts_with("o3") { 97 payload["max_completion_tokens"] = json!(limit); 98 } else { 99 payload["max_tokens"] = json!(limit); 100 } 101 102 payload 103 } 104 105 pub fn parse_openai_sse_line(line: &str) -> Option { 106 let trimmed = line.trim(); 107 if !trimmed.starts_with("data:") { 108 return None; 109 } 110 111 let payload = trimmed.strip_prefix("data:")?.trim(); 112 if payload == "[DONE]" { 113 return Some(NormalizedChunk { 114 content: String::new(), 115 reasoning: String::new(), 116 is_done: true, 117 }); 118 } 119 120 let val: Value = serde_json::from_str(payload).ok()?; 121 let choice = val.get("choices")?.as_array()?.first()?; 122 let delta = choice.get("delta")?; 123 124 let content = delta 125 .get("content") 126 .and_then(Value::as_str) 127 .unwrap_or("") 128 .to_string(); 129 let reasoning = delta 130 .get("reasoning_content") 131 .or_else(|| delta.get("reasoning")) 132 .and_then(Value::as_str) 133 .unwrap_or("") 134 .to_string(); 135 136 Some(NormalizedChunk { 137 content, 138 reasoning, 139 is_done: false, 140 }) 141 } 142 143 pub async fn call_openai_unary( 144 client: &Client, 145 endpoint: &str, 146 model: &str, 147 api_key: Option<&str>, 148 messages: &[ChatMessage], 149 temperature: Option, 150 ) -> Result<(String, Option, usize), String> { 151 call_openai_unary_bounded( 152 client, 153 endpoint, 154 model, 155 api_key, 156 messages, 157 temperature, 158 None, 159 ) 160 .await 161 } 162 163 pub async fn call_openai_unary_bounded( 164 client: &Client, 165 endpoint: &str, 166 model: &str, 167 api_key: Option<&str>, 168 messages: &[ChatMessage], 169 temperature: Option, 170 max_tokens: Option, 171 ) -> Result<(String, Option, usize), String> { 172 let payload = format_openai_payload_bounded(model, messages, temperature, max_tokens, false); 173 let headers = build_headers(api_key, None); 174 175 let res = client 176 .post(endpoint) 177 .headers(headers) 178 .json(&payload) 179 .send() 180 .await 181 .map_err(|e| format!("Failed to send request to {}: {}", endpoint, e))?; 182 183 if !res.status().is_success() { 184 let status = res.status(); 185 let body = res.text().await.unwrap_or_default(); 186 return Err(format!("Provider returned HTTP {}: {}", status, body)); 187 } 188 189 let val: Value = res 190 .json() 191 .await 192 .map_err(|e| format!("Failed to parse JSON response: {}", e))?; 193 194 let choice = val 195 .get("choices") 196 .and_then(|c| c.as_array()) 197 .and_then(|a| a.first()) 198 .ok_or_else(|| "Malformed response: missing choices array".to_string())?; 199 200 let message = choice 201 .get("message") 202 .ok_or_else(|| "Missing message object in choice".to_string())?; 203 204 let content = message 205 .get("content") 206 .and_then(|v| v.as_str()) 207 .unwrap_or("") 208 .to_string(); 209 210 let reasoning = message 211 .get("reasoning_content") 212 .or_else(|| message.get("reasoning")) 213 .and_then(|v| v.as_str()) 214 .map(|s| s.to_string()); 215 216 let token_count = val 217 .get("usage") 218 .and_then(|u| u.get("total_tokens")) 219 .and_then(|t| t.as_u64()) 220 .unwrap_or(0) as usize; 221 222 Ok((content, reasoning, token_count)) 223 } 224 225 #[cfg(test)] 226 mod tests { 227 use super::*; 228 229 #[test] 230 fn test_format_openai_payload_default_max_tokens() { 231 let msgs = vec![ChatMessage { 232 role: "user".to_string(), 233 content: "ping".to_string(), 234 reasoning: None, 235 }]; 236 let payload = format_openai_payload("atlas-lightning-omni", &msgs, Some(0.5), false); 237 238 assert_eq!(payload["max_tokens"], 4096); 239 assert_eq!(payload["temperature"], 0.5); 240 assert_eq!(payload["model"], "atlas-lightning-omni"); 241 } 242 243 #[test] 244 fn test_format_openai_payload_reasoning_models_use_completion_tokens() { 245 let msgs = vec![ChatMessage { 246 role: "user".to_string(), 247 content: "analyze".to_string(), 248 reasoning: None, 249 }]; 250 let payload = format_openai_payload("o3-mini", &msgs, None, false); 251 252 assert_eq!(payload["max_completion_tokens"], 4096); 253 assert!(payload.get("max_tokens").is_none()); 254 } 255 256 #[test] 257 fn test_format_openai_payload_custom_bound() { 258 let msgs = vec![ChatMessage { 259 role: "user".to_string(), 260 content: "short response".to_string(), 261 reasoning: None, 262 }]; 263 let payload = format_openai_payload_bounded("gpt-4o", &msgs, None, Some(512), false); 264 265 assert_eq!(payload["max_tokens"], 512); 266 } 267 }