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        GaiseImageRequest, GaiseInstructRequest, GaiseListModelsRequest, GaiseOperation,
18        GaiseTranscriptionRequest, GaiseVideoJobRequest, GaiseVideoRequest,
19    },
20    registry,
21};
22use std::sync::Arc;
23use tracing::error;
24
25#[cfg(feature = "live")]
26use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
27#[cfg(feature = "live")]
28use gaise_core::{
29    GaiseLiveClient,
30    contracts::{GaiseLiveConfig, GaiseLiveEvent, GaiseLiveInput},
31};
32#[cfg(any(feature = "elevenlabs", feature = "xai"))]
33use gaise_core::{
34    GaiseSpeechClient,
35    contracts::{GaiseSpeechChunk, GaiseSpeechRequest},
36};
37
38pub struct AppState {
39    pub client_service: GaiseClientService,
40}
41
42pub fn create_app(state: Arc<AppState>) -> Router {
43    let router = Router::new()
44        .route("/v1/decision", post(handle_decision))
45        // Same handler: the path TypeSafe and Ollama use for this protocol.
46        .route("/v1/systemone", post(handle_decision))
47        .route("/v1/instruct", post(handle_instruct))
48        .route("/v1/instruct/stream", post(handle_instruct_stream))
49        .route("/v1/embeddings", post(handle_embeddings))
50        .route("/v1/embeddings/contents", post(handle_content_embeddings))
51        .route("/v1/models", get(handle_list_models))
52        .route("/v1/models/limits", get(handle_model_limits))
53        .route("/v1/models/:model", get(handle_get_model))
54        .route("/v1/transcriptions", post(handle_transcribe))
55        .route("/v1/images", post(handle_images))
56        .route("/v1/videos", post(handle_start_video))
57        .route("/v1/videos/:id", get(handle_get_video));
58
59    #[cfg(feature = "live")]
60    let router = router
61        .route("/v1/live", axum::routing::get(handle_live_ws))
62        .route(
63            "/v1/transcriptions/live",
64            axum::routing::get(handle_transcription_ws),
65        );
66
67    #[cfg(any(feature = "elevenlabs", feature = "xai"))]
68    let router = router
69        .route("/v1/speech", post(handle_speech))
70        .route("/v1/speech/stream", post(handle_speech_stream))
71        .route("/v1/speech/audio", post(handle_speech_audio));
72
73    router.with_state(state)
74}
75
76/// `POST /v1/decision` body: a decision request plus optional `images`
77/// (`GaiseContent` image items) shared by every question.
78#[derive(serde::Deserialize)]
79struct DecisionBody {
80    #[serde(flatten)]
81    request: GaiseDecisionRequest,
82    #[serde(default)]
83    images: Vec<GaiseContent>,
84}
85
86async fn handle_decision(
87    State(state): State<Arc<AppState>>,
88    Json(body): Json<DecisionBody>,
89) -> impl IntoResponse {
90    let DecisionBody { request, images } = body;
91    if let Err(error) = request.validate() {
92        return (StatusCode::BAD_REQUEST, error).into_response();
93    }
94    match state
95        .client_service
96        .decision_with_images(&request, &images)
97        .await
98    {
99        Ok(response) => Json(response).into_response(),
100        Err(e) => {
101            error!("Decision error: {}", e);
102            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
103        }
104    }
105}
106
107async fn handle_instruct(
108    State(state): State<Arc<AppState>>,
109    Json(request): Json<GaiseInstructRequest>,
110) -> impl IntoResponse {
111    match state.client_service.instruct(&request).await {
112        Ok(response) => Json(response).into_response(),
113        Err(e) => {
114            error!("Instruct error: {}", e);
115            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
116        }
117    }
118}
119
120async fn handle_instruct_stream(
121    State(state): State<Arc<AppState>>,
122    Json(request): Json<GaiseInstructRequest>,
123) -> impl IntoResponse {
124    match state.client_service.instruct_stream(&request).await {
125        Ok(stream) => {
126            let sse_stream = stream.map(|item| match item {
127                Ok(chunk) => Event::default().json_data(chunk),
128                Err(e) => Ok(Event::default().event("error").data(e.to_string())),
129            });
130            Sse::new(sse_stream).into_response()
131        }
132        Err(e) => {
133            error!("Instruct stream error: {}", e);
134            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
135        }
136    }
137}
138
139async fn handle_embeddings(
140    State(state): State<Arc<AppState>>,
141    Json(request): Json<GaiseEmbeddingsRequest>,
142) -> impl IntoResponse {
143    match state.client_service.embeddings(&request).await {
144        Ok(response) => Json(response).into_response(),
145        Err(e) => {
146            error!("Embeddings error: {}", e);
147            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
148        }
149    }
150}
151
152async fn handle_content_embeddings(
153    State(state): State<Arc<AppState>>,
154    Json(request): Json<GaiseContentEmbeddingsRequest>,
155) -> impl IntoResponse {
156    if let Err(error) = request.validate() {
157        return (StatusCode::BAD_REQUEST, error).into_response();
158    }
159    match state.client_service.embed_contents(&request).await {
160        Ok(response) => Json(response).into_response(),
161        Err(e) => {
162            error!("Embeddings error: {}", e);
163            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
164        }
165    }
166}
167
168// ── Media endpoints ────────────────────────────────────────────────
169
170/// Validation failures are the caller's (400); everything else is a
171/// provider or routing failure (500).
172fn media_error(
173    what: &str,
174    e: Box<dyn std::error::Error + Send + Sync>,
175) -> axum::response::Response {
176    error!("{what} error: {e}");
177    (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
178}
179
180/// `POST /v1/transcriptions` — `GaiseTranscriptionRequest` (audio as a
181/// `bytes` or `url` media source) to `GaiseTranscriptionResponse`.
182async fn handle_transcribe(
183    State(state): State<Arc<AppState>>,
184    Json(request): Json<GaiseTranscriptionRequest>,
185) -> impl IntoResponse {
186    if let Err(e) = request.validate() {
187        return (StatusCode::BAD_REQUEST, e).into_response();
188    }
189    match state.client_service.transcribe(&request).await {
190        Ok(response) => Json(response).into_response(),
191        Err(e) => media_error("Transcription", e),
192    }
193}
194
195/// `POST /v1/images` — generate or edit images.
196async fn handle_images(
197    State(state): State<Arc<AppState>>,
198    Json(request): Json<GaiseImageRequest>,
199) -> impl IntoResponse {
200    if let Err(e) = request.validate() {
201        return (StatusCode::BAD_REQUEST, e).into_response();
202    }
203    match state.client_service.generate_images(&request).await {
204        Ok(response) => Json(response).into_response(),
205        Err(e) => media_error("Image generation", e),
206    }
207}
208
209/// `POST /v1/videos` — start a video job; returns `202` with the job.
210async fn handle_start_video(
211    State(state): State<Arc<AppState>>,
212    Json(request): Json<GaiseVideoRequest>,
213) -> impl IntoResponse {
214    if let Err(e) = request.validate() {
215        return (StatusCode::BAD_REQUEST, e).into_response();
216    }
217    match state.client_service.start_video(&request).await {
218        Ok(job) => (StatusCode::ACCEPTED, Json(job)).into_response(),
219        Err(e) => media_error("Video generation", e),
220    }
221}
222
223/// Query for `GET /v1/videos/{id}`.
224#[derive(Debug, serde::Deserialize)]
225pub struct VideoJobQuery {
226    /// The `provider::model` the job was started with.
227    pub model: String,
228    pub correlation_id: Option<String>,
229}
230
231/// `GET /v1/videos/{id}?model=provider::model` — poll a video job. The id is
232/// the job id returned by `POST /v1/videos`, URL-encoded (Google operation
233/// names and Bedrock ARNs contain `/` and `:`).
234async fn handle_get_video(
235    State(state): State<Arc<AppState>>,
236    Path(id): Path<String>,
237    Query(query): Query<VideoJobQuery>,
238) -> impl IntoResponse {
239    let request = GaiseVideoJobRequest {
240        model: query.model,
241        id,
242        correlation_id: query.correlation_id,
243        connection: None,
244    };
245    match state.client_service.get_video(&request).await {
246        Ok(job) => Json(job).into_response(),
247        Err(e) => media_error("Video status", e),
248    }
249}
250
251/// Query parameters for `GET /v1/models`.
252#[derive(Debug, Default, serde::Deserialize)]
253pub struct ListModelsQuery {
254    /// Restrict to one provider key.
255    pub provider: Option<String>,
256    /// Keep only models supporting this operation
257    /// (`instruct`, `instruct_stream`, `embeddings`, `speech`, `live`, `decision`).
258    pub operation: Option<String>,
259    /// Fetch per-model detail where it costs extra requests (Ollama).
260    #[serde(default)]
261    pub include_details: bool,
262    /// Attach each provider's native record.
263    #[serde(default)]
264    pub include_raw: bool,
265    pub correlation_id: Option<String>,
266}
267
268impl ListModelsQuery {
269    fn into_request(self) -> Result<GaiseListModelsRequest, String> {
270        let operation = match self.operation.as_deref() {
271            None | Some("") => None,
272            Some(value) => Some(
273                GaiseOperation::parse(value)
274                    .ok_or_else(|| format!("unknown operation '{value}'"))?,
275            ),
276        };
277        Ok(GaiseListModelsRequest {
278            provider: self.provider.filter(|p| !p.is_empty()),
279            operation,
280            include_details: self.include_details,
281            include_raw: self.include_raw,
282            correlation_id: self.correlation_id,
283            connection: None,
284        })
285    }
286}
287
288async fn handle_list_models(
289    State(state): State<Arc<AppState>>,
290    Query(query): Query<ListModelsQuery>,
291) -> impl IntoResponse {
292    let request = match query.into_request() {
293        Ok(request) => request,
294        Err(message) => return (StatusCode::BAD_REQUEST, message).into_response(),
295    };
296    match state.client_service.list_models(&request).await {
297        Ok(response) => Json(response).into_response(),
298        Err(e) => {
299            error!("List models error: {}", e);
300            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
301        }
302    }
303}
304
305/// Query parameters for `GET /v1/models/limits`.
306#[derive(Debug, Default, serde::Deserialize)]
307pub struct ModelLimitsQuery {
308    /// Restrict to one provider key.
309    pub provider: Option<String>,
310    /// Keep only entries mapped to this operation.
311    pub operation: Option<String>,
312}
313
314/// `GET /v1/models/limits` — the registry's model × limits matrix
315/// (`context_window`, `max_input_tokens`, `max_output_tokens`,
316/// `embedding_dimensions`), served without contacting any provider or
317/// needing credentials. `GET /v1/models` carries the same fields per model,
318/// with provider-reported values taking precedence over the registry.
319async fn handle_model_limits(Query(query): Query<ModelLimitsQuery>) -> impl IntoResponse {
320    let operation = match query.operation.as_deref() {
321        None | Some("") => None,
322        Some(value) => match GaiseOperation::parse(value) {
323            Some(op) => Some(op),
324            None => {
325                return (
326                    StatusCode::BAD_REQUEST,
327                    format!("unknown operation '{value}'"),
328                )
329                    .into_response();
330            }
331        },
332    };
333    let provider = query.provider.filter(|p| !p.is_empty());
334    let mut matrix = registry::limits_matrix(provider.as_deref());
335    if let Some(operation) = operation {
336        matrix.models.retain(|m| m.operations.contains(&operation));
337    }
338    Json(matrix).into_response()
339}
340
341/// `GET /v1/models/{provider}::{id}` — one model from one provider's listing.
342async fn handle_get_model(
343    State(state): State<Arc<AppState>>,
344    Path(model): Path<String>,
345    Query(query): Query<ListModelsQuery>,
346) -> impl IntoResponse {
347    let Some((provider, _)) = model.split_once("::") else {
348        return (
349            StatusCode::BAD_REQUEST,
350            "model must be in the format 'provider::model'".to_string(),
351        )
352            .into_response();
353    };
354    let request = GaiseListModelsRequest {
355        provider: Some(provider.to_string()),
356        operation: None,
357        include_details: query.include_details,
358        include_raw: query.include_raw,
359        correlation_id: query.correlation_id,
360        connection: None,
361    };
362    match state.client_service.list_models(&request).await {
363        Ok(response) => match response.models.into_iter().find(|m| m.id == model) {
364            Some(found) => Json(found).into_response(),
365            None => (
366                StatusCode::NOT_FOUND,
367                format!("model '{model}' not listed by {provider}"),
368            )
369                .into_response(),
370        },
371        Err(e) => {
372            error!("Get model error: {}", e);
373            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
374        }
375    }
376}
377
378// ── Speech endpoints ───────────────────────────────────────────────
379
380/// `POST /v1/speech` — full clip as JSON (`audio` is a byte array).
381#[cfg(any(feature = "elevenlabs", feature = "xai"))]
382async fn handle_speech(
383    State(state): State<Arc<AppState>>,
384    Json(request): Json<GaiseSpeechRequest>,
385) -> impl IntoResponse {
386    match state.client_service.speech(&request).await {
387        Ok(response) => Json(response).into_response(),
388        Err(e) => {
389            error!("Speech error: {}", e);
390            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
391        }
392    }
393}
394
395/// `POST /v1/speech/stream` — SSE of `GaiseSpeechStreamResponse` (audio,
396/// alignment, usage chunks).
397#[cfg(any(feature = "elevenlabs", feature = "xai"))]
398async fn handle_speech_stream(
399    State(state): State<Arc<AppState>>,
400    Json(request): Json<GaiseSpeechRequest>,
401) -> impl IntoResponse {
402    match state.client_service.speech_stream(&request).await {
403        Ok(stream) => {
404            let sse_stream = stream.map(|item| match item {
405                Ok(chunk) => Event::default().json_data(chunk),
406                Err(e) => Ok(Event::default().event("error").data(e.to_string())),
407            });
408            Sse::new(sse_stream).into_response()
409        }
410        Err(e) => {
411            error!("Speech stream error: {}", e);
412            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
413        }
414    }
415}
416
417/// `POST /v1/speech/audio` — raw audio bytes, chunked as the provider
418/// produces them, with the MIME type in `Content-Type` and the PCM rate in
419/// `X-Gaise-Sample-Rate`. Alignment and usage chunks are dropped.
420#[cfg(any(feature = "elevenlabs", feature = "xai"))]
421async fn handle_speech_audio(
422    State(state): State<Arc<AppState>>,
423    Json(request): Json<GaiseSpeechRequest>,
424) -> impl IntoResponse {
425    use axum::body::Body;
426    use futures_util::StreamExt as _;
427
428    let mut stream = match state.client_service.speech_stream(&request).await {
429        Ok(stream) => stream,
430        Err(e) => {
431            error!("Speech audio error: {}", e);
432            return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
433        }
434    };
435    // Peek the first audio chunk so the headers can carry the real format.
436    let mut first: Option<(Vec<u8>, String, Option<u32>)> = None;
437    while let Some(item) = stream.next().await {
438        match item {
439            Ok(resp) => {
440                if let GaiseSpeechChunk::Audio {
441                    data,
442                    format,
443                    sample_rate,
444                } = resp.chunk
445                {
446                    first = Some((data, format, sample_rate));
447                    break;
448                }
449            }
450            Err(e) => {
451                error!("Speech audio error: {}", e);
452                return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
453            }
454        }
455    }
456    let Some((head, format, sample_rate)) = first else {
457        return (
458            StatusCode::BAD_GATEWAY,
459            "provider returned no audio".to_string(),
460        )
461            .into_response();
462    };
463    let rest = stream.filter_map(|item| async move {
464        match item {
465            Ok(resp) => match resp.chunk {
466                GaiseSpeechChunk::Audio { data, .. } => Some(Ok::<_, std::io::Error>(data)),
467                _ => None,
468            },
469            Err(e) => Some(Err(std::io::Error::other(e.to_string()))),
470        }
471    });
472    let body = Body::from_stream(futures_util::stream::once(async move { Ok(head) }).chain(rest));
473    let mut response = axum::response::Response::new(body);
474    response.headers_mut().insert(
475        axum::http::header::CONTENT_TYPE,
476        axum::http::HeaderValue::from_str(&format).unwrap_or(axum::http::HeaderValue::from_static(
477            "application/octet-stream",
478        )),
479    );
480    if let Some(rate) = sample_rate
481        && let Ok(value) = axum::http::HeaderValue::from_str(&rate.to_string())
482    {
483        response.headers_mut().insert("x-gaise-sample-rate", value);
484    }
485    response
486}
487
488// ── Live WebSocket endpoint ─────────────────────────────────────────
489
490#[cfg(feature = "live")]
491async fn handle_live_ws(
492    ws: WebSocketUpgrade,
493    State(state): State<Arc<AppState>>,
494) -> impl IntoResponse {
495    ws.on_upgrade(move |socket| handle_live_session(socket, state))
496}
497
498#[cfg(feature = "live")]
499async fn handle_live_session(socket: WebSocket, state: Arc<AppState>) {
500    use futures_util::SinkExt;
501
502    let (mut ws_sink, mut ws_source) = socket.split();
503
504    // First message must be a config message
505    let config: GaiseLiveConfig = loop {
506        match ws_source.next().await {
507            Some(Ok(Message::Text(text))) => match serde_json::from_str::<GaiseLiveConfig>(&text) {
508                Ok(cfg) => break cfg,
509                Err(e) => {
510                    let err = serde_json::json!({"type": "error", "message": format!("Invalid config: {}", e)});
511                    let _ = ws_sink.send(Message::Text(err.to_string())).await;
512                    return;
513                }
514            },
515            Some(Ok(Message::Close(_))) | None => return,
516            _ => continue,
517        }
518    };
519
520    // Connect to provider
521    let session = match state.client_service.live_connect(&config).await {
522        Ok(s) => s,
523        Err(e) => {
524            let err =
525                serde_json::json!({"type": "error", "message": format!("Connect error: {}", e)});
526            let _ = ws_sink.send(Message::Text(err.to_string())).await;
527            return;
528        }
529    };
530
531    let input_tx = session.tx;
532    let mut event_rx = session.rx;
533
534    // Forward provider events → client WebSocket
535    let send_handle = tokio::spawn(async move {
536        while let Some(event) = event_rx.next().await {
537            let msg = match event {
538                Ok(GaiseLiveEvent::Audio { data, sample_rate }) => {
539                    // Send audio as binary frames
540                    // Prepend 4-byte sample rate header for client to know the rate
541                    let mut frame = Vec::with_capacity(4 + data.len());
542                    frame.extend_from_slice(&sample_rate.to_le_bytes());
543                    frame.extend_from_slice(&data);
544                    Message::Binary(frame)
545                }
546                Ok(event) => match serde_json::to_string(&event) {
547                    Ok(json) => Message::Text(json),
548                    Err(_) => continue,
549                },
550                Err(e) => {
551                    let err = serde_json::json!({"type": "error", "message": e.to_string()});
552                    Message::Text(err.to_string())
553                }
554            };
555            if ws_sink.send(msg).await.is_err() {
556                break;
557            }
558        }
559    });
560
561    // Forward client WebSocket → provider input channel
562    while let Some(msg) = ws_source.next().await {
563        let msg = match msg {
564            Ok(m) => m,
565            Err(_) => break,
566        };
567
568        let input = match msg {
569            Message::Text(text) => match serde_json::from_str::<GaiseLiveInput>(&text) {
570                Ok(input) => input,
571                Err(_) => continue,
572            },
573            Message::Binary(data) => {
574                // Binary frames are raw PCM audio (16kHz PCM16 by default)
575                GaiseLiveInput::Audio {
576                    data: data.to_vec(),
577                    sample_rate: 16000,
578                }
579            }
580            Message::Close(_) => {
581                let _ = input_tx.send(GaiseLiveInput::Close).await;
582                break;
583            }
584            _ => continue,
585        };
586
587        if input_tx.send(input).await.is_err() {
588            break;
589        }
590    }
591
592    // Cleanup
593    let _ = input_tx.send(GaiseLiveInput::Close).await;
594    send_handle.abort();
595}
596
597// ── Streaming transcription WebSocket ──────────────────────────────
598
599#[cfg(feature = "live")]
600async fn handle_transcription_ws(
601    ws: WebSocketUpgrade,
602    State(state): State<Arc<AppState>>,
603) -> impl IntoResponse {
604    ws.on_upgrade(move |socket| handle_transcription_session(socket, state))
605}
606
607/// First text frame: `GaiseTranscriptionSessionConfig`. Then binary frames
608/// are audio in the configured format, and text frames are
609/// `GaiseTranscriptionInput` (`commit`, `close`). Every event goes back as a
610/// JSON text frame.
611#[cfg(feature = "live")]
612async fn handle_transcription_session(socket: WebSocket, state: Arc<AppState>) {
613    use futures_util::SinkExt;
614    use gaise_core::contracts::{GaiseTranscriptionInput, GaiseTranscriptionSessionConfig};
615
616    let (mut ws_sink, mut ws_source) = socket.split();
617    let config: GaiseTranscriptionSessionConfig = loop {
618        match ws_source.next().await {
619            Some(Ok(Message::Text(text))) => match serde_json::from_str(&text) {
620                Ok(cfg) => break cfg,
621                Err(e) => {
622                    let err = serde_json::json!({"type": "error", "message": format!("Invalid config: {e}")});
623                    let _ = ws_sink.send(Message::Text(err.to_string())).await;
624                    return;
625                }
626            },
627            Some(Ok(Message::Close(_))) | None => return,
628            _ => continue,
629        }
630    };
631
632    let session = match state.client_service.transcribe_connect(&config).await {
633        Ok(s) => s,
634        Err(e) => {
635            let err =
636                serde_json::json!({"type": "error", "message": format!("Connect error: {e}")});
637            let _ = ws_sink.send(Message::Text(err.to_string())).await;
638            return;
639        }
640    };
641    let input_tx = session.tx;
642    let mut event_rx = session.rx;
643
644    let send_handle = tokio::spawn(async move {
645        while let Some(event) = event_rx.next().await {
646            let text = match event {
647                Ok(event) => match serde_json::to_string(&event) {
648                    Ok(json) => json,
649                    Err(_) => continue,
650                },
651                Err(e) => {
652                    serde_json::json!({"type": "error", "message": e.to_string()}).to_string()
653                }
654            };
655            if ws_sink.send(Message::Text(text)).await.is_err() {
656                break;
657            }
658        }
659    });
660
661    while let Some(Ok(msg)) = ws_source.next().await {
662        let input = match msg {
663            Message::Binary(data) => GaiseTranscriptionInput::Audio {
664                data: data.to_vec(),
665            },
666            Message::Text(text) => match serde_json::from_str::<GaiseTranscriptionInput>(&text) {
667                Ok(input) => input,
668                Err(_) => continue,
669            },
670            Message::Close(_) => break,
671            _ => continue,
672        };
673        if input_tx.send(input).await.is_err() {
674            break;
675        }
676    }
677    let _ = input_tx.send(GaiseTranscriptionInput::Close).await;
678    // Let the provider deliver the final transcript before tearing down.
679    let _ = tokio::time::timeout(std::time::Duration::from_secs(10), send_handle).await;
680}