genai 0.7.0-beta.17

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
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
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
use super::{OpenAIRespStreamer, RespResponse};
use crate::adapter::adapters::openai::OpenAIAdapter;
use crate::adapter::adapters::openai::cache_policy::{
	OpenAiPromptCachePolicy, OpenAiProtocol, is_gpt_5_6_or_later, openai_prompt_cache_policy,
	supports_openai_responses_prompt_cache_options,
};
use crate::adapter::adapters::openai::schema::{
	OpenAiResponseFormatPlan, response_format_plan, tool_parameters_schema,
};
use crate::adapter::adapters::support::get_api_key;
use crate::adapter::{Adapter, AdapterDispatcher, AdapterKind, ServiceType, WebRequestData};
use crate::chat::{
	CacheControl, ChatOptionsSet, ChatRequest, ChatResponse, ChatRole, ChatStream, ChatStreamResponse, ContentPart,
	MessageContent, ReasoningEffort, StopReason, Tool, ToolChoice, ToolConfig, ToolName, Usage,
};
use crate::resolver::{AuthData, Endpoint};
use crate::webc::{EventSourceStream, WebClient, WebResponse};
use crate::{Error, Headers, Result};
use crate::{ModelIden, ServiceTarget};
use reqwest::RequestBuilder;
use serde_json::{Map, Value, json};
use std::collections::BTreeSet;
use value_ext::JsonValueExt;

pub struct OpenAIRespAdapter;

fn openai_resp_tool_choice(tool_choice: Option<&ToolChoice>) -> Option<Value> {
	match tool_choice? {
		ToolChoice::Auto => Some(json!("auto")),
		ToolChoice::None => Some(json!("none")),
		ToolChoice::Required => Some(json!("required")),
		ToolChoice::Tool { name } => Some(json!({
			"type": "function",
			"name": name
		})),
	}
}

impl OpenAIRespAdapter {
	pub const API_KEY_DEFAULT_ENV_NAME: &str = "OPENAI_API_KEY";
}

impl Adapter for OpenAIRespAdapter {
	const DEFAULT_API_KEY_ENV_NAME: Option<&'static str> = Some(Self::API_KEY_DEFAULT_ENV_NAME);

	fn default_auth(_kind: AdapterKind) -> AuthData {
		match Self::DEFAULT_API_KEY_ENV_NAME {
			Some(env_name) => AuthData::from_env(env_name),
			None => AuthData::None,
		}
	}

	fn default_endpoint(_kind: AdapterKind) -> Endpoint {
		const BASE_URL: &str = "https://api.openai.com/v1/";
		Endpoint::from_static(BASE_URL)
	}

	/// Note: Currently returns the common models (see above)
	async fn all_model_names(
		kind: AdapterKind,
		endpoint: Endpoint,
		auth: AuthData,
		web_client: &WebClient,
	) -> Result<Vec<String>> {
		//
		OpenAIAdapter::list_model_names_for_end_target(kind, endpoint, auth, web_client).await
	}

	fn get_service_url(model: &ModelIden, service_type: ServiceType, endpoint: Endpoint) -> Result<String> {
		Self::util_get_service_url(model, service_type, endpoint)
	}

