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
aien-sovereign-core-mv / crates / aien-serve-http / src / server.rs
| 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 | //! The HTTP surface: `GET /v1/models`, `POST /v1/chat/completions` (JSON or SSE), |
| 17 | //! `GET /health`. Every error is OpenAI error JSON. As many generations at a time as the |
| 18 | //! engine says it takes ([`Engine::concurrency`], 1 unless the engine batches): the next |
| 19 | //! request while all those run gets 503 `server_busy` with `Retry-After: 1`. |
| 20 | |
| 21 | use std::convert::Infallible; |
| 22 | use std::net::{IpAddr, Ipv4Addr, SocketAddr}; |
| 23 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 24 | use std::sync::Arc; |
| 25 | use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; |
| 26 | |
| 27 | use axum::body::{to_bytes, Body, Bytes}; |
| 28 | use axum::extract::{Path, State}; |
| 29 | use axum::http::{header, HeaderMap, HeaderValue, Request, StatusCode}; |
| 30 | use axum::response::sse::{Event, KeepAlive, Sse}; |
| 31 | use axum::response::{IntoResponse, Response}; |
| 32 | use axum::routing::{get, post}; |
| 33 | use axum::{Json, Router}; |
| 34 | use serde_json::Value; |
| 35 | use tokio::sync::{mpsc, OwnedSemaphorePermit, Semaphore}; |
| 36 | use tokio::task::JoinHandle; |
| 37 | use tokio_stream::wrappers::ReceiverStream; |
| 38 | |
| 39 | use aien_inference_abi::tokenizer::ChatOptions; |
| 40 | |
| 41 | use crate::codec::{Codec, CodecError}; |
| 42 | use crate::engine::{Engine, EngineError, FinishReason, GenerateParams, TestSwitches}; |
| 43 | use crate::openai::{ |
| 44 | chunk_json, chunk_json_with, completion_json, ChatRequest, ErrorBody, ModelCard, ModelList, |
| 45 | Usage, |
| 46 | }; |
| 47 | use crate::sampling::SamplingRecord; |
| 48 | use crate::text::{Push, TextAssembler}; |
| 49 | |
| 50 | /// How long a client has to send a complete request head (request line and headers) once the |
| 51 | /// server starts waiting for one: on a new connection and on a kept-alive connection between |
| 52 | /// requests. A client that sends part of a head, or nothing, is disconnected when it runs out, so a |
| 53 | /// slow client cannot hold a connection open indefinitely (DRA-47). 30 s is hyper's own default for |
| 54 | /// this bound, which `axum::serve` never armed because it gives hyper no timer; a loopback client |
| 55 | /// sends its head in well under a millisecond. |
| 56 | pub const HEADER_READ_TIMEOUT: Duration = Duration::from_secs(30); |
| 57 | |
| 58 | /// The most connections served at once. Past it the server accepts no new connection until one |
| 59 | /// closes (the kernel's listen backlog queues the rest), so connections cannot exhaust the |
| 60 | /// process's file descriptors. Generations are bounded separately by [`Engine::concurrency`]. |
| 61 | pub const MAX_CONNECTIONS: usize = 256; |
| 62 | |
| 63 | #[derive(Clone)] |
| 64 | pub struct ServerConfig { |
| 65 | /// Must be a loopback address; `serve` refuses anything else. |
| 66 | pub bind: IpAddr, |
| 67 | /// `0` picks a free port (tests). |
| 68 | pub port: u16, |
| 69 | pub model_id: String, |
| 70 | pub max_body_bytes: usize, |
| 71 | pub max_messages: usize, |
| 72 | pub max_stop_strings: usize, |
| 73 | /// Upper bound on `max_tokens`; larger requests are clamped to it. |
| 74 | pub max_new_tokens_cap: usize, |
| 75 | pub default_max_new_tokens: usize, |
| 76 | pub default_temperature: f32, |
| 77 | pub default_top_p: f32, |
| 78 | pub default_top_k: usize, |
| 79 | /// Optional server-side context cap (min with the engine's own limit). |
| 80 | pub max_context_tokens: Option<usize>, |
| 81 | /// `enable_thinking` for requests that do not set it (`None`: the chat template's own |
| 82 | /// default). Only templates with a thinking switch read it (Qwen3.8-27B). |
| 83 | pub default_enable_thinking: Option<bool>, |
| 84 | /// The eight readers (sc L371): a second model id that reads a long input in parts at once. |
| 85 | /// `None`: one id, as before. |
| 86 | pub readers: Option<crate::readers::ReadersConfig>, |
| 87 | /// Secret supplied out of band; an absent or empty credential refuses startup. |
| 88 | pub bearer_token: String, |
| 89 | /// See [`HEADER_READ_TIMEOUT`]. |
| 90 | pub header_read_timeout: Duration, |
| 91 | /// See [`MAX_CONNECTIONS`]. |
| 92 | pub max_connections: usize, |
| 93 | /// Tool-calling layout of the model's chat template ([`crate::tools::ToolFormat::from_model_dir`]). |
| 94 | pub tool_format: crate::tools::ToolFormat, |
| 95 | } |
| 96 | |
| 97 | impl Default for ServerConfig { |
| 98 | fn default() -> Self { |
| 99 | Self { |
| 100 | bind: IpAddr::V4(Ipv4Addr::LOCALHOST), |
| 101 | port: 18091, |
| 102 | model_id: "qwen3-30b-a3b-instruct-2507".into(), |
| 103 | max_body_bytes: 8 * 1024 * 1024, |
| 104 | max_messages: 512, |
| 105 | max_stop_strings: 8, |
| 106 | max_new_tokens_cap: 4096, |
| 107 | default_max_new_tokens: 1024, |
| 108 | default_temperature: 0.7, |
| 109 | default_top_p: 0.8, |
| 110 | default_top_k: 20, |
| 111 | max_context_tokens: None, |
| 112 | default_enable_thinking: None, |
| 113 | readers: None, |
| 114 | bearer_token: String::new(), |
| 115 | header_read_timeout: HEADER_READ_TIMEOUT, |
| 116 | max_connections: MAX_CONNECTIONS, |
| 117 | tool_format: crate::tools::ToolFormat::default(), |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | pub struct AppState { |
| 123 | engine: Arc<dyn Engine>, |
| 124 | codec: Arc<dyn Codec>, |
| 125 | cfg: ServerConfig, |
| 126 | /// One permit per generation the engine runs at once. |
| 127 | gate: Arc<Semaphore>, |
| 128 | allowed_hosts: [String; 3], |
| 129 | started: Instant, |
| 130 | counter: AtomicU64, |
| 131 | } |
| 132 | |
| 133 | /// An OpenAI-shaped error with its HTTP status. |
| 134 | #[derive(Debug)] |
| 135 | pub struct ApiError { |
| 136 | status: StatusCode, |
| 137 | body: ErrorBody, |
| 138 | retry_after: Option<u64>, |
| 139 | } |
| 140 | |
| 141 | impl ApiError { |
| 142 | fn unauthorized() -> Self { |
| 143 | Self { |
| 144 | status: StatusCode::UNAUTHORIZED, |
| 145 | body: ErrorBody::new( |
| 146 | "authentication_error", |
| 147 | "valid bearer authorization required", |
| 148 | ), |
| 149 | retry_after: None, |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | fn forbidden(msg: &'static str) -> Self { |
| 154 | Self { |
| 155 | status: StatusCode::FORBIDDEN, |
| 156 | body: ErrorBody::new("invalid_request_error", msg), |
| 157 | retry_after: None, |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | fn unsupported_media_type() -> Self { |
| 162 | Self { |
| 163 | status: StatusCode::UNSUPPORTED_MEDIA_TYPE, |
| 164 | body: ErrorBody::new( |
| 165 | "invalid_request_error", |
| 166 | "Content-Type must be application/json", |
| 167 | ), |
| 168 | retry_after: None, |
| 169 | } |
| 170 | } |
| 171 | fn bad_request(msg: impl Into<String>) -> Self { |
| 172 | Self { |
| 173 | status: StatusCode::BAD_REQUEST, |
| 174 | body: ErrorBody::new("invalid_request_error", msg), |
| 175 | retry_after: None, |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | /// The prompt would not fit the free host memory (413, the limit is in the message). |
| 180 | fn memory_exceeded(msg: impl Into<String>) -> Self { |
| 181 | let mut e = Self::bad_request(msg); |
| 182 | e.status = StatusCode::PAYLOAD_TOO_LARGE; |
| 183 | e.body.error.code = Some("prompt_exceeds_memory_budget".into()); |
| 184 | e |
| 185 | } |
| 186 | |
| 187 | fn context_exceeded(msg: impl Into<String>) -> Self { |
| 188 | let mut e = Self::bad_request(msg); |
| 189 | e.body.error.code = Some("context_length_exceeded".into()); |
| 190 | e |
| 191 | } |
| 192 | |
| 193 | fn not_found(msg: impl Into<String>) -> Self { |
| 194 | Self { |
| 195 | status: StatusCode::NOT_FOUND, |
| 196 | body: ErrorBody::new("not_found_error", msg), |
| 197 | retry_after: None, |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | fn too_large(max: usize) -> Self { |
| 202 | Self { |
| 203 | status: StatusCode::PAYLOAD_TOO_LARGE, |
| 204 | body: ErrorBody::new( |
| 205 | "invalid_request_error", |
| 206 | format!("request body exceeds the limit of {max} bytes"), |
| 207 | ), |
| 208 | retry_after: None, |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | fn busy() -> Self { |
| 213 | Self { |
| 214 | status: StatusCode::SERVICE_UNAVAILABLE, |
| 215 | body: ErrorBody::new( |
| 216 | "server_busy", |
| 217 | "every generation slot is taken (the engine's concurrency): retry shortly", |
| 218 | ), |
| 219 | retry_after: Some(1), |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | /// The engine could not get the shared chip in time (another job holds the GPU lock). |
| 224 | fn gpu_busy(detail: &str) -> Self { |
| 225 | let mut e = Self { |
| 226 | status: StatusCode::SERVICE_UNAVAILABLE, |
| 227 | body: ErrorBody::new( |
| 228 | "server_busy", |
| 229 | format!("GPU busy with another job, retry shortly: {detail}"), |
| 230 | ), |
| 231 | retry_after: Some(5), |
| 232 | }; |
| 233 | e.body.error.code = Some("gpu_busy".into()); |
| 234 | e |
| 235 | } |
| 236 | |
| 237 | fn internal(msg: impl Into<String>) -> Self { |
| 238 | Self { |
| 239 | status: StatusCode::INTERNAL_SERVER_ERROR, |
| 240 | body: ErrorBody::new("server_error", msg), |
| 241 | retry_after: None, |
| 242 | } |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | impl IntoResponse for ApiError { |
| 247 | fn into_response(self) -> Response { |
| 248 | let mut resp = (self.status, Json(self.body)).into_response(); |
| 249 | if let Some(s) = self.retry_after { |
| 250 | resp.headers_mut().insert( |
| 251 | header::RETRY_AFTER, |
| 252 | HeaderValue::from_str(&s.to_string()).expect("digits"), |
| 253 | ); |
| 254 | } |
| 255 | resp |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | struct Prepared { |
| 260 | prompt_tokens: Vec<u32>, |
| 261 | params: GenerateParams, |
| 262 | stop_strings: Vec<String>, |
| 263 | stream: bool, |
| 264 | /// The prompt opens a thinking block: reply tokens up to this id are reasoning. |
| 265 | reasoning_end: Option<u32>, |
| 266 | return_ids: bool, |
| 267 | /// The request carried tools: parse `<tool_call>` blocks out of the reply. |
| 268 | tools: bool, |
| 269 | /// The merge train's switches for this request (empty: none; `aien_test` absent). |
| 270 | test: TestSwitches, |
| 271 | } |
| 272 | |
| 273 | /// What the generation thread sends to the HTTP side. `Done` is sent once per request, so its size |
| 274 | /// (past clippy's line since `aien_test` joined it) costs nothing. |
| 275 | #[allow(clippy::large_enum_variant)] |
| 276 | enum Ev { |
| 277 | Delta(String), |
| 278 | /// Text of the thinking block (`reasoning_content`). |
| 279 | Reasoning(String), |
| 280 | Done { |
| 281 | finish: &'static str, |
| 282 | completion_tokens: usize, |
| 283 | sampling: Option<SamplingRecord>, |
| 284 | token_ids: Option<Vec<u32>>, |
| 285 | /// The `aien_test` switches applied (`usage.aien_test.applied`), when the request set any. |
| 286 | test: Option<Vec<&'static str>>, |
| 287 | }, |
| 288 | Error(String), |
| 289 | /// Memory admission refused a prompt inside the engine: 413 `prompt_exceeds_memory_budget` |
| 290 | /// while nothing has been sent, an error event with that code once a stream is open. |
| 291 | MemoryExceeded(String), |
| 292 | /// The engine could not get the shared chip: 503 before any token. |
| 293 | Busy(String), |
| 294 | /// Readers, streaming: the reading has started (the response goes out; nothing is sent). |
| 295 | Reading, |
| 296 | /// Readers: what each reader found (`aien_readers`) and the connect prompt's length. |
| 297 | Readers { |
| 298 | info: Value, |
| 299 | prompt_tokens: usize, |
| 300 | }, |
| 301 | } |
| 302 | |
| 303 | fn unix_now() -> (u64, u128) { |
| 304 | let d = SystemTime::now() |
| 305 | .duration_since(UNIX_EPOCH) |
| 306 | .unwrap_or(Duration::ZERO); |
| 307 | (d.as_secs(), d.as_nanos()) |
| 308 | } |
| 309 | |
| 310 | pub fn router(state: Arc<AppState>) -> Router { |
| 311 | Router::new() |
| 312 | .route("/v1/models", get(list_models)) |
| 313 | .route("/v1/models/:id", get(get_model)) |
| 314 | .route("/v1/chat/completions", post(chat_completions)) |
| 315 | .route("/health", get(health)) |
| 316 | .fallback(not_found) |
| 317 | .with_state(state) |
| 318 | } |
| 319 | |
| 320 | /// Binds `cfg.bind:cfg.port` (loopback only) and serves in a background task. |
| 321 | /// Returns the bound address (useful with port 0) and the task handle. |
| 322 | pub async fn serve( |
| 323 | cfg: ServerConfig, |
| 324 | engine: Arc<dyn Engine>, |
| 325 | codec: Arc<dyn Codec>, |
| 326 | ) -> std::io::Result<(SocketAddr, JoinHandle<()>)> { |
| 327 | serve_until(cfg, engine, codec, std::future::pending()).await |
| 328 | } |
| 329 | |
| 330 | /// [`serve`] until `shutdown` resolves: then no new connection is accepted, the requests in |
| 331 | /// flight finish (a streaming generation runs to its end) and the task ends, releasing the |
| 332 | /// server's hold on `engine`. |
| 333 | pub async fn serve_until( |
| 334 | cfg: ServerConfig, |
| 335 | engine: Arc<dyn Engine>, |
| 336 | codec: Arc<dyn Codec>, |
| 337 | shutdown: impl std::future::Future<Output = ()> + Send + 'static, |
| 338 | ) -> std::io::Result<(SocketAddr, JoinHandle<()>)> { |
| 339 | if !cfg.bind.is_loopback() { |
| 340 | return Err(std::io::Error::new( |
| 341 | std::io::ErrorKind::InvalidInput, |
| 342 | format!("refusing to bind {}: loopback addresses only", cfg.bind), |
| 343 | )); |
| 344 | } |
| 345 | if cfg.bearer_token.is_empty() || !cfg.bearer_token.bytes().all(|b| b.is_ascii_graphic()) { |
| 346 | return Err(std::io::Error::new( |
| 347 | std::io::ErrorKind::InvalidInput, |
| 348 | "a nonempty printable bearer token is required before binding", |
| 349 | )); |
| 350 | } |
| 351 | let listener = tokio::net::TcpListener::bind(SocketAddr::new(cfg.bind, cfg.port)).await?; |
| 352 | let addr = listener.local_addr()?; |
| 353 | let gate = Arc::new(Semaphore::new(engine.concurrency().max(1))); |
| 354 | let header_read_timeout = cfg.header_read_timeout; |
| 355 | let slots = Arc::new(Semaphore::new(cfg.max_connections.max(1))); |
| 356 | let state = Arc::new(AppState { |
| 357 | engine, |
| 358 | codec, |
| 359 | cfg, |
| 360 | gate, |
| 361 | allowed_hosts: [ |
| 362 | "localhost".into(), |
| 363 | format!("localhost:{}", addr.port()), |
| 364 | addr.to_string(), |
| 365 | ], |
| 366 | started: Instant::now(), |
| 367 | counter: AtomicU64::new(0), |
| 368 | }); |
| 369 | let app = router(state); |
| 370 | let handle = tokio::spawn(serve_connections( |
| 371 | listener, |
| 372 | app, |
| 373 | header_read_timeout, |
| 374 | slots, |
| 375 | shutdown, |
| 376 | )); |
| 377 | Ok((addr, handle)) |
| 378 | } |
| 379 | |
| 380 | /// The accept loop: HTTP/1 on each connection with the head bounded by `header_read_timeout`, at |
| 381 | /// most `slots` connections at once. When `shutdown` resolves no new connection is accepted, idle |
| 382 | /// connections close, requests in flight run to their end, and the loop returns once every |
| 383 | /// connection is gone. |
| 384 | async fn serve_connections( |
| 385 | listener: tokio::net::TcpListener, |
| 386 | app: Router, |
| 387 | header_read_timeout: Duration, |
| 388 | slots: Arc<Semaphore>, |
| 389 | shutdown: impl std::future::Future<Output = ()> + Send + 'static, |
| 390 | ) { |
| 391 | let (stop_tx, stop_rx) = tokio::sync::watch::channel(()); |
| 392 | let mut connections = tokio::task::JoinSet::new(); |
| 393 | tokio::pin!(shutdown); |
| 394 | loop { |
| 395 | let slot = tokio::select! { |
| 396 | _ = &mut shutdown => break, |
| 397 | slot = Arc::clone(&slots).acquire_owned() => slot.expect("the slots are never closed"), |
| 398 | }; |
| 399 | let stream = tokio::select! { |
| 400 | _ = &mut shutdown => break, |
| 401 | accepted = listener.accept() => match accepted { |
| 402 | Ok((stream, _)) => stream, |
| 403 | Err(e) if matches!( |
| 404 | e.kind(), |
| 405 | std::io::ErrorKind::ConnectionRefused |
| 406 | | std::io::ErrorKind::ConnectionAborted |
| 407 | | std::io::ErrorKind::ConnectionReset |
| 408 | ) => continue, |
| 409 | Err(e) => { |
| 410 | // Out of file descriptors and the like: wait for some to be released. |
| 411 | eprintln!("aien-serve-http: accept failed: {e}"); |
| 412 | tokio::time::sleep(Duration::from_secs(1)).await; |
| 413 | continue; |
| 414 | } |
| 415 | }, |
| 416 | }; |
| 417 | let app = app.clone(); |
| 418 | let mut stop = stop_rx.clone(); |
| 419 | connections.spawn(async move { |
| 420 | let _slot = slot; |
| 421 | let mut http = hyper::server::conn::http1::Builder::new(); |
| 422 | http.timer(hyper_util::rt::TokioTimer::new()) |
| 423 | .header_read_timeout(header_read_timeout); |
| 424 | let conn = http.serve_connection( |
| 425 | hyper_util::rt::TokioIo::new(stream), |
| 426 | hyper_util::service::TowerToHyperService::new(app), |
| 427 | ); |
| 428 | tokio::pin!(conn); |
| 429 | tokio::select! { |
| 430 | _ = conn.as_mut() => return, |
| 431 | _ = stop.changed() => conn.as_mut().graceful_shutdown(), |
| 432 | } |
| 433 | let _ = conn.await; |
| 434 | }); |
| 435 | while connections.try_join_next().is_some() {} |
| 436 | } |
| 437 | drop(listener); |
| 438 | let _ = stop_tx.send(()); |
| 439 | while connections.join_next().await.is_some() {} |
| 440 | } |
| 441 | |
| 442 | fn model_card(state: &AppState) -> ModelCard { |
| 443 | model_card_for(state, &state.cfg.model_id) |
| 444 | } |
| 445 | |
| 446 | fn model_card_for(state: &AppState, id: &str) -> ModelCard { |
| 447 | ModelCard { |
| 448 | id: id.to_string(), |
| 449 | object: "model", |
| 450 | created: unix_now().0 - state.started.elapsed().as_secs(), |
| 451 | owned_by: format!("aien/{}", state.engine.kind()), |
| 452 | } |
| 453 | } |
| 454 | |
| 455 | async fn list_models(State(state): State<Arc<AppState>>) -> Json<ModelList> { |
| 456 | Json(ModelList { |
| 457 | object: "list", |
| 458 | data: std::iter::once(model_card(&state)) |
| 459 | .chain( |
| 460 | state |
| 461 | .cfg |
| 462 | .readers |
| 463 | .as_ref() |
| 464 | .map(|r| model_card_for(&state, &r.model_id)), |
| 465 | ) |
| 466 | .collect(), |
| 467 | }) |
| 468 | } |
| 469 | |
| 470 | async fn get_model( |
| 471 | State(state): State<Arc<AppState>>, |
| 472 | Path(id): Path<String>, |
| 473 | ) -> Result<Json<ModelCard>, ApiError> { |
| 474 | if let Some(r) = state.cfg.readers.as_ref().filter(|r| r.model_id == id) { |
| 475 | return Ok(Json(model_card_for(&state, &r.model_id))); |
| 476 | } |
| 477 | if id != state.cfg.model_id { |
| 478 | return Err(ApiError::not_found(format!( |
| 479 | "model '{id}' not found; this server serves '{}'", |
| 480 | state.cfg.model_id |
| 481 | ))); |
| 482 | } |
| 483 | Ok(Json(model_card(&state))) |
| 484 | } |
| 485 | |
| 486 | async fn health(State(state): State<Arc<AppState>>) -> Json<Value> { |
| 487 | let mut v = serde_json::json!({ |
| 488 | "status": "ok", |
| 489 | "model": state.cfg.model_id, |
| 490 | "engine": state.engine.kind(), |
| 491 | "busy": state.gate.available_permits() == 0, |
| 492 | "uptime_s": state.started.elapsed().as_secs(), |
| 493 | }); |
| 494 | // A batching engine says how many it runs at once; one-at-a-time engines leave `/health` |
| 495 | // exactly as it was. |
| 496 | let n = state.engine.concurrency(); |
| 497 | if let (true, Some(obj)) = (n > 1, v.as_object_mut()) { |
| 498 | obj.insert("concurrency".into(), n.into()); |
| 499 | obj.insert( |
| 500 | "in_flight".into(), |
| 501 | (n - state.gate.available_permits().min(n)).into(), |
| 502 | ); |
| 503 | } |
| 504 | // Persistent KV (sc#505): present only when AIEN_KV_STORE_DIR asked for it. |
| 505 | if let (Some(pk), Some(obj)) = (state.engine.persistence_status(), v.as_object_mut()) { |
| 506 | obj.insert("persistent_kv".into(), pk); |
| 507 | } |
| 508 | // The merge train (L384): which `aien_test` switches this build honors, so the train marks a |
| 509 | // lever NOT-ON-TRAIN instead of PASS when its switch is not in the candidate. Test builds only. |
| 510 | // Absent for an engine with no switches, so its /health stays exactly as it was. |
| 511 | #[cfg(feature = "aien-test-switches")] |
| 512 | if let (false, Some(obj)) = ( |
| 513 | state.engine.test_switches_honored().is_empty(), |
| 514 | v.as_object_mut(), |
| 515 | ) { |
| 516 | obj.insert( |
| 517 | "aien_test".into(), |
| 518 | serde_json::json!({ "honored": state.engine.test_switches_honored() }), |
| 519 | ); |
| 520 | } |
| 521 | Json(v) |
| 522 | } |
| 523 | |
| 524 | async fn not_found() -> ApiError { |
| 525 | ApiError::not_found( |
| 526 | "no such route; this server exposes /v1/models, /v1/chat/completions and /health", |
| 527 | ) |
| 528 | } |
| 529 | |
| 530 | /// Keep all authorization and slot decisions before the first body poll. |
| 531 | async fn chat_completions(State(state): State<Arc<AppState>>, request: Request<Body>) -> Response { |
| 532 | match handle_chat(state, request).await { |
| 533 | Ok(r) => r, |
| 534 | Err(e) => e.into_response(), |
| 535 | } |
| 536 | } |
| 537 | |
| 538 | fn authorized(headers: &HeaderMap, token: &str) -> bool { |
| 539 | if headers.get_all(header::AUTHORIZATION).iter().count() != 1 { |
| 540 | return false; |
| 541 | } |
| 542 | let Some(value) = headers |
| 543 | .get(header::AUTHORIZATION) |
| 544 | .and_then(|h| h.to_str().ok()) |
| 545 | else { |
| 546 | return false; |
| 547 | }; |
| 548 | let Some(provided) = value.strip_prefix("Bearer ") else { |
| 549 | return false; |
| 550 | }; |
| 551 | let (a, b) = (provided.as_bytes(), token.as_bytes()); |
| 552 | if a.len() != b.len() { |
| 553 | return false; |
| 554 | } |
| 555 | let mut diff = 0u8; |
| 556 | for (&x, &y) in a.iter().zip(b) { |
| 557 | diff |= x ^ y; |
| 558 | } |
| 559 | diff == 0 |
| 560 | } |
| 561 | |
| 562 | fn check_headers(state: &AppState, headers: &HeaderMap) -> Result<(), ApiError> { |
| 563 | if !authorized(headers, &state.cfg.bearer_token) { |
| 564 | return Err(ApiError::unauthorized()); |
| 565 | } |
| 566 | if headers.get_all(header::HOST).iter().count() != 1 { |
| 567 | return Err(ApiError::forbidden("unrecognized Host")); |
| 568 | } |
| 569 | let host = headers |
| 570 | .get(header::HOST) |
| 571 | .and_then(|h| h.to_str().ok()) |
| 572 | .ok_or_else(|| ApiError::forbidden("unrecognized Host"))?; |
| 573 | if !state |
| 574 | .allowed_hosts |
| 575 | .iter() |
| 576 | .any(|h| host.eq_ignore_ascii_case(h)) |
| 577 | { |
| 578 | return Err(ApiError::forbidden("unrecognized Host")); |
| 579 | } |
| 580 | if headers.get_all(header::ORIGIN).iter().count() > 1 { |
| 581 | return Err(ApiError::forbidden("unrecognized Origin")); |
| 582 | } |
| 583 | if let Some(origin) = headers.get(header::ORIGIN) { |
| 584 | let origin = origin |
| 585 | .to_str() |
| 586 | .map_err(|_| ApiError::forbidden("unrecognized Origin"))?; |
| 587 | let origin_host = origin |
| 588 | .strip_prefix("http://") |
| 589 | .ok_or_else(|| ApiError::forbidden("unrecognized Origin"))?; |
| 590 | if !state.allowed_hosts[1..] |
| 591 | .iter() |
| 592 | .any(|h| origin_host.eq_ignore_ascii_case(h)) |
| 593 | { |
| 594 | return Err(ApiError::forbidden("unrecognized Origin")); |
| 595 | } |
| 596 | } |
| 597 | if headers.get_all(header::CONTENT_TYPE).iter().count() != 1 { |
| 598 | return Err(ApiError::unsupported_media_type()); |
| 599 | } |
| 600 | let media = headers |
| 601 | .get(header::CONTENT_TYPE) |
| 602 | .and_then(|h| h.to_str().ok()) |
| 603 | .unwrap_or(""); |
| 604 | if !media |
| 605 | .split(';') |
| 606 | .next() |
| 607 | .is_some_and(|kind| kind.eq_ignore_ascii_case("application/json")) |
| 608 | { |
| 609 | return Err(ApiError::unsupported_media_type()); |
| 610 | } |
| 611 | Ok(()) |
| 612 | } |
| 613 | |
| 614 | async fn handle_chat(state: Arc<AppState>, request: Request<Body>) -> Result<Response, ApiError> { |
| 615 | check_headers(&state, request.headers())?; |
| 616 | // A request owns its engine slot while the bounded body is read and while parsing or |
| 617 | // tokenizing. Readers may reserve additional slots only after their initial admission. |
| 618 | let guard = Arc::clone(&state.gate) |
| 619 | .try_acquire_owned() |
| 620 | .map_err(|_| ApiError::busy())?; |
| 621 | if request |
| 622 | .headers() |
| 623 | .get(header::CONTENT_LENGTH) |
| 624 | .and_then(|h| h.to_str().ok()) |
| 625 | .and_then(|s| s.parse::<usize>().ok()) |
| 626 | .is_some_and(|n| n > state.cfg.max_body_bytes) |
| 627 | { |
| 628 | return Err(ApiError::too_large(state.cfg.max_body_bytes)); |
| 629 | } |
| 630 | let limit = state.cfg.max_body_bytes; |
| 631 | let body = tokio::time::timeout( |
| 632 | Duration::from_secs(15), |
| 633 | to_bytes(request.into_body(), limit), |
| 634 | ) |
| 635 | .await |
| 636 | .map_err(|_| ApiError::bad_request("request body read timed out"))? |
| 637 | .map_err(|_| ApiError::too_large(limit))?; |
| 638 | let pending = tokio::task::spawn_blocking(move || prepare_chat(state, body, guard)) |
| 639 | .await |
| 640 | .map_err(|_| ApiError::internal("request preparation failed"))??; |
| 641 | respond( |
| 642 | pending.rx, |
| 643 | pending.stream, |
| 644 | pending.id, |
| 645 | pending.created, |
| 646 | pending.model, |
| 647 | pending.prompt_tokens, |
| 648 | pending.tools, |
| 649 | ) |
| 650 | .await |
| 651 | } |
| 652 | |
| 653 | struct PendingResponse { |
| 654 | rx: mpsc::Receiver<Ev>, |
| 655 | stream: bool, |
| 656 | id: String, |
| 657 | created: u64, |
| 658 | model: String, |
| 659 | prompt_tokens: usize, |
| 660 | tools: bool, |
| 661 | } |
| 662 | |
| 663 | fn prepare_chat( |
| 664 | state: Arc<AppState>, |
| 665 | body: Bytes, |
| 666 | guard: OwnedSemaphorePermit, |
| 667 | ) -> Result<PendingResponse, ApiError> { |
| 668 | let mut guard = Some(guard); |
| 669 | let mut raw: Value = serde_json::from_slice(&body) |
| 670 | .map_err(|e| ApiError::bad_request(format!("invalid JSON request: {e}")))?; |
| 671 | let mut model = state.cfg.model_id.clone(); |
| 672 | if let Some(rc) = state.cfg.readers.as_ref() { |
| 673 | if raw.get("model").and_then(Value::as_str) == Some(rc.model_id.as_str()) { |
| 674 | raw["model"] = Value::String(state.cfg.model_id.clone()); |
| 675 | if let Some(r) = handle_readers(&state, rc, &raw, &mut guard)? { |
| 676 | return Ok(r); |
| 677 | } |
| 678 | model = rc.model_id.clone(); |
| 679 | } |
| 680 | } |
| 681 | let req: ChatRequest = serde_json::from_value(raw) |
| 682 | .map_err(|e| ApiError::bad_request(format!("invalid JSON request: {e}")))?; |
| 683 | let prepared = prepare(&state, req)?; |
| 684 | let (created, id) = new_id(&state); |
| 685 | let prompt_tokens = prepared.prompt_tokens.len(); |
| 686 | let stream = prepared.stream; |
| 687 | let tools = prepared.tools; |
| 688 | let (tx, rx) = mpsc::channel::<Ev>(64); |
| 689 | let engine = Arc::clone(&state.engine); |
| 690 | let codec = Arc::clone(&state.codec); |
| 691 | let log_id = id.clone(); |
| 692 | tokio::task::spawn_blocking(move || { |
| 693 | run_generation( |
| 694 | engine, |
| 695 | codec, |
| 696 | prepared, |
| 697 | tx, |
| 698 | guard.expect("admitted slot"), |
| 699 | &log_id, |
| 700 | ); |
| 701 | }); |
| 702 | Ok(PendingResponse { |
| 703 | rx, |
| 704 | stream, |
| 705 | id, |
| 706 | created, |
| 707 | model, |
| 708 | prompt_tokens, |
| 709 | tools, |
| 710 | }) |
| 711 | } |
| 712 | |
| 713 | fn new_id(state: &AppState) -> (u64, String) { |
| 714 | let (created, nanos) = unix_now(); |
| 715 | let n = state.counter.fetch_add(1, Ordering::Relaxed); |
| 716 | (created, format!("chatcmpl-{nanos:x}{n:04x}")) |
| 717 | } |
| 718 | |
| 719 | /// A request to the readers id: `Ok(None)` when its long input is under the threshold (the caller |
| 720 | /// serves it on the plain path). Otherwise the rows that are free now (up to `rc.readers`; one |
| 721 | /// free row of a batching engine is 503 `server_busy`) each read one part, and one of them writes |
| 722 | /// the answer from the notes. |
| 723 | fn handle_readers( |
| 724 | state: &Arc<AppState>, |
| 725 | rc: &crate::readers::ReadersConfig, |
| 726 | raw: &Value, |
| 727 | first: &mut Option<OwnedSemaphorePermit>, |
| 728 | ) -> Result<Option<PendingResponse>, ApiError> { |
| 729 | use crate::readers; |
| 730 | let msgs: &[Value] = raw |
| 731 | .get("messages") |
| 732 | .and_then(Value::as_array) |
| 733 | .map_or(&[], Vec::as_slice); |
| 734 | let count = |s: &str| state.codec.encode(s).map_or(s.len() / 4, |t| t.len()); |
| 735 | let Some(mut plan) = readers::plan(msgs, rc, &count) else { |
| 736 | return Ok(None); |
| 737 | }; |
| 738 | let slots = state.engine.concurrency().max(1); |
| 739 | let want = plan.parts.len().min(slots); |
| 740 | let (extra, got) = (1..want) |
| 741 | .rev() |
| 742 | .find_map(|k| { |
| 743 | Arc::clone(&state.gate) |
| 744 | .try_acquire_many_owned(k as u32) |
| 745 | .ok() |
| 746 | .map(|p| (Some(p), k + 1)) |
| 747 | }) |
| 748 | .unwrap_or((None, 1)); |
| 749 | if slots > 1 && got < 2 { |
| 750 | return Err(ApiError::busy()); |
| 751 | } |
| 752 | if slots > 1 && got < plan.parts.len() { |
| 753 | let fewer = readers::ReadersConfig { |
| 754 | readers: got, |
| 755 | ..rc.clone() |
| 756 | }; |
| 757 | plan = readers::plan(msgs, &fewer, &count) |
| 758 | .ok_or_else(|| ApiError::internal("readers: the plan vanished with fewer readers"))?; |
| 759 | } |
| 760 | let base = state.cfg.model_id.as_str(); |
| 761 | let from = |v: Value| -> Result<Prepared, ApiError> { |
| 762 | let req: ChatRequest = serde_json::from_value(v) |
| 763 | .map_err(|e| ApiError::bad_request(format!("invalid JSON request: {e}")))?; |
| 764 | prepare(state, req) |
| 765 | }; |
| 766 | let maps = (0..plan.parts.len()) |
| 767 | .map(|i| { |
| 768 | // The readers ride the request's merge-train switches too. |
| 769 | let mut b = readers::map_body(msgs, &plan, i, base, rc); |
| 770 | if let Some(t) = raw.get("aien_test") { |
| 771 | b["aien_test"] = t.clone(); |
| 772 | } |
| 773 | from(b) |
| 774 | }) |
| 775 | .collect::<Result<Vec<_>, _>>()?; |
| 776 | // The connect request must be valid before any row reads (same checks, notes not yet known). |
| 777 | let blank = vec![String::new(); plan.parts.len()]; |
| 778 | let check = from(readers::connect_body(raw, &plan, &blank, base))?; |
| 779 | let (stream, tools) = (check.stream, check.tools); |
| 780 | let show_notes = raw |
| 781 | .get("aien_show_notes") |
| 782 | .and_then(Value::as_bool) |
| 783 | .unwrap_or(false); |
| 784 | let (created, id) = new_id(state); |
| 785 | let (tx, rx) = mpsc::channel::<Ev>(64); |
| 786 | let st = Arc::clone(state); |
| 787 | let raw = raw.clone(); |
| 788 | let log_id = id.clone(); |
| 789 | let mut permit = first.take().expect("admitted slot"); |
| 790 | if let Some(extra) = extra { |
| 791 | permit.merge(extra); |
| 792 | } |
| 793 | tokio::task::spawn_blocking(move || { |
| 794 | run_readers(st, raw, plan, maps, permit, tx, stream, show_notes, &log_id); |
| 795 | }); |
| 796 | Ok(Some(PendingResponse { |
| 797 | rx, |
| 798 | stream, |
| 799 | id, |
| 800 | created, |
| 801 | model: rc.model_id.clone(), |
| 802 | prompt_tokens: 0, |
| 803 | tools, |
| 804 | })) |
| 805 | } |
| 806 | |
| 807 | /// Phase 1 (map: every part read at once through [`Engine::generate_group`]) and phase 2 |
| 808 | /// (connect: the notes into one answer on the usual generation path), on a blocking thread |
| 809 | /// holding the readers' permits; all but one are given back when the notes are in. |
| 810 | #[allow(clippy::too_many_arguments)] |
| 811 | fn run_readers( |
| 812 | state: Arc<AppState>, |
| 813 | raw: Value, |
| 814 | plan: crate::readers::Plan, |
| 815 | maps: Vec<Prepared>, |
| 816 | mut permit: OwnedSemaphorePermit, |
| 817 | tx: mpsc::Sender<Ev>, |
| 818 | stream: bool, |
| 819 | show_notes: bool, |
| 820 | id: &str, |
| 821 | ) { |
| 822 | use crate::readers; |
| 823 | use std::sync::atomic::AtomicBool; |
| 824 | let n = maps.len(); |
| 825 | let t0 = Instant::now(); |
| 826 | if stream { |
| 827 | // The response goes out now; the reading takes a while. |
| 828 | let mut s = format!("Reading {} tokens in {n} parts at once:", plan.total_tokens); |
| 829 | for (k, p) in plan.parts.iter().enumerate() { |
| 830 | s.push_str(&format!( |
| 831 | " {}: lines {}-{} ({} tok);", |
| 832 | k + 1, |
| 833 | p.first_line, |
| 834 | p.last_line, |
| 835 | p.tokens |
| 836 | )); |
| 837 | } |
| 838 | s.push('\n'); |
| 839 | if tx.blocking_send(Ev::Reading).is_err() || tx.blocking_send(Ev::Reasoning(s)).is_err() { |
| 840 | return; |
| 841 | } |
| 842 | } |
| 843 | let cancel = Arc::new(AtomicBool::new(false)); |
| 844 | let jobs: Vec<crate::engine::GroupJob> = maps |
| 845 | .iter() |
| 846 | .map(|p| crate::engine::GroupJob { |
| 847 | prompt: p.prompt_tokens.clone(), |
| 848 | params: p.params.clone(), |
| 849 | cancel: Some(Arc::clone(&cancel)), |
| 850 | test: p.test.clone(), |
| 851 | }) |
| 852 | .collect(); |
| 853 | // A client that leaves stops every reader, even one still taking in its part. |
| 854 | let reading = Arc::new(AtomicBool::new(true)); |
| 855 | { |
| 856 | let (tx, cancel, reading) = (tx.clone(), Arc::clone(&cancel), Arc::clone(&reading)); |
| 857 | std::thread::spawn(move || { |
| 858 | while reading.load(Ordering::SeqCst) { |
| 859 | if tx.is_closed() { |
| 860 | cancel.store(true, Ordering::SeqCst); |
| 861 | return; |
| 862 | } |
| 863 | std::thread::sleep(Duration::from_millis(200)); |
| 864 | } |
| 865 | }); |
| 866 | } |
| 867 | let mut toks: Vec<Vec<u32>> = vec![Vec::new(); n]; |
| 868 | let outs = state.engine.generate_group(&jobs, &mut |i, t| { |
| 869 | toks[i].push(t); |
| 870 | !cancel.load(Ordering::SeqCst) |
| 871 | }); |
| 872 | reading.store(false, Ordering::SeqCst); |
| 873 | let map_ms = t0.elapsed().as_millis() as u64; |
| 874 | if cancel.load(Ordering::SeqCst) && tx.is_closed() { |
| 875 | eprintln!("aien-serve-http: {id}: readers: client left while reading"); |
| 876 | return; |
| 877 | } |
| 878 | let mut parts = Vec::with_capacity(n); |
| 879 | let mut notes = Vec::with_capacity(n); |
| 880 | for (k, (out, t)) in outs.into_iter().zip(&toks).enumerate() { |
| 881 | let out = match out { |
| 882 | Ok(o) => o, |
| 883 | Err(EngineError::Busy(m)) => { |
| 884 | let _ = tx.blocking_send(Ev::Busy(m)); |
| 885 | return; |
| 886 | } |
| 887 | Err(EngineError::MemoryExceeded(m)) => { |
| 888 | eprintln!("aien-serve-http: {id}: reader {} refused: {m}", k + 1); |
| 889 | let _ = |
| 890 | tx.blocking_send(Ev::MemoryExceeded(format!("reader {} of {n}: {m}", k + 1))); |
| 891 | return; |
| 892 | } |
| 893 | Err(e) => { |
| 894 | eprintln!("aien-serve-http: {id}: reader {} failed: {e}", k + 1); |
| 895 | let _ = tx.blocking_send(Ev::Error(format!("reader {} of {n}: {e}", k + 1))); |
| 896 | return; |
| 897 | } |
| 898 | }; |
| 899 | let text = state.codec.decode(t).unwrap_or_default(); |
| 900 | let note = readers::clean_notes(&text); |
| 901 | let p = &plan.parts[k]; |
| 902 | parts.push(serde_json::json!({ |
| 903 | "part": k + 1, |
| 904 | "lines": [p.first_line, p.last_line], |
| 905 | "tokens": p.tokens, |
| 906 | "prompt_tokens": maps[k].prompt_tokens.len(), |
| 907 | "note_tokens": out.emitted_tokens, |
| 908 | "finish": match out.finish { |
| 909 | FinishReason::Length => "length", |
| 910 | _ => "stop", |
| 911 | }, |
| 912 | "notes": note, |
| 913 | })); |
| 914 | notes.push(note); |
| 915 | } |
| 916 | // Keep one row for the answer, give the others back. |
| 917 | let Some(one) = permit.split(1) else { |
| 918 | let _ = tx.blocking_send(Ev::Error("readers: no permit left for the answer".into())); |
| 919 | return; |
| 920 | }; |
| 921 | drop(permit); |
| 922 | let body = readers::connect_body(&raw, &plan, ¬es, &state.cfg.model_id); |
| 923 | let connect = match serde_json::from_value::<ChatRequest>(body) |
| 924 | .map_err(|e| (false, e.to_string())) |
| 925 | .and_then(|r| { |
| 926 | prepare(&state, r).map_err(|e| { |
| 927 | ( |
| 928 | e.body.error.code.as_deref() == Some("prompt_exceeds_memory_budget"), |
| 929 | e.body.error.message, |
| 930 | ) |
| 931 | }) |
| 932 | }) { |
| 933 | Ok(p) => p, |
| 934 | Err((memory, m)) => { |
| 935 | let m = format!("readers: connect request: {m}"); |
| 936 | let _ = tx.blocking_send(if memory { |
| 937 | Ev::MemoryExceeded(m) |
| 938 | } else { |
| 939 | Ev::Error(m) |
| 940 | }); |
| 941 | return; |
| 942 | } |
| 943 | }; |
| 944 | let info = serde_json::json!({ |
| 945 | "readers": n, |
| 946 | "input_tokens": plan.total_tokens, |
| 947 | "input_lines": plan.total_lines, |
| 948 | "question_is_excerpt": plan.question_is_excerpt, |
| 949 | "map_ms": map_ms, |
| 950 | "map_prompt_tokens": maps.iter().map(|m| m.prompt_tokens.len()).sum::<usize>(), |
| 951 | "connect_prompt_tokens": connect.prompt_tokens.len(), |
| 952 | "parts": parts, |
| 953 | }); |
| 954 | eprintln!( |
| 955 | "aien-serve-http: {id}: readers: {n} parts of {} tokens read in {map_ms} ms, notes {} tok, connect prompt {} tok", |
| 956 | plan.total_tokens, |
| 957 | parts.iter().map(|p| p["note_tokens"].as_u64().unwrap_or(0)).sum::<u64>(), |
| 958 | connect.prompt_tokens.len() |
| 959 | ); |
| 960 | if stream { |
| 961 | let s = format!( |
| 962 | "Notes from {n} readers in {:.1} s; connecting them.\n", |
| 963 | map_ms as f64 / 1000.0 |
| 964 | ); |
| 965 | if tx.blocking_send(Ev::Reasoning(s)).is_err() { |
| 966 | return; |
| 967 | } |
| 968 | } |
| 969 | let prompt_tokens = connect.prompt_tokens.len(); |
| 970 | if tx |
| 971 | .blocking_send(Ev::Readers { |
| 972 | info, |
| 973 | prompt_tokens, |
| 974 | }) |
| 975 | .is_err() |
| 976 | { |
| 977 | return; |
| 978 | } |
| 979 | if show_notes |
| 980 | && tx |
| 981 | .blocking_send(Ev::Delta(readers::notes_preface(&plan, ¬es))) |
| 982 | .is_err() |
| 983 | { |
| 984 | return; |
| 985 | } |
| 986 | run_generation( |
| 987 | Arc::clone(&state.engine), |
| 988 | Arc::clone(&state.codec), |
| 989 | connect, |
| 990 | tx, |
| 991 | one, |
| 992 | id, |
| 993 | ); |
| 994 | } |
| 995 | |
| 996 | /// The response for a generation's events: the first decides the status (a busy chip is 503). |
| 997 | async fn respond( |
| 998 | mut rx: mpsc::Receiver<Ev>, |
| 999 | stream: bool, |
| 1000 | id: String, |
| 1001 | created: u64, |
| 1002 | model: String, |
| 1003 | prompt_tokens: usize, |
| 1004 | tools: bool, |
| 1005 | ) -> Result<Response, ApiError> { |
| 1006 | // The first event decides the status: a busy chip is a 503 in the OpenAI error envelope, |
| 1007 | // before any headers go out (streaming included). Everything else is forwarded unchanged. |
| 1008 | let first = rx.recv().await; |
| 1009 | match &first { |
| 1010 | Some(Ev::Busy(m)) => return Err(ApiError::gpu_busy(m)), |
| 1011 | Some(Ev::MemoryExceeded(m)) => return Err(ApiError::memory_exceeded(m.clone())), |
| 1012 | _ => {} |
| 1013 | } |
| 1014 | let (ftx, frx) = mpsc::channel::<Ev>(64); |
| 1015 | tokio::spawn(async move { |
| 1016 | if let Some(ev) = first { |
| 1017 | if ftx.send(ev).await.is_err() { |
| 1018 | return; |
| 1019 | } |
| 1020 | } |
| 1021 | while let Some(ev) = rx.recv().await { |
| 1022 | if ftx.send(ev).await.is_err() { |
| 1023 | return; |
| 1024 | } |
| 1025 | } |
| 1026 | }); |
| 1027 | let rx = frx; |
| 1028 | if stream { |
| 1029 | Ok(stream_response( |
| 1030 | id, |
| 1031 | created, |
| 1032 | model, |
| 1033 | prompt_tokens, |
| 1034 | rx, |
| 1035 | tools, |
| 1036 | )) |
| 1037 | } else { |
| 1038 | collect_response(id, created, &model, prompt_tokens, rx, tools).await |
| 1039 | } |
| 1040 | } |
| 1041 | |
| 1042 | fn text_of_content(content: &Value) -> Result<String, ApiError> { |
| 1043 | match content { |
| 1044 | Value::Null => Ok(String::new()), |
| 1045 | Value::String(s) => Ok(s.clone()), |
| 1046 | Value::Array(parts) => { |
| 1047 | let mut out = String::new(); |
| 1048 | for part in parts { |
| 1049 | match part.get("type").and_then(Value::as_str) { |
| 1050 | Some("text") => out.push_str( |
| 1051 | part.get("text") |
| 1052 | .and_then(Value::as_str) |
| 1053 | .ok_or_else(|| ApiError::bad_request("text part without 'text'"))?, |
| 1054 | ), |
| 1055 | other => { |
| 1056 | return Err(ApiError::bad_request(format!( |
| 1057 | "unsupported content part type {:?}: only text parts are accepted", |
| 1058 | other.unwrap_or("missing") |
| 1059 | ))) |
| 1060 | } |
| 1061 | } |
| 1062 | } |
| 1063 | Ok(out) |
| 1064 | } |
| 1065 | _ => Err(ApiError::bad_request( |
| 1066 | "message content must be a string or an array of text parts", |
| 1067 | )), |
| 1068 | } |
| 1069 | } |
| 1070 | |
| 1071 | fn prepare(state: &AppState, req: ChatRequest) -> Result<Prepared, ApiError> { |
| 1072 | let cfg = &state.cfg; |
| 1073 | if let Some(m) = req.model.as_deref() { |
| 1074 | if m != cfg.model_id { |
| 1075 | return Err(ApiError::not_found(format!( |
| 1076 | "model '{m}' not found; this server serves '{}'", |
| 1077 | cfg.model_id |
| 1078 | ))); |
| 1079 | } |
| 1080 | } |
| 1081 | if matches!(req.n, Some(n) if n != 1) { |
| 1082 | return Err(ApiError::bad_request("n must be 1")); |
| 1083 | } |
| 1084 | // Tool calling in the model's own format (`cfg.tool_format`, read from its chat template at |
| 1085 | // load): legacy `functions` are accepted as tools. |
| 1086 | let tool_defs: Vec<Value> = match (&req.tools, &req.functions) { |
| 1087 | (Some(t), _) if !t.is_empty() => t.clone(), |
| 1088 | (_, Some(f)) if !f.is_empty() => f |
| 1089 | .iter() |
| 1090 | .map(|f| serde_json::json!({"type": "function", "function": f})) |
| 1091 | .collect(), |
| 1092 | _ => Vec::new(), |
| 1093 | }; |
| 1094 | if req.messages.is_empty() { |
| 1095 | return Err(ApiError::bad_request("messages must be a non-empty array")); |
| 1096 | } |
| 1097 | if req.messages.len() > cfg.max_messages { |
| 1098 | return Err(ApiError::bad_request(format!( |
| 1099 | "too many messages: {} (limit {})", |
| 1100 | req.messages.len(), |
| 1101 | cfg.max_messages |
| 1102 | ))); |
| 1103 | } |
| 1104 | let mut msgs: Vec<(&str, String, Option<&[Value]>)> = Vec::with_capacity(req.messages.len()); |
| 1105 | for m in &req.messages { |
| 1106 | let role = match m.role.trim().to_ascii_lowercase().as_str() { |
| 1107 | "system" | "developer" => "system", |
| 1108 | "user" => "user", |
| 1109 | "assistant" => "assistant", |
| 1110 | "tool" | "function" => "tool", |
| 1111 | other => { |
| 1112 | return Err(ApiError::bad_request(format!( |
| 1113 | "unknown message role '{other}'" |
| 1114 | ))) |
| 1115 | } |
| 1116 | }; |
| 1117 | msgs.push((role, text_of_content(&m.content)?, m.tool_calls.as_deref())); |
| 1118 | } |
| 1119 | let turns = crate::tools::fold_turns(cfg.tool_format, &tool_defs, msgs); |
| 1120 | let turn_refs: Vec<(&str, &str)> = turns |
| 1121 | .iter() |
| 1122 | .map(|(r, c)| (r.as_str(), c.as_str())) |
| 1123 | .collect(); |
| 1124 | let mut opts = chat_options(&req)?; |
| 1125 | if opts.enable_thinking.is_none() { |
| 1126 | opts.enable_thinking = cfg.default_enable_thinking; |
| 1127 | } |
| 1128 | let prompt_text = state |
| 1129 | .codec |
| 1130 | .render_chat_with(&turn_refs, &opts) |
| 1131 | .map_err(|e| match e { |
| 1132 | CodecError::Unrenderable(m) => ApiError::bad_request(m), |
| 1133 | CodecError::Failed(m) => ApiError::internal(m), |
| 1134 | })?; |
| 1135 | let prompt_tokens = state |
| 1136 | .codec |
| 1137 | .encode(&prompt_text) |
| 1138 | .map_err(|e| ApiError::context_exceeded(format!("could not tokenize prompt: {e}")))?; |
| 1139 | if prompt_tokens.is_empty() { |
| 1140 | return Err(ApiError::bad_request("the rendered prompt is empty")); |
| 1141 | } |
| 1142 | |
| 1143 | let ctx = cfg |
| 1144 | .max_context_tokens |
| 1145 | .unwrap_or(usize::MAX) |
| 1146 | .min(state.engine.max_context_tokens()); |
| 1147 | if prompt_tokens.len() >= ctx { |
| 1148 | return Err(ApiError::context_exceeded(format!( |
| 1149 | "prompt is {} tokens; the context window is {} tokens and at least one token must be left for the reply", |
| 1150 | prompt_tokens.len(), |
| 1151 | ctx |
| 1152 | ))); |
| 1153 | } |
| 1154 | state |
| 1155 | .engine |
| 1156 | .admit(&prompt_tokens) |
| 1157 | .map_err(ApiError::memory_exceeded)?; |
| 1158 | let requested = match req.max_tokens.or(req.max_completion_tokens) { |
| 1159 | Some(v) if v < 1 => return Err(ApiError::bad_request("max_tokens must be at least 1")), |
| 1160 | Some(v) => v as usize, |
| 1161 | None => cfg.default_max_new_tokens, |
| 1162 | }; |
| 1163 | let max_new_tokens = requested |
| 1164 | .min(cfg.max_new_tokens_cap) |
| 1165 | .min(ctx - prompt_tokens.len()); |
| 1166 | |
| 1167 | let temperature = req.temperature.unwrap_or(cfg.default_temperature); |
| 1168 | if !(0.0..=2.0).contains(&temperature) { |
| 1169 | return Err(ApiError::bad_request("temperature must be between 0 and 2")); |
| 1170 | } |
| 1171 | let top_p = req.top_p.unwrap_or(cfg.default_top_p); |
| 1172 | if !(top_p > 0.0 && top_p <= 1.0) { |
| 1173 | return Err(ApiError::bad_request("top_p must be in (0, 1]")); |
| 1174 | } |
| 1175 | let top_k = match req.top_k { |
| 1176 | Some(k) if k < 0 => return Err(ApiError::bad_request("top_k must be >= 0")), |
| 1177 | Some(k) => k as usize, |
| 1178 | None => cfg.default_top_k, |
| 1179 | }; |
| 1180 | let seed = match req.seed { |
| 1181 | Some(s) if s < 0 => return Err(ApiError::bad_request("seed must be >= 0")), |
| 1182 | Some(s) => s as u64, |
| 1183 | None => (unix_now().1 as u64) ^ state.counter.load(Ordering::Relaxed).rotate_left(32), |
| 1184 | }; |
| 1185 | let stop_strings = match req.stop { |
| 1186 | None | Some(Value::Null) => Vec::new(), |
| 1187 | Some(Value::String(s)) => vec![s], |
| 1188 | Some(Value::Array(items)) => items |
| 1189 | .into_iter() |
| 1190 | .map(|v| match v { |
| 1191 | Value::String(s) => Ok(s), |
| 1192 | _ => Err(ApiError::bad_request( |
| 1193 | "stop must be a string or an array of strings", |
| 1194 | )), |
| 1195 | }) |
| 1196 | .collect::<Result<Vec<_>, _>>()?, |
| 1197 | Some(_) => { |
| 1198 | return Err(ApiError::bad_request( |
| 1199 | "stop must be a string or an array of strings", |
| 1200 | )) |
| 1201 | } |
| 1202 | }; |
| 1203 | if stop_strings.iter().any(String::is_empty) { |
| 1204 | return Err(ApiError::bad_request("stop strings must be non-empty")); |
| 1205 | } |
| 1206 | if stop_strings.len() > cfg.max_stop_strings { |
| 1207 | return Err(ApiError::bad_request(format!( |
| 1208 | "at most {} stop strings are accepted", |
| 1209 | cfg.max_stop_strings |
| 1210 | ))); |
| 1211 | } |
| 1212 | |
| 1213 | Ok(Prepared { |
| 1214 | prompt_tokens, |
| 1215 | params: GenerateParams { |
| 1216 | max_new_tokens, |
| 1217 | temperature, |
| 1218 | top_p, |
| 1219 | top_k, |
| 1220 | seed, |
| 1221 | stop_token_ids: state.codec.stop_token_ids(), |
| 1222 | }, |
| 1223 | stop_strings, |
| 1224 | stream: req.stream, |
| 1225 | reasoning_end: if prompt_text.ends_with("<think>\n") { |
| 1226 | state.codec.reasoning_end_id() |
| 1227 | } else { |
| 1228 | None |
| 1229 | }, |
| 1230 | return_ids: req.aien_return_token_ids, |
| 1231 | tools: !tool_defs.is_empty(), |
| 1232 | test: test_switches(state, req.aien_test.as_ref())?, |
| 1233 | }) |
| 1234 | } |
| 1235 | |
| 1236 | /// The merge train's `aien_test` field. A build without the `aien-test-switches` feature (the |
| 1237 | /// live server) refuses the field outright; a test build parses it and refuses any switch the |
| 1238 | /// engine does not honor, so no switch is ever ignored in silence and no verdict rests on one. |
| 1239 | fn test_switches(state: &AppState, v: Option<&Value>) -> Result<TestSwitches, ApiError> { |
| 1240 | let Some(v) = v.filter(|v| !v.is_null()) else { |
| 1241 | return Ok(TestSwitches::default()); |
| 1242 | }; |
| 1243 | #[cfg(not(feature = "aien-test-switches"))] |
| 1244 | { |
| 1245 | let _ = (state, v); |
| 1246 | Err(ApiError::bad_request( |
| 1247 | "aien_test: this server was built without the merge train's test switches (cargo feature aien-test-switches); it never serves a test case", |
| 1248 | )) |
| 1249 | } |
| 1250 | #[cfg(feature = "aien-test-switches")] |
| 1251 | { |
| 1252 | let t = TestSwitches::from_json(v).map_err(ApiError::bad_request)?; |
| 1253 | let honored = state.engine.test_switches_honored(); |
| 1254 | let unhonored: Vec<&str> = t |
| 1255 | .names() |
| 1256 | .into_iter() |
| 1257 | .filter(|n| !honored.contains(n)) |
| 1258 | .collect(); |
| 1259 | if !unhonored.is_empty() { |
| 1260 | return Err(ApiError::bad_request(format!( |
| 1261 | "aien_test: switches {unhonored:?} are not honored by this server's {} engine (it honors {honored:?}); a load-only switch needs its own server", |
| 1262 | state.engine.kind() |
| 1263 | ))); |
| 1264 | } |
| 1265 | Ok(t) |
| 1266 | } |
| 1267 | } |
| 1268 | |
| 1269 | /// The template switches of a request: `chat_template_kwargs.enable_thinking` / |
| 1270 | /// `.reasoning_effort` / `.preserve_thinking`, and the top-level `reasoning_effort`. |
| 1271 | fn chat_options(req: &ChatRequest) -> Result<ChatOptions, ApiError> { |
| 1272 | let mut o = ChatOptions::default(); |
| 1273 | if let Some(kw) = req.chat_template_kwargs.as_ref().filter(|v| !v.is_null()) { |
| 1274 | let Some(map) = kw.as_object() else { |
| 1275 | return Err(ApiError::bad_request( |
| 1276 | "chat_template_kwargs must be an object", |
| 1277 | )); |
| 1278 | }; |
| 1279 | if let Some(v) = map.get("enable_thinking").filter(|v| !v.is_null()) { |
| 1280 | o.enable_thinking = Some(v.as_bool().ok_or_else(|| { |
| 1281 | ApiError::bad_request("chat_template_kwargs.enable_thinking must be a boolean") |
| 1282 | })?); |
| 1283 | } |
| 1284 | if let Some(v) = map.get("preserve_thinking").filter(|v| !v.is_null()) { |
| 1285 | o.preserve_thinking = Some(v.as_bool().ok_or_else(|| { |
| 1286 | ApiError::bad_request("chat_template_kwargs.preserve_thinking must be a boolean") |
| 1287 | })?); |
| 1288 | } |
| 1289 | if let Some(v) = map.get("reasoning_effort").filter(|v| !v.is_null()) { |
| 1290 | o.reasoning_effort = Some( |
| 1291 | v.as_str() |
| 1292 | .ok_or_else(|| { |
| 1293 | ApiError::bad_request( |
| 1294 | "chat_template_kwargs.reasoning_effort must be a string", |
| 1295 | ) |
| 1296 | })? |
| 1297 | .to_string(), |
| 1298 | ); |
| 1299 | } |
| 1300 | } |
| 1301 | if let Some(e) = req.reasoning_effort.as_deref() { |
| 1302 | o.reasoning_effort = Some(e.to_string()); |
| 1303 | } |
| 1304 | Ok(o) |
| 1305 | } |
| 1306 | |
| 1307 | /// Runs on a blocking thread holding the generation lock (`guard`). The lock is released as soon |
| 1308 | /// as the engine returns, before the final event is sent, so a client that sends its next request |
| 1309 | /// the moment it has the reply never meets a stale 503 `server_busy`. |
| 1310 | fn run_generation( |
| 1311 | engine: Arc<dyn Engine>, |
| 1312 | codec: Arc<dyn Codec>, |
| 1313 | prepared: Prepared, |
| 1314 | tx: mpsc::Sender<Ev>, |
| 1315 | guard: OwnedSemaphorePermit, |
| 1316 | id: &str, |
| 1317 | ) { |
| 1318 | let mut asm = TextAssembler::new(Arc::clone(&codec), prepared.stop_strings); |
| 1319 | // The thinking block (prompt ends in `<think>\n`): its text goes out as reasoning, the |
| 1320 | // closing token is dropped, and the answer's leading newlines are trimmed (the template |
| 1321 | // puts `\n</think>\n\n` between the two). |
| 1322 | let mut thinking = prepared |
| 1323 | .reasoning_end |
| 1324 | .map(|end| (end, TextAssembler::new(codec, Vec::new()))); |
| 1325 | let mut answer_started = prepared.reasoning_end.is_none(); |
| 1326 | let mut ids = prepared.return_ids.then(Vec::new); |
| 1327 | let mut stopped_by_string = false; |
| 1328 | let mut client_gone = false; |
| 1329 | let test_report = (!prepared.test.is_empty()).then(|| prepared.test.names()); |
| 1330 | let result = engine.generate_with_test( |
| 1331 | &prepared.prompt_tokens, |
| 1332 | &prepared.params, |
| 1333 | &prepared.test, |
| 1334 | &mut |tok| { |
| 1335 | if let Some(ids) = ids.as_mut() { |
| 1336 | ids.push(tok); |
| 1337 | } |
| 1338 | if let Some((end, rasm)) = thinking.as_mut() { |
| 1339 | let ev = if tok == *end { |
| 1340 | let rest = rasm.finish(); |
| 1341 | thinking = None; |
| 1342 | rest |
| 1343 | } else { |
| 1344 | match rasm.push(tok) { |
| 1345 | Push::Delta(d) | Push::StopAt(d) => Some(d), |
| 1346 | Push::Hold => None, |
| 1347 | } |
| 1348 | }; |
| 1349 | if let Some(d) = ev.filter(|d| !d.is_empty()) { |
| 1350 | if tx.blocking_send(Ev::Reasoning(d)).is_err() { |
| 1351 | client_gone = true; |
| 1352 | return false; |
| 1353 | } |
| 1354 | } |
| 1355 | return true; |
| 1356 | } |
| 1357 | let trim = |d: String, started: &mut bool| { |
| 1358 | if *started { |
| 1359 | return d; |
| 1360 | } |
| 1361 | let t = d.trim_start_matches('\n'); |
| 1362 | *started = !t.is_empty(); |
| 1363 | t.to_string() |
| 1364 | }; |
| 1365 | match asm.push(tok) { |
| 1366 | Push::Hold => true, |
| 1367 | Push::Delta(d) => { |
| 1368 | let d = trim(d, &mut answer_started); |
| 1369 | if d.is_empty() { |
| 1370 | return true; |
| 1371 | } |
| 1372 | if tx.blocking_send(Ev::Delta(d)).is_err() { |
| 1373 | client_gone = true; |
| 1374 | false |
| 1375 | } else { |
| 1376 | true |
| 1377 | } |
| 1378 | } |
| 1379 | Push::StopAt(d) => { |
| 1380 | stopped_by_string = true; |
| 1381 | let d = trim(d, &mut answer_started); |
| 1382 | if !d.is_empty() { |
| 1383 | let _ = tx.blocking_send(Ev::Delta(d)); |
| 1384 | } |
| 1385 | false |
| 1386 | } |
| 1387 | } |
| 1388 | }, |
| 1389 | ); |
| 1390 | drop(guard); |
| 1391 | match result { |
| 1392 | Err(EngineError::Busy(m)) => { |
| 1393 | eprintln!("aien-serve-http: {id}: GPU busy: {m}"); |
| 1394 | let _ = tx.blocking_send(Ev::Busy(m)); |
| 1395 | } |
| 1396 | Err(EngineError::MemoryExceeded(m)) => { |
| 1397 | eprintln!("aien-serve-http: {id}: memory admission refused: {m}"); |
| 1398 | let _ = tx.blocking_send(Ev::MemoryExceeded(m)); |
| 1399 | } |
| 1400 | Err(e) => { |
| 1401 | eprintln!("aien-serve-http: {id}: {e}"); |
| 1402 | let _ = tx.blocking_send(Ev::Error(e.to_string())); |
| 1403 | } |
| 1404 | Ok(out) => { |
| 1405 | if client_gone { |
| 1406 | eprintln!( |
| 1407 | "aien-serve-http: {id}: client left after {} tokens", |
| 1408 | out.emitted_tokens |
| 1409 | ); |
| 1410 | return; |
| 1411 | } |
| 1412 | if let Some((_, mut rasm)) = thinking.take() { |
| 1413 | if let Some(rest) = rasm.finish().filter(|r| !r.is_empty()) { |
| 1414 | let _ = tx.blocking_send(Ev::Reasoning(rest)); |
| 1415 | } |
| 1416 | } |
| 1417 | if let Some(rest) = asm.finish() { |
| 1418 | let rest = if answer_started { |
| 1419 | rest |
| 1420 | } else { |
| 1421 | rest.trim_start_matches('\n').to_string() |
| 1422 | }; |
| 1423 | if !rest.is_empty() { |
| 1424 | let _ = tx.blocking_send(Ev::Delta(rest)); |
| 1425 | } |
| 1426 | } |
| 1427 | let finish = if stopped_by_string { |
| 1428 | "stop" |
| 1429 | } else { |
| 1430 | match out.finish { |
| 1431 | FinishReason::Stop | FinishReason::Cancelled => "stop", |
| 1432 | FinishReason::Length => "length", |
| 1433 | } |
| 1434 | }; |
| 1435 | let tps = if out.decode_ms > 0 { |
| 1436 | out.emitted_tokens as f64 * 1000.0 / out.decode_ms as f64 |
| 1437 | } else { |
| 1438 | 0.0 |
| 1439 | }; |
| 1440 | let sampling_fields = out |
| 1441 | .sampling |
| 1442 | .as_ref() |
| 1443 | .map(|s| format!(", {}", s.log_fields())) |
| 1444 | .unwrap_or_default(); |
| 1445 | eprintln!( |
| 1446 | "aien-serve-http: {id}: prompt {} tok, reply {} tok, finish {finish}, prefill {} ms, decode {} ms ({tps:.2} tok/s){sampling_fields}", |
| 1447 | prepared.prompt_tokens.len(), |
| 1448 | out.emitted_tokens, |
| 1449 | out.prefill_ms, |
| 1450 | out.decode_ms |
| 1451 | ); |
| 1452 | let _ = tx.blocking_send(Ev::Done { |
| 1453 | finish, |
| 1454 | completion_tokens: out.emitted_tokens, |
| 1455 | sampling: out.sampling, |
| 1456 | token_ids: ids, |
| 1457 | test: test_report, |
| 1458 | }); |
| 1459 | } |
| 1460 | } |
| 1461 | } |
| 1462 | |
| 1463 | async fn collect_response( |
| 1464 | id: String, |
| 1465 | created: u64, |
| 1466 | model: &str, |
| 1467 | mut prompt_tokens: usize, |
| 1468 | mut rx: mpsc::Receiver<Ev>, |
| 1469 | tools: bool, |
| 1470 | ) -> Result<Response, ApiError> { |
| 1471 | let mut content = String::new(); |
| 1472 | let mut reasoning: Option<String> = None; |
| 1473 | let mut readers: Option<Value> = None; |
| 1474 | while let Some(ev) = rx.recv().await { |
| 1475 | match ev { |
| 1476 | Ev::Delta(d) => content.push_str(&d), |
| 1477 | Ev::Reading => {} |
| 1478 | Ev::Readers { |
| 1479 | info, |
| 1480 | prompt_tokens: p, |
| 1481 | } => { |
| 1482 | readers = Some(info); |
| 1483 | prompt_tokens = p; |
| 1484 | } |
| 1485 | Ev::Reasoning(d) => reasoning.get_or_insert_with(String::new).push_str(&d), |
| 1486 | Ev::Done { |
| 1487 | finish, |
| 1488 | completion_tokens, |
| 1489 | sampling, |
| 1490 | token_ids, |
| 1491 | test, |
| 1492 | } => { |
| 1493 | let usage = Usage { |
| 1494 | prompt_tokens, |
| 1495 | completion_tokens, |
| 1496 | total_tokens: prompt_tokens + completion_tokens, |
| 1497 | aien_sampling: sampling, |
| 1498 | aien_token_ids: token_ids, |
| 1499 | aien_test: test.map(|n| serde_json::json!({ "applied": n })), |
| 1500 | }; |
| 1501 | let reasoning = reasoning.as_deref().map(str::trim); |
| 1502 | let (text, calls) = if tools { |
| 1503 | crate::tools::parse_reply(&content, &id) |
| 1504 | } else { |
| 1505 | (content.clone(), Vec::new()) |
| 1506 | }; |
| 1507 | let mut body = |
| 1508 | completion_json(&id, created, model, &text, reasoning, finish, &usage); |
| 1509 | if !calls.is_empty() { |
| 1510 | let msg = &mut body["choices"][0]["message"]; |
| 1511 | msg["tool_calls"] = Value::Array(calls); |
| 1512 | if text.trim().is_empty() { |
| 1513 | msg["content"] = Value::Null; |
| 1514 | } |
| 1515 | body["choices"][0]["finish_reason"] = Value::String("tool_calls".into()); |
| 1516 | } |
| 1517 | if let Some(info) = readers { |
| 1518 | body["aien_readers"] = info; |
| 1519 | } |
| 1520 | return Ok(Json(body).into_response()); |
| 1521 | } |
| 1522 | Ev::Error(m) => return Err(ApiError::internal(m)), |
| 1523 | // Not the first event on the readers' path (`Ev::Readers` goes before the connect |
| 1524 | // generation); nothing has been sent yet, so it is the same 503 as a busy first event. |
| 1525 | Ev::Busy(m) => return Err(ApiError::gpu_busy(&m)), |
| 1526 | Ev::MemoryExceeded(m) => return Err(ApiError::memory_exceeded(m)), |
| 1527 | } |
| 1528 | } |
| 1529 | Err(ApiError::internal("generation ended without a result")) |
| 1530 | } |
| 1531 | |
| 1532 | fn stream_response( |
| 1533 | id: String, |
| 1534 | created: u64, |
| 1535 | model: String, |
| 1536 | mut prompt_tokens: usize, |
| 1537 | mut rx: mpsc::Receiver<Ev>, |
| 1538 | tools: bool, |
| 1539 | ) -> Response { |
| 1540 | let (etx, erx) = mpsc::channel::<Result<Event, Infallible>>(64); |
| 1541 | tokio::spawn(async move { |
| 1542 | // Tool requests: content streams until a `<tool_call>` opens (a possible split tag is held |
| 1543 | // back); from there the reply is buffered and sent as one `tool_calls` delta at the end. |
| 1544 | let mut held = String::new(); |
| 1545 | let mut in_call = false; |
| 1546 | let data = |v: Value| Ok(Event::default().data(v.to_string())); |
| 1547 | let first = chunk_json( |
| 1548 | &id, |
| 1549 | created, |
| 1550 | &model, |
| 1551 | Some("assistant"), |
| 1552 | Some(""), |
| 1553 | None, |
| 1554 | None, |
| 1555 | ); |
| 1556 | if etx.send(data(first)).await.is_err() { |
| 1557 | return; |
| 1558 | } |
| 1559 | while let Some(ev) = rx.recv().await { |
| 1560 | let item = match ev { |
| 1561 | Ev::Reading => continue, |
| 1562 | Ev::Readers { |
| 1563 | info, |
| 1564 | prompt_tokens: p, |
| 1565 | } => { |
| 1566 | prompt_tokens = p; |
| 1567 | let mut v = chunk_json(&id, created, &model, None, None, None, None); |
| 1568 | v["aien_readers"] = info; |
| 1569 | data(v) |
| 1570 | } |
| 1571 | Ev::Delta(d) if tools => { |
| 1572 | held.push_str(&d); |
| 1573 | if in_call { |
| 1574 | continue; |
| 1575 | } |
| 1576 | let out = if let Some(p) = held.find(crate::tools::OPEN) { |
| 1577 | in_call = true; |
| 1578 | let out = held[..p].to_string(); |
| 1579 | held = held[p..].to_string(); |
| 1580 | out |
| 1581 | } else { |
| 1582 | let keep = crate::tools::partial_open_len(&held); |
| 1583 | let cut = held.len() - keep; |
| 1584 | let out = held[..cut].to_string(); |
| 1585 | held = held[cut..].to_string(); |
| 1586 | out |
| 1587 | }; |
| 1588 | if out.is_empty() { |
| 1589 | continue; |
| 1590 | } |
| 1591 | data(chunk_json( |
| 1592 | &id, |
| 1593 | created, |
| 1594 | &model, |
| 1595 | None, |
| 1596 | Some(&out), |
| 1597 | None, |
| 1598 | None, |
| 1599 | )) |
| 1600 | } |
| 1601 | Ev::Delta(d) => data(chunk_json(&id, created, &model, None, Some(&d), None, None)), |
| 1602 | Ev::Reasoning(d) => data(chunk_json_with( |
| 1603 | &id, |
| 1604 | created, |
| 1605 | &model, |
| 1606 | None, |
| 1607 | None, |
| 1608 | Some(&d), |
| 1609 | None, |
| 1610 | None, |
| 1611 | )), |
| 1612 | Ev::Done { |
| 1613 | finish, |
| 1614 | completion_tokens, |
| 1615 | sampling, |
| 1616 | token_ids, |
| 1617 | test, |
| 1618 | } => { |
| 1619 | let usage = Usage { |
| 1620 | prompt_tokens, |
| 1621 | completion_tokens, |
| 1622 | total_tokens: prompt_tokens + completion_tokens, |
| 1623 | aien_sampling: sampling, |
| 1624 | aien_token_ids: token_ids, |
| 1625 | aien_test: test.map(|n| serde_json::json!({ "applied": n })), |
| 1626 | }; |
| 1627 | let mut finish = finish; |
| 1628 | if tools && !held.is_empty() { |
| 1629 | let (text, calls) = crate::tools::parse_reply(&held, &id); |
| 1630 | if !text.is_empty() |
| 1631 | && etx |
| 1632 | .send(data(chunk_json( |
| 1633 | &id, |
| 1634 | created, |
| 1635 | &model, |
| 1636 | None, |
| 1637 | Some(&text), |
| 1638 | None, |
| 1639 | None, |
| 1640 | ))) |
| 1641 | .await |
| 1642 | .is_err() |
| 1643 | { |
| 1644 | return; |
| 1645 | } |
| 1646 | if !calls.is_empty() { |
| 1647 | let deltas: Vec<Value> = calls |
| 1648 | .into_iter() |
| 1649 | .enumerate() |
| 1650 | .map(|(i, mut c)| { |
| 1651 | c["index"] = Value::from(i); |
| 1652 | c |
| 1653 | }) |
| 1654 | .collect(); |
| 1655 | let mut ch = chunk_json(&id, created, &model, None, None, None, None); |
| 1656 | ch["choices"][0]["delta"]["tool_calls"] = Value::Array(deltas); |
| 1657 | if etx.send(data(ch)).await.is_err() { |
| 1658 | return; |
| 1659 | } |
| 1660 | finish = "tool_calls"; |
| 1661 | } |
| 1662 | } |
| 1663 | let last = |
| 1664 | chunk_json(&id, created, &model, None, None, Some(finish), Some(&usage)); |
| 1665 | if etx.send(data(last)).await.is_err() { |
| 1666 | return; |
| 1667 | } |
| 1668 | let _ = etx.send(Ok(Event::default().data("[DONE]"))).await; |
| 1669 | return; |
| 1670 | } |
| 1671 | Ev::Error(m) | Ev::Busy(m) => { |
| 1672 | let err = serde_json::to_value(ErrorBody::new("server_error", m)) |
| 1673 | .expect("error serializes"); |
| 1674 | if etx.send(data(err)).await.is_err() { |
| 1675 | return; |
| 1676 | } |
| 1677 | let _ = etx.send(Ok(Event::default().data("[DONE]"))).await; |
| 1678 | return; |
| 1679 | } |
| 1680 | Ev::MemoryExceeded(m) => { |
| 1681 | let mut body = ErrorBody::new("invalid_request_error", m); |
| 1682 | body.error.code = Some("prompt_exceeds_memory_budget".into()); |
| 1683 | let err = serde_json::to_value(body).expect("error serializes"); |
| 1684 | if etx.send(data(err)).await.is_err() { |
| 1685 | return; |
| 1686 | } |
| 1687 | let _ = etx.send(Ok(Event::default().data("[DONE]"))).await; |
| 1688 | return; |
| 1689 | } |
| 1690 | }; |
| 1691 | if etx.send(item).await.is_err() { |
| 1692 | return; |
| 1693 | } |
| 1694 | } |
| 1695 | }); |
| 1696 | Sse::new(ReceiverStream::new(erx)) |
| 1697 | .keep_alive( |
| 1698 | KeepAlive::new() |
| 1699 | .interval(Duration::from_secs(15)) |
| 1700 | .text("keep-alive"), |
| 1701 | ) |
| 1702 | .into_response() |
| 1703 | } |
| 1704 | |
| 1705 | #[cfg(test)] |
| 1706 | mod tests { |
| 1707 | use super::*; |
| 1708 | |
| 1709 | async fn answer(events: Vec<Ev>, stream: bool) -> Response { |
| 1710 | let (tx, rx) = mpsc::channel(events.len().max(1)); |
| 1711 | for ev in events { |
| 1712 | tx.send(ev).await.expect("room for every event"); |
| 1713 | } |
| 1714 | drop(tx); |
| 1715 | respond(rx, stream, "id".into(), 0, "m".into(), 3, false) |
| 1716 | .await |
| 1717 | .unwrap_or_else(IntoResponse::into_response) |
| 1718 | } |
| 1719 | |
| 1720 | fn assert_chip_busy(resp: &Response) { |
| 1721 | assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE); |
| 1722 | assert_eq!( |
| 1723 | resp.headers() |
| 1724 | .get(header::RETRY_AFTER) |
| 1725 | .map(|v| v.as_bytes()), |
| 1726 | Some(&b"5"[..]) |
| 1727 | ); |
| 1728 | } |
| 1729 | |
| 1730 | /// A busy chip before anything else is a 503 with Retry-After 5. |
| 1731 | #[tokio::test] |
| 1732 | async fn busy_first_is_a_503_with_retry_after() { |
| 1733 | assert_chip_busy(&answer(vec![Ev::Busy("held".into())], false).await); |
| 1734 | } |
| 1735 | |
| 1736 | /// The readers' non-streaming path sends `Ev::Readers` before the connect generation, so a busy |
| 1737 | /// chip for that generation is not the first event: it must still be the same 503 with |
| 1738 | /// Retry-After 5, not a 500. |
| 1739 | #[tokio::test] |
| 1740 | async fn busy_after_the_readers_event_is_the_same_503() { |
| 1741 | let events = vec![ |
| 1742 | Ev::Readers { |
| 1743 | info: serde_json::json!({ "readers": 2 }), |
| 1744 | prompt_tokens: 7, |
| 1745 | }, |
| 1746 | Ev::Busy("GPU lock held by other jobs for 300 s".into()), |
| 1747 | ]; |
| 1748 | assert_chip_busy(&answer(events, false).await); |
| 1749 | } |
| 1750 | } |