Skip to main content

steeldb/agent/
paddock.rs

1//! Paddock provider — a local OpenAI-compatible server (e.g. Qwen3.5-2B). Speaks
2//! `POST {base_url}/chat/completions` with function/tool calling. Translates the neutral
3//! message/tool types to OpenAI chat messages and back.
4
5use crate::agent::provider::LlmProvider;
6use crate::agent::types::{Block, Msg, Role, Stop, ToolSpec, Turn};
7use async_trait::async_trait;
8use serde_json::{json, Value};
9
10pub struct PaddockProvider {
11    client: reqwest::Client,
12    base_url: String,
13    model: String,
14    api_key: Option<String>,
15    /// Cached after the server rejects a native `tools` field (e.g. ollama's gemma3n) — subsequent
16    /// requests inline the tool schema in the system prompt so the harness can recover `<tool_call>`
17    /// blocks from the reply.
18    prompt_only_tools: std::sync::atomic::AtomicBool,
19}
20
21impl PaddockProvider {
22    pub fn new(base_url: String, model: String, api_key: Option<String>) -> PaddockProvider {
23        PaddockProvider {
24            client: reqwest::Client::new(),
25            base_url,
26            model,
27            api_key,
28            prompt_only_tools: std::sync::atomic::AtomicBool::new(false),
29        }
30    }
31}
32
33/// Inline tool schema for models the server won't accept `tools` for. Emit-format matches Hermes,
34/// which the harness already recovers.
35fn inline_tools_prompt(tools: &[ToolSpec]) -> String {
36    let mut out = String::from(
37        "\n\nYou have access to these tools. To call one, emit ONLY a single line in this exact form (no prose around it):\n<tool_call>{\"name\":\"<tool_name>\",\"arguments\":{...}}</tool_call>\nAfter the tool result comes back, either call another tool or give the final answer as plain text.\n\nAvailable tools:\n",
38    );
39    for t in tools {
40        out.push_str(&format!("- {} — {}\n  schema: {}\n", t.name, t.description, t.schema));
41    }
42    out
43}
44
45/// Flatten neutral messages into OpenAI chat messages (system first).
46fn to_openai_messages(system: &str, msgs: &[Msg]) -> Vec<Value> {
47    let mut out = vec![json!({ "role": "system", "content": system })];
48    for m in msgs {
49        match m.role {
50            Role::User => {
51                // user text and/or tool results
52                let mut text = String::new();
53                for b in &m.blocks {
54                    match b {
55                        Block::Text(t) => {
56                            if !text.is_empty() {
57                                text.push('\n');
58                            }
59                            text.push_str(t);
60                        }
61                        Block::ToolResult { id, content, .. } => {
62                            out.push(json!({ "role": "tool", "tool_call_id": id, "content": content }));
63                        }
64                        _ => {}
65                    }
66                }
67                if !text.is_empty() {
68                    out.push(json!({ "role": "user", "content": text }));
69                }
70            }
71            Role::Assistant => {
72                let mut text = String::new();
73                let mut tool_calls = Vec::new();
74                for b in &m.blocks {
75                    match b {
76                        Block::Text(t) => text.push_str(t),
77                        Block::ToolUse { id, name, input } => {
78                            tool_calls.push(json!({
79                                "id": id,
80                                "type": "function",
81                                "function": { "name": name, "arguments": input.to_string() }
82                            }));
83                        }
84                        _ => {}
85                    }
86                }
87                let mut msg = json!({ "role": "assistant", "content": if text.is_empty() { Value::Null } else { Value::String(text) } });
88                if !tool_calls.is_empty() {
89                    msg["tool_calls"] = Value::Array(tool_calls);
90                }
91                out.push(msg);
92            }
93        }
94    }
95    out
96}
97
98fn to_openai_tools(tools: &[ToolSpec]) -> Vec<Value> {
99    tools
100        .iter()
101        .map(|t| json!({ "type": "function", "function": { "name": t.name, "description": t.description, "parameters": t.schema } }))
102        .collect()
103}
104
105#[async_trait]
106impl LlmProvider for PaddockProvider {
107    fn name(&self) -> &str {
108        "paddock"
109    }
110
111    async fn chat(&self, system: &str, msgs: &[Msg], tools: &[ToolSpec]) -> Result<Turn, String> {
112        use std::sync::atomic::Ordering;
113        let url = format!("{}/chat/completions", self.base_url.trim_end_matches('/'));
114        let mut prompt_only = self.prompt_only_tools.load(Ordering::Relaxed);
115        let resp = loop {
116            let system_full = if prompt_only && !tools.is_empty() { format!("{system}{}", inline_tools_prompt(tools)) } else { system.to_string() };
117            // `/no_think` is the soft switch Qwen-family reasoning models honour, and it has to ride on the
118            // LAST USER turn — in the system prompt it is ignored. It is also the only switch that survives an
119            // OpenAI-compatible proxy which drops unknown body fields, which ollama's /v1 endpoint does.
120            // Harmless to a model that does not recognise it.
121            let mut messages = to_openai_messages(&system_full, msgs);
122            if let Some(last_user) = messages
123                .iter_mut()
124                .rev()
125                .find(|m| m.get("role").and_then(|r| r.as_str()) == Some("user"))
126            {
127                if let Some(c) = last_user.get("content").and_then(|c| c.as_str()) {
128                    last_user["content"] = json!(format!("{c}\n\n/no_think"));
129                }
130            }
131            let mut body = json!({
132                "model": self.model,
133                "messages": messages,
134                "max_tokens": 2048
135            });
136            if !prompt_only && !tools.is_empty() {
137                body["tools"] = json!(to_openai_tools(tools));
138                body["tool_choice"] = json!("auto");
139            }
140            let mut req = self.client.post(&url).json(&body);
141            if let Some(k) = &self.api_key {
142                req = req.bearer_auth(k);
143            }
144            let resp = req.send().await.map_err(|e| format!("paddock request: {e}"))?;
145            if resp.status().is_success() {
146                break resp;
147            }
148            let status = resp.status();
149            let text = resp.text().await.unwrap_or_default();
150            // fall back to prompt-only when the server rejects a native `tools` field
151            if !prompt_only && !tools.is_empty() && (text.contains("does not support tools") || text.contains("tool_choice")) {
152                self.prompt_only_tools.store(true, Ordering::Relaxed);
153                prompt_only = true;
154                continue;
155            }
156            return Err(format!("paddock {status}: {text}"));
157        };
158        let v: Value = resp.json().await.map_err(|e| format!("paddock decode: {e}"))?;
159        let choice = v.get("choices").and_then(|c| c.get(0)).ok_or("paddock: no choices")?;
160        let message = choice.get("message").ok_or("paddock: no message")?;
161
162        let text = message.get("content").and_then(|c| c.as_str()).unwrap_or("").to_string();
163        let mut tool_uses = Vec::new();
164        if let Some(calls) = message.get("tool_calls").and_then(|c| c.as_array()) {
165            for call in calls {
166                let id = call.get("id").and_then(|x| x.as_str()).unwrap_or("").to_string();
167                let func = call.get("function");
168                let name = func.and_then(|f| f.get("name")).and_then(|x| x.as_str()).unwrap_or("").to_string();
169                let args_str = func.and_then(|f| f.get("arguments")).and_then(|x| x.as_str()).unwrap_or("{}");
170                let input: Value = serde_json::from_str(args_str).unwrap_or(json!({}));
171                tool_uses.push((id, name, input));
172            }
173        }
174        let stop = match choice.get("finish_reason").and_then(|f| f.as_str()) {
175            Some("tool_calls") => Stop::ToolUse,
176            Some("stop") | Some("length") => Stop::EndTurn,
177            _ => {
178                if tool_uses.is_empty() {
179                    Stop::EndTurn
180                } else {
181                    Stop::ToolUse
182                }
183            }
184        };
185        Ok(Turn { text, tool_uses, stop })
186    }
187
188    /// Constrain decoding to `schema` via the OpenAI-compatible `response_format`.
189    ///
190    /// Ollama, llama.cpp's server, vLLM and LM Studio all accept this and compile the schema into a decoding
191    /// grammar internally, so the model can only emit tokens the schema permits. That is why this works on
192    /// models with no tool-calling ability at all: nothing is being asked of the model except to continue, and
193    /// the sampler does the rest.
194    ///
195    /// Two degradations, because not every server implements the whole thing:
196    ///   * a server that rejects `json_schema` is retried with `json_object`, which constrains the output to
197    ///     *some* JSON and leaves the shape to the prompt;
198    ///   * a server that rejects `response_format` entirely returns `Ok(None)`, so the caller falls back rather
199    ///     than seeing an error it cannot act on.
200    async fn chat_json(
201        &self,
202        system: &str,
203        msgs: &[Msg],
204        schema: &Value,
205        name: &str,
206    ) -> Result<Option<Value>, String> {
207        // Ollama's native endpoint FIRST, when this looks like ollama. Its OpenAI-compatible shim silently
208        // drops `think`, `chat_template_kwargs` and the `/no_think` soft switch alike, so a hybrid reasoning
209        // model spends the whole completion budget on a `reasoning` field and returns zero characters of
210        // content. The native route accepts `think: false` and takes the JSON schema directly as `format`,
211        // which is the only way to actually get structured output out of such a model here. Falls through to
212        // the portable path when this is not ollama, or when the native call does not produce usable JSON.
213        if let Some(base) = self.base_url.trim_end_matches('/').strip_suffix("/v1") {
214            if let Some(v) = self.ollama_native_json(base, system, msgs, schema).await? {
215                return Ok(Some(v));
216            }
217        }
218
219        let url = format!("{}/chat/completions", self.base_url.trim_end_matches('/'));
220
221        // Do NOT put the schema JSON in the prompt. The first version did, on the reasoning that the grammar
222        // guarantees shape while only the prompt conveys intent — and `qwen2.5:0.5b` promptly returned the facet
223        // names "surface", "token", "head" and "tail", which are the schema's own field names. A small model
224        // treats anything in its context as material to copy, so handing it a vocabulary of key names invites
225        // exactly that. The grammar already enforces the shape; the caller's own system prompt explains the task.
226        let system_full = format!("{system}\n\nReply with JSON only. No prose, no code fence.");
227
228        for mode in ["json_schema", "json_object"] {
229            let mut body = json!({
230                "model": self.model,
231                "messages": to_openai_messages(&system_full, msgs),
232                "max_tokens": 4096,
233                // Structured output is used for decisions, not prose, so sample greedily: the reference's
234                // curator runs at temperature 0. Without this, two curations of the SAME clusters produced
235                // materially different ontologies — one run named a facet `sensing-modality`, the next
236                // `5g_compatible` — which makes the vocabulary irreproducible for no benefit.
237                "temperature": 0,
238                // Turn OFF chain-of-thought. A hybrid reasoning model spends its budget thinking before it
239                // emits anything, and the grammar constrains only the ANSWER — `qwen3:1.7b` came back
240                // `finish_reason: length` having spent all 4096 completion tokens with ZERO characters of
241                // content, the reasoning having gone to a separate `reasoning` field. Reasoning buys nothing
242                // here: the schema dictates the shape and the judgment wanted is a naming decision.
243                //
244                // These two flags are sent because some servers honour them — ollama's /v1 endpoint does NOT,
245                // which is why the prompt also carries the `/no_think` soft switch below. An unrecognised field
246                // is ignored rather than rejected, so sending both costs nothing.
247                "think": false,
248                "chat_template_kwargs": { "enable_thinking": false },
249            });
250            body["response_format"] = if mode == "json_schema" {
251                json!({ "type": "json_schema",
252                        "json_schema": { "name": name, "strict": true, "schema": schema } })
253            } else {
254                json!({ "type": "json_object" })
255            };
256
257            let mut req = self.client.post(&url).json(&body);
258            if let Some(k) = &self.api_key {
259                req = req.bearer_auth(k);
260            }
261            let resp = req.send().await.map_err(|e| format!("paddock request: {e}"))?;
262            if !resp.status().is_success() {
263                let status = resp.status();
264                let text = resp.text().await.unwrap_or_default();
265                // this server has no structured-output support at all; let the caller fall back
266                if text.contains("response_format") || status.as_u16() == 400 {
267                    continue;
268                }
269                return Err(format!("paddock {status}: {text}"));
270            }
271            let v: Value = resp.json().await.map_err(|e| format!("paddock decode: {e}"))?;
272            if std::env::var("STEELDB_DEBUG_JSON").is_ok() {
273                eprintln!(
274                    "[dbg] mode={mode} finish={:?} completion_tokens={:?} sys_chars={} content_chars={}",
275                    v.pointer("/choices/0/finish_reason"),
276                    v.pointer("/usage/completion_tokens"),
277                    system_full.len(),
278                    v.pointer("/choices/0/message/content").and_then(|c| c.as_str()).map(|c| c.len()).unwrap_or(0)
279                );
280            }
281            let content = v
282                .get("choices")
283                .and_then(|c| c.get(0))
284                .and_then(|c| c.get("message"))
285                .and_then(|m| m.get("content"))
286                .and_then(|c| c.as_str())
287                .unwrap_or("");
288            if content.trim().is_empty() {
289                continue;
290            }
291            // A constrained reply should be bare JSON, but a server that only honoured `json_object` may still
292            // wrap it in prose or a code fence, so reuse the tolerant extractor.
293            if let Ok(parsed) = serde_json::from_str::<Value>(content.trim()) {
294                return Ok(Some(parsed));
295            }
296            if let Some(parsed) = crate::vocabulary::extract_json(content) {
297                return Ok(Some(parsed));
298            }
299        }
300        Ok(None)
301    }
302}
303
304impl PaddockProvider {
305    /// Ollama's native `/api/chat`: `format` takes a JSON schema directly, and `think: false` actually works.
306    ///
307    /// Returns `Ok(None)` when this is not ollama or the reply is unusable, so the caller can fall back to the
308    /// OpenAI-compatible route rather than failing outright.
309    async fn ollama_native_json(
310        &self,
311        base: &str,
312        system: &str,
313        msgs: &[Msg],
314        schema: &Value,
315    ) -> Result<Option<Value>, String> {
316        let mut messages = vec![json!({ "role": "system", "content": system })];
317        for m in to_openai_messages("", msgs).into_iter().filter(|m| {
318            m.get("role").and_then(|r| r.as_str()) != Some("system")
319        }) {
320            messages.push(m);
321        }
322        let body = json!({
323            "model": self.model,
324            "messages": messages,
325            "stream": false,
326            "think": false,
327            "format": schema,
328            "options": { "temperature": 0, "num_predict": 4096 },
329        });
330        let resp = match self.client.post(format!("{base}/api/chat")).json(&body).send().await {
331            Ok(r) => r,
332            // not ollama, or not listening: let the caller try the portable route
333            Err(_) => return Ok(None),
334        };
335        if !resp.status().is_success() {
336            return Ok(None);
337        }
338        let v: Value = match resp.json().await {
339            Ok(v) => v,
340            Err(_) => return Ok(None),
341        };
342        let content = v.pointer("/message/content").and_then(|c| c.as_str()).unwrap_or("");
343        if std::env::var("STEELDB_DEBUG_JSON").is_ok() {
344            eprintln!(
345                "[dbg] ollama-native done={:?} content_chars={}",
346                v.get("done_reason"),
347                content.len()
348            );
349        }
350        if content.trim().is_empty() {
351            return Ok(None);
352        }
353        Ok(serde_json::from_str::<Value>(content.trim())
354            .ok()
355            .or_else(|| crate::vocabulary::extract_json(content)))
356    }
357}