modelbridge 0.5.2

One provider-neutral Rust client for OpenAI, Anthropic, Gemini, Groq, Ollama and friends: streaming, tool calling, an agent loop, usage accounting, and subscription sign-in
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
//! The loop: ask, run whatever tools the model asked for, hand the results
//! back, repeat until it answers.
//!
//! Writing this by hand is where tool-using applications go wrong, because the
//! mistakes are all in the bookkeeping — replaying calls as prose, losing the
//! call id, looping on the same search forever, or streaming a planning
//! paragraph to the user as if it were the answer. [`Agent`] does the
//! bookkeeping; you supply [`Tools`].
//!
//! ```no_run
//! use modelbridge::agent::{Agent, Step, Tools};
//! use modelbridge::{Client, ToolCall, ToolSchema};
//! use serde_json::json;
//!
//! struct Clock;
//!
//! impl Tools for Clock {
//!     fn schemas(&self) -> Vec<ToolSchema> {
//!         vec![ToolSchema::new("now", "The current time", json!({"type": "object"}))]
//!     }
//!
//!     fn run(&mut self, _call: &ToolCall) -> Result<String, String> {
//!         Ok("2026-08-05T09:00:00Z".into())
//!     }
//! }
//!
//! let client = Client::default_for("anthropic")?;
//! let mut agent = Agent::new(&client, Clock).instructions("Answer with tools when they help.");
//! let answer = agent.ask("What time is it?", &mut |step| {
//!     if let Step::Token(text) = step {
//!         print!("{text}");
//!     }
//! })?;
//! println!("\n{} tokens", answer.usage.total());
//! # Ok::<(), modelbridge::Error>(())
//! ```

use std::sync::mpsc::channel;

use crate::message::{Message, ToolCall, ToolResult};
use crate::request::{Cancel, ToolSchema};
use crate::{Chunk, Error, Provider, Request, Result, Usage};

/// The tools an agent may call.
///
/// `run` returns `Err` for a call that failed in a way the model should know
/// about and could work around — a page that would not load, a path outside
/// the workspace. That is reported as a failed tool call rather than as
/// output, so the model tries something else instead of quoting the error back
/// as a fact.
pub trait Tools {
    fn schemas(&self) -> Vec<ToolSchema>;
    fn run(&mut self, call: &ToolCall) -> std::result::Result<String, String>;
}

/// So that an application which owns its tool set can lend it to an agent
/// built for one question rather than handing over the only copy.
impl<T: Tools + ?Sized> Tools for &mut T {
    fn schemas(&self) -> Vec<ToolSchema> {
        (**self).schemas()
    }

    fn run(&mut self, call: &ToolCall) -> std::result::Result<String, String> {
        (**self).run(call)
    }
}

/// No tools at all, for a plain multi-turn conversation.
pub struct NoTools;

impl Tools for NoTools {
    fn schemas(&self) -> Vec<ToolSchema> {
        Vec::new()
    }

    fn run(&mut self, call: &ToolCall) -> std::result::Result<String, String> {
        Err(format!("no tool named `{}`", call.name))
    }
}

