The pieces / weirdnet-openai

weirdnet-openai

A loopback-only OpenAI-compatible bridge over a weirdnet-agent inference pool (chat, embeddings, speech and transcription), with a token, a Host check and no CORS.

v0.2.5 GitHub crates.io docs.rs weirdnet-openai = "0.2.5"

What it brings

Use weirdnet-openai to let the user's local tools that already speak the OpenAI API use their own devices' models (chat, embeddings, speech and transcription). Point the tool at http://127.0.0.1:<port>/v1 with the bridge token as the API key; requests go through a weirdnet-agent pool, so failover, resume and stand-ins work as they do for the app.

What it is

Local tools that speak the OpenAI API (editors, notebooks, curl) reach the user’s inference nodes through it: chat completions, streaming or not, the model list, embeddings, speech and transcription, all through a weirdnet-agent 0.5 Pool, so failover, resume and stand-ins come with it.

It binds 127.0.0.1 only, checks the Host header against its own address, requires a bearer token and sends no CORS headers, so web pages can’t call it.

How it works

Who can call it

The bridge binds 127.0.0.1 only. Every request must have a Host of 127.0.0.1:<port> or localhost:<port> (so a web page can't reach it by DNS rebinding) and the bearer token (at least 16 characters, compared in constant time). It sends no CORS headers, so browsers block pages from reading its answers.

Requests

Chat bodies become infer/2 requests: messages (string content or parts: text, image_url with a data:image/... URL, input_audio and, since 0.2.5, video_url with a data:video/... URL; remote image or video URLs and other part types get 400), sampling, seed, response_format and function tools; other parameters are ignored. x-wait: 1 sets wait_for_model. "cache": false or x-weirdnet-cache: off (0.2.1) skips the nodes' answer cache, and "cache": "refresh" or x-weirdnet-cache: refresh skips the read and stores the fresh answer (weirdnet-agent 0.5.1 Request::cache); with both, the stricter wins, and any other value is a 400. continue_final_message: true (0.1.2, as in vLLM) moves the last assistant message into the request's prefix, so the model continues it (weirdnet-agent's Request::continuing); the answer, whole or streamed, holds only the new text. It needs the last message to be an assistant message without tool calls and add_generation_prompt not true (else 400), and a node that can continue (else 501). Without the flag a trailing assistant message is passed on as a message. A streamed answer starts when a node accepts the request, so an error before that is a plain HTTP error; after that, an error arrives as a final error event. Answers carry x-weirdnet-model, x-weirdnet-cache and x-weirdnet-standin, and the same under weirdnet in the body (on the last chunk when streaming).

Images and audio (0.2.0) and video (0.2.5) go to the pool unchanged, which sends them only to a model whose catalog entry takes them (vision, audio, video, and all three as inputs, under weirdnet in /v1/models): with no model it picks one; a named model that lacks the input, or a pool with no such model, is a 400 that says so. A client whose model doesn't read video sends frames as images instead.

Speech (0.2.5)

POST /v1/audio/speech runs infer/2 Speak through Pool::speak, or Pool::speak_stream with stream_format: "audio" (the bytes as the node sends them; "sse" is refused). The body is OpenAI's: input, model, voice (a preset name or {"id": name}), instructions, response_format (wav, pcm, mp3, opus or flac; absent, the model's first format, which is wav for the usual speech models rather than OpenAI's mp3) and speed. Weirdnet extensions go under weirdnet: language, seed, sample_rate, design (a voice described in words), ref_audio (a base64 data: URL; remote and file URLs are never fetched) with ref_text and consent: true to clone a voice, script ([{"speaker": 0, "text": "..."}] instead of input) and raw.

Before a node is asked, the bridge checks the request against the catalog's speech profile for the model (weirdnet-agent 0.5.11 Catalog::route_speak), or picks a speaker that covers it when no model is named. A voice, format or feature the model lacks is a 400 that names the model and what it has, for example model `tts` has no preset voice `alloy` (presets: vivian, ryan): OpenAI voice names are never mapped to another voice. The answer's Content-Type is the real format (audio/pcm;rate=24000 for raw PCM), with x-audio-sample-rate and x-weirdnet-audio-channels when the node knows them; a whole answer also names request fields the model ignored (such as a reference transcript) in x-weirdnet-ignored. A streamed answer that fails after audio has left ends early: the pool never fails over once audio has started, because another node would start again with another voice.

Transcription (0.2.5)

POST /v1/audio/transcriptions takes multipart/form-data and runs infer/2 Transcribe through Pool::transcribe: file, model (absent, the catalog's transcriber), language, prompt, response_format and timestamp_granularities[]=segment (word and stream are refused). The audio's format comes from the file name, else its audio/* type, else its first bytes. json (the default) answers {"text": ...}; verbose_json adds language, duration (seconds) and segments; text is plain text; srt and vtt are subtitles from the transcriber's timed segments (one cue over the whole clip when it reports only the duration, and a 501 when it times nothing, rather than invented cues). Speech and transcription are never cached.

Request size (0.2.4): bodies (chat, speech and transcription alike) may be up to 32 MiB (DEFAULT_MAX_REQUEST_BYTES) unless the bridge is set otherwise with Bridge::with_max_request_bytes. A larger body gets a 413 with code request_too_large whose message names the limit, and the x-weirdnet-max-request-bytes header carries it. /v1/models reports weirdnet.max_request_bytes per model (the smaller of the bridge's and the node's) and weirdnet.limits, the model's media limits from weirdnet-agent 0.5.7, so a client sizes frames to fit the bytes as well as the tokens. infer/2 carries at most 32 MiB per message.

LoRA adapters (0.2.2): "adapter_scale" in a chat or completion body sets how strongly a LoRA adapter model applies for that request (weirdnet-agent 0.5.2 Request::adapter_scale); a value that is not a finite number is a 400. /v1/models reports an adapter's base model as weirdnet.base (null for models). Since 0.2.3 it also reports weirdnet.origin (hub, upload or train) and weirdnet.license when the node says (weirdnet-agent 0.5.4 CatalogModel::origin and license), and null otherwise.

Errors map to OpenAI-style bodies: unknown model 404, bad request 400, busy 503 with Retry-After, unavailable 503, refused 403, unsupported 501, timeouts 504, engine failures 502.

Key types and modules

  • Speech (0.2.5): POST /v1/audio/speech over weirdnet-agent 0.5.11 Pool::speak and Pool::speak_stream. OpenAI’s input, model, voice (a name or {"id": ...}), instructions, response_format (wav, pcm, mp3, opus, flac; absent: the model’s first format), speed and stream_format: "audio" (bytes as they come; sse is refused), plus weirdnet extensions: language, seed, sample_rate, design, ref_audio (a data: URL only) with ref_text and consent, script and raw. Each request is checked against the catalog first, so a voice, format or feature the model lacks is a 400 that names what it has: OpenAI voices such as alloy are never mapped to another voice. The answer’s Content-Type is the real format (audio/pcm;rate=24000 for raw PCM), with x-audio-sample-rate, x-weirdnet-audio-channels and x-weirdnet-ignored; a stream that fails after audio has left ends early instead of splicing another take. request::speech parses the body.
  • Transcription (0.2.5): POST /v1/audio/transcriptions (multipart) over Pool::transcribe: file, model, language, prompt, response_format (json, verbose_json, text, srt, vtt) and timestamp_granularities[]=segment. Subtitles come from the transcriber’s timed segments; one that times nothing gets a 501, not invented cues. Both audio endpoints share the request size limit and its 413, and neither is cached.
  • Video (0.2.5): chat messages may carry video_url parts with a data:video/... URL (weirdnet-agent 0.5.10 ContentPart::VideoUrl); the pool sends them only to a model that reads video. Remote and non-video URLs are a 400; nothing is fetched.
  • Request size (0.2.4): Bridge::with_max_request_bytes sets the largest body (default DEFAULT_MAX_REQUEST_BYTES, 32 MiB); a larger one gets a 413 request_too_large that names the limit, also in x-weirdnet-max-request-bytes. /v1/models reports weirdnet.max_request_bytes and the model’s weirdnet.limits.
  • POST /v1/chat/completions: SSE streaming with data: [DONE], or one JSON answer; reasoning as reasoning_content, tool calls, usage with cached and reasoning tokens. Dropping the response cancels the pool request. continue_final_message: true (0.1.2, vLLM’s parameter) continues the last assistant message and answers with only the new text.
  • POST /v1/completions (0.1.1): a raw prompt, whole or streamed as text_completion chunks; n/best_of above 1, echo, suffix and logprobs are refused with 400.
  • Images and audio (0.2.0): chat messages may carry image_url parts with a data:image/... URL and input_audio parts; they go to the pool unchanged, which sends them only to a model that takes them. With no model the pool picks one; a named text-only model, or a pool with none that can, is a 400 that says so. Request bodies may be up to 32 MiB.
  • GET /v1/models: the pool catalog, with state, purpose (chat, embed, transcribe, speak, ...), replicas, context, revision, vision, audio, video and inputs (0.2.5), a speaking model’s speech profile when reported (0.2.5), and a LoRA adapter’s base (0.2.2; null for models), and origin and license (0.2.3; null when the node doesn’t say) under weirdnet. POST /v1/embeddings: float vectors.
  • x-weirdnet-model, x-weirdnet-cache: hit and x-weirdnet-standin headers; x-wait: 1 waits for the requested model instead of a stand-in.
  • Answer cache (0.2.1): "cache": false or x-weirdnet-cache: off skips the nodes’ answer cache; "cache": "refresh" or x-weirdnet-cache: refresh refreshes it. The stricter of body and header wins; other values are a 400.
  • Adapter scale (0.2.2): "adapter_scale" in a chat or completion body sets how strongly a LoRA adapter model applies for that request (weirdnet-agent Request::adapter_scale); a value that is not a finite number is a 400.
  • GET /metrics: Prometheus counters weirdnet_bridge_{requests,errors,cache_hits,standin}_total.
  • request: OpenAI bodies to infer/2 requests. new_token() makes a 32-byte hex token.

Feature flags

None: everything is on by default.

Usage

[dependencies]
weirdnet-openai = "0.2.5"
# Cargo.toml
weirdnet-openai = "0.2"

// main.rs
use std::sync::Arc;
use weirdnet_openai::{Bridge, BridgeOptions, new_token};

let token = new_token(); // show it to the user once; keep it in their keychain
let bridge = Bridge::bind(BridgeOptions::new(11435, token)).await?;
bridge.serve(Arc::new(pool), shutdown).await?; // pool: weirdnet_agent::remote::pool::Pool

Where it fits

Version 0.2.5 is on crates.io (docs.rs). 0.2.5 is additive and needs weirdnet-agent 0.5.11: POST /v1/audio/speech and POST /v1/audio/transcriptions, video_url parts in chat, and weirdnet.video, weirdnet.inputs, weirdnet.speech and the video limits in /v1/models. 0.2.4 is additive and needs weirdnet-agent 0.5.7: a configurable request size limit with a 413 that names it, and media limits in /v1/models. Extracted from Ymir’s ymir-openai. 0.2.3 is additive and needs weirdnet-agent 0.5.4: weirdnet.origin (hub, upload or train) and weirdnet.license in /v1/models. 0.2.2 is additive and needs weirdnet-agent 0.5.2: "adapter_scale" in chat and completion bodies, and weirdnet.base in /v1/models for LoRA adapters. 0.2.1 is additive and needs weirdnet-agent 0.5.1: the cache parameter and x-weirdnet-cache request header, and request::cache_header / request::stricter. 0.2.0 needs weirdnet-agent 0.5 (breaking, since it takes an agent Pool): image and audio content parts pass through to the pool instead of a 400, /v1/models reports vision and audio, and request bodies may be up to 32 MiB (16 MiB before). 0.1.2 (on weirdnet-agent "0.4.2") adds continue_final_message: with no node that can continue it is a 501, and with add_generation_prompt: true or a last message that is not a plain assistant message, a 400. 0.1.1 (on weirdnet-agent "0.4.1") makes /v1/completions work as an infer/2 raw prompt, whole or streamed (a node that can’t take raw prompts answers 501); streamed answers carry x-weirdnet-cache: hit from early metadata; /v1/embeddings reports real usage.prompt_tokens and keeps a node’s bad request a 400. Unknown parameters are ignored (#1); Retry-After is 1 s until busy nodes report a delay (#2).