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
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
//! The HTTP client: one route, one credential, one meter.

use std::collections::HashMap;
use std::io::Read as _;
use std::sync::mpsc::Sender;
use std::sync::Arc;
use std::thread::sleep;
use std::time::Duration;

use serde_json::Value;

use crate::catalog::{self, ApiStyle, Auth};
use crate::encode::{self, Wire};
use crate::meter::Meter;
use crate::{Chunk, Error, OAuthTokenProvider, Provider, Request, Response, Result, Usage};

/// How many times a transient failure is worth repeating, and how long to wait
/// first. A server that sends `Retry-After` overrides the delay.
#[derive(Clone, Copy, Debug)]
pub struct Retry {
    pub attempts: u32,
    pub backoff: Duration,
}

impl Default for Retry {
    fn default() -> Self {
        Self {
            attempts: 2,
            backoff: Duration::from_millis(600),
        }
    }
}

impl Retry {
    /// Never retry. Appropriate when the caller drives its own loop.
    pub const NONE: Retry = Retry {
        attempts: 0,
        backoff: Duration::ZERO,
    };

    fn delay(&self, attempt: u32, asked: Option<Duration>) -> Duration {
        // Exponential, but a server that named a wait always wins.
        asked.unwrap_or(self.backoff * 2_u32.pow(attempt.min(4)))
    }
}

enum Credential {
    None,
    ApiKey(String),
    Bearer(String),
    OAuth(Arc<dyn OAuthTokenProvider>),
}

pub struct ClientBuilder {
    provider: String,
    api: ApiStyle,
    url: String,
    key_env: Option<String>,
    key: Option<String>,
    bearer_token: Option<String>,
    oauth: Option<Arc<dyn OAuthTokenProvider>>,
    model: String,
    side_model: Option<String>,
    reasoning_effort: Option<String>,
    default_max_tokens: u32,
    accepts_output_limit: bool,
    headers: Vec<(String, String)>,
    connect_timeout: Duration,
    read_timeout: Duration,
    retry: Retry,
}

impl ClientBuilder {
    pub fn new(provider: &str, model: impl Into<String>) -> Result<Self> {
        let spec = catalog::provider(provider).ok_or_else(|| {
            Error::Config(format!(
                "unknown provider `{provider}`; built in: {}",
                catalog::PROVIDERS
                    .iter()
                    .map(|spec| spec.id)
                    .collect::<Vec<_>>()
                    .join(", ")
            ))
        })?;
        Ok(Self {
            key_env: match spec.auth {
                Auth::Key(name) => Some(name.to_string()),
                Auth::Local => None,
            },
            ..Self::custom(spec.id, spec.api, spec.url, model)
        })
    }

    /// A route that is not in the built-in provider table.
    pub fn custom(
        label: impl Into<String>,
        api: ApiStyle,
        url: impl Into<String>,
        model: impl Into<String>,
    ) -> Self {
        Self {
            provider: label.into(),
            api,
            url: url.into(),
            key_env: None,
            key: None,
            bearer_token: None,
            oauth: None,
            model: model.into(),
            side_model: None,
            reasoning_effort: None,
            default_max_tokens: 1024,
            accepts_output_limit: true,
            headers: Vec::new(),
            connect_timeout: Duration::from_secs(20),
            // Streaming replies can pause between tokens; be generous.
            read_timeout: Duration::from_secs(180),
            retry: Retry::default(),
        }
    }

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

    /// Read the key from a different environment variable than the catalog's.
    pub fn api_key_env(mut self, name: impl Into<String>) -> Self {
        self.key_env = Some(name.into());
        self
    }

    /// A ready-made access token, used verbatim as `Authorization: Bearer`.
    pub fn bearer_token(mut self, token: impl Into<String>) -> Self {
        self.bearer_token = Some(token.into());
        self
    }

    /// A credential the client can refresh; see [`OAuthTokenProvider`].
    pub fn oauth(mut self, provider: Arc<dyn OAuthTokenProvider>) -> Self {
        self.oauth = Some(provider);
        self
    }

    /// The cheaper model used for [`Request::side_call`] work.
    pub fn side_model(mut self, model: impl Into<String>) -> Self {
        self.side_model = Some(model.into());
        self
    }

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

    /// Anthropic requires an output limit on every request; this is what is
    /// sent when a request does not name one.
    pub fn default_max_tokens(mut self, tokens: u32) -> Self {
        self.default_max_tokens = tokens;
        self
    }

