genai 0.7.0-beta.20

Multi-AI Providers Library for Rust. (OpenAI, Gemini, Anthropic, Ollama, AWS Bedrock, Vertex, Groq, DeepSeek, Kimi, GLM and many more)
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
use super::{OpenAIAdapter, ToWebRequestDataOptions};
use crate::adapter::AdapterKind;
use crate::chat::{
	CacheControl, ChatMessage, ChatOptions, ChatOptionsSet, ChatRequest, ContentPart, MessageContent, Tool, ToolCall,
	ToolChoice,
};
use crate::resolver::{AuthData, Endpoint};
use crate::{ModelIden, ServiceTarget};
use serde_json::{Value, json};

type Result<T> = core::result::Result<T, Box<dyn std::error::Error>>;

#[test]
fn test_cache_control_without_eligible_content_does_not_fail_chat_completion() -> Result<()> {
	// -- Setup & Fixtures
	let target = ServiceTarget {
		model: ModelIden::new(AdapterKind::OpenAI, "gpt-5.6"),
		auth: AuthData::from_single("test-key"),
		endpoint: Endpoint::from_static("https://api.openai.com/v1/"),
	};
	let assistant_msg = ChatMessage::assistant(MessageContent::from_parts(vec![ContentPart::ToolCall(ToolCall {
		call_id: "call_1".to_string(),
		fn_name: "get_weather".to_string(),
		fn_arguments: json!({}),
		thought_signatures: None,
	})]))
	.with_options(CacheControl::Ephemeral);
	let chat_req = ChatRequest::new(vec![ChatMessage::user("hello"), assistant_msg]);

	// -- Exec
	let web_req = OpenAIAdapter::util_to_web_request_data(
		target,
		crate::adapter::ServiceType::Chat,
		chat_req,
		ChatOptionsSet::default(),
		None,
	)?;

	// -- Check
	assert_eq!(web_req.payload["prompt_cache_options"]["mode"], "explicit");

	Ok(())
}

#[test]
fn test_extra_body_merged_into_chat_completion_payload() -> Result<()> {
	// -- Setup & Fixtures
	let chat_options = ChatOptions::default()
		.with_temperature(0.2)
		.with_extra_body(json!({"temperature": 0.7, "enable_thinking": false}));
	let options_set = ChatOptionsSet::default().with_chat_options(Some(&chat_options));
	let target = ServiceTarget {
		model: test_model(),
		auth: AuthData::from_single("test-key"),
		endpoint: Endpoint::from_static("https://api.openai.com/v1/"),
	};

	// -- Exec
	let web_req = OpenAIAdapter::util_to_web_request_data(
		target,
		crate::adapter::ServiceType::Chat,
		ChatRequest::from_user("hello"),
		options_set,
		None,
	)?;

	// -- Check
	assert_eq!(web_req.payload["enable_thinking"], false);
	assert_eq!(web_req.payload["temperature"], 0.7);

	Ok(())
}

#[test]
fn test_tool_choice_specific_tool_serialized_on_chat_completion_payload() -> Result<()> {
	// -- Setup & Fixtures
	let chat_options = ChatOptions::default().with_tool_choice(ToolChoice::tool("get_weather"));
	let options_set = ChatOptionsSet::default().with_chat_options(Some(&chat_options));
	let target = ServiceTarget {
		model: test_model(),
		auth: AuthData::from_single("test-key"),
		endpoint: Endpoint::from_static("https://api.openai.com/v1/"),
	};
	let chat_req = ChatRequest::from_user("weather").with_tools(vec![Tool::new("get_weather")]);

	// -- Exec
	let web_req = OpenAIAdapter::util_to_web_request_data(
		target,
		crate::adapter::ServiceType::Chat,
		chat_req,
		options_set,
		None,
	)?;

	// -- Check
	assert_eq!(
		web_req.payload["tool_choice"],
		json!({
			"type": "function",
			"function": { "name": "get_weather" }
		})
	);

	Ok(())
}

#[test]
fn test_null_usage_is_treated_as_absent_usage() -> Result<()> {
	// -- Setup & Fixtures
	let usage = OpenAIAdapter::into_usage(AdapterKind::OpenAI, Value::Null);

	// -- Exec & Check
	assert!(usage.prompt_tokens.is_none());
	assert!(usage.completion_tokens.is_none());
	assert!(usage.total_tokens.is_none());

	Ok(())
}

