use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum WorkflowTimeoutPolicy {
#[default]
TimeOutWf,
AlertOnly,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TaskType {
#[default]
Simple,
Dynamic,
ForkJoin,
ForkJoinDynamic,
Decision,
Switch,
Join,
DoWhile,
SubWorkflow,
Event,
Wait,
Human,
UserDefined,
Http,
#[serde(rename = "HTTP_POLL")]
HttpPoll,
Lambda,
Inline,
ExclusiveJoin,
Terminate,
KafkaPublish,
JsonJqTransform,
SetVariable,
StartWorkflow,
#[serde(rename = "WAIT_FOR_WEBHOOK")]
WaitForWebhook,
#[serde(rename = "LLM_TEXT_COMPLETE")]
LlmTextComplete,
#[serde(rename = "LLM_CHAT_COMPLETE")]
LlmChatComplete,
#[serde(rename = "LLM_GENERATE_EMBEDDINGS")]
LlmGenerateEmbeddings,
#[serde(rename = "LLM_INDEX_TEXT")]
LlmIndexText,
#[serde(rename = "LLM_INDEX_DOCUMENT")]
LlmIndexDocument,
#[serde(rename = "LLM_SEARCH_INDEX")]
LlmSearchIndex,
#[serde(rename = "LLM_GET_EMBEDDINGS")]
LlmGetEmbeddings,
#[serde(rename = "LLM_STORE_EMBEDDINGS")]
LlmStoreEmbeddings,
#[serde(rename = "LLM_SEARCH_EMBEDDINGS")]
LlmSearchEmbeddings,
#[serde(rename = "GENERATE_IMAGE")]
GenerateImage,
#[serde(rename = "GENERATE_AUDIO")]
GenerateAudio,
#[serde(rename = "LIST_MCP_TOOLS")]
ListMcpTools,
#[serde(rename = "CALL_MCP_TOOL")]
CallMcpTool,
#[serde(rename = "GET_DOCUMENT")]
GetDocument,
Noop,
#[serde(rename = "UPDATE_TASK")]
UpdateTask,
#[serde(rename = "GET_WORKFLOW")]
GetWorkflow,
#[serde(rename = "UPDATE_SECRET")]
UpdateSecret,
#[serde(rename = "PUBLISH_METRIC")]
PublishMetric,
#[serde(rename = "QUERY_PROCESSOR")]
QueryProcessor,
Jdbc,
#[serde(rename = "BUSINESS_RULE")]
BusinessRule,
#[serde(rename = "AWS_LAMBDA")]
AwsLambda,
#[serde(rename = "OPS_GENIE")]
OpsGenie,
Sendgrid,
#[serde(rename = "WAIT_UNTIL")]
WaitUntil,
#[serde(rename = "MCP_REMOTE")]
McpRemote,
#[serde(rename = "START_WORKFLOW_BATCH")]
StartWorkflowBatch,
#[serde(other)]
Other,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkflowTask {
pub name: String,
pub task_reference_name: String,
#[serde(rename = "type")]
pub task_type: TaskType,
#[serde(default)]
pub input_parameters: HashMap<String, serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub dynamic_task_name_param: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub case_value_param: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub case_expression: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub script_expression: Option<String>,
#[serde(default)]
pub decision_cases: HashMap<String, Vec<WorkflowTask>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub dynamic_fork_tasks_param: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub dynamic_fork_tasks_input_param_name: Option<String>,
#[serde(default)]
pub default_case: Vec<WorkflowTask>,
#[serde(default)]
pub fork_tasks: Vec<Vec<WorkflowTask>>,
#[serde(default)]
pub start_delay: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub sub_workflow_param: Option<SubWorkflowParams>,
#[serde(default)]
pub join_on: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sink: Option<String>,
#[serde(default)]
pub optional: bool,
#[serde(default)]
pub async_complete: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub default_exclusive_join_task: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub loop_condition: Option<String>,
#[serde(default)]
pub loop_over: Vec<WorkflowTask>,
#[serde(skip_serializing_if = "Option::is_none")]
pub retry_count: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub evaluator_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub expression: Option<String>,
#[serde(default)]
pub rate_limited: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub join_on_script: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub on_state_change: Option<StateChangeConfig>,
#[serde(skip_serializing_if = "Option::is_none")]
pub task_definition: Option<EmbeddedTaskDef>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StateChangeConfig {
#[serde(default)]
pub event_type: Vec<StateChangeEventType>,
#[serde(default)]
pub events: Vec<StateChangeEvent>,
}
impl StateChangeConfig {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn on_event(mut self, event_type: StateChangeEventType) -> Self {
self.event_type.push(event_type);
self
}
#[must_use]
pub fn with_event(mut self, event: StateChangeEvent) -> Self {
self.events.push(event);
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum StateChangeEventType {
OnScheduled,
OnStart,
OnFailed,
OnCompleted,
OnCancelled,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StateChangeEvent {
#[serde(rename = "type")]
pub event_type: String,
#[serde(default)]
pub payload: HashMap<String, serde_json::Value>,
}
impl StateChangeEvent {
pub fn new(task_type: impl Into<String>) -> Self {
Self {
event_type: task_type.into(),
payload: HashMap::new(),
}
}
#[must_use]
pub fn with_payload(
mut self,
key: impl Into<String>,
value: impl Into<serde_json::Value>,
) -> Self {
self.payload.insert(key.into(), value.into());
self
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EmbeddedTaskDef {
#[serde(default)]
pub name: String,
#[serde(default)]
pub retry_count: i32,
#[serde(default)]
pub timeout_seconds: i64,
#[serde(default)]
pub response_timeout_seconds: i64,
}
impl EmbeddedTaskDef {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
..Default::default()
}
}
#[must_use]
pub fn with_retry_count(mut self, count: i32) -> Self {
self.retry_count = count;
self
}
#[must_use]
pub fn with_timeout(mut self, seconds: i64) -> Self {
self.timeout_seconds = seconds;
self
}
}
impl WorkflowTask {
pub fn simple(name: impl Into<String>, task_ref_name: impl Into<String>) -> Self {
Self {
name: name.into(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::Simple,
..Default::default()
}
}
pub fn sub_workflow(
task_ref_name: impl Into<String>,
workflow_name: impl Into<String>,
) -> Self {
Self {
name: "sub_workflow".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::SubWorkflow,
sub_workflow_param: Some(SubWorkflowParams {
name: workflow_name.into(),
version: None,
task_to_domain: HashMap::new(),
}),
..Default::default()
}
}
pub fn wait(task_ref_name: impl Into<String>) -> Self {
Self {
name: "wait".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::Wait,
..Default::default()
}
}
pub fn http(task_ref_name: impl Into<String>, uri: impl Into<String>) -> Self {
let http_request = serde_json::json!({
"uri": uri.into(),
"method": "GET"
});
let mut input = HashMap::new();
input.insert("http_request".to_owned(), http_request);
Self {
name: "http".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::Http,
input_parameters: input,
..Default::default()
}
}
pub fn list_mcp_tools(
task_ref_name: impl Into<String>,
mcp_server: impl Into<String>,
headers: Option<HashMap<String, String>>,
) -> Self {
let mut input = HashMap::new();
input.insert(
"mcpServer".to_owned(),
serde_json::Value::String(mcp_server.into()),
);
if let Some(headers) = headers {
input.insert(
"headers".to_owned(),
serde_json::to_value(headers).unwrap_or_default(),
);
}
Self {
name: "list_mcp_tools".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::ListMcpTools,
input_parameters: input,
..Default::default()
}
}
pub fn inline(task_ref_name: impl Into<String>, script: impl Into<String>) -> Self {
let mut input = HashMap::new();
input.insert(
"expression".to_owned(),
serde_json::Value::String(script.into()),
);
input.insert(
"evaluatorType".to_owned(),
serde_json::Value::String("graaljs".to_owned()),
);
Self {
name: "inline".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::Inline,
input_parameters: input,
..Default::default()
}
}
#[must_use]
pub fn with_input(mut self, input: HashMap<String, serde_json::Value>) -> Self {
self.input_parameters = input;
self
}
#[must_use]
pub fn with_input_param(mut self, key: impl Into<String>, value: impl Serialize) -> Self {
self.input_parameters.insert(
key.into(),
serde_json::to_value(value).unwrap_or(serde_json::Value::Null),
);
self
}
#[must_use]
pub fn with_description(mut self, desc: impl Into<String>) -> Self {
self.description = Some(desc.into());
self
}
#[must_use]
pub fn optional(mut self) -> Self {
self.optional = true;
self
}
pub fn switch(task_ref_name: impl Into<String>, case_expression: impl Into<String>) -> Self {
Self {
name: "switch".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::Switch,
expression: Some(case_expression.into()),
evaluator_type: Some("javascript".to_owned()),
..Default::default()
}
}
pub fn switch_value_param(
task_ref_name: impl Into<String>,
case_expression: impl Into<String>,
) -> Self {
Self {
name: "switch".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::Switch,
expression: Some(case_expression.into()),
evaluator_type: Some("value-param".to_owned()),
..Default::default()
}
}
#[must_use]
pub fn with_switch_case(
mut self,
case_value: impl Into<String>,
tasks: Vec<WorkflowTask>,
) -> Self {
self.decision_cases.insert(case_value.into(), tasks);
self
}
#[must_use]
pub fn with_default_case(mut self, tasks: Vec<WorkflowTask>) -> Self {
self.default_case = tasks;
self
}
pub fn fork(task_ref_name: impl Into<String>, branches: Vec<Vec<WorkflowTask>>) -> Self {
Self {
name: "fork".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::ForkJoin,
fork_tasks: branches,
..Default::default()
}
}
pub fn join(task_ref_name: impl Into<String>, join_on: Vec<String>) -> Self {
Self {
name: "join".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::Join,
join_on,
..Default::default()
}
}
pub fn set_variable(task_ref_name: impl Into<String>) -> Self {
Self {
name: "set_variable".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::SetVariable,
..Default::default()
}
}
pub fn terminate(task_ref_name: impl Into<String>, status: impl Into<String>) -> Self {
let mut input = HashMap::new();
input.insert(
"terminationStatus".to_owned(),
serde_json::Value::String(status.into()),
);
Self {
name: "terminate".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::Terminate,
input_parameters: input,
..Default::default()
}
}
#[must_use]
pub fn with_termination_reason(mut self, reason: impl Into<String>) -> Self {
self.input_parameters.insert(
"terminationReason".to_owned(),
serde_json::Value::String(reason.into()),
);
self
}
pub fn json_jq_transform(task_ref_name: impl Into<String>, query: impl Into<String>) -> Self {
let mut input = HashMap::new();
input.insert(
"queryExpression".to_owned(),
serde_json::Value::String(query.into()),
);
Self {
name: "json_jq_transform".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::JsonJqTransform,
input_parameters: input,
..Default::default()
}
}
pub fn wait_duration(task_ref_name: impl Into<String>, duration: impl Into<String>) -> Self {
let mut input = HashMap::new();
input.insert(
"duration".to_owned(),
serde_json::Value::String(duration.into()),
);
Self {
name: "wait".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::Wait,
input_parameters: input,
..Default::default()
}
}
pub fn event(task_ref_name: impl Into<String>, sink: impl Into<String>) -> Self {
Self {
name: "event".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::Event,
sink: Some(sink.into()),
..Default::default()
}
}
pub fn do_while(
task_ref_name: impl Into<String>,
loop_condition: impl Into<String>,
loop_tasks: Vec<WorkflowTask>,
) -> Self {
Self {
name: "do_while".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::DoWhile,
loop_condition: Some(loop_condition.into()),
loop_over: loop_tasks,
..Default::default()
}
}
pub fn human(task_ref_name: impl Into<String>) -> Self {
Self {
name: "human".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::Human,
..Default::default()
}
}
#[must_use]
pub fn async_complete(mut self) -> Self {
self.async_complete = true;
self
}
#[must_use]
pub fn with_start_delay(mut self, seconds: i32) -> Self {
self.start_delay = seconds;
self
}
#[must_use]
pub fn with_state_change(mut self, config: StateChangeConfig) -> Self {
self.on_state_change = Some(config);
self
}
#[must_use]
pub fn with_task_definition(mut self, task_def: EmbeddedTaskDef) -> Self {
self.task_definition = Some(task_def);
self
}
pub fn join_with_script(
task_ref_name: impl Into<String>,
join_on: Vec<String>,
script: impl Into<String>,
) -> Self {
Self {
name: "join".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::Join,
join_on,
join_on_script: Some(script.into()),
..Default::default()
}
}
pub fn http_poll(task_ref_name: impl Into<String>, uri: impl Into<String>) -> Self {
let http_request = serde_json::json!({
"uri": uri.into(),
"method": "GET",
"pollingStrategy": "FIXED",
"pollingInterval": 1000
});
let mut input = HashMap::new();
input.insert("http_request".to_owned(), http_request);
Self {
name: "http_poll".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::HttpPoll,
input_parameters: input,
..Default::default()
}
}
#[must_use]
pub fn with_polling_strategy(mut self, strategy: impl Into<String>) -> Self {
if let Some(req) = self.input_parameters.get_mut("http_request") {
req["pollingStrategy"] = serde_json::json!(strategy.into());
}
self
}
#[must_use]
pub fn with_polling_interval(mut self, interval_secs: i64) -> Self {
if let Some(req) = self.input_parameters.get_mut("http_request") {
req["pollingInterval"] = serde_json::json!(interval_secs);
}
self
}
#[must_use]
pub fn with_termination_condition(mut self, script: impl Into<String>) -> Self {
if let Some(req) = self.input_parameters.get_mut("http_request") {
req["terminationCondition"] = serde_json::json!(script.into());
}
self
}
pub fn wait_for_webhook(task_ref_name: impl Into<String>) -> Self {
Self {
name: "wait_for_webhook".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::WaitForWebhook,
..Default::default()
}
}
#[must_use]
pub fn with_matches(mut self, matches: HashMap<String, String>) -> Self {
let matches_value: HashMap<String, serde_json::Value> = matches
.into_iter()
.map(|(k, v)| (k, serde_json::json!(v)))
.collect();
self.input_parameters
.insert("matches".to_owned(), serde_json::json!(matches_value));
self
}
pub fn llm_text_complete(
task_ref_name: impl Into<String>,
llm_provider: impl Into<String>,
model: impl Into<String>,
prompt_name: impl Into<String>,
) -> Self {
let mut input = HashMap::new();
input.insert(
"llmProvider".to_owned(),
serde_json::json!(llm_provider.into()),
);
input.insert("model".to_owned(), serde_json::json!(model.into()));
input.insert(
"promptName".to_owned(),
serde_json::json!(prompt_name.into()),
);
Self {
name: "llm_text_complete".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::LlmTextComplete,
input_parameters: input,
..Default::default()
}
}
pub fn llm_chat_complete(
task_ref_name: impl Into<String>,
llm_provider: impl Into<String>,
model: impl Into<String>,
) -> Self {
let mut input = HashMap::new();
input.insert(
"llmProvider".to_owned(),
serde_json::json!(llm_provider.into()),
);
input.insert("model".to_owned(), serde_json::json!(model.into()));
input.insert("messages".to_owned(), serde_json::json!([]));
Self {
name: "llm_chat_complete".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::LlmChatComplete,
input_parameters: input,
..Default::default()
}
}
#[must_use]
pub fn with_instructions_template(mut self, template_name: impl Into<String>) -> Self {
self.input_parameters.insert(
"instructionsTemplate".to_owned(),
serde_json::json!(template_name.into()),
);
self
}
#[must_use]
pub fn with_messages(mut self, messages: Vec<ChatMessage>) -> Self {
self.input_parameters.insert(
"messages".to_owned(),
serde_json::to_value(messages).unwrap_or_default(),
);
self
}
#[must_use]
pub fn with_temperature(mut self, temp: f32) -> Self {
self.input_parameters
.insert("temperature".to_owned(), serde_json::json!(temp));
self
}
#[must_use]
pub fn with_max_tokens(mut self, tokens: i32) -> Self {
self.input_parameters
.insert("maxTokens".to_owned(), serde_json::json!(tokens));
self
}
#[must_use]
pub fn with_top_p(mut self, top_p: f32) -> Self {
self.input_parameters
.insert("topP".to_owned(), serde_json::json!(top_p));
self
}
#[must_use]
pub fn with_prompt_variables(mut self, variables: HashMap<String, serde_json::Value>) -> Self {
self.input_parameters
.insert("promptVariables".to_owned(), serde_json::json!(variables));
self
}
#[must_use]
pub fn with_prompt_variable(
mut self,
key: impl Into<String>,
value: impl Into<serde_json::Value>,
) -> Self {
let vars = self
.input_parameters
.entry("promptVariables".to_owned())
.or_insert_with(|| serde_json::json!({}));
if let serde_json::Value::Object(map) = vars {
map.insert(key.into(), value.into());
}
self
}
pub fn llm_generate_embeddings(
task_ref_name: impl Into<String>,
llm_provider: impl Into<String>,
model: impl Into<String>,
text: impl Into<String>,
) -> Self {
let mut input = HashMap::new();
input.insert(
"llmProvider".to_owned(),
serde_json::json!(llm_provider.into()),
);
input.insert("model".to_owned(), serde_json::json!(model.into()));
input.insert("text".to_owned(), serde_json::json!(text.into()));
Self {
name: "llm_generate_embeddings".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::LlmGenerateEmbeddings,
input_parameters: input,
..Default::default()
}
}
pub fn llm_search_index(
task_ref_name: impl Into<String>,
vector_db: impl Into<String>,
index: impl Into<String>,
query: impl Into<String>,
) -> Self {
let mut input = HashMap::new();
input.insert("vectorDB".to_owned(), serde_json::json!(vector_db.into()));
input.insert("index".to_owned(), serde_json::json!(index.into()));
input.insert("query".to_owned(), serde_json::json!(query.into()));
Self {
name: "llm_search_index".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::LlmSearchIndex,
input_parameters: input,
..Default::default()
}
}
pub fn llm_search_embeddings(
task_ref_name: impl Into<String>,
vector_db: impl Into<String>,
index: impl Into<String>,
embeddings: Vec<f64>,
) -> Self {
let mut input = HashMap::new();
input.insert("vectorDB".to_owned(), serde_json::json!(vector_db.into()));
input.insert("index".to_owned(), serde_json::json!(index.into()));
input.insert("embeddings".to_owned(), serde_json::json!(embeddings));
input.insert("maxResults".to_owned(), serde_json::json!(1));
Self {
name: "llm_search_embeddings".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::LlmSearchEmbeddings,
input_parameters: input,
..Default::default()
}
}
pub fn generate_image(
task_ref_name: impl Into<String>,
llm_provider: impl Into<String>,
model: impl Into<String>,
prompt: impl Into<String>,
) -> Self {
let mut input = HashMap::new();
input.insert(
"llmProvider".to_owned(),
serde_json::json!(llm_provider.into()),
);
input.insert("model".to_owned(), serde_json::json!(model.into()));
input.insert("prompt".to_owned(), serde_json::json!(prompt.into()));
input.insert("width".to_owned(), serde_json::json!(1024));
input.insert("height".to_owned(), serde_json::json!(1024));
input.insert("n".to_owned(), serde_json::json!(1));
input.insert("outputFormat".to_owned(), serde_json::json!("png"));
Self {
name: "generate_image".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::GenerateImage,
input_parameters: input,
..Default::default()
}
}
pub fn generate_audio(
task_ref_name: impl Into<String>,
llm_provider: impl Into<String>,
model: impl Into<String>,
) -> Self {
let mut input = HashMap::new();
input.insert(
"llmProvider".to_owned(),
serde_json::json!(llm_provider.into()),
);
input.insert("model".to_owned(), serde_json::json!(model.into()));
input.insert("n".to_owned(), serde_json::json!(1));
Self {
name: "generate_audio".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::GenerateAudio,
input_parameters: input,
..Default::default()
}
}
#[must_use]
pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
self.input_parameters
.insert("namespace".to_owned(), serde_json::json!(namespace.into()));
self
}
#[must_use]
pub fn with_max_results(mut self, max: i32) -> Self {
self.input_parameters
.insert("maxResults".to_owned(), serde_json::json!(max));
self
}
#[must_use]
pub fn with_embedding_model(
mut self,
provider: impl Into<String>,
model: impl Into<String>,
) -> Self {
self.input_parameters.insert(
"embeddingModelProvider".to_owned(),
serde_json::json!(provider.into()),
);
self.input_parameters
.insert("embeddingModel".to_owned(), serde_json::json!(model.into()));
self
}
#[must_use]
pub fn with_dimensions(mut self, dimensions: i32) -> Self {
self.input_parameters
.insert("dimensions".to_owned(), serde_json::json!(dimensions));
self
}
#[must_use]
pub fn with_n(mut self, n: i32) -> Self {
self.input_parameters
.insert("n".to_owned(), serde_json::json!(n));
self
}
#[must_use]
pub fn with_image_dimensions(mut self, width: i32, height: i32) -> Self {
self.input_parameters
.insert("width".to_owned(), serde_json::json!(width));
self.input_parameters
.insert("height".to_owned(), serde_json::json!(height));
self
}
#[must_use]
pub fn with_size(mut self, size: impl Into<String>) -> Self {
self.input_parameters
.insert("size".to_owned(), serde_json::json!(size.into()));
self
}
#[must_use]
pub fn with_style(mut self, style: impl Into<String>) -> Self {
self.input_parameters
.insert("style".to_owned(), serde_json::json!(style.into()));
self
}
#[must_use]
pub fn with_weight(mut self, weight: f64) -> Self {
self.input_parameters
.insert("weight".to_owned(), serde_json::json!(weight));
self
}
#[must_use]
pub fn with_output_format(mut self, format: impl Into<String>) -> Self {
self.input_parameters
.insert("outputFormat".to_owned(), serde_json::json!(format.into()));
self
}
#[must_use]
pub fn with_text(mut self, text: impl Into<String>) -> Self {
self.input_parameters
.insert("text".to_owned(), serde_json::json!(text.into()));
self
}
#[must_use]
pub fn with_voice(mut self, voice: impl Into<String>) -> Self {
self.input_parameters
.insert("voice".to_owned(), serde_json::json!(voice.into()));
self
}
#[must_use]
pub fn with_speed(mut self, speed: f64) -> Self {
self.input_parameters
.insert("speed".to_owned(), serde_json::json!(speed));
self
}
#[must_use]
pub fn with_response_format(mut self, format: impl Into<String>) -> Self {
self.input_parameters.insert(
"responseFormat".to_owned(),
serde_json::json!(format.into()),
);
self
}
#[must_use]
pub fn with_prompt(mut self, prompt: impl Into<String>) -> Self {
self.input_parameters
.insert("prompt".to_owned(), serde_json::json!(prompt.into()));
self
}
pub fn llm_index_text(
task_ref_name: impl Into<String>,
vector_db: impl Into<String>,
index: impl Into<String>,
text: impl Into<String>,
doc_id: impl Into<String>,
) -> Self {
let mut input = HashMap::new();
input.insert("vectorDB".to_owned(), serde_json::json!(vector_db.into()));
input.insert("index".to_owned(), serde_json::json!(index.into()));
input.insert("text".to_owned(), serde_json::json!(text.into()));
input.insert("docId".to_owned(), serde_json::json!(doc_id.into()));
Self {
name: "llm_index_text".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::LlmIndexText,
input_parameters: input,
..Default::default()
}
}
pub fn llm_index_document(
task_ref_name: impl Into<String>,
vector_db: impl Into<String>,
index: impl Into<String>,
url: impl Into<String>,
doc_id: impl Into<String>,
) -> Self {
let mut input = HashMap::new();
input.insert("vectorDB".to_owned(), serde_json::json!(vector_db.into()));
input.insert("index".to_owned(), serde_json::json!(index.into()));
input.insert("url".to_owned(), serde_json::json!(url.into()));
input.insert("docId".to_owned(), serde_json::json!(doc_id.into()));
Self {
name: "llm_index_document".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::LlmIndexDocument,
input_parameters: input,
..Default::default()
}
}
#[must_use]
pub fn with_media_type(mut self, media_type: impl Into<String>) -> Self {
self.input_parameters
.insert("mediaType".to_owned(), serde_json::json!(media_type.into()));
self
}
#[must_use]
pub fn with_metadata(mut self, metadata: HashMap<String, String>) -> Self {
self.input_parameters
.insert("metadata".to_owned(), serde_json::json!(metadata));
self
}
pub fn dynamic(task_ref_name: impl Into<String>, dynamic_task_name: impl Into<String>) -> Self {
let mut input = HashMap::new();
input.insert(
"dynamicTaskName".to_owned(),
serde_json::json!(dynamic_task_name.into()),
);
Self {
name: "dynamic".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::Dynamic,
input_parameters: input,
dynamic_task_name_param: Some("dynamicTaskName".to_owned()),
..Default::default()
}
}
pub fn get_document(task_ref_name: impl Into<String>, url: impl Into<String>) -> Self {
let mut input = HashMap::new();
input.insert("url".to_owned(), serde_json::json!(url.into()));
Self {
name: "get_document".to_owned(),
task_reference_name: task_ref_name.into(),
task_type: TaskType::GetDocument,
input_parameters: input,
..Default::default()
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatMessage {
pub role: String,
pub message: String,
}
impl ChatMessage {
pub fn user(message: impl Into<String>) -> Self {
Self {
role: "user".to_owned(),
message: message.into(),
}
}
pub fn assistant(message: impl Into<String>) -> Self {
Self {
role: "assistant".to_owned(),
message: message.into(),
}
}
pub fn system(message: impl Into<String>) -> Self {
Self {
role: "system".to_owned(),
message: message.into(),
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SubWorkflowParams {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub version: Option<i32>,
#[serde(default)]
pub task_to_domain: HashMap<String, String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkflowDef {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default = "default_version")]
pub version: i32,
#[serde(default)]
pub tasks: Vec<WorkflowTask>,
#[serde(default)]
pub input_parameters: Vec<String>,
#[serde(default)]
pub output_parameters: HashMap<String, serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub failure_workflow: Option<String>,
#[serde(default = "default_schema_version")]
pub schema_version: i32,
#[serde(default = "default_true")]
pub restartable: bool,
#[serde(default)]
pub workflow_status_listener_enabled: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub owner_email: Option<String>,
#[serde(default)]
pub timeout_policy: WorkflowTimeoutPolicy,
#[serde(default)]
pub timeout_seconds: i64,
#[serde(default)]
pub variables: HashMap<String, serde_json::Value>,
#[serde(default)]
pub input_template: HashMap<String, serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub created_by: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub update_time: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub create_time: Option<i64>,
}
fn default_version() -> i32 {
1
}
fn default_schema_version() -> i32 {
2
}
fn default_true() -> bool {
true
}
impl WorkflowDef {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
version: 1,
schema_version: 2,
restartable: true,
..Default::default()
}
}
#[must_use]
pub fn with_description(mut self, desc: impl Into<String>) -> Self {
self.description = Some(desc.into());
self
}
#[must_use]
pub fn with_version(mut self, version: i32) -> Self {
self.version = version;
self
}
#[must_use]
pub fn with_task(mut self, task: WorkflowTask) -> Self {
self.tasks.push(task);
self
}
#[must_use]
pub fn with_tasks(mut self, tasks: Vec<WorkflowTask>) -> Self {
self.tasks = tasks;
self
}
#[must_use]
pub fn with_input_parameters(mut self, params: Vec<String>) -> Self {
self.input_parameters = params;
self
}
#[must_use]
pub fn with_output_parameters(mut self, params: HashMap<String, serde_json::Value>) -> Self {
self.output_parameters = params;
self
}
#[must_use]
pub fn with_output_param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.output_parameters
.insert(key.into(), serde_json::Value::String(value.into()));
self
}
#[must_use]
pub fn with_failure_workflow(mut self, name: impl Into<String>) -> Self {
self.failure_workflow = Some(name.into());
self
}
#[must_use]
pub fn with_timeout(mut self, seconds: i64, policy: WorkflowTimeoutPolicy) -> Self {
self.timeout_seconds = seconds;
self.timeout_policy = policy;
self
}
#[must_use]
pub fn with_owner(mut self, email: impl Into<String>) -> Self {
self.owner_email = Some(email.into());
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_workflow_def_builder() {
let wf = WorkflowDef::new("my_workflow")
.with_description("Test workflow")
.with_version(1)
.with_task(WorkflowTask::simple("task1", "task1_ref"))
.with_task(WorkflowTask::simple("task2", "task2_ref"));
assert_eq!(wf.name, "my_workflow");
assert_eq!(wf.description, Some("Test workflow".to_owned()));
assert_eq!(wf.tasks.len(), 2);
}
#[test]
fn test_workflow_task_builder() {
let task = WorkflowTask::simple("my_task", "my_task_ref")
.with_input_param("name", "value")
.with_description("A simple task");
assert_eq!(task.name, "my_task");
assert_eq!(task.task_reference_name, "my_task_ref");
assert_eq!(task.task_type, TaskType::Simple);
assert!(task.input_parameters.contains_key("name"));
}
#[test]
fn test_workflow_def_serialization() {
let wf = WorkflowDef::new("test").with_task(WorkflowTask::simple("t1", "t1_ref"));
let json = serde_json::to_string(&wf).unwrap();
assert!(json.contains("\"name\":\"test\""));
assert!(json.contains("\"tasks\":["));
}
#[test]
fn test_llm_search_embeddings_task_builder() {
let task = WorkflowTask::llm_search_embeddings(
"search_ref",
"pinecone_db",
"my_index",
vec![0.1, 0.2, 0.3],
)
.with_namespace("my_namespace")
.with_dimensions(3)
.with_embedding_model("openai", "text-embedding-3-small");
assert_eq!(task.task_type, TaskType::LlmSearchEmbeddings);
assert_eq!(
task.input_parameters.get("vectorDB"),
Some(&serde_json::json!("pinecone_db"))
);
assert_eq!(
task.input_parameters.get("embeddings"),
Some(&serde_json::json!([0.1, 0.2, 0.3]))
);
assert_eq!(
task.input_parameters.get("maxResults"),
Some(&serde_json::json!(1))
);
assert_eq!(
task.input_parameters.get("namespace"),
Some(&serde_json::json!("my_namespace"))
);
assert_eq!(
task.input_parameters.get("dimensions"),
Some(&serde_json::json!(3))
);
assert_eq!(
task.input_parameters.get("embeddingModel"),
Some(&serde_json::json!("text-embedding-3-small"))
);
}
#[test]
fn test_generate_image_task_builder_has_python_matching_defaults() {
let task = WorkflowTask::generate_image("img_ref", "openai", "dall-e-3", "a cat");
assert_eq!(task.task_type, TaskType::GenerateImage);
assert_eq!(
task.input_parameters.get("prompt"),
Some(&serde_json::json!("a cat"))
);
assert_eq!(
task.input_parameters.get("width"),
Some(&serde_json::json!(1024))
);
assert_eq!(
task.input_parameters.get("height"),
Some(&serde_json::json!(1024))
);
assert_eq!(task.input_parameters.get("n"), Some(&serde_json::json!(1)));
assert_eq!(
task.input_parameters.get("outputFormat"),
Some(&serde_json::json!("png"))
);
}
#[test]
fn test_generate_image_task_builder_overrides() {
let task = WorkflowTask::generate_image("img_ref", "openai", "dall-e-3", "a cat")
.with_image_dimensions(512, 512)
.with_size("512x512")
.with_style("vivid")
.with_weight(0.5)
.with_n(2)
.with_output_format("jpg");
assert_eq!(
task.input_parameters.get("width"),
Some(&serde_json::json!(512))
);
assert_eq!(
task.input_parameters.get("size"),
Some(&serde_json::json!("512x512"))
);
assert_eq!(
task.input_parameters.get("style"),
Some(&serde_json::json!("vivid"))
);
assert_eq!(
task.input_parameters.get("weight"),
Some(&serde_json::json!(0.5))
);
assert_eq!(task.input_parameters.get("n"), Some(&serde_json::json!(2)));
assert_eq!(
task.input_parameters.get("outputFormat"),
Some(&serde_json::json!("jpg"))
);
}
#[test]
fn test_generate_audio_task_builder() {
let task = WorkflowTask::generate_audio("audio_ref", "openai", "tts-1")
.with_text("hello world")
.with_voice("alloy")
.with_speed(1.5)
.with_response_format("mp3")
.with_prompt("an alternative prompt");
assert_eq!(task.task_type, TaskType::GenerateAudio);
assert_eq!(task.input_parameters.get("n"), Some(&serde_json::json!(1)));
assert_eq!(
task.input_parameters.get("text"),
Some(&serde_json::json!("hello world"))
);
assert_eq!(
task.input_parameters.get("voice"),
Some(&serde_json::json!("alloy"))
);
assert_eq!(
task.input_parameters.get("speed"),
Some(&serde_json::json!(1.5))
);
assert_eq!(
task.input_parameters.get("responseFormat"),
Some(&serde_json::json!("mp3"))
);
assert_eq!(
task.input_parameters.get("prompt"),
Some(&serde_json::json!("an alternative prompt"))
);
}
#[test]
fn test_list_mcp_tools_task_builder() {
let task = WorkflowTask::list_mcp_tools("list_tools", "http://localhost:3001/mcp", None);
assert_eq!(task.task_type, TaskType::ListMcpTools);
assert_eq!(
task.input_parameters.get("mcpServer"),
Some(&serde_json::Value::String(
"http://localhost:3001/mcp".to_owned()
))
);
assert!(!task.input_parameters.contains_key("headers"));
}
#[test]
fn test_list_mcp_tools_task_includes_headers_when_given() {
let mut headers = HashMap::new();
headers.insert("Authorization".to_owned(), "Bearer x".to_owned());
let task = WorkflowTask::list_mcp_tools("list_tools", "http://mcp", Some(headers));
assert_eq!(
task.input_parameters.get("headers"),
Some(&serde_json::json!({"Authorization": "Bearer x"}))
);
}
#[test]
fn test_list_mcp_tools_and_call_mcp_tool_wire_strings() {
assert_eq!(
serde_json::to_string(&TaskType::ListMcpTools).unwrap(),
"\"LIST_MCP_TOOLS\""
);
assert_eq!(
serde_json::to_string(&TaskType::CallMcpTool).unwrap(),
"\"CALL_MCP_TOOL\""
);
}
}