open-agent-sdk 0.10.0

Production-ready Rust SDK for building AI agents over two wire protocols: OpenAI chat completions (LMStudio, Ollama, llama.cpp, vLLM, OpenRouter) and Anthropic messages. Features streaming, tools, hooks, retry logic, and comprehensive examples.
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
//! Translation tests for [`AnthropicRequest::from_openai`].
//!
//! Every case here asserts on the serialized JSON rather than on the struct, because the
//! shape on the wire is the contract: a field that serializes under the wrong name, or one
//! that should have been omitted, is invisible at the struct level.

use super::*;
use crate::types::{OpenAIFunction, OpenAIImageUrl, OpenAIToolCall};

/// Builds a request carrying `messages` and nothing else optional.
fn request_with(messages: Vec<OpenAIMessage>) -> OpenAIRequest {
    OpenAIRequest {
        model: "m".to_string(),
        messages,
        stream: true,
        max_tokens: None,
        temperature: None,
        tools: None,
    }
}

/// A text message in the given role.
fn message(role: &str, text: &str) -> OpenAIMessage {
    OpenAIMessage {
        role: role.to_string(),
        content: Some(OpenAIContent::Text(text.to_string())),
        tool_calls: None,
        tool_call_id: None,
    }
}

/// Serializes a translated request so assertions read against the wire shape.
fn wire(request: &OpenAIRequest) -> Value {
    serde_json::to_value(AnthropicRequest::from_openai(request)).expect("serializes")
}

#[test]
fn the_system_prompt_leaves_the_messages_array() {
    let out = wire(&request_with(vec![
        message("system", "be terse"),
        message("user", "hi"),
    ]));

    assert_eq!(out["system"], json!("be terse"));
    assert_eq!(out["messages"].as_array().expect("array").len(), 1);
    assert_eq!(out["messages"][0]["role"], json!("user"));
}

#[test]
fn multiple_system_messages_are_joined_rather_than_dropped() {
    let out = wire(&request_with(vec![
        message("system", "first"),
        message("system", "second"),
        message("user", "hi"),
    ]));

    assert_eq!(out["system"], json!("first\n\nsecond"));
}

#[test]
fn a_request_with_no_system_message_omits_the_field() {
    let out = wire(&request_with(vec![message("user", "hi")]));

    assert!(
        out.get("system").is_none(),
        "system must be omitted, got {out}"
    );
}

#[test]
fn a_text_only_turn_serializes_as_a_bare_string() {
    let out = wire(&request_with(vec![message("user", "hi")]));

    assert_eq!(out["messages"][0]["content"], json!("hi"));
}

#[test]
fn a_turn_whose_only_part_is_text_also_serializes_as_a_bare_string() {
    // Vision callers build content as a part array even when the turn ends up carrying only
    // text. That is the same turn as the one above and goes on the wire the same way, rather
    // than as a one-element block array.
    let user = OpenAIMessage {
        role: "user".to_string(),
        content: Some(OpenAIContent::Parts(vec![OpenAIContentPart::Text {
            text: "hi".to_string(),
        }])),
        tool_calls: None,
        tool_call_id: None,
    };

    let out = wire(&request_with(vec![user]));

    assert_eq!(out["messages"][0]["content"], json!("hi"));
}

#[test]
fn a_turn_with_text_and_an_image_keeps_its_block_array() {
    // The bare-string shortcut applies only when text is the whole turn; a second part means
    // the array is the only representation that can carry it.
    let user = OpenAIMessage {
        role: "user".to_string(),
        content: Some(OpenAIContent::Parts(vec![
            OpenAIContentPart::Text {
                text: "what is this".to_string(),
            },
            OpenAIContentPart::ImageUrl {
                image_url: OpenAIImageUrl {
                    url: "https://example.com/a.png".to_string(),
                    detail: None,
                },
            },
        ])),
        tool_calls: None,
        tool_call_id: None,
    };

    let out = wire(&request_with(vec![user]));

    let blocks = out["messages"][0]["content"]
        .as_array()
        .expect("a multi-part turn keeps its array");
    assert_eq!(blocks.len(), 2, "{out}");
    assert_eq!(blocks[0]["type"], json!("text"));
    assert_eq!(blocks[1]["type"], json!("image"));
}