	/// OpenAI Doc: https://platform.openai.com/docs/api-reference/responses/create
	///
	/// ## Note related to OpenAI Responses API
	/// - `.store = false` - To maintain consistent behavior with other chat completions, store is set to false
	/// - `.instructions` For now we do not use the top ".instructions" (genai::ChatRequest.system),
	///   but just add this top system as a regular system message.
	/// - `.summary` reasoning summary is opt-in via `ChatOptions.capture_reasoning_content(true)` → `"detailed"`
	///
	fn to_web_request_data(
		target: ServiceTarget,
		service_type: ServiceType,
		chat_req: ChatRequest,
		chat_options: ChatOptionsSet<'_, '_>,
	) -> Result<WebRequestData> {
		let ServiceTarget { model, auth, endpoint } = target;
		let (_, model_name) = model.model_name.namespace_and_name();
		let adapter_kind = model.adapter_kind;
		let protocol = OpenAiProtocol::Responses;
		let prompt_cache_policy = if supports_openai_responses_prompt_cache_options(&endpoint) {
			openai_prompt_cache_policy(adapter_kind, model_name, &chat_req, &chat_options, protocol)
		} else {
			None
		};
		let response_format_plan = response_format_plan(&chat_options);

		// -- api_key
		let api_key = get_api_key(auth, &model)?;

		// -- url
		let url = AdapterDispatcher::get_service_url(&model, service_type, endpoint)?;

		// -- headers
		let headers = Headers::from(("Authorization".to_string(), format!("Bearer {api_key}")));

		let stream = matches!(service_type, ServiceType::ChatStream);

		// -- compute reasoning_effort and eventual trimmed model_name
		// For now, just for openai AdapterKind
		let (reasoning_effort, model_name): (Option<ReasoningEffort>, &str) =
			if matches!(adapter_kind, AdapterKind::OpenAIResp) {
				let (reasoning_effort, model_name) = chat_options
					.reasoning_effort()
					.cloned()
					.map(|v| (Some(v), model_name))
					.unwrap_or_else(|| ReasoningEffort::from_model_name(model_name));

				(reasoning_effort, model_name)
			} else {
				(None, model_name)
			};

		// -- Extract system prompt before consuming chat_req.
		// Use the Responses API `instructions` field instead of an input system message.
		// `instructions` is the canonical way to set system prompt in the Responses API:
		// - It overrides on each call (important for stateful sessions with previous_response_id)
		// - It separates instructions from conversation items
		// - Inline system messages (ChatRole::System in messages) still go to input as-is
		let instructions = chat_req.system.clone();
		let mut chat_req = chat_req;
		chat_req.system = None;

		// -- Extract stateful session fields before consuming chat_req
		let previous_response_id = chat_req.previous_response_id.clone();
		let explicit_store = chat_req.store;

		// -- Build the basic payload
		let OpenAIRespRequestParts {
			input_items: messages,
			tools,
		} = Self::into_openai_request_parts(&model, chat_req, prompt_cache_policy.as_ref())?;

		// Store: always opt-in. If not explicitly set, default is false.
		// Privacy first: we never implicitly set store=true, even when previous_response_id is set.
		// If previous_response_id is set without store=true, log a warning — the caller must be explicit.
		let store = explicit_store.unwrap_or(false);
		if previous_response_id.is_some() && explicit_store != Some(true) {
			tracing::warn!(
				"previous_response_id is set but store is not explicitly true — \
				 stateful session requires store=true to work. Set `store: Some(true)` explicitly."
			);
		}

		let mut payload = json!({
			"store": store,
			"model": model_name,
			"stream": stream,
		});

		if let Some(policy) = prompt_cache_policy.as_ref() {
			let mut prompt_cache_options = json!({"mode": "explicit"});
			if let Some(ttl) = policy.ttl {
				prompt_cache_options.x_insert("ttl", ttl)?;
			}
			payload.x_insert("prompt_cache_options", prompt_cache_options)?;
		}

		// -- System prompt as instructions
		if let Some(instructions) = &instructions {
			payload.x_insert("instructions", instructions.as_str())?;
		}

		// -- Stateful session: add previous_response_id
		if let Some(prev_id) = &previous_response_id {
			payload.x_insert("previous_response_id", prev_id.as_str())?;
		}

		// -- Set reasoning options
		//
		// The `reasoning` object on the request controls two things:
		//   * `.effort` — how much reasoning the model should do
		//   * `.summary` — whether a text summary of the reasoning is
		//     returned in the response (required to populate
		//     `ChatResponse.reasoning_content` for the Responses API)
		//
		// Either half is sufficient to warrant inserting the object;
		// previously the object was only emitted when `reasoning_effort`
		// was set, which silently defeated `capture_reasoning_content(true)`
		// on its own — callers asking for reasoning capture got no
		// `summary=detailed` opt-in, and every response came back with
		// empty `reasoning_content`.
		let capture_reasoning = chat_options.capture_reasoning_content() == Some(true);
		let effort_keyword = reasoning_effort.and_then(|effort| match effort {
			ReasoningEffort::Zero => Some("none"),
			_ => effort.as_keyword(),
		});

		if effort_keyword.is_some() || capture_reasoning {
			let mut reasoning_obj = json!({});
			if let Some(keyword) = effort_keyword {
				reasoning_obj
					.x_insert("effort", keyword)
					.map_err(|e| Error::Internal(format!("reasoning effort insert: {e}")))?;
			}
			if capture_reasoning {
				reasoning_obj
					.x_insert("summary", "detailed")
					.map_err(|e| Error::Internal(format!("reasoning summary insert: {e}")))?;
			}
			payload.x_insert("reasoning", reasoning_obj)?;
		}

		// -- Opt-in: request encrypted reasoning content (thought signatures)
		// when the caller explicitly asks for reasoning content capture.
		if chat_options.capture_reasoning_content() == Some(true) {
			payload.x_insert("include", json!(["reasoning.encrypted_content"]))?;
		}

		// -- Tools (before messages)
		if let Some(tools) = tools {
			payload.x_insert("/tools", tools)?;
		}
		if let Some(tool_choice) = openai_resp_tool_choice(chat_options.tool_choice()) {
			payload.x_insert("tool_choice", tool_choice)?;
		}

		// -- Messages (after tools)
		payload.x_insert("input", messages)?;

		// -- Compute response format
		let response_format = match response_format_plan {
			OpenAiResponseFormatPlan::None => None,
			OpenAiResponseFormatPlan::JsonMode => Some(json!({"type": "json_object"})),
			OpenAiResponseFormatPlan::JsonSchema { name, schema } => Some(json!({
				"type": "json_schema",
				"name": name,
				"strict": true,
				"schema": schema,
			})),
		};

		// -- Get verbosity
		let verbosity = chat_options.verbosity().and_then(|v| v.as_keyword());

		if response_format.is_some() || verbosity.is_some() {
			let mut value_map = Map::new();
			if let Some(verbosity) = verbosity {
				value_map.insert("verbosity".into(), verbosity.into());
			}
			if let Some(response_format) = response_format {
				value_map.insert("format".into(), response_format);
			}

			payload.x_insert("text", value_map)?;
		}

		// -- Add supported ChatOptions
		if let Some(temperature) = chat_options.temperature() {
			payload.x_insert("temperature", temperature)?;
		}

		if !chat_options.stop_sequences().is_empty() {
			payload.x_insert("stop", chat_options.stop_sequences())?;
		}

		if let Some(max_tokens) = chat_options.max_tokens() {
			payload.x_insert("max_output_tokens", max_tokens)?;
		}
		if let Some(top_p) = chat_options.top_p() {
			payload.x_insert("top_p", top_p)?;
		}
		if let Some(seed) = chat_options.seed() {
			payload.x_insert("seed", seed)?;
		}

		// -- OpenAI prompt cache options
		if let Some(prompt_cache_key) = chat_options.prompt_cache_key() {
			payload.x_insert("prompt_cache_key", prompt_cache_key)?;
		}
		if !is_gpt_5_6_or_later(model_name)
			&& let Some(cache_control) = chat_options.cache_control()
		{
			let prompt_cache_retention = match cache_control {
				CacheControl::Memory | CacheControl::Ephemeral => Some("in_memory"),
				CacheControl::Ephemeral24h => Some("24h"),
				CacheControl::Ephemeral5m | CacheControl::Ephemeral1h => None,
			};
			if let Some(prompt_cache_retention) = prompt_cache_retention {
				payload.x_insert("prompt_cache_retention", prompt_cache_retention)?;
			}
		}

		// -- Provider-specific payload extension
		// Merged last so callers can intentionally override previously set fields.
		if let Some(extra_body) = chat_options.extra_body() {
			payload.x_merge(extra_body.clone())?;
		}
		Ok(WebRequestData { url, headers, payload })
	}

