troupekit-ffi-core 0.4.0

Binding-neutral Troupekit API: plain Rust handles, records and host traits that the UniFFI and PyO3 adapters translate.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
use crate::error::{ErrorCode, FfiError};
use crate::host::{HostModel, TokenSink};
use crate::records::{HostMessage, HostModelCaps, HostReply, HostRequest};
use async_trait::async_trait;
use serde_json::{json, Value};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::Arc;
use troupekit_core::error::{ProviderError, ProviderErrorKind};
use troupekit_core::event::Usage;
use troupekit_core::message::{ContentPart, Message, Role};
use troupekit_providers::model::MAX_REPLY_BYTES;
use troupekit_providers::{
    CompletionRequest, CompletionResponse, Delta, FailedCall, Model, StopReason, RESEND_NOTE_BYTES,
};

/// Starts the message of every host model failure, for people reading it.
/// The error code comes from the `ProviderErrorKind::Host` kind, never
/// from this text.
const HOST_CALLBACK: &str = "host model callback failed: ";

const _: () = assert!(REPAIR.len() <= RESEND_NOTE_BYTES);

const REPAIR: &str = "Your last reply was not valid. Reply again with only one JSON object: \
{\"tool\": \"<name>\", \"arguments\": {...}} to call a tool, or {\"answer\": ...} to answer.";

/// Wraps host model `host` as a kit model, reading its id once. When
/// `priced`, token counts the host leaves low are raised to a byte
/// estimate so a priced reply is never billed as free.
/// Output: the model and its id, or `InvalidArgument` for an empty or
/// over-long id. Each request reads `capabilities` again.
pub(crate) fn wrap_model(
    host: Arc<dyn HostModel>,
    priced: bool,
) -> Result<(Arc<dyn Model>, String), FfiError> {
    let id = host.id();
    if id.trim().is_empty() || id.len() > 256 {
        return Err(FfiError::new(
            ErrorCode::InvalidArgument,
            "host model id must be 1 to 256 bytes",
        ));
    }
    assert!(!id.is_empty());
    Ok((
        Arc::new(HostModelAdapter {
            host,
            id: id.clone(),
            priced,
        }),
        id,
    ))
}

struct HostModelAdapter {
    host: Arc<dyn HostModel>,
    id: String,
    priced: bool,
}

#[async_trait]
impl Model for HostModelAdapter {
    fn id(&self) -> &str {
        &self.id
    }

    fn extra_calls(&self, req: &CompletionRequest) -> u32 {
        u32::from(!req.tools.is_empty())
    }

    async fn complete(&self, req: &CompletionRequest) -> Result<CompletionResponse, ProviderError> {
        self.complete_billed(req)
            .await
            .map_err(|failed| failed.error)
    }

    async fn stream(
        &self,
        req: &CompletionRequest,
        on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
    ) -> Result<CompletionResponse, ProviderError> {
        self.stream_billed(req, on_delta)
            .await
            .map_err(|failed| failed.error)
    }

    async fn complete_billed(
        &self,
        req: &CompletionRequest,
    ) -> Result<CompletionResponse, FailedCall> {
        self.stream_billed(req, &mut |_| {}).await
    }

    async fn stream_billed(
        &self,
        req: &CompletionRequest,
        on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
    ) -> Result<CompletionResponse, FailedCall> {
        req.validate()?;
        let req = req.sendable(false)?;
        let caps = self.capabilities().await?;
        let emulate = !caps.tools && !req.tools.is_empty();
        let mut request = render(&req, &caps)?;
        let first = self.generate(&request, !emulate, on_delta).await?;
        let mut usage = self.usage_of(&request, &first);
        let lost = |error: ProviderError, usage: Usage| FailedCall { error, usage };
        let parts = match parse(&req, &caps, &first) {
            Some(parts) => parts,
            None if emulate => {
                request
                    .messages
                    .push(host_message("assistant", &first.text));
                request.messages.push(host_message("user", REPAIR));
                let second = self
                    .generate(&request, false, on_delta)
                    .await
                    .map_err(|failed| lost(failed.error, usage + failed.usage))?;
                usage += self.usage_of(&request, &second);
                parse(&req, &caps, &second).ok_or_else(|| {
                    lost(
                        decode("host model reply is not the tool JSON after one repair"),
                        usage,
                    )
                })?
            }
            None => {
                return Err(lost(
                    decode("host model tool_calls_json is not a list of calls"),
                    usage,
                ))
            }
        };
        let called = parts
            .iter()
            .any(|p| matches!(p, ContentPart::ToolCall { .. }));
        if emulate {
            for part in &parts {
                if let ContentPart::Text { text } = part {
                    on_delta(&Delta::TextDelta { text: text.clone() });
                }
            }
        }
        assert!(!parts.is_empty());
        Ok(CompletionResponse {
            message: Message {
                role: Role::Assistant,
                parts,
            },
            usage,
            stop: if called {
                StopReason::ToolUse
            } else {
                StopReason::EndTurn
            },
        })
    }
}