/// When an assistant message carries reasoning_content, it must appear
/// in the serialized JSON so providers that require it (Kimi, DeepSeek)
/// don't reject the request.
#[test]
fn test_reasoning_content_serialized_on_assistant_message() -> Result<()> {
	// -- Setup & Fixtures
	let tool_call = ToolCall {
		call_id: "call_1".to_string(),
		fn_name: "get_weather".to_string(),
		fn_arguments: serde_json::json!({"city": "Paris"}),
		thought_signatures: None,
	};

	let assistant_msg = ChatMessage::assistant(MessageContent::from_parts(vec![
		ContentPart::Text("Let me check.".to_string()),
		ContentPart::ToolCall(tool_call),
	]))
	.with_reasoning_content(Some("I should look up the weather.".to_string()));

	let chat_req = ChatRequest::new(vec![ChatMessage::user("What's the weather in Paris?"), assistant_msg]);

	// -- Exec
	let parts = OpenAIAdapter::into_openai_request_parts(&test_model(), chat_req, None)?;

	// -- Check
	// The assistant message is the second message (after user)
	let assistant_json = parts
		.messages
		.get(1)
		.ok_or_else(|| std::io::Error::other("assistant message should be present"))?;
	assert_eq!(assistant_json["role"], "assistant");
	assert_eq!(
		assistant_json["reasoning_content"], "I should look up the weather.",
		"reasoning_content should be present in serialized assistant message"
	);

	Ok(())
}

/// When reasoning_content is None, the field should not appear in the JSON.
#[test]
fn test_no_reasoning_content_when_absent() -> Result<()> {
	// -- Setup & Fixtures
	let chat_req = ChatRequest::new(vec![ChatMessage::user("Hello"), ChatMessage::assistant("Hi there!")]);

	// -- Exec
	let parts = OpenAIAdapter::into_openai_request_parts(&test_model(), chat_req, None)?;

	// -- Check
	let assistant_json = parts
		.messages
		.get(1)
		.ok_or_else(|| std::io::Error::other("assistant message should be present"))?;
	assert_eq!(assistant_json["role"], "assistant");
	assert!(
		assistant_json.get("reasoning_content").is_none(),
		"reasoning_content should be absent when not set"
	);

	Ok(())
}

#[test]
fn test_gpt_5_6_chat_completion_defaults_to_explicit_cache_mode() -> Result<()> {
	// -- Setup & Fixtures
	let target = ServiceTarget {
		model: ModelIden::new(AdapterKind::OpenAI, "gpt-5.6"),
		auth: AuthData::from_single("test-key"),
		endpoint: Endpoint::from_static("https://api.openai.com/v1/"),
	};

	// -- Exec
	let web_req = OpenAIAdapter::util_to_web_request_data(
		target,
		crate::adapter::ServiceType::Chat,
		ChatRequest::from_user("hello"),
		ChatOptionsSet::default(),
		None,
	)?;

	// -- Check
	assert_eq!(web_req.payload["prompt_cache_options"]["mode"], "explicit");
	assert!(web_req.payload["prompt_cache_options"].get("ttl").is_none());
	assert!(web_req.payload["messages"][0]["content"]["prompt_cache_breakpoint"].is_null());

	Ok(())
}

#[test]
fn test_gpt_5_6_chat_completion_cache_key_uses_api_default_mode() -> Result<()> {
	// -- Setup & Fixtures
	let target = ServiceTarget {
		model: ModelIden::new(AdapterKind::OpenAI, "gpt-5.6-mini"),
		auth: AuthData::from_single("test-key"),
		endpoint: Endpoint::from_static("https://api.openai.com/v1/"),
	};
	let options = ChatOptions::default().with_prompt_cache_key("stable-key");
	let options_set = ChatOptionsSet::default().with_chat_options(Some(&options));

	// -- Exec
	let web_req = OpenAIAdapter::util_to_web_request_data(
		target,
		crate::adapter::ServiceType::Chat,
		ChatRequest::from_user("hello"),
		options_set,
		None,
	)?;

	// -- Check
	assert!(web_req.payload.get("prompt_cache_options").is_none());
	assert!(web_req.payload["messages"][0]["content"]["prompt_cache_breakpoint"].is_null());

	Ok(())
}

