Building Scheduled Workflows in Astreus

Astreus enables developers to build time-based automated workflows with simple schedule strings and dependency management. This guide shows you how to create workflows that run automatically on your schedule.

## Quick Start

Get started by cloning the example repository or installing the package:

```bash
git clone https://github.com/astreus-ai/scheduled-workflows
cd scheduled-workflows
npm install
```

Or install directly:

```bash
npm install @astreus-ai/astreus
```

Create a `.env` file with your configuration:

```
OPENAI_API_KEY=sk-your-openai-api-key-here
DB_URL=sqlite://./astreus.db
NODE_ENV=development
```

The database persists workflow state, ensuring tasks continue after restarts.

## Creating Your First Agent

Every workflow starts with an agent that handles the AI operations:

```typescript
const agent = await Agent.create({
name: 'ContentAgent',
model: 'gpt-4o',
systemPrompt: 'You are a content creation specialist.'
});
```

The agent encapsulates the AI model and behavior. You can create multiple agents with different capabilities for different tasks.

## Building a Workflow Graph

Workflows are represented as graphs with nodes and dependencies:

```typescript
const graph = new Graph({
name: 'Quick Test Pipeline',
description: 'Test automated workflow with seconds interval',
maxConcurrency: 2
}, agent);
```

The graph manages execution order, concurrency limits, and task dependencies. Setting maxConcurrency prevents overwhelming your API limits or system resources.

## Adding Scheduled Tasks

Add task nodes with schedules and dependencies:

```typescript
const researchNode = graph.addTaskNode({
name: 'Content Research',
prompt: 'Research trending topics in AI and technology...',
schedule: 'after:5s'
});

const creationNode = graph.addTaskNode({
name: 'Content Creation',
prompt: 'Create a blog post summary...',
schedule: 'after:10s',
dependsOn: ['Content Research']
});
```

The `dependsOn` array ensures tasks execute in the correct order. If a dependency fails, dependent tasks won't run.

## Schedule Format Patterns

Astreus uses human-readable schedule strings:

- `daily@06:00` - Execute daily at 6 AM
- `weekly@monday@09:00` - Weekly on Monday at 9 AM
- `monthly@15@10:00` - 15th of each month at 10 AM
- `after:5s` - Delay 5 seconds (testing)
- `after:2h` - Delay 2 hours
- `every:30m` - Repeat every 30 minutes

Use short intervals like `after:5s` during development for rapid testing, then switch to production schedules.

## Running the Workflow

Execute your workflow with a simple call:

```typescript
const result = await graph.run();
```

The run method returns detailed execution results:

```typescript
{
success: true,
completedNodes: 2,
failedNodes: 0,
duration: 15432,
results: {
'node-id-1': { output: '...' },
'node-id-2': { output: '...' }
},
errors: []
}
```

You get full visibility into which tasks succeeded, how long they took, and what outputs they produced.

## Multi-Step Content Pipeline

Here's a practical example that chains multiple tasks:

```typescript
const agent = await Agent.create({
name: 'ContentAgent',
model: 'gpt-4o',
systemPrompt: 'You are a content creation specialist.'
});

const graph = new Graph({
name: 'Daily Content Pipeline',
description: 'Automated content research and creation',
maxConcurrency: 2
}, agent);

const researchNode = graph.addTaskNode({
name: 'Topic Research',
prompt: 'Research trending topics in technology',
schedule: 'daily@07:00'
});

const draftNode = graph.addTaskNode({
name: 'Draft Creation',
prompt: 'Create a blog post draft from research',
schedule: 'daily@08:00',
dependsOn: ['Topic Research']
});

const optimizeNode = graph.addTaskNode({
name: 'SEO Optimization',
prompt: 'Optimize draft for SEO',
schedule: 'daily@09:00',
dependsOn: ['Draft Creation']
});

const result = await graph.run();
```

This pipeline researches topics at 7 AM, creates drafts at 8 AM, and optimizes them at 9 AM, all automatically.

## Testing with Short Intervals

Don't wait hours between test runs. Use short schedules during development:

```typescript
const testGraph = new Graph({
name: 'Quick Test Pipeline',
description: 'Test automated workflow with seconds interval',
maxConcurrency: 2
}, agent);

const testNode = graph.addTaskNode({
name: 'Quick Test',
prompt: 'Test task execution',
schedule: 'after:5s'
});

const result = await testGraph.run();
```

Using `after:5s` lets you iterate quickly and catch issues early.

## Handling Execution Results

Process workflow results to integrate with other systems:

```typescript
const result = await graph.run();

if (result.success) {
console.log(`Completed ${result.completedNodes} tasks in ${result.duration}ms`);

// Access individual task outputs
for (const [nodeId, output] of Object.entries(result.results)) {
console.log(`${nodeId}:`, output);
}
} else {
console.error(`Failed tasks: ${result.failedNodes}`);
result.errors.forEach(error => {
console.error(`Error in ${error.nodeId}:`, error.message);
});
}
```

The results object gives you everything you need to monitor, debug, and respond to workflow outcomes.

## Production Deployment

Deploy your workflow as a long-running process:

```typescript
import { Agent, Graph } from '@astreus-ai/astreus';

async function main() {
const agent = await Agent.create({
name: 'ProductionAgent',
model: 'gpt-4o',
systemPrompt: 'You are a production workflow agent.'
});

const graph = new Graph({
name: 'Production Pipeline',
description: 'Automated daily workflows',
maxConcurrency: 3
}, agent);

// Add your scheduled tasks
graph.addTaskNode({
name: 'Daily Report',
prompt: 'Generate daily summary report',
schedule: 'daily@08:00'
});

// Run and keep process alive
await graph.run();

process.on('SIGTERM', async () => {
console.log('Shutting down gracefully...');
process.exit(0);
});
}

main().catch(console.error);
```

This setup ensures your workflows continue running and handle shutdown signals gracefully.

## Best Practices

Follow these guidelines for reliable workflows:

- Start with `after:5s` schedules during development for rapid testing
- Use descriptive names for nodes to make debugging easier
- Set appropriate maxConcurrency limits to avoid overwhelming APIs
- Always check result.success before processing outputs
- Use dependsOn to enforce correct task ordering
- Store sensitive configuration in environment variables
- Monitor result.duration to optimize performance

## Complete Example

Explore the full implementation at https://github.com/astreus-ai/scheduled-workflows. The repository includes working examples, additional patterns, and production-ready configurations.

## Next Steps

Now you can build automated workflows that run on your schedule. Try creating a daily report generator, weekly content summarizer, or hourly data processor. The Astreus API handles the complexity of timing and execution while you focus on the tasks themselves.

This experiment is written for Astreus v0.5.37. Please ensure you are using a compatible version.