use super::types::{
FunctionCall, ImageUrl, OpenAIContent, OpenAIContentItem, OpenAIMessage, OpenAIRequest,
OpenAITool, OpenAIToolCall, OpenAIToolChoice, OpenAIToolFunction,
};
use crate::openai_compatible::OpenAiCompatProfile;
use crate::types::{
Attachment, ChatRequest, Content, ContentPart, Effort, Message, Role, ToolChoice,
ToolDefinition, ToolResult, ToolUse, replay_safe_tool_args,
};
use anyhow::Result;
use tracing::debug;
pub(in crate::openai_compatible) fn to_message_request(
request: &ChatRequest,
provider_id: &str,
supported_efforts: Option<&[Effort]>,
) -> Result<OpenAIRequest> {
let profile = OpenAiCompatProfile::from_model(provider_id, &request.model);
let thinking = profile.thinking_params(supported_efforts, request.effort);
tracing::debug!(
model = %request.model,
thinking = ?request.effort,
reasoning_effort = ?thinking.reasoning_effort,
thinking_config = ?thinking.thinking.as_ref().map(|config| config.thinking_type()),
enable_thinking = ?thinking.enable_thinking,
"OpenAI-compatible thinking config"
);
let mut messages = Vec::new();
if profile.supports_system_role() {
if profile.merges_system_messages() {
let system_text = request.system_text();
if !system_text.is_empty() {
messages.push(OpenAIMessage::system_text(system_text));
}
} else {
for system in request.system_prompts() {
messages.push(OpenAIMessage::system_text(system.to_string()));
}
}
}
for message in request.messages.iter() {
messages.extend(to_open_ai_message(message.as_ref(), profile)?);
}
if !profile.supports_system_role() {
let system_text = request.system_text();
if !system_text.is_empty() {
if let Some(msg) = messages.iter_mut().find(|m| m.role == "user") {
msg.prepend_text(&system_text);
} else {
messages
.insert(0, OpenAIMessage::new("user", Some(OpenAIContent::Text(system_text))));
}
}
}
let tools = convert_tools(request.tools.to_vec());
let tool_choice = request.resolved_tool_choice()?.map(|choice| match choice {
ToolChoice::Required => OpenAIToolChoice::Required,
ToolChoice::Tool(name) => OpenAIToolChoice::Function { name: name.clone() },
ToolChoice::Forbid => OpenAIToolChoice::None,
});
let wire = OpenAIRequest {
model: request.model.clone(),
messages,
reasoning_effort: thinking.reasoning_effort,
max_tokens: request.max_tokens,
temperature: request.temperature,
stop: request.stop_sequences.as_ref().map(|s| serde_json::json!(s)),
tools,
tool_choice,
thinking: thinking.thinking,
enable_thinking: thinking.enable_thinking,
..Default::default()
};
debug!(
"OpenAI-compatible request: {}",
serde_json::to_string_pretty(&wire).unwrap_or_default()
);
Ok(wire)
}
fn to_openai_role(role: &Role) -> String {
match role {
Role::User => "user".to_string(),
Role::Model => "assistant".to_string(),
Role::System => "developer".to_string(),
Role::Custom(role) => role.clone(),
}
}
fn openai_item_for_image(image: &Attachment) -> OpenAIContentItem {
OpenAIContentItem::ImageUrl { image_url: ImageUrl { url: image.to_uri() } }
}
fn openai_item_for_document(document: &Attachment) -> OpenAIContentItem {
let media_type = match document {
Attachment::Base64 { media_type, .. } => media_type.clone(),
Attachment::Url { url } => format!("url:{url}"),
};
OpenAIContentItem::Text {
text: format!(
"[Document content (type: {media_type}) - model does not support document vision]"
),
}
}
impl TryFrom<&ToolUse> for OpenAIToolCall {
type Error = anyhow::Error;
fn try_from(tool_use: &ToolUse) -> Result<Self> {
Ok(OpenAIToolCall {
id: tool_use.id.clone(),
call_type: "function".to_string(),
function: FunctionCall {
name: tool_use.name.clone(),
arguments: serde_json::to_string(replay_safe_tool_args(tool_use).as_ref())?,
},
})
}
}
struct ToolResultConversion {
tool_message: OpenAIMessage,
image_message: Option<OpenAIMessage>,
}
fn tool_result_to_openai(result: &ToolResult) -> ToolResultConversion {
let mut text_content = String::new();
let mut image_items: Vec<OpenAIContentItem> = Vec::new();
match &result.content {
Content::Text(text) => {
text_content = text.clone();
}
Content::Parts(parts) => {
for part in parts {
match part {
ContentPart::Text(text) => {
if !text_content.is_empty() {
text_content.push('\n');
}
text_content.push_str(text);
}
ContentPart::Image(image) => {
image_items.push(openai_item_for_image(image));
}
ContentPart::Document(document) => {
image_items.push(openai_item_for_document(document));
}
_ => {}
}
}
}
}
if !image_items.is_empty() {
if !text_content.is_empty() {
text_content.push('\n');
}
text_content.push_str(&format!(
"[Attachments from tool call {} are included below.]",
result.tool_use_id
));
image_items.insert(
0,
OpenAIContentItem::Text {
text: format!("Attachments from tool call {}:", result.tool_use_id),
},
);
}
let tool_message =
OpenAIMessage::tool_response(result.tool_use_id.clone(), OpenAIContent::Text(text_content));
let image_message = if image_items.is_empty() {
None
} else {
Some(OpenAIMessage::new("user", Some(OpenAIContent::List(image_items))))
};
ToolResultConversion { tool_message, image_message }
}
fn content_part_to_openai_items(part: &ContentPart) -> Vec<OpenAIContentItem> {
match part {
ContentPart::Text(text) => vec![OpenAIContentItem::Text { text: text.clone() }],
ContentPart::Image(image) => vec![openai_item_for_image(image)],
ContentPart::Document(document) => vec![openai_item_for_document(document)],
ContentPart::RedactedThinking { .. } => vec![],
other => vec![OpenAIContentItem::Text { text: format!("{other:?}") }],
}
}
pub(in crate::openai_compatible) fn to_open_ai_message(
message: &Message,
profile: OpenAiCompatProfile,
) -> Result<Vec<OpenAIMessage>> {
let role = to_openai_role(&message.role);
let is_assistant = matches!(message.role, Role::Model);
match &message.content {
Content::Text(text) => {
let mut msg = OpenAIMessage::new(role, Some(OpenAIContent::Text(text.clone())));
if profile.requires_assistant_reasoning() && is_assistant {
msg.reasoning_content = Some(String::new());
}
Ok(vec![msg])
}
Content::Parts(parts) => {
let mut messages = Vec::new();
let mut image_messages = Vec::new();
let mut items = Vec::new();
let mut tool_calls = Vec::new();
let mut reasoning_content: Option<String> = None;
for part in parts {
match part {
ContentPart::ToolUse(tool_use) => {
tool_calls.push(OpenAIToolCall::try_from(tool_use)?);
}
ContentPart::ToolResult(result) => {
let conversion = tool_result_to_openai(result);
messages.push(conversion.tool_message);
if let Some(image_msg) = conversion.image_message {
image_messages.push(image_msg);
}
}
ContentPart::Thinking { text, .. } if is_assistant => {
match &mut reasoning_content {
Some(existing) => {
existing.push('\n');
existing.push_str(text);
}
None => {
reasoning_content = Some(text.clone());
}
}
}
other => {
items.extend(content_part_to_openai_items(other));
}
}
}
let content = if !items.is_empty() {
Some(OpenAIContent::List(items))
} else if is_assistant && tool_calls.is_empty() && messages.is_empty() {
Some(OpenAIContent::Text(String::new()))
} else {
None
};
let resolved_reasoning = if profile.requires_assistant_reasoning() && is_assistant {
Some(reasoning_content.unwrap_or_default())
} else {
None
};
if tool_calls.is_empty() {
if messages.is_empty() {
let mut msg = OpenAIMessage::new(role, content);
msg.reasoning_content = resolved_reasoning;
messages.push(msg);
}
} else if messages.is_empty() {
messages.push(OpenAIMessage::with_tool_calls(
role,
content,
resolved_reasoning,
tool_calls,
));
}
messages.extend(image_messages);
Ok(messages)
}
}
}
pub(in crate::openai_compatible) fn convert_tools(
tools: Vec<ToolDefinition>,
) -> Option<Vec<OpenAITool>> {
if tools.is_empty() {
return None;
}
Some(
tools
.into_iter()
.map(|tool| OpenAITool {
tool_type: "function".to_string(),
function: OpenAIToolFunction {
name: tool.name,
description: tool.description.unwrap_or_default(),
parameters: materialize_empty_properties(tool.input_schema),
},
})
.collect(),
)
}
fn materialize_empty_properties(mut schema: serde_json::Value) -> serde_json::Value {
if let Some(obj) = schema.as_object_mut()
&& obj.get("type").is_some_and(|t| t == "object")
&& !obj.contains_key("properties")
{
obj.insert("properties".to_string(), serde_json::Value::Object(serde_json::Map::new()));
}
schema
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn parameterless_tool_renders_empty_properties() {
let tools = vec![ToolDefinition {
name: "no_args".to_string(),
description: Some("takes nothing".to_string()),
input_schema: json!({"type": "object"}),
}];
let converted = convert_tools(tools).unwrap();
assert_eq!(converted[0].function.parameters, json!({"type": "object", "properties": {}}));
}
}