Skip to content

Commit 8dc0795

Browse files
committed
refactor: improve structure
1 parent 9faea7a commit 8dc0795

File tree

3 files changed

+26
-14
lines changed

3 files changed

+26
-14
lines changed

crates/provider_openai/src/speech.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ pub async fn handle(
5858

5959
let mut headers = HeaderMap::new();
6060
// TODO: remove unwrap
61-
headers.insert(header::CONTENT_TYPE, "audio/mpeg".parse().unwrap());
61+
headers.insert(header::CONTENT_TYPE, "audio/mpeg".parse()?);
6262

6363
Ok((headers, bytes))
6464
}

crates/shared/src/speech.rs

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
use std::collections::HashMap;
22

3+
use axum::http::StatusCode;
34
use serde::{Deserialize, Serialize};
45
use serde_json::Value;
56

7+
use crate::AppError;
8+
69
#[derive(Deserialize)]
710
// https://platform.openai.com/docs/api-reference/audio/createSpeech
811
pub struct SpeechOptions {
@@ -42,17 +45,26 @@ pub struct ProcessedSpeechOptions {
4245
pub provider: String,
4346
}
4447

45-
pub fn process_speech_options(options: SpeechOptions) -> ProcessedSpeechOptions {
46-
let vec: Vec<&str> = options.model.split('/').collect();
47-
48-
ProcessedSpeechOptions {
49-
input: options.input,
50-
model: vec[1].to_string(),
51-
voice: options.voice,
52-
instructions: options.instructions,
53-
response_format: options.response_format,
54-
speed: options.speed,
55-
extra: options.extra,
56-
provider: vec[0].to_string(),
48+
pub fn process_speech_options(options: SpeechOptions) -> Result<ProcessedSpeechOptions, AppError> {
49+
match options.model.split_once('/') {
50+
Some((provider, model)) => {
51+
if provider.is_empty() || model.is_empty() {
52+
Err(AppError::new(anyhow::anyhow!("Invalid model: {}", options.model), Some(StatusCode::BAD_REQUEST)))
53+
} else {
54+
Ok(ProcessedSpeechOptions {
55+
input: options.input,
56+
model: model.to_string(),
57+
voice: options.voice,
58+
instructions: options.instructions,
59+
response_format: options.response_format,
60+
speed: options.speed,
61+
extra: options.extra,
62+
provider: provider.to_string(),
63+
})
64+
}
65+
}
66+
None => {
67+
Err(AppError::new(anyhow::anyhow!("Invalid model: {}", options.model), Some(StatusCode::BAD_REQUEST)))
68+
}
5769
}
5870
}

src/speech.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ pub async fn speech(
2020
TypedHeader(bearer): TypedHeader<Authorization<Bearer>>,
2121
Json(body): Json<SpeechOptions>,
2222
) -> Result<(HeaderMap, Bytes), AppError> {
23-
let options = process_speech_options(body);
23+
let options = process_speech_options(body)?;
2424
let token = bearer.token();
2525

2626
match options.provider.as_str() {

0 commit comments

Comments
 (0)