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
//! Message conversion utilities for Responses API → Chat API.
use crate::error::ConversionError;
use crate::types::chat_api::{
ChatMessage, Content, ContentBlock, FunctionCall, ImageUrlField, ImageUrlObject, MessageRole,
ToolCall,
};
use crate::types::response_api::{
Content as ResponseContent, ContentPart, InputItemOrString,
};
/// Convert input (with optional instructions) to Chat messages.
pub fn convert_input_to_messages(
input: InputItemOrString,
instructions: Option<String>,
enforce_tool_result_adjacency: bool,
) -> Result<Vec<ChatMessage>, ConversionError> {
let mut messages = Vec::new();
// Add system message from instructions
if let Some(inst) = instructions {
messages.push(ChatMessage {
role: MessageRole::System,
content: Content::String(inst),
name: None,
annotations: None,
tool_calls: None,
tool_call_id: None,
function_call: None,
refusal: None,
});
}
// Convert input items
match input {
InputItemOrString::String(s) => {
messages.push(ChatMessage {
role: MessageRole::User,
content: Content::String(s),
name: None,
annotations: None,
tool_calls: None,
tool_call_id: None,
function_call: None,
refusal: None,
});
}
InputItemOrString::Array(items) => {
let mut pending_tool_calls: Option<Vec<ToolCall>> = None;
let mut emitted_tool_call_ids: std::collections::HashSet<String> =
std::collections::HashSet::new();
let mut emitted_tool_call_names: std::collections::HashMap<String, String> =
std::collections::HashMap::new();
for item in items {
match item.item_type {
crate::types::response_api::InputItemType::Message => {
let role = match item.role.as_deref() {
Some("developer") => MessageRole::Developer,
Some("system") => MessageRole::System,
Some("assistant") => MessageRole::Assistant,
Some("tool") => MessageRole::Tool,
Some("user") | None => MessageRole::User,
Some(other) => {
return Err(ConversionError::InvalidFormat(format!(
"unsupported message role: {other}"
)));
}
};
// tool_call_id is only valid on role=tool per Chat API spec
// (ChatCompletionRequestToolMessage). Avoid leaking it to other roles.
let tool_call_id_for_msg = if matches!(role, MessageRole::Tool) {
item.call_id.clone()
} else {
None
};
let content = extract_content(&item.content)?;
// If we have pending tool calls and now receive an assistant message,
// merge them into ONE assistant message. Some providers require
// tool outputs to immediately follow the assistant tool_calls message.
if enforce_tool_result_adjacency && role == MessageRole::Assistant {
if let Some(tool_calls) = pending_tool_calls.take() {
for tc in &tool_calls {
emitted_tool_call_ids.insert(tc.id.clone());
emitted_tool_call_names.insert(tc.id.clone(), tc.function.name.clone());
}
messages.push(ChatMessage {
role,
content,
name: item.name,
annotations: None,
tool_calls: Some(tool_calls),
tool_call_id: tool_call_id_for_msg.clone(),
function_call: None,
refusal: None,
});
tracing::debug!(
"[REQUEST_CONVERT] merged assistant message with pending tool_calls to keep tool result adjacency"
);
continue;
}
} else if let Some(tool_calls) = pending_tool_calls.take() {
// Flush pending tool calls before non-assistant message items
for tc in &tool_calls {
emitted_tool_call_ids.insert(tc.id.clone());
emitted_tool_call_names.insert(tc.id.clone(), tc.function.name.clone());
}
messages.push(ChatMessage {
role: MessageRole::Assistant,
content: Content::String(String::new()),
name: None,
annotations: None,
tool_calls: Some(tool_calls),
tool_call_id: None,
function_call: None,
refusal: None,
});
}
messages.push(ChatMessage {
role,
content,
name: item.name,
annotations: None,
tool_calls: None,
tool_call_id: tool_call_id_for_msg,
function_call: None,
refusal: None,
});
}
crate::types::response_api::InputItemType::FunctionCall => {
// Accumulate FunctionCall items into pending_tool_calls
let arguments = item.arguments.unwrap_or_default();
let name = item
.name
.ok_or_else(|| ConversionError::MissingField("name".to_string()))?;
// Use call_id to match FunctionCallOutput's call_id reference
let id = item.call_id.or(item.id).unwrap_or_else(|| format!("call_{}", uuid::Uuid::new_v4()));
let tool_call = ToolCall {
id,
tool_type: "function".to_string(),
function: FunctionCall { name, arguments },
};
pending_tool_calls.get_or_insert_with(Vec::new).push(tool_call);
}
crate::types::response_api::InputItemType::FunctionCallOutput => {
let call_id = item
.call_id
.clone()
.unwrap_or_else(|| format!("call_{}", uuid::Uuid::new_v4()));
let output_name = item
.name
.clone()
.or_else(|| emitted_tool_call_names.get(&call_id).cloned())
.unwrap_or_else(|| "unknown_tool".to_string());
// Flush pending tool calls before FunctionCallOutput
if let Some(tool_calls) = pending_tool_calls.take() {
for tc in &tool_calls {
emitted_tool_call_ids.insert(tc.id.clone());
emitted_tool_call_names.insert(tc.id.clone(), tc.function.name.clone());
}
messages.push(ChatMessage {
role: MessageRole::Assistant,
content: Content::String(String::new()),
name: None,
annotations: None,
tool_calls: Some(tool_calls),
tool_call_id: None,
function_call: None,
refusal: None,
});
}
// Some providers require a preceding assistant.tool_calls message
// before each tool result. If missing in the current input window,
// synthesize a minimal one to preserve protocol validity.
if enforce_tool_result_adjacency && !emitted_tool_call_ids.contains(&call_id) {
tracing::warn!(
"[REQUEST_CONVERT] function_call_output without preceding function_call, synthesizing assistant tool_call (call_id={}, name={})",
call_id,
output_name
);
let synthetic_tool_call = ToolCall {
id: call_id.clone(),
tool_type: "function".to_string(),
function: FunctionCall {
name: output_name.clone(),
arguments: "{}".to_string(),
},
};
messages.push(ChatMessage {
role: MessageRole::Assistant,
content: Content::String(String::new()),
name: None,
annotations: None,
tool_calls: Some(vec![synthetic_tool_call]),
tool_call_id: None,
function_call: None,
refusal: None,
});
emitted_tool_call_ids.insert(call_id.clone());
}
messages.push(ChatMessage {
role: MessageRole::Tool,
content: Content::String(item.output.unwrap_or_default()),
name: item.name,
annotations: None,
tool_calls: None,
tool_call_id: Some(call_id.clone()),
function_call: None,
refusal: None,
});
tracing::debug!(
"[REQUEST_CONVERT] emitted tool result message (call_id={}, name={})",
call_id,
output_name
);
}
}
}
// Handle any remaining tool calls
if let Some(tool_calls) = pending_tool_calls {
for tc in &tool_calls {
emitted_tool_call_ids.insert(tc.id.clone());
emitted_tool_call_names.insert(tc.id.clone(), tc.function.name.clone());
}
messages.push(ChatMessage {
role: MessageRole::Assistant,
content: Content::String(String::new()),
name: None,
annotations: None,
tool_calls: Some(tool_calls),
tool_call_id: None,
function_call: None,
refusal: None,
});
}
tracing::debug!(
"[REQUEST_CONVERT] input array converted: messages={}, emitted_tool_calls={}",
messages.len(),
emitted_tool_call_ids.len()
);
}
}
Ok(messages)
}
/// Extract text content from Response API content.
pub fn extract_content(content: &Option<ResponseContent>) -> Result<Content, ConversionError> {
match content {
Some(ResponseContent::String(s)) => Ok(Content::String(s.clone())),
Some(ResponseContent::Array(parts)) => {
let mut blocks: Vec<ContentBlock> = Vec::new();
for part in parts {
match part {
ContentPart::InputText { text } => blocks.push(ContentBlock {
block_type: "text".to_string(),
text: Some(text.clone()),
image_url: None,
}),
ContentPart::OutputText { text, .. } => blocks.push(ContentBlock {
block_type: "text".to_string(),
text: Some(text.clone()),
image_url: None,
}),
ContentPart::InputImage { image_url } => blocks.push(ContentBlock {
block_type: "image_url".to_string(),
text: None,
image_url: Some(ImageUrlField::Object(ImageUrlObject {
url: image_url.clone(),
})),
}),
ContentPart::InputFile { file_url, file_id } => {
let file_ref = file_url
.as_ref()
.or(file_id.as_ref())
.cloned()
.unwrap_or_else(|| "unknown_file".to_string());
blocks.push(ContentBlock {
block_type: "text".to_string(),
text: Some(format!("[input_file] {}", file_ref)),
image_url: None,
});
}
}
}
if blocks.is_empty() {
Ok(Content::String(String::new()))
} else if blocks.len() == 1 && blocks[0].block_type == "text" {
Ok(Content::String(blocks[0].text.clone().unwrap_or_default()))
} else {
Ok(Content::Array(blocks))
}
}
None => Ok(Content::String(String::new())),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::response_api::{Content as ResponseContent, ContentPart};
#[test]
fn test_extract_content_image_url_serializes_as_object() {
// OpenAI `ChatCompletionRequestMessageContentPartImage.image_url` is a
// required object `{url, detail?}`, not a string.
let content = ResponseContent::Array(vec![
ContentPart::InputText { text: "see this:".into() },
ContentPart::InputImage { image_url: "https://example.com/x.png".into() },
]);
let chat_content = extract_content(&Some(content)).unwrap();
let json = serde_json::to_value(&chat_content).unwrap();
let arr = json.as_array().expect("array content");
let image_block = arr
.iter()
.find(|b| b["type"] == "image_url")
.expect("image_url block present");
assert!(image_block["image_url"].is_object(), "image_url must be object: {image_block}");
assert_eq!(image_block["image_url"]["url"], "https://example.com/x.png");
}
#[test]
fn test_unknown_role_returns_error() {
let input = InputItemOrString::Array(vec![crate::types::response_api::InputItem {
id: None,
item_type: crate::types::response_api::InputItemType::Message,
role: Some("alien".to_string()),
content: Some(ResponseContent::String("hi".into())),
name: None,
arguments: None,
call_id: None,
output: None,
namespace: None,
}]);
let err = convert_input_to_messages(input, None, false)
.expect_err("unknown role must fail");
assert!(matches!(err, ConversionError::InvalidFormat(_)));
}
}