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