use axum::extract::State;
use axum::http::HeaderMap;
use axum::response::{IntoResponse, Response};
use axum::Json;
use eclipse_core::tools::DenyAll;
use eclipse_web::app::Shared;
use serde::Deserialize;
use serde_json::{json, Value};
#[derive(Deserialize)]
#[allow(dead_code)] pub struct ChatCompletionsRequest {
pub model: Option<String>,
pub messages: Vec<ApiMessage>,
pub max_completion_tokens: Option<u32>,
pub max_tokens: Option<u32>,
pub n: Option<u32>,
pub stream: Option<bool>,
}
#[derive(Deserialize)]
pub struct ApiMessage {
pub role: String,
pub content: Option<Value>,
}
fn text_of(content: Option<Value>) -> String {
match content {
None => String::new(),
Some(Value::String(s)) => s,
Some(Value::Array(parts)) => parts
.iter()
.filter_map(|p| {
let ty = p.get("type").and_then(|t| t.as_str())?;
if ty != "text" {
return None;
}
p.get("text")
.and_then(|t| t.as_str())
.map(|t| t.to_string())
})
.collect::<Vec<_>>()
.join("\n"),
Some(Value::Object(_)) => String::new(),
Some(other) => other.to_string(),
}
}
fn images_of(content: Option<&Value>) -> Result<Vec<eclipse_core::message::ImagePart>, String> {
let Some(Value::Array(parts)) = content else {
return Ok(Vec::new());
};
let mut out = Vec::new();
for part in parts {
if part.get("type").and_then(|ty| ty.as_str()) != Some("image_url") {
continue;
}
let url = part
.get("image_url")
.and_then(|value| value.get("url"))
.and_then(|value| value.as_str())
.ok_or_else(|| {
"an `image_url` part has no `url`; send {\"type\": \"image_url\", \"image_url\": {\"url\": \"data:image/png;base64,...\"}}"
.to_string()
})?;
out.push(eclipse_core::message::ImagePart::from_data_url("", url)?);
}
Ok(out)
}
fn picture_count(content: Option<&Value>) -> usize {
match content {
Some(Value::Array(parts)) => parts
.iter()
.filter(|part| part.get("type").and_then(|ty| ty.as_str()) == Some("image_url"))
.count(),
_ => 0,
}
}
pub fn flatten_carrying(messages: &[ApiMessage], carried: Option<usize>) -> String {
let mut out = String::new();
for (index, m) in messages.iter().enumerate() {
let mut text = text_of(m.content.clone());
let pictures = picture_count(m.content.as_ref());
if pictures > 0 {
if Some(index) == carried {
if text.trim().is_empty() {
text = "(the attached picture)".to_string();
}
} else {
if !text.trim().is_empty() {
text.push('\n');
}
text.push_str(&format!(
"[{pictures} picture(s) attached to this message did not travel: one flattened \
prompt can only carry the last message's pictures]"
));
}
}
if text.trim().is_empty() {
continue;
}
let role = match m.role.as_str() {
"system" => "system",
"assistant" => "assistant",
_ => "user",
};
if role == "system" {
if !out.is_empty() {
out.push_str("\n\n");
}
out.push_str(&format!("[system instruction]\n{text}"));
} else {
out.push_str(&format!("\n\n[{role}]\n{text}"));
}
}
out.trim().to_string()
}
pub fn bearer_ok(headers: &HeaderMap, token: &str) -> bool {
let Some(value) = headers.get("authorization").and_then(|v| v.to_str().ok()) else {
return false;
};
let Some((scheme, rest)) = value.split_once(' ') else {
return false;
};
if !scheme.eq_ignore_ascii_case("bearer") {
return false;
}
let stripped = rest;
eclipse_core::token::constant_time_eq(stripped.trim(), token)
}
fn model_ok(asked: Option<&str>, answering: &str) -> Result<(), String> {
match asked.map(str::trim) {
Some(name) if !name.is_empty() && name != answering => Err(format!(
"this gateway answers as `{answering}`; the request asked for `{name}`. Omit `model` to \
use the configured one"
)),
_ => Ok(()),
}
}
fn failure(err: &eclipse_core::Error) -> (axum::http::StatusCode, &'static str, String) {
match err {
eclipse_core::Error::Provider(_) => (
axum::http::StatusCode::BAD_GATEWAY,
"server_error",
"the model backend failed to answer; the gateway log has the detail".to_string(),
),
eclipse_core::Error::Vision(sentence) => (
axum::http::StatusCode::BAD_REQUEST,
"invalid_request_error",
sentence.clone(),
),
eclipse_core::Error::MaxIterations(iterations) => (
axum::http::StatusCode::BAD_GATEWAY,
"server_error",
format!("the model did not produce a final answer within {iterations} iterations"),
),
_ => (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
"server_error",
"the gateway could not run the request; the gateway log has the detail".to_string(),
),
}
}
pub async fn chat_completions(
State(st): State<Shared>,
headers: HeaderMap,
body: axum::body::Bytes,
) -> Response {
if !bearer_ok(&headers, st.token()) {
return (
axum::http::StatusCode::UNAUTHORIZED,
Json(json!({"error": {"message": "missing or invalid bearer token", "type": "auth_error"}})),
)
.into_response();
}
let body: ChatCompletionsRequest = match serde_json::from_slice(&body) {
Ok(body) => body,
Err(e) => {
return (
axum::http::StatusCode::BAD_REQUEST,
Json(json!({"error": {"message": format!("the request body is not a chat-completions request: {e}"), "type": "invalid_request_error"}})),
)
.into_response();
}
};
if body.stream == Some(true) {
return (
axum::http::StatusCode::BAD_REQUEST,
Json(json!({"error": {"message": "streaming is not supported yet; omit stream or set it to false", "type": "invalid_request_error"}})),
)
.into_response();
}
if let Some(n) = body.n.filter(|n| *n != 1) {
return (
axum::http::StatusCode::BAD_REQUEST,
Json(json!({"error": {"message": format!("n = {n} is not supported: this build answers one choice, so omit n or set it to 1"), "type": "invalid_request_error"}})),
)
.into_response();
}
let Some(agent) = st.agent.clone() else {
return (
axum::http::StatusCode::SERVICE_UNAVAILABLE,
Json(json!({"error": {"message": st.config_error.clone().unwrap_or_else(|| "provider not configured".to_string()), "type": "server_error"}})),
)
.into_response();
};
let answering = st.current_model().unwrap_or_else(|| st.model.clone());
if let Err(why) = model_ok(body.model.as_deref(), &answering) {
return (
axum::http::StatusCode::BAD_REQUEST,
Json(json!({"error": {"message": why, "type": "invalid_request_error"}})),
)
.into_response();
}
let carried = body
.messages
.iter()
.rposition(|m| m.role != "assistant" && m.role != "system");
let asked = carried
.map(|index| text_of(body.messages[index].content.clone()))
.unwrap_or_default();
if eclipse_core::tasks::bg_prompt(&asked).is_some() {
return (
axum::http::StatusCode::BAD_REQUEST,
Json(json!({"error": {"message": eclipse_core::tasks::bg_refusal("the gateway"), "type": "invalid_request_error"}})),
)
.into_response();
}
let images = match carried.map(|index| images_of(body.messages[index].content.as_ref())) {
Some(Ok(images)) => images,
Some(Err(sentence)) => {
return (
axum::http::StatusCode::BAD_REQUEST,
Json(json!({"error": {"message": sentence, "type": "invalid_request_error"}})),
)
.into_response();
}
None => Vec::new(),
};
let prompt = flatten_carrying(&body.messages, carried);
if prompt.trim().is_empty() {
return (
axum::http::StatusCode::BAD_REQUEST,
Json(json!({"error": {"message": "messages must contain non-empty text", "type": "invalid_request_error"}})),
)
.into_response();
}
let Some(_slot) = st.try_chat_slot() else {
return (
axum::http::StatusCode::TOO_MANY_REQUESTS,
Json(json!({"error": {"message": "too many chats in progress; try again shortly", "type": "rate_limit_error"}})),
)
.into_response();
};
let session_id = agent.store().new_id();
if let Err(e) = agent.store().begin_api(&session_id) {
let (status, kind, message) = failure(&e);
eprintln!("[api] could not tag session {session_id} as api: {e}");
return (
status,
Json(json!({"error": {"message": message, "type": kind}})),
)
.into_response();
}
let opts = eclipse_core::runtime::RunOptions {
max_iterations: None,
resume: false,
output_schema: None,
title: false,
images,
};
let result = agent
.run_with(Some(&session_id), &prompt, &DenyAll, &|_event| {}, &opts)
.await;
match result {
Ok(run) => {
let created = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let body = json!({
"id": format!("chatcmpl-{}", session_id),
"object": "chat.completion",
"created": created,
"model": answering,
"choices": [{
"index": 0,
"message": {
"role": "assistant",
"content": run.reply,
},
"finish_reason": "stop",
}],
});
(axum::http::StatusCode::OK, Json(body)).into_response()
}
Err(e) => {
let (status, kind, message) = failure(&e);
eprintln!("[api] the run failed: {e}");
(
status,
Json(json!({"error": {"message": message, "type": kind}})),
)
.into_response()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn flatten_keeps_roles_and_system_prefix() {
let messages = vec![
ApiMessage {
role: "system".into(),
content: Some(json!("be brief")),
},
ApiMessage {
role: "user".into(),
content: Some(json!("hi")),
},
ApiMessage {
role: "assistant".into(),
content: Some(json!("hello")),
},
ApiMessage {
role: "user".into(),
content: Some(json!("again")),
},
];
let out = flatten_carrying(&messages, None);
assert!(out.starts_with("[system instruction]\nbe brief"));
assert!(out.contains("[user]\nhi"));
assert!(out.contains("[assistant]\nhello"));
assert!(out.ends_with("[user]\nagain"));
}
#[test]
fn flatten_drops_empty_parts() {
let messages = vec![
ApiMessage {
role: "user".into(),
content: None,
},
ApiMessage {
role: "user".into(),
content: Some(json!("real")),
},
];
assert_eq!(flatten_carrying(&messages, None), "[user]\nreal");
}
#[test]
fn flatten_text_parts_only() {
let messages = vec![ApiMessage {
role: "user".into(),
content: Some(json!([
{"type": "text", "text": "one"},
{"type": "image_url", "image_url": {"url": "x"}},
{"type": "text", "text": "two"},
])),
}];
let out = flatten_carrying(&messages, None);
assert!(out.starts_with("[user]\none\ntwo\n"), "{out}");
assert!(
out.contains("1 picture(s) attached to this message did not travel"),
"{out}"
);
assert!(!out.contains("\"x\""), "the part's url is not text: {out}");
assert_eq!(flatten_carrying(&messages, Some(0)), "[user]\none\ntwo");
}
#[test]
fn a_request_for_another_model_is_refused() {
let why = model_ok(Some("gpt-4"), "qwen-3.8-27b").expect_err("a different model is a no");
assert!(why.contains("gpt-4"), "{why}");
assert!(why.contains("qwen-3.8-27b"), "{why}");
}
#[test]
fn the_model_that_answers_may_be_named_and_omitting_it_is_fine() {
assert!(model_ok(Some("qwen-3.8-27b"), "qwen-3.8-27b").is_ok());
assert!(
model_ok(Some(" qwen-3.8-27b "), "qwen-3.8-27b").is_ok(),
"trimmed"
);
assert!(model_ok(None, "qwen-3.8-27b").is_ok());
assert!(
model_ok(Some(""), "qwen-3.8-27b").is_ok(),
"an empty name is not a request"
);
assert!(model_ok(Some(" "), "qwen-3.8-27b").is_ok());
}
#[test]
fn the_bearer_scheme_is_case_insensitive_and_the_token_is_not() {
use axum::http::HeaderMap;
for scheme in ["Bearer", "bearer", "BEARER", "BeArEr"] {
let mut h = HeaderMap::new();
h.insert("authorization", format!("{scheme} tok").parse().unwrap());
assert!(bearer_ok(&h, "tok"), "{scheme} must authenticate");
assert!(!bearer_ok(&h, "TOK"), "the token itself is exact");
}
for bad in ["Bearer", "BearerX tok", "Basic tok", ""] {
let mut h = HeaderMap::new();
h.insert("authorization", bad.parse().unwrap());
assert!(!bearer_ok(&h, "tok"), "{bad:?} must not authenticate");
}
}
#[test]
fn bearer_requires_the_token() {
use axum::http::HeaderMap;
let mut h = HeaderMap::new();
assert!(!bearer_ok(&h, "tok"));
h.insert("authorization", "Bearer wrong".parse().unwrap());
assert!(!bearer_ok(&h, "tok"));
h.insert("authorization", "Bearer tok".parse().unwrap());
assert!(bearer_ok(&h, "tok"));
}
#[test]
fn a_failed_run_is_answered_by_its_class_and_not_by_its_payload() {
use eclipse_core::Error;
let (status, kind, message) = failure(&Error::provider(
"could not reach http://10.1.2.3:9/v1: refused",
));
assert_eq!(status, axum::http::StatusCode::BAD_GATEWAY);
assert_eq!(kind, "server_error");
assert!(
!message.contains("10.1.2.3"),
"the endpoint is not the caller's business: {message}"
);
let (status, _, message) = failure(&Error::Session(
"no such table: messages at /home/someone/x.db".into(),
));
assert_eq!(status, axum::http::StatusCode::INTERNAL_SERVER_ERROR);
assert!(
!message.contains("messages") && !message.contains("/home/"),
"a store failure is this process's own: {message}"
);
let (status, kind, message) =
failure(&Error::Vision("say why, then what to change".into()));
assert_eq!(status, axum::http::StatusCode::BAD_REQUEST);
assert_eq!(kind, "invalid_request_error");
assert_eq!(message, "say why, then what to change");
let (status, _, message) = failure(&Error::MaxIterations(3));
assert_eq!(status, axum::http::StatusCode::BAD_GATEWAY);
assert!(message.contains('3'), "{message}");
}
#[test]
fn an_image_part_becomes_a_picture_the_turn_carries() {
let content = json!([
{"type": "text", "text": "what does the sign say?"},
{"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="}},
]);
let images = images_of(Some(&content)).expect("a data URL is a picture");
assert_eq!(images.len(), 1);
assert_eq!(images[0].mime, "image/png");
assert_eq!(images[0].url, "data:image/png;base64,iVBORw0KGgo=");
assert_eq!(images[0].name, "picture");
let messages: Vec<ApiMessage> = vec![ApiMessage {
role: "user".to_string(),
content: Some(content),
}];
let prompt = flatten_carrying(&messages, Some(0));
assert!(prompt.contains("what does the sign say?"), "{prompt}");
assert!(
!prompt.contains("data:image/png"),
"the bytes are the part's, not the prompt's: {prompt}"
);
}
#[test]
fn a_picture_that_is_not_a_data_url_is_refused_not_dropped() {
let content =
json!([{"type": "image_url", "image_url": {"url": "https://example.com/a.png"}}]);
let sentence = images_of(Some(&content)).expect_err("a link is not a picture");
assert!(sentence.contains("base64 data: URL"), "{sentence}");
let content = json!([{"type": "image_url", "image_url": {"url": "data:application/pdf;base64,iVBORw0KGgo="}}]);
let sentence = images_of(Some(&content)).expect_err("a PDF is not a picture");
assert!(
sentence.contains("not a picture this build can carry"),
"{sentence}"
);
let content = json!([{"type": "image_url"}]);
let sentence = images_of(Some(&content)).expect_err("no url at all");
assert!(sentence.contains("has no `url`"), "{sentence}");
}
#[test]
fn only_the_last_messages_pictures_travel_and_the_rest_are_named() {
let with = |text: &str| ApiMessage {
role: "user".to_string(),
content: Some(json!([
{"type": "text", "text": text},
{"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="}},
])),
};
let messages = vec![with("earlier"), with("now")];
let prompt = flatten_carrying(&messages, Some(1));
assert!(prompt.contains("earlier"), "{prompt}");
assert!(prompt.contains("did not travel"), "{prompt}");
assert!(
prompt.matches("did not travel").count() == 1,
"the carried message is not named as left behind: {prompt}"
);
let bare = vec![ApiMessage {
role: "user".to_string(),
content: Some(json!([
{"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="}},
])),
}];
let prompt = flatten_carrying(&bare, Some(0));
assert!(prompt.contains("(the attached picture)"), "{prompt}");
}
}