crates/edge/api/src/openai.rs 31.7 KiB 1005 lines Raw
1 //! The OpenAI adapters.2 //!3 //! An OpenAI client sends its own fields and expects its own objects. The core4 //! takes parts and sends one event. This module is the only place that both5 //! vocabularies meet, and it is pure: no socket, no clock, no thread. The web6 //! supplies the identifiers and the time, and writes the bytes.7 8 use std::collections::BTreeMap;9 use std::fmt;10 11 use inf3r_json::{Object, Value};12 13 /// The object name of one streamed chunk.14 const CHUNK_OBJECT: &str = "chat.completion.chunk";15 16 /// The object name of one whole reply.17 const COMPLETION_OBJECT: &str = "chat.completion";18 19 /// A one-choice reply has this index. OpenAI reads it, so it is not optional.20 const CHOICE_INDEX: i64 = 0;21 22 /// The most images that one generation request may ask for. Above this the23 /// adapter refuses; four jobs at a time are already a lot for one request.24 pub const MAX_IMAGES: u32 = 4;25 26 /// The parts of a chat request that inf3r uses. A standard OpenAI field that27 /// the chat capability does not name is ignored, not refused (spec R26).28 #[derive(Clone, PartialEq, Debug)]29 pub struct ChatRequest {30     /// The served name. The core resolves it against the catalogue.31     pub model: String,32     /// The turns, in the order the client sent them.33     pub messages: Vec<Message>,34     /// Whether the client wants SSE chunks or one body.35     pub stream: bool,36     /// The output limit, when the client gave one. `max_completion_tokens` wins37     /// over `max_tokens`, because that is the field that current clients send.38     pub max_tokens: Option<u32>,39     /// The sampling temperature, when the client gave one.40     pub temperature: Option<f32>,41     /// The nucleus probability, when the client gave one.42     pub top_p: Option<f32>,43     /// The stop sequences, when the client gave any.44     pub stop: Vec<String>,45     /// A fixed seed for a repeatable job, when the client gave one.46     pub seed: Option<u64>,47     /// An optional opaque namespace for the cache prefix.48     pub prompt_cache_key: Option<String>,49     /// The `tools` array, which becomes a `json` part with role `tools`.50     pub tools: Option<Value>,51     /// The `response_format` object, which becomes a `json` part.52     pub response_format: Option<Value>,53     /// Standard sampling parameters that the capability names but that this54     /// struct does not model one by one.55     pub params: Vec<(String, Value)>,56     /// Whether a stream must carry a final `usage` chunk.57     pub include_usage: bool,58 }59 60 /// One turn of a chat request.61 #[derive(Clone, PartialEq, Debug)]62 pub struct Message {63     /// Who spoke.64     pub role: Role,65     /// The text and images of this turn.66     pub parts: Vec<Part>,67 }68 69 /// The speaker of a turn.70 #[derive(Clone, Copy, PartialEq, Eq, Debug)]71 pub enum Role {72     /// The system instruction. OpenAI's newer `developer` role maps here.73     System,74     /// A user turn.75     User,76     /// A previous assistant turn.77     Assistant,78     /// A tool result.79     Tool,80 }81 82 /// One content part of a message.83 #[derive(Clone, PartialEq, Debug)]84 pub struct Part {85     /// What the part carries.86     pub kind: Kind,87     /// The text, for a text part.88     pub text: Option<String>,89     /// The media type, for an image part.90     pub mime: Option<String>,91     /// The decoded image bytes. A remote URL is refused.92     pub bytes: Option<Vec<u8>>,93 }94 95 /// The kinds of content part that the adapter carries.96 #[derive(Clone, Copy, PartialEq, Eq, Debug)]97 pub enum Kind {98     /// A UTF-8 fragment.99     Text,100     /// Image bytes.101     Image,102 }103 104 /// A request for `POST /openai/v1/embeddings`.105 #[derive(Clone, PartialEq, Debug)]106 pub struct EmbeddingRequest {107     /// The served name.108     pub model: String,109     /// The text to embed, in input order.110     pub input: Vec<String>,111     /// The wanted vector length, when the client gave one.112     pub dimensions: Option<u32>,113     /// Whether the reply carries base64 floats instead of a JSON array.114     pub base64: bool,115 }116 117 /// A request for `POST /openai/v1/audio/speech`.118 #[derive(Clone, PartialEq, Debug)]119 pub struct SpeechRequest {120     /// The served name.121     pub model: String,122     /// The text to speak.123     pub input: String,124     /// The voice, when the client chose one.125     pub voice: Option<String>,126     /// The response format, when the client chose one.127     pub response_format: Option<String>,128     /// The speaking rate, when the client gave one.129     pub speed: Option<f32>,130 }131 132 /// A request for `POST /openai/v1/images/generations`.133 #[derive(Clone, PartialEq, Debug)]134 pub struct ImageRequest {135     /// The served name.136     pub model: String,137     /// The prompt.138     pub prompt: String,139     /// How many images to make.140     pub n: u32,141     /// The size, when the client gave one.142     pub size: Option<String>,143     /// The quality, when the client gave one.144     pub quality: Option<String>,145     /// The style, when the client gave one.146     pub style: Option<String>,147 }148 149 /// The reason a request cannot become neutral fields.150 #[derive(Clone, PartialEq, Eq, Debug)]151 pub struct AdapterError {152     /// The class of refusal.153     pub kind: AdapterErrorKind,154     /// One sentence for the client.155     pub message: String,156 }157 158 /// The class of an adapter refusal.159 #[derive(Clone, PartialEq, Eq, Debug)]160 pub enum AdapterErrorKind {161     /// The body is not a JSON object.162     NotObject,163     /// The request has no model name.164     MissingModel,165     /// A message is not an object with a role and content.166     BadMessage,167     /// A content part, or the base64 in a data URL, is malformed.168     BadContent,169     /// The role is not one of the OpenAI chat roles.170     BadRole,171     /// The image URL is not a data URL. The core does not fetch.172     RemoteUrl,173     /// A field is valid OpenAI but has no neutral equivalent here.174     Unsupported(&'static str),175 }176 177 impl fmt::Display for AdapterError {178     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {179         f.write_str(&self.message)180     }181 }182 183 impl std::error::Error for AdapterError {}184 185 fn error(kind: AdapterErrorKind, message: impl Into<String>) -> AdapterError {186     AdapterError {187         kind,188         message: message.into(),189     }190 }191 192 fn unsupported(field: &'static str) -> AdapterError {193     error(194         AdapterErrorKind::Unsupported(field),195         format!("{field} is not supported by this adapter"),196     )197 }198 199 fn optional_u32(field: &str, value: &Value) -> Result<Option<u32>, AdapterError> {200     if matches!(value, Value::Null) {201         return Ok(None);202     }203     let number = value.as_u64().ok_or_else(|| {204         error(205             AdapterErrorKind::BadMessage,206             format!("{field} must be a non-negative integer"),207         )208     })?;209     let number = u32::try_from(number).map_err(|_| {210         error(211             AdapterErrorKind::BadMessage,212             format!("{field} is above the 32-bit limit"),213         )214     })?;215     Ok(Some(number))216 }217 218 fn optional_f32(field: &str, value: &Value) -> Result<Option<f32>, AdapterError> {219     if matches!(value, Value::Null) {220         return Ok(None);221     }222     let number = value.as_f64().ok_or_else(|| {223         error(224             AdapterErrorKind::BadMessage,225             format!("{field} must be a number"),226         )227     })?;228     Ok(Some(number as f32))229 }230 231 fn optional_u64(field: &str, value: &Value) -> Result<Option<u64>, AdapterError> {232     if matches!(value, Value::Null) {233         return Ok(None);234     }235     value.as_u64().map(Some).ok_or_else(|| {236         error(237             AdapterErrorKind::BadMessage,238             format!("{field} must be a non-negative integer"),239         )240     })241 }242 243 fn optional_string(field: &str, value: &Value) -> Result<Option<String>, AdapterError> {244     if matches!(value, Value::Null) {245         return Ok(None);246     }247     value248         .as_str()249         .map(|text| Some(text.to_string()))250         .ok_or_else(|| {251             error(252                 AdapterErrorKind::BadMessage,253                 format!("{field} must be a string"),254             )255         })256 }257 258 fn parse_stop(value: &Value) -> Result<Vec<String>, AdapterError> {259     match value {260         Value::Null => Ok(Vec::new()),261         Value::Str(stop) => Ok(vec![stop.clone()]),262         Value::Array(items) => items263             .iter()264             .map(|item| {265                 item.as_str().map(str::to_string).ok_or_else(|| {266                     error(267                         AdapterErrorKind::BadMessage,268                         "stop must be a string or an array of strings",269                     )270                 })271             })272             .collect(),273         _ => Err(error(274             AdapterErrorKind::BadMessage,275             "stop must be a string or an array of strings",276         )),277     }278 }279 280 fn parse_role(value: &Value) -> Result<Role, AdapterError> {281     match value.as_str() {282         Some("system") | Some("developer") => Ok(Role::System),283         Some("user") => Ok(Role::User),284         Some("assistant") => Ok(Role::Assistant),285         Some("tool") => Ok(Role::Tool),286         Some(role) => Err(error(287             AdapterErrorKind::BadRole,288             format!("role {role} is not system, developer, user, assistant, or tool"),289         )),290         None => Err(error(291             AdapterErrorKind::BadRole,292             "the message role is not a string",293         )),294     }295 }296 297 /// Splits a data URL into its MIME type and its decoded bytes.298 ///299 /// The bytes are decoded once here. The app checks the inline limit against300 /// them and never decodes the same URL again.301 fn parse_image_url(url: &str) -> Result<(String, Vec<u8>), AdapterError> {302     let Some(rest) = url.strip_prefix("data:") else {303         return Err(error(304             AdapterErrorKind::RemoteUrl,305             "the image URL is not a data URL; the core does not fetch",306         ));307     };308     let Some((meta, payload)) = rest.split_once(',') else {309         return Err(error(310             AdapterErrorKind::BadContent,311             "the data URL has no comma before its payload",312         ));313     };314     let mime = meta.split(';').next().unwrap_or(meta);315     let bytes = inf3r_json::b64::decode(payload).ok_or_else(|| {316         error(317             AdapterErrorKind::BadContent,318             "the data URL payload is not base64",319         )320     })?;321     Ok((mime.to_string(), bytes))322 }323 324 fn image_url(part: &Value) -> Option<&str> {325     match part.get("image_url") {326         Some(Value::Str(url)) => Some(url),327         Some(value) => value.get("url").and_then(Value::as_str),328         None => None,329     }330 }331 332 fn parse_part(value: &Value) -> Result<Part, AdapterError> {333     let part = value.as_object().ok_or_else(|| {334         error(335             AdapterErrorKind::BadContent,336             "a content part is not an object",337         )338     })?;339     let kind = part340         .get("type")341         .and_then(Value::as_str)342         .ok_or_else(|| error(AdapterErrorKind::BadContent, "a content part has no type"))?;343     match kind {344         "text" | "input_text" => {345             let text = part346                 .get("text")347                 .and_then(Value::as_str)348                 .ok_or_else(|| error(AdapterErrorKind::BadContent, "a text part has no text"))?;349             Ok(Part {350                 kind: Kind::Text,351                 text: Some(text.to_string()),352                 mime: None,353                 bytes: None,354             })355         }356         "image_url" | "input_image" => {357             let url = image_url(value).ok_or_else(|| {358                 error(359                     AdapterErrorKind::BadContent,360                     "an image part has no image_url",361                 )362             })?;363             let (mime, bytes) = parse_image_url(url)?;364             Ok(Part {365                 kind: Kind::Image,366                 text: None,367                 mime: Some(mime),368                 bytes: Some(bytes),369             })370         }371         other => Err(error(372             AdapterErrorKind::BadContent,373             format!("content part type {other} is not text or image_url"),374         )),375     }376 }377 378 fn text_part(text: &str) -> Part {379     Part {380         kind: Kind::Text,381         text: Some(text.to_string()),382         mime: None,383         bytes: None,384     }385 }386 387 fn parse_content(value: &Value) -> Result<Vec<Part>, AdapterError> {388     match value {389         Value::Null => Ok(Vec::new()),390         Value::Str(text) => Ok(vec![text_part(text)]),391         Value::Array(items) => items.iter().map(parse_part).collect(),392         _ => Err(error(393             AdapterErrorKind::BadContent,394             "message content is not a string or an array",395         )),396     }397 }398 399 fn parse_message(value: &Value) -> Result<Message, AdapterError> {400     let message = value401         .as_object()402         .ok_or_else(|| error(AdapterErrorKind::BadMessage, "a message is not an object"))?;403     let role = message404         .get("role")405         .ok_or_else(|| error(AdapterErrorKind::BadMessage, "a message has no role"))?;406     let role = parse_role(role)?;407     let mut parts = match message.get("content") {408         Some(content) => parse_content(content)?,409         None => Vec::new(),410     };411     // An assistant turn that only calls a tool has null content. The older412     // tool-call shape is still text to the plugin, so it rides as text rather413     // than disappearing from the conversation.414     if parts.is_empty()415         && let Some(calls) = message.get("tool_calls")416     {417         parts.push(text_part(&inf3r_json::to_string(calls)));418     }419     Ok(Message { role, parts })420 }421 422 fn parse_messages(value: &Value) -> Result<Vec<Message>, AdapterError> {423     let items = value424         .as_array()425         .ok_or_else(|| error(AdapterErrorKind::BadMessage, "messages is not an array"))?;426     items.iter().map(parse_message).collect()427 }428 429 /// Parses a chat request.430 ///431 /// A standard field that the capability names is carried into a part or a432 /// parameter. A field outside the object is ignored: a client that sends a433 /// newer OpenAI field must not lose the whole request (spec R26).434 pub fn parse_chat(body: &Value) -> Result<ChatRequest, AdapterError> {435     let map = body.as_object().ok_or_else(|| {436         error(437             AdapterErrorKind::NotObject,438             "the chat request is not an object",439         )440     })?;441 442     let mut model = None;443     let mut messages = None;444     let mut stream = false;445     let mut max_tokens = None;446     let mut max_completion_tokens = None;447     let mut temperature = None;448     let mut top_p = None;449     let mut stop = Vec::new();450     let mut seed = None;451     let mut tools = None;452     let mut prompt_cache_key = None;453     let mut functions = None;454     let mut response_format = None;455     let mut include_usage = false;456     let mut params = Vec::new();457 458     for (key, value) in map {459         match key.as_str() {460             "model" => {461                 let name = value.as_str().ok_or_else(|| {462                     error(AdapterErrorKind::MissingModel, "the model is not a string")463                 })?;464                 model = Some(name.to_string());465             }466             "messages" => messages = Some(parse_messages(value)?),467             "stream" => {468                 stream = value.as_bool().ok_or_else(|| {469                     error(AdapterErrorKind::BadMessage, "stream must be true or false")470                 })?;471             }472             "max_tokens" => max_tokens = optional_u32("max_tokens", value)?,473             "max_completion_tokens" => {474                 max_completion_tokens = optional_u32("max_completion_tokens", value)?475             }476             "temperature" => temperature = optional_f32("temperature", value)?,477             "top_p" => top_p = optional_f32("top_p", value)?,478             "stop" => stop = parse_stop(value)?,479             "seed" => seed = optional_u64("seed", value)?,480             "prompt_cache_key" => {481                 prompt_cache_key = Some(482                     value483                         .as_str()484                         .ok_or_else(|| {485                             error(486                                 AdapterErrorKind::BadMessage,487                                 "prompt_cache_key must be a string",488                             )489                         })?490                         .to_string(),491                 );492             }493             "tools" => {494                 if !matches!(value, Value::Array(_)) {495                     return Err(error(496                         AdapterErrorKind::BadMessage,497                         "tools must be an array",498                     ));499                 }500                 tools = Some(value.clone());501             }502             "functions" => {503                 if !matches!(value, Value::Array(_)) {504                     return Err(error(505                         AdapterErrorKind::BadMessage,506                         "functions must be an array",507                     ));508                 }509                 functions = Some(value.clone());510             }511             "response_format" => {512                 if !matches!(value, Value::Object(_)) {513                     return Err(error(514                         AdapterErrorKind::BadMessage,515                         "response_format must be an object",516                     ));517                 }518                 response_format = Some(value.clone());519             }520             "stream_options" => {521                 let options = value.as_object().ok_or_else(|| {522                     error(523                         AdapterErrorKind::BadMessage,524                         "stream_options must be an object",525                     )526                 })?;527                 if let Some(value) = options.get("include_usage") {528                     include_usage = value.as_bool().ok_or_else(|| {529                         error(530                             AdapterErrorKind::BadMessage,531                             "stream_options.include_usage must be true or false",532                         )533                     })?;534                 }535             }536             // One choice is the only shape this adapter can make. A request537             // for more is valid OpenAI, so it is `Unsupported`.538             "n" => {539                 if value.as_u64() != Some(1) {540                     return Err(unsupported("n"));541                 }542             }543             // The capability names these, so they ride in `params` as given.544             "tool_choice"545             | "logprobs"546             | "top_logprobs"547             | "presence_penalty"548             | "frequency_penalty"549             | "logit_bias"550             | "parallel_tool_calls" => {551                 params.push((key.clone(), value.clone()));552             }553             // A client field with no neutral meaning. It is not an error.554             _ => {}555         }556     }557 558     let model = model.ok_or_else(|| {559         error(560             AdapterErrorKind::MissingModel,561             "the chat request has no model",562         )563     })?;564     let messages = messages.ok_or_else(|| {565         error(566             AdapterErrorKind::BadMessage,567             "the chat request has no messages",568         )569     })?;570     if tools.is_none()571         && let Some(functions) = functions572     {573         tools = Some(functions);574     }575 576     Ok(ChatRequest {577         model,578         messages,579         stream,580         max_tokens: max_completion_tokens.or(max_tokens),581         temperature,582         top_p,583         stop,584         seed,585         tools,586         prompt_cache_key,587         response_format,588         params,589         include_usage,590     })591 }592 593 /// Parses an embeddings request.594 pub fn parse_embeddings(body: &Value) -> Result<EmbeddingRequest, AdapterError> {595     let map = body.as_object().ok_or_else(|| {596         error(597             AdapterErrorKind::NotObject,598             "the embeddings request is not an object",599         )600     })?;601     let model = map602         .get("model")603         .and_then(Value::as_str)604         .ok_or_else(|| error(AdapterErrorKind::MissingModel, "the request has no model"))?605         .to_string();606     let input = map607         .get("input")608         .ok_or_else(|| error(AdapterErrorKind::BadMessage, "the request has no input"))?;609     let input = match input {610         Value::Str(text) => vec![text.clone()],611         Value::Array(items) => items612             .iter()613             .map(|item| {614                 item.as_str().map(str::to_string).ok_or_else(|| {615                     error(616                         AdapterErrorKind::Unsupported("token arrays"),617                         "input must be a string or an array of strings",618                     )619                 })620             })621             .collect::<Result<Vec<_>, _>>()?,622         _ => {623             return Err(error(624                 AdapterErrorKind::BadMessage,625                 "input must be a string or an array of strings",626             ));627         }628     };629     if input.is_empty() {630         return Err(error(AdapterErrorKind::BadMessage, "input has no text"));631     }632     let dimensions = map633         .get("dimensions")634         .map(|value| optional_u32("dimensions", value))635         .transpose()?636         .flatten();637     let base64 = match map.get("encoding_format").and_then(Value::as_str) {638         Some("base64") => true,639         Some("float") | None => false,640         Some(other) => {641             return Err(error(642                 AdapterErrorKind::BadMessage,643                 format!("encoding_format {other} is not float or base64"),644             ));645         }646     };647     Ok(EmbeddingRequest {648         model,649         input,650         dimensions,651         base64,652     })653 }654 655 /// Parses a speech request.656 pub fn parse_speech(body: &Value) -> Result<SpeechRequest, AdapterError> {657     let map = body.as_object().ok_or_else(|| {658         error(659             AdapterErrorKind::NotObject,660             "the speech request is not an object",661         )662     })?;663     let model = map664         .get("model")665         .and_then(Value::as_str)666         .ok_or_else(|| error(AdapterErrorKind::MissingModel, "the request has no model"))?667         .to_string();668     let input = map669         .get("input")670         .and_then(Value::as_str)671         .ok_or_else(|| error(AdapterErrorKind::BadMessage, "the request has no input"))?672         .to_string();673     let voice = map674         .get("voice")675         .map(|value| optional_string("voice", value))676         .transpose()?677         .flatten();678     let response_format = map679         .get("response_format")680         .map(|value| optional_string("response_format", value))681         .transpose()?682         .flatten();683     let speed = map684         .get("speed")685         .map(|value| optional_f32("speed", value))686         .transpose()?687         .flatten();688     Ok(SpeechRequest {689         model,690         input,691         voice,692         response_format,693         speed,694     })695 }696 697 /// Parses an image generation request.698 pub fn parse_images(body: &Value) -> Result<ImageRequest, AdapterError> {699     let map = body.as_object().ok_or_else(|| {700         error(701             AdapterErrorKind::NotObject,702             "the images request is not an object",703         )704     })?;705     let model = map706         .get("model")707         .and_then(Value::as_str)708         .ok_or_else(|| error(AdapterErrorKind::MissingModel, "the request has no model"))?709         .to_string();710     let prompt = map711         .get("prompt")712         .and_then(Value::as_str)713         .ok_or_else(|| error(AdapterErrorKind::BadMessage, "the request has no prompt"))?714         .to_string();715     let n = map716         .get("n")717         .map(|value| optional_u32("n", value))718         .transpose()?719         .flatten()720         .unwrap_or(1);721     if n == 0 || n > MAX_IMAGES {722         return Err(error(723             AdapterErrorKind::BadMessage,724             format!("n must be between 1 and {MAX_IMAGES}"),725         ));726     }727     let field = |name: &str| -> Result<Option<String>, AdapterError> {728         map.get(name)729             .map(|value| optional_string(name, value))730             .transpose()731             .map(Option::flatten)732     };733     Ok(ImageRequest {734         model,735         prompt,736         n,737         size: field("size")?,738         quality: field("quality")?,739         style: field("style")?,740     })741 }742 743 /// The OpenAI usage object for one terminal usage map.744 ///745 /// The native names are `tokens_in` and `tokens_out`; a map that already has746 /// the OpenAI names keeps them. A missing prompt count is zero, because OpenAI747 /// always sends a number for every field.748 pub fn usage(counts: &BTreeMap<String, u64>) -> Value {749     let prompt = counts750         .get("prompt_tokens")751         .or_else(|| counts.get("tokens_in"))752         .copied()753         .unwrap_or(0);754     let completion = counts755         .get("completion_tokens")756         .or_else(|| counts.get("tokens_out"))757         .copied()758         .unwrap_or(0);759     let total = counts760         .get("total_tokens")761         .copied()762         .unwrap_or_else(|| prompt.saturating_add(completion));763     let mut body = Object::new()764         .put("prompt_tokens", count_value(prompt))765         .put("completion_tokens", count_value(completion))766         .put("total_tokens", count_value(total));767     if let Some(cached) = counts.get("cached_tokens").copied() {768         body = body.put(769             "prompt_tokens_details",770             Object::new()771                 .put("cached_tokens", count_value(cached))772                 .build(),773         );774     }775     body.build()776 }777 778 /// One count, as an integer or a float above the signed range.779 fn count_value(value: u64) -> Value {780     match i64::try_from(value) {781         Ok(value) => Value::Int(value),782         Err(_) => Value::Float(value as f64),783     }784 }785 786 fn created_value(created: u64) -> Value {787     Value::Int(i64::try_from(created).unwrap_or(i64::MAX))788 }789 790 fn choice(delta: Value, finish_reason: Value) -> Value {791     Object::new()792         .put("index", Value::Int(CHOICE_INDEX))793         .put("delta", delta)794         .put("finish_reason", finish_reason)795         .build()796 }797 798 fn chunk_with(id: &str, model: &str, created: u64, delta: Value) -> Value {799     Object::new()800         .put("id", Value::str(id))801         .put("object", Value::str(CHUNK_OBJECT))802         .put("created", created_value(created))803         .put("model", Value::str(model))804         .put("choices", Value::Array(vec![choice(delta, Value::Null)]))805         .build()806 }807 808 /// One chunk of a streamed reply.809 pub fn chunk(id: &str, model: &str, created: u64, text: &str) -> Value {810     let delta = Object::new().put("content", Value::str(text)).build();811     chunk_with(id, model, created, delta)812 }813 814 /// One chunk that carries reasoning from the `progress` channel.815 pub fn reasoning_chunk(id: &str, model: &str, created: u64, text: &str) -> Value {816     let delta = Object::new()817         .put("reasoning_content", Value::str(text))818         .build();819     chunk_with(id, model, created, delta)820 }821 822 /// The chunk that closes a stream.823 pub fn finish(id: &str, model: &str, created: u64, reason: &str) -> Value {824     let delta = Object::new().build();825     Object::new()826         .put("id", Value::str(id))827         .put("object", Value::str(CHUNK_OBJECT))828         .put("created", created_value(created))829         .put("model", Value::str(model))830         .put(831             "choices",832             Value::Array(vec![choice(delta, Value::str(reason))]),833         )834         .build()835 }836 837 /// The chunk that carries stream usage. Its choices are empty, as OpenAI's are.838 pub fn usage_chunk(id: &str, model: &str, created: u64, usage: Value) -> Value {839     Object::new()840         .put("id", Value::str(id))841         .put("object", Value::str(CHUNK_OBJECT))842         .put("created", created_value(created))843         .put("model", Value::str(model))844         .put("choices", Value::Array(Vec::new()))845         .put("usage", usage)846         .build()847 }848 849 /// The whole reply, for `stream: false`.850 pub fn completion(851     id: &str,852     model: &str,853     created: u64,854     text: &str,855     reason: &str,856     usage: Option<Value>,857 ) -> Value {858     completion_reasoning(id, model, created, text, None, reason, usage)859 }860 861 /// The whole reply, with reasoning text when the stream carried any.862 pub fn completion_reasoning(863     id: &str,864     model: &str,865     created: u64,866     text: &str,867     reasoning: Option<&str>,868     reason: &str,869     usage: Option<Value>,870 ) -> Value {871     let mut message = Object::new()872         .put("role", Value::str("assistant"))873         .put("content", Value::str(text));874     if let Some(reasoning) = reasoning.filter(|text| !text.is_empty()) {875         message = message.put("reasoning_content", Value::str(reasoning));876     }877     let choice = Object::new()878         .put("index", Value::Int(CHOICE_INDEX))879         .put("message", message.build())880         .put("finish_reason", Value::str(reason))881         .build();882     let mut body = Object::new()883         .put("id", Value::str(id))884         .put("object", Value::str(COMPLETION_OBJECT))885         .put("created", created_value(created))886         .put("model", Value::str(model))887         .put("choices", Value::Array(vec![choice]));888     if let Some(usage) = usage {889         body = body.put("usage", usage);890     }891     body.build()892 }893 894 /// One OpenAI embeddings reply.895 pub fn embeddings(model: &str, vectors: &[Vec<f32>], prompt_tokens: u64, base64: bool) -> Value {896     let data = vectors897         .iter()898         .enumerate()899         .map(|(index, vector)| {900             let embedding = if base64 {901                 Value::str(floats_base64(vector))902             } else {903                 Value::Array(904                     vector905                         .iter()906                         .map(|value| Value::Float(f64::from(*value)))907                         .collect(),908                 )909             };910             Object::new()911                 .put("object", Value::str("embedding"))912                 .put("embedding", embedding)913                 .put("index", Value::Int(index as i64))914                 .build()915         })916         .collect();917     Object::new()918         .put("object", Value::str("list"))919         .put("data", Value::Array(data))920         .put("model", Value::str(model))921         .put(922             "usage",923             Object::new()924                 .put("prompt_tokens", count_value(prompt_tokens))925                 .put("total_tokens", count_value(prompt_tokens))926                 .build(),927         )928         .build()929 }930 931 /// One OpenAI image reply. Every image is base64, because the engine has no932 /// public URL to give a client.933 pub fn images(created: u64, images: &[Vec<u8>]) -> Value {934     let data = images935         .iter()936         .map(|bytes| {937             Object::new()938                 .put("b64_json", Value::str(inf3r_json::b64::encode(bytes)))939                 .build()940         })941         .collect();942     Object::new()943         .put("created", created_value(created))944         .put("data", Value::Array(data))945         .build()946 }947 948 /// One OpenAI model list.949 pub fn models(ids: &[String], created: u64) -> Value {950     let data = ids951         .iter()952         .map(|id| {953             Object::new()954                 .put("id", Value::str(id.clone()))955                 .put("object", Value::str("model"))956                 .put("created", created_value(created))957                 .put("owned_by", Value::str("inf3r"))958                 .build()959         })960         .collect();961     Object::new()962         .put("object", Value::str("list"))963         .put("data", Value::Array(data))964         .build()965 }966 967 /// One OpenAI transcription reply.968 pub fn transcription(text: &str) -> Value {969     Object::new().put("text", Value::str(text)).build()970 }971 972 /// The vectors of one CBOR embedding artifact.973 pub fn embedding_vectors(bytes: &[u8]) -> Option<Vec<Vec<f32>>> {974     let value = inf3r_proto::cbor::decode(bytes).ok()?;975     let inf3r_proto::cbor::Value::Array(items) = value else {976         return None;977     };978     let mut vectors = Vec::with_capacity(items.len());979     for item in items {980         let inf3r_proto::cbor::Value::Array(values) = item else {981             return None;982         };983         let mut vector = Vec::with_capacity(values.len());984         for value in values {985             let number = match value {986                 inf3r_proto::cbor::Value::Float(value) => value as f32,987                 inf3r_proto::cbor::Value::Uint(value) => value as f32,988                 inf3r_proto::cbor::Value::Nint(value) => value as f32,989                 _ => return None,990             };991             vector.push(number);992         }993         vectors.push(vector);994     }995     Some(vectors)996 }997 998 /// Little-endian float32 values, base64 encoded, as OpenAI's embeddings shape.999 fn floats_base64(values: &[f32]) -> String {1000     let mut bytes = Vec::with_capacity(values.len() * 4);1001     for value in values {1002         bytes.extend_from_slice(&value.to_le_bytes());1003     }1004     inf3r_json::b64::encode(&bytes)1005 }