1use std::fmt;
4use std::path::{Path, PathBuf};
5
6use base64::Engine;
7use bytes::Bytes;
8use futures_util::Stream;
9use reqwest::Method;
10use serde::{Deserialize, Serialize};
11use serde_json::{json, Value};
12
13use crate::client::{json_body, Request, RequestOptions, Wellfriend};
14use crate::download::Download;
15use crate::error::{Error, Result};
16use crate::file_input::{FileInput, ToolInput};
17use crate::generated::tools::{tool_spec, ToolId};
18use crate::models::{Operation, OperationOutputs, Output, WorkflowRun};
19use crate::operations;
20use crate::uploads;
21use crate::Object;
22
23#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
33#[serde(transparent)]
34pub struct ToolParameters(Object);
35
36impl ToolParameters {
37 pub fn new() -> Self {
39 Self::default()
40 }
41
42 pub fn set(mut self, name: impl Into<String>, value: impl Into<Value>) -> Self {
44 self.0.insert(name.into(), value.into());
45 self
46 }
47
48 pub fn as_object(&self) -> &Object {
50 &self.0
51 }
52
53 pub fn into_object(self) -> Object {
55 self.0
56 }
57
58 pub fn from_serialize<P: Serialize>(params: &P) -> Result<Self> {
60 match serde_json::to_value(params)
61 .map_err(|error| Error::InvalidInput(error.to_string()))?
62 {
63 Value::Object(map) => Ok(ToolParameters(map)),
64 Value::Null => Ok(ToolParameters::default()),
65 other => Err(Error::InvalidInput(format!(
66 "tool parameters must be an object, got {other}"
67 ))),
68 }
69 }
70}
71
72impl From<Object> for ToolParameters {
73 fn from(map: Object) -> Self {
74 ToolParameters(map)
75 }
76}
77
78#[derive(Debug)]
80pub enum Asset {
81 File(FileInput),
83 Inline {
86 content: Bytes,
88 file_name: String,
90 },
91}
92
93impl Asset {
94 pub fn file(input: impl Into<FileInput>) -> Self {
96 Asset::File(input.into())
97 }
98
99 pub fn inline(content: impl Into<Bytes>, file_name: impl Into<String>) -> Self {
101 Asset::Inline {
102 content: content.into(),
103 file_name: file_name.into(),
104 }
105 }
106}
107
108#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
110#[serde(rename_all = "camelCase")]
111pub struct ToolUsage {
112 #[serde(default, skip_serializing_if = "Option::is_none")]
114 pub request_units: Option<i64>,
115 #[serde(default, skip_serializing_if = "Option::is_none")]
117 pub credits: Option<i64>,
118 #[serde(flatten)]
120 pub extra: Object,
121}
122
123#[derive(Clone, Debug)]
139pub struct Tools {
140 pub(crate) client: Wellfriend,
141 pub(crate) options: RequestOptions,
142}
143
144impl Wellfriend {
145 pub fn tools(&self) -> Tools {
147 Tools {
148 client: self.clone(),
149 options: RequestOptions::default(),
150 }
151 }
152}
153
154impl Tools {
155 pub fn with_options(mut self, options: RequestOptions) -> Self {
157 self.options = options;
158 self
159 }
160
161 pub async fn run(
173 &self,
174 tool: impl Into<ToolId>,
175 input: impl Into<ToolInput>,
176 params: Option<ToolParameters>,
177 ) -> Result<ToolResult> {
178 self.request(tool)
179 .input(input)
180 .params(params.unwrap_or_default())
181 .run()
182 .await
183 }
184
185 pub async fn start(
188 &self,
189 tool: impl Into<ToolId>,
190 input: impl Into<ToolInput>,
191 params: Option<ToolParameters>,
192 ) -> Result<Operation> {
193 self.request(tool)
194 .input(input)
195 .params(params.unwrap_or_default())
196 .start()
197 .await
198 }
199
200 pub fn request(&self, tool: impl Into<ToolId>) -> ToolRequest {
202 ToolRequest {
203 tools: self.clone(),
204 tool: tool.into(),
205 input: ToolInput::default(),
206 parameters: ToolParameters::default(),
207 assets: Vec::new(),
208 }
209 }
210
211 pub(crate) async fn run_typed<P: Serialize>(
212 &self,
213 tool: ToolId,
214 input: ToolInput,
215 params: Option<&P>,
216 ) -> Result<ToolResult> {
217 let parameters = match params {
218 Some(params) => ToolParameters::from_serialize(params)?,
219 None => ToolParameters::default(),
220 };
221 ToolRequest {
222 tools: self.clone(),
223 tool,
224 input,
225 parameters,
226 assets: Vec::new(),
227 }
228 .run()
229 .await
230 }
231}
232
233#[derive(Debug)]
252pub struct ToolRequest {
253 tools: Tools,
254 tool: ToolId,
255 input: ToolInput,
256 parameters: ToolParameters,
257 assets: Vec<(String, Asset)>,
258}
259
260impl ToolRequest {
261 pub fn input(mut self, input: impl Into<ToolInput>) -> Self {
263 self.input = input.into();
264 self
265 }
266
267 pub fn params(mut self, params: impl Into<ToolParameters>) -> Self {
269 self.parameters = params.into();
270 self
271 }
272
273 pub fn asset(mut self, name: impl Into<String>, asset: Asset) -> Self {
275 self.assets.push((name.into(), asset));
276 self
277 }
278
279 pub async fn run(self) -> Result<ToolResult> {
281 let tools = self.tools.clone();
282 let stem = self.input.files.first().and_then(FileInput::stem);
283 let operation = self.start().await?;
284 let operation =
285 operations::wait_operation(&tools.client, &tools.options, &operation.id).await?;
286 ToolResult::from_operation(&tools.client, &tools.options, operation, stem).await
287 }
288
289 pub async fn start(self) -> Result<Operation> {
291 let ToolRequest {
292 tools,
293 tool,
294 input,
295 parameters,
296 assets,
297 } = self;
298 let client = &tools.client;
299 let options = &tools.options;
300 if let Some(spec) = tool_spec(tool.as_str()) {
301 let count = input.files.len();
302 if count < spec.min_files || count > spec.max_files {
303 let wanted = if spec.min_files == spec.max_files {
304 format!("{}", spec.min_files)
305 } else {
306 format!("{} to {}", spec.min_files, spec.max_files)
307 };
308 return Err(Error::InvalidInput(format!(
309 "{tool} takes {wanted} input files, got {count}"
310 )));
311 }
312 } else if input.files.is_empty() {
313 return Err(Error::InvalidInput(format!("{tool} needs an input file")));
314 }
315 let mut stored = Vec::with_capacity(input.files.len());
316 for (index, file) in input.files.into_iter().enumerate() {
317 let key = options.derived_key(&format!("upload{index}"));
318 stored.push(
319 uploads::ensure_stored(client, options, file, key)
320 .await?
321 .reference,
322 );
323 }
324 let mut asset_map = Object::new();
325 for (name, asset) in assets {
326 let value = match asset {
327 Asset::File(file) => {
328 let key = options.derived_key(&format!("asset-{name}"));
329 let reference = uploads::ensure_stored(client, options, file, key)
330 .await?
331 .reference;
332 serde_json::to_value(reference)
333 .map_err(|error| Error::InvalidInput(error.to_string()))?
334 }
335 Asset::Inline { content, file_name } => {
336 json!({ "content": base64::engine::general_purpose::STANDARD.encode(&content), "fileName": file_name })
337 }
338 };
339 asset_map.insert(name, value);
340 }
341 let mut stored = stored.into_iter();
342 let first = stored
343 .next()
344 .ok_or_else(|| Error::InvalidInput(format!("{tool} needs an input file")))?;
345 let mut body = json!({ "toolId": tool.as_str(), "documentId": first.document_id, "parameters": parameters.into_object() });
346 if let Some(version) = first.version_id {
347 body["versionId"] = json!(version);
348 }
349 let rest: Vec<_> = stored.collect();
350 if !rest.is_empty() {
351 body["inputs"] = serde_json::to_value(rest)
352 .map_err(|error| Error::InvalidInput(error.to_string()))?;
353 }
354 if !asset_map.is_empty() {
355 body["assets"] = Value::Object(asset_map);
356 }
357 let key = options.key();
358 let request = Request::new(Method::POST, ["document-operations"])
359 .json(json_body(&body, Some(&key))?)
360 .idempotency_key(key);
361 client.json_field(options, request, "operation").await
362 }
363}
364
365#[non_exhaustive]
378pub struct ToolResult {
379 client: Wellfriend,
380 options: RequestOptions,
381 stem: Option<String>,
382 pub operation: Operation,
384 pub outputs: Vec<Output>,
386 pub usage: Option<ToolUsage>,
388 pub run: Option<WorkflowRun>,
390}
391
392impl fmt::Debug for ToolResult {
393 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
394 f.debug_struct("ToolResult")
395 .field("operation", &self.operation)
396 .field("outputs", &self.outputs)
397 .field("usage", &self.usage)
398 .field("run", &self.run.as_ref().map(|run| &run.id))
399 .finish_non_exhaustive()
400 }
401}
402
403impl ToolResult {
404 pub(crate) async fn from_operation(
405 client: &Wellfriend,
406 options: &RequestOptions,
407 operation: Operation,
408 stem: Option<String>,
409 ) -> Result<ToolResult> {
410 let reads = options.without_key();
411 let request = Request::new(
412 Method::GET,
413 ["document-operations", operation.id.as_str(), "outputs"],
414 );
415 let outputs = match client.json::<OperationOutputs>(&reads, request).await {
416 Ok(listed) if !listed.outputs.is_empty() => listed.outputs,
417 Ok(_) | Err(Error::NotFound(_)) => fallback_outputs(&operation),
418 Err(error) => return Err(error),
419 };
420 let usage = operation
421 .extra
422 .get("usage")
423 .and_then(|value| serde_json::from_value(value.clone()).ok());
424 Ok(ToolResult {
425 client: client.clone(),
426 options: reads,
427 stem,
428 operation,
429 outputs,
430 usage,
431 run: None,
432 })
433 }
434
435 pub(crate) fn with_run(mut self, run: WorkflowRun) -> Self {
436 self.run = Some(run);
437 self
438 }
439
440 pub fn output(&self) -> Option<&Output> {
442 self.outputs
443 .iter()
444 .find(|output| output.document_id.is_some())
445 }
446
447 pub async fn download(&self) -> Result<Download> {
449 let output = self.output().ok_or_else(|| {
450 Error::Decode(format!(
451 "operation {} has no stored output",
452 self.operation.id
453 ))
454 })?;
455 self.download_output(output).await
456 }
457
458 pub async fn download_output(&self, output: &Output) -> Result<Download> {
460 let (Some(document), Some(version)) = (&output.document_id, &output.version_id) else {
461 return Err(Error::InvalidInput(format!(
462 "output {} has not been stored as a document",
463 output.index
464 )));
465 };
466 let request = Request::new(
467 Method::GET,
468 [
469 "documents",
470 document.as_str(),
471 "versions",
472 version.as_str(),
473 "content",
474 ],
475 );
476 Ok(Download::new(
477 self.client.send(&self.options, request).await?,
478 ))
479 }
480
481 pub async fn save(&self, path: impl AsRef<Path>) -> Result<Vec<PathBuf>> {
486 let path = path.as_ref();
487 let is_dir = tokio::fs::metadata(path)
488 .await
489 .map(|meta| meta.is_dir())
490 .unwrap_or(false);
491 if !is_dir {
492 self.download().await?.save(path).await?;
493 return Ok(vec![path.to_path_buf()]);
494 }
495 let mut written = Vec::new();
496 for output in self
497 .outputs
498 .iter()
499 .filter(|output| output.document_id.is_some())
500 {
501 let target = path.join(self.file_name_for(output));
502 self.download_output(output).await?.save(&target).await?;
503 written.push(target);
504 }
505 Ok(written)
506 }
507
508 pub async fn bytes(&self) -> Result<Bytes> {
511 self.download().await?.bytes().await
512 }
513
514 pub async fn stream(&self) -> Result<impl Stream<Item = Result<Bytes>> + Send + 'static> {
516 Ok(self.download().await?.bytes_stream())
517 }
518
519 fn file_name_for(&self, output: &Output) -> String {
521 if let Some(name) = crate::util::safe_file_name(&output.filename) {
522 return name;
523 }
524 let extension = tool_spec(self.operation.tool_id.as_str())
525 .map(|spec| spec.output_extension.to_owned())
526 .unwrap_or_else(|| crate::util::extension_for(&output.content_type).to_owned());
527 let stem = self.stem.clone().unwrap_or_else(|| "output".into());
528 format!(
529 "{stem}-{}-{}.{extension}",
530 self.operation.tool_id, output.index
531 )
532 }
533}
534
535fn fallback_outputs(operation: &Operation) -> Vec<Output> {
537 match &operation.output_document_id {
538 Some(document) => vec![Output {
539 index: 0,
540 document_id: Some(document.clone()),
541 version_id: operation.output_version_id.clone(),
542 filename: operation.output_file_name().unwrap_or_default().to_owned(),
543 content_type: operation
544 .result
545 .get("mimeType")
546 .and_then(Value::as_str)
547 .unwrap_or_default()
548 .to_owned(),
549 size_bytes: operation.result.get("sizeBytes").and_then(Value::as_u64),
550 extra: Object::new(),
551 }],
552 None => Vec::new(),
553 }
554}