aien-protocols-mv
Canonical specifications, wire protocols, and schemas for the AIEN sovereign ecosystem
Brought by drakestapleton
aien-protocols-mv / crates / aien-inference-client / src / lib.rs
| 1 | use aien_inference_protocol::*; |
| 2 | use aien_protocol_types::ProtocolVersion; |
| 3 | use async_trait::async_trait; |
| 4 | use reqwest::{Client, StatusCode}; |
| 5 | use std::sync::Arc; |
| 6 | use std::time::Duration; |
| 7 | |
| 8 | pub struct LocalInferenceClient { |
| 9 | service: Arc<dyn InferenceService>, |
| 10 | } |
| 11 | |
| 12 | impl LocalInferenceClient { |
| 13 | pub fn new(service: Arc<dyn InferenceService>) -> Self { |
| 14 | Self { service } |
| 15 | } |
| 16 | } |
| 17 | |
| 18 | #[async_trait] |
| 19 | impl InferenceService for LocalInferenceClient { |
| 20 | async fn infer(&self, req: InferenceRequest) -> Result<InferenceResponse, InferenceError> { |
| 21 | self.service.infer(req).await |
| 22 | } |
| 23 | |
| 24 | async fn branch_context( |
| 25 | &self, |
| 26 | req: BranchContextRequest, |
| 27 | ) -> Result<BranchContextReceipt, InferenceError> { |
| 28 | self.service.branch_context(req).await |
| 29 | } |
| 30 | |
| 31 | async fn get_capabilities(&self) -> Result<InferenceCapabilities, InferenceError> { |
| 32 | self.service.get_capabilities().await |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | /// Real HTTP transport adapter implementing InferenceService over remote REST endpoints. |
| 37 | pub struct HttpInferenceClient { |
| 38 | pub endpoint: String, |
| 39 | pub auth_token: Option<String>, |
| 40 | client: Client, |
| 41 | } |
| 42 | |
| 43 | impl HttpInferenceClient { |
| 44 | pub fn new(endpoint: String, auth_token: Option<String>) -> Self { |
| 45 | let client = Client::builder() |
| 46 | .timeout(Duration::from_secs(60)) |
| 47 | .build() |
| 48 | .unwrap_or_else(|_| Client::new()); |
| 49 | |
| 50 | Self { |
| 51 | endpoint, |
| 52 | auth_token, |
| 53 | client, |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | pub fn with_client(endpoint: String, auth_token: Option<String>, client: Client) -> Self { |
| 58 | Self { |
| 59 | endpoint, |
| 60 | auth_token, |
| 61 | client, |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | fn url(&self, path: &str) -> String { |
| 66 | let base = self.endpoint.trim_end_matches('/'); |
| 67 | let rel = path.trim_start_matches('/'); |
| 68 | format!("{}/{}", base, rel) |
| 69 | } |
| 70 | |
| 71 | fn map_http_error(status: StatusCode, body: &str) -> InferenceError { |
| 72 | match status { |
| 73 | StatusCode::NOT_FOUND => { |
| 74 | InferenceError::Internal(format!("Resource not found (404): {}", body)) |
| 75 | } |
| 76 | StatusCode::CONFLICT => InferenceError::StaleRuntimeEpoch, |
| 77 | StatusCode::TOO_MANY_REQUESTS => InferenceError::ResourceExhausted(format!( |
| 78 | "Capacity or rate limit exceeded (429): {}", |
| 79 | body |
| 80 | )), |
| 81 | _ => InferenceError::Internal(format!("HTTP {}: {}", status, body)), |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | #[async_trait] |
| 87 | impl InferenceService for HttpInferenceClient { |
| 88 | async fn infer(&self, req: InferenceRequest) -> Result<InferenceResponse, InferenceError> { |
| 89 | if self.endpoint.is_empty() { |
| 90 | return Err(InferenceError::Internal( |
| 91 | "HTTP transport endpoint is empty".to_string(), |
| 92 | )); |
| 93 | } |
| 94 | |
| 95 | let url = self.url("v1/chat/completions"); |
| 96 | let mut builder = self.client.post(&url).json(&req); |
| 97 | |
| 98 | if let Some(token) = &self.auth_token { |
| 99 | builder = builder.header("Authorization", format!("Bearer {}", token)); |
| 100 | } |
| 101 | |
| 102 | let resp = builder.send().await.map_err(|e| { |
| 103 | InferenceError::Internal(format!("HTTP request failed to {}: {}", url, e)) |
| 104 | })?; |
| 105 | |
| 106 | let status = resp.status(); |
| 107 | if !status.is_success() { |
| 108 | let body = resp.text().await.unwrap_or_default(); |
| 109 | return Err(Self::map_http_error(status, &body)); |
| 110 | } |
| 111 | |
| 112 | resp.json::<InferenceResponse>().await.map_err(|e| { |
| 113 | InferenceError::Internal(format!("Failed to parse InferenceResponse JSON: {}", e)) |
| 114 | }) |
| 115 | } |
| 116 | |
| 117 | async fn branch_context( |
| 118 | &self, |
| 119 | req: BranchContextRequest, |
| 120 | ) -> Result<BranchContextReceipt, InferenceError> { |
| 121 | if self.endpoint.is_empty() { |
| 122 | return Err(InferenceError::Internal( |
| 123 | "HTTP transport endpoint is empty".to_string(), |
| 124 | )); |
| 125 | } |
| 126 | |
| 127 | let url = self.url("v1/context/branch"); |
| 128 | let mut builder = self.client.post(&url).json(&req); |
| 129 | |
| 130 | if let Some(token) = &self.auth_token { |
| 131 | builder = builder.header("Authorization", format!("Bearer {}", token)); |
| 132 | } |
| 133 | |
| 134 | let resp = builder.send().await.map_err(|e| { |
| 135 | InferenceError::Internal(format!("HTTP request failed to {}: {}", url, e)) |
| 136 | })?; |
| 137 | |
| 138 | let status = resp.status(); |
| 139 | if !status.is_success() { |
| 140 | let body = resp.text().await.unwrap_or_default(); |
| 141 | return Err(Self::map_http_error(status, &body)); |
| 142 | } |
| 143 | |
| 144 | resp.json::<BranchContextReceipt>().await.map_err(|e| { |
| 145 | InferenceError::Internal(format!("Failed to parse BranchContextReceipt JSON: {}", e)) |
| 146 | }) |
| 147 | } |
| 148 | |
| 149 | async fn get_capabilities(&self) -> Result<InferenceCapabilities, InferenceError> { |
| 150 | if self.endpoint.is_empty() { |
| 151 | return Err(InferenceError::Internal( |
| 152 | "HTTP transport endpoint is empty".to_string(), |
| 153 | )); |
| 154 | } |
| 155 | |
| 156 | let url = self.url("v1/capabilities"); |
| 157 | let mut builder = self.client.get(&url); |
| 158 | |
| 159 | if let Some(token) = &self.auth_token { |
| 160 | builder = builder.header("Authorization", format!("Bearer {}", token)); |
| 161 | } |
| 162 | |
| 163 | let resp = builder.send().await.map_err(|e| { |
| 164 | InferenceError::Internal(format!("HTTP request failed to {}: {}", url, e)) |
| 165 | })?; |
| 166 | |
| 167 | let status = resp.status(); |
| 168 | if !status.is_success() { |
| 169 | let body = resp.text().await.unwrap_or_default(); |
| 170 | return Err(Self::map_http_error(status, &body)); |
| 171 | } |
| 172 | |
| 173 | resp.json::<InferenceCapabilities>().await.map_err(|e| { |
| 174 | InferenceError::Internal(format!("Failed to parse InferenceCapabilities JSON: {}", e)) |
| 175 | }) |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | pub struct MockInferenceClient { |
| 180 | capabilities: InferenceCapabilities, |
| 181 | } |
| 182 | |
| 183 | impl MockInferenceClient { |
| 184 | pub fn new() -> Self { |
| 185 | Self { |
| 186 | capabilities: InferenceCapabilities { |
| 187 | protocol: ProtocolVersion::new(1, 0), |
| 188 | context_branching: true, |
| 189 | physical_cow: true, |
| 190 | streaming: false, |
| 191 | cancellation: true, |
| 192 | max_context_tokens: Some(32768), |
| 193 | }, |
| 194 | } |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | impl Default for MockInferenceClient { |
| 199 | fn default() -> Self { |
| 200 | Self::new() |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | #[async_trait] |
| 205 | impl InferenceService for MockInferenceClient { |
| 206 | async fn infer(&self, req: InferenceRequest) -> Result<InferenceResponse, InferenceError> { |
| 207 | Ok(InferenceResponse { |
| 208 | request_id: req.request_id, |
| 209 | content: "mock inference output".to_string(), |
| 210 | finish_reason: "stop".to_string(), |
| 211 | prompt_tokens: 16, |
| 212 | completion_tokens: 8, |
| 213 | context: req.context, |
| 214 | }) |
| 215 | } |
| 216 | |
| 217 | async fn branch_context( |
| 218 | &self, |
| 219 | req: BranchContextRequest, |
| 220 | ) -> Result<BranchContextReceipt, InferenceError> { |
| 221 | let mut child_context = req.parent_context.clone(); |
| 222 | child_context.branch_id = req.child_branch_id; |
| 223 | child_context.generation = child_context.generation.next(); |
| 224 | child_context.lineage.parent_context = Some(req.parent_context.context_id); |
| 225 | child_context.lineage.parent_branch = Some(req.parent_context.branch_id); |
| 226 | |
| 227 | Ok(BranchContextReceipt { |
| 228 | operation_id: req.operation_id, |
| 229 | child_context, |
| 230 | shared_pages: 10, |
| 231 | copied_pages: 0, |
| 232 | lease_expires_at_monotonic: 999999999, |
| 233 | }) |
| 234 | } |
| 235 | |
| 236 | async fn get_capabilities(&self) -> Result<InferenceCapabilities, InferenceError> { |
| 237 | Ok(self.capabilities.clone()) |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | pub type DynInferenceService = Arc<dyn InferenceService>; |