#[test]
fn system_text_survives_a_parts_message_and_images_do_not() {
    let system = OpenAIMessage {
        role: "system".to_string(),
        content: Some(OpenAIContent::Parts(vec![
            OpenAIContentPart::text("be "),
            OpenAIContentPart::ImageUrl {
                image_url: OpenAIImageUrl {
                    url: "https://example.com/a.png".to_string(),
                    detail: None,
                },
            },
            OpenAIContentPart::text("terse"),
        ])),
        tool_calls: None,
        tool_call_id: None,
    };

    let out = wire(&request_with(vec![system, message("user", "hi")]));

    assert_eq!(out["system"], json!("be terse"));
}

#[test]
fn an_assistant_tool_call_becomes_a_tool_use_block_with_parsed_input() {
    let assistant = OpenAIMessage {
        role: "assistant".to_string(),
        content: None,
        tool_calls: Some(vec![OpenAIToolCall {
            id: "call_1".to_string(),
            call_type: "function".to_string(),
            function: OpenAIFunction {
                name: "search".to_string(),
                arguments: r#"{"q":"rust"}"#.to_string(),
            },
        }]),
        tool_call_id: None,
    };

    let out = wire(&request_with(vec![message("user", "hi"), assistant]));
    let block = &out["messages"][1]["content"][0];

    assert_eq!(block["type"], json!("tool_use"));
    assert_eq!(block["id"], json!("call_1"));
    assert_eq!(block["name"], json!("search"));
    // Parsed into an object, not passed through as the JSON string OpenAI sends.
    assert_eq!(block["input"], json!({ "q": "rust" }));
}

#[test]
fn text_alongside_a_tool_call_precedes_it_in_the_block_array() {
    let assistant = OpenAIMessage {
        role: "assistant".to_string(),
        content: Some(OpenAIContent::Text("looking".to_string())),
        tool_calls: Some(vec![OpenAIToolCall {
            id: "call_1".to_string(),
            call_type: "function".to_string(),
            function: OpenAIFunction {
                name: "search".to_string(),
                arguments: "{}".to_string(),
            },
        }]),
        tool_call_id: None,
    };

    let out = wire(&request_with(vec![assistant]));
    let blocks = out["messages"][0]["content"]
        .as_array()
        .expect("block array");

    assert_eq!(blocks.len(), 2);
    assert_eq!(blocks[0], json!({ "type": "text", "text": "looking" }));
    assert_eq!(blocks[1]["type"], json!("tool_use"));
}

#[test]
fn malformed_tool_arguments_become_an_empty_object() {
    let assistant = OpenAIMessage {
        role: "assistant".to_string(),
        content: None,
        tool_calls: Some(vec![OpenAIToolCall {
            id: "call_1".to_string(),
            call_type: "function".to_string(),
            function: OpenAIFunction {
                name: "search".to_string(),
                arguments: "{not json".to_string(),
            },
        }]),
        tool_call_id: None,
    };

    let out = wire(&request_with(vec![assistant]));

    assert_eq!(out["messages"][0]["content"][0]["input"], json!({}));
}

#[test]
fn a_tool_result_becomes_a_user_turn() {
    let result = OpenAIMessage {
        role: "tool".to_string(),
        content: Some(OpenAIContent::Text("42".to_string())),
        tool_calls: None,
        tool_call_id: Some("call_1".to_string()),
    };

    let out = wire(&request_with(vec![result]));
    let block = &out["messages"][0]["content"][0];

    assert_eq!(out["messages"][0]["role"], json!("user"));
    assert_eq!(block["type"], json!("tool_result"));
    assert_eq!(block["tool_use_id"], json!("call_1"));
    assert_eq!(block["content"], json!("42"));
}