impl HostModelAdapter {
    /// The usage of one `generate` call: the host's counts, raised for a
    /// priced model to a quarter of the request and reply bytes, rounded
    /// up, as the budget estimate counts them.
    /// Input: the request sent and the reply. Output: the usage, unpriced.
    fn usage_of(&self, request: &HostRequest, reply: &HostReply) -> Usage {
        let mut usage = Usage {
            input_tokens: reply.input_tokens,
            output_tokens: reply.output_tokens,
            cost_usd_micros: 0,
        };
        if self.priced {
            usage.input_tokens = usage.input_tokens.max(tokens_of(request_bytes(request)));
            usage.output_tokens = usage.output_tokens.max(tokens_of(reply_bytes(reply)));
            assert!(usage.output_tokens > 0 || reply_bytes(reply) == 0);
        }
        usage
    }

    async fn capabilities(&self) -> Result<HostModelCaps, ProviderError> {
        let host = self.host.clone();
        let read = tokio::task::spawn_blocking(move || {
            catch_unwind(AssertUnwindSafe(|| host.capabilities()))
        })
        .await;
        match read {
            Ok(Ok(caps)) => Ok(caps),
            _ => Err(failed(format!(
                "host model `{}` panicked in capabilities",
                self.id
            ))),
        }
    }

    /// Sends `request` to the host model, passing streamed text to
    /// `on_delta` when `forward`. Output: the reply, or the failure with
    /// the usage of a reply that arrived but is over the reply cap.
    async fn generate(
        &self,
        request: &HostRequest,
        forward: bool,
        on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
    ) -> Result<HostReply, FailedCall> {
        let sent = request.clone();
        let queue = crate::runtime::settings().event_buffer.saturating_add(1);
        let (sink, mut deltas) = TokenSink::channel(forward, MAX_REPLY_BYTES, queue);
        let rest = sink.clone();
        let host = self.host.clone();
        let mut job = tokio::task::spawn_blocking(move || {
            catch_unwind(AssertUnwindSafe(|| host.generate(sent, sink)))
        });
        let joined = loop {
            tokio::select! {
                Some(text) = deltas.recv() => on_delta(&Delta::TextDelta { text }),
                joined = &mut job => break joined,
            }
        };
        while let Ok(text) = deltas.try_recv() {
            on_delta(&Delta::TextDelta { text });
        }
        let text = rest.take_pending();
        if !text.is_empty() {
            on_delta(&Delta::TextDelta { text });
        }
        let reply = match joined {
            Ok(Ok(Ok(reply))) => reply,
            Ok(Ok(Err(error))) => return Err(failed(error.message).into()),
            Ok(Err(_)) | Err(_) => return Err(failed(format!("`{}` panicked", self.id)).into()),
        };
        if reply_bytes(&reply) > MAX_REPLY_BYTES {
            return Err(FailedCall {
                error: decode("host model reply is over the reply cap"),
                usage: self.usage_of(request, &reply),
            });
        }
        Ok(reply)
    }
}

fn failed(message: String) -> ProviderError {
    ProviderError::new(ProviderErrorKind::Host, format!("{HOST_CALLBACK}{message}"))
}

fn decode(message: &str) -> ProviderError {
    ProviderError::new(ProviderErrorKind::Decode, message)
}