/// What the agent is doing, reported as it happens.
#[derive(Clone, Copy, Debug)]
pub enum Step<'a> {
    /// A model turn is starting. Zero on the first.
    Turn(usize),
    /// A piece of the model's text, as it streams.
    Token(&'a str),
    /// That turn ended in tool calls, so the text it streamed was planning
    /// rather than the answer. Interfaces that showed the tokens should clear
    /// them.
    Planning(&'a str),
    Calling(&'a ToolCall),
    Called(&'a ToolResult),
}

/// A finished run.
#[derive(Clone, Debug, Default)]
pub struct Answer {
    pub text: String,
    /// Usage for this run alone.
    pub usage: Usage,
    /// How many model turns it took.
    pub turns: usize,
}

/// A conversation that can call tools.
pub struct Agent<'a, T: Tools> {
    provider: &'a dyn Provider,
    tools: T,
    instructions: String,
    max_turns: usize,
    max_output_tokens: Option<u32>,
    model: Option<String>,
    cancel: Option<Cancel>,
    history: Vec<Message>,
}

impl<'a, T: Tools> Agent<'a, T> {
    pub fn new(provider: &'a dyn Provider, tools: T) -> Self {
        Self {
            provider,
            tools,
            instructions: String::new(),
            max_turns: 8,
            max_output_tokens: None,
            model: None,
            cancel: None,
            history: Vec::new(),
        }
    }

    /// The system prompt. Set it per run when it carries the date or other
    /// changing context.
    pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
        self.instructions = instructions.into();
        self
    }

    /// How many model turns one question may take before the agent stops
    /// calling tools and demands an answer.
    pub fn max_turns(mut self, turns: usize) -> Self {
        self.max_turns = turns.max(1);
        self
    }

    pub fn max_output_tokens(mut self, tokens: u32) -> Self {
        self.max_output_tokens = Some(tokens);
        self
    }

    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    pub fn cancel(mut self, cancel: Cancel) -> Self {
        self.cancel = Some(cancel);
        self
    }

    /// Resume an earlier conversation. Pair it with [`Agent::into_history`]
    /// when the agent is rebuilt per question rather than held for a session.
    pub fn history(mut self, history: Vec<Message>) -> Self {
        self.history = history;
        self
    }

    pub fn set_instructions(&mut self, instructions: impl Into<String>) {
        self.instructions = instructions.into();
    }

    /// Everything said so far, tool calls included.
    pub fn transcript(&self) -> &[Message] {
        &self.history
    }

    /// Take the conversation back, to hand to the next agent.
    pub fn into_history(self) -> Vec<Message> {
        self.history
    }

    /// Start again with an empty conversation.
    pub fn clear(&mut self) {
        self.history.clear();
    }

    pub fn tools(&self) -> &T {
        &self.tools
    }

    pub fn tools_mut(&mut self) -> &mut T {
        &mut self.tools
    }

    fn cancelled(&self) -> bool {
        self.cancel
            .as_ref()
            .is_some_and(|flag| flag.load(std::sync::atomic::Ordering::Relaxed))
    }

    fn request(&self, messages: Vec<Message>, tools: Vec<ToolSchema>) -> Request {
        let mut request = Request::new(self.instructions.clone())
            .messages(messages)
            .tools(tools);
        if let Some(tokens) = self.max_output_tokens {
            request = request.max_output_tokens(tokens);
        }
        if let Some(model) = &self.model {
            request = request.model(model.clone());
        }
        if let Some(cancel) = &self.cancel {
            request = request.cancel(cancel.clone());
        }
        request
    }

    /// Answer one question, appending the exchange to the agent's history.
    ///
    /// `observe` sees every token and every tool call as they happen; pass
    /// `&mut |_| {}` to ignore them.
    pub fn ask(&mut self, question: &str, observe: &mut dyn FnMut(Step)) -> Result<Answer> {
        let mut messages = self.history.clone();
        messages.push(Message::user(question));

        let mut answer = Answer::default();
        // The same call with the same arguments twice means the model has lost
        // the thread. Answering it a second time teaches it nothing.
        let mut already_run: Vec<String> = Vec::new();

        for turn in 0..self.max_turns {
            if self.cancelled() {
                return Err(Error::Cancelled);
            }
            observe(Step::Turn(turn));
            answer.turns = turn + 1;

            let request = self.request(messages.clone(), self.tools.schemas());
            let (text, calls, usage) = self.turn(&request, observe)?;
            answer.usage = answer.usage + usage;

            if calls.is_empty() {
                answer.text = text;
                messages.push(Message::assistant(&answer.text));
                self.history = messages;
                return Ok(answer);
            }

            observe(Step::Planning(&text));
            let called = Message::tool_calls(text, calls);
            let mut results = Vec::new();
            for (index, call) in called.calls.iter().enumerate() {
                if self.cancelled() {
                    return Err(Error::Cancelled);
                }
                observe(Step::Calling(call));
                let signature = format!("{}{}", call.name, call.args);
                let result = if already_run.contains(&signature) {
                    ToolResult::failure(
                        call,
                        index,
                        "You already ran this exact call. Use what it returned, try different \
                         arguments, or answer now.",
                    )
                } else {
                    already_run.push(signature);
                    match self.tools.run(call) {
                        Ok(output) => ToolResult::new(call, index, output),
                        Err(message) => ToolResult::failure(call, index, message),
                    }
                };
                observe(Step::Called(&result));
                results.push(result);
            }
            messages.push(called);
            messages.push(Message::tool_results(results));
        }

        // Out of turns with tools still being called. Ask once more with no
        // tools offered, so the model has to answer from what it gathered.
        observe(Step::Turn(self.max_turns));
        let mut closing = messages.clone();
        closing.push(Message::user(
            "Answer now with what you have gathered. Do not call any more tools.",
        ));
        let request = self.request(closing, Vec::new());
        let (text, _, usage) = self.turn(&request, observe)?;
        answer.usage = answer.usage + usage;
        answer.text = text;
        messages.push(Message::assistant(&answer.text));
        self.history = messages;
        Ok(answer)
    }

    /// One model turn, streamed. The provider runs on a scoped thread so text
    /// reaches `observe` as it arrives rather than after the turn ends.
    fn turn(
        &self,
        request: &Request,
        observe: &mut dyn FnMut(Step),
    ) -> Result<(String, Vec<ToolCall>, Usage)> {
        let (tx, rx) = channel::<Chunk>();
        let provider = self.provider;

        std::thread::scope(|scope| {
            let sending = scope.spawn(move || {
                let result = provider.stream(request, &tx);
                drop(tx);
                result
            });

            let mut text = String::new();
            let mut calls = Vec::new();
            let mut usage = Usage::default();
            let mut failure = None;
            for chunk in rx {
                match chunk {
                    Chunk::Text(piece) => {
                        observe(Step::Token(&piece));
                        text.push_str(&piece);
                    }
                    Chunk::Tool(call) => calls.push(call),
                    Chunk::Done {
                        input_tokens,
                        output_tokens,
                    } => {
                        usage.input = input_tokens as u64;
                        usage.output = output_tokens as u64;
                        usage.calls = 1;
                    }
                    Chunk::Failed(error) => failure = Some(error),
                }
            }

            sending
                .join()
                .map_err(|_| Error::Stream("the model stream panicked".into()))??;
            match failure {
                Some(error) if text.trim().is_empty() && calls.is_empty() => Err(error),
                _ => Ok((text, calls, usage)),
            }
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::request::ToolSchema;
    use serde_json::json;
    use std::sync::mpsc::Sender;
    use std::sync::Mutex;

    /// A provider that replays a script: one entry per turn.
    struct Script {
        turns: Mutex<Vec<(String, Vec<ToolCall>)>>,
        /// Every request body the agent sent, for inspecting the conversation.
        seen: Mutex<Vec<Request>>,
    }

    impl Script {
        fn new(turns: Vec<(&str, Vec<ToolCall>)>) -> Self {
            Self {
                turns: Mutex::new(
                    turns
                        .into_iter()
                        .map(|(text, calls)| (text.to_string(), calls))
                        .collect(),
                ),
                seen: Mutex::new(Vec::new()),
            }
        }
    }

    impl Provider for Script {
        fn stream(&self, request: &Request, sender: &Sender<Chunk>) -> Result<()> {
            self.seen.lock().unwrap().push(request.clone());
            let mut turns = self.turns.lock().unwrap();
            let (text, calls) = if turns.is_empty() {
                ("out of script".to_string(), Vec::new())
            } else {
                turns.remove(0)
            };
            if !text.is_empty() {
                sender.send(Chunk::Text(text)).unwrap();
            }
            for call in calls {
                sender.send(Chunk::Tool(call)).unwrap();
            }
            sender
                .send(Chunk::Done {
                    input_tokens: 5,
                    output_tokens: 2,
                })
                .unwrap();
            Ok(())
        }

        fn label(&self) -> String {
            "script".into()
        }
    }

    #[derive(Default)]
    struct Counter {
        runs: Vec<String>,
        fail: bool,
    }

    impl Tools for Counter {
        fn schemas(&self) -> Vec<ToolSchema> {
            vec![ToolSchema::new(
                "search",
                "Search",
                json!({"type": "object"}),
            )]
        }

        fn run(&mut self, call: &ToolCall) -> std::result::Result<String, String> {
            self.runs.push(call.args.to_string());
            if self.fail {
                Err("the page would not load".into())
            } else {
                Ok(format!("results for {}", call.args))
            }
        }
    }

    fn search(query: &str) -> ToolCall {
        ToolCall::new("search", json!({ "q": query }))
    }

    #[test]
    fn a_tool_call_is_run_and_its_output_is_fed_back() {
        let script = Script::new(vec![
            ("Looking it up.", vec![search("rust gats")]),
            ("Generic associated types.", Vec::new()),
        ]);
        let mut agent = Agent::new(&script, Counter::default()).instructions("Be brief");

        let answer = agent.ask("what are gats?", &mut |_| {}).unwrap();

        assert_eq!(answer.text, "Generic associated types.");
        assert_eq!(answer.turns, 2);
        assert_eq!(answer.usage.calls, 2);
        assert_eq!(agent.tools().runs, [r#"{"q":"rust gats"}"#]);

        // The second request replayed the call and its result as real turns,
        // with matching ids — not as prose.
        let second = &script.seen.lock().unwrap()[1];
        let called = &second.messages[1];
        let answered = &second.messages[2];
        assert_eq!(called.calls[0].name, "search");
        assert_eq!(answered.results[0].id, called.calls[0].id);
        assert!(answered.results[0].output.contains("results for"));
    }

    #[test]
    fn a_repeated_call_is_refused_rather_than_run_twice() {
        let script = Script::new(vec![
            ("", vec![search("same")]),
            ("", vec![search("same")]),
            ("Answering.", Vec::new()),
        ]);
        let mut agent = Agent::new(&script, Counter::default());

        agent.ask("q", &mut |_| {}).unwrap();
        assert_eq!(agent.tools().runs.len(), 1, "the tool ran once");

        let third = &script.seen.lock().unwrap()[2];
        let refusal = third
            .messages
            .iter()
            .flat_map(|message| &message.results)
            .find(|result| result.failed)
            .expect("the repeat was reported as a failed call");
        assert!(refusal.output.contains("already ran"));
    }

    #[test]
    fn a_failing_tool_is_reported_to_the_model_as_a_failure() {
        let script = Script::new(vec![
            ("", vec![search("x")]),
            ("Could not check.", Vec::new()),
        ]);
        let tools = Counter {
            fail: true,
            ..Counter::default()
        };
        let mut agent = Agent::new(&script, tools);

        let mut failures = 0;
        agent
            .ask("q", &mut |step| {
                if matches!(step, Step::Called(result) if result.failed) {
                    failures += 1;
                }
            })
            .unwrap();
        assert_eq!(failures, 1);
    }

    #[test]
    fn running_out_of_turns_forces_an_answer_without_tools() {
        let script = Script::new(vec![
            ("", vec![search("one")]),
            ("", vec![search("two")]),
            ("Here is what I found.", Vec::new()),
        ]);
        let mut agent = Agent::new(&script, Counter::default()).max_turns(2);

        let answer = agent.ask("q", &mut |_| {}).unwrap();
        assert_eq!(answer.text, "Here is what I found.");

        let closing = script.seen.lock().unwrap().last().unwrap().clone();
        assert!(closing.tools.is_empty(), "no tools were offered");
        assert!(closing.messages.last().unwrap().text.contains("Answer now"));
    }

    #[test]
    fn tokens_and_planning_are_reported_separately() {
        let script = Script::new(vec![
            ("Let me check.", vec![search("x")]),
            ("The answer.", Vec::new()),
        ]);
        let mut agent = Agent::new(&script, Counter::default());

        let (mut tokens, mut planning) = (String::new(), String::new());
        agent
            .ask("q", &mut |step| match step {
                Step::Token(text) => tokens.push_str(text),
                Step::Planning(text) => planning.push_str(text),
                _ => {}
            })
            .unwrap();

        assert_eq!(tokens, "Let me check.The answer.");
        assert_eq!(planning, "Let me check.");
    }

    #[test]
    fn history_carries_the_conversation_into_the_next_question() {
        let script = Script::new(vec![("First.", Vec::new()), ("Second.", Vec::new())]);
        let mut agent = Agent::new(&script, NoTools);

        agent.ask("one", &mut |_| {}).unwrap();
        agent.ask("two", &mut |_| {}).unwrap();

        assert_eq!(agent.transcript().len(), 4);
        assert_eq!(script.seen.lock().unwrap()[1].messages.len(), 3);

        agent.clear();
        assert!(agent.transcript().is_empty());
    }

    #[test]
    fn a_raised_cancel_flag_stops_before_the_first_request() {
        let script = Script::new(vec![("never", Vec::new())]);
        let cancel = Cancel::default();
        cancel.store(true, std::sync::atomic::Ordering::Relaxed);
        let mut agent = Agent::new(&script, NoTools).cancel(cancel);

        assert!(matches!(agent.ask("q", &mut |_| {}), Err(Error::Cancelled)));
        assert!(script.seen.lock().unwrap().is_empty());
    }
}