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