A high-performance inference engine for AI models
use super::*;
use crate::common::thinking::ReasoningEffortSet;
fn request(json: &str) -> ChatCompletionRequest {
serde_json::from_str(json).expect("valid request json")
}
fn reply_config(json: &str) -> ChatReplyConfig {
build_reply_config(&request(json)).expect("valid reply config")
}
#[test]
fn response_format_maps_to_grammar() {
assert!(reply_config(r#"{"messages":[]}"#).grammar.is_none());
assert!(reply_config(r#"{"messages":[],"response_format":{"type":"text"}}"#).grammar.is_none());
assert_eq!(
reply_config(r#"{"messages":[],"response_format":{"type":"json_object"}}"#).grammar,
Some(Grammar::JsonAny {})
);
}
#[test]
fn seed_maps_to_reply_sampling_seed() {
assert_eq!(reply_config(r#"{"messages":[]}"#).sampling_seed, SamplingSeed::Default {});
assert_eq!(
reply_config(r#"{"messages":[],"seed":42}"#).sampling_seed,
SamplingSeed::Custom {
seed: 42
}
);
assert_eq!(
reply_config(r#"{"messages":[],"seed":-7}"#).sampling_seed,
SamplingSeed::Custom {
seed: -7
}
);
// A seed alone leaves the model's default sampling in place.
assert_eq!(
reply_config(r#"{"messages":[],"seed":42}"#).sampling_policy,
uzu::types::basic::SamplingPolicy::Default {}
);
}
#[test]
fn seed_must_be_an_integer() {
assert!(serde_json::from_str::<ChatCompletionRequest>(r#"{"messages":[],"seed":1.5}"#).is_err());
assert!(serde_json::from_str::<ChatCompletionRequest>(r#"{"messages":[],"seed":"42"}"#).is_err());
}
#[test]
fn response_format_unrecognized_is_invalid() {
let error = build_reply_config(&request(r#"{"messages":[],"response_format":{"type":"totally-bogus"}}"#))
.expect_err("unrecognized response_format should be rejected");
assert!(
matches!(error, ResponseFormatError::InvalidResponseFormat(_)),
"expected InvalidResponseFormat, got {error:?}"
);
}
#[test]
fn response_format_json_schema_maps_to_grammar() {
let config = reply_config(
r#"{"messages":[],"response_format":{"type":"json_schema","json_schema":{"name":"person","schema":{"type":"object"}}}}"#,
);
assert_eq!(
config.grammar,
Some(Grammar::JsonSchema {
schema: r#"{"type":"object"}"#.to_string(),
})
);
}
#[test]
fn response_format_json_schema_rejects_invalid_schema() {
let error = build_reply_config(&request(
r#"{"messages":[],"response_format":{"type":"json_schema","json_schema":{"schema":{"type":"not-a-json-schema-type"}}}}"#,
))
.expect_err("an invalid JSON Schema should be rejected");
assert!(matches!(error, ResponseFormatError::InvalidJsonSchema(_)), "expected InvalidJsonSchema, got {error:?}");
assert_eq!(error.code(), "invalid_json_schema");
}
#[test]
fn response_format_validation_errors_are_request_errors() {
let error = ResponseFormatError::InvalidResponseFormat("unknown type".to_string());
match invalid_request_response("response_format", error.code(), error.message()) {
ChatCompletionResult::Error(_) => {},
ChatCompletionResult::Json(_, _) | ChatCompletionResult::Stream(_) => {
panic!("response_format validation errors should be request errors")
},
}
}
#[test]
fn malformed_response_format_passes_json_extraction() {
for body in [
r#"{"messages":[],"response_format":{"type":"totally-bogus"}}"#,
r#"{"messages":[],"response_format":"not-even-an-object"}"#,
] {
serde_json::from_str::<ChatCompletionRequest>(body)
.unwrap_or_else(|error| panic!("expected {body} to pass extraction, got {error}"));
}
}
fn any_levels() -> ThinkingSupport {
ThinkingSupport::Levels {
effort: ReasoningEffort::Default,
supported: ReasoningEffortSet::ALL,
}
}
fn messages_with_support(
json: &str,
thinking_support: ThinkingSupport,
) -> Vec<ChatMessage> {
build_messages(&request(json), thinking_support).expect("valid request")
}
#[test]
fn reasoning_effort_prepends_system_message_for_levels_model() {
use uzu::types::session::chat::ChatMessageList;
let messages = messages_with_support(
r#"{"messages":[{"role":"user","content":"hi"}],"reasoning_effort":"high"}"#,
any_levels(),
);
assert_eq!(messages.len(), 2);
assert_eq!(messages[0].reasoning_effort(), Some(ReasoningEffort::High));
assert_eq!(messages.reasoning_effort(), Some(ReasoningEffort::High));
}
#[test]
fn reasoning_effort_merges_into_leading_system_message() {
let messages = messages_with_support(
r#"{"messages":[{"role":"system","content":"be brief"},{"role":"user","content":"hi"}],"reasoning_effort":"high"}"#,
any_levels(),
);
assert_eq!(messages.len(), 2);
assert_eq!(messages[0].role, ChatRole::System {});
assert_eq!(messages[0].reasoning_effort(), Some(ReasoningEffort::High));
assert_eq!(messages[0].text().as_deref(), Some("be brief"));
}
#[test]
fn developer_message_becomes_system_message() {
let request = request(r#"{"messages":[{"role":"developer","content":"be brief"},{"role":"user","content":"hi"}]}"#);
assert_eq!(
to_chat_messages(&request.messages),
vec![ChatMessage::system().with_text("be brief".to_string()), ChatMessage::user().with_text("hi".to_string())]
);
}
#[test]
fn consecutive_system_messages_merge_into_one_text_block() {
let request = request(
r#"{"messages":[
{"role":"system","content":"be brief"},
{"role":"developer","content":"answer in uppercase"},
{"role":"system","content":""},
{"role":"user","content":"hi"},
{"role":"system","content":"late"}
]}"#,
);
assert_eq!(
to_chat_messages(&request.messages),
vec![
ChatMessage::system().with_text("be brief\n\nanswer in uppercase".to_string()),
ChatMessage::user().with_text("hi".to_string()),
ChatMessage::system().with_text("late".to_string()),
]
);
}
#[test]
fn developer_instructions_precede_tools_and_carry_reasoning_effort() {
let messages = messages_with_support(
r#"{
"messages":[{"role":"developer","content":"be brief"},{"role":"user","content":"hi"}],
"tools":[{"type":"function","function":{"name":"get_time","parameters":{"type":"object","properties":{}}}}],
"reasoning_effort":"high"
}"#,
any_levels(),
);
let roles = messages.iter().map(|message| message.role.clone()).collect::<Vec<_>>();
assert_eq!(roles, [ChatRole::System {}, ChatRole::Developer {}, ChatRole::User {}]);
assert_eq!(messages[0].text().as_deref(), Some("be brief"));
assert_eq!(messages[0].reasoning_effort(), Some(ReasoningEffort::High));
assert_eq!(messages[1].text(), None);
assert_eq!(messages[1].tool_namespaces().len(), 1);
}
#[test]
fn reasoning_effort_default_emits_no_system_message() {
for body in [
r#"{"messages":[{"role":"user","content":"hi"}]}"#,
r#"{"messages":[{"role":"user","content":"hi"}],"reasoning_effort":"default"}"#,
] {
let messages = messages_with_support(body, any_levels());
assert_eq!(messages.len(), 1);
assert!(messages.iter().all(|message| message.reasoning_effort().is_none()));
}
}
#[test]
fn reasoning_effort_maps_levels_to_on_off_for_toggle_model() {
let enabled = messages_with_support(r#"{"messages":[],"reasoning_effort":"low"}"#, ThinkingSupport::Toggle(true));
assert_eq!(enabled[0].reasoning_effort(), Some(ReasoningEffort::Default));
let disabled =
messages_with_support(r#"{"messages":[],"reasoning_effort":"disabled"}"#, ThinkingSupport::Toggle(true));
assert_eq!(disabled[0].reasoning_effort(), Some(ReasoningEffort::Disabled));
}
#[test]
fn reasoning_effort_satisfied_without_system_message_when_model_behavior_already_matches() {
for (support, body) in [
(ThinkingSupport::AlwaysOn, r#"{"messages":[{"role":"user","content":"hi"}],"reasoning_effort":"high"}"#),
(
ThinkingSupport::Unsupported,
r#"{"messages":[{"role":"user","content":"hi"}],"reasoning_effort":"disabled"}"#,
),
] {
let messages = messages_with_support(body, support);
assert_eq!(messages.len(), 1);
assert!(messages.iter().all(|message| message.reasoning_effort().is_none()));
}
}
#[test]
fn reasoning_effort_rejected_when_model_cannot_produce_it() {
for (support, body) in [
(ThinkingSupport::AlwaysOn, r#"{"messages":[],"reasoning_effort":"disabled"}"#),
(ThinkingSupport::Unsupported, r#"{"messages":[],"reasoning_effort":"high"}"#),
] {
let error =
build_messages(&request(body), support).expect_err("unfulfillable reasoning_effort should be rejected");
assert!(
matches!(error, MessageBuildError::ReasoningEffort(_)),
"expected ReasoningEffort error, got {error:?}"
);
}
}
#[test]
fn enable_thinking_honored_for_toggle_model() {
let enabled = messages_with_support(r#"{"messages":[],"enable_thinking":true}"#, ThinkingSupport::Toggle(false));
assert_eq!(enabled[0].reasoning_effort(), Some(ReasoningEffort::Default));
let disabled = messages_with_support(
r#"{"messages":[],"chat_template_kwargs":{"enable_thinking":false}}"#,
ThinkingSupport::Toggle(true),
);
assert_eq!(disabled[0].reasoning_effort(), Some(ReasoningEffort::Disabled));
}
#[test]
fn enable_thinking_honored_for_levels_model() {
let disabled = messages_with_support(r#"{"messages":[],"enable_thinking":false}"#, any_levels());
assert_eq!(disabled[0].reasoning_effort(), Some(ReasoningEffort::Disabled));
}
#[test]
fn enable_thinking_rejected_when_model_cannot_produce_it() {
let error = build_messages(&request(r#"{"messages":[],"enable_thinking":false}"#), ThinkingSupport::AlwaysOn)
.expect_err("disabling an always-on model should be rejected");
assert!(matches!(error, MessageBuildError::EnableThinking(_)), "expected EnableThinking error, got {error:?}");
let error = build_messages(&request(r#"{"messages":[],"enable_thinking":true}"#), ThinkingSupport::Unsupported)
.expect_err("enabling reasoning on an unsupported model should be rejected");
assert!(matches!(error, MessageBuildError::EnableThinking(_)), "expected EnableThinking error, got {error:?}");
}
#[test]
fn enable_thinking_rejects_contradictions() {
for body in [
r#"{"messages":[],"enable_thinking":true,"chat_template_kwargs":{"enable_thinking":false}}"#,
r#"{"messages":[],"enable_thinking":false,"reasoning_effort":"high"}"#,
r#"{"messages":[],"enable_thinking":true,"reasoning_effort":"disabled"}"#,
] {
build_messages(&request(body), any_levels()).expect_err("contradictory thinking requests should be rejected");
}
}
#[test]
fn enable_thinking_agrees_with_compatible_reasoning_effort() {
let messages =
messages_with_support(r#"{"messages":[],"enable_thinking":true,"reasoning_effort":"low"}"#, any_levels());
assert_eq!(messages[0].reasoning_effort(), Some(ReasoningEffort::Low));
}
#[test]
fn enable_thinking_rejects_malformed_values() {
for body in [
r#"{"messages":[],"enable_thinking":"yes"}"#,
r#"{"messages":[],"chat_template_kwargs":{"enable_thinking":1}}"#,
r#"{"messages":[],"chat_template_kwargs":"nope"}"#,
] {
build_messages(&request(body), ThinkingSupport::Toggle(true))
.expect_err("malformed enable_thinking should be rejected");
}
}
#[test]
fn chat_template_kwargs_ignores_unrelated_keys_and_null() {
for body in [
r#"{"messages":[],"chat_template_kwargs":{"some_other_kwarg":42}}"#,
r#"{"messages":[],"chat_template_kwargs":{"enable_thinking":null}}"#,
r#"{"messages":[],"enable_thinking":null}"#,
] {
let messages = messages_with_support(body, ThinkingSupport::Toggle(true));
assert!(messages.iter().all(|message| message.reasoning_effort().is_none()));
}
}
#[test]
fn malformed_enable_thinking_passes_json_extraction() {
for body in [r#"{"messages":[],"enable_thinking":"yes"}"#, r#"{"messages":[],"chat_template_kwargs":"nope"}"#] {
serde_json::from_str::<ChatCompletionRequest>(body)
.unwrap_or_else(|error| panic!("expected {body} to pass extraction, got {error}"));
}
}
#[test]
fn reasoning_effort_rejects_unrecognized_values() {
for body in [r#"{"messages":[],"reasoning_effort":"totally-bogus"}"#, r#"{"messages":[],"reasoning_effort":42}"#] {
let error = build_messages(&request(body), ThinkingSupport::default())
.expect_err("bad reasoning_effort should be rejected");
assert!(
matches!(error, MessageBuildError::ReasoningEffort(_)),
"expected ReasoningEffort error, got {error:?}"
);
assert_eq!(error.param(), "reasoning_effort");
assert_eq!(error.code(), "invalid_reasoning_effort");
}
}
#[test]
fn malformed_reasoning_effort_passes_json_extraction() {
for body in [r#"{"messages":[],"reasoning_effort":"totally-bogus"}"#, r#"{"messages":[],"reasoning_effort":42}"#] {
serde_json::from_str::<ChatCompletionRequest>(body)
.unwrap_or_else(|error| panic!("expected {body} to pass extraction, got {error}"));
}
}
#[rocket::get("/err")]
fn err_route() -> ChatCompletionResult {
let error = ResponseFormatError::InvalidResponseFormat("bad".to_string());
invalid_request_response("response_format", error.code(), error.message())
}
#[test]
fn error_responder_yields_http_400_with_openai_body() {
let client = rocket::local::blocking::Client::tracked(rocket::build().mount("/", rocket::routes![err_route]))
.expect("rocket client");
let response = client.get("/err").dispatch();
assert_eq!(response.status(), Status::BadRequest);
let body: serde_json::Value = response.into_json().expect("json error body");
assert_eq!(body["error"]["type"], "invalid_request_error");
assert_eq!(body["error"]["param"], "response_format");
assert_eq!(body["error"]["code"], "invalid_response_format");
assert!(
body["error"]["message"].as_str().is_some_and(|message| !message.is_empty()),
"expected a non-empty error message, got {body}"
);
}
#[test]
fn response_format_composes_with_sampling_options() {
let stochastic = reply_config(
r#"{"messages":[],"temperature":0.7,"top_p":0.9,"top_k":40,"response_format":{"type":"json_object"}}"#,
);
assert_eq!(stochastic.grammar, Some(Grammar::JsonAny {}));
assert_eq!(
stochastic.sampling_policy,
uzu::types::basic::SamplingPolicy::Custom {
method: SamplingMethod::Stochastic {
temperature: Some(0.7),
top_k: Some(40),
top_p: Some(0.9),
min_p: None,
repetition_penalty: None,
suffix_repetition_length: None,
},
}
);
let greedy = reply_config(r#"{"messages":[],"temperature":0,"response_format":{"type":"json_object"}}"#);
assert_eq!(greedy.grammar, Some(Grammar::JsonAny {}));
assert_eq!(
greedy.sampling_policy,
uzu::types::basic::SamplingPolicy::Custom {
method: SamplingMethod::Greedy {},
}
);
}
#[test]
fn message_content_accepts_string_null_and_text_parts() {
let messages = request(
r#"{"messages":[
{"role":"user","content":"plain"},
{"role":"assistant","content":null},
{"role":"user","content":[{"type":"text","text":"Hello"},{"type":"text","text":" world"}]}
]}"#,
)
.messages;
assert_eq!(messages[0].content.as_deref(), Some("plain"));
assert_eq!(messages[1].content, None);
assert_eq!(messages[2].content.as_deref(), Some("Hello world"));
let missing = request(r#"{"messages":[{"role":"user"}]}"#);
assert_eq!(missing.messages[0].content, None);
let image = serde_json::from_str::<ChatCompletionRequest>(
r#"{"messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,AA=="}}]}]}"#,
);
assert!(image.is_err());
}
#[test]
fn assistant_reasoning_content_round_trips_in_session_block_order() {
let messages = messages_with_support(
r#"{"messages":[
{"role":"user","content":"hi"},
{"role":"assistant","reasoning_content":"thoughts","content":"answer","tool_calls":[{"id":"c1","type":"function","function":{"name":"f","arguments":"{}"}}]},
{"role":"assistant","reasoning_content":"","content":"no thinking"},
{"role":"user","content":"again"}
]}"#,
any_levels(),
);
let assistant = &messages[1];
let kinds = assistant
.content
.iter()
.map(|block| match block {
ChatContentBlock::Reasoning {
..
} => "reasoning",
ChatContentBlock::Text {
..
} => "text",
ChatContentBlock::ToolCall {
..
} => "tool_call",
_ => "other",
})
.collect::<Vec<_>>();
assert_eq!(kinds, ["reasoning", "text", "tool_call"]);
assert_eq!(assistant.reasoning().as_deref(), Some("thoughts"));
// empty reasoning_content must not create a block, matching how replies are stored
assert_eq!(messages[2].reasoning(), None);
assert_eq!(messages[2].text().as_deref(), Some("no thinking"));
}
#[test]
fn prefix_match_allows_omitted_assistant_reasoning_across_turns() {
let current = vec![
ChatMessage::system().with_text("instructions".to_string()),
ChatMessage::user().with_text("hi".to_string()),
ChatMessage::assistant().with_reasoning("first thoughts".to_string()).with_text("hello".to_string()),
ChatMessage::user().with_text("again".to_string()),
ChatMessage::assistant().with_reasoning("second thoughts".to_string()).with_text("hello again".to_string()),
];
// OpenAI clients commonly omit the reasoning field or echo null/empty text.
for reasoning in [None, Some(serde_json::Value::Null), Some(serde_json::json!(""))] {
let mut body = serde_json::json!({"messages": [
{"role": "system", "content": "instructions"},
{"role": "user", "content": "hi"},
{"role": "assistant", "content": "hello"},
{"role": "user", "content": "again"},
{"role": "assistant", "content": "hello again"},
{"role": "user", "content": "once more"}
]});
if let Some(reasoning) = reasoning {
body["messages"][2]["reasoning_content"] = reasoning.clone();
body["messages"][4]["reasoning_content"] = reasoning;
}
let request: ChatCompletionRequest = serde_json::from_value(body).unwrap();
assert!(messages_have_prefix(&to_chat_messages(&request.messages), ¤t));
}
}
#[test]
fn prefix_match_still_rejects_edits_when_assistant_reasoning_is_omitted() {
let current = vec![ChatMessage::assistant().with_reasoning("thoughts".to_string()).with_text("hello".to_string())];
for edited in [
ChatMessage::assistant().with_text("changed".to_string()),
ChatMessage::assistant(),
ChatMessage::user().with_text("hello".to_string()),
ChatMessage::assistant().with_text("hello".to_string()).with_reasoning_effort(ReasoningEffort::Disabled),
ChatMessage::assistant().with_reasoning("different thoughts".to_string()).with_text("hello".to_string()),
] {
assert!(!messages_have_prefix(&[edited, ChatMessage::user().with_text("more".to_string())], ¤t));
}
let without_reasoning = vec![ChatMessage::assistant().with_text("hello".to_string())];
assert!(!messages_have_prefix(¤t, &without_reasoning), "new reasoning must not be ignored");
let system = vec![ChatMessage::system().with_reasoning("thoughts".to_string()).with_text("hello".to_string())];
assert!(!messages_have_prefix(&[ChatMessage::system().with_text("hello".to_string())], &system));
}
#[test]
fn prefix_match_preserves_tool_calls_with_empty_assistant_content() {
let tool_call = uzu::types::basic::ToolCall {
identifier: Some("c1".to_string()),
name: "f".to_string(),
arguments: uzu::types::basic::Value {
json: "{}".to_string(),
},
};
for reasoning in ["", "thoughts"] {
let mut assistant = ChatMessage::assistant();
if !reasoning.is_empty() {
assistant = assistant.with_reasoning(reasoning.to_string());
}
let current =
vec![ChatMessage::user().with_text("hi".to_string()), assistant.with_tool_call(tool_call.clone())];
for content in [None, Some("null"), Some("\"\""), Some("[]"), Some(r#"[{"type":"text","text":""}]"#)] {
let mut body = serde_json::json!({"messages": [
{"role": "user", "content": "hi"},
{"role": "assistant", "reasoning_content": reasoning, "tool_calls": [
{"id": "c1", "type": "function", "function": {"name": "f", "arguments": "{}"}}
]},
{"role": "tool", "tool_call_id": "c1", "content": "result"}
]});
if let Some(content) = content {
body["messages"][1]["content"] = serde_json::from_str(content).unwrap();
}
for echo_reasoning in [true, false] {
if !echo_reasoning {
body["messages"][1].as_object_mut().unwrap().remove("reasoning_content");
}
let request: ChatCompletionRequest = serde_json::from_value(body.clone()).unwrap();
let messages = to_chat_messages(&request.messages);
assert!(messages.len() > current.len());
assert!(messages_have_prefix(&messages, ¤t), "content: {content:?}, reasoning: {reasoning:?}");
}
}
}
}
#[test]
fn empty_tool_result_content_is_preserved() {
let request = request(r#"{"messages":[{"role":"tool","tool_call_id":"c1","content":""}]}"#);
assert_eq!(
to_chat_messages(&request.messages),
vec![ChatMessage::tool().with_block(tool_call_result_block("c1", String::new()))]
);
}
#[test]
fn prefix_match_ignores_tool_call_identifiers() {
let assistant_call = |identifier: &str| {
ChatMessage::assistant().with_tool_call(uzu::types::basic::ToolCall {
identifier: Some(identifier.to_string()),
name: "write".to_string(),
arguments: uzu::types::basic::Value {
json: r#"{"path":"/tmp/a"}"#.to_string(),
},
})
};
let current = vec![ChatMessage::user().with_text("hi".to_string()), assistant_call("nagare-uuid")];
let extending = vec![
ChatMessage::user().with_text("hi".to_string()),
assistant_call("server-uuid"),
ChatMessage::user().with_text("again".to_string()),
];
assert!(messages_have_prefix(&extending, ¤t));
let mut different = assistant_call("nagare-uuid");
different.content.push(ChatContentBlock::Text {
value: "extra".to_string(),
});
let not_matching = vec![ChatMessage::user().with_text("hi".to_string()), different];
assert!(!messages_have_prefix(¬_matching, ¤t));
}
#[test]
fn prefix_match_treats_coerced_arguments_as_equal() {
let assistant_call = |arguments: &str| {
ChatMessage::assistant().with_tool_call(uzu::types::basic::ToolCall {
identifier: Some("id".to_string()),
name: "search".to_string(),
arguments: uzu::types::basic::Value {
json: arguments.to_string(),
},
})
};
// the session stores the parser's stringified scalar; the client echoes the
// coerced typed value it received
let current = vec![assistant_call(r#"{"query":"cats","limit":"5"}"#)];
let extending =
vec![assistant_call(r#"{"query":"cats","limit":5}"#), ChatMessage::user().with_text("more".to_string())];
assert!(messages_have_prefix(&extending, ¤t));
// a genuinely different value is still a mismatch
let different =
vec![assistant_call(r#"{"query":"cats","limit":6}"#), ChatMessage::user().with_text("more".to_string())];
assert!(!messages_have_prefix(&different, ¤t));
// string-declared values that the parser typed by their braces also match their echo
let stored_object = vec![assistant_call(r#"{"content":{"a":1}}"#)];
let echoed_string =
vec![assistant_call(r#"{"content":"{\"a\":1}"}"#), ChatMessage::user().with_text("more".to_string())];
assert!(messages_have_prefix(&echoed_string, &stored_object));
// the session stores a Python-style boolean (qwen3.5 markup); the client
// echoes the coerced JSON boolean it received
let stored_python = vec![assistant_call(r#"{"metric":"True"}"#)];
let echoed_boolean = vec![assistant_call(r#"{"metric":true}"#), ChatMessage::user().with_text("more".to_string())];
assert!(messages_have_prefix(&echoed_boolean, &stored_python));
// the session stores a declared array as the text the model wrote; the
// client echoes the typed array it received
let stored_text = vec![assistant_call(r#"{"edits":"[{\"a\": 1}, 2]"}"#)];
let echoed_array =
vec![assistant_call(r#"{"edits":[{"a":1},2]}"#), ChatMessage::user().with_text("more".to_string())];
assert!(messages_have_prefix(&echoed_array, &stored_text));
}
#[test]
fn sampling_values_out_of_range_are_rejected() {
for body in [
r#"{"messages":[],"temperature":0}"#,
r#"{"messages":[],"temperature":2}"#,
r#"{"messages":[],"top_p":1}"#,
r#"{"messages":[],"top_p":0.01}"#,
r#"{"messages":[],"top_k":1}"#,
] {
validate_sampling(&request(body)).unwrap_or_else(|(_, message)| panic!("expected {body} to pass: {message}"));
}
for (body, param) in [
(r#"{"messages":[],"temperature":-5}"#, "temperature"),
(r#"{"messages":[],"temperature":100}"#, "temperature"),
(r#"{"messages":[],"top_p":0}"#, "top_p"),
(r#"{"messages":[],"top_p":7}"#, "top_p"),
(r#"{"messages":[],"top_k":0}"#, "top_k"),
(r#"{"messages":[],"top_k":-3}"#, "top_k"),
] {
let error = validate_sampling(&request(body)).expect_err("out-of-range value should be rejected");
assert_eq!(error.0, param, "for {body}");
}
}
#[test]
fn backend_error_bodies_are_openai_errors_with_collapsed_prefixes() {
let body = serde_json::to_value(oai_error_body(
Status::BadRequest,
"backend_error",
"Backend error: Backend error: Role 'wizard' is not supported",
))
.expect("serializable error body");
assert_eq!(body["error"]["type"], "invalid_request_error");
assert_eq!(body["error"]["code"], "backend_error");
assert_eq!(body["error"]["message"], "Role 'wizard' is not supported");
let body =
serde_json::to_value(oai_error_body(Status::InternalServerError, "no_response", "No response generated"))
.expect("serializable error body");
assert_eq!(body["error"]["type"], "server_error");
assert_eq!(body["error"]["message"], "No response generated");
}
#[test]
fn context_overflow_is_reported_as_context_length_exceeded() {
let error = ChatSessionError::Backend {
error: BackendError::ContextOverflow {},
};
let body = serde_json::to_value(stream_error_body(&error)).expect("serializable error body");
assert_eq!(body["error"]["type"], "invalid_request_error");
assert_eq!(body["error"]["code"], "context_length_exceeded");
assert_eq!(body["error"]["param"], "messages");
assert_eq!(body["error"]["message"], "Input exceeds the context window of this model");
}
#[test]
fn overflow_text_without_the_variant_stays_a_backend_error() {
let body =
serde_json::to_value(stream_error_body(&ChatSessionError::backend("Context overflow"))).expect("serializable");
assert_eq!(body["error"]["code"], "backend_error");
assert_eq!(body["error"]["param"], serde_json::Value::Null);
assert_eq!(body["error"]["message"], "Context overflow");
}