modelrelay 1.5.0

Rust SDK for the ModelRelay API
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
# ModelRelay Rust SDK

The ModelRelay Rust SDK is a **responses-first**, **streaming-first** client for building cross-provider LLM features without committing to any single vendor API.

It’s designed to feel great in Rust:
- One fluent builder (`ResponseBuilder`) for **sync/async**, **streaming/non-streaming**, **text/structured**, and **customer-attributed** requests.
- Structured outputs powered by real Rust types (`schemars::JsonSchema` + `serde::Deserialize`) with schema generation, validation, and retry.
- A practical tool-use toolkit (registry, typed arg parsing, retry loops, streaming tool deltas) for “LLM + tools” apps.

```toml
[dependencies]
modelrelay = "0.95.0"
```

## Quick Start (Async)

```rust
use modelrelay::{Client, ResponseBuilder};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::from_api_key(std::env::var("MODELRELAY_API_KEY")?)?.build()?;

    let response = ResponseBuilder::new()
        .model("claude-sonnet-4-20250514")
        .system("Answer concisely.")
        .user("Write one line about Rust.")
        .send(&client.responses())
        .await?;

    // The response is structured: output items, tool calls, citations, usage, etc.
    // For the common case, you can extract assistant text directly:
    println!("{}", response.text());
    println!("tokens: {}", response.usage.total());
    Ok(())
}
```

## Chat-Like Text Helpers

For the most common path (**system + user → assistant text**), use the built-in convenience:

```rust
let text = client
    .responses()
    .text("claude-sonnet-4-20250514", "Answer concisely.", "Say hi.")
    .await?;
println!("{text}");
```

For customer-attributed requests where the backend selects the model:

```rust
let customer = client.for_customer("customer-123")?;
let text = customer
    .responses()
    .text("Answer concisely.", "Say hi.")
    .await?;
```

## Extracting Assistant Text

If you just need the assistant text, use:

```rust
let text = response.text();
let parts = response.text_chunks(); // each assistant text content part, in order
```

These helpers:
- include only output items with `role == assistant`
- include only `text` content parts

## Why This SDK Feels Good

### Fluent request building (value-style)

`ResponseBuilder` is a small, clonable value. You can compose “base requests” and reuse them:

```rust
use modelrelay::ResponseBuilder;

let base = ResponseBuilder::new()
    .model("gpt-4.1")
    .system("You are a careful reviewer.");

let a = base.clone().user("Summarize this changelog…");
let b = base.clone().user("Extract 3 risks…");
```

### Streaming you can actually use

If you only want text, stream just deltas:

```rust
use futures_util::StreamExt;
use modelrelay::ResponseBuilder;

let mut deltas = ResponseBuilder::new()
    .model("claude-sonnet-4-20250514")
    .user("Write a haiku about type systems.")
    .stream_deltas(&client.responses())
    .await?;

while let Some(delta) = deltas.next().await {
    print!("{}", delta?);
}
```

If you want full control, stream typed events (message start/delta/stop, tool deltas, ping/custom):

```rust
use futures_util::StreamExt;
use modelrelay::{ResponseBuilder, StreamEventKind};

let mut stream = ResponseBuilder::new()
    .model("claude-sonnet-4-20250514")
    .user("Think step by step, but only output the final answer.")
    .stream(&client.responses())
    .await?;

while let Some(evt) = stream.next().await {
    let evt = evt?;
    if evt.kind == StreamEventKind::MessageDelta {
        if let Some(text) = evt.text_delta {
            print!("{}", text);
        }
    }
}
```

## Workflows

High-level helpers for common workflow patterns:

### Chain (Sequential)

Sequential LLM calls where each step's output feeds the next step's input:

```rust
use modelrelay::{Chain, LLMStep, ResponseBuilder};

let summarize = ResponseBuilder::new()
    .model("claude-sonnet-4-20250514")
    .system("Summarize the input concisely.")
    .user("The quick brown fox...");

let translate = ResponseBuilder::new()
    .model("claude-sonnet-4-20250514")
    .system("Translate the input to French.");

let spec = Chain::new("summarize-translate")
    .step(LLMStep::new("summarize", summarize)?)
    .step(LLMStep::new("translate", translate)?.with_stream())
    .output_last("result")
    .build()?;
```