#[test]
fn test_gpt_5_6_chat_completion_places_breakpoint_on_last_eligible_block() -> Result<()> {
	// -- Setup & Fixtures
	let target = ServiceTarget {
		model: ModelIden::new(AdapterKind::OpenAI, "gpt-5.6"),
		auth: AuthData::from_single("test-key"),
		endpoint: Endpoint::from_static("https://api.openai.com/v1/"),
	};
	let chat_req = ChatRequest::new(vec![
		ChatMessage::user(vec![
			ContentPart::from_text("stable text"),
			ContentPart::from_binary_url("image/png", "https://example.com/image.png", None),
			ContentPart::from_text("last text"),
		])
		.with_options(CacheControl::Ephemeral),
	]);

	// -- Exec
	let web_req = OpenAIAdapter::util_to_web_request_data(
		target,
		crate::adapter::ServiceType::Chat,
		chat_req,
		ChatOptionsSet::default(),
		None,
	)?;

	// -- Check
	let blocks = web_req.payload["messages"][0]["content"]
		.as_array()
		.ok_or_else(|| std::io::Error::other("message content should be an array"))?;
	let first = blocks.first().ok_or_else(|| std::io::Error::other("missing first block"))?;
	assert!(first["prompt_cache_breakpoint"].is_null());

	let image = blocks.get(1).ok_or_else(|| std::io::Error::other("missing image block"))?;
	assert!(image["prompt_cache_breakpoint"].is_null());

	let last = blocks.get(2).ok_or_else(|| std::io::Error::other("missing last block"))?;
	assert_eq!(last["prompt_cache_breakpoint"]["mode"], "explicit");

	Ok(())
}

#[test]
fn test_gpt_5_5_chat_completion_keeps_legacy_cache_retention() -> Result<()> {
	// -- Setup & Fixtures
	let target = ServiceTarget {
		model: ModelIden::new(AdapterKind::OpenAI, "gpt-5.5"),
		auth: AuthData::from_single("test-key"),
		endpoint: Endpoint::from_static("https://api.openai.com/v1/"),
	};
	let options = ChatOptions::default().with_cache_control(CacheControl::Ephemeral24h);
	let options_set = ChatOptionsSet::default().with_chat_options(Some(&options));

	// -- Exec
	let web_req = OpenAIAdapter::util_to_web_request_data(
		target,
		crate::adapter::ServiceType::Chat,
		ChatRequest::from_user("hello"),
		options_set,
		None,
	)?;

	// -- Check
	assert_eq!(web_req.payload["prompt_cache_retention"], "24h");
	assert!(web_req.payload.get("prompt_cache_options").is_none());

	Ok(())
}

#[test]
fn test_gpt_5_6_chat_completion_ignores_tool_cache_control() -> Result<()> {
	// -- Setup & Fixtures
	let target = ServiceTarget {
		model: ModelIden::new(AdapterKind::OpenAI, "gpt-5.6"),
		auth: AuthData::from_single("test-key"),
		endpoint: Endpoint::from_static("https://api.openai.com/v1/"),
	};
	let chat_req = ChatRequest::from_user("hello")
		.append_tool(Tool::new("get_weather").with_cache_control(CacheControl::Ephemeral));

	// -- Exec
	let web_req = OpenAIAdapter::util_to_web_request_data(
		target,
		crate::adapter::ServiceType::Chat,
		chat_req,
		ChatOptionsSet::default(),
		None,
	)?;

	// -- Check
	assert_eq!(web_req.payload["prompt_cache_options"]["mode"], "explicit");
	assert!(web_req.payload["tools"][0].get("prompt_cache_breakpoint").is_none());

	Ok(())
}

// region:    --- Managed Thinking

#[test]
fn test_managed_body_thinking_disables_zero_effort() -> Result<()> {
	// -- Setup & Fixtures
	let options = ChatOptions::default().with_reasoning_effort(crate::chat::ReasoningEffort::Zero);
	let options_set = ChatOptionsSet::default().with_chat_options(Some(&options));

	// -- Exec
	let payload = payload("test-model", options_set, Some(managed_options()))?;

	// -- Check
	assert_eq!(payload["thinking"]["type"], "disabled");
	assert!(payload.get("reasoning_effort").is_none());

	Ok(())
}

