use crate::host::TokenSink;
use crate::host_model::{parse, render};
use crate::records::{HostModelCaps, HostReply};
use serde_json::json;
use troupekit_core::message::{ContentPart, Message, Role};
use troupekit_core::tool::ToolSpec;
use troupekit_providers::CompletionRequest;
fn with_tool() -> CompletionRequest {
let mut req = CompletionRequest::user("1 + 2", 100);
req.tools.push(ToolSpec {
name: "add".into(),
description: "Adds.".into(),
schema: json!({"type": "object"}),
hosted: None,
});
req
}
fn text_reply(text: &str) -> HostReply {
HostReply {
text: text.into(),
..HostReply::default()
}
}
#[test]
fn delta_bytes_capped() {
let (sink, mut deltas) = TokenSink::channel(true, 10, 8);
sink.delta("12345".into());
sink.delta("123456".into());
sink.delta("12345".into());
sink.delta("1".into());
let mut got = Vec::new();
while let Ok(text) = deltas.try_recv() {
got.push(text);
}
assert_eq!(got, vec!["12345".to_string(), "12345".to_string()]);
let (off, mut none) = TokenSink::channel(false, 10, 8);
off.delta("1".into());
assert!(none.try_recv().is_err());
}
#[test]
fn full_queue_joins_deltas_and_loses_none() {
let (sink, mut deltas) = TokenSink::channel(true, 100, 2);
sink.delta(String::new());
sink.delta("a".into());
sink.delta(String::new());
sink.delta("b".into());
sink.delta("c".into());
sink.delta("d".into());
let mut got = Vec::new();
while let Ok(text) = deltas.try_recv() {
got.push(text);
}
assert_eq!(got, vec!["a".to_string(), "b".to_string()]);
sink.delta("e".into());
assert_eq!(deltas.try_recv().unwrap(), "cde");
sink.delta("f".into());
sink.delta("g".into());
sink.delta("h".into());
assert_eq!(sink.take_pending(), "h");
assert_eq!(deltas.try_recv().unwrap(), "f");
assert_eq!(deltas.try_recv().unwrap(), "g");
assert_eq!(sink.take_pending(), "");
}
#[test]
fn output_schema_without_tools_goes_to_schema_or_prompt() {
let mut req = CompletionRequest::user("hi", 100);
req.output_schema = Some(json!({"type": "object", "properties": {"n": {"type": "integer"}}}));
let mut caps = HostModelCaps::default();
let prompted = render(&req, &caps).unwrap();
assert!(prompted.schema_json.is_none());
assert!(prompted.system.unwrap().contains("\"integer\""));
caps.json_schema = true;
let schema = render(&req, &caps).unwrap();
let shape: serde_json::Value = serde_json::from_str(&schema.schema_json.unwrap()).unwrap();
assert_eq!(shape["properties"]["n"]["type"], "integer");
}
#[test]
fn output_schema_with_emulated_tools_types_the_answer() {
let mut req = with_tool();
req.output_schema = Some(json!({"type": "object", "properties": {"n": {"type": "integer"}}}));
let caps = HostModelCaps {
json_schema: true,
..HostModelCaps::default()
};
let rendered = render(&req, &caps).unwrap();
let shape: serde_json::Value = serde_json::from_str(&rendered.schema_json.unwrap()).unwrap();
assert_eq!(
shape["oneOf"][0]["properties"]["answer"]["properties"]["n"]["type"],
"integer"
);
let parts = parse(&req, &caps, &text_reply(r#"{"answer": {"n": 3}}"#)).unwrap();
assert_eq!(
parts,
vec![ContentPart::Text {
text: r#"{"n":3}"#.into()
}]
);
}
#[test]
fn envelope_keeps_local_refs_of_the_answer_schema() {
let mut req = with_tool();
req.output_schema = Some(json!({
"$defs": {"N": {"type": "integer"}},
"type": "object",
"properties": {
"n": {"$ref": "#/$defs/N"},
"me": {"$ref": "#"},
"tag": {"$ref": "#t"},
"default": {"$ref": "#/$defs/N"},
},
}));
let caps = HostModelCaps {
json_schema: true,
..HostModelCaps::default()
};
let rendered = render(&req, &caps).unwrap();
let shape: serde_json::Value = serde_json::from_str(&rendered.schema_json.unwrap()).unwrap();
let answer = &shape["oneOf"][0]["properties"]["answer"];
let target = answer["properties"]["n"]["$ref"].as_str().unwrap();
let resolved = shape.pointer(target.strip_prefix('#').unwrap()).unwrap();
assert_eq!(resolved["type"], "integer");
let me = answer["properties"]["me"]["$ref"].as_str().unwrap();
assert_eq!(
shape.pointer(me.strip_prefix('#').unwrap()).unwrap(),
answer
);
assert_eq!(answer["properties"]["tag"]["$ref"], "#t");
assert_eq!(answer["properties"]["default"]["$ref"], target);
}
#[test]
fn envelope_leaves_refs_of_an_own_id_schema() {
let mut req = with_tool();
req.output_schema = Some(json!({
"$id": "https://example.test/out",
"$defs": {"N": {"type": "integer"}},
"properties": {"n": {"$ref": "#/$defs/N"}},
}));
let caps = HostModelCaps {
json_schema: true,
..HostModelCaps::default()
};
let rendered = render(&req, &caps).unwrap();
let shape: serde_json::Value = serde_json::from_str(&rendered.schema_json.unwrap()).unwrap();
let answer = &shape["oneOf"][0]["properties"]["answer"];
assert_eq!(answer["properties"]["n"]["$ref"], "#/$defs/N");
}
#[test]
fn output_schema_with_native_tools_sends_both() {
let mut req = with_tool();
req.output_schema = Some(json!({"type": "object"}));
let caps = HostModelCaps {
tools: true,
json_schema: true,
..HostModelCaps::default()
};
let rendered = render(&req, &caps).unwrap();
assert!(rendered.tools_json.is_some());
assert!(rendered.schema_json.is_some());
}
#[test]
fn emulated_call_ids_count_prior_calls() {
let mut req = with_tool();
let call = ContentPart::ToolCall {
id: "call_0".into(),
name: "add".into(),
arguments: json!({}),
};
req.messages
.push(Message::new(Role::Assistant, vec![call]).unwrap());
let caps = HostModelCaps::default();
let reply = text_reply(r#"{"tool": "add", "arguments": {}}"#);
let first = parse(&req, &caps, &reply).unwrap();
let again = parse(&req, &caps, &reply).unwrap();
assert_eq!(first, again);
assert!(matches!(&first[0], ContentPart::ToolCall { id, .. } if id == "call_1"));
}
#[test]
fn unknown_tool_or_bad_shape_does_not_parse() {
let req = with_tool();
let caps = HostModelCaps::default();
for text in [
"",
"3",
"[1]",
r#"{"tool": "sub", "arguments": {}}"#,
r#"{"tool": "add", "arguments": 1}"#,
r#"{"tool": "add"}"#,
r#"{"other": 1}"#,
] {
assert!(parse(&req, &caps, &text_reply(text)).is_none(), "{text}");
}
}
#[test]
fn image_part_is_refused() {
let mut req = CompletionRequest::user("look", 100);
req.messages[0].parts.push(ContentPart::Image {
media_type: "image/png".into(),
source: troupekit_core::message::MediaSource::Base64 {
data: "AA==".into(),
},
});
let err = render(&req, &HostModelCaps::default()).unwrap_err();
assert!(err.message.contains("text only"), "{err}");
}
#[test]
fn history_without_tools_in_request_stays_text_for_a_plain_model() {
let mut req = CompletionRequest::user("1 + 2", 100);
let call = ContentPart::ToolCall {
id: "call_0".into(),
name: "add".into(),
arguments: json!({"a": 1}),
};
req.messages
.push(Message::new(Role::Assistant, vec![call]).unwrap());
let result = ContentPart::ToolResult {
call_id: "call_0".into(),
content: "3".into(),
is_error: false,
};
req.messages
.push(Message::new(Role::Tool, vec![result]).unwrap());
let rendered = render(&req, &HostModelCaps::default()).unwrap();
assert!(rendered
.messages
.iter()
.all(|m| m.tool_calls_json.is_none()));
assert!(rendered.messages.iter().all(|m| m.tool_call_id.is_none()));
assert!(rendered.messages.iter().all(|m| m.role != "tool"));
assert!(rendered.messages[1].text.contains(r#""tool":"add""#));
assert!(rendered.messages[2].text.contains('3'));
}
struct Billed {
caps: HostModelCaps,
replies: std::sync::Mutex<Vec<HostReply>>,
}
impl crate::host::HostModel for Billed {
fn id(&self) -> String {
"host/billed".into()
}
fn capabilities(&self) -> HostModelCaps {
self.caps
}
fn generate(
&self,
_request: crate::records::HostRequest,
_sink: std::sync::Arc<TokenSink>,
) -> Result<HostReply, crate::records::HostError> {
let mut replies = self.replies.lock().unwrap();
if replies.is_empty() {
return Err(crate::records::HostError::new("script ran out"));
}
Ok(replies.remove(0))
}
}
fn counted(text: &str) -> HostReply {
let mut reply = text_reply(text);
reply.input_tokens = 10;
reply.output_tokens = 2;
reply
}
async fn billed_failure(
caps: HostModelCaps,
replies: Vec<HostReply>,
) -> troupekit_providers::FailedCall {
let host = std::sync::Arc::new(Billed {
caps,
replies: std::sync::Mutex::new(replies),
});
let (model, _) = crate::host_model::wrap_model(host, false).unwrap();
model.complete_billed(&with_tool()).await.unwrap_err()
}
#[tokio::test]
async fn failed_repair_bills_the_first_reply() {
let failed = billed_failure(HostModelCaps::default(), vec![counted("three")]).await;
assert!(
failed.error.message.contains("script ran out"),
"{}",
failed.error
);
assert_eq!(
(failed.usage.input_tokens, failed.usage.output_tokens),
(10, 2)
);
}
#[tokio::test]
async fn unparsed_repair_bills_both_replies() {
let failed = billed_failure(
HostModelCaps::default(),
vec![counted("three"), counted("still three")],
)
.await;
assert_eq!(
failed.error.kind,
troupekit_core::error::ProviderErrorKind::Decode
);
assert_eq!(
(failed.usage.input_tokens, failed.usage.output_tokens),
(20, 4)
);
}
#[tokio::test]
async fn bad_native_tool_calls_bill_the_reply() {
let caps = HostModelCaps {
tools: true,
..HostModelCaps::default()
};
let mut reply = counted("");
reply.tool_calls_json = Some("not json".into());
let failed = billed_failure(caps, vec![reply]).await;
assert_eq!(
failed.error.kind,
troupekit_core::error::ProviderErrorKind::Decode
);
assert_eq!(
(failed.usage.input_tokens, failed.usage.output_tokens),
(10, 2)
);
}
#[tokio::test]
async fn reply_over_the_cap_bills_the_reply() {
let huge = counted(&"a".repeat(troupekit_providers::model::MAX_REPLY_BYTES + 1));
let failed = billed_failure(HostModelCaps::default(), vec![huge]).await;
assert!(
failed.error.message.contains("reply cap"),
"{}",
failed.error
);
assert_eq!(
(failed.usage.input_tokens, failed.usage.output_tokens),
(10, 2)
);
}
fn assistant(parts: Vec<ContentPart>) -> Message {
Message::new(Role::Assistant, parts).unwrap()
}
fn add_call(id: &str) -> ContentPart {
ContentPart::ToolCall {
id: id.into(),
name: "add".into(),
arguments: json!({"a": 1}),
}
}
#[test]
fn typed_answer_replays_as_json_value() {
let mut req = with_tool();
req.output_schema = Some(json!({"type": "object", "properties": {"n": {"type": "integer"}}}));
req.messages.push(assistant(vec![ContentPart::Text {
text: r#"{"n":3}"#.into(),
}]));
let rendered = render(&req, &HostModelCaps::default()).unwrap();
let replayed: serde_json::Value = serde_json::from_str(&rendered.messages[1].text).unwrap();
assert_eq!(replayed, json!({"answer": {"n": 3}}));
}
#[test]
fn text_answer_replays_as_string() {
let mut req = with_tool();
req.messages.push(assistant(vec![ContentPart::Text {
text: r#"{"n":3}"#.into(),
}]));
let rendered = render(&req, &HostModelCaps::default()).unwrap();
let replayed: serde_json::Value = serde_json::from_str(&rendered.messages[1].text).unwrap();
assert_eq!(replayed, json!({"answer": r#"{"n":3}"#}));
}
#[test]
fn typed_answers_keep_their_json_type_for_every_schema_shape() {
let strings = json!({"type": "string"});
let values = ["true", "3", r#"{"n":3}"#];
let shapes = [
(
"$ref",
json!({"$ref": "#/$defs/s", "$defs": {"s": {"type": "string"}}}),
),
(
"anyOf",
json!({"anyOf": [strings.clone(), {"type": "integer"}]}),
),
("enum", json!({"enum": values})),
("type array", json!({"type": ["string", "integer"]})),
("type string", strings),
];
let caps = HostModelCaps::default();
for (shape, schema) in shapes {
for answer in values.map(|v| json!(v)).into_iter().chain([json!(3)]) {
let mut req = with_tool();
req.output_schema = Some(schema.clone());
let reply = text_reply(&json!({ "answer": answer }).to_string());
let parts = parse(&req, &caps, &reply).unwrap();
let [ContentPart::Text { text }] = parts.as_slice() else {
panic!("{shape}: {parts:?}");
};
let checked: Option<serde_json::Value> = serde_json::from_str(text).ok();
assert_eq!(checked.as_ref(), Some(&answer), "{shape}: {text}");
req.messages.push(assistant(parts.clone()));
let rendered = render(&req, &caps).unwrap();
let last = rendered.messages.last().unwrap();
assert_eq!(last.role, "assistant", "{shape}");
let replayed: serde_json::Value = serde_json::from_str(&last.text).unwrap();
assert_eq!(replayed, json!({ "answer": answer }), "{shape}");
}
}
}
#[test]
fn text_mode_replay_keeps_assistant_text_before_calls() {
let mut req = CompletionRequest::user("1 + 2", 100);
req.messages.push(assistant(vec![
ContentPart::Text {
text: "Let me add.".into(),
},
add_call("call_0"),
]));
let envelope = json!({"tool": "add", "arguments": {"a": 1}});
let rendered = render(&req, &HostModelCaps::default()).unwrap();
let (said, call) = rendered.messages[1].text.split_once('\n').unwrap();
assert_eq!(said, "Let me add.");
assert_eq!(
serde_json::from_str::<serde_json::Value>(call).unwrap(),
envelope
);
let mut bare = CompletionRequest::user("1 + 2", 100);
bare.messages.push(assistant(vec![add_call("call_0")]));
let rendered = render(&bare, &HostModelCaps::default()).unwrap();
let text = &rendered.messages[1].text;
assert!(!text.contains('\n'), "{text}");
assert_eq!(
serde_json::from_str::<serde_json::Value>(text).unwrap(),
envelope
);
}
#[test]
fn a_request_with_tools_may_cost_a_repair_call() {
let host = std::sync::Arc::new(Billed {
caps: HostModelCaps::default(),
replies: std::sync::Mutex::new(Vec::new()),
});
let (model, _) = crate::host_model::wrap_model(host, false).unwrap();
assert_eq!(model.extra_calls(&with_tool()), 1);
assert_eq!(model.extra_calls(&CompletionRequest::user("hi", 10)), 0);
}
#[test]
fn generated_native_ids_skip_explicit_ids_in_the_reply() {
let req = with_tool();
let caps = HostModelCaps {
tools: true,
..HostModelCaps::default()
};
let mut reply = text_reply("");
reply.tool_calls_json =
Some(r#"[{"id": "call_1", "name": "add"}, {"name": "add"}, {"name": "add"}]"#.into());
let parts = parse(&req, &caps, &reply).unwrap();
let ids: Vec<&str> = parts
.iter()
.filter_map(|p| match p {
ContentPart::ToolCall { id, .. } => Some(id.as_str()),
_ => None,
})
.collect();
assert_eq!(ids, vec!["call_1", "call_2", "call_3"]);
assert_eq!(parse(&req, &caps, &reply).unwrap(), parts);
}
#[test]
fn generated_ids_skip_explicit_ids_in_the_history() {
let mut req = with_tool();
req.messages.push(assistant(vec![add_call("call_1")]));
let reply = text_reply(r#"{"tool": "add", "arguments": {}}"#);
let parts = parse(&req, &HostModelCaps::default(), &reply).unwrap();
assert!(matches!(&parts[0], ContentPart::ToolCall { id, .. } if id == "call_2"));
let caps = HostModelCaps {
tools: true,
..HostModelCaps::default()
};
let mut native = text_reply("");
native.tool_calls_json = Some(r#"[{"name": "add"}]"#.into());
let parts = parse(&req, &caps, &native).unwrap();
assert!(matches!(&parts[0], ContentPart::ToolCall { id, .. } if id == "call_2"));
}