	fn to_chat_response(
		model_iden: ModelIden,
		web_response: WebResponse,
		options_set: ChatOptionsSet<'_, '_>,
	) -> Result<ChatResponse> {
		let WebResponse { body, .. } = web_response;

		let captured_raw_body = options_set.capture_raw_body().unwrap_or_default().then(|| body.clone());

		let resp: RespResponse = serde_json::from_value(body)?;

		// -- Capture the provider_model_iden
		let provider_model_iden = model_iden.from_name(&resp.model);

		// -- Capture the usage
		let usage = resp.usage.map(Usage::from).unwrap_or_default();

		// -- Capture the content
		let mut content: MessageContent = MessageContent::default();
		let reasoning_content: Option<String> = None;

		// -- Extract the content message
		for output_item in resp.output {
			let parts = ContentPart::from_resp_output_item(output_item)?;
			content.extend(parts);
		}

		Ok(ChatResponse {
			content,
			reasoning_content,
			model_iden,
			provider_model_iden,
			stop_reason: Some(StopReason::from(resp.status)),
			usage,
			captured_raw_body,
			response_id: Some(resp.id),
		})
	}

	fn to_chat_stream(
		model_iden: ModelIden,
		reqwest_builder: RequestBuilder,
		options_sets: ChatOptionsSet<'_, '_>,
	) -> Result<ChatStreamResponse> {
		let event_source = EventSourceStream::new(reqwest_builder);
		let openai_stream = OpenAIRespStreamer::new(event_source, model_iden.clone(), options_sets);
		let chat_stream = ChatStream::from_inter_stream(openai_stream);

		Ok(ChatStreamResponse {
			model_iden,
			stream: chat_stream,
		})
	}

	fn to_embed_request_data(
		_service_target: ServiceTarget,
		_embed_req: crate::embed::EmbedRequest,
		_options_set: crate::embed::EmbedOptionsSet<'_, '_>,
	) -> Result<WebRequestData> {
		Err(crate::Error::AdapterNotSupported {
			adapter_kind: crate::adapter::AdapterKind::OpenAIResp,
			feature: "embeddings".to_string(),
		})
	}

	fn to_embed_response(
		_model_iden: ModelIden,
		_web_response: WebResponse,
		_options_set: crate::embed::EmbedOptionsSet<'_, '_>,
	) -> Result<crate::embed::EmbedResponse> {
		Err(crate::Error::AdapterNotSupported {
			adapter_kind: crate::adapter::AdapterKind::OpenAIResp,
			feature: "embeddings".to_string(),
		})
	}
}