#[test]
fn test_managed_body_thinking_enables_max_effort() -> Result<()> {
	// -- Setup & Fixtures
	let options = ChatOptions::default().with_reasoning_effort(crate::chat::ReasoningEffort::Max);
	let options_set = ChatOptionsSet::default().with_chat_options(Some(&options));

	// -- Exec
	let payload = payload("test-model", options_set, Some(managed_options()))?;

	// -- Check
	assert_eq!(payload["thinking"]["type"], "enabled");
	assert_eq!(payload["reasoning_effort"], "max");

	Ok(())
}

#[test]
fn test_managed_body_thinking_enables_keyword_effort() -> Result<()> {
	// -- Setup & Fixtures
	let options = ChatOptions::default().with_reasoning_effort(crate::chat::ReasoningEffort::Low);
	let options_set = ChatOptionsSet::default().with_chat_options(Some(&options));

	// -- Exec
	let payload = payload("test-model", options_set, Some(managed_options()))?;

	// -- Check
	assert_eq!(payload["thinking"]["type"], "enabled");
	assert_eq!(payload["reasoning_effort"], "low");

	Ok(())
}

#[test]
fn test_managed_body_thinking_preserves_budget_behavior() -> Result<()> {
	// -- Setup & Fixtures
	let options = ChatOptions::default().with_reasoning_effort(crate::chat::ReasoningEffort::Budget(1024));
	let options_set = ChatOptionsSet::default().with_chat_options(Some(&options));

	// -- Exec
	let payload = payload("test-model", options_set, Some(managed_options()))?;

	// -- Check
	assert_eq!(payload["thinking"]["type"], "enabled");
	assert!(payload.get("reasoning_effort").is_none());

	Ok(())
}

#[test]
fn test_managed_body_thinking_omits_fields_without_effort() -> Result<()> {
	// -- Setup & Fixtures
	let options_set = ChatOptionsSet::default();

	// -- Exec
	let payload = payload("test-model", options_set, Some(managed_options()))?;

	// -- Check
	assert!(payload.get("thinking").is_none());
	assert!(payload.get("reasoning_effort").is_none());

	Ok(())
}

#[test]
fn test_managed_body_disabled_thinking_preserves_reasoning_effort_payload() -> Result<()> {
	// -- Setup & Fixtures
	let options = ChatOptions::default().with_reasoning_effort(crate::chat::ReasoningEffort::Max);
	let options_set = ChatOptionsSet::default().with_chat_options(Some(&options));

	// -- Exec
	let payload = payload("test-model", options_set, None)?;

	// -- Check
	assert!(payload.get("thinking").is_none());
	assert_eq!(payload["reasoning_effort"], "max");

	Ok(())
}

#[test]
fn test_managed_body_thinking_uses_model_name_derived_effort() -> Result<()> {
	// -- Setup & Fixtures
	let candidates = ["test-model-high", "test-model:high", "test-model@high"];

	// -- Exec
	let (model_name, derived_effort) = candidates
		.into_iter()
		.find_map(|model_name| {
			let (effort, _) = crate::chat::ReasoningEffort::from_model_name(model_name);
			effort.map(|effort| (model_name, effort))
		})
		.ok_or_else(|| std::io::Error::other("a supported model-name reasoning suffix should be available"))?;
	let payload = payload(model_name, ChatOptionsSet::default(), Some(managed_options()))?;

	// -- Check
	assert!(matches!(derived_effort, crate::chat::ReasoningEffort::High));
	assert_eq!(payload["thinking"]["type"], "enabled");
	assert_eq!(payload["reasoning_effort"], "high");

	Ok(())
}

// endregion: --- Managed Thinking

// region:    --- Support

fn test_model() -> ModelIden {
	ModelIden::new(AdapterKind::OpenAI, "test-model")
}

fn target(model_name: &str) -> ServiceTarget {
	ServiceTarget {
		model: ModelIden::new(AdapterKind::OpenAI, model_name),
		auth: AuthData::from_single("test-key"),
		endpoint: Endpoint::from_static("https://api.openai.com/v1/"),
	}
}

fn managed_options() -> ToWebRequestDataOptions {
	ToWebRequestDataOptions {
		managed_body_thinking: true,
		..Default::default()
	}
}

fn payload(
	model_name: &str,
	options_set: ChatOptionsSet<'_, '_>,
	custom: Option<ToWebRequestDataOptions>,
) -> Result<Value> {
	Ok(OpenAIAdapter::util_to_web_request_data(
		target(model_name),
		crate::adapter::ServiceType::Chat,
		ChatRequest::from_user("hello"),
		options_set,
		custom,
	)?
	.payload)
}

// endregion: --- Support