1 //! The twelve capability bodies.2 //!3 //! Each one reads its parts the way its page says, refuses a request that the4 //! page does not permit, and then writes its channels. The output is a function5 //! of the input: a golden that this plugin wrote yesterday still matches today.6 7 use std::io::Write;8 use std::os::fd::OwnedFd;9 use std::time::Instant;10 11 use inf3r_plugin_sdk::capability::{Artifact, Report};12 use inf3r_plugin_sdk::emitter::Emitter;13 use inf3r_plugin_sdk::{USAGE_FIRST_TOKEN_MS, USAGE_TOKENS_OUT, USAGE_TOKENS_PER_S};14 use inf3r_proto::Value;15 16 use crate::catalogue::{DIMS, MP4, PNG, RATE};17 use crate::{Input, Silent, digest, refuse};18 19 /// The MIME of text that a client can print.20 const TEXT: &str = "text/plain; charset=utf-8";21 22 /// The MIME of CBOR that a client decodes.23 const CBOR: &str = "application/cbor";24 25 /// The MIME of the progress channel.26 const JSON: &str = "application/json";27 28 /// One second of silence, as the sample format states it.29 const SILENCE_MS: u64 = 1_000;30 31 /// A 100 ms slice, so that a job exercises credit and more than one frame.32 const SLICE_MS: u64 = 100;33 34 /// One second in milliseconds, the denominator of a rate.35 const MS_PER_SECOND: u64 = 1_000;36 37 /// Hundredths per whole token per second. The usage field is an integer, so a38 /// rate that keeps two decimal places is multiplied by this.39 const HUNDREDTHS: u64 = 100;40 41 /// `chat`: echo the user turns, one token at a time.42 pub fn chat(43 req: inf3r_plugin_sdk::capability::Request<'_>,44 out: &mut dyn Emitter,45 ) -> Result<Report, Silent> {46 let input = Input::new(&req);47 let prompt = input.require_text("user")?;48 49 let started = Instant::now();50 out.emit("progress", JSON, br#"{"stage":"decode","pct":0}"#)?;51 52 // A test knob: `params.bytes` asks for that many bytes of text in 1 MiB53 // chunks. A stream longer than one credit window is the only way to prove54 // that the web replenishes it; a fixture cannot wait for 8 MiB of words.55 if let Some(Value::Uint(bytes)) = req.params.get("bytes") {56 let bytes = *bytes;57 let chunk = vec![b'x'; 1 << 20];58 let mut left = bytes;59 let mut tokens_out = 0;60 let mut first_token_ms = None;61 while left > 0 {62 let take = usize::try_from(left.min(chunk.len() as u64)).unwrap_or(chunk.len());63 out.emit("text", TEXT, &chunk[..take])?;64 left -= take as u64;65 tokens_out += 1;66 first_token_ms.get_or_insert_with(|| elapsed_ms(started));67 }68 let elapsed_ms = elapsed_ms(started);69 out.usage(USAGE_TOKENS_OUT, tokens_out);70 out.usage(USAGE_FIRST_TOKEN_MS, first_token_ms.unwrap_or(elapsed_ms));71 out.usage(USAGE_TOKENS_PER_S, tokens_per_s(tokens_out, elapsed_ms));72 let mut usage = Report::default();73 usage.usage.insert("tokens_in".into(), prompt.len() as u64);74 return Ok(usage);75 }76 77 // One word per chunk, because a stream that arrives as one frame does not78 // prove that a stream works.79 let mut tokens_out = 0;80 let mut first_token_ms = None;81 for word in prompt.split_whitespace() {82 let mut chunk = String::with_capacity(word.len() + 1);83 chunk.push_str(word);84 chunk.push(' ');85 out.emit("text", TEXT, chunk.as_bytes())?;86 tokens_out += 1;87 first_token_ms.get_or_insert_with(|| elapsed_ms(started));88 }89 90 let elapsed_ms = elapsed_ms(started);91 out.usage(USAGE_TOKENS_OUT, tokens_out);92 out.usage(USAGE_FIRST_TOKEN_MS, first_token_ms.unwrap_or(elapsed_ms));93 out.usage(USAGE_TOKENS_PER_S, tokens_per_s(tokens_out, elapsed_ms));94 95 let mut usage = Report::default();96 usage.usage.insert("tokens_in".into(), prompt.len() as u64);97 Ok(usage)98 }99 100 /// `embed`: one vector for each text part, in input order.101 pub fn embed(102 req: inf3r_plugin_sdk::capability::Request<'_>,103 out: &mut dyn Emitter,104 ) -> Result<Report, Silent> {105 let input = Input::new(&req);106 let texts: Vec<&str> = input107 .all_text()108 .ok_or_else(|| refuse("the embed parts are not all UTF-8 text"))?;109 if texts.is_empty() {110 return Err(refuse("embed needs at least one text part"));111 }112 113 let vectors: Vec<Value> = texts114 .iter()115 .map(|text| {116 let seed = digest(text);117 Value::Array(118 (0..DIMS)119 .map(|index| {120 // A value in [-1, 1) from one bit range of the hash.121 let bits = seed.rotate_left(index * 5) & 0xffff;122 Value::Float(bits as f64 / 32_768.0 - 1.0)123 })124 .collect(),125 )126 })127 .collect();128 129 let mut bytes = Vec::new();130 inf3r_proto::cbor::encode(&Value::Array(vectors), &mut bytes);131 out.emit("embedding", CBOR, &bytes)?;132 let mut usage = Report::default();133 usage.usage.insert("vectors".into(), texts.len() as u64);134 Ok(usage)135 }136 137 /// `rerank`: one score for each document, in input order.138 pub fn rerank(139 req: inf3r_plugin_sdk::capability::Request<'_>,140 out: &mut dyn Emitter,141 ) -> Result<Report, Silent> {142 let input = Input::new(&req);143 let query = input.require_text("query")?;144 let documents = input.require_json("documents")?;145 let documents = documents146 .get("documents")147 .and_then(|value| value.as_array())148 .ok_or_else(|| refuse("the documents part has no array"))?;149 150 let seed = digest(query);151 let scores: Vec<Value> = documents152 .iter()153 .enumerate()154 .map(|(index, document)| {155 let text = document.as_str().unwrap_or_default();156 let score = (digest(text) ^ seed.rotate_left(index as u32)) & 0xffff;157 Value::Float(score as f64 / 65_535.0)158 })159 .collect();160 161 let mut bytes = Vec::new();162 inf3r_proto::cbor::encode(&Value::Array(scores), &mut bytes);163 out.emit("embedding", CBOR, &bytes)?;164 let mut usage = Report::default();165 usage166 .usage167 .insert("documents".into(), documents.len() as u64);168 Ok(usage)169 }170 171 /// `decide`: choose the first option, with the uniform probability that follows172 /// from having no model.173 pub fn decide(174 req: inf3r_plugin_sdk::capability::Request<'_>,175 out: &mut dyn Emitter,176 ) -> Result<Report, Silent> {177 let input = Input::new(&req);178 let _question = input.require_text("question")?;179 let options = input.require_json("options")?;180 let options = options181 .get("options")182 .and_then(|value| value.as_array())183 .filter(|options| !options.is_empty())184 .ok_or_else(|| refuse("the options part has no options"))?;185 186 let ids: Vec<String> = options187 .iter()188 .filter_map(|option| {189 option190 .get("id")191 .and_then(|id| id.as_str())192 .map(str::to_string)193 })194 .collect();195 if ids.len() != options.len() {196 return Err(refuse("an option has no id"));197 }198 199 let share = 1.0 / ids.len() as f64;200 let reply = inf3r_json::Object::new().put("chosen", inf3r_json::Value::str(ids[0].clone()));201 let scored: Vec<inf3r_json::Value> = ids202 .iter()203 .map(|id| {204 inf3r_json::Object::new()205 .put("id", inf3r_json::Value::str(id.clone()))206 .put("probability", inf3r_json::Value::Float(share))207 .build()208 })209 .collect();210 let reply = reply211 .put("options", inf3r_json::Value::Array(scored))212 .build();213 214 out.emit("decision", JSON, inf3r_json::to_string(&reply).as_bytes())?;215 Ok(Report::default())216 }217 218 /// `extract`: one empty string for each field that the request names.219 pub fn extract(220 req: inf3r_plugin_sdk::capability::Request<'_>,221 out: &mut dyn Emitter,222 ) -> Result<Report, Silent> {223 let input = Input::new(&req);224 let _source = input.require_text("source")?;225 let fields = input.require_json("fields")?;226 let fields = fields227 .get("fields")228 .and_then(|value| value.as_array())229 .ok_or_else(|| refuse("the fields part has no array"))?;230 231 let mut object = inf3r_json::Object::new();232 for field in fields {233 let name = field234 .get("name")235 .and_then(|name| name.as_str())236 .ok_or_else(|| refuse("a field has no name"))?;237 object = object.put(name, inf3r_json::Value::str(""));238 }239 let reply = object.build();240 241 out.emit("decision", JSON, inf3r_json::to_string(&reply).as_bytes())?;242 Ok(Report::default())243 }244 245 /// `tts`: silence, in slices, with a progress step before each one.246 pub fn tts(247 req: inf3r_plugin_sdk::capability::Request<'_>,248 out: &mut dyn Emitter,249 ) -> Result<Report, Silent> {250 let input = Input::new(&req);251 let text = input.require_text("any")?;252 speak(out, text, SILENCE_MS)253 }254 255 /// `stt`: a fixed transcript, as text and as tokens, with progress.256 pub fn stt(257 req: inf3r_plugin_sdk::capability::Request<'_>,258 out: &mut dyn Emitter,259 ) -> Result<Report, Silent> {260 let input = Input::new(&req);261 if input.bytes("any")?.is_none() {262 return Err(refuse("the audio part is missing"));263 }264 265 out.emit("progress", JSON, br#"{"stage":"decode","pct":0}"#)?;266 let transcript = "mock transcript";267 for word in transcript.split_whitespace() {268 out.emit("text", TEXT, format!("{word} ").as_bytes())?;269 let token = Value::Map(vec![270 (Value::Text("id".into()), Value::Uint(digest(word) & 0xffff)),271 (Value::Text("text".into()), Value::Text(word.into())),272 (Value::Text("t_ms".into()), Value::Uint(0)),273 ]);274 let mut bytes = Vec::new();275 inf3r_proto::cbor::encode(&token, &mut bytes);276 out.emit("tokens", CBOR, &bytes)?;277 }278 out.emit("progress", JSON, br#"{"stage":"decode","pct":1}"#)?;279 280 let mut usage = Report::default();281 usage.usage.insert(282 "tokens_out".into(),283 transcript.split_whitespace().count() as u64,284 );285 Ok(usage)286 }287 288 /// `music`: silence for one second, seeded by the prompt.289 pub fn music(290 req: inf3r_plugin_sdk::capability::Request<'_>,291 out: &mut dyn Emitter,292 ) -> Result<Report, Silent> {293 let input = Input::new(&req);294 let prompt = input.require_text("prompt")?;295 let seconds = req296 .params297 .get("duration_s")298 .and_then(|value| match value {299 Value::Uint(n) => Some(*n),300 _ => None,301 })302 .unwrap_or(1);303 speak(out, prompt, seconds * 1_000)304 }305 306 /// `image-gen`: the smallest PNG, after a progress step.307 pub fn image_gen(308 req: inf3r_plugin_sdk::capability::Request<'_>,309 out: &mut dyn Emitter,310 ) -> Result<Report, Silent> {311 let input = Input::new(&req);312 let _prompt = input.require_text("prompt")?;313 picture(out)314 }315 316 /// `image-edit`: the smallest PNG, after reading both images.317 pub fn image_edit(318 req: inf3r_plugin_sdk::capability::Request<'_>,319 out: &mut dyn Emitter,320 ) -> Result<Report, Silent> {321 let input = Input::new(&req);322 if input.bytes("source")?.is_none() {323 return Err(refuse("the source image is missing"));324 }325 let _instruction = input.require_text("instruction")?;326 picture(out)327 }328 329 /// `t2v-gen`: the mp4 header, after a progress step.330 pub fn t2v_gen(331 req: inf3r_plugin_sdk::capability::Request<'_>,332 out: &mut dyn Emitter,333 ) -> Result<Report, Silent> {334 let input = Input::new(&req);335 let _prompt = input.require_text("prompt")?;336 clip(out)337 }338 339 /// `i2v-gen`: the mp4 header, after reading the first frame.340 pub fn i2v_gen(341 req: inf3r_plugin_sdk::capability::Request<'_>,342 out: &mut dyn Emitter,343 ) -> Result<Report, Silent> {344 let input = Input::new(&req);345 if input.bytes("first_frame")?.is_none() {346 return Err(refuse("the first frame is missing"));347 }348 let _prompt = input.require_text("prompt")?;349 clip(out)350 }351 352 /// Writes audio in slices, and reports one progress step per slice.353 fn speak(out: &mut dyn Emitter, seed_text: &str, millis: u64) -> Result<Report, Silent> {354 let mime = format!("audio/pcm; enc=s16le; rate={RATE}; channels=1");355 let bytes_per_slice = (u64::from(RATE) * SLICE_MS / 1_000) * 2;356 let slices = (millis / SLICE_MS).max(1);357 let _ = digest(seed_text);358 359 for index in 0..slices {360 let pct = (index + 1) as f64 / slices as f64;361 let step = format!("{{\"stage\":\"synth\",\"pct\":{pct:.3}}}");362 out.emit("progress", JSON, step.as_bytes())?;363 let silence = vec![0u8; bytes_per_slice as usize];364 out.emit("pcm", &mime, &silence)?;365 }366 367 let mut usage = Report::default();368 usage.usage.insert("rate".into(), u64::from(RATE));369 usage.usage.insert("ms".into(), millis);370 Ok(usage)371 }372 373 fn picture(out: &mut dyn Emitter) -> Result<Report, Silent> {374 out.emit("progress", JSON, br#"{"stage":"denoise","pct":1}"#)?;375 out.emit("image", "image/png", PNG)?;376 out.artifact("image", "image/png", file_artifact(PNG)?)?;377 let mut usage = Report::default();378 usage.usage.insert("images".into(), 1);379 Ok(usage)380 }381 382 fn clip(out: &mut dyn Emitter) -> Result<Report, Silent> {383 out.emit("progress", JSON, br#"{"stage":"denoise","pct":1}"#)?;384 out.emit("clip", "video/mp4", MP4)?;385 out.artifact("clip", "video/mp4", file_artifact(MP4)?)?;386 let mut usage = Report::default();387 usage.usage.insert("clips".into(), 1);388 Ok(usage)389 }390 391 /// Puts the bytes in an unlinked file and returns its descriptor. The file is392 /// deleted now; the descriptor is the only name that remains.393 fn file_artifact(bytes: &[u8]) -> Result<Artifact, Silent> {394 static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);395 let path = std::env::temp_dir().join(format!(396 "inf3r-mock-artifact-{}-{}",397 std::process::id(),398 NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)399 ));400 let mut file = std::fs::OpenOptions::new()401 .create_new(true)402 .read(true)403 .write(true)404 .open(&path)405 .map_err(file_error)?;406 file.write_all(bytes).map_err(file_error)?;407 let _ = std::fs::remove_file(&path);408 let fd: OwnedFd = file.into();409 Ok(Artifact::File(fd))410 }411 412 /// A local file failure is an internal fault, not a request refusal.413 fn file_error(why: std::io::Error) -> Silent {414 Silent::Refused(inf3r_plugin_sdk::Failure::new(415 inf3r_proto::body::ErrorCode::Internal,416 why.to_string(),417 ))418 }419 420 /// Whole milliseconds since `started`, with a floor of one so that a rate has421 /// a denominator.422 fn elapsed_ms(started: Instant) -> u64 {423 u64::try_from(started.elapsed().as_millis())424 .unwrap_or(u64::MAX)425 .max(1)426 }427 428 /// Hundredths of a token per second over the whole job.429 fn tokens_per_s(tokens_out: u64, elapsed_ms: u64) -> u64 {430 tokens_out431 .saturating_mul(MS_PER_SECOND)432 .saturating_mul(HUNDREDTHS)433 / elapsed_ms434 }