/// Support functions for other adapters that share OpenAI APIs
impl OpenAIRespAdapter {
	pub(in crate::adapter::adapters) fn util_get_service_url(
		_model: &ModelIden,
		service_type: ServiceType,
		// -- utility arguments
		default_endpoint: Endpoint,
	) -> Result<String> {
		let base_url = default_endpoint.base_url();
		// Parse into URL and query-params
		let base_url = reqwest::Url::parse(base_url)
			.map_err(|err| Error::Internal(format!("Cannot parse url: {base_url}. Cause:\n{err}")))?;
		let original_query_params = base_url.query().to_owned();

		let suffix = match service_type {
			ServiceType::Chat | ServiceType::ChatStream => "responses",
			ServiceType::Embed => "embeddings", // TODO: Probably needs to say not supported
		};
		let mut full_url = base_url.join(suffix).map_err(|err| {
			Error::Internal(format!(
				"Cannot joing url suffix '{suffix}' for base_url '{base_url}'. Cause:\n{err}"
			))
		})?;
		full_url.set_query(original_query_params);
		Ok(full_url.to_string())
	}

	/// Takes the genai ChatMessages and builds the OpenAIChatRequestParts
	/// - `genai::ChatRequest.system`, if present, is added as the first message with role 'system'.
	/// - All messages get added with the corresponding roles (tools are not supported for now)
	///
	fn into_openai_request_parts(
		model_iden: &ModelIden,
		chat_req: ChatRequest,
		cache_policy: Option<&OpenAiPromptCachePolicy>,
	) -> Result<OpenAIRespRequestParts> {
		let mut input_items: Vec<Value> = Vec::new();
		let custom_tool_names = chat_req
			.tools
			.as_ref()
			.into_iter()
			.flatten()
			.filter(|tool| tool.custom_format.is_some())
			.map(|tool| tool.name.as_str().to_string())
			.collect::<BTreeSet<_>>();
		let mut custom_call_ids = BTreeSet::new();

		// -- Process the system
		if let Some(system_msg) = chat_req.system {
			input_items.push(json!({"role": "system", "content": system_msg}));
		}

		let mut unamed_file_count = 0;

		// -- Process the messages
		for msg in chat_req.messages {
			let cache_controlled = cache_policy.is_some()
				&& msg
					.options
					.as_ref()
					.and_then(|options| options.cache_control.as_ref())
					.is_some();

			// Note: Will handle more types later
			match msg.role {
				// For now, system and tool messages go to the system
				ChatRole::System => {
					if let Some(content) = msg.content.into_joined_texts() {
						if cache_controlled {
							let mut values = vec![json!({"type": "input_text", "text": content})];
							apply_resp_cache_breakpoint(model_iden, &mut values, "message")?;
							input_items.push(json!({"role": "system", "content": values}));
						} else {
							input_items.push(json!({"role": "system", "content": content}))
						}
					}
					// TODO: Probably need to warn if it is a ToolCalls type of content
				}

				// User - For now support Text and Binary
				ChatRole::User => {
					// -- If we have only text, then, we jjust returned the joined_texts
					if msg.content.is_text_only() && !cache_controlled {
						// NOTE: for now, if no content, just return empty string (respect current logic)
						let content = json!(msg.content.joined_texts().unwrap_or_else(String::new));
						input_items.push(json! ({"role": "user", "content": content}));
					} else {
						let mut values: Vec<Value> = Vec::new();

						for part in msg.content {
							match part {
								// -- Simple Text
								ContentPart::Text(content) => {
									values.push(json!({"type": "input_text", "text": content}))
								}
								// -- Binary
								ContentPart::Binary(mut binary) => {
									let is_image = binary.is_image();

									// Process the image
									if is_image {
										let image_url = binary.into_url();
										let input_image = json!({
											"type": "input_image",
											"detail": "auto",
											"image_url": image_url
										});
										values.push(input_image);
									}
									// Process file
									// TODO - Needs to support audio
									else {
										let mut input_file = Map::new();
										input_file.insert("type".into(), "input_file".into());

										// Set the file name if not defined (otherwise error)
										if let Some(file_name) = binary.name.take() {
											input_file.insert("filename".into(), file_name.into());
										} else {
											unamed_file_count += 1;
											input_file
												.insert("filename".into(), format!("file-{unamed_file_count}").into());
										}

										let file_url = binary.into_url();
										if file_url.starts_with("data") {
											input_file.insert("file_data".into(), file_url.into());
										} else {
											input_file.insert("file_url".into(), file_url.into());
										}
										let input_file: Value = input_file.into();

										values.push(input_file);
									}
								}

								// Use `match` instead of `if let`. This will allow to future-proof this
								// implementation in case some new message content types would appear,
								// this way library would not compile if not all methods are implemented
								// continue would allow to gracefully skip pushing unserializable message
								// TODO: Probably need to warn if it is a ToolCalls type of content
								ContentPart::ToolCall(_) => (),
								ContentPart::ToolResponse(_) => (),
								ContentPart::ThoughtSignature(_) => (),
								ContentPart::ReasoningContent(_) => (),
								// Custom are ignored for this logic
								ContentPart::Custom(_) => {}
							}
						}
						if cache_controlled {
							apply_resp_cache_breakpoint(model_iden, &mut values, "message")?;
						}
						input_items.push(json! ({"role": "user", "content": values}));
					}
				}

				// Assistant - For now support Text and ToolCalls
				ChatRole::Assistant => {
					// Here we make sure if multiple text content part, we keep them in the same assistant message
					// In the new OpenAI Responses API, the tool call are just items out of assistant message
					let mut item_message_content: Vec<Value> = Vec::new();

					// Pre-pass: encrypted reasoning blobs from prior turns must be
					// carried back as top-level `{type: "reasoning"}` input items
					// to keep the Responses-API prefix cache warm. Without this,
					// even a verbatim resend of a prior turn re-processes every
					// token. They precede the assistant message they belong to,
					// mirroring the order the API emits them in the streaming
					// response. The blobs ride in on `ContentPart::ThoughtSignature`
					// parts (from `StreamEnd::captured_content`) or on
					// `ToolCall::thought_signatures` (rust-genai's streamer stashes
					// captured blobs there when there are tool calls).
					for part in msg.content.iter() {
						if let ContentPart::ThoughtSignature(blob) = part {
							input_items.push(json!({
								"type": "reasoning",
								"encrypted_content": blob,
								"summary": [],
							}));
						}
					}
					for part in msg.content.iter() {
						if let ContentPart::ToolCall(tool_call) = part
							&& let Some(sigs) = tool_call.thought_signatures.as_ref()
						{
							for blob in sigs {
								input_items.push(json!({
									"type": "reasoning",
									"encrypted_content": blob,
									"summary": [],
								}));
							}
						}
					}

					for part in msg.content {
						match part {
							ContentPart::Text(text) => {
								item_message_content.push(json!({
										"type": "output_text",
										"text": text
								}));
							}
							ContentPart::ToolCall(tool_call) => {
								// Make sure to create the assistant message
								if !item_message_content.is_empty() {
									input_items.push(json!({
										"type": "message",
										"role": "assistant",
										"content": item_message_content
									}));
									item_message_content = Vec::new();
								}
								if custom_tool_names.contains(&tool_call.fn_name) {
									let input = tool_call
										.fn_arguments
										.as_str()
										.map_or_else(|| tool_call.fn_arguments.to_string(), str::to_string);
									custom_call_ids.insert(tool_call.call_id.clone());
									input_items.push(json!({
										"type": "custom_tool_call",
										"call_id": tool_call.call_id,
										"name": tool_call.fn_name,
										"input": input,
									}));
								} else {
									// NOTE: Flatten for OpenAI Responses API.
									input_items.push(json!({
										"type": "function_call",
										"call_id": tool_call.call_id,
										"name": tool_call.fn_name,
										"arguments": tool_call.fn_arguments.to_string(),
									}));
								}
							}

							// TODO: Probably need towarn on this one (probably need to add binary here)
							ContentPart::Binary(_) => {}
							ContentPart::ToolResponse(_) => {}
							// ThoughtSignature and ReasoningContent are emitted as
							// top-level `type:reasoning` items in the pre-pass above.
							ContentPart::ThoughtSignature(_) => {}
							ContentPart::ReasoningContent(_) => {}
							// Custom are ignored for this logic
							ContentPart::Custom(_) => {}
						}
					}

					// Make sure we handle the rest of the assistant message
					if !item_message_content.is_empty() {
						input_items.push(json!({
							"type": "message",
							"role": "assistant",
							"content": item_message_content
						}));
					}
				}

				// Tool Response (Function tool call output)
				ChatRole::Tool => {
					for part in msg.content {
						if let ContentPart::ToolResponse(tool_response) = part {
							let response_type = if custom_call_ids.contains(&tool_response.call_id) {
								"custom_tool_call_output"
							} else {
								"function_call_output"
							};
							input_items.push(json!({
								"type": response_type,
								"call_id": tool_response.call_id,
								"output": tool_response.content,
							}));
						}
					}

					// TODO: Probably need to trace/warn that this will be ignored
				}
			}
		}

		// -- Process the tools
		let tools = chat_req
			.tools
			.map(|tools| tools.into_iter().map(Self::tool_to_openai_tool).collect::<Result<Vec<Value>>>())
			.transpose()?;

		Ok(OpenAIRespRequestParts { input_items, tools })
	}