    /// Declare that this endpoint refuses an output limit, so
    /// [`Request::max_output_tokens`] is left out of the body rather than sent
    /// and rejected. Default is `true`, which is right for every documented API.
    ///
    /// This exists for endpoints that are not the documented API — the Codex
    /// backend behind the ChatGPT subscription answers `HTTP 400: Unsupported
    /// parameter: max_output_tokens`. `Subscription::client` already sets it
    /// (with the `oauth` feature), so applications on that route need do
    /// nothing.
    ///
    /// [`Request::max_output_tokens`]: crate::Request::max_output_tokens
    pub fn accepts_output_limit(mut self, accepts: bool) -> Self {
        self.accepts_output_limit = accepts;
        self
    }

    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }

    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = timeout;
        self
    }

    pub fn read_timeout(mut self, timeout: Duration) -> Self {
        self.read_timeout = timeout;
        self
    }

    pub fn retry(mut self, retry: Retry) -> Self {
        self.retry = retry;
        self
    }

    pub fn build(self) -> Result<Client> {
        let alternate = self.oauth.is_some()
            || self
                .bearer_token
                .as_deref()
                .is_some_and(|token| !token.trim().is_empty());
        let key = match (self.key, self.key_env.as_deref(), alternate) {
            (_, _, true) => None,
            (Some(key), _, false) if !key.trim().is_empty() => Some(key),
            (_, Some(name), false) => {
                Some(std::env::var(name).map_err(|_| Error::Config(format!("{name} is not set")))?)
                    .filter(|key| !key.trim().is_empty())
            }
            _ => None,
        };
        if self.key_env.is_some() && key.is_none() && !alternate {
            return Err(Error::Config(format!(
                "{} is empty",
                self.key_env.unwrap_or_default()
            )));
        }

        let credential = if let Some(provider) = self.oauth {
            Credential::OAuth(provider)
        } else if let Some(token) = self.bearer_token.filter(|token| !token.trim().is_empty()) {
            Credential::Bearer(token)
        } else if let Some(key) = key {
            Credential::ApiKey(key)
        } else {
            Credential::None
        };

        Ok(Client {
            agent: ureq::AgentBuilder::new()
                .timeout_connect(self.connect_timeout)
                .timeout_read(self.read_timeout)
                .build(),
            provider: self.provider,
            api: self.api,
            url: self.url,
            credential,
            model: self.model,
            side_model: self.side_model,
            reasoning_effort: self.reasoning_effort,
            default_max_tokens: self.default_max_tokens,
            accepts_output_limit: self.accepts_output_limit,
            headers: self.headers,
            retry: self.retry,
            meter: Meter::default(),
        })
    }
}

/// A configured route to one provider.
///
/// `Client` implements [`Provider`], so an application can hold
/// `Arc<dyn Provider>` and never learn which vendor is behind it.
pub struct Client {
    agent: ureq::Agent,
    provider: String,
    api: ApiStyle,
    url: String,
    credential: Credential,
    model: String,
    side_model: Option<String>,
    reasoning_effort: Option<String>,
    default_max_tokens: u32,
    accepts_output_limit: bool,
    headers: Vec<(String, String)>,
    retry: Retry,
    meter: Meter,
}

impl Client {
    pub fn builder(provider: &str, model: impl Into<String>) -> Result<ClientBuilder> {
        ClientBuilder::new(provider, model)
    }

    /// A route whose key comes from the provider's usual environment variable.
    pub fn from_env(provider: &str, model: impl Into<String>) -> Result<Self> {
        Self::builder(provider, model)?.build()
    }

    /// The same, on the provider's default model.
    pub fn default_for(provider: &str) -> Result<Self> {
        let spec = catalog::provider(provider)
            .ok_or_else(|| Error::Config(format!("unknown provider `{provider}`")))?;
        Self::from_env(provider, spec.default_model)
    }

    /// Any OpenAI-compatible chat-completions endpoint.
    pub fn compatible(
        url: impl Into<String>,
        model: impl Into<String>,
        key: impl Into<String>,
    ) -> Result<Self> {
        ClientBuilder::custom("compatible", ApiStyle::ChatCompletions, url, model)
            .api_key(key)
            .build()
    }

    /// Which provider id this route uses.
    pub fn provider(&self) -> &str {
        &self.provider
    }

    /// The default model for requests that do not override it.
    pub fn model(&self) -> &str {
        &self.model
    }