### Parallel (Fan-out with Aggregation)

Concurrent LLM calls with optional aggregation:

```rust
use modelrelay::{Parallel, LLMStep, ResponseBuilder};

let gpt4_req = ResponseBuilder::new().model("gpt-4.1").user("Analyze this...");
let claude_req = ResponseBuilder::new().model("claude-sonnet-4-20250514").user("Analyze this...");
let synthesize_req = ResponseBuilder::new()
    .model("claude-sonnet-4-20250514")
    .system("Synthesize the analyses into a unified view.");

let spec = Parallel::new("multi-model-compare")
    .step(LLMStep::new("gpt4", gpt4_req)?)
    .step(LLMStep::new("claude", claude_req)?)
    .aggregate("synthesize", synthesize_req)?
    .output("result", "synthesize")?
    .build()?;
```

### MapReduce (Parallel Map with Reduce)

Process items in parallel, then combine results:

```rust
use modelrelay::{MapReduce, ResponseBuilder};

let combine_req = ResponseBuilder::new()
    .model("claude-sonnet-4-20250514")
    .system("Combine summaries into a cohesive overview.");

let spec = MapReduce::new("summarize-docs")
    .add_item("doc1", ResponseBuilder::new()
        .model("claude-sonnet-4-20250514")
        .user("Summarize: Document 1 content..."))?
    .add_item("doc2", ResponseBuilder::new()
        .model("claude-sonnet-4-20250514")
        .user("Summarize: Document 2 content..."))?
    .reduce("combine", combine_req)?
    .output("result", "combine")?
    .build()?;
```

### Structured outputs from Rust types (with retry)

Structured outputs are the “Rust-native” path: you describe a type, and you get a typed value back.

```rust
use modelrelay::{Client, ResponseBuilder};
use schemars::JsonSchema;
use serde::Deserialize;

#[derive(Debug, Deserialize, JsonSchema)]
struct Person {
    name: String,
    age: u32,
    email: Option<String>,
}

let client = Client::from_api_key(std::env::var("MODELRELAY_API_KEY")?)?.build()?;

let result = ResponseBuilder::new()
    .model("claude-sonnet-4-20250514")
    .user("Extract: John Doe is 30 years old, john@example.com")
    .structured::<Person>()
    .max_retries(2)
    .send(&client.responses())
    .await?;

println!("{:?}", result.value);
```

And you can stream typed JSON with field-level completion for progressive UIs:

```rust
use futures_util::StreamExt;
use schemars::JsonSchema;
use serde::Deserialize;
use modelrelay::ResponseBuilder;

#[derive(Debug, Deserialize, JsonSchema)]
struct Article {
    title: String,
    summary: String,
    body: String,
}

let mut stream = ResponseBuilder::new()
    .model("claude-sonnet-4-20250514")
    .user("Write an article about Rust's ownership model.")
    .structured::<Article>()
    .stream(&client.responses())
    .await?;

while let Some(evt) = stream.next().await {
    let evt = evt?;
    for field in &evt.complete_fields {
        if field == "title" {
            println!("Title: {}", evt.payload.title);
        }
    }
}
```

### Tool use is end-to-end (not just a schema)

The SDK ships the pieces you need to build a complete tool loop:
- create tool schemas from types
- parse/validate tool args into typed structs
- execute tool calls via a registry
- feed results back as tool result messages
- retry tool calls when args are malformed (with model-facing error formatting)

