use serde_json::{Value, json};
use causa_kernel::{
CacheDirective, ContextFrame, GenerationOptions, ModelInvokeError, ModelInvokeErrorKind,
ModelOutput, ModelRef, ModelResponse, ModelStopReason, ReasoningPayload, TextPayload,
ToolCallDraft, ToolSurface,
};
use super::context_frame::{self, ResolvedMedia, Role, Segment};
use super::media::MediaSet;
struct AssistantRun {
text: String,
calls: Vec<Value>,
}
pub fn render_openai_chat_messages(
frame: &ContextFrame,
media: &MediaSet,
tool_surface: &ToolSurface,
generation: &GenerationOptions,
model: &ModelRef,
_cache: CacheDirective,
) -> Result<Value, ModelInvokeError> {
let normalized = context_frame::normalize(frame, media);
let mut messages: Vec<Value> = Vec::new();
let mut run: Option<AssistantRun> = None;
for segment in &normalized.segments {
let closes_run = !matches!(
segment,
Segment::Text {
role: Role::Assistant,
..
} | Segment::ToolCall(_)
);
if closes_run && let Some(finished) = run.take() {
messages.push(assistant_message(finished));
}
match segment {
Segment::Text {
role: Role::System,
text,
} => {
messages.push(json!({"role": "system", "content": text}));
}
Segment::Text {
role: Role::User,
text,
} => {
messages.push(json!({"role": "user", "content": text}));
}
Segment::Media { role, media } => match (role, media) {
(Role::System, ResolvedMedia::Placeholder(text)) => {
messages.push(json!({"role": "system", "content": text}));
}
(Role::Assistant, ResolvedMedia::Placeholder(text)) => {
if let Some(finished) = run.take() {
messages.push(assistant_message(finished));
}
messages.push(json!({"role": "assistant", "content": text}));
}
(
_,
ResolvedMedia::Image {
media_type,
data_base64,
},
) => {
messages.push(json!({
"role": "user",
"content": [{"type": "image_url", "image_url": {"url": data_url(media_type, data_base64)}}],
}));
}
(_, ResolvedMedia::Placeholder(text)) => {
messages.push(json!({"role": "user", "content": text}));
}
},
Segment::Text {
role: Role::Assistant,
text,
} => match &mut run {
Some(state) => {
state.text.push('\n');
state.text.push_str(text);
}
None => {
run = Some(AssistantRun {
text: text.clone(),
calls: Vec::new(),
})
}
},
Segment::ToolCall(call) => {
let wire_call = json!({
"id": call.wire_id,
"type": "function",
"function": {
"name": call.name,
"arguments": call.arguments.to_string(),
},
});
match &mut run {
Some(state) => state.calls.push(wire_call),
None => {
run = Some(AssistantRun {
text: String::new(),
calls: vec![wire_call],
})
}
}
}
Segment::ToolResult {
wire_id,
content,
media,
..
} => {
messages.push(json!({
"role": "tool",
"tool_call_id": wire_id,
"content": content,
}));
if !media.is_empty() {
let mut parts = vec![json!({
"type": "text",
"text": format!("[tool result media for call {wire_id}]"),
})];
parts.extend(media.iter().map(|m| match m {
ResolvedMedia::Image {
media_type,
data_base64,
} => json!({
"type": "image_url",
"image_url": {"url": data_url(media_type, data_base64)},
}),
ResolvedMedia::Placeholder(text) => {
json!({"type": "text", "text": text})
}
}));
messages.push(json!({"role": "user", "content": parts}));
}
}
}
}
if let Some(finished) = run.take() {
messages.push(assistant_message(finished));
}
if messages.is_empty() {
return Err(ModelInvokeError::new(
ModelInvokeErrorKind::InvalidRequest,
"frame rendered to zero messages; nothing to send",
));
}
let mut body = json!({
"model": model.0,
"messages": messages,
});
if let Some(temperature) = generation.temperature {
body["temperature"] = json!(temperature);
}
if let Some(max_tokens) = generation.max_tokens {
body["max_tokens"] = json!(max_tokens);
}
if let Some(schema) = &generation.output_schema {
body["response_format"] = json!({
"type": "json_schema",
"json_schema": {
"name": super::OUTPUT_SCHEMA_NAME,
"schema": schema,
"strict": false,
},
});
}
if !tool_surface.definitions.is_empty() {
body["tools"] = json!(context_frame::tool_definitions(
tool_surface,
context_frame::ToolShape::OpenAiChat
));
}
Ok(body)
}
fn assistant_message(run: AssistantRun) -> Value {
let mut message = json!({"role": "assistant"});
if !run.text.is_empty() {
message["content"] = json!(run.text);
}
if !run.calls.is_empty() {
message["tool_calls"] = json!(run.calls);
}
message
}
fn data_url(media_type: &str, data_base64: &str) -> String {
format!("data:{media_type};base64,{data_base64}")
}
pub fn parse_openai_chat_response(value: &Value) -> Result<ModelOutput, ModelInvokeError> {
fn permanent(message: impl Into<String>) -> ModelInvokeError {
ModelInvokeError::new(ModelInvokeErrorKind::Permanent, message)
}
let choice = value
.get("choices")
.and_then(Value::as_array)
.and_then(|c| c.first())
.ok_or_else(|| permanent("missing choices[0]"))?;
let message = choice
.get("message")
.ok_or_else(|| permanent("missing choices[0].message"))?;
let text = match message.get("content") {
None | Some(Value::Null) => String::new(),
Some(Value::String(s)) => s.clone(),
Some(_) => return Err(permanent("choices[0].message.content: expected a string")),
};
let mut tool_calls = Vec::new();
if let Some(wire_calls) = message.get("tool_calls").and_then(Value::as_array) {
for call in wire_calls {
let id = call
.get("id")
.and_then(Value::as_str)
.ok_or_else(|| permanent("tool_calls[]: missing `id` string"))?;
let function = call
.get("function")
.ok_or_else(|| permanent("tool_calls[]: missing `function`"))?;
let name = function
.get("name")
.and_then(Value::as_str)
.ok_or_else(|| permanent("tool_calls[].function: missing `name` string"))?;
let arguments = context_frame::decode_wire_arguments(function.get("arguments"))?;
tool_calls.push(ToolCallDraft {
tool_name: name.to_string(),
arguments,
provider_call_id: Some(id.to_string()),
});
}
}
let stop_reason = match choice.get("finish_reason") {
Some(Value::String(s)) => match s.as_str() {
"stop" => ModelStopReason::EndTurn,
"tool_calls" => ModelStopReason::ToolUse,
"length" => ModelStopReason::MaxTokens,
"content_filter" => ModelStopReason::Refusal,
_ => ModelStopReason::EndTurn,
},
None | Some(Value::Null) => return Err(permanent("missing choices[0].finish_reason")),
Some(_) => return Err(permanent("choices[0].finish_reason: expected a string")),
};
let reasoning = message
.get("reasoning_content")
.and_then(Value::as_str)
.map(|text| ReasoningPayload {
text: text.to_string(),
signature: None,
});
let usage = value
.get("usage")
.filter(|v| v.is_object())
.map(crate::translation::usage::model_usage_from_openai_chat);
Ok(ModelOutput {
response: ModelResponse {
text: TextPayload::new(text),
tool_calls,
},
usage,
stop_reason,
reasoning,
})
}
#[cfg(test)]
mod tests {
use super::*;
use causa_kernel::{ModelUsage, ToolDefinition, ToolResultStatus};
use crate::translation::media::{MediaPayload, MediaSet};
use crate::translation::test_support::{
call, frame, media_part, parts, result, result_with_media, text, text_part,
};
fn render(frame: &ContextFrame) -> Value {
render_openai_chat_messages(
frame,
&MediaSet::new(),
&ToolSurface::empty(),
&GenerationOptions::default(),
&ModelRef::new("gpt-test"),
CacheDirective::None,
)
.unwrap()
}
#[test]
fn source_vocabulary_full_branch_coverage() {
let f = frame(vec![
text(0, "be terse", Some("system")),
text(1, "model said", None),
text(2, "user said", Some("user")),
text(3, "replayed", Some("assistant")),
text(4, "injected", Some("inject:note")),
text(5, "unknown tag", Some("provider:gpt-x")),
]);
let v = render(&f);
let msgs = v["messages"].as_array().unwrap();
assert_eq!(msgs.len(), 5);
assert_eq!(msgs[0], json!({"role": "system", "content": "be terse"}));
assert_eq!(
msgs[1],
json!({"role": "assistant", "content": "model said"})
);
assert_eq!(msgs[2], json!({"role": "user", "content": "user said"}));
assert_eq!(msgs[3], json!({"role": "assistant", "content": "replayed"}));
assert_eq!(
msgs[4],
json!({"role": "user", "content": "injected\nunknown tag"})
);
}
#[test]
fn tool_round_trip_pairing_and_assistant_merge() {
let f = frame(vec![
text(0, "reading now", None),
call(1, "kc1", Some("toolu_a"), "read", json!({"path": "a"})),
call(2, "kc2", None, "list", json!({})),
result(3, "kc1", ToolResultStatus::Succeeded, json!("file-a")),
result(4, "kc2", ToolResultStatus::Failed, json!({"error": "boom"})),
]);
let v = render(&f);
let msgs = v["messages"].as_array().unwrap();
assert_eq!(msgs.len(), 3);
assert_eq!(
msgs[0],
json!({
"role": "assistant",
"content": "reading now",
"tool_calls": [
{"id": "toolu_a", "type": "function",
"function": {"name": "read", "arguments": "{\"path\":\"a\"}"}},
{"id": "kc2", "type": "function",
"function": {"name": "list", "arguments": "{}"}},
],
})
);
assert_eq!(
msgs[1],
json!({"role": "tool", "tool_call_id": "toolu_a", "content": "file-a"})
);
assert_eq!(
msgs[2],
json!({"role": "tool", "tool_call_id": "kc2", "content": "{\"error\":\"boom\"}"})
);
}
#[test]
fn assistant_tool_calls_only_omits_empty_content() {
let f = frame(vec![call(0, "kc1", Some("toolu_a"), "read", json!({}))]);
let v = render(&f);
assert_eq!(
v["messages"][0],
json!({
"role": "assistant",
"tool_calls": [
{"id": "toolu_a", "type": "function",
"function": {"name": "read", "arguments": "{}"}},
],
})
);
assert!(v["messages"][0].get("content").is_none());
}
#[test]
fn adjacent_assistant_texts_join_into_one_message() {
let f = frame(vec![
text(0, "first", None),
call(1, "kc1", Some("toolu_a"), "read", json!({})),
text(2, "second", None),
]);
let v = render(&f);
let msgs = v["messages"].as_array().unwrap();
assert_eq!(msgs.len(), 1);
assert_eq!(msgs[0]["role"], "assistant");
assert_eq!(msgs[0]["content"], json!("first\nsecond"));
assert_eq!(msgs[0]["tool_calls"].as_array().unwrap().len(), 1);
let f = frame(vec![text(0, "a", None), text(1, "b", None)]);
let v = render(&f);
assert_eq!(
v["messages"],
json!([{"role": "assistant", "content": "a\nb"}])
);
}
#[test]
fn unpaired_tool_result_falls_back_to_kernel_call_id() {
let f = frame(vec![result(
0,
"orphan",
ToolResultStatus::Succeeded,
json!("x"),
)]);
let v = render(&f);
assert_eq!(v["messages"][0]["tool_call_id"], json!("orphan"));
}
#[test]
fn tools_generation_and_byte_determinism() {
let surface = ToolSurface::from_definitions(vec![ToolDefinition {
name: "read".into(),
description: "read a file".into(),
parameters: json!({"type": "object"}),
}]);
let f = frame(vec![text(0, "hi", Some("user"))]);
let generation = GenerationOptions {
temperature: Some(0.5),
max_tokens: None,
..GenerationOptions::default()
};
let v = render_openai_chat_messages(
&f,
&MediaSet::new(),
&surface,
&generation,
&ModelRef::new("gpt-test"),
CacheDirective::None,
)
.unwrap();
assert_eq!(v["model"], json!("gpt-test"));
assert_eq!(v["temperature"], json!(0.5));
assert!(v.get("max_tokens").is_none());
assert_eq!(
v["tools"],
json!([{
"type": "function",
"function": {"name": "read", "description": "read a file", "parameters": {"type": "object"}},
}])
);
let generation = GenerationOptions {
temperature: Some(0.5),
max_tokens: Some(100),
..GenerationOptions::default()
};
let v2 = render_openai_chat_messages(
&f,
&MediaSet::new(),
&surface,
&generation,
&ModelRef::new("gpt-test"),
CacheDirective::None,
)
.unwrap();
assert_eq!(v2["max_tokens"], json!(100));
let again = render_openai_chat_messages(
&f,
&MediaSet::new(),
&surface,
&generation,
&ModelRef::new("gpt-test"),
CacheDirective::None,
)
.unwrap();
assert_eq!(
serde_json::to_string(&v2).unwrap(),
serde_json::to_string(&again).unwrap()
);
}
#[test]
fn output_schema_maps_and_cache_directive_is_a_noop() {
let f = frame(vec![text(0, "hi", Some("user"))]);
let generation = GenerationOptions {
output_schema: Some(json!({"type": "object"})),
..GenerationOptions::default()
};
let v = render_openai_chat_messages(
&f,
&MediaSet::new(),
&ToolSurface::empty(),
&generation,
&ModelRef::new("gpt-test"),
CacheDirective::None,
)
.unwrap();
assert_eq!(
v["response_format"],
json!({
"type": "json_schema",
"json_schema": {
"name": "response",
"schema": {"type": "object"},
"strict": false,
},
})
);
let cached = render_openai_chat_messages(
&f,
&MediaSet::new(),
&ToolSurface::empty(),
&generation,
&ModelRef::new("gpt-test"),
CacheDirective::StablePrefix,
)
.unwrap();
assert_eq!(v, cached);
}
#[test]
fn empty_frame_is_invalid_request() {
let e = render_openai_chat_messages(
&frame(vec![]),
&MediaSet::new(),
&ToolSurface::empty(),
&GenerationOptions::default(),
&ModelRef::new("m"),
CacheDirective::None,
)
.unwrap_err();
assert!(matches!(e.kind(), ModelInvokeErrorKind::InvalidRequest));
}
use causa_kernel::MediaRef;
fn resolved(reference: &str) -> MediaSet {
let mut m = MediaSet::new();
m.insert(reference, MediaPayload::new("image/png", "AAAA"));
m
}
#[test]
fn image_parts_render_as_image_url_messages() {
let f = frame(vec![parts(
0,
vec![
text_part("caption"),
media_part("image/png", "asset-1"),
text_part("after"),
],
Some("user"),
)]);
let v = render_openai_chat_messages(
&f,
&resolved("asset-1"),
&ToolSurface::empty(),
&GenerationOptions::default(),
&ModelRef::new("gpt-test"),
CacheDirective::None,
)
.unwrap();
let msgs = v["messages"].as_array().unwrap();
assert_eq!(msgs[0], json!({"role": "user", "content": "caption"}));
assert_eq!(
msgs[1],
json!({"role": "user", "content": [
{"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}
]})
);
assert_eq!(msgs[2], json!({"role": "user", "content": "after"}));
}
#[test]
fn unresolved_media_degrades_to_the_deterministic_placeholder() {
let f = frame(vec![parts(
0,
vec![media_part("image/png", "missing-asset")],
Some("user"),
)]);
let v = render_openai_chat_messages(
&f,
&MediaSet::new(),
&ToolSurface::empty(),
&GenerationOptions::default(),
&ModelRef::new("gpt-test"),
CacheDirective::None,
)
.unwrap();
assert_eq!(
v["messages"][0],
json!({"role": "user", "content": "[media: image/png missing-asset]"})
);
}
#[test]
fn tool_result_media_hoists_into_a_user_message_with_provenance() {
let f = frame(vec![
call(0, "kc1", Some("call_1"), "render", json!({})),
result_with_media(
1,
"kc1",
ToolResultStatus::Succeeded,
json!("chart ready"),
vec![
MediaRef::new("image/png", "asset-1"),
MediaRef::new("image/png", "asset-2"),
],
),
]);
let mut media = MediaSet::new();
media.insert("asset-1", MediaPayload::new("image/png", "AAAA"));
media.insert("asset-2", MediaPayload::new("image/jpeg", "BBBB"));
let v = render_openai_chat_messages(
&f,
&media,
&ToolSurface::empty(),
&GenerationOptions::default(),
&ModelRef::new("gpt-test"),
CacheDirective::None,
)
.unwrap();
let msgs = v["messages"].as_array().unwrap();
assert_eq!(msgs[1]["role"], "tool");
assert_eq!(msgs[2]["role"], "user");
assert_eq!(
msgs[2]["content"],
json!([
{"type": "text", "text": "[tool result media for call call_1]"},
{"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}},
{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,BBBB"}},
])
);
}
#[test]
fn hoisted_placeholders_stay_in_payload_order() {
let f = frame(vec![result_with_media(
0,
"kc1",
ToolResultStatus::Succeeded,
json!("mixed"),
vec![
MediaRef::new("image/png", "good"),
MediaRef::new("image/png", "missing"),
MediaRef::new("application/pdf", "doc"),
],
)]);
let mut media = MediaSet::new();
media.insert("good", MediaPayload::new("image/png", "AAAA"));
media.insert("doc", MediaPayload::new("application/pdf", "BBBB"));
let v = render_openai_chat_messages(
&f,
&media,
&ToolSurface::empty(),
&GenerationOptions::default(),
&ModelRef::new("gpt-test"),
CacheDirective::None,
)
.unwrap();
let msgs = v["messages"].as_array().unwrap();
assert_eq!(
msgs[1]["content"],
json!([
{"type": "text", "text": "[tool result media for call kc1]"},
{"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}},
{"type": "text", "text": "[media: image/png missing]"},
{"type": "text", "text": "[media: application/pdf doc]"},
])
);
}
#[test]
fn parse_full_message_shape_with_provider_id_passthrough() {
let v = json!({
"choices": [{
"message": {
"role": "assistant",
"content": "Let me check.",
"tool_calls": [{
"id": "call_9",
"type": "function",
"function": {"name": "read", "arguments": "{\"path\": \"a\"}"},
}],
"reasoning_content": "hmm",
},
"finish_reason": "tool_calls",
}],
"usage": {
"prompt_tokens": 100,
"completion_tokens": 20,
"prompt_tokens_details": {"cached_tokens": 11},
"completion_tokens_details": {"reasoning_tokens": 5},
},
});
let out = parse_openai_chat_response(&v).unwrap();
assert_eq!(out.response.text.0, "Let me check.");
assert_eq!(out.response.tool_calls.len(), 1);
let tc = &out.response.tool_calls[0];
assert_eq!(tc.tool_name, "read");
assert_eq!(tc.arguments, json!({"path": "a"}));
assert_eq!(tc.provider_call_id.as_deref(), Some("call_9"));
assert!(matches!(out.stop_reason, ModelStopReason::ToolUse));
let reasoning = out.reasoning.unwrap();
assert_eq!(reasoning.text, "hmm");
assert_eq!(reasoning.signature, None);
let u: ModelUsage = out.usage.unwrap();
assert_eq!((u.input_tokens, u.output_tokens), (100, 20));
assert_eq!(u.cache_read_tokens, Some(11));
assert_eq!(u.cache_write_tokens, None);
assert_eq!(u.reasoning_tokens, Some(5));
}
#[test]
fn finish_reason_mapping_full_and_unknown_degrades_to_end_turn() {
for (wire, expected) in [
("stop", ModelStopReason::EndTurn),
("tool_calls", ModelStopReason::ToolUse),
("length", ModelStopReason::MaxTokens),
("content_filter", ModelStopReason::Refusal),
("some_new_reason", ModelStopReason::EndTurn),
] {
let v = json!({"choices": [{"message": {"content": ""}, "finish_reason": wire}]});
let out = parse_openai_chat_response(&v).unwrap();
assert_eq!(
std::mem::discriminant(&out.stop_reason),
std::mem::discriminant(&expected),
"finish_reason = {wire}"
);
}
}
#[test]
fn missing_choices_or_finish_reason_is_permanent_error() {
let e = parse_openai_chat_response(&json!({"choices": []})).unwrap_err();
assert!(matches!(e.kind(), ModelInvokeErrorKind::Permanent));
let e = parse_openai_chat_response(&json!({"choices": [{"message": {}}]})).unwrap_err();
assert!(matches!(e.kind(), ModelInvokeErrorKind::Permanent));
assert!(e.message.contains("finish_reason"));
}
#[test]
fn malformed_arguments_string_is_permanent_error() {
let v = json!({
"choices": [{
"message": {"content": null, "tool_calls": [
{"id": "c1", "function": {"name": "read", "arguments": "{not json"}},
]},
"finish_reason": "tool_calls",
}],
});
let e = parse_openai_chat_response(&v).unwrap_err();
assert!(matches!(e.kind(), ModelInvokeErrorKind::Permanent));
assert!(e.message.contains("arguments"));
}
#[test]
fn empty_arguments_string_degrades_to_empty_object() {
let v = json!({
"choices": [{
"message": {"tool_calls": [
{"id": "c1", "function": {"name": "list", "arguments": ""}},
]},
"finish_reason": "tool_calls",
}],
});
let out = parse_openai_chat_response(&v).unwrap();
assert_eq!(out.response.tool_calls[0].arguments, json!({}));
}
}