    /// Run a request to completion, keeping text, tool calls, and usage.
    pub fn complete(&self, request: &Request) -> Result<Response> {
        let before = self.meter.snapshot();
        let mut response = crate::complete(self, request)?;
        let after = self.meter.snapshot();
        response.usage.cost_micros = after.cost_micros.saturating_sub(before.cost_micros);
        response.usage.est_micros = after.est_micros.saturating_sub(before.est_micros);
        response.usage.unpriced_calls = after.unpriced_calls.saturating_sub(before.unpriced_calls);
        Ok(response)
    }

    /// Run a request and parse the first JSON object out of the reply, which is
    /// what "answer in JSON" prompts actually produce once a model adds a
    /// sentence or a code fence around it.
    pub fn complete_json(&self, request: &Request) -> Result<Value> {
        let text = self.complete(request)?.text;
        crate::extract_json(&text).ok_or_else(|| {
            Error::Decode(format!(
                "no JSON object in the reply: {}",
                text.chars().take(160).collect::<String>()
            ))
        })
    }

    /// The exact body this request would send. Useful in tests and when
    /// reporting a provider bug.
    pub fn request_body(&self, request: &Request) -> Value {
        encode::body(&self.wire(request), request)
    }

    fn wire<'a>(&'a self, request: &'a Request) -> Wire<'a> {
        Wire {
            api: self.api,
            model: self.resolved_model(request),
            reasoning_effort: self.effort(request),
            default_max_tokens: self.default_max_tokens,
            accepts_output_limit: self.accepts_output_limit,
        }
    }

    /// Side models are commonly smaller or older models that do not implement
    /// an effort parameter, and side calls are lightweight by design. Omitting
    /// effort there is both more compatible and less surprising.
    fn effort(&self, request: &Request) -> Option<&str> {
        if request.side_call && self.api == ApiStyle::Anthropic {
            return None;
        }
        self.reasoning_effort
            .as_deref()
            .filter(|effort| !effort.is_empty() && *effort != "none")
    }

    fn resolved_model<'a>(&'a self, request: &'a Request) -> &'a str {
        if request.side_call {
            self.side_model
                .as_deref()
                .filter(|model| !model.trim().is_empty())
                .unwrap_or(&self.model)
        } else {
            request.model.as_deref().unwrap_or(&self.model)
        }
    }

    /// Send, refreshing a refreshable credential once and retrying transient
    /// failures. Nothing has been written to `tx` when a retry happens: every
    /// retryable failure is detected before the response body is read.
    fn send(&self, request: &Request, tx: &Sender<Chunk>) -> Result<()> {
        let mut attempt = 0;
        loop {
            if request.cancelled() {
                return Err(Error::Cancelled);
            }
            match self.attempt(request, tx, None) {
                Ok(()) => return Ok(()),
                Err(error) if error.is_auth() => return self.refresh_and_retry(request, tx, error),
                Err(error) if error.retryable() && attempt < self.retry.attempts => {
                    sleep(self.retry.delay(attempt, error.retry_after()));
                    attempt += 1;
                }
                Err(error) => return Err(error),
            }
        }
    }

    fn refresh_and_retry(
        &self,
        request: &Request,
        tx: &Sender<Chunk>,
        rejected: Error,
    ) -> Result<()> {
        let Credential::OAuth(provider) = &self.credential else {
            return Err(rejected);
        };
        let token = provider
            .refresh_access_token()
            .map_err(|error| Error::Auth(format!("OAuth refresh failed: {error}")))?;
        if token.trim().is_empty() {
            return Err(Error::Auth(
                "OAuth refresh returned an empty access token".into(),
            ));
        }
        self.attempt(request, tx, Some(&token)).map_err(|error| {
            if error.is_auth() {
                Error::Auth("credential rejected after one refresh".into())
            } else {
                error
            }
        })
    }

