### Install Agentflow Starter Kit
Source: https://github.com/aaronrussell/agentflow/blob/main/packages/create-agentflow/README.md
Use your preferred package manager's create command to install the Agentflow starter kit. This command initiates the project setup process.
```sh
npm create agentflow@latest my-project
```
```sh
yarn create agentflow my-project
```
```sh
bun create agentflow my-project
```
--------------------------------
### Install Project Dependencies with Bun
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/README.md
Use this command to install all necessary project dependencies. Ensure Bun is installed on your system.
```bash
bun install
```
--------------------------------
### Agentflow CLI Usage Examples
Source: https://github.com/aaronrussell/agentflow/blob/main/packages/cli/README.md
Examples demonstrating how to initialize a new Agentflow project and execute a workflow.
```sh
# Create a new Agentflow project
aflow init my-project
cd my-project && npm install
# Execute a workflow
aflow exec hello-world
```
--------------------------------
### Navigate and Install Dependencies
Source: https://github.com/aaronrussell/agentflow/blob/main/packages/create-agentflow/README.md
After running the create command and configuring your project, navigate into the project directory and install the necessary dependencies using npm.
```sh
cd my-project
npm install
```
--------------------------------
### Install Dependencies with npm, yarn, or bun
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/getting-started.md
After creating the project, navigate to the project directory and install the necessary dependencies.
```sh
cd my-agents
npm i
```
```sh
cd my-agents
yarn
```
```sh
cd my-agents
bun i
```
--------------------------------
### Install Agentflow CLI with bun
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/cli.md
Install the Agentflow CLI globally using bun. If you created your project with `npm create agentflow`, the CLI is already installed locally.
```sh
bun install -g @agentflow/cli
```
--------------------------------
### Install Dependencies and Run Help with NPM
Source: https://github.com/aaronrussell/agentflow/blob/main/README.md
After creating a project with NPM, install local dependencies and then use npx to run the Agentflow CLI help command.
```bash
cd my-agents && npm install
npx aflow help
```
--------------------------------
### Install Agentflow CLI with npm
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/cli.md
Install the Agentflow CLI globally using npm. If you created your project with `npm create agentflow`, the CLI is already installed locally.
```sh
npm install -g @agentflow/cli
```
--------------------------------
### Install Dependencies and Run Help with Yarn
Source: https://github.com/aaronrussell/agentflow/blob/main/README.md
After creating a project with Yarn, install local dependencies and then use yarn to run the Agentflow CLI help command.
```bash
cd my-agents && yarn
yarn aflow help
```
--------------------------------
### Install Agentflow Core
Source: https://github.com/aaronrussell/agentflow/blob/main/packages/core/README.md
Install the Agentflow Core package using npm.
```sh
npm install @agentflow/core
```
--------------------------------
### Agentflow Workflow Example
Source: https://github.com/aaronrussell/agentflow/blob/main/README.md
This example demonstrates a workflow that prompts for a topic, generates a blog post using an AI model, and then translates the post into multiple languages using a loop.
```mdx
---
data:
languages:
- Spanish
- French
- German
input:
topic:
type: text
message: "Enter a topic to write about"
---
Write a short blog post about {topic}.
Translate this article to {language}:
{original}
```
--------------------------------
### Initialize New Project with Global CLI
Source: https://github.com/aaronrussell/agentflow/blob/main/README.md
Use the globally installed Agentflow CLI to initialize a new project and then navigate into the project directory.
```bash
aflow init my-agents
cd my-agents
```
--------------------------------
### Install Agentflow CLI with yarn
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/cli.md
Install the Agentflow CLI globally using yarn. If you created your project with `npm create agentflow`, the CLI is already installed locally.
```sh
yarn global add @agentflow/cli
```
--------------------------------
### Prompt Fragments Example
Source: https://context7.com/aaronrussell/agentflow/llms.txt
Reusable prompt components stored in the `prompts/` directory. Use the `include()` function to incorporate them into workflows.
```mdx
You are a senior data analyst with expertise in:
- Statistical analysis
- Data visualization
- Business intelligence
- Machine learning fundamentals
Always provide data-driven insights backed by evidence.
Format your response as follows:
1. Executive Summary (2-3 sentences)
2. Key Findings (bullet points)
3. Detailed Analysis
4. Recommendations
---
input:
data:
type: text
message: "Paste your data"
---
```
--------------------------------
### Install Agentflow Core Package
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/javascript-api.md
Install the Agentflow core package using npm, yarn, or bun.
```sh
npm install @agentflow/core
```
```sh
yarn add @agentflow/core
```
```sh
bun install @agentflow/core
```
--------------------------------
### Install @agentflow/tools
Source: https://github.com/aaronrussell/agentflow/blob/main/packages/tools/README.md
Install the @agentflow/tools package alongside the AgentFlow core package using npm.
```sh
npm install @agentflow/tools
```
--------------------------------
### Install Agentflow CLI Locally
Source: https://github.com/aaronrussell/agentflow/blob/main/packages/cli/README.md
Install the CLI as a project dependency for project-specific usage.
```sh
npm install @agentflow/cli
```
--------------------------------
### Run the Agentflow Project with Bun
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/README.md
Execute this command to start the Agentflow project. This assumes the main entry point is index.ts.
```bash
bun run index.ts
```
--------------------------------
### Get Agentflow CLI Help with npm, yarn, or bun
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/getting-started.md
Use the 'aflow help' command to view available commands for managing Agentflow workflows.
```sh
npx aflow help
```
```sh
yarn run aflow help
```
```sh
bunx aflow help
```
--------------------------------
### Prompt Fragment Composition Example
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/workflow-structure.md
Illustrates how prompt fragments can be composed by including other fragments using the `include()` function within an MDX file. This enables building complex agent behaviors from smaller, reusable pieces.
```mdx
{include('personas/marketer.mdx')}
Additionally, you have 15+ years of marketing experience and
specialize in B2B technology marketing.
```
--------------------------------
### Create Agentflow Project with NPM
Source: https://github.com/aaronrussell/agentflow/blob/main/README.md
Use this command to scaffold a new Agentflow project using NPM. The CLI will be installed locally as a project dependency.
```bash
npm create agentflow@latest my-agents
```
--------------------------------
### Single Phase Workflow Example
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/workflow-structure.md
Demonstrates a simple workflow with two sequential actions within a single phase. The output of the first action ('poem') is used as context for the second action ('translation').
```mdx
> Within a single phase, the result of each actions builds up the context
> that is provided to subsequent actions.
Write a poem about cats.
Now translate it to German:
```
--------------------------------
### Agentflow CLI Commands
Source: https://context7.com/aaronrussell/agentflow/llms.txt
Commands for initializing, listing, and executing Agentflow projects and workflows. Install globally for easy access.
```bash
# Install CLI globally
npm install -g @agentflow/cli
# Initialize new project
aflow init my-project
cd my-project
# Or use create command
npm create agentflow@latest my-project
# List available workflows
aflow list
# Output:
# Workflows:
# hello-world Hello World!
# joke-review Joke review!
# story-gen Story Generator
# Execute a workflow
aflow exec hello-world
# Or use alias
aflow x hello-world
# Workflows are stored in flows/ directory
# flows/
# hello-world.mdx
# joke-review.mdx
# story-gen.mdx
# Output is saved to outputs/{date}/{time}-{workflow}/output.md
```
--------------------------------
### Install Anthropic Provider with npm, yarn, or bun
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/ai-generations.md
Install the Anthropic AI provider using your preferred package manager. This is a prerequisite for using Anthropic models with Agentflow.
```sh
npm install @ai-sdk/anthropic
```
```sh
yarn add @ai-sdk/anthropic
```
```sh
bun add @ai-sdk/anthropic
```
--------------------------------
### Multiple Phases Workflow Example with Context Injection
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/workflow-structure.md
Illustrates a workflow with two distinct phases separated by a horizontal rule. It shows how to inject the output ('poem') from the first phase into the context of the second phase using a JavaScript expression.
```mdx
> Seperate phases have their own isolated context.
Write a poem about cats.
---
> Output from previous phases can be injected into the context of this
> phase using a JavaScript expression.
Translate this poem to German: {poem}
```
--------------------------------
### Configure File System Tools in agentflow.config.js
Source: https://github.com/aaronrussell/agentflow/blob/main/packages/tools/README.md
Configure file system tools by importing necessary modules and creating an instance of createFileSystemTools with a base directory. This setup is done within the agentflow.config.js file.
```ts
import { join } from 'node:path'
import { defineConfig } from '@agentflow/core'
import { createFileSystemTools } from '@agentflow/tools'
// Configure file system tools with a base directory
const baseDir = join(process.cwd(), 'outputs')
const fs = createFileSystemTools(baseDir)
export default defineConfig({
tools: [
fs.write_files
],
// other config options
})
```
--------------------------------
### Create Agentflow Project with Yarn
Source: https://github.com/aaronrussell/agentflow/blob/main/README.md
Use this command to scaffold a new Agentflow project using Yarn. The CLI will be installed locally as a project dependency.
```bash
yarn create agentflow my-agents
```
--------------------------------
### Configure Custom AI Provider Instances
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/ai-generations.md
Create custom instances of AI providers, such as OpenAI compatible providers, with specific configurations like API keys and base URLs. This allows for more flexibility in provider setup.
```typescript
import { defineConfig } from '@agentflow/core'
import { createOpenAI } from '@ai-sdk/openai'
export default defineConfig({
providers: {
openai: createOpenAI({
apiKey: process.env.COMPANY_OAI_KEY,
compatibility: 'strict',
}),
together: createOpenAI({
apiKey: process.env.TOGETHER_API_KEY,
baseURL: 'https://api.together.xyz/v1',
compatibility: 'compatible',
}),
}
})
```
--------------------------------
### Define AI Workflow with Natural Language
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/what-is-agentflow.md
Example of an Agentflow workflow written in Markdown, specifying a summarization task and an AI model for generation. Ensure the `{article}` variable is provided during execution.
```markdown
Summarize the following article in three bullet points:
{article}
```
--------------------------------
### Define LLM Function-Calling Tools
Source: https://context7.com/aaronrussell/agentflow/llms.txt
Create tools for LLMs to invoke using defineTool. Tools have a name, description, parameter schema, and an invoke function. This example defines 'calculator' and 'web_search' tools.
```typescript
import { defineTool, Environment, Workflow } from '@agentflow/core'
import { z } from 'zod'
// Define tools for LLM function calling
const calculatorTool = defineTool({
name: 'calculator',
description: 'Perform mathematical calculations',
params: z.object({
expression: z.string().describe('Mathematical expression to evaluate')
}),
invoke: async ({ expression }) => {
try {
// Safe evaluation (use a proper math library in production)
const result = Function(`"use strict"; return (${expression})`)()
return { result, expression }
} catch (error) {
return { error: 'Invalid expression' }
}
}
})
const searchTool = defineTool({
name: 'web_search',
description: 'Search the web for information',
params: z.object({
query: z.string().describe('Search query'),
limit: z.number().default(5).describe('Number of results')
}),
invoke: async ({ query, limit }) => {
// Implement actual search logic
return {
query,
results: [
{ title: 'Result 1', url: 'https://example.com/1' },
{ title: 'Result 2', url: 'https://example.com/2' }
]
}
}
})
const env = new Environment({
providers: { /* ... */ },
tools: [calculatorTool, searchTool]
})
// Tools are used in GenText actions
const workflow = Workflow.compileSync (
`
Calculate the compound interest on $10,000 at 5% for 10 years.
Use the calculator tool to compute: 10000 * (1.05 ^ 10)
`,
env
)
```
--------------------------------
### Basic Agentflow Project Configuration
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/configuration.md
Configure your Agentflow project by defining actions, tools, AI providers, plugins, and validators in the `agentflow.config.js` file. Ensure necessary packages like `@agentflow/core` and AI SDKs are installed.
```javascript
import { defineConfig } from '@agentflow/core'
import { openai } from '@ai-sdk/openai'
import { anthropic } from '@ai-sdk/anthropic'
import { debugAction, writeFileTool } from './lib/custom'
export default defineConfig({
// Register custom actions
actions: [
debugAction
],
// Register tools for LLM actions
tools: [
writeFileTool
],
// Register LLM providers (compatible with Vercel AI SDK)
providers: {
openai,
anthropic: createAnthropic({ apiKey: process.env.ANTHROPIC_API_KEY }),
},
// Add Agentflow plugins
plugins: [],
// Add custom workflow validators
validators: []
})
```
--------------------------------
### Scoped Expressions with `provide` Attribute
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/workflow-structure.md
Shows how to manage state across nested scopes using the `provide` attribute in Agentflow. This example demonstrates passing data like `poem` from a parent scope to a child `` scope, where it's then used in subsequent actions.
```mdx
Write a poem about cats.
Translate this poem to {language}:
{original}
```
--------------------------------
### Define Custom Action with Schema
Source: https://context7.com/aaronrussell/agentflow/llms.txt
Create reusable custom actions using defineAction. Actions can have a Zod schema for props and helpers accessible in workflows. This example defines a 'fetch-url' action.
```typescript
import { defineAction, Environment, Workflow } from '@agentflow/core'
import { z } from 'zod'
// Define a custom action
const fetchUrlAction = defineAction({
name: 'fetch-url',
schema: z.object({
url: z.string().url(),
selector: z.string().optional()
}),
helpers: {
// Helpers accessible via $.propertyName in workflows
timestamp: () => new Date().toISOString()
},
execute: async (ctx, props) => {
const response = await fetch(props.url)
const html = await response.text()
// Push metadata about the response
ctx.pushResponseMeta('http', {
status: response.status,
headers: Object.fromEntries(response.headers)
})
return { type: 'primitive', value: html }
}
})
// Register with environment
const env = new Environment({
providers: { /* ... */ },
actions: [fetchUrlAction]
})
// Use in workflow
const workflow = Workflow.compileSync (
`
Fetch the content from this URL and summarize it.
{page}
`,
env
)
```
--------------------------------
### Iterate and Generate Tweets for Speakers
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/ai-generations.md
Utilize the Loop action to iterate over a generated list of speakers and generate personalized tweets for each. This example filters speakers with Twitter profiles and uses the Loop's provide context to access individual speaker data within the GenText action.
```mdx
!!s.twitter).length}
provide={{ speaker: speakers.filter(s => !!s.twitter)[$.index] }}>
Write a tweet to the conference speaker thanking them for their
presentation. Use a disturbing amount of emojis.
Name: {speaker.name}
Company: {speaker.company}
Twitter: {speaker.twitter}
```
--------------------------------
### Create File System Tools
Source: https://context7.com/aaronrussell/agentflow/llms.txt
Initializes file system tools for writing files within workflows. Ensure the output directory exists.
```typescript
import { Environment, Workflow } from '@agentflow/core'
import { createFileSystemTools } from '@agentflow/tools'
import { openai } from '@ai-sdk/openai'
// Create file system tools scoped to output directory
const fsTools = createFileSystemTools('./output')
const env = new Environment({
providers: { openai },
tools: Object.values(fsTools)
})
const workflow = Workflow.compileSync(`
---
input:
topic:
type: text
message: "Enter a topic for the story"
---
# Story Generator
Write a short story about {topic}.
Save the story to a file called "story.txt" using the write_files tool.
`, env)
await workflow.createExecution({
topic: { type: 'primitive', value: 'a robot learning to paint' }
}).runAll()
// File is saved to ./output/story.txt
```
--------------------------------
### Compile and Execute a Workflow Programmatically
Source: https://github.com/aaronrussell/agentflow/blob/main/packages/core/README.md
Demonstrates how to compile and execute a simple Markdown-based workflow using the Agentflow Core library. Ensure AI providers like OpenAI are initialized in the environment.
```ts
import { Environment, Workflow } from '@agentflow/core'
import { openai } from '@ai-sdk/openai'
// Initialize environment with AI providers
const env = new Environment({
providers: {
openai
}
})
// Compile a workflow
const workflow = Workflow.compileSync(`
Write a short story about {topic}.
`, env)
// Create and run execution
const ctrl = workflow.createExecution({
topic: { type: 'primitive', value: 'a magical forest' }
})
// Handle execution events
ctrl.on('step', (step, event) => {
event.action?.then(({ result }) => console.log(result))
})
ctrl.on('complete', (output) => {
console.log('Done!\n', output)
})
// Run the workflow
await ctrl.runAll()
```
--------------------------------
### Initialize a new Agentflow project
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/cli.md
Create a new Agentflow project in a specified directory. If no path is provided, the project is created in the current directory. Use the -t option to specify a project template.
```sh
aflow init [path] [options]
```
```sh
aflow i [path] [options]
```
--------------------------------
### Create Agentflow Project with npm, yarn, or bun
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/getting-started.md
Bootstrap a new Agentflow project using your preferred package manager. Optionally specify the project name.
```sh
npm create agentflow@latest my-agents
```
```sh
yarn create agentflow my-agents
```
```sh
bun create agentflow my-agents
```
--------------------------------
### Including Prompt Fragments in Workflows
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/workflow-structure.md
Demonstrates how to incorporate reusable prompt fragments into Agentflow workflows using the `include()` function within expressions. This allows for modularity and consistency in prompt engineering.
```mdx
Write marketing copy for our new product:
{content}
{include('instructions/tone-guidelines.mdx')}
{include('instructions/conversion-rules.mdx')}
```
--------------------------------
### Compile Workflow from Markdown
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/javascript-api.md
Compile a Markdown-formatted workflow string into a Workflow instance using the Environment. Ensure the Environment is configured with necessary AI providers.
```ts
import { Environment, Workflow } from '@agentflow/core'
const env = new Environment({
providers: {
// configure AI providers
}
})
const markdown = `
# Joke generator
Tell me the corniest dad joke you can think of.
`
const workflow = Workflow.compileSync(markdown, env)
```
--------------------------------
### Configure AgentFlow Environment with Multiple Providers
Source: https://context7.com/aaronrussell/agentflow/llms.txt
Sets up an execution environment with multiple AI providers (OpenAI, Anthropic, Ollama), custom prompts, tools, and plugins. The environment is essential for compiling and running workflows.
```typescript
import { Environment, defineConfig, defineAction, defineTool } from '@agentflow/core'
import { openai } from '@ai-sdk/openai'
import { anthropic } from '@ai-sdk/anthropic'
import { ollama } from 'ollama-ai-provider'
import { z } from 'zod'
// Define configuration with multiple providers
const config = defineConfig({
providers: {
openai,
anthropic,
ollama
},
// Custom prompts directory
prompts: {
'personas/writer.mdx': 'You are a creative writer with expertise in storytelling.',
'instructions/format.mdx': 'Always format responses in markdown.'
},
// Custom tools for LLM function calling
tools: [
defineTool({
name: 'get_weather',
description: 'Get current weather for a location',
params: z.object({
city: z.string().describe('City name'),
units: z.enum(['celsius', 'fahrenheit']).default('celsius')
}),
invoke: async ({ city, units }) => {
// Fetch weather data
return { city, temperature: 22, units }
}
})
],
// Plugins for extending environment
plugins: [
(builder) => {
// Register additional actions or tools
console.log('Plugin initialized')
}
]
})
const env = new Environment(config)
// Use specific models in workflows
const workflow = Workflow.compileSync (
`
What's the weather like?
`,
env
)
```
--------------------------------
### Workflow.compileSync
Source: https://context7.com/aaronrussell/agentflow/llms.txt
Compiles a Markdown-formatted workflow string into a Workflow instance that can be executed. The workflow is parsed, validated, and prepared for execution with the provided environment configuration.
```APIDOC
## Workflow.compileSync
### Description
Compiles a Markdown-formatted workflow string into a Workflow instance that can be executed. The workflow is parsed, validated, and prepared for execution with the provided environment configuration.
### Method
`Workflow.compileSync`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```typescript
import { Environment, Workflow } from '@agentflow/core'
import { openai } from '@ai-sdk/openai'
// Initialize environment with AI providers
const env = new Environment({
providers: {
openai
}
})
// Compile workflow from markdown string
const workflow = Workflow.compileSync(`
---
input:
topic:
type: text
message: "Enter a topic"
---
# Blog Writer
Write a short blog post about {topic}.
`, env)
console.log(workflow.title) // "Blog Writer"
console.log(workflow.meta) // { input: { topic: { type: 'text', message: '...' } } }
```
### Response
#### Success Response (200)
- **title** (string) - The title of the workflow.
- **meta** (object) - Metadata associated with the workflow, including input schema.
#### Response Example
```json
{
"title": "Blog Writer",
"meta": {
"input": {
"topic": {
"type": "text",
"message": "Enter a topic"
}
}
}
}
```
```
--------------------------------
### Compile and Run Agentflow Workflow in JavaScript
Source: https://github.com/aaronrussell/agentflow/blob/main/README.md
Use `@agentflow/core` to compile a Markdown-formatted workflow and control its execution. This includes initializing the environment, compiling the workflow, creating an execution instance, handling events like 'step' and 'complete', and running the workflow.
```typescript
import { Environment, Workflow } from '@agentflow/core'
// Initialize the environment
const env = new Environment({
providers: {
// configure AI providers
}
})
// Compile a workflow from markdown
const workflow = Workflow.compileSync(
`
Write a haiku about {topic}.
`,
env
)
// Create and run the execution
const ctrl = workflow.createExecution({
topic: { type: 'primitive', value: 'spring rain' }
})
// Handle execution events
ctrl.on('step', (step, event) => {
event.action?.then(({ result }) => console.log(result))
})
ctrl.on('complete', (output) => {
console.log('Done!\n', output)
})
// Run the workflow
await ctrl.runAll()
```
--------------------------------
### Fine-tune AI Generation with Options
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/ai-generations.md
Adjust AI model generation behavior using the `options` attribute in `` and `` actions. Options include `temperature`, `maxTokens`, `seed`, `stop`, `topP`, `topK`, `presencePenalty`, and `frequencyPenalty`.
```mdx
```
--------------------------------
### Configure Default AI Providers
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/ai-generations.md
Configure the default OpenAI and Anthropic providers in your `agentflow.config.js`. Ensure your `.env` file contains the necessary API keys.
```typescript
import { defineConfig } from '@agentflow/core'
import { openai } from '@ai-sdk/openai'
import { anthropic } from '@ai-sdk/anthropic'
export default defineConfig({
providers: {
openai,
anthropic,
}
})
```
--------------------------------
### Compile Workflow Sync
Source: https://context7.com/aaronrussell/agentflow/llms.txt
Compiles a Markdown-formatted workflow string into a Workflow instance. Ensure the Environment is initialized with necessary AI providers before compilation.
```typescript
import { Environment, Workflow } from '@agentflow/core'
import { openai } from '@ai-sdk/openai'
// Initialize environment with AI providers
const env = new Environment({
providers: {
openai
}
})
// Compile workflow from markdown string
const workflow = Workflow.compileSync(`
---
input:
topic:
type: text
message: "Enter a topic"
---
# Blog Writer
Write a short blog post about {topic}.
`, env)
console.log(workflow.title) // "Blog Writer"
console.log(workflow.meta) // { input: { topic: { type: 'text', message: '...' } } }
```
--------------------------------
### Execute Workflow and Monitor Events
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/javascript-api.md
Execute a compiled workflow step-by-step using an ExecutionController. Monitor progress with 'step', 'complete', and 'error' events. The controller allows for fine-grained control over execution.
```ts
// Create a new execution controller
const ctrl = workflow.createExecution({
// Optional: provide initial context values
name: { type: 'primitive', value: 'Joe Bloggs' }
})
// Step events are emitted at the start of each step
ctrl.on('step', (step, event, cursor) => {
// Each step event provides:
// - step: the current workflow step
// - event: contains the action promise and any streaming data
// - cursor: the current position in the workflow
console.log(`Executing step: ${cursor.toString()}`)
// If the step has an action, we can access its result
event.action?.then(({ result }) => {
console.log(result)
})
})
// Emitted when the workflow completes
ctrl.on('complete', (output) => {
console.log('Workflow completed:')
console.log(output)
})
// Emitted if an error occurs during execution
ctrl.on('error', (error) => {
console.error('Workflow error:', error)
})
// Start the workflow
await controller.runAll()
```
--------------------------------
### workflow.createExecution
Source: https://context7.com/aaronrussell/agentflow/llms.txt
Creates an ExecutionController for a compiled workflow, optionally accepting initial input values. The controller manages step-by-step execution and provides event-based monitoring of workflow progress.
```APIDOC
## workflow.createExecution
### Description
Creates an ExecutionController for a compiled workflow, optionally accepting initial input values. The controller manages step-by-step execution and provides event-based monitoring of workflow progress.
### Method
`workflow.createExecution(initialInput?: object)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **initialInput** (object) - Optional. Initial input values for the workflow execution.
### Request Example
```typescript
import { Environment, Workflow } from '@agentflow/core'
import { openai } from '@ai-sdk/openai'
const env = new Environment({ providers: { openai } })
const workflow = Workflow.compileSync(`
Write a haiku about {topic}.
`, env)
// Create execution with input values
const ctrl = workflow.createExecution({
topic: { type: 'primitive', value: 'spring rain' }
})
// Subscribe to step events
ctrl.on('step', (step, event, cursor) => {
console.log(`Step: ${cursor.toString()}`)
// Handle streaming response
if (event.stream) {
(async () => {
for await (const chunk of event.stream) {
process.stdout.write(chunk)
}
})()
}
// Access final action result
event.action?.then(({ result }) => {
console.log('\nResult:', result.value)
})
})
ctrl.on('complete', (output) => {
console.log('Final output:\n', output)
})
ctrl.on('error', (error) => {
console.error('Error:', error)
})
// Run entire workflow
await ctrl.runAll()
```
### Response
#### Success Response (200)
- **ExecutionController** (object) - An instance of ExecutionController to manage workflow execution.
#### Response Example
```json
{
"status": "running",
"currentStep": "step-1"
}
```
```
--------------------------------
### ExecutionController.runNext
Source: https://context7.com/aaronrussell/agentflow/llms.txt
Executes the next single action in the workflow, providing fine-grained control over execution. Returns a Promise resolving to the ExecutionCursor position after the step completes.
```APIDOC
## ExecutionController.runNext
### Description
Executes the next single action in the workflow, providing fine-grained control over execution. Returns a Promise resolving to the ExecutionCursor position after the step completes.
### Method
`ctrl.runNext()`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```typescript
import { Environment, Workflow, ExecutionStatus } from '@agentflow/core'
import { openai } from '@ai-sdk/openai'
const env = new Environment({ providers: { openai } })
const workflow = Workflow.compileSync(`
Write a joke.
Now explain why it's funny.
`, env)
const ctrl = workflow.createExecution()
// Execute steps one at a time
while (ctrl.status !== ExecutionStatus.Completed && ctrl.status !== ExecutionStatus.Error) {
const cursor = await ctrl.runNext()
console.log(`Completed step at: ${cursor.toString()}`)
// Access state after each step
const results = ctrl.state.getContext(cursor)
console.log('Current context:', results)
}
console.log('Final output:', ctrl.getFinalOutput())
```
### Response
#### Success Response (200)
- **ExecutionCursor** (object) - The cursor position after the step completes.
#### Response Example
```json
{
"step": "step-1",
"path": []
}
```
```
--------------------------------
### List available workflows
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/cli.md
Display all available workflows in the current Agentflow project. This command scans the project's workflows directory and lists workflows by their IDs and titles.
```sh
aflow list
```
```sh
aflow ls
```
--------------------------------
### Capture User Input in Agentflow Workflow
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/input-data.md
Utilize the 'input' field in the frontmatter to prompt users for data at runtime. This makes workflows more reusable by allowing dynamic input, such as a quote for translation.
```mdx
---
data:
langs:
- Spanish
- Portugese
- French
- German
input:
quote:
type: text
message: "Enter a quote to translate"
---
Translate "{ quote }" into { langs[$.index] }
```
--------------------------------
### Looping for Character Creation in AgentFlow
Source: https://github.com/aaronrussell/agentflow/blob/main/examples/flows/story-gen.mdx
This snippet demonstrates how to use the `` component to generate multiple characters based on a given theme. The loop continues until a specified condition is met.
```agentflow
Create a character for a story with the theme: {theme}
Write a concise character card that includes name, gender, age and character traits.
```
--------------------------------
### Configure Agentflow Project
Source: https://context7.com/aaronrussell/agentflow/llms.txt
Configuration file for Agentflow projects. Defines AI providers, tools, and plugins. Placed in the project root.
```javascript
// agentflow.config.js
import { defineConfig } from '@agentflow/core'
import { openai, createOpenAI } from '@ai-sdk/openai'
import { anthropic } from '@ai-sdk/anthropic'
import { ollama } from 'ollama-ai-provider'
import { createFileSystemTools } from '@agentflow/tools'
export default defineConfig({
// Configure AI providers
providers: {
openai,
anthropic,
ollama,
// Custom OpenAI-compatible provider
together: createOpenAI({
apiKey: process.env.TOGETHER_API_KEY,
baseURL: 'https://api.together.xyz/v1',
compatibility: 'compatible'
})
},
// Register tools
tools: [
...Object.values(createFileSystemTools('./output'))
],
// Plugins extend the environment
plugins: [
(builder) => {
// Custom initialization logic
}
]
})
```
--------------------------------
### Environment Variables for API Keys
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/configuration.md
Store sensitive API keys and other configuration values in a `.env` file in your project's root directory. These variables are automatically loaded and accessible via `process.env` in your configuration file.
```dotenv
# .env
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-...
```
--------------------------------
### Create Workflow Execution
Source: https://context7.com/aaronrussell/agentflow/llms.txt
Creates an ExecutionController for a compiled workflow, allowing for step-by-step execution and event monitoring. Initial input values can be provided during creation.
```typescript
import { Environment, Workflow } from '@agentflow/core'
import { openai } from '@ai-sdk/openai'
const env = new Environment({ providers: { openai } })
const workflow = Workflow.compileSync(
Write a haiku about {topic}.
, env)
// Create execution with input values
const ctrl = workflow.createExecution({
topic: { type: 'primitive', value: 'spring rain' }
})
// Subscribe to step events
ctrl.on('step', (step, event, cursor) => {
console.log(`Step: ${cursor.toString()}`)
// Handle streaming response
if (event.stream) {
(async () => {
for await (const chunk of event.stream) {
process.stdout.write(chunk)
}
})()
}
// Access final action result
event.action?.then(({ result }) => {
console.log('\nResult:', result.value)
})
})
ctrl.on('complete', (output) => {
console.log('Final output:\n', output)
})
ctrl.on('error', (error) => {
console.error('Error:', error)
})
// Run entire workflow
await ctrl.runAll()
```
--------------------------------
### Looping with Agentflow's action
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/control-flow.md
Use the `` action to repeat a block of workflow content until a specified condition is met. The `as` attribute defines the variable name for the loop's results, and `until` provides the boolean condition to break the loop. The `provide` attribute can pass data to the child scope of the loop.
```mdx
new Date().getFullYear()}
provide={{ year: 2000 + $.index }}>
Write an interesting fact about the year: {year}
```
--------------------------------
### Pause and Rewind Execution with ExecutionController
Source: https://context7.com/aaronrussell/agentflow/llms.txt
Demonstrates pausing a workflow execution and rewinding to a specific cursor point using `ExecutionController.pause()` and `ExecutionController.rewindTo()`. Useful for implementing retry logic or interactive debugging.
```typescript
import { Environment, Workflow, ExecutionCursor } from '@agentflow/core'
import { openai } from '@ai-sdk/openai'
const env = new Environment({ providers: { openai } })
const workflow = Workflow.compileSync (
`
Generate a random number between 1 and 10.
Double the number: {number}
`,
env
)
const ctrl = workflow.createExecution()
ctrl.on('step', async (step, event, cursor) => {
// Pause after first step
if (cursor.toString() === '/0.0.1') {
ctrl.pause()
console.log('Paused at:', cursor.toString())
// Rewind to beginning
ctrl.rewindTo('/0.0.0')
console.log('Rewound to start')
}
})
await ctrl.runAll()
```
--------------------------------
### Review Joke and Score with Llama3.1
Source: https://github.com/aaronrussell/agentflow/blob/main/examples/flows/joke-review.mdx
Use the GenObject component to review the generated joke and provide a score. Define the output schema for the review and score using Zod.
```agentflow
```
--------------------------------
### Execute a specific workflow
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/cli.md
Execute a specified workflow by name. The command loads and runs the workflow, streams progress and outputs to the console, and saves results to the `/outputs` folder.
```sh
aflow exec
```
```sh
aflow x
```
--------------------------------
### Configure OpenAI Provider in agentflow.config.js
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/getting-started.md
Configure AI providers, such as OpenAI, in the agentflow.config.js file. Ensure your API key is set in the .env file.
```typescript
import { defineConfig } from '@agentflow/core'
import { createOpenAI } from '@ai-sdk/openai'
export default defineConfig({
providers: {
openai: createOpenAI({
apiKey: process.env.MY_OPENAI_KEY
})
}
})
```
--------------------------------
### Basic Expression Usage in MDX
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/workflow-structure.md
Demonstrates text, flow, and attribute expressions within an MDX context. Text expressions are embedded directly in strings, flow expressions are multi-line blocks, and attribute expressions are used in component props.
```mdx
This is a text expression: Hello {name}!
{
// this is a flow expression
instructions.join('\n').map(str => `- ${str}`)
}
```
--------------------------------
### Execute Next Workflow Step
Source: https://context7.com/aaronrussell/agentflow/llms.txt
Executes the next single action in the workflow, offering granular control. This method returns a Promise that resolves with the ExecutionCursor position after the step completes.
```typescript
import { Environment, Workflow, ExecutionStatus } from '@agentflow/core'
import { openai } from '@ai-sdk/openai'
const env = new Environment({ providers: { openai } })
const workflow = Workflow.compileSync(
Write a joke.
Now explain why it's funny.
, env)
const ctrl = workflow.createExecution()
// Execute steps one at a time
while (ctrl.status !== ExecutionStatus.Completed && ctrl.status !== ExecutionStatus.Error) {
const cursor = await ctrl.runNext()
console.log(`Completed step at: ${cursor.toString()}`)
// Access state after each step
const results = ctrl.state.getContext(cursor)
console.log('Current context:', results)
}
console.log('Final output:', ctrl.getFinalOutput())
```
--------------------------------
### Implement Loops with Loop Action
Source: https://context7.com/aaronrussell/agentflow/llms.txt
Utilizes the `Loop` action to repeatedly execute a block of workflow content until a specified condition is met. Provides access to loop state via `$.index`, `$.self`, and `$.last`.
```mdx
---
data:
languages:
- Spanish
- French
- German
- Japanese
input:
content:
type: text
message: "Enter text to translate"
---
```
--------------------------------
### Generate Text with GenText Action
Source: https://context7.com/aaronrussell/agentflow/llms.txt
Uses the `GenText` action to generate text content with AI models. It takes preceding context as input and stores the output in a specified variable. Supports custom roles and generation options.
```mdx
---
input:
topic:
type: text
message: "Enter a topic for the blog post"
---
# Blog Generator
Write a comprehensive blog post about {topic}. Include an introduction,
three main points, and a conclusion.
---
Now create a catchy social media summary of the article:
{article}
```
--------------------------------
### Generate a Joke with Llama3.1
Source: https://github.com/aaronrussell/agentflow/blob/main/examples/flows/joke-review.mdx
Use the GenText component to generate a one-liner joke. Specify the desired output variable name and the model to use.
```agentflow
```
--------------------------------
### Generate Conference Speakers List
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/ai-generations.md
Use the GenObject action to scrape a webpage and generate a structured array of conference speakers based on a Zod schema. Ensure the schema accurately describes the desired output properties.
```mdx
Scrape the following web page and create a list of conference speakers:
{url}
```
--------------------------------
### Generate Scientific Abstract with GenText
Source: https://github.com/aaronrussell/agentflow/blob/main/docs/guide/ai-generations.md
Use the GenText action to generate a scientific abstract based on provided research. Specify the output variable name with 'as' and the AI model with 'model'.
```mdx
Based on the following research paper, create a concise and detailed
scientific abstract that summarises the research findings:
{research}
```