```rust
use modelrelay::{
    function_tool_from_type, parse_tool_args, respond_to_tool_call_json, ResponseBuilder, Tool,
    ToolChoice, ToolRegistry, ResponseExt,
};
use schemars::JsonSchema;
use serde::Deserialize;

#[derive(Debug, Deserialize, JsonSchema)]
struct WeatherArgs {
    location: String,
}

let registry = ToolRegistry::new().register(
    "get_weather",
    modelrelay::sync_handler(|_args_json, call| {
        let args: WeatherArgs = parse_tool_args(call)?;
        Ok(serde_json::json!({ "location": args.location, "temp_f": 72 }))
    }),
);

let schema = function_tool_from_type::<WeatherArgs>()?;
let tool = Tool::function(
    "get_weather",
    Some("Get current weather for a location".into()),
    Some(schema.parameters),
);

let response = ResponseBuilder::new()
    .model("claude-sonnet-4-20250514")
    .user("Use the tool to get the weather in San Francisco.")
    .tools(vec![tool])
    .tool_choice(ToolChoice::auto())
    .send(&client.responses())
    .await?;

if response.has_tool_calls() {
    let call = response.first_tool_call().unwrap();
    let result = registry.execute(call).await;
    let tool_result = respond_to_tool_call_json(call, &result.result)?;

    // Feed the tool result back as an input item and continue the conversation.
    let followup = ResponseBuilder::new()
        .model("claude-sonnet-4-20250514")
        .user("Great—now summarize it in one sentence.")
        .item(tool_result)
        .send(&client.responses())
        .await?;

    println!("followup tokens: {}", followup.usage.total());
}
```

### tools.v0 local filesystem tools (fs.*)

The Rust SDK includes a safe-by-default local filesystem tool pack that implements:
`fs.read_file`, `fs.list_files`, and `fs.search`.

```rust
use modelrelay::{LocalFSToolPack, ToolRegistry};

let mut registry = ToolRegistry::new();
let fs_tools = LocalFSToolPack::new(".", Vec::new());
fs_tools.register_into(&mut registry);

// Now registry can execute fs.read_file/fs.list_files/fs.search tool calls.
```

## Customer-Attributed Requests

For metered billing, set `customer_id(...)`. The customer's tier can determine the model (so `model(...)` can be omitted):

```rust
use modelrelay::ResponseBuilder;

let response = ResponseBuilder::new()
    .customer_id("customer-123")
    .user("Hello!")
    .send(&client.responses())
    .await?;
```

## Blocking API (No Tokio)

Enable the `blocking` feature and use the same builder ergonomics:

```rust
use modelrelay::{BlockingClient, BlockingConfig, ResponseBuilder};

let client = BlockingClient::new(BlockingConfig {
    api_key: Some(std::env::var("MODELRELAY_API_KEY")?),
    ..Default::default()
})?;

let response = ResponseBuilder::new()
    .model("claude-sonnet-4-20250514")
    .user("Hello!")
    .send_blocking(&client.responses())?;
```

## Feature Flags

| Feature | Default | Description |
|---------|---------|-------------|
| `streaming` | Yes | NDJSON streaming support |
| `blocking` | No | Sync client without Tokio |
| `tracing` | No | OpenTelemetry spans/events |
| `mock` | No | In-memory client for tests |

## Errors

Errors are typed so callers can branch cleanly:

```rust
use modelrelay::{Error, ResponseBuilder};

let result = ResponseBuilder::new()
    .model("claude-sonnet-4-20250514")
    .user("Hello!")
    .send(&client.responses())
    .await;

match result {
    Ok(_response) => {}
    Err(Error::Api(e)) if e.is_rate_limit() => {}
    Err(Error::Api(e)) if e.is_unauthorized() => {}
    Err(Error::Transport(_)) => {}
    Err(e) => return Err(e.into()),
}
```

## Documentation

For detailed guides and API reference, visit [docs.modelrelay.ai](https://docs.modelrelay.ai):

- [Rust SDK Reference]https://docs.modelrelay.ai/sdks/rust — Full SDK documentation
- [First Request]https://docs.modelrelay.ai/getting-started/first-request — Make your first API call
- [Streaming]https://docs.modelrelay.ai/guides/streaming — Real-time response streaming
- [Structured Output]https://docs.modelrelay.ai/guides/structured-output — Get typed JSON responses
- [Tool Use]https://docs.modelrelay.ai/guides/tools — Let models call functions
- [Error Handling]https://docs.modelrelay.ai/guides/error-handling — Handle errors gracefully
- [Workflows]https://docs.modelrelay.ai/guides/workflows — Multi-step AI pipelines