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