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