	fn tool_to_openai_tool(tool: Tool) -> Result<Value> {
		let Tool {
			name,
			description,
			schema,
			custom_format,
			strict,
			config,
			..
		} = tool;

		let name = match name {
			ToolName::WebSearch => "web_search".to_string(),
			ToolName::Custom(name) => name,
		};

		let tool_value = if let Some(format) = custom_format {
			json!({
				"type": "custom",
				"name": name,
				"description": description,
				"format": format,
			})
		} else {
			match name.as_ref() {
				"web_search" => {
					let mut tool_value = json!({"type": "web_search"});
					match config {
						Some(ToolConfig::WebSearch(_ws_config)) => {
							// FIXME: Implement what is posible in filters
						}
						Some(ToolConfig::Custom(config_value)) => {
							// IMPORTANT: Here like anthropic, we merge it on top of the toll value
							//            (and not as value of "name" as this would not fit that api)
							//            Gemini does a `{name: config}` which fit that API
							tool_value.x_merge(config_value)?;
						}
						None => (),
					};
					tool_value
				}
				name => {
					let strict = strict.unwrap_or(false);
					let parameters = tool_parameters_schema(schema, strict);

					json!({
						"type": "function",
						"name": name,
						"description": description,
						"parameters": parameters,
						"strict": strict,
					})
				}
			}
		};

		Ok(tool_value)
	}
}
// region:    --- Support

