Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

openai chat completions response format

Stan SKY4c9a81cab95d
diff --git a/Cargo.lock b/Cargo.lock
index 834d7d0f7..84b4c59c5 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1023,6 +1023,7 @@ dependencies = [
"clap",
"comfy-table",
"indicatif",
+ "jsonschema",
"rocket",
"serde",
"serde_json",
diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml
index 278350560..ba19d2e81 100644
--- a/crates/cli/Cargo.toml
+++ b/crates/cli/Cargo.toml
@@ -30,6 +30,7 @@ comfy-table.workspace = true
indicatif.workspace = true
serde.workspace = true
serde_json.workspace = true
+jsonschema.workspace = true
rocket.workspace = true
uuid.workspace = true
tokio-stream.workspace = true
diff --git a/crates/cli/src/server/chat_completions.rs b/crates/cli/src/server/chat_completions.rs
index 2ddeec495..c707e5e67 100644
--- a/crates/cli/src/server/chat_completions.rs
+++ b/crates/cli/src/server/chat_completions.rs
@@ -8,9 +8,10 @@ use std::{
use rocket::{
Request, State,
futures::Stream,
+ http::Status,
post,
response::{
- Responder,
+ Responder, status,
stream::{Event, EventStream},
},
serde::json::Json,
@@ -22,7 +23,7 @@ use uuid::Uuid;
use uzu::{
session::chat::{ChatSession, ChatSessionStreamChunk},
types::{
- basic::SamplingMethod,
+ basic::{Grammar, SamplingMethod},
session::chat::{ChatMessage, ChatReplyConfig, ChatReplyFinishReason, ChatReplyStats, ChatRole},
},
};
@@ -51,11 +52,29 @@ pub struct ChatCompletionRequest {
pub top_p: Option<f64>,
#[serde(default)]
pub top_k: Option<i64>,
+ // Raw value (not typed) so a bad response_format is our 400, not Rocket's 422.
+ #[serde(default)]
+ pub response_format: Option<serde_json::Value>,
#[serde(default)]
#[allow(dead_code)]
pub model: Option<String>,
}
+#[derive(Deserialize)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum ResponseFormat {
+ Text,
+ JsonObject,
+ JsonSchema {
+ json_schema: JsonSchemaFormat,
+ },
+}
+
+#[derive(Deserialize)]
+pub struct JsonSchemaFormat {
+ pub schema: serde_json::Value,
+}
+
#[derive(Serialize, Clone)]
pub struct ChatCompletionChoice {
pub index: u32,
@@ -106,9 +125,24 @@ struct ChatCompletionChunk {
usage: Option<ChatCompletionUsage>,
}
+#[derive(Serialize)]
+pub struct OaiErrorResponse {
+ error: OaiError,
+}
+
+#[derive(Serialize)]
+struct OaiError {
+ message: String,
+ #[serde(rename = "type")]
+ kind: String,
+ param: Option<String>,
+ code: Option<String>,
+}
+
pub enum ChatCompletionResult {
Json(Json<ChatCompletionResponse>),
Stream(EventStream<Pin<Box<dyn Stream<Item = Event> + Send>>>),
+ Error(status::Custom<Json<OaiErrorResponse>>),
}
impl<'r> Responder<'r, 'r> for ChatCompletionResult {
@@ -119,6 +153,7 @@ impl<'r> Responder<'r, 'r> for ChatCompletionResult {
match self {
ChatCompletionResult::Json(json) => json.respond_to(request),
ChatCompletionResult::Stream(stream) => stream.respond_to(request),
+ ChatCompletionResult::Error(error) => error.respond_to(request),
}
}
}
@@ -137,16 +172,81 @@ fn to_chat_messages(messages: &[OaiMessage]) -> Vec<ChatMessage> {
.collect()
}
-fn build_reply_config(request: &ChatCompletionRequest) -> ChatReplyConfig {
- let token_limit = request.max_completion_tokens.or(request.max_tokens);
- let config = ChatReplyConfig::default().with_token_limit(token_limit);
+#[derive(Debug, PartialEq, Eq)]
+enum ResponseFormatError {
+ GrammarUnsupported,
+ InvalidResponseFormat(String),
+ InvalidJsonSchema(String),
+}
- if request.temperature.is_some_and(|temperature| temperature <= 0.0) {
- return config.with_sampling_method(SamplingMethod::Greedy {});
+impl ResponseFormatError {
+ fn message(&self) -> String {
+ match self {
+ ResponseFormatError::GrammarUnsupported => {
+ "response_format with JSON constraints requires building mirai server with capability-grammar"
+ .to_string()
+ },
+ ResponseFormatError::InvalidResponseFormat(detail) => {
+ format!("response_format is not a recognized object: {detail}")
+ },
+ ResponseFormatError::InvalidJsonSchema(detail) => {
+ format!("response_format.json_schema.schema is not a valid JSON Schema: {detail}")
+ },
+ }
+ }
+
+ fn code(&self) -> &'static str {
+ match self {
+ ResponseFormatError::GrammarUnsupported => "unsupported_response_format",
+ ResponseFormatError::InvalidResponseFormat(_) => "invalid_response_format",
+ ResponseFormatError::InvalidJsonSchema(_) => "invalid_json_schema",
+ }
+ }
+}
+
+fn request_error_response(error: ResponseFormatError) -> ChatCompletionResult {
+ ChatCompletionResult::Error(status::Custom(
+ Status::BadRequest,
+ Json(OaiErrorResponse {
+ error: OaiError {
+ message: error.message(),
+ kind: "invalid_request_error".to_string(),
+ param: Some("response_format".to_string()),
+ code: Some(error.code().to_string()),
+ },
+ }),
+ ))
+}
+
+fn with_response_format_grammar(
+ config: ChatReplyConfig,
+ grammar: Grammar,
+) -> Result<ChatReplyConfig, ResponseFormatError> {
+ if !cfg!(feature = "capability-grammar") {
+ return Err(ResponseFormatError::GrammarUnsupported);
}
- if request.temperature.is_some() || request.top_p.is_some() || request.top_k.is_some() {
- return config.with_sampling_method(SamplingMethod::Stochastic {
+ Ok(config.with_grammar(Some(grammar)))
+}
+
+fn json_schema_grammar(json_schema: &JsonSchemaFormat) -> Result<Grammar, ResponseFormatError> {
+ jsonschema::meta::validate(&json_schema.schema)
+ .map_err(|error| ResponseFormatError::InvalidJsonSchema(error.to_string()))?;
+ let schema = serde_json::to_string(&json_schema.schema)
+ .map_err(|error| ResponseFormatError::InvalidResponseFormat(error.to_string()))?;
+ Ok(Grammar::JsonSchema {
+ schema,
+ })
+}
+
+fn build_reply_config(request: &ChatCompletionRequest) -> Result<ChatReplyConfig, ResponseFormatError> {
+ let token_limit = request.max_completion_tokens.or(request.max_tokens);
+ let mut config = ChatReplyConfig::default().with_token_limit(token_limit);
+
+ if request.temperature.is_some_and(|temperature| temperature <= 0.0) {
+ config = config.with_sampling_method(SamplingMethod::Greedy {});
+ } else if request.temperature.is_some() || request.top_p.is_some() || request.top_k.is_some() {
+ config = config.with_sampling_method(SamplingMethod::Stochastic {
temperature: request.temperature,
top_k: request.top_k,
top_p: request.top_p,
@@ -156,7 +256,23 @@ fn build_reply_config(request: &ChatCompletionRequest) -> ChatReplyConfig {
});
}
- config
+ let response_format = match &request.response_format {
+ Some(value) => Some(
+ serde_json::from_value::<ResponseFormat>(value.clone())
+ .map_err(|error| ResponseFormatError::InvalidResponseFormat(error.to_string()))?,
+ ),
+ None => None,
+ };
+
+ config = match response_format {
+ Some(ResponseFormat::JsonObject) => with_response_format_grammar(config, Grammar::JsonAny {})?,
+ Some(ResponseFormat::JsonSchema {
+ json_schema,
+ }) => with_response_format_grammar(config, json_schema_grammar(&json_schema)?)?,
+ Some(ResponseFormat::Text) | None => config,
+ };
+
+ Ok(config)
}
fn map_finish_reason(finish_reason: &ChatReplyFinishReason) -> String {
@@ -390,8 +506,11 @@ pub async fn handle_chat_completions(
let model = state.model_name.clone();
let is_stream = request.stream.unwrap_or(false);
+ let config = match build_reply_config(&request) {
+ Ok(config) => config,
+ Err(error) => return request_error_response(error),
+ };
let messages = to_chat_messages(&request.messages);
- let config = build_reply_config(&request);
if is_stream {
let session = Arc::clone(&state.session);
@@ -405,3 +524,7 @@ pub async fn handle_chat_completions(
ChatCompletionResult::Json(Json(response))
}
}
+
+#[cfg(test)]
+#[path = "../../unit/server/chat_completions_test.rs"]
+mod tests;
diff --git a/crates/cli/unit/server/chat_completions_test.rs b/crates/cli/unit/server/chat_completions_test.rs
new file mode 100644
index 000000000..6b142e521
--- /dev/null
+++ b/crates/cli/unit/server/chat_completions_test.rs
@@ -0,0 +1,151 @@
+use super::*;
+
+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")
+}
+
+#[cfg(not(feature = "capability-grammar"))]
+fn reply_config_error(json: &str) -> ResponseFormatError {
+ build_reply_config(&request(json)).expect_err("invalid 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());
+
+ #[cfg(feature = "capability-grammar")]
+ assert_eq!(
+ reply_config(r#"{"messages":[],"response_format":{"type":"json_object"}}"#).grammar,
+ Some(Grammar::JsonAny {})
+ );
+}
+
+#[test]
+fn response_format_rejects_grammar_without_capability() {
+ #[cfg(not(feature = "capability-grammar"))]
+ {
+ assert_eq!(
+ reply_config_error(r#"{"messages":[],"response_format":{"type":"json_object"}}"#),
+ ResponseFormatError::GrammarUnsupported
+ );
+ assert_eq!(
+ reply_config_error(
+ r#"{"messages":[],"response_format":{"type":"json_schema","json_schema":{"schema":{"type":"object"}}}}"#
+ ),
+ ResponseFormatError::GrammarUnsupported
+ );
+ }
+}
+
+#[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:?}"
+ );
+}
+
+#[cfg(feature = "capability-grammar")]
+#[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() {
+ match request_error_response(ResponseFormatError::GrammarUnsupported) {
+ 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}"));
+ }
+}
+
+#[rocket::get("/err")]
+fn err_route() -> ChatCompletionResult {
+ request_error_response(ResponseFormatError::InvalidResponseFormat("bad".to_string()))
+}
+
+#[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}"
+ );
+}
+
+#[cfg(feature = "capability-grammar")]
+#[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 {},
+ }
+ );
+}