fn tokens_of(bytes: usize) -> u64 {
    u64::try_from(bytes.div_ceil(4)).expect("byte count fits in u64")
}

fn request_bytes(request: &HostRequest) -> usize {
    let optional = |text: &Option<String>| text.as_ref().map_or(0, String::len);
    let messages: usize = request
        .messages
        .iter()
        .map(|m| {
            m.role.len() + m.text.len() + optional(&m.tool_calls_json) + optional(&m.tool_call_id)
        })
        .fold(0, usize::saturating_add);
    messages
        .saturating_add(optional(&request.system))
        .saturating_add(optional(&request.tools_json))
        .saturating_add(optional(&request.schema_json))
}

fn reply_bytes(reply: &HostReply) -> usize {
    reply
        .text
        .len()
        .saturating_add(reply.tool_calls_json.as_ref().map_or(0, String::len))
}

fn host_message(role: &str, text: &str) -> HostMessage {
    HostMessage {
        role: role.into(),
        text: text.into(),
        ..HostMessage::default()
    }
}

/// Renders kit request `req` for a host model with `caps`: native tools
/// as `tools_json`, else the tool list and the JSON reply shape in the
/// system text, with that shape as `schema_json` when supported.
/// Output: the host request, or `BadRequest` for a non-text part.
pub(crate) fn render(
    req: &CompletionRequest,
    caps: &HostModelCaps,
) -> Result<HostRequest, ProviderError> {
    let emulate = !caps.tools && !req.tools.is_empty();
    let typed = emulate && typed_answer(req.output_schema.as_ref());
    let mut messages = Vec::with_capacity(req.messages.len());
    for message in req.messages.iter().filter(|m| m.role != Role::System) {
        render_message(message, caps.tools, emulate, typed, &mut messages)?;
    }
    let mut system: Vec<String> = req.system_text().into_iter().collect();
    let mut request = HostRequest::default();
    let shape = if emulate {
        system.push(tool_prompt(req));
        Some(envelope(req))
    } else {
        req.output_schema.clone()
    };
    if caps.tools && !req.tools.is_empty() {
        let tools: Vec<Value> = req
            .tools
            .iter()
            .map(|t| json!({"name": t.name, "description": t.description, "schema": t.schema}))
            .collect();
        request.tools_json = Some(Value::Array(tools).to_string());
    }
    match shape {
        Some(shape) if caps.json_schema => request.schema_json = Some(shape.to_string()),
        Some(shape) => system.push(format!(
            "Reply with only JSON that matches this schema: {shape}"
        )),
        None => {}
    }
    request.system = (!system.is_empty()).then(|| system.join("\n\n"));
    request.messages = messages;
    request.max_tokens = req.max_tokens;
    assert!(request.tools_json.is_none() || !emulate);
    Ok(request)
}

/// Reports whether an emulated answer under output schema `schema` is
/// stored as JSON text. With any schema set, `parse_envelope` keeps every
/// answer, strings with their quotes, as its JSON, so the agent's output
/// check and the replay read back the exact value. Output: the flag.
fn typed_answer(schema: Option<&Value>) -> bool {
    schema.is_some()
}

