gaise-api 0.2.0

Axum HTTP server for GAISe — exposes /v1/instruct, /v1/instruct/stream, and /v1/embeddings
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use axum::{
    Json, Router,
    extract::{Path, Query, State},
    http::StatusCode,
    response::{
        IntoResponse,
        sse::{Event, Sse},
    },
    routing::{get, post},
};
use futures_util::StreamExt;
use gaise_client::GaiseClientService;
use gaise_core::{
    GaiseClient,
    contracts::{
        GaiseEmbeddingsRequest, GaiseInstructRequest, GaiseListModelsRequest, GaiseOperation,
    },
};
use std::sync::Arc;
use tracing::error;

#[cfg(feature = "live")]
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
#[cfg(feature = "live")]
use gaise_core::{
    GaiseLiveClient,
    contracts::{GaiseLiveConfig, GaiseLiveEvent, GaiseLiveInput},
};
#[cfg(feature = "elevenlabs")]
use gaise_core::{
    GaiseSpeechClient,
    contracts::{GaiseSpeechChunk, GaiseSpeechRequest},
};

pub struct AppState {
    pub client_service: GaiseClientService,
}

pub fn create_app(state: Arc<AppState>) -> Router {
    let router = Router::new()
        .route("/v1/instruct", post(handle_instruct))
        .route("/v1/instruct/stream", post(handle_instruct_stream))
        .route("/v1/embeddings", post(handle_embeddings))
        .route("/v1/models", get(handle_list_models))
        .route("/v1/models/:model", get(handle_get_model));

    #[cfg(feature = "live")]
    let router = router.route("/v1/live", axum::routing::get(handle_live_ws));

    #[cfg(feature = "elevenlabs")]
    let router = router
        .route("/v1/speech", post(handle_speech))
        .route("/v1/speech/stream", post(handle_speech_stream))
        .route("/v1/speech/audio", post(handle_speech_audio));

    router.with_state(state)
}

async fn handle_instruct(
    State(state): State<Arc<AppState>>,
    Json(request): Json<GaiseInstructRequest>,
) -> impl IntoResponse {
    match state.client_service.instruct(&request).await {
        Ok(response) => Json(response).into_response(),
        Err(e) => {
            error!("Instruct error: {}", e);
            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
        }
    }
}

async fn handle_instruct_stream(
    State(state): State<Arc<AppState>>,
    Json(request): Json<GaiseInstructRequest>,
) -> impl IntoResponse {
    match state.client_service.instruct_stream(&request).await {
        Ok(stream) => {
            let sse_stream = stream.map(|item| match item {
                Ok(chunk) => Event::default().json_data(chunk),
                Err(e) => Ok(Event::default().event("error").data(e.to_string())),
            });
            Sse::new(sse_stream).into_response()
        }
        Err(e) => {
            error!("Instruct stream error: {}", e);
            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
        }
    }
}

async fn handle_embeddings(
    State(state): State<Arc<AppState>>,
    Json(request): Json<GaiseEmbeddingsRequest>,
) -> impl IntoResponse {
    match state.client_service.embeddings(&request).await {
        Ok(response) => Json(response).into_response(),
        Err(e) => {
            error!("Embeddings error: {}", e);
            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
        }
    }
}

/// Query parameters for `GET /v1/models`.
#[derive(Debug, Default, serde::Deserialize)]
pub struct ListModelsQuery {
    /// Restrict to one provider key.
    pub provider: Option<String>,
    /// Keep only models supporting this operation
    /// (`instruct`, `instruct_stream`, `embeddings`, `live`).
    pub operation: Option<String>,
    /// Fetch per-model detail where it costs extra requests (Ollama).
    #[serde(default)]
    pub include_details: bool,
    /// Attach each provider's native record.
    #[serde(default)]
    pub include_raw: bool,
    pub correlation_id: Option<String>,
}

impl ListModelsQuery {
    fn into_request(self) -> Result<GaiseListModelsRequest, String> {
        let operation = match self.operation.as_deref() {
            None | Some("") => None,
            Some(value) => Some(
                GaiseOperation::parse(value)
                    .ok_or_else(|| format!("unknown operation '{value}'"))?,
            ),
        };
        Ok(GaiseListModelsRequest {
            provider: self.provider.filter(|p| !p.is_empty()),
            operation,
            include_details: self.include_details,
            include_raw: self.include_raw,
            correlation_id: self.correlation_id,
            connection: None,
        })
    }
}