#[test]
fn consecutive_tool_results_merge_into_one_user_turn() {
    let result = |id: &str, body: &str| OpenAIMessage {
        role: "tool".to_string(),
        content: Some(OpenAIContent::Text(body.to_string())),
        tool_calls: None,
        tool_call_id: Some(id.to_string()),
    };

    let out = wire(&request_with(vec![
        result("call_1", "a"),
        result("call_2", "b"),
    ]));

    let messages = out["messages"].as_array().expect("array");
    assert_eq!(messages.len(), 1, "parallel results share one turn: {out}");
    let blocks = messages[0]["content"].as_array().expect("block array");
    assert_eq!(blocks.len(), 2);
    assert_eq!(blocks[0]["tool_use_id"], json!("call_1"));
    assert_eq!(blocks[1]["tool_use_id"], json!("call_2"));
}

#[test]
fn a_tool_result_does_not_merge_into_a_real_user_turn() {
    let result = OpenAIMessage {
        role: "tool".to_string(),
        content: Some(OpenAIContent::Text("42".to_string())),
        tool_calls: None,
        tool_call_id: Some("call_1".to_string()),
    };

    let out = wire(&request_with(vec![message("user", "hi"), result]));

    let messages = out["messages"].as_array().expect("array");
    assert_eq!(messages.len(), 2, "the user turn is not a tool turn: {out}");
    assert_eq!(messages[0]["content"], json!("hi"));
    assert_eq!(messages[1]["content"][0]["type"], json!("tool_result"));
}

#[test]
fn a_tool_result_does_not_merge_into_a_user_turn_that_is_already_a_block_array() {
    // The turn a `content_blocks` conversion produces for an image is an array too, so
    // "content is an array" is not enough to identify a turn this module built. Absorbing a
    // tool result into it would attach an answer to the wrong turn.
    let with_image = OpenAIMessage {
        role: "user".to_string(),
        content: Some(OpenAIContent::Parts(vec![
            OpenAIContentPart::text("look"),
            OpenAIContentPart::ImageUrl {
                image_url: OpenAIImageUrl {
                    url: "https://example.com/a.png".to_string(),
                    detail: None,
                },
            },
        ])),
        tool_calls: None,
        tool_call_id: None,
    };
    let result = OpenAIMessage {
        role: "tool".to_string(),
        content: Some(OpenAIContent::Text("42".to_string())),
        tool_calls: None,
        tool_call_id: Some("call_1".to_string()),
    };

    let out = wire(&request_with(vec![with_image, result]));

    let messages = out["messages"].as_array().expect("array");
    assert_eq!(messages.len(), 2, "the image turn keeps to itself: {out}");
    assert_eq!(
        messages[0]["content"].as_array().expect("blocks").len(),
        2,
        "the image turn is unchanged: {out}"
    );
    assert_eq!(messages[1]["content"][0]["type"], json!("tool_result"));
}

#[test]
fn a_data_uri_image_becomes_a_base64_source() {
    let user = OpenAIMessage {
        role: "user".to_string(),
        content: Some(OpenAIContent::Parts(vec![OpenAIContentPart::ImageUrl {
            image_url: OpenAIImageUrl {
                url: "data:image/png;base64,AAAB".to_string(),
                detail: None,
            },
        }])),
        tool_calls: None,
        tool_call_id: None,
    };

    let out = wire(&request_with(vec![user]));

    assert_eq!(
        out["messages"][0]["content"][0],
        json!({
            "type": "image",
            "source": { "type": "base64", "media_type": "image/png", "data": "AAAB" },
        })
    );
}

#[test]
fn data_uri_parameters_are_not_part_of_the_media_type() {
    // `ImageBlock::from_url` reads the media type up to the first `;`, so it accepts this URI
    // and reports `image/png`. Splitting on `;base64` instead would send Anthropic
    // `image/png;charset=utf-8`, a media type it rejects, for an image the SDK had accepted.
    let user = OpenAIMessage {
        role: "user".to_string(),
        content: Some(OpenAIContent::Parts(vec![OpenAIContentPart::ImageUrl {
            image_url: OpenAIImageUrl {
                url: "data:image/png;charset=utf-8;base64,AAAB".to_string(),
                detail: None,
            },
        }])),
        tool_calls: None,
        tool_call_id: None,
    };

    let out = wire(&request_with(vec![user]));

    assert_eq!(
        out["messages"][0]["content"][0],
        json!({
            "type": "image",
            "source": { "type": "base64", "media_type": "image/png", "data": "AAAB" },
        })
    );
}

