spark-rsi-mv
Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger
Brought by drakestapleton
spark-rsi-mv / src / propose / model_seat.rs
| 1 | //! Client for the local model seat: any OpenAI-compatible chat completions endpoint |
| 2 | //! (by AIEN convention, 127.0.0.1:18006/v1 on the Spark). |
| 3 | |
| 4 | use serde::{Deserialize, Serialize}; |
| 5 | use std::time::Duration; |
| 6 | |
| 7 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 8 | pub struct ChatMessage { |
| 9 | pub role: String, |
| 10 | pub content: String, |
| 11 | } |
| 12 | |
| 13 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 14 | pub struct ChatCompletionRequest { |
| 15 | pub model: String, |
| 16 | pub messages: Vec<ChatMessage>, |
| 17 | #[serde(skip_serializing_if = "Option::is_none")] |
| 18 | pub max_tokens: Option<usize>, |
| 19 | #[serde(skip_serializing_if = "Option::is_none")] |
| 20 | pub temperature: Option<f32>, |
| 21 | } |
| 22 | |
| 23 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 24 | pub struct ChatMessageResponse { |
| 25 | pub role: String, |
| 26 | #[serde(default)] |
| 27 | pub content: Option<String>, |
| 28 | #[serde(default)] |
| 29 | pub reasoning: Option<String>, |
| 30 | #[serde(default)] |
| 31 | pub reasoning_content: Option<String>, |
| 32 | } |
| 33 | |
| 34 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 35 | pub struct ChatChoice { |
| 36 | pub index: usize, |
| 37 | pub message: ChatMessageResponse, |
| 38 | #[serde(default)] |
| 39 | pub finish_reason: Option<String>, |
| 40 | } |
| 41 | |
| 42 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 43 | pub struct ChatCompletionResponse { |
| 44 | pub id: String, |
| 45 | pub choices: Vec<ChatChoice>, |
| 46 | } |
| 47 | |
| 48 | #[derive(Debug, Clone)] |
| 49 | pub struct ModelSeatClient { |
| 50 | pub base_url: String, |
| 51 | pub model_id: String, |
| 52 | client: reqwest::Client, |
| 53 | } |
| 54 | |
| 55 | impl ModelSeatClient { |
| 56 | pub fn new(base_url: &str, model_id: &str) -> Self { |
| 57 | let client = reqwest::Client::builder() |
| 58 | .timeout(Duration::from_secs(360)) |
| 59 | .build() |
| 60 | .unwrap_or_default(); |
| 61 | |
| 62 | Self { |
| 63 | base_url: base_url.trim_end_matches('/').to_string(), |
| 64 | model_id: model_id.to_string(), |
| 65 | client, |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | pub async fn is_available(&self) -> bool { |
| 70 | let url = format!("{}/models", self.base_url); |
| 71 | let check_client = match reqwest::Client::builder() |
| 72 | .timeout(std::time::Duration::from_millis(500)) |
| 73 | .build() |
| 74 | { |
| 75 | Ok(c) => c, |
| 76 | Err(_) => return false, |
| 77 | }; |
| 78 | match check_client.get(&url).send().await { |
| 79 | Ok(resp) => resp.status().is_success(), |
| 80 | Err(_) => false, |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | pub async fn complete( |
| 85 | &self, |
| 86 | messages: &[ChatMessage], |
| 87 | max_tokens: usize, |
| 88 | temperature: f32, |
| 89 | ) -> Result<String, String> { |
| 90 | let url = format!("{}/chat/completions", self.base_url); |
| 91 | let req = ChatCompletionRequest { |
| 92 | model: self.model_id.clone(), |
| 93 | messages: messages.to_vec(), |
| 94 | max_tokens: Some(max_tokens), |
| 95 | temperature: Some(temperature), |
| 96 | }; |
| 97 | |
| 98 | let resp = self |
| 99 | .client |
| 100 | .post(&url) |
| 101 | .json(&req) |
| 102 | .send() |
| 103 | .await |
| 104 | .map_err(|e| format!("Model seat completion request failed: {}", e))?; |
| 105 | |
| 106 | if !resp.status().is_success() { |
| 107 | let status = resp.status(); |
| 108 | let body = resp.text().await.unwrap_or_default(); |
| 109 | return Err(format!("Model seat returned HTTP {}: {}", status, body)); |
| 110 | } |
| 111 | |
| 112 | let body: ChatCompletionResponse = resp |
| 113 | .json() |
| 114 | .await |
| 115 | .map_err(|e| format!("Failed to parse model seat response: {}", e))?; |
| 116 | |
| 117 | let choice = body |
| 118 | .choices |
| 119 | .first() |
| 120 | .ok_or_else(|| "Model seat response returned an empty choices array".to_string())?; |
| 121 | |
| 122 | let content = choice.message.content.as_deref().unwrap_or_default().trim(); |
| 123 | |
| 124 | if content.is_empty() { |
| 125 | // Check if a fenced code block exists inside reasoning |
| 126 | for r in [&choice.message.reasoning, &choice.message.reasoning_content] { |
| 127 | if let Some(text) = r { |
| 128 | if let Some(start) = text.find("```") { |
| 129 | let after = &text[start + 3..]; |
| 130 | let code_start = after.find('\n').map(|i| i + 1).unwrap_or(0); |
| 131 | let rest = &after[code_start..]; |
| 132 | if let Some(end) = rest.rfind("```") { |
| 133 | let block = rest[..end].trim(); |
| 134 | if !block.is_empty() { |
| 135 | return Ok(format!("```rust\n{}\n```", block)); |
| 136 | } |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | } |
| 141 | return Err( |
| 142 | "Model seat assistant message did not emit code output (exhausted in reasoning)" |
| 143 | .to_string(), |
| 144 | ); |
| 145 | } |
| 146 | |
| 147 | Ok(content.to_string()) |
| 148 | } |
| 149 | } |