async fn handle_list_models(
    State(state): State<Arc<AppState>>,
    Query(query): Query<ListModelsQuery>,
) -> impl IntoResponse {
    let request = match query.into_request() {
        Ok(request) => request,
        Err(message) => return (StatusCode::BAD_REQUEST, message).into_response(),
    };
    match state.client_service.list_models(&request).await {
        Ok(response) => Json(response).into_response(),
        Err(e) => {
            error!("List models error: {}", e);
            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
        }
    }
}

/// `GET /v1/models/{provider}::{id}` — one model from one provider's listing.
async fn handle_get_model(
    State(state): State<Arc<AppState>>,
    Path(model): Path<String>,
    Query(query): Query<ListModelsQuery>,
) -> impl IntoResponse {
    let Some((provider, _)) = model.split_once("::") else {
        return (
            StatusCode::BAD_REQUEST,
            "model must be in the format 'provider::model'".to_string(),
        )
            .into_response();
    };
    let request = GaiseListModelsRequest {
        provider: Some(provider.to_string()),
        operation: None,
        include_details: query.include_details,
        include_raw: query.include_raw,
        correlation_id: query.correlation_id,
        connection: None,
    };
    match state.client_service.list_models(&request).await {
        Ok(response) => match response.models.into_iter().find(|m| m.id == model) {
            Some(found) => Json(found).into_response(),
            None => (
                StatusCode::NOT_FOUND,
                format!("model '{model}' not listed by {provider}"),
            )
                .into_response(),
        },
        Err(e) => {
            error!("Get model error: {}", e);
            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
        }
    }
}

// ── Speech endpoints ───────────────────────────────────────────────

/// `POST /v1/speech` — full clip as JSON (`audio` is a byte array).
#[cfg(feature = "elevenlabs")]
async fn handle_speech(
    State(state): State<Arc<AppState>>,
    Json(request): Json<GaiseSpeechRequest>,
) -> impl IntoResponse {
    match state.client_service.speech(&request).await {
        Ok(response) => Json(response).into_response(),
        Err(e) => {
            error!("Speech error: {}", e);
            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
        }
    }
}

/// `POST /v1/speech/stream` — SSE of `GaiseSpeechStreamResponse` (audio,
/// alignment, usage chunks).
#[cfg(feature = "elevenlabs")]
async fn handle_speech_stream(
    State(state): State<Arc<AppState>>,
    Json(request): Json<GaiseSpeechRequest>,
) -> impl IntoResponse {
    match state.client_service.speech_stream(&request).await {
        Ok(stream) => {
            let sse_stream = stream.map(|item| match item {
                Ok(chunk) => Event::default().json_data(chunk),
                Err(e) => Ok(Event::default().event("error").data(e.to_string())),
            });
            Sse::new(sse_stream).into_response()
        }
        Err(e) => {
            error!("Speech stream error: {}", e);
            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
        }
    }
}

/// `POST /v1/speech/audio` — raw audio bytes, chunked as the provider
/// produces them, with the MIME type in `Content-Type` and the PCM rate in
/// `X-Gaise-Sample-Rate`. Alignment and usage chunks are dropped.
#[cfg(feature = "elevenlabs")]
async fn handle_speech_audio(
    State(state): State<Arc<AppState>>,
    Json(request): Json<GaiseSpeechRequest>,
) -> impl IntoResponse {
    use axum::body::Body;
    use futures_util::StreamExt as _;

    let mut stream = match state.client_service.speech_stream(&request).await {
        Ok(stream) => stream,
        Err(e) => {
            error!("Speech audio error: {}", e);
            return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
        }
    };
    // Peek the first audio chunk so the headers can carry the real format.
    let mut first: Option<(Vec<u8>, String, Option<u32>)> = None;
    while let Some(item) = stream.next().await {
        match item {
            Ok(resp) => {
                if let GaiseSpeechChunk::Audio {
                    data,
                    format,
                    sample_rate,
                } = resp.chunk
                {
                    first = Some((data, format, sample_rate));
                    break;
                }
            }
            Err(e) => {
                error!("Speech audio error: {}", e);
                return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
            }
        }
    }
    let Some((head, format, sample_rate)) = first else {
        return (
            StatusCode::BAD_GATEWAY,
            "provider returned no audio".to_string(),
        )
            .into_response();
    };
    let rest = stream.filter_map(|item| async move {
        match item {
            Ok(resp) => match resp.chunk {
                GaiseSpeechChunk::Audio { data, .. } => Some(Ok::<_, std::io::Error>(data)),
                _ => None,
            },
            Err(e) => Some(Err(std::io::Error::other(e.to_string()))),
        }
    });
    let body = Body::from_stream(futures_util::stream::once(async move { Ok(head) }).chain(rest));
    let mut response = axum::response::Response::new(body);
    response.headers_mut().insert(
        axum::http::header::CONTENT_TYPE,
        axum::http::HeaderValue::from_str(&format).unwrap_or(axum::http::HeaderValue::from_static(
            "application/octet-stream",
        )),
    );
    if let Some(rate) = sample_rate
        && let Ok(value) = axum::http::HeaderValue::from_str(&rate.to_string())
    {
        response.headers_mut().insert("x-gaise-sample-rate", value);
    }
    response
}

