use crate::utils::error::gateway_error::{GatewayError, Result};
use futures::stream::{BoxStream, StreamExt};
#[inline]
fn bytes_to_utf8_string(bytes: &[u8]) -> std::result::Result<String, std::str::Utf8Error> {
std::str::from_utf8(bytes).map(|s| s.to_owned())
}
pub struct OpenAIStreaming;
impl OpenAIStreaming {
pub fn create_stream(response: reqwest::Response) -> BoxStream<'static, Result<String>> {
let stream = response.bytes_stream().map(|chunk_result| {
chunk_result
.map_err(|e| GatewayError::Network(e.to_string()))
.and_then(|chunk| {
bytes_to_utf8_string(&chunk)
.map_err(|e| GatewayError::Validation(e.to_string()))
})
});
Box::pin(stream)
}
}
pub struct AnthropicStreaming;
impl AnthropicStreaming {
pub fn create_stream(response: reqwest::Response) -> BoxStream<'static, Result<String>> {
let stream = response.bytes_stream().map(|chunk_result| {
chunk_result
.map_err(|e| GatewayError::network(e.to_string()))
.and_then(|chunk| {
bytes_to_utf8_string(&chunk)
.map_err(|e| GatewayError::internal(format!("Parsing error: {}", e)))
})
});
Box::pin(stream)
}
}
pub struct GenericStreaming;
impl GenericStreaming {
pub fn create_stream(response: reqwest::Response) -> BoxStream<'static, Result<String>> {
let stream = response.bytes_stream().map(|chunk_result| {
chunk_result
.map_err(|e| GatewayError::network(e.to_string()))
.and_then(|chunk| {
bytes_to_utf8_string(&chunk)
.map_err(|e| GatewayError::internal(format!("Parsing error: {}", e)))
})
});
Box::pin(stream)
}
}