1use 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 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
33fn 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
45fn 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 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 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 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 async fn chat_json(
201 &self,
202 system: &str,
203 msgs: &[Msg],
204 schema: &Value,
205 name: &str,
206 ) -> Result<Option<Value>, String> {
207 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 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 "temperature": 0,
238 "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 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 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 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 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}