// ── Live WebSocket endpoint ─────────────────────────────────────────

#[cfg(feature = "live")]
async fn handle_live_ws(
    ws: WebSocketUpgrade,
    State(state): State<Arc<AppState>>,
) -> impl IntoResponse {
    ws.on_upgrade(move |socket| handle_live_session(socket, state))
}

#[cfg(feature = "live")]
async fn handle_live_session(socket: WebSocket, state: Arc<AppState>) {
    use futures_util::SinkExt;

    let (mut ws_sink, mut ws_source) = socket.split();

    // First message must be a config message
    let config: GaiseLiveConfig = loop {
        match ws_source.next().await {
            Some(Ok(Message::Text(text))) => match serde_json::from_str::<GaiseLiveConfig>(&text) {
                Ok(cfg) => break cfg,
                Err(e) => {
                    let err = serde_json::json!({"type": "error", "message": format!("Invalid config: {}", e)});
                    let _ = ws_sink.send(Message::Text(err.to_string())).await;
                    return;
                }
            },
            Some(Ok(Message::Close(_))) | None => return,
            _ => continue,
        }
    };

    // Connect to provider
    let session = match state.client_service.live_connect(&config).await {
        Ok(s) => s,
        Err(e) => {
            let err =
                serde_json::json!({"type": "error", "message": format!("Connect error: {}", e)});
            let _ = ws_sink.send(Message::Text(err.to_string())).await;
            return;
        }
    };

    let input_tx = session.tx;
    let mut event_rx = session.rx;

    // Forward provider events → client WebSocket
    let send_handle = tokio::spawn(async move {
        while let Some(event) = event_rx.next().await {
            let msg = match event {
                Ok(GaiseLiveEvent::Audio { data, sample_rate }) => {
                    // Send audio as binary frames
                    // Prepend 4-byte sample rate header for client to know the rate
                    let mut frame = Vec::with_capacity(4 + data.len());
                    frame.extend_from_slice(&sample_rate.to_le_bytes());
                    frame.extend_from_slice(&data);
                    Message::Binary(frame)
                }
                Ok(event) => match serde_json::to_string(&event) {
                    Ok(json) => Message::Text(json),
                    Err(_) => continue,
                },
                Err(e) => {
                    let err = serde_json::json!({"type": "error", "message": e.to_string()});
                    Message::Text(err.to_string())
                }
            };
            if ws_sink.send(msg).await.is_err() {
                break;
            }
        }
    });

    // Forward client WebSocket → provider input channel
    while let Some(msg) = ws_source.next().await {
        let msg = match msg {
            Ok(m) => m,
            Err(_) => break,
        };

        let input = match msg {
            Message::Text(text) => match serde_json::from_str::<GaiseLiveInput>(&text) {
                Ok(input) => input,
                Err(_) => continue,
            },
            Message::Binary(data) => {
                // Binary frames are raw PCM audio (16kHz PCM16 by default)
                GaiseLiveInput::Audio {
                    data: data.to_vec(),
                    sample_rate: 16000,
                }
            }
            Message::Close(_) => {
                let _ = input_tx.send(GaiseLiveInput::Close).await;
                break;
            }
            _ => continue,
        };

        if input_tx.send(input).await.is_err() {
            break;
        }
    }

    // Cleanup
    let _ = input_tx.send(GaiseLiveInput::Close).await;
    send_handle.abort();
}