modelrelay 6.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
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
# 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 = "5.7.0"
```

## Convenience API

The simplest way to get started. Three methods cover the most common use cases:

### Ask — Get a Quick Answer

```rust
use modelrelay::Client;

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

let answer = client.ask("claude-sonnet-4-5", "What is 2 + 2?", None).await?;
println!("{}", answer); // "4"
```

### Chat — Full Response with Metadata

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

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

let response = client.chat(
    "claude-sonnet-4-5",
    "Explain quantum computing",
    Some(ChatOptions::new().with_system("You are a physics professor")),
).await?;

println!("{}", response.text());
println!("Tokens: {}", response.usage.total_tokens);
```

### Agent — Agentic Tool Loops

Run an agent that automatically executes tools until completion:

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

#[derive(JsonSchema, Deserialize)]
struct ReadFileArgs {
    /// File path to read
    path: String,
}

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

let tools = ToolBuilder::new()
    .add_sync::<ReadFileArgs, _>("read_file", "Read a file", |args, _call| {
        let content = std::fs::read_to_string(&args.path)
            .map_err(|e| e.to_string())?;
        Ok(serde_json::json!({ "content": content }))
    });

let result = client.agent(
    "claude-sonnet-4-5",
    AgentOptions::new(tools, "Read config.json and summarize it")
        .with_system("You are a helpful file assistant"),
).await?;

println!("{}", result.output);
println!("Tool calls: {}", result.usage.tool_calls);
```

## 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-5")
        .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-5", "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-5")
    .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-5")
    .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

Build multi-step AI pipelines with the workflow helpers.

### Sequential Chain

```rust
use modelrelay::{chain, llm, ChainOptions};

let spec = chain(
    vec![
        llm("summarize", |n| n.system("Summarize.").user("{{task}}")),
        llm("translate", |n| n.system("Translate to French.").user("{{summarize}}")),
    ],
    ChainOptions { name: Some("summarize-translate".into()), model: Some("claude-sonnet-4-5".into()), ..Default::default() },
)
.output("result", "translate", None)
.build()?;

let run = client.runs().create(spec).await?;
```

### Parallel with Aggregation

```rust
use modelrelay::{parallel, llm, ParallelOptions};

let spec = parallel(
    vec![
        llm("agent_a", |n| n.user("Write 3 ideas for {{task}}.")),
        llm("agent_b", |n| n.user("Write 3 objections for {{task}}.")),
    ],
    ParallelOptions { name: Some("multi-agent".into()), model: Some("claude-sonnet-4-5".into()), ..Default::default() },
)
.llm("aggregate", |n| n.system("Synthesize.").user("{{join}}"))
.edge("join", "aggregate")
.output("result", "aggregate", None)
.build()?;
```

### Map Fan-out

```rust
use modelrelay::{workflow, MapFanoutOptions, LLMNodeBuilder};

let spec = workflow()
    .name("fanout-example")
    .model("claude-sonnet-4-5")
    .llm("generator", |n| n.user("Generate 3 subquestions for {{task}}"))
    .map_fanout("fanout", MapFanoutOptions {
        items_from: Some("generator".into()),
        items_from_input: None,
        items_path: Some("/questions".into()),
        subnode: LLMNodeBuilder::new("answer").user("Answer: {{item}}").build(),
        max_parallelism: Some(4),
    })
    .llm("aggregate", |n| n.user("Combine: {{fanout}}"))
    .output("result", "aggregate", None)
    .build()?;
```

### Precompiled Workflows

For workflows that run repeatedly, compile once and reuse:

```rust
use modelrelay::RunsCreateOptions;
use serde_json::json;

// Compile once
let compiled = client.workflows().compile(spec).await?;

// Run multiple times with different inputs
for task in &tasks {
    let run = client.runs().create_from_plan_with_options(
        compiled.plan_hash.clone(),
        RunsCreateOptions {
            input: Some(json!({ "task": task })),
            ..Default::default()
        },
    ).await?;
}
```

### Plugins (Workflows)

Load GitHub-hosted plugins (markdown commands + agents), convert to workflows via `/responses`, then run them with `/runs`:

```rust
use modelrelay::{Client, OrchestrationMode, PluginRunConfig, new_local_fs_tools};

let client = Client::from_secret_key(std::env::var("MODELRELAY_API_KEY")?)?.build()?;
let tools = new_local_fs_tools(std::env::current_dir()?);

let plugin = client.plugins().load("github.com/your-org/your-plugin").await?;
let result = client.plugins().run(
    &plugin,
    "run",
    PluginRunConfig {
        user_task: "Summarize the repo and suggest next steps.".to_string(),
        orchestration_mode: Some(OrchestrationMode::Dynamic),
        tool_registry: Some(std::sync::Arc::new(tools)),
        ..Default::default()
    },
).await?;

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

### 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-5")
    .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-5")
    .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-5")
    .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-5")
        .user("Great—now summarize it in one sentence.")
        .item(tool_result)
        .send(&client.responses())
        .await?;

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

### User Interaction — `user.ask`

Use the built-in `user.ask` tool to request human input in a workflow run:

```rust
use futures_util::StreamExt;
use modelrelay::{
    user_ask_result_freeform, user_ask_tool, RunEventPayload, RunsToolCallV0,
    RunsToolResultItemV0, RunsToolResultsRequest,
};

let tools = vec![user_ask_tool()];
let run = client.runs().create(spec).await?;

let mut events = client.runs().stream_events(run.run_id, None, None).await?;
while let Some(event) = events.next().await {
    let event = event?;
    if let RunEventPayload::NodeUserAsk { node_id, user_ask } = event.payload {
        let answer = prompt_user(&user_ask.question); // your UI/input here
        let output = user_ask_result_freeform(answer)?;

        client
            .runs()
            .submit_tool_results(
                run.run_id,
                RunsToolResultsRequest {
                    node_id,
                    step: user_ask.step,
                    request_id: user_ask.request_id,
                    results: vec![RunsToolResultItemV0 {
                        tool_call: RunsToolCallV0 {
                            id: user_ask.tool_call.id,
                            name: user_ask.tool_call.name,
                            arguments: None,
                        },
                        output,
                    }],
                },
            )
            .await?;
    }
}
```

### 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`, `fs.search`, and `fs.edit`.

```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/fs.edit 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-5")
    .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-5")
    .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