#[test]
fn a_remote_image_url_becomes_a_url_source() {
    let user = OpenAIMessage {
        role: "user".to_string(),
        content: Some(OpenAIContent::Parts(vec![OpenAIContentPart::ImageUrl {
            image_url: OpenAIImageUrl {
                url: "https://example.com/a.png".to_string(),
                detail: None,
            },
        }])),
        tool_calls: None,
        tool_call_id: None,
    };

    let out = wire(&request_with(vec![user]));

    assert_eq!(
        out["messages"][0]["content"][0]["source"],
        json!({ "type": "url", "url": "https://example.com/a.png" })
    );
}

#[test]
fn a_data_uri_that_is_not_base64_is_not_read_as_base64() {
    // `data:image/svg+xml,<svg/>` carries the payload verbatim. Declaring it base64 would
    // hand the API bytes that are not base64 at all.
    let user = OpenAIMessage {
        role: "user".to_string(),
        content: Some(OpenAIContent::Parts(vec![OpenAIContentPart::ImageUrl {
            image_url: OpenAIImageUrl {
                url: "data:image/svg+xml,<svg/>".to_string(),
                detail: None,
            },
        }])),
        tool_calls: None,
        tool_call_id: None,
    };

    let out = wire(&request_with(vec![user]));

    assert_eq!(
        out["messages"][0]["content"][0]["source"]["type"],
        json!("url")
    );
}

#[test]
fn a_tool_definition_is_flattened_out_of_its_function_envelope() {
    let mut request = request_with(vec![message("user", "hi")]);
    request.tools = Some(vec![json!({
        "type": "function",
        "function": {
            "name": "search",
            "description": "find things",
            "parameters": { "type": "object", "properties": { "q": { "type": "string" } } },
        },
    })]);

    let out = wire(&request);

    assert_eq!(
        out["tools"][0],
        json!({
            "name": "search",
            "description": "find things",
            "input_schema": { "type": "object", "properties": { "q": { "type": "string" } } },
        })
    );
}

#[test]
fn a_tool_definition_without_parameters_gets_an_empty_object_schema() {
    let mut request = request_with(vec![message("user", "hi")]);
    request.tools = Some(vec![json!({
        "type": "function",
        "function": { "name": "ping" },
    })]);

    let out = wire(&request);

    assert_eq!(
        out["tools"][0]["input_schema"],
        json!({ "type": "object", "properties": {} }),
        "input_schema is required by the API, so it is never omitted"
    );
}

#[test]
fn a_tool_already_in_anthropic_shape_passes_through_untouched() {
    let mut request = request_with(vec![message("user", "hi")]);
    let native = json!({
        "name": "search",
        "input_schema": { "type": "object", "properties": {} },
    });
    request.tools = Some(vec![native.clone()]);

    let out = wire(&request);

    assert_eq!(out["tools"][0], native);
}

#[test]
fn unset_ceilings_are_omitted_from_the_wire() {
    let out = wire(&request_with(vec![message("user", "hi")]));

    assert!(out.get("max_tokens").is_none(), "got {out}");
    assert!(out.get("temperature").is_none(), "got {out}");
    assert!(out.get("tools").is_none(), "got {out}");
}

#[test]
fn set_ceilings_reach_the_wire() {
    let mut request = request_with(vec![message("user", "hi")]);
    request.max_tokens = Some(1024);
    request.temperature = Some(0.2);

    let out = wire(&request);

    assert_eq!(out["max_tokens"], json!(1024));
    assert_eq!(out["model"], json!("m"));
    assert_eq!(out["stream"], json!(true));
    assert!(
        (out["temperature"].as_f64().expect("number") - 0.2).abs() < 1e-6,
        "got {out}"
    );
}

#[test]
fn streaming_is_carried_through_rather_than_assumed() {
    let mut request = request_with(vec![message("user", "hi")]);
    request.stream = false;

    assert_eq!(wire(&request)["stream"], json!(false));
}