    fn attempt(
        &self,
        request: &Request,
        tx: &Sender<Chunk>,
        refreshed_token: Option<&str>,
    ) -> Result<()> {
        let mut call = self
            .agent
            .post(&self.url)
            .set("content-type", "application/json")
            .set("accept", "text/event-stream");
        if let Some((name, value)) = self.credential_header(refreshed_token)? {
            call = call.set(name, &value);
        }
        if self.api == ApiStyle::Anthropic {
            call = call.set("anthropic-version", ANTHROPIC_VERSION);
        }
        for (name, value) in &self.headers {
            call = call.set(name, value);
        }

        match call.send_json(self.request_body(request)) {
            Ok(response) => {
                let cancel = request.cancel.as_deref();
                let reader = response.into_reader();
                let tally = match self.api {
                    ApiStyle::Responses => crate::stream::responses(reader, tx, cancel),
                    ApiStyle::Anthropic => crate::stream::anthropic(reader, tx, cancel),
                    ApiStyle::ChatCompletions => crate::stream::chat(reader, tx, cancel),
                };
                let model = self.resolved_model(request);
                self.meter.record(
                    &format!("{}/{model}", self.provider),
                    model,
                    tally.input,
                    tally.output,
                    tally.cost_micros,
                );
                Ok(())
            }
            Err(ureq::Error::Status(status, response)) => {
                let retry_after = response
                    .header("retry-after")
                    .and_then(|value| value.trim().parse::<u64>().ok())
                    .map(Duration::from_secs);
                let mut body = String::new();
                let _ = response.into_reader().take(4096).read_to_string(&mut body);
                let message = summarize_error(&body);
                Err(match status {
                    401 | 403 => Error::Auth(format!(
                        "HTTP {status}: credential rejected by {} ({message})",
                        self.provider
                    )),
                    429 => Error::RateLimited {
                        message,
                        retry_after,
                    },
                    _ => Error::Api { status, message },
                })
            }
            Err(error) if self.provider == "ollama" => Err(Error::Network(format!(
                "{error}. Is Ollama running? Try `ollama serve`."
            ))),
            Err(error) => Err(Error::Network(error.to_string())),
        }
    }

    fn credential_header(
        &self,
        refreshed_token: Option<&str>,
    ) -> Result<Option<(&'static str, String)>> {
        if let Some(token) = refreshed_token {
            return Ok(Some(("authorization", format!("Bearer {token}"))));
        }
        match &self.credential {
            Credential::None => Ok(None),
            Credential::ApiKey(key) if self.api == ApiStyle::Anthropic => {
                Ok(Some(("x-api-key", key.clone())))
            }
            Credential::ApiKey(key) | Credential::Bearer(key) => {
                Ok(Some(("authorization", format!("Bearer {key}"))))
            }
            Credential::OAuth(provider) => {
                let token = provider
                    .access_token()
                    .map_err(|error| Error::Auth(format!("no OAuth access token: {error}")))?;
                if token.trim().is_empty() {
                    Err(Error::Auth(
                        "OAuth provider returned an empty access token".into(),
                    ))
                } else {
                    Ok(Some(("authorization", format!("Bearer {token}"))))
                }
            }
        }
    }
}

const ANTHROPIC_VERSION: &str = "2023-06-01";

impl Provider for Client {
    fn stream(&self, request: &Request, sender: &Sender<Chunk>) -> Result<()> {
        self.send(request, sender)
    }

    fn label(&self) -> String {
        format!("{}/{}", self.provider, self.model)
    }

    fn usage(&self) -> Usage {
        self.meter.snapshot()
    }

    fn usage_by_model(&self) -> HashMap<String, Usage> {
        self.meter.by_model()
    }
}

