1use super::config::MuseConfig;
8use adk_core::{AdkError, ErrorComponent};
9use reqwest::Client;
10use serde::Deserialize;
11
12#[derive(Debug, Clone, Deserialize)]
14pub struct FileObject {
15 pub id: String,
17 #[serde(default)]
19 pub filename: Option<String>,
20 #[serde(default)]
22 pub bytes: Option<u64>,
23 #[serde(default)]
25 pub purpose: Option<String>,
26 #[serde(default)]
28 pub created_at: Option<u64>,
29}
30
31#[derive(Debug, Clone, Deserialize)]
33struct FileList {
34 #[serde(default)]
35 data: Vec<FileObject>,
36}
37
38pub struct MuseFilesClient {
49 client: Client,
50 config: MuseConfig,
51}
52
53impl MuseFilesClient {
54 pub fn new(config: MuseConfig) -> Result<Self, AdkError> {
56 let client = crate::HttpTimeouts::default()
57 .apply(Client::builder())
58 .build()
59 .map_err(|e| AdkError::model(format!("Failed to create HTTP client: {e}")))?;
60 Ok(Self { client, config })
61 }
62
63 pub async fn upload(
69 &self,
70 bytes: Vec<u8>,
71 filename: impl Into<String>,
72 content_type: &str,
73 purpose: impl Into<String>,
74 ) -> Result<FileObject, AdkError> {
75 let part = reqwest::multipart::Part::bytes(bytes)
76 .file_name(filename.into())
77 .mime_str(content_type)
78 .map_err(|e| AdkError::model(format!("invalid file content type: {e}")))?;
79 let form =
80 reqwest::multipart::Form::new().text("purpose", purpose.into()).part("file", part);
81 let response = self
82 .client
83 .post(format!("{}/files", self.base()))
84 .header("Authorization", self.auth())
85 .multipart(form)
86 .send()
87 .await
88 .map_err(|e| self.transport(e))?;
89 self.read_json(response).await
90 }
91
92 pub async fn list(&self) -> Result<Vec<FileObject>, AdkError> {
98 let response = self
99 .client
100 .get(format!("{}/files", self.base()))
101 .header("Authorization", self.auth())
102 .send()
103 .await
104 .map_err(|e| self.transport(e))?;
105 let list: FileList = self.read_json(response).await?;
106 Ok(list.data)
107 }
108
109 pub async fn get(&self, file_id: &str) -> Result<FileObject, AdkError> {
115 let response = self
116 .client
117 .get(format!("{}/files/{file_id}", self.base()))
118 .header("Authorization", self.auth())
119 .send()
120 .await
121 .map_err(|e| self.transport(e))?;
122 self.read_json(response).await
123 }
124
125 pub async fn content(&self, file_id: &str) -> Result<Vec<u8>, AdkError> {
131 let response = self
132 .client
133 .get(format!("{}/files/{file_id}/content", self.base()))
134 .header("Authorization", self.auth())
135 .send()
136 .await
137 .map_err(|e| self.transport(e))?;
138 if !response.status().is_success() {
139 return Err(self.api_error(response).await);
140 }
141 response
142 .bytes()
143 .await
144 .map(|bytes| bytes.to_vec())
145 .map_err(|e| AdkError::model(format!("Failed to read file content: {e}")))
146 }
147
148 pub async fn delete(&self, file_id: &str) -> Result<(), AdkError> {
154 let response = self
155 .client
156 .delete(format!("{}/files/{file_id}", self.base()))
157 .header("Authorization", self.auth())
158 .send()
159 .await
160 .map_err(|e| self.transport(e))?;
161 if !response.status().is_success() {
162 return Err(self.api_error(response).await);
163 }
164 Ok(())
165 }
166
167 fn base(&self) -> String {
168 self.config.effective_base_url().trim_end_matches('/').to_string()
169 }
170
171 fn auth(&self) -> String {
172 format!("Bearer {}", self.config.api_key)
173 }
174
175 fn transport(&self, error: reqwest::Error) -> AdkError {
176 AdkError::new(
177 ErrorComponent::Model,
178 crate::http_timeouts::transport_category(&error),
179 "model.muse.request",
180 format!("Muse files request failed: {error}"),
181 )
182 .with_provider("muse")
183 }
184
185 async fn api_error(&self, response: reqwest::Response) -> AdkError {
186 let status = response.status();
187 let status_code = status.as_u16();
188 let error_text = response.text().await.unwrap_or_default();
189 AdkError::new(
190 ErrorComponent::Model,
191 crate::retry::category_for_status_code(status_code),
192 "model.muse.api_error",
193 format!(
194 "Muse files API error (HTTP {status}): {}",
195 adk_core::upstream_excerpt(&error_text)
196 ),
197 )
198 .with_upstream_status(status_code)
199 .with_provider("muse")
200 }
201
202 async fn read_json<T: serde::de::DeserializeOwned>(
203 &self,
204 response: reqwest::Response,
205 ) -> Result<T, AdkError> {
206 if !response.status().is_success() {
207 return Err(self.api_error(response).await);
208 }
209 let text = response
210 .text()
211 .await
212 .map_err(|e| AdkError::model(format!("Failed to read files response: {e}")))?;
213 serde_json::from_str(&text).map_err(|e| {
214 AdkError::model(format!(
215 "Failed to parse files response: {}",
216 adk_core::json_error_summary(&e)
217 ))
218 })
219 }
220}