fn render_message(
    message: &Message,
    native: bool,
    emulate: bool,
    typed: bool,
    out: &mut Vec<HostMessage>,
) -> Result<(), ProviderError> {
    let mut text = Vec::new();
    let mut calls = Vec::new();
    for part in &message.parts {
        match part {
            ContentPart::Text { text: t } => text.push(t.clone()),
            ContentPart::Image { .. } => {
                return Err(ProviderError::new(
                    ProviderErrorKind::BadRequest,
                    "host models take text only",
                ))
            }
            ContentPart::ToolCall {
                id,
                name,
                arguments,
            } => calls.push(json!({"id": id, "name": name, "arguments": arguments})),
            ContentPart::ToolResult {
                call_id,
                content,
                is_error,
            } => {
                let content = if *is_error {
                    format!("Error: {content}")
                } else {
                    content.clone()
                };
                let mut result = if native {
                    host_message("tool", &content)
                } else {
                    host_message(
                        "user",
                        &format!("Result of tool call {call_id}:\n{content}"),
                    )
                };
                if native {
                    result.tool_call_id = Some(call_id.clone());
                }
                out.push(result);
            }
            ContentPart::Hosted { .. } => {}
        }
    }
    let role = match message.role {
        Role::User => "user",
        Role::Assistant => "assistant",
        Role::Tool | Role::System => return Ok(()),
    };
    let mut rendered = host_message(role, &text.join("\n"));
    if native && !calls.is_empty() {
        rendered.tool_calls_json = Some(Value::Array(calls).to_string());
    } else if !calls.is_empty() {
        let mut lines: Vec<String> = Vec::with_capacity(calls.len() + 1);
        if !rendered.text.is_empty() {
            lines.push(rendered.text.clone());
        }
        lines.extend(
            calls
                .iter()
                .map(|c| json!({"tool": c["name"], "arguments": c["arguments"]}).to_string()),
        );
        rendered.text = lines.join("\n");
    } else if role == "assistant" && emulate {
        let answer = if typed {
            serde_json::from_str::<Value>(&rendered.text)
                .unwrap_or_else(|_| Value::String(rendered.text.clone()))
        } else {
            Value::String(rendered.text.clone())
        };
        rendered.text = json!({ "answer": answer }).to_string();
    }
    assert!(rendered.tool_calls_json.is_none() || native);
    out.push(rendered);
    Ok(())
}

fn tool_prompt(req: &CompletionRequest) -> String {
    let mut prompt = String::from(
        "You can call tools. To call one, reply with only the JSON \
{\"tool\": \"<name>\", \"arguments\": {...}}. To answer, reply with only the JSON \
{\"answer\": <answer>}. Tools:",
    );
    for tool in &req.tools {
        prompt.push_str(&format!(
            "\n- {}: {}\n  arguments schema: {}",
            tool.name, tool.description, tool.schema
        ));
    }
    prompt
}

const ANSWER_POINTER: &str = "#/oneOf/0/properties/answer";
const DATA_KEYWORDS: [&str; 5] = ["$ref", "enum", "const", "default", "examples"];
const NAMED_SCHEMAS: [&str; 5] = [
    "properties",
    "patternProperties",
    "$defs",
    "definitions",
    "dependentSchemas",
];

fn envelope(req: &CompletionRequest) -> Value {
    let mut answer = req
        .output_schema
        .clone()
        .unwrap_or_else(|| json!({"type": "string"}));
    rebase_refs(&mut answer);
    let names: Vec<&str> = req.tools.iter().map(|t| t.name.as_str()).collect();
    json!({"oneOf": [
        {"type": "object", "properties": {"answer": answer}, "required": ["answer"], "additionalProperties": false},
        {"type": "object", "properties": {"tool": {"type": "string", "enum": names}, "arguments": {"type": "object"}},
         "required": ["tool", "arguments"], "additionalProperties": false}
    ]})
}

/// Rewrites every local pointer `$ref` (`#` or `#/...`) in `schema` to
/// resolve from the envelope root, where the answer schema now sits at
/// `ANSWER_POINTER`. A subschema with its own `$id` is its own resource,
/// so it and everything under it are left as they are. Anchors and
/// instance data (`enum`, `const`, `default`, `examples`) stay; maps
/// of named subschemas such as `properties` are walked by value.
fn rebase_refs(schema: &mut Value) {
    match schema {
        Value::Object(map) => {
            if map.contains_key("$id") {
                return;
            }
            if let Some(Value::String(target)) = map.get_mut("$ref") {
                if target == "#" || target.starts_with("#/") {
                    let rest = &target[1..];
                    *target = format!("{ANSWER_POINTER}{rest}");
                    assert!(target.starts_with(ANSWER_POINTER));
                }
            }
            for (key, value) in map.iter_mut() {
                let key = key.as_str();
                if DATA_KEYWORDS.contains(&key) {
                    continue;
                }
                match value {
                    Value::Object(named) if NAMED_SCHEMAS.contains(&key) => {
                        named.values_mut().for_each(rebase_refs);
                    }
                    _ => rebase_refs(value),
                }
            }
        }
        Value::Array(items) => {
            for item in items {
                rebase_refs(item);
            }
        }
        _ => {}
    }
}