/// The human-readable part of an error body, without echoing anything that
/// might be a credential.
fn summarize_error(body: &str) -> String {
    if let Ok(value) = serde_json::from_str::<Value>(body) {
        if let Some(message) = value
            .pointer("/error/message")
            .and_then(Value::as_str)
            .or_else(|| value.get("detail").and_then(Value::as_str))
            .or_else(|| value.get("message").and_then(Value::as_str))
        {
            return message.to_string();
        }
    }
    let body = body.trim();
    if body.is_empty() {
        "no response body".into()
    } else {
        body.chars().take(300).collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::message::{Message, ToolCall};
    use crate::request::{Cancel, ToolSchema};
    use serde_json::json;
    use std::io::{Read, Write};
    use std::net::{TcpListener, TcpStream};
    use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
    use std::sync::Mutex;
    use std::thread;

    struct RefreshingTokens {
        token: Mutex<String>,
        refreshes: AtomicUsize,
    }

    impl OAuthTokenProvider for RefreshingTokens {
        fn access_token(&self) -> std::result::Result<String, String> {
            Ok(self.token.lock().unwrap().clone())
        }

        fn refresh_access_token(&self) -> std::result::Result<String, String> {
            self.refreshes.fetch_add(1, AtomicOrdering::Relaxed);
            let mut token = self.token.lock().unwrap();
            *token = "fresh-token".into();
            Ok(token.clone())
        }
    }

    fn request() -> Request {
        Request::new("Be concise")
            .user("Hello")
            .max_output_tokens(50)
    }

    fn keyed(provider: &str) -> Client {
        ClientBuilder::new(provider, "test")
            .unwrap()
            .api_key("key")
            .build()
            .unwrap()
    }

    const OK_STREAM: &str = concat!(
        "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n",
        "data: {\"choices\":[{\"delta\":{\"content\":\"Hello from Modelbridge\"}}]}\n\n",
        "data: {\"choices\":[],\"usage\":{\"prompt_tokens\":7,\"completion_tokens\":3}}\n\n",
        "data: [DONE]\n\n",
    );

    fn read_request(socket: &mut TcpStream) -> String {
        let mut received = Vec::new();
        let mut buffer = [0_u8; 2048];
        loop {
            let count = socket.read(&mut buffer).unwrap();
            if count == 0 {
                break;
            }
            received.extend_from_slice(&buffer[..count]);
            let request = String::from_utf8_lossy(&received);
            if request.contains("\r\n\r\n") && request.contains("Hello") {
                break;
            }
        }
        String::from_utf8_lossy(&received).into_owned()
    }

    /// A server that answers each connection with the next scripted response.
    fn serve(responses: Vec<String>) -> (String, thread::JoinHandle<Vec<String>>) {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap().to_string();
        let handle = thread::spawn(move || {
            let mut seen = Vec::new();
            for response in responses {
                let (mut socket, _) = listener.accept().unwrap();
                seen.push(read_request(&mut socket));
                let _ = socket.write_all(response.as_bytes());
            }
            seen
        });
        (address, handle)
    }

    fn client_for(address: &str) -> ClientBuilder {
        ClientBuilder::custom(
            "test",
            ApiStyle::ChatCompletions,
            format!("http://{address}/v1/chat/completions"),
            "test-model",
        )
    }

    #[test]
    fn built_in_routes_need_no_url_configuration() {
        for provider in catalog::PROVIDERS {
            assert!(!provider.url.is_empty());
            assert!(!provider.default_model.is_empty());
        }
    }

    #[test]
    fn request_shapes_follow_each_api() {
        assert_eq!(
            keyed("openai").request_body(&request())["instructions"],
            "Be concise"
        );
        assert_eq!(
            keyed("anthropic").request_body(&request())["system"],
            "Be concise"
        );
        assert_eq!(
            keyed("groq").request_body(&request())["messages"][0]["role"],
            "system"
        );
    }

    #[test]
    fn tool_schemas_are_translated_for_each_api() {
        let request = request().tool(ToolSchema::new(
            "weather",
            "Get weather",
            json!({"type": "object"}),
        ));
        assert_eq!(
            keyed("openai").request_body(&request)["tools"][0]["type"],
            "function"
        );
        assert_eq!(
            keyed("anthropic").request_body(&request)["tools"][0]["input_schema"]["type"],
            "object"
        );
        assert_eq!(
            keyed("groq").request_body(&request)["tools"][0]["function"]["name"],
            "weather"
        );
    }

    #[test]
    fn anthropic_side_calls_take_the_side_model_and_omit_effort() {
        let client = ClientBuilder::new("anthropic", "claude-opus-5")
            .unwrap()
            .api_key("key")
            .side_model("claude-haiku-4-5")
            .reasoning_effort("low")
            .build()
            .unwrap();
        assert_eq!(
            client.request_body(&request())["output_config"]["effort"],
            "low"
        );

        let side = client.request_body(&request().side_call(true));
        assert_eq!(side["model"], "claude-haiku-4-5");
        assert!(side.get("output_config").is_none());
    }

    #[test]
    fn arbitrary_models_are_allowed() {
        let client = ClientBuilder::new("openai", "released-tomorrow")
            .unwrap()
            .api_key("key")
            .build()
            .unwrap();
        assert_eq!(
            client.request_body(&request())["model"],
            "released-tomorrow"
        );
    }

    #[test]
    fn a_custom_client_completes_a_real_http_sse_round_trip() {
        let (address, server) = serve(vec![OK_STREAM.into()]);
        let client = Client::compatible(
            format!("http://{address}/v1/chat/completions"),
            "test-model",
            "secret",
        )
        .unwrap();

        let response = client.complete(&request()).unwrap();
        server.join().unwrap();
        assert_eq!(response.text, "Hello from Modelbridge");
        assert_eq!(response.usage.input, 7);
        assert_eq!(response.usage.output, 3);
        assert_eq!(response.usage.unpriced_calls, 1);
    }

    #[test]
    fn oauth_refreshes_once_after_unauthorized_and_retries() {
        let unauthorized =
            "HTTP/1.1 401 Unauthorized\r\ncontent-length: 0\r\nconnection: close\r\n\r\n";
        let (address, server) = serve(vec![unauthorized.into(), OK_STREAM.into()]);
        let tokens = Arc::new(RefreshingTokens {
            token: Mutex::new("stale-token".into()),
            refreshes: AtomicUsize::new(0),
        });
        let client = client_for(&address).oauth(tokens.clone()).build().unwrap();

        assert!(client.complete(&request()).unwrap().text.contains("Hello"));
        let seen = server.join().unwrap();
        assert_eq!(tokens.refreshes.load(AtomicOrdering::Relaxed), 1);
        assert!(seen[0].contains("authorization: Bearer stale-token"));
        assert!(seen[1].contains("authorization: Bearer fresh-token"));
    }

    #[test]
    fn a_rejected_api_key_is_not_retried() {
        let unauthorized =
            "HTTP/1.1 401 Unauthorized\r\ncontent-length: 0\r\nconnection: close\r\n\r\n";
        let (address, server) = serve(vec![unauthorized.into()]);
        let client = client_for(&address).api_key("bad").build().unwrap();

        let error = client.complete(&request()).unwrap_err();
        server.join().unwrap();
        assert!(error.is_auth(), "{error}");
        assert!(!error.retryable());
    }

    #[test]
    fn a_rate_limit_is_retried_after_the_wait_the_server_named() {
        let limited = "HTTP/1.1 429 Too Many Requests\r\nretry-after: 0\r\ncontent-length: 0\r\nconnection: close\r\n\r\n";
        let (address, server) = serve(vec![limited.into(), OK_STREAM.into()]);
        let client = client_for(&address)
            .api_key("key")
            .retry(Retry {
                attempts: 1,
                backoff: Duration::from_millis(1),
            })
            .build()
            .unwrap();

        assert!(client.complete(&request()).unwrap().text.contains("Hello"));
        assert_eq!(server.join().unwrap().len(), 2);
    }

    #[test]
    fn a_rate_limit_gives_up_once_the_attempts_are_spent() {
        let limited = "HTTP/1.1 429 Too Many Requests\r\nretry-after: 0\r\ncontent-length: 0\r\nconnection: close\r\n\r\n";
        let (address, server) = serve(vec![limited.into()]);
        let client = client_for(&address)
            .api_key("key")
            .retry(Retry::NONE)
            .build()
            .unwrap();

        let error = client.complete(&request()).unwrap_err();
        server.join().unwrap();
        assert!(matches!(error, Error::RateLimited { .. }));
    }

    #[test]
    fn a_cancelled_request_never_leaves_the_process() {
        let client = client_for("127.0.0.1:1").api_key("key").build().unwrap();
        let flag = Cancel::default();
        flag.store(true, AtomicOrdering::Relaxed);
        assert_eq!(
            client.complete(&request().cancel(flag)).unwrap_err(),
            Error::Cancelled
        );
    }

    #[test]
    fn a_tool_round_trip_survives_a_second_turn() {
        let call = ToolCall::new("weather", json!({"city": "Porto"})).with_id("call_1");
        let request = request()
            .message(Message::tool_calls("Checking.", vec![call.clone()]))
            .message(Message::tool_results(vec![crate::ToolResult::new(
                &call, 0, "20C",
            )]));
        let body = keyed("groq").request_body(&request);
        let roles: Vec<&str> = body["messages"]
            .as_array()
            .unwrap()
            .iter()
            .map(|message| message["role"].as_str().unwrap())
            .collect();
        assert_eq!(roles, ["system", "user", "assistant", "tool"]);
    }

    #[test]
    fn vendor_errors_are_reduced_to_safe_human_messages() {
        assert_eq!(
            summarize_error(r#"{"error":{"message":"quota exceeded","token":"secret"}}"#),
            "quota exceeded"
        );
        assert_eq!(summarize_error("   "), "no response body");
    }
}