mistralrs_server_core/
image_generation.rs

1//! ## Image generation functionality and route handler.
2
3use std::{error::Error, sync::Arc};
4
5use anyhow::Result;
6use axum::{
7    extract::{Json, State},
8    http::{self},
9    response::IntoResponse,
10};
11use mistralrs_core::{
12    Constraint, DiffusionGenerationParams, ImageGenerationResponse, MistralRs, NormalRequest,
13    Request, RequestMessage, Response, SamplingParams,
14};
15use tokio::sync::mpsc::{Receiver, Sender};
16
17use crate::{
18    handler_core::{
19        base_process_non_streaming_response, create_response_channel, send_request,
20        ErrorToResponse, JsonError,
21    },
22    openai::ImageGenerationRequest,
23    types::{ExtractedMistralRsState, SharedMistralRsState},
24    util::validate_model_name,
25};
26
27/// Represents different types of image generation responses.
28pub enum ImageGenerationResponder {
29    Json(ImageGenerationResponse),
30    InternalError(Box<dyn Error>),
31    ValidationError(Box<dyn Error>),
32}
33
34impl IntoResponse for ImageGenerationResponder {
35    /// Converts the image generation responder into an HTTP response.
36    fn into_response(self) -> axum::response::Response {
37        match self {
38            ImageGenerationResponder::Json(s) => Json(s).into_response(),
39            ImageGenerationResponder::InternalError(e) => {
40                JsonError::new(e.to_string()).to_response(http::StatusCode::INTERNAL_SERVER_ERROR)
41            }
42            ImageGenerationResponder::ValidationError(e) => {
43                JsonError::new(e.to_string()).to_response(http::StatusCode::UNPROCESSABLE_ENTITY)
44            }
45        }
46    }
47}
48
49/// Parses and validates a image generation request.
50///
51/// This function transforms a image generation request into the
52/// request format used by mistral.rs.
53pub fn parse_request(
54    oairequest: ImageGenerationRequest,
55    state: Arc<MistralRs>,
56    tx: Sender<Response>,
57) -> Result<Request> {
58    let repr = serde_json::to_string(&oairequest).expect("Serialization of request failed.");
59    MistralRs::maybe_log_request(state.clone(), repr);
60
61    // Validate that the requested model matches the loaded model
62    validate_model_name(&oairequest.model, state.clone())?;
63
64    Ok(Request::Normal(Box::new(NormalRequest {
65        id: state.next_request_id(),
66        messages: RequestMessage::ImageGeneration {
67            prompt: oairequest.prompt,
68            format: oairequest.response_format,
69            generation_params: DiffusionGenerationParams {
70                height: oairequest.height,
71                width: oairequest.width,
72            },
73        },
74        sampling_params: SamplingParams::deterministic(),
75        response: tx,
76        return_logprobs: false,
77        is_streaming: false,
78        suffix: None,
79        constraint: Constraint::None,
80        tool_choice: None,
81        tools: None,
82        logits_processors: None,
83        return_raw_logits: false,
84        web_search_options: None,
85        model_id: if oairequest.model == "default" {
86            None
87        } else {
88            Some(oairequest.model.clone())
89        },
90    })))
91}
92
93/// Image generation endpoint handler.
94#[utoipa::path(
95    post,
96    tag = "Mistral.rs",
97    path = "/v1/images/generations",
98    request_body = ImageGenerationRequest,
99    responses((status = 200, description = "Image generation"))
100)]
101pub async fn image_generation(
102    State(state): ExtractedMistralRsState,
103    Json(oairequest): Json<ImageGenerationRequest>,
104) -> ImageGenerationResponder {
105    let (tx, mut rx) = create_response_channel(None);
106
107    let request = match parse_request(oairequest, state.clone(), tx) {
108        Ok(x) => x,
109        Err(e) => return handle_error(state, e.into()),
110    };
111
112    if let Err(e) = send_request(&state, request).await {
113        return handle_error(state, e.into());
114    }
115
116    process_non_streaming_response(&mut rx, state).await
117}
118
119/// Helper function to handle image generation errors and logging them.
120pub fn handle_error(
121    state: SharedMistralRsState,
122    e: Box<dyn std::error::Error + Send + Sync + 'static>,
123) -> ImageGenerationResponder {
124    let e = anyhow::Error::msg(e.to_string());
125    MistralRs::maybe_log_error(state, &*e);
126    ImageGenerationResponder::InternalError(e.into())
127}
128
129/// Process non-streaming image generation responses.
130pub async fn process_non_streaming_response(
131    rx: &mut Receiver<Response>,
132    state: SharedMistralRsState,
133) -> ImageGenerationResponder {
134    base_process_non_streaming_response(rx, state, match_responses, handle_error).await
135}
136
137/// Matches and processes different types of model responses into appropriate image generation responses.
138pub fn match_responses(
139    state: SharedMistralRsState,
140    response: Response,
141) -> ImageGenerationResponder {
142    match response {
143        Response::InternalError(e) => {
144            MistralRs::maybe_log_error(state, &*e);
145            ImageGenerationResponder::InternalError(e)
146        }
147        Response::ValidationError(e) => ImageGenerationResponder::ValidationError(e),
148        Response::ImageGeneration(response) => {
149            MistralRs::maybe_log_response(state, &response);
150            ImageGenerationResponder::Json(response)
151        }
152        Response::CompletionModelError(m, _) => {
153            let e = anyhow::Error::msg(m.to_string());
154            MistralRs::maybe_log_error(state, &*e);
155            ImageGenerationResponder::InternalError(e.into())
156        }
157        Response::CompletionDone(_) => unreachable!(),
158        Response::CompletionChunk(_) => unreachable!(),
159        Response::Chunk(_) => unreachable!(),
160        Response::Done(_) => unreachable!(),
161        Response::ModelError(_, _) => unreachable!(),
162        Response::Speech { .. } => unreachable!(),
163        Response::Raw { .. } => unreachable!(),
164    }
165}