use std::fmt;
use std::path::{Path, PathBuf};
use base64::Engine;
use bytes::Bytes;
use futures_util::Stream;
use reqwest::Method;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use crate::client::{json_body, Request, RequestOptions, Wellfriend};
use crate::download::Download;
use crate::error::{Error, Result};
use crate::file_input::{FileInput, ToolInput};
use crate::generated::tools::{tool_spec, ToolId};
use crate::models::{Operation, OperationOutputs, Output, WorkflowRun};
use crate::operations;
use crate::uploads;
use crate::Object;
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ToolParameters(Object);
impl ToolParameters {
pub fn new() -> Self {
Self::default()
}
pub fn set(mut self, name: impl Into<String>, value: impl Into<Value>) -> Self {
self.0.insert(name.into(), value.into());
self
}
pub fn as_object(&self) -> &Object {
&self.0
}
pub fn into_object(self) -> Object {
self.0
}
pub fn from_serialize<P: Serialize>(params: &P) -> Result<Self> {
match serde_json::to_value(params)
.map_err(|error| Error::InvalidInput(error.to_string()))?
{
Value::Object(map) => Ok(ToolParameters(map)),
Value::Null => Ok(ToolParameters::default()),
other => Err(Error::InvalidInput(format!(
"tool parameters must be an object, got {other}"
))),
}
}
}
impl From<Object> for ToolParameters {
fn from(map: Object) -> Self {
ToolParameters(map)
}
}
#[derive(Debug)]
pub enum Asset {
File(FileInput),
Inline {
content: Bytes,
file_name: String,
},
}
impl Asset {
pub fn file(input: impl Into<FileInput>) -> Self {
Asset::File(input.into())
}
pub fn inline(content: impl Into<Bytes>, file_name: impl Into<String>) -> Self {
Asset::Inline {
content: content.into(),
file_name: file_name.into(),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolUsage {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub request_units: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub credits: Option<i64>,
#[serde(flatten)]
pub extra: Object,
}
#[derive(Clone, Debug)]
pub struct Tools {
pub(crate) client: Wellfriend,
pub(crate) options: RequestOptions,
}
impl Wellfriend {
pub fn tools(&self) -> Tools {
Tools {
client: self.clone(),
options: RequestOptions::default(),
}
}
}
impl Tools {
pub fn with_options(mut self, options: RequestOptions) -> Self {
self.options = options;
self
}
pub async fn run(
&self,
tool: impl Into<ToolId>,
input: impl Into<ToolInput>,
params: Option<ToolParameters>,
) -> Result<ToolResult> {
self.request(tool)
.input(input)
.params(params.unwrap_or_default())
.run()
.await
}
pub async fn start(
&self,
tool: impl Into<ToolId>,
input: impl Into<ToolInput>,
params: Option<ToolParameters>,
) -> Result<Operation> {
self.request(tool)
.input(input)
.params(params.unwrap_or_default())
.start()
.await
}
pub fn request(&self, tool: impl Into<ToolId>) -> ToolRequest {
ToolRequest {
tools: self.clone(),
tool: tool.into(),
input: ToolInput::default(),
parameters: ToolParameters::default(),
assets: Vec::new(),
}
}
pub(crate) async fn run_typed<P: Serialize>(
&self,
tool: ToolId,
input: ToolInput,
params: Option<&P>,
) -> Result<ToolResult> {
let parameters = match params {
Some(params) => ToolParameters::from_serialize(params)?,
None => ToolParameters::default(),
};
ToolRequest {
tools: self.clone(),
tool,
input,
parameters,
assets: Vec::new(),
}
.run()
.await
}
}
#[derive(Debug)]
pub struct ToolRequest {
tools: Tools,
tool: ToolId,
input: ToolInput,
parameters: ToolParameters,
assets: Vec<(String, Asset)>,
}
impl ToolRequest {
pub fn input(mut self, input: impl Into<ToolInput>) -> Self {
self.input = input.into();
self
}
pub fn params(mut self, params: impl Into<ToolParameters>) -> Self {
self.parameters = params.into();
self
}
pub fn asset(mut self, name: impl Into<String>, asset: Asset) -> Self {
self.assets.push((name.into(), asset));
self
}
pub async fn run(self) -> Result<ToolResult> {
let tools = self.tools.clone();
let stem = self.input.files.first().and_then(FileInput::stem);
let operation = self.start().await?;
let operation =
operations::wait_operation(&tools.client, &tools.options, &operation.id).await?;
ToolResult::from_operation(&tools.client, &tools.options, operation, stem).await
}
pub async fn start(self) -> Result<Operation> {
let ToolRequest {
tools,
tool,
input,
parameters,
assets,
} = self;
let client = &tools.client;
let options = &tools.options;
if let Some(spec) = tool_spec(tool.as_str()) {
let count = input.files.len();
if count < spec.min_files || count > spec.max_files {
let wanted = if spec.min_files == spec.max_files {
format!("{}", spec.min_files)
} else {
format!("{} to {}", spec.min_files, spec.max_files)
};
return Err(Error::InvalidInput(format!(
"{tool} takes {wanted} input files, got {count}"
)));
}
} else if input.files.is_empty() {
return Err(Error::InvalidInput(format!("{tool} needs an input file")));
}
let mut stored = Vec::with_capacity(input.files.len());
for (index, file) in input.files.into_iter().enumerate() {
let key = options.derived_key(&format!("upload{index}"));
stored.push(
uploads::ensure_stored(client, options, file, key)
.await?
.reference,
);
}
let mut asset_map = Object::new();
for (name, asset) in assets {
let value = match asset {
Asset::File(file) => {
let key = options.derived_key(&format!("asset-{name}"));
let reference = uploads::ensure_stored(client, options, file, key)
.await?
.reference;
serde_json::to_value(reference)
.map_err(|error| Error::InvalidInput(error.to_string()))?
}
Asset::Inline { content, file_name } => {
json!({ "content": base64::engine::general_purpose::STANDARD.encode(&content), "fileName": file_name })
}
};
asset_map.insert(name, value);
}
let mut stored = stored.into_iter();
let first = stored
.next()
.ok_or_else(|| Error::InvalidInput(format!("{tool} needs an input file")))?;
let mut body = json!({ "toolId": tool.as_str(), "documentId": first.document_id, "parameters": parameters.into_object() });
if let Some(version) = first.version_id {
body["versionId"] = json!(version);
}
let rest: Vec<_> = stored.collect();
if !rest.is_empty() {
body["inputs"] = serde_json::to_value(rest)
.map_err(|error| Error::InvalidInput(error.to_string()))?;
}
if !asset_map.is_empty() {
body["assets"] = Value::Object(asset_map);
}
let key = options.key();
let request = Request::new(Method::POST, ["document-operations"])
.json(json_body(&body, Some(&key))?)
.idempotency_key(key);
client.json_field(options, request, "operation").await
}
}
#[non_exhaustive]
pub struct ToolResult {
client: Wellfriend,
options: RequestOptions,
stem: Option<String>,
pub operation: Operation,
pub outputs: Vec<Output>,
pub usage: Option<ToolUsage>,
pub run: Option<WorkflowRun>,
}
impl fmt::Debug for ToolResult {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ToolResult")
.field("operation", &self.operation)
.field("outputs", &self.outputs)
.field("usage", &self.usage)
.field("run", &self.run.as_ref().map(|run| &run.id))
.finish_non_exhaustive()
}
}
impl ToolResult {
pub(crate) async fn from_operation(
client: &Wellfriend,
options: &RequestOptions,
operation: Operation,
stem: Option<String>,
) -> Result<ToolResult> {
let reads = options.without_key();
let request = Request::new(
Method::GET,
["document-operations", operation.id.as_str(), "outputs"],
);
let outputs = match client.json::<OperationOutputs>(&reads, request).await {
Ok(listed) if !listed.outputs.is_empty() => listed.outputs,
Ok(_) | Err(Error::NotFound(_)) => fallback_outputs(&operation),
Err(error) => return Err(error),
};
let usage = operation
.extra
.get("usage")
.and_then(|value| serde_json::from_value(value.clone()).ok());
Ok(ToolResult {
client: client.clone(),
options: reads,
stem,
operation,
outputs,
usage,
run: None,
})
}
pub(crate) fn with_run(mut self, run: WorkflowRun) -> Self {
self.run = Some(run);
self
}
pub fn output(&self) -> Option<&Output> {
self.outputs
.iter()
.find(|output| output.document_id.is_some())
}
pub async fn download(&self) -> Result<Download> {
let output = self.output().ok_or_else(|| {
Error::Decode(format!(
"operation {} has no stored output",
self.operation.id
))
})?;
self.download_output(output).await
}
pub async fn download_output(&self, output: &Output) -> Result<Download> {
let (Some(document), Some(version)) = (&output.document_id, &output.version_id) else {
return Err(Error::InvalidInput(format!(
"output {} has not been stored as a document",
output.index
)));
};
let request = Request::new(
Method::GET,
[
"documents",
document.as_str(),
"versions",
version.as_str(),
"content",
],
);
Ok(Download::new(
self.client.send(&self.options, request).await?,
))
}
pub async fn save(&self, path: impl AsRef<Path>) -> Result<Vec<PathBuf>> {
let path = path.as_ref();
let is_dir = tokio::fs::metadata(path)
.await
.map(|meta| meta.is_dir())
.unwrap_or(false);
if !is_dir {
self.download().await?.save(path).await?;
return Ok(vec![path.to_path_buf()]);
}
let mut written = Vec::new();
for output in self
.outputs
.iter()
.filter(|output| output.document_id.is_some())
{
let target = path.join(self.file_name_for(output));
self.download_output(output).await?.save(&target).await?;
written.push(target);
}
Ok(written)
}
pub async fn bytes(&self) -> Result<Bytes> {
self.download().await?.bytes().await
}
pub async fn stream(&self) -> Result<impl Stream<Item = Result<Bytes>> + Send + 'static> {
Ok(self.download().await?.bytes_stream())
}
fn file_name_for(&self, output: &Output) -> String {
if let Some(name) = crate::util::safe_file_name(&output.filename) {
return name;
}
let extension = tool_spec(self.operation.tool_id.as_str())
.map(|spec| spec.output_extension.to_owned())
.unwrap_or_else(|| crate::util::extension_for(&output.content_type).to_owned());
let stem = self.stem.clone().unwrap_or_else(|| "output".into());
format!(
"{stem}-{}-{}.{extension}",
self.operation.tool_id, output.index
)
}
}
fn fallback_outputs(operation: &Operation) -> Vec<Output> {
match &operation.output_document_id {
Some(document) => vec![Output {
index: 0,
document_id: Some(document.clone()),
version_id: operation.output_version_id.clone(),
filename: operation.output_file_name().unwrap_or_default().to_owned(),
content_type: operation
.result
.get("mimeType")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned(),
size_bytes: operation.result.get("sizeBytes").and_then(Value::as_u64),
extra: Object::new(),
}],
None => Vec::new(),
}
}