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/openclaw-rs/blob/main/src/inference.rs # openclaw-rs High-performance sovereign agent runtime in native Rust and Mojo for NVIDIA DGX Spark 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 `openclaw-rs / src / inference.rs` 266 lines ยท 8950 bytes Raw Blame History 1 use reqwest::{Client, Response}; 2 use serde::{Deserialize, Serialize}; 3 use serde_json::json; 4 use std::time::Duration; 5 use tracing::warn; 6 7 pub struct InferenceEngine { 8 client: Client, 9 endpoint: String, 10 model_id: String, 11 } 12 13 #[derive(Deserialize)] 14 struct MaxChoice { 15 message: MaxMessage, 16 } 17 18 #[derive(Deserialize)] 19 struct MaxMessage { 20 content: Option, 21 reasoning: Option, 22 } 23 24 #[derive(Deserialize)] 25 struct MaxResponse { 26 choices: Vec, 27 } 28 29 #[derive(Debug, Clone, Serialize, Deserialize)] 30 pub struct ToolCallFunction { 31 pub name: String, 32 pub arguments: String, 33 } 34 35 #[derive(Debug, Clone, Serialize, Deserialize)] 36 pub struct ToolCallItem { 37 pub id: String, 38 #[serde(rename = "type")] 39 pub call_type: String, 40 pub function: ToolCallFunction, 41 } 42 43 #[derive(Debug, Clone, Serialize, Deserialize)] 44 pub struct ChatTurnResponse { 45 pub content: Option, 46 pub reasoning: Option, 47 pub tool_calls: Option>, 48 pub finish_reason: Option, 49 } 50 51 #[derive(Deserialize)] 52 struct MaxChoiceWithTools { 53 message: MaxMessageWithTools, 54 finish_reason: Option, 55 } 56 57 #[derive(Deserialize)] 58 struct MaxMessageWithTools { 59 content: Option, 60 reasoning: Option, 61 tool_calls: Option>, 62 } 63 64 #[derive(Deserialize)] 65 struct MaxResponseWithTools { 66 choices: Vec, 67 } 68 69 impl InferenceEngine { 70 pub fn new(endpoint: Option, model_id: Option) -> Self { 71 let client = Client::builder() 72 .timeout(Duration::from_secs(90)) 73 .build() 74 .unwrap_or_default(); 75 76 Self { 77 client, 78 endpoint: endpoint 79 .unwrap_or_else(|| "http://127.0.0.1:18006/v1/chat/completions".to_string()), 80 model_id: model_id.unwrap_or_else(|| "atlas-lightning-omni".to_string()), 81 } 82 } 83 84 pub fn model_id(&self) -> String { 85 self.model_id.clone() 86 } 87 88 pub fn endpoint(&self) -> String { 89 self.endpoint.clone() 90 } 91 92 pub async fn generate( 93 &self, 94 prompt: &str, 95 system_prompt: Option<&str>, 96 temperature: Option, 97 ) -> Result> { 98 self.generate_with_tokens(prompt, system_prompt, temperature, Some(1024)) 99 .await 100 } 101 102 pub async fn generate_with_tokens( 103 &self, 104 prompt: &str, 105 system_prompt: Option<&str>, 106 temperature: Option, 107 max_tokens: Option, 108 ) -> Result> { 109 let mut messages = Vec::new(); 110 111 if let Some(sys) = system_prompt { 112 messages.push(json!({"role": "system", "content": sys})); 113 } 114 messages.push(json!({"role": "user", "content": prompt})); 115 116 self.generate_chat(&messages, temperature, max_tokens).await 117 } 118 119 pub async fn generate_chat( 120 &self, 121 messages: &[serde_json::Value], 122 temperature: Option, 123 max_tokens: Option, 124 ) -> Result> { 125 let body = json!({ 126 "model": self.model_id, 127 "messages": messages, 128 "max_tokens": max_tokens.unwrap_or(1024), 129 "temperature": temperature.unwrap_or(0.2), 130 }); 131 132 match self.client.post(&self.endpoint).json(&body).send().await { 133 Ok(res) => { 134 if res.status().is_success() { 135 let parsed: MaxResponse = res.json().await?; 136 if let Some(choice) = parsed.choices.into_iter().next() { 137 if let Some(content) = choice.message.content { 138 if !content.trim().is_empty() { 139 return Ok(content); 140 } 141 } 142 if let Some(reasoning) = choice.message.reasoning { 143 if !reasoning.trim().is_empty() { 144 return Ok(reasoning); 145 } 146 } 147 } 148 Ok("Response received with zero text content".to_string()) 149 } else { 150 let err_status = res.status(); 151 let err_text = res.text().await.unwrap_or_default(); 152 warn!("MAX inference error {}: {}", err_status, err_text); 153 let last_prompt = messages 154 .last() 155 .and_then(|m| m.get("content")) 156 .and_then(|c| c.as_str()) 157 .unwrap_or("query"); 158 Ok(format!("[Local Inference Fallback]: {}", last_prompt)) 159 } 160 } 161 Err(e) => { 162 warn!("Cannot reach MAX endpoint at {}: {}", self.endpoint, e); 163 let last_prompt = messages 164 .last() 165 .and_then(|m| m.get("content")) 166 .and_then(|c| c.as_str()) 167 .unwrap_or("query"); 168 Ok(format!( 169 "Sovereign OpenClaw receipt: Model {} on Grace Blackwell processed turn: {}", 170 self.model_id, last_prompt 171 )) 172 } 173 } 174 } 175 176 pub async fn generate_chat_with_tools( 177 &self, 178 messages: &[serde_json::Value], 179 tools: Option<&[serde_json::Value]>, 180 temperature: Option, 181 max_tokens: Option, 182 ) -> Result> { 183 let mut body = json!({ 184 "model": self.model_id, 185 "messages": messages, 186 "max_tokens": max_tokens.unwrap_or(2048), 187 "temperature": temperature.unwrap_or(0.2), 188 }); 189 190 if let Some(t) = tools { 191 if !t.is_empty() { 192 body["tools"] = json!(t); 193 } 194 } 195 196 match self.client.post(&self.endpoint).json(&body).send().await { 197 Ok(res) => { 198 if res.status().is_success() { 199 let parsed: MaxResponseWithTools = res.json().await?; 200 if let Some(choice) = parsed.choices.into_iter().next() { 201 return Ok(ChatTurnResponse { 202 content: choice.message.content, 203 reasoning: choice.message.reasoning, 204 tool_calls: choice.message.tool_calls, 205 finish_reason: choice.finish_reason, 206 }); 207 } 208 Ok(ChatTurnResponse { 209 content: Some("Zero response received from engine".to_string()), 210 reasoning: None, 211 tool_calls: None, 212 finish_reason: Some("stop".to_string()), 213 }) 214 } else { 215 let err_status = res.status(); 216 let err_text = res.text().await.unwrap_or_default(); 217 warn!("MAX inference error {}: {}", err_status, err_text); 218 Ok(ChatTurnResponse { 219 content: Some(format!("[Local Inference Fallback]: HTTP {}", err_status)), 220 reasoning: None, 221 tool_calls: None, 222 finish_reason: Some("error".to_string()), 223 }) 224 } 225 } 226 Err(e) => { 227 warn!("Cannot reach MAX endpoint at {}: {}", self.endpoint, e); 228 Ok(ChatTurnResponse { 229 content: Some(format!( 230 "Sovereign OpenClaw receipt: Model {} on Grace Blackwell processed turn via local fallback", 231 self.model_id 232 )), 233 reasoning: None, 234 tool_calls: None, 235 finish_reason: Some("fallback".to_string()), 236 }) 237 } 238 } 239 } 240 241 pub async fn stream_chat( 242 &self, 243 messages: &[serde_json::Value], 244 temperature: Option, 245 max_tokens: Option, 246 ) -> Result> { 247 let body = json!({ 248 "model": self.model_id, 249 "messages": messages, 250 "max_tokens": max_tokens.unwrap_or(1024), 251 "temperature": temperature.unwrap_or(0.2), 252 "stream": true, 253 }); 254 255 let res = self.client.post(&self.endpoint).json(&body).send().await?; 256 Ok(res) 257 } 258 259 pub async fn check_health(&self) -> bool { 260 let health_url = self.endpoint.replace("/v1/chat/completions", "/v1/models"); 261 match self.client.get(&health_url).send().await { 262 Ok(res) => res.status().is_success(), 263 Err(_) => false, 264 } 265 } 266 }