Skip to main content

gaise_api/
lib.rs

1use axum::{
2    Json, Router,
3    extract::{Path, Query, State},
4    http::StatusCode,
5    response::{
6        IntoResponse,
7        sse::{Event, Sse},
8    },
9    routing::{get, post},
10};
11use futures_util::StreamExt;
12use gaise_client::GaiseClientService;
13use gaise_core::{
14    GaiseClient,
15    contracts::{
16        GaiseEmbeddingsRequest, GaiseInstructRequest, GaiseListModelsRequest, GaiseOperation,
17    },
18};
19use std::sync::Arc;
20use tracing::error;
21
22#[cfg(feature = "live")]
23use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
24#[cfg(feature = "live")]
25use gaise_core::{
26    GaiseLiveClient,
27    contracts::{GaiseLiveConfig, GaiseLiveEvent, GaiseLiveInput},
28};
29#[cfg(feature = "elevenlabs")]
30use gaise_core::{
31    GaiseSpeechClient,
32    contracts::{GaiseSpeechChunk, GaiseSpeechRequest},
33};
34
35pub struct AppState {
36    pub client_service: GaiseClientService,
37}
38
39pub fn create_app(state: Arc<AppState>) -> Router {
40    let router = Router::new()
41        .route("/v1/instruct", post(handle_instruct))
42        .route("/v1/instruct/stream", post(handle_instruct_stream))
43        .route("/v1/embeddings", post(handle_embeddings))
44        .route("/v1/models", get(handle_list_models))
45        .route("/v1/models/:model", get(handle_get_model));
46
47    #[cfg(feature = "live")]
48    let router = router.route("/v1/live", axum::routing::get(handle_live_ws));
49
50    #[cfg(feature = "elevenlabs")]
51    let router = router
52        .route("/v1/speech", post(handle_speech))
53        .route("/v1/speech/stream", post(handle_speech_stream))
54        .route("/v1/speech/audio", post(handle_speech_audio));
55
56    router.with_state(state)
57}
58
59async fn handle_instruct(
60    State(state): State<Arc<AppState>>,
61    Json(request): Json<GaiseInstructRequest>,
62) -> impl IntoResponse {
63    match state.client_service.instruct(&request).await {
64        Ok(response) => Json(response).into_response(),
65        Err(e) => {
66            error!("Instruct error: {}", e);
67            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
68        }
69    }
70}
71
72async fn handle_instruct_stream(
73    State(state): State<Arc<AppState>>,
74    Json(request): Json<GaiseInstructRequest>,
75) -> impl IntoResponse {
76    match state.client_service.instruct_stream(&request).await {
77        Ok(stream) => {
78            let sse_stream = stream.map(|item| match item {
79                Ok(chunk) => Event::default().json_data(chunk),
80                Err(e) => Ok(Event::default().event("error").data(e.to_string())),
81            });
82            Sse::new(sse_stream).into_response()
83        }
84        Err(e) => {
85            error!("Instruct stream error: {}", e);
86            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
87        }
88    }
89}
90
91async fn handle_embeddings(
92    State(state): State<Arc<AppState>>,
93    Json(request): Json<GaiseEmbeddingsRequest>,
94) -> impl IntoResponse {
95    match state.client_service.embeddings(&request).await {
96        Ok(response) => Json(response).into_response(),
97        Err(e) => {
98            error!("Embeddings error: {}", e);
99            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
100        }
101    }
102}
103
104/// Query parameters for `GET /v1/models`.
105#[derive(Debug, Default, serde::Deserialize)]
106pub struct ListModelsQuery {
107    /// Restrict to one provider key.
108    pub provider: Option<String>,
109    /// Keep only models supporting this operation
110    /// (`instruct`, `instruct_stream`, `embeddings`, `live`).
111    pub operation: Option<String>,
112    /// Fetch per-model detail where it costs extra requests (Ollama).
113    #[serde(default)]
114    pub include_details: bool,
115    /// Attach each provider's native record.
116    #[serde(default)]
117    pub include_raw: bool,
118    pub correlation_id: Option<String>,
119}
120
121impl ListModelsQuery {
122    fn into_request(self) -> Result<GaiseListModelsRequest, String> {
123        let operation = match self.operation.as_deref() {
124            None | Some("") => None,
125            Some(value) => Some(
126                GaiseOperation::parse(value)
127                    .ok_or_else(|| format!("unknown operation '{value}'"))?,
128            ),
129        };
130        Ok(GaiseListModelsRequest {
131            provider: self.provider.filter(|p| !p.is_empty()),
132            operation,
133            include_details: self.include_details,
134            include_raw: self.include_raw,
135            correlation_id: self.correlation_id,
136            connection: None,
137        })
138    }
139}
140
141async fn handle_list_models(
142    State(state): State<Arc<AppState>>,
143    Query(query): Query<ListModelsQuery>,
144) -> impl IntoResponse {
145    let request = match query.into_request() {
146        Ok(request) => request,
147        Err(message) => return (StatusCode::BAD_REQUEST, message).into_response(),
148    };
149    match state.client_service.list_models(&request).await {
150        Ok(response) => Json(response).into_response(),
151        Err(e) => {
152            error!("List models error: {}", e);
153            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
154        }
155    }
156}
157
158/// `GET /v1/models/{provider}::{id}` — one model from one provider's listing.
159async fn handle_get_model(
160    State(state): State<Arc<AppState>>,
161    Path(model): Path<String>,
162    Query(query): Query<ListModelsQuery>,
163) -> impl IntoResponse {
164    let Some((provider, _)) = model.split_once("::") else {
165        return (
166            StatusCode::BAD_REQUEST,
167            "model must be in the format 'provider::model'".to_string(),
168        )
169            .into_response();
170    };
171    let request = GaiseListModelsRequest {
172        provider: Some(provider.to_string()),
173        operation: None,
174        include_details: query.include_details,
175        include_raw: query.include_raw,
176        correlation_id: query.correlation_id,
177        connection: None,
178    };
179    match state.client_service.list_models(&request).await {
180        Ok(response) => match response.models.into_iter().find(|m| m.id == model) {
181            Some(found) => Json(found).into_response(),
182            None => (
183                StatusCode::NOT_FOUND,
184                format!("model '{model}' not listed by {provider}"),
185            )
186                .into_response(),
187        },
188        Err(e) => {
189            error!("Get model error: {}", e);
190            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
191        }
192    }
193}
194
195// ── Speech endpoints ───────────────────────────────────────────────
196
197/// `POST /v1/speech` — full clip as JSON (`audio` is a byte array).
198#[cfg(feature = "elevenlabs")]
199async fn handle_speech(
200    State(state): State<Arc<AppState>>,
201    Json(request): Json<GaiseSpeechRequest>,
202) -> impl IntoResponse {
203    match state.client_service.speech(&request).await {
204        Ok(response) => Json(response).into_response(),
205        Err(e) => {
206            error!("Speech error: {}", e);
207            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
208        }
209    }
210}
211
212/// `POST /v1/speech/stream` — SSE of `GaiseSpeechStreamResponse` (audio,
213/// alignment, usage chunks).
214#[cfg(feature = "elevenlabs")]
215async fn handle_speech_stream(
216    State(state): State<Arc<AppState>>,
217    Json(request): Json<GaiseSpeechRequest>,
218) -> impl IntoResponse {
219    match state.client_service.speech_stream(&request).await {
220        Ok(stream) => {
221            let sse_stream = stream.map(|item| match item {
222                Ok(chunk) => Event::default().json_data(chunk),
223                Err(e) => Ok(Event::default().event("error").data(e.to_string())),
224            });
225            Sse::new(sse_stream).into_response()
226        }
227        Err(e) => {
228            error!("Speech stream error: {}", e);
229            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
230        }
231    }
232}
233
234/// `POST /v1/speech/audio` — raw audio bytes, chunked as the provider
235/// produces them, with the MIME type in `Content-Type` and the PCM rate in
236/// `X-Gaise-Sample-Rate`. Alignment and usage chunks are dropped.
237#[cfg(feature = "elevenlabs")]
238async fn handle_speech_audio(
239    State(state): State<Arc<AppState>>,
240    Json(request): Json<GaiseSpeechRequest>,
241) -> impl IntoResponse {
242    use axum::body::Body;
243    use futures_util::StreamExt as _;
244
245    let mut stream = match state.client_service.speech_stream(&request).await {
246        Ok(stream) => stream,
247        Err(e) => {
248            error!("Speech audio error: {}", e);
249            return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
250        }
251    };
252    // Peek the first audio chunk so the headers can carry the real format.
253    let mut first: Option<(Vec<u8>, String, Option<u32>)> = None;
254    while let Some(item) = stream.next().await {
255        match item {
256            Ok(resp) => {
257                if let GaiseSpeechChunk::Audio {
258                    data,
259                    format,
260                    sample_rate,
261                } = resp.chunk
262                {
263                    first = Some((data, format, sample_rate));
264                    break;
265                }
266            }
267            Err(e) => {
268                error!("Speech audio error: {}", e);
269                return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
270            }
271        }
272    }
273    let Some((head, format, sample_rate)) = first else {
274        return (
275            StatusCode::BAD_GATEWAY,
276            "provider returned no audio".to_string(),
277        )
278            .into_response();
279    };
280    let rest = stream.filter_map(|item| async move {
281        match item {
282            Ok(resp) => match resp.chunk {
283                GaiseSpeechChunk::Audio { data, .. } => Some(Ok::<_, std::io::Error>(data)),
284                _ => None,
285            },
286            Err(e) => Some(Err(std::io::Error::other(e.to_string()))),
287        }
288    });
289    let body = Body::from_stream(futures_util::stream::once(async move { Ok(head) }).chain(rest));
290    let mut response = axum::response::Response::new(body);
291    response.headers_mut().insert(
292        axum::http::header::CONTENT_TYPE,
293        axum::http::HeaderValue::from_str(&format).unwrap_or(axum::http::HeaderValue::from_static(
294            "application/octet-stream",
295        )),
296    );
297    if let Some(rate) = sample_rate
298        && let Ok(value) = axum::http::HeaderValue::from_str(&rate.to_string())
299    {
300        response.headers_mut().insert("x-gaise-sample-rate", value);
301    }
302    response
303}
304
305// ── Live WebSocket endpoint ─────────────────────────────────────────
306
307#[cfg(feature = "live")]
308async fn handle_live_ws(
309    ws: WebSocketUpgrade,
310    State(state): State<Arc<AppState>>,
311) -> impl IntoResponse {
312    ws.on_upgrade(move |socket| handle_live_session(socket, state))
313}
314
315#[cfg(feature = "live")]
316async fn handle_live_session(socket: WebSocket, state: Arc<AppState>) {
317    use futures_util::SinkExt;
318
319    let (mut ws_sink, mut ws_source) = socket.split();
320
321    // First message must be a config message
322    let config: GaiseLiveConfig = loop {
323        match ws_source.next().await {
324            Some(Ok(Message::Text(text))) => match serde_json::from_str::<GaiseLiveConfig>(&text) {
325                Ok(cfg) => break cfg,
326                Err(e) => {
327                    let err = serde_json::json!({"type": "error", "message": format!("Invalid config: {}", e)});
328                    let _ = ws_sink.send(Message::Text(err.to_string())).await;
329                    return;
330                }
331            },
332            Some(Ok(Message::Close(_))) | None => return,
333            _ => continue,
334        }
335    };
336
337    // Connect to provider
338    let session = match state.client_service.live_connect(&config).await {
339        Ok(s) => s,
340        Err(e) => {
341            let err =
342                serde_json::json!({"type": "error", "message": format!("Connect error: {}", e)});
343            let _ = ws_sink.send(Message::Text(err.to_string())).await;
344            return;
345        }
346    };
347
348    let input_tx = session.tx;
349    let mut event_rx = session.rx;
350
351    // Forward provider events → client WebSocket
352    let send_handle = tokio::spawn(async move {
353        while let Some(event) = event_rx.next().await {
354            let msg = match event {
355                Ok(GaiseLiveEvent::Audio { data, sample_rate }) => {
356                    // Send audio as binary frames
357                    // Prepend 4-byte sample rate header for client to know the rate
358                    let mut frame = Vec::with_capacity(4 + data.len());
359                    frame.extend_from_slice(&sample_rate.to_le_bytes());
360                    frame.extend_from_slice(&data);
361                    Message::Binary(frame)
362                }
363                Ok(event) => match serde_json::to_string(&event) {
364                    Ok(json) => Message::Text(json),
365                    Err(_) => continue,
366                },
367                Err(e) => {
368                    let err = serde_json::json!({"type": "error", "message": e.to_string()});
369                    Message::Text(err.to_string())
370                }
371            };
372            if ws_sink.send(msg).await.is_err() {
373                break;
374            }
375        }
376    });
377
378    // Forward client WebSocket → provider input channel
379    while let Some(msg) = ws_source.next().await {
380        let msg = match msg {
381            Ok(m) => m,
382            Err(_) => break,
383        };
384
385        let input = match msg {
386            Message::Text(text) => match serde_json::from_str::<GaiseLiveInput>(&text) {
387                Ok(input) => input,
388                Err(_) => continue,
389            },
390            Message::Binary(data) => {
391                // Binary frames are raw PCM audio (16kHz PCM16 by default)
392                GaiseLiveInput::Audio {
393                    data: data.to_vec(),
394                    sample_rate: 16000,
395                }
396            }
397            Message::Close(_) => {
398                let _ = input_tx.send(GaiseLiveInput::Close).await;
399                break;
400            }
401            _ => continue,
402        };
403
404        if input_tx.send(input).await.is_err() {
405            break;
406        }
407    }
408
409    // Cleanup
410    let _ = input_tx.send(GaiseLiveInput::Close).await;
411    send_handle.abort();
412}