struct OpenAIRespRequestParts {
	input_items: Vec<Value>,
	tools: Option<Vec<Value>>,
}

fn apply_resp_cache_breakpoint(_model_iden: &ModelIden, content: &mut [Value], _scope: &'static str) -> Result<()> {
	let Some(content_block) = content.iter_mut().rev().find(|value| {
		matches!(
			value.get("type").and_then(Value::as_str),
			Some("input_text" | "input_image" | "input_file")
		)
	}) else {
		return Ok(());
	};

	content_block.x_insert("prompt_cache_breakpoint", json!({"mode": "explicit"}))?;
	Ok(())
}

// endregion: --- Support

// region:    --- Tests

#[cfg(test)]
mod tests {
	type Result<T> = core::result::Result<T, Box<dyn std::error::Error>>;

	use super::*;
	use crate::adapter::AdapterKind;
	use crate::chat::{ChatMessage, ChatOptions, JsonSpec, Tool, ToolCall, ToolChoice, ToolResponse};

	#[test]
	fn test_cache_control_without_eligible_content_does_not_fail_response_request() {
		let target = ServiceTarget {
			model: ModelIden::new(AdapterKind::OpenAIResp, "gpt-5.6"),
			auth: AuthData::from_single("test-key"),
			endpoint: OpenAIRespAdapter::default_endpoint(AdapterKind::OpenAIResp),
		};
		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]);

		let web_req =
			OpenAIRespAdapter::to_web_request_data(target, ServiceType::Chat, chat_req, ChatOptionsSet::default())
				.expect("unsupported breakpoint placement should be ignored");

		assert_eq!(web_req.payload["prompt_cache_options"]["mode"], "explicit");
	}

	#[test]
	fn custom_grammar_tool_and_roundtrip_use_responses_native_items() {
		let target = ServiceTarget {
			model: ModelIden::new(AdapterKind::OpenAIResp, "gpt-5.6"),
			auth: AuthData::from_single("test-key"),
			endpoint: OpenAIRespAdapter::default_endpoint(AdapterKind::OpenAIResp),
		};
		let patch = "*** Begin Patch\n*** Update File: source.c\n@@\n-old\n+new\n*** End Patch\n";
		let assistant = ChatMessage::assistant(vec![ToolCall {
			call_id: "call_patch".to_string(),
			fn_name: "apply_patch".to_string(),
			fn_arguments: Value::String(patch.to_string()),
			thought_signatures: None,
		}]);
		let response = ChatMessage::from(ToolResponse::new("call_patch", "Done!"));
		let format = json!({
			"type": "grammar",
			"syntax": "lark",
			"definition": "start: PATCH",
		});
		let request = ChatRequest::new(vec![ChatMessage::user("patch it"), assistant, response]).with_tools(vec![
			Tool::new("apply_patch")
				.with_description("Apply a patch")
				.with_custom_format(format.clone()),
		]);

		let web_req =
			OpenAIRespAdapter::to_web_request_data(target, ServiceType::Chat, request, ChatOptionsSet::default())
				.unwrap();
		assert_eq!(
			web_req.payload["tools"][0],
			json!({
				"type": "custom",
				"name": "apply_patch",
				"description": "Apply a patch",
				"format": format,
			})
		);
		let input = web_req.payload["input"].as_array().unwrap();
		assert!(input.iter().any(|item| {
			item["type"] == "custom_tool_call" && item["call_id"] == "call_patch" && item["input"] == patch
		}));
		assert!(input.iter().any(|item| {
			item["type"] == "custom_tool_call_output" && item["call_id"] == "call_patch" && item["output"] == "Done!"
		}));
	}

	#[test]
	fn test_extra_body_merged_into_response_payload() {
		let chat_options = ChatOptions::default()
			.with_top_p(0.3)
			.with_extra_body(json!({"top_p": 0.9, "metadata": {"source": "test"}}));
		let options_set = ChatOptionsSet::default().with_chat_options(Some(&chat_options));
		let target = ServiceTarget {
			model: ModelIden::new(AdapterKind::OpenAIResp, "gpt-5-mini"),
			auth: AuthData::from_single("test-key"),
			endpoint: OpenAIRespAdapter::default_endpoint(AdapterKind::OpenAIResp),
		};

		let web_req = OpenAIRespAdapter::to_web_request_data(
			target,
			ServiceType::Chat,
			ChatRequest::from_user("hello"),
			options_set,
		)
		.expect("to_web_request_data should succeed");

		assert_eq!(web_req.payload["top_p"], 0.9);
		assert_eq!(web_req.payload["metadata"]["source"], "test");
	}

	#[test]
	fn pydantic_union_schema_is_sanitized_for_responses() {
		let schema = json!({
			"type": "object",
			"properties": {
				"animal": {
					"discriminator": {"propertyName": "kind"},
					"oneOf": [{"$ref": "#/$defs/Cat"}, {"$ref": "#/$defs/Dog"}]
				}
			},
			"$defs": {
				"Cat": {
					"type": "object",
					"properties": {"kind": {"const": "cat"}},
					"required": ["kind"]
				},
				"Dog": {
					"type": "object",
					"properties": {"kind": {"const": "dog"}},
					"required": ["kind"]
				}
			}
		});
		let options = ChatOptions::default().with_response_format(JsonSpec::new("union", schema));
		let options_set = ChatOptionsSet::default().with_chat_options(Some(&options));
		let target = ServiceTarget {
			model: ModelIden::new(AdapterKind::OpenAIResp, "gpt-5-mini"),
			auth: AuthData::from_single("test-key"),
			endpoint: OpenAIRespAdapter::default_endpoint(AdapterKind::OpenAIResp),
		};

		let web_req = OpenAIRespAdapter::to_web_request_data(
			target,
			ServiceType::Chat,
			ChatRequest::from_user("return an animal"),
			options_set,
		)
		.unwrap();

		let animal = &web_req.payload["text"]["format"]["schema"]["properties"]["animal"];
		assert!(animal.get("oneOf").is_none());
		assert_eq!(animal["discriminator"], json!({"propertyName": "kind"}));
		assert_eq!(
			animal["anyOf"],
			json!([{"$ref": "#/$defs/Cat"}, {"$ref": "#/$defs/Dog"}])
		);
	}

	#[test]
	fn dynamic_map_schema_is_sent_to_backend_for_validation() {
		let schema = json!({
			"type": "object",
			"properties": {
				"lookup": {"type": "object", "additionalProperties": {"type": "integer"}}
			}
		});
		let options = ChatOptions::default().with_response_format(JsonSpec::new("mapping", schema));
		let options_set = ChatOptionsSet::default().with_chat_options(Some(&options));
		let target = ServiceTarget {
			model: ModelIden::new(AdapterKind::OpenAIResp, "gpt-5-mini"),
			auth: AuthData::from_single("test-key"),
			endpoint: OpenAIRespAdapter::default_endpoint(AdapterKind::OpenAIResp),
		};

		let web_req = OpenAIRespAdapter::to_web_request_data(
			target,
			ServiceType::Chat,
			ChatRequest::from_user("return a mapping"),
			options_set,
		)
		.unwrap();

		assert_eq!(
			web_req.payload["text"]["format"]["schema"]["properties"]["lookup"]["additionalProperties"],
			json!({"type": "integer"})
		);
	}

	#[test]
	fn test_tool_choice_specific_tool_serialized_on_response_payload() {
		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: ModelIden::new(AdapterKind::OpenAIResp, "gpt-5-mini"),
			auth: AuthData::from_single("test-key"),
			endpoint: OpenAIRespAdapter::default_endpoint(AdapterKind::OpenAIResp),
		};
		let chat_req = ChatRequest::from_user("weather").with_tools(vec![Tool::new("get_weather")]);

		let web_req = OpenAIRespAdapter::to_web_request_data(target, ServiceType::Chat, chat_req, options_set)
			.expect("to_web_request_data should succeed");

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

	/// Test that assistant message text content uses "output_text" type (not "input_text").
	///
	/// This is required by OpenAI's Responses API - assistant content is model output,
	/// so it must use "output_text". Using "input_text" causes:
	/// "Invalid value: 'input_text'. Supported values are: 'output_text' and 'refusal'."
	#[test]
	fn test_assistant_message_uses_output_text_content_type() {
		let model_iden = ModelIden::new(AdapterKind::OpenAIResp, "gpt-5-codex");

		// Create a chat request with an assistant message
		let chat_req = ChatRequest::default()
			.with_system("You are a helpful assistant.")
			.append_message(ChatMessage::user("What's the weather?"))
			.append_message(ChatMessage::assistant("The weather is sunny."));

		// Serialize to OpenAI Responses API format
		let parts = OpenAIRespAdapter::into_openai_request_parts(&model_iden, chat_req, None)
			.expect("Should serialize successfully");

		// Find the assistant message in input_items
		let assistant_msg = parts
			.input_items
			.iter()
			.find(|item| {
				item.get("type").and_then(|t| t.as_str()) == Some("message")
					&& item.get("role").and_then(|r| r.as_str()) == Some("assistant")
			})
			.expect("Should have an assistant message");

		// Check the content uses "output_text" type
		let content = assistant_msg
			.get("content")
			.and_then(|c| c.as_array())
			.expect("Assistant message should have content array");

		assert!(!content.is_empty(), "Content should not be empty");

		let first_content = &content[0];
		let content_type = first_content
			.get("type")
			.and_then(|t| t.as_str())
			.expect("Content should have a type");

		assert_eq!(
			content_type, "output_text",
			"Assistant message content should use 'output_text' type, not 'input_text'"
		);
	}

	#[test]
	fn test_gpt_5_6_responses_defaults_to_explicit_cache_mode() {
		let target = ServiceTarget {
			model: ModelIden::new(AdapterKind::OpenAIResp, "gpt-5.6"),
			auth: AuthData::from_single("test-key"),
			endpoint: OpenAIRespAdapter::default_endpoint(AdapterKind::OpenAIResp),
		};

		let web_req = OpenAIRespAdapter::to_web_request_data(
			target,
			ServiceType::Chat,
			ChatRequest::from_user("hello"),
			ChatOptionsSet::default(),
		)
		.expect("to_web_request_data should succeed");

		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["input"][0]["content"][0]
				.get("prompt_cache_breakpoint")
				.is_none()
		);
	}

	#[test]
	fn test_gpt_5_6_codex_responses_endpoint_omits_prompt_cache_options() -> Result<()> {
		let target = ServiceTarget {
			model: ModelIden::new(AdapterKind::OpenAIResp, "gpt-5.6"),
			auth: AuthData::from_single("test-key"),
			endpoint: Endpoint::from_static("https://chatgpt.com/backend-api/codex/"),
		};

		let web_req = OpenAIRespAdapter::to_web_request_data(
			target,
			ServiceType::Chat,
			ChatRequest::from_user("hello"),
			ChatOptionsSet::default(),
		)?;

		assert!(web_req.payload.get("prompt_cache_options").is_none());
		Ok(())
	}

	#[test]
	fn test_gpt_5_6_responses_cache_key_uses_api_default_cache_mode() {
		let target = ServiceTarget {
			model: ModelIden::new(AdapterKind::OpenAIResp, "gpt-5.6-mini"),
			auth: AuthData::from_single("test-key"),
			endpoint: OpenAIRespAdapter::default_endpoint(AdapterKind::OpenAIResp),
		};
		let chat_options = ChatOptions::default().with_prompt_cache_key("stable-key");
		let options_set = ChatOptionsSet::default().with_chat_options(Some(&chat_options));

		let web_req = OpenAIRespAdapter::to_web_request_data(
			target,
			ServiceType::Chat,
			ChatRequest::from_user("hello"),
			options_set,
		)
		.expect("to_web_request_data should succeed");

		assert!(web_req.payload.get("prompt_cache_options").is_none());
		assert!(
			web_req.payload["input"][0]["content"][0]
				.get("prompt_cache_breakpoint")
				.is_none()
		);
	}

	#[test]
	fn test_gpt_5_6_responses_places_breakpoint_on_last_eligible_content_block() {
		let target = ServiceTarget {
			model: ModelIden::new(AdapterKind::OpenAIResp, "gpt-5.6"),
			auth: AuthData::from_single("test-key"),
			endpoint: OpenAIRespAdapter::default_endpoint(AdapterKind::OpenAIResp),
		};
		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),
		]);

		let web_req =
			OpenAIRespAdapter::to_web_request_data(target, ServiceType::Chat, chat_req, ChatOptionsSet::default())
				.expect("to_web_request_data should succeed");

		let blocks = web_req.payload["input"][0]["content"]
			.as_array()
			.expect("message content should be an array");
		assert!(blocks[0].get("prompt_cache_breakpoint").is_none());
		assert!(blocks[1].get("prompt_cache_breakpoint").is_none());
		assert_eq!(blocks[2]["prompt_cache_breakpoint"]["mode"], "explicit");
	}

	#[test]
	fn test_gpt_5_6_responses_ignores_tool_cache_control() {
		let target = ServiceTarget {
			model: ModelIden::new(AdapterKind::OpenAIResp, "gpt-5.6"),
			auth: AuthData::from_single("test-key"),
			endpoint: OpenAIRespAdapter::default_endpoint(AdapterKind::OpenAIResp),
		};
		let chat_req = ChatRequest::from_user("hello")
			.append_tool(Tool::new("get_weather").with_cache_control(CacheControl::Ephemeral));

		let web_req =
			OpenAIRespAdapter::to_web_request_data(target, ServiceType::Chat, chat_req, ChatOptionsSet::default())
				.expect("tool cache control should be ignored");

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

	#[test]
	fn test_gpt_5_5_responses_keeps_legacy_cache_retention() {
		let target = ServiceTarget {
			model: ModelIden::new(AdapterKind::OpenAIResp, "gpt-5.5"),
			auth: AuthData::from_single("test-key"),
			endpoint: OpenAIRespAdapter::default_endpoint(AdapterKind::OpenAIResp),
		};
		let chat_options = ChatOptions::default().with_cache_control(CacheControl::Ephemeral24h);
		let options_set = ChatOptionsSet::default().with_chat_options(Some(&chat_options));

		let web_req = OpenAIRespAdapter::to_web_request_data(
			target,
			ServiceType::Chat,
			ChatRequest::from_user("hello"),
			options_set,
		)
		.expect("to_web_request_data should succeed");

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

// endregion: --- Tests