Skip to main content

weirdnet_backends/
openai.rs

1//! Engine request bodies (OpenAI `/v1/chat/completions` and `/v1/completions`) from infer/2
2//! requests.
3
4use serde_json::{Map, Value, json};
5use weirdnet_agent::remote::RemoteError;
6use weirdnet_agent::remote::infer::v2::{Input, Request, ResponseFormat, Sampling};
7use weirdnet_agent::{Message, Role, ToolSpec};
8
9use crate::engine::EngineKind;
10use crate::error::bad_request;
11
12/// An OpenAI chat message. Image and audio parts go through unchanged, in the OpenAI shape.
13pub fn message(m: &Message) -> Value {
14    let role = match m.role {
15        Role::System => "system",
16        Role::User => "user",
17        Role::Assistant => "assistant",
18        Role::Tool => "tool",
19        _ => "user",
20    };
21    let mut v = json!({"role": role, "content": m.content});
22    if !m.tool_calls.is_empty() {
23        v["tool_calls"] = m
24            .tool_calls
25            .iter()
26            .map(|c| {
27                let args = match &c.arguments {
28                    Value::String(s) => s.clone(),
29                    other => other.to_string(),
30                };
31                json!({"id": c.id, "type": "function", "function": {"name": c.name, "arguments": args}})
32            })
33            .collect();
34    }
35    if let Some(id) = &m.tool_call_id {
36        v["tool_call_id"] = id.clone().into();
37    }
38    v
39}
40
41/// An OpenAI function tool.
42pub fn tool(t: &ToolSpec) -> Value {
43    json!({"type": "function", "function": {"name": t.name, "description": t.description, "parameters": t.input_schema}})
44}
45
46fn sampling(obj: &mut Map<String, Value>, s: &Sampling, engine: EngineKind) {
47    let mut put = |k: &str, v: Option<Value>| {
48        if let Some(v) = v {
49            obj.insert(k.into(), v);
50        }
51    };
52    put("temperature", s.temperature.map(Value::from));
53    put("top_p", s.top_p.map(Value::from));
54    put("top_k", s.top_k.map(Value::from));
55    put("min_p", s.min_p.map(Value::from));
56    put("max_tokens", s.max_tokens.map(Value::from));
57    put("presence_penalty", s.presence_penalty.map(Value::from));
58    put("frequency_penalty", s.frequency_penalty.map(Value::from));
59    let repeat = if matches!(engine, EngineKind::Vllm | EngineKind::Mlx) { "repetition_penalty" } else { "repeat_penalty" };
60    put(repeat, s.repeat_penalty.map(Value::from));
61    if !s.stop.is_empty() {
62        obj.insert("stop".into(), s.stop.clone().into());
63    }
64}
65
66/// Which model a request body is for: a base model, or a LoRA adapter on one.
67#[derive(Debug, Clone, PartialEq)]
68#[non_exhaustive]
69pub enum Target {
70    /// The engine's alias for the model, with no adapter applied.
71    Base {
72        alias: String,
73        /// The base has adapters loaded (llama.cpp then gets an explicit empty `"lora"` list).
74        has_adapters: bool,
75    },
76    /// Adapter `id` on `base`: llama.cpp gets `"lora": [{"id": index, "scale": scale}]` with
77    /// `index` its position in the engine's `--lora` list; vLLM gets `"model": id`.
78    Adapter { base: String, index: usize, id: String, scale: f32 },
79}
80
81impl Target {
82    /// A base model without adapters.
83    pub fn base(alias: impl Into<String>) -> Self {
84        Target::Base { alias: alias.into(), has_adapters: false }
85    }
86}
87
88fn streaming(obj: &mut Map<String, Value>, target: &Target, engine: EngineKind) {
89    let model = match (target, engine) {
90        (Target::Adapter { id, .. }, EngineKind::Vllm) => id.as_str(),
91        (Target::Adapter { base, .. }, _) => base.as_str(),
92        (Target::Base { alias, .. }, _) => alias.as_str(),
93    };
94    obj.insert("model".into(), model.into());
95    if engine == EngineKind::Llamacpp {
96        match target {
97            Target::Adapter { index, scale, .. } => {
98                obj.insert("lora".into(), json!([{"id": index, "scale": scale}]));
99            }
100            Target::Base { has_adapters: true, .. } => {
101                obj.insert("lora".into(), json!([]));
102            }
103            _ => {}
104        }
105    }
106    obj.insert("stream".into(), true.into());
107    obj.insert("stream_options".into(), json!({"include_usage": true}));
108}
109
110/// The streaming chat body for `request` on the engine's `alias`. An assistant prefix becomes a
111/// final assistant message the engine continues (llama.cpp prefills a trailing assistant
112/// message; vLLM gets `continue_final_message`). Reasoning in the prefix is not continued.
113pub fn chat_body(request: &Request, alias: &str, engine: EngineKind) -> Result<Value, RemoteError> {
114    chat_body_for(request, &Target::base(alias), engine)
115}
116
117/// [`chat_body`] for a [`Target`]: a base model or an adapter on one.
118pub fn chat_body_for(request: &Request, target: &Target, engine: EngineKind) -> Result<Value, RemoteError> {
119    let Input::Messages(messages) = &request.input else {
120        return Err(bad_request("chat takes assembled messages, not a context_ref or a raw prompt"));
121    };
122    let mut msgs: Vec<Value> = messages.iter().map(message).collect();
123    let prefix = request.assistant_prefix.as_ref().filter(|p| !p.text.is_empty());
124    if let Some(p) = prefix {
125        msgs.push(json!({"role": "assistant", "content": p.text}));
126    }
127    if msgs.is_empty() {
128        return Err(bad_request("no messages"));
129    }
130    let mut obj = Map::new();
131    obj.insert("messages".into(), Value::Array(msgs));
132    if prefix.is_some() && engine == EngineKind::Vllm {
133        obj.insert("continue_final_message".into(), true.into());
134        obj.insert("add_generation_prompt".into(), false.into());
135    }
136    sampling(&mut obj, &request.sampling, engine);
137    if let Some(seed) = request.seed {
138        obj.insert("seed".into(), seed.into());
139    }
140    match &request.response_format {
141        Some(ResponseFormat::Json) => {
142            obj.insert("response_format".into(), json!({"type": "json_object"}));
143        }
144        Some(ResponseFormat::JsonSchema { name, schema, strict }) => {
145            obj.insert("response_format".into(), json!({"type": "json_schema", "json_schema": {"name": name, "schema": schema, "strict": strict}}));
146        }
147        _ => {}
148    }
149    if !request.tools.is_empty() {
150        obj.insert("tools".into(), request.tools.iter().map(tool).collect());
151    }
152    streaming(&mut obj, target, engine);
153    Ok(Value::Object(obj))
154}
155
156/// The streaming `/v1/completions` body for a raw `prompt`.
157pub fn completion_body(prompt: &str, s: &Sampling, seed: Option<u64>, alias: &str, engine: EngineKind) -> Value {
158    completion_body_for(prompt, s, seed, &Target::base(alias), engine)
159}
160
161/// [`completion_body`] for a [`Target`].
162pub fn completion_body_for(prompt: &str, s: &Sampling, seed: Option<u64>, target: &Target, engine: EngineKind) -> Value {
163    let mut obj = Map::new();
164    obj.insert("prompt".into(), prompt.into());
165    sampling(&mut obj, s, engine);
166    if let Some(seed) = seed {
167        obj.insert("seed".into(), seed.into());
168    }
169    streaming(&mut obj, target, engine);
170    Value::Object(obj)
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176
177    #[test]
178    fn adapter_targets() {
179        let r = Request::messages(vec![Message::user("hi")]);
180        let a = Target::Adapter { base: "qwen".into(), index: 1, id: "tune".into(), scale: 0.5 };
181        let b = chat_body_for(&r, &a, EngineKind::Llamacpp).unwrap();
182        assert_eq!((b["model"].as_str(), &b["lora"]), (Some("qwen"), &json!([{"id": 1, "scale": 0.5}])));
183        let b = chat_body_for(&r, &a, EngineKind::Vllm).unwrap();
184        assert_eq!(b["model"], "tune");
185        assert!(b.get("lora").is_none());
186        let base = Target::Base { alias: "qwen".into(), has_adapters: true };
187        let b = completion_body_for("x", &Sampling::default(), None, &base, EngineKind::Llamacpp);
188        assert_eq!((b["model"].as_str(), &b["lora"]), (Some("qwen"), &json!([])));
189        let b = chat_body(&r, "qwen", EngineKind::Llamacpp).unwrap();
190        assert!(b.get("lora").is_none(), "no adapters, no lora field");
191    }
192    use weirdnet_agent::ToolCall;
193    use weirdnet_agent::remote::infer::v2::{ContextRef, Prefix};
194
195    fn req() -> Request {
196        let call = Message::assistant("", vec![ToolCall { id: "c1".into(), name: "f".into(), arguments: json!({"x": 1}) }]);
197        let result = Message::tool("c1", "42");
198        let mut s = Sampling::default();
199        s.temperature = Some(0.0);
200        s.max_tokens = Some(5);
201        s.repeat_penalty = Some(1.1);
202        s.stop = vec!["\n".into()];
203        Request::messages(vec![Message::system("be brief"), Message::user("hi"), call, result])
204            .with_sampling(s)
205            .with_seed(7)
206            .with_tools(vec![ToolSpec::new("f", "a tool")])
207            .with_response_format(ResponseFormat::Json)
208    }
209
210    #[test]
211    fn chat_bodies() {
212        let b = chat_body(&req(), "alias", EngineKind::Llamacpp).unwrap();
213        assert_eq!(b["model"], "alias");
214        assert_eq!(b["stream"], true);
215        assert_eq!(b["stream_options"]["include_usage"], true);
216        assert_eq!(b["messages"][0], json!({"role": "system", "content": "be brief"}));
217        assert_eq!(b["messages"][2]["tool_calls"][0]["function"]["arguments"], "{\"x\":1}");
218        assert_eq!(b["messages"][3], json!({"role": "tool", "content": "42", "tool_call_id": "c1"}));
219        assert_eq!((b["temperature"].clone(), b["max_tokens"].clone(), b["seed"].clone()), (json!(0.0), json!(5), json!(7)));
220        assert!(b["repeat_penalty"].is_number() && b.get("repetition_penalty").is_none());
221        assert_eq!(b["stop"], json!(["\n"]));
222        assert_eq!(b["tools"][0]["function"]["name"], "f");
223        assert_eq!(b["response_format"]["type"], "json_object");
224        let v = chat_body(&req(), "alias", EngineKind::Vllm).unwrap();
225        assert!(v["repetition_penalty"].is_number());
226        assert!(v.get("continue_final_message").is_none());
227    }
228
229    #[test]
230    fn a_prefix_is_continued() {
231        let r = Request::messages(vec![Message::user("hi")]).with_prefix(Prefix::new("Hello th", ""));
232        let b = chat_body(&r, "m", EngineKind::Llamacpp).unwrap();
233        assert_eq!(b["messages"][1], json!({"role": "assistant", "content": "Hello th"}));
234        let v = chat_body(&r, "m", EngineKind::Vllm).unwrap();
235        assert_eq!((v["continue_final_message"].clone(), v["add_generation_prompt"].clone()), (json!(true), json!(false)));
236    }
237
238    #[test]
239    fn context_refs_and_empty_requests_are_refused() {
240        assert!(matches!(chat_body(&Request::context(ContextRef::new("c", None)), "m", EngineKind::Llamacpp), Err(RemoteError::BadRequest { .. })));
241        assert!(chat_body(&Request::messages(vec![]), "m", EngineKind::Llamacpp).is_err());
242    }
243
244    #[test]
245    fn content_parts_go_through_unchanged() {
246        use weirdnet_agent::ContentPart;
247        let png = "data:image/png;base64,iVBORw0KGgo=";
248        let r =
249            Request::messages(vec![Message::user(vec![ContentPart::text("what?"), ContentPart::image(png), ContentPart::audio("UklGRg==", "wav")])]);
250        let b = chat_body(&r, "m", EngineKind::Llamacpp).unwrap();
251        assert_eq!(
252            b["messages"][0]["content"],
253            json!([
254                {"type": "text", "text": "what?"},
255                {"type": "image_url", "image_url": {"url": png}},
256                {"type": "input_audio", "input_audio": {"data": "UklGRg==", "format": "wav"}}
257            ])
258        );
259    }
260
261    #[test]
262    fn completion_bodies() {
263        let b = completion_body("Once", &Sampling::default(), None, "m", EngineKind::Llamacpp);
264        assert_eq!((b["prompt"].clone(), b["stream"].clone()), (json!("Once"), json!(true)));
265    }
266}