/// Hands out tool-call ids `call_{n}` that match no id already used in
/// the history or the reply, so every call result names one call.
struct CallIds {
    used: std::collections::HashSet<String>,
    next: usize,
}

impl CallIds {
    /// Returns the first free id at or after `call_{from}` and reserves
    /// it. The search is bounded: of `used.len() + 1` candidates at
    /// least one is free. Output: the id.
    fn fresh(&mut self, from: usize) -> String {
        self.next = self.next.max(from);
        let bound = self.used.len() + 1;
        for _ in 0..bound {
            let candidate = format!("call_{}", self.next);
            self.next += 1;
            if self.used.insert(candidate.clone()) {
                return candidate;
            }
        }
        unreachable!("one of {bound} call ids must be free");
    }
}

/// Turns host `reply` into message parts: the emulated JSON envelope
/// when tools are emulated, else the text and any native tool calls.
/// Generated call ids start at the count of prior calls in `req` and skip
/// every id in the history or the reply, so a replayed step gets the same
/// ids. Output: the parts, or `None` when the reply does not parse.
pub(crate) fn parse(
    req: &CompletionRequest,
    caps: &HostModelCaps,
    reply: &HostReply,
) -> Option<Vec<ContentPart>> {
    let history: Vec<&str> = req
        .messages
        .iter()
        .flat_map(|m| &m.parts)
        .filter_map(|p| match p {
            ContentPart::ToolCall { id, .. } => Some(id.as_str()),
            _ => None,
        })
        .collect();
    let prior = history.len();
    let mut ids = CallIds {
        used: history.into_iter().map(str::to_string).collect(),
        next: prior,
    };
    if !caps.tools && !req.tools.is_empty() {
        return parse_envelope(req, &reply.text, &mut ids).map(|part| vec![part]);
    }
    let mut parts = Vec::new();
    if !reply.text.is_empty() {
        parts.push(ContentPart::Text {
            text: reply.text.clone(),
        });
    }
    if let Some(calls) = &reply.tool_calls_json {
        let Ok(Value::Array(calls)) = serde_json::from_str::<Value>(calls) else {
            return None;
        };
        let explicit = |call: &Value| {
            call.get("id")
                .and_then(Value::as_str)
                .filter(|id| !id.is_empty())
                .map(str::to_string)
        };
        ids.used.extend(calls.iter().filter_map(explicit));
        for (index, call) in calls.iter().enumerate() {
            let name = call.get("name")?.as_str()?.to_string();
            let arguments = call.get("arguments").cloned().unwrap_or_else(|| json!({}));
            let id = match explicit(call) {
                Some(id) => id,
                None => ids.fresh(prior + index),
            };
            parts.push(ContentPart::ToolCall {
                id,
                name,
                arguments,
            });
        }
    }
    if parts.is_empty() {
        parts.push(ContentPart::Text {
            text: String::new(),
        });
    }
    Some(parts)
}

fn parse_envelope(req: &CompletionRequest, text: &str, ids: &mut CallIds) -> Option<ContentPart> {
    let body = text.trim();
    let body = body
        .strip_prefix("```json")
        .or_else(|| body.strip_prefix("```"))
        .and_then(|b| b.strip_suffix("```"))
        .unwrap_or(body)
        .trim();
    let Value::Object(object) = serde_json::from_str::<Value>(body).ok()? else {
        return None;
    };
    if let Some(name) = object.get("tool").and_then(Value::as_str) {
        if !req.tools.iter().any(|t| t.name == name) {
            return None;
        }
        let arguments = object.get("arguments")?.clone();
        if !arguments.is_object() {
            return None;
        }
        let from = ids.next;
        return Some(ContentPart::ToolCall {
            id: ids.fresh(from),
            name: name.to_string(),
            arguments,
        });
    }
    let text = match object.get("answer")? {
        Value::String(answer) if !typed_answer(req.output_schema.as_ref()) => answer.clone(),
        other => other.to_string(),
    };
    Some(ContentPart::Text { text })
}