use super::config::MuseConfig;
use adk_core::{AdkError, ErrorComponent};
use reqwest::Client;
use serde::Deserialize;
#[derive(Debug, Clone, Deserialize)]
pub struct FileObject {
pub id: String,
#[serde(default)]
pub filename: Option<String>,
#[serde(default)]
pub bytes: Option<u64>,
#[serde(default)]
pub purpose: Option<String>,
#[serde(default)]
pub created_at: Option<u64>,
}
#[derive(Debug, Clone, Deserialize)]
struct FileList {
#[serde(default)]
data: Vec<FileObject>,
}
pub struct MuseFilesClient {
client: Client,
config: MuseConfig,
}
impl MuseFilesClient {
pub fn new(config: MuseConfig) -> Result<Self, AdkError> {
let client = crate::HttpTimeouts::default()
.apply(Client::builder())
.build()
.map_err(|e| AdkError::model(format!("Failed to create HTTP client: {e}")))?;
Ok(Self { client, config })
}
pub async fn upload(
&self,
bytes: Vec<u8>,
filename: impl Into<String>,
content_type: &str,
purpose: impl Into<String>,
) -> Result<FileObject, AdkError> {
let part = reqwest::multipart::Part::bytes(bytes)
.file_name(filename.into())
.mime_str(content_type)
.map_err(|e| AdkError::model(format!("invalid file content type: {e}")))?;
let form =
reqwest::multipart::Form::new().text("purpose", purpose.into()).part("file", part);
let response = self
.client
.post(format!("{}/files", self.base()))
.header("Authorization", self.auth())
.multipart(form)
.send()
.await
.map_err(|e| self.transport(e))?;
self.read_json(response).await
}
pub async fn list(&self) -> Result<Vec<FileObject>, AdkError> {
let response = self
.client
.get(format!("{}/files", self.base()))
.header("Authorization", self.auth())
.send()
.await
.map_err(|e| self.transport(e))?;
let list: FileList = self.read_json(response).await?;
Ok(list.data)
}
pub async fn get(&self, file_id: &str) -> Result<FileObject, AdkError> {
let response = self
.client
.get(format!("{}/files/{file_id}", self.base()))
.header("Authorization", self.auth())
.send()
.await
.map_err(|e| self.transport(e))?;
self.read_json(response).await
}
pub async fn content(&self, file_id: &str) -> Result<Vec<u8>, AdkError> {
let response = self
.client
.get(format!("{}/files/{file_id}/content", self.base()))
.header("Authorization", self.auth())
.send()
.await
.map_err(|e| self.transport(e))?;
if !response.status().is_success() {
return Err(self.api_error(response).await);
}
response
.bytes()
.await
.map(|bytes| bytes.to_vec())
.map_err(|e| AdkError::model(format!("Failed to read file content: {e}")))
}
pub async fn delete(&self, file_id: &str) -> Result<(), AdkError> {
let response = self
.client
.delete(format!("{}/files/{file_id}", self.base()))
.header("Authorization", self.auth())
.send()
.await
.map_err(|e| self.transport(e))?;
if !response.status().is_success() {
return Err(self.api_error(response).await);
}
Ok(())
}
fn base(&self) -> String {
self.config.effective_base_url().trim_end_matches('/').to_string()
}
fn auth(&self) -> String {
format!("Bearer {}", self.config.api_key)
}
fn transport(&self, error: reqwest::Error) -> AdkError {
AdkError::new(
ErrorComponent::Model,
crate::http_timeouts::transport_category(&error),
"model.muse.request",
format!("Muse files request failed: {error}"),
)
.with_provider("muse")
}
async fn api_error(&self, response: reqwest::Response) -> AdkError {
let status = response.status();
let status_code = status.as_u16();
let error_text = response.text().await.unwrap_or_default();
AdkError::new(
ErrorComponent::Model,
crate::retry::category_for_status_code(status_code),
"model.muse.api_error",
format!(
"Muse files API error (HTTP {status}): {}",
adk_core::upstream_excerpt(&error_text)
),
)
.with_upstream_status(status_code)
.with_provider("muse")
}
async fn read_json<T: serde::de::DeserializeOwned>(
&self,
response: reqwest::Response,
) -> Result<T, AdkError> {
if !response.status().is_success() {
return Err(self.api_error(response).await);
}
let text = response
.text()
.await
.map_err(|e| AdkError::model(format!("Failed to read files response: {e}")))?;
serde_json::from_str(&text).map_err(|e| {
AdkError::model(format!(
"Failed to parse files response: {}",
adk_core::json_error_summary(&e)
))
})
}
}