# n8n Workflow Generator

Generate n8n workflows from natural language using Claude AI.

This custom n8n node leverages Claude Sonnet 4.5's structured outputs to transform plain English descriptions into fully functional n8n workflows. Simply describe what you want your workflow to do, and the AI will generate the complete workflow JSON with proper nodes, connections, and parameters.

## Features

- **Natural Language to Workflow**: Describe workflows in plain English
- **Claude Sonnet 4.5 Integration**: Uses structured outputs for reliable JSON generation
- **Automatic Validation**: Validates generated workflows before creation
- **Smart Node Selection**: Uses a curated library of common n8n nodes
- **Error Handling**: Clear error messages and automatic retry logic
- **Flexible Configuration**: Control temperature, tokens, and other AI parameters

## Supported Nodes

The node currently supports these common n8n node types:

- **Webhook**: HTTP webhook triggers
- **HTTP Request**: API calls and HTTP requests
- **IF**: Conditional logic and branching
- **Code**: Custom JavaScript execution
- **Set**: Data transformation and field mapping
- **Slack**: Slack message integration
- **Merge**: Combine data from multiple branches
- **Split In Batches**: Process items in batches
- **Wait**: Pause workflow execution
- **Respond to Webhook**: Return responses to webhook callers

## Prerequisites

- n8n instance (self-hosted or cloud) with API access enabled
- Anthropic API key (Claude access)
- Node.js 18+ (for development)

## Installation

### Option 1: Install from npm (when published)

```bash
npm install n8n-nodes-workflow-generator
```

### Option 2: Install from source

1. Clone this repository:
```bash
git clone https://github.com/yourusername/n8n-nodes-workflow-generator.git
cd n8n-nodes-workflow-generator
```

2. Install dependencies:
```bash
npm install
```

3. Build the node:
```bash
npm run build
```

4. Link to your n8n installation:
```bash
npm link
cd ~/.n8n/custom
npm link n8n-nodes-workflow-generator
```

5. Restart n8n:
```bash
n8n start
```

## Setup

### 1. Enable n8n API

For self-hosted n8n:

```bash
# Add to your environment variables
export N8N_API_KEY=your-api-key-here
```

Or in your n8n settings (Settings > n8n API), generate an API key.

For n8n Cloud:
- Go to Settings > n8n API
- Generate a new API key

### 2. Get Claude API Key

1. Sign up at [console.anthropic.com](https://console.anthropic.com/)
2. Generate an API key from the API Keys section
3. Copy the key (starts with `sk-ant-api03-`)

### 3. Configure Credentials in n8n

1. In n8n, go to **Settings > Credentials**
2. Add **Claude API** credentials:
   - Click "Add Credential"
   - Search for "Claude API"
   - Enter your Anthropic API key
   - Test and save

3. Add **n8n API** credentials:
   - Click "Add Credential"
   - Search for "n8n API"
   - Enter your n8n API key
   - Test and save

## Usage

### Basic Example

1. Create a new workflow in n8n
2. Add the **Workflow Generator** node
3. Connect it to a trigger (e.g., Manual Trigger)
4. Select your Claude and n8n API credentials
5. Enter a workflow description:

```
Create a workflow that:
1. Triggers on webhook POST to /order-notification
2. Fetches customer data from https://api.example.com/customers
3. Checks if order total is greater than 100
4. If yes, sends notification to #premium-orders Slack channel
5. If no, sends to #standard-orders channel
6. Returns success response to webhook
```

6. Set your n8n instance URL (e.g., `https://your-n8n.com` or `http://localhost:5678`)
7. Execute the workflow
8. The generated workflow will be created in your n8n instance

### Advanced Options

- **Include Comments**: Add explanatory comments in Code nodes (default: true)
- **Auto Activate**: Automatically activate the workflow after creation (default: false)
- **Max Tokens**: Control Claude response length (default: 4096)
- **Temperature**: Adjust creativity vs determinism (default: 0.3, range: 0-1)

## Examples

### Example 1: Simple Webhook to Slack

**Input:**
```
Webhook that receives POST requests and sends the data to #notifications Slack channel
```

**Generated Workflow:**
- Webhook node (POST endpoint)
- Slack node (sends to #notifications)
- Proper connection between nodes

### Example 2: API Integration with Conditional Logic

**Input:**
```
1. Webhook trigger
2. Fetch user data from https://api.myapp.com/users/{{$json.userId}}
3. If user.status is "premium", send to #premium-support
4. Otherwise send to #standard-support
5. Respond to webhook with success message
```

**Generated Workflow:**
- Webhook trigger node
- HTTP Request node to fetch user data
- IF node checking status field
- Two Slack nodes for different channels
- Respond to Webhook node

### Example 3: Data Processing Pipeline

**Input:**
```
Process incoming orders:
1. Webhook receives order data
2. Transform data to add timestamp and order_id
3. Split into batches of 10
4. For each batch, send to https://api.warehouse.com/orders
5. Wait 2 seconds between batches
```

**Generated Workflow:**
- Webhook node
- Set node for data transformation
- Split In Batches node
- HTTP Request node
- Wait node
- Proper loop connections

## Validation

The node performs multi-level validation:

1. **Schema Validation**: Ensures JSON matches n8n workflow structure (Zod)
2. **Node Validation**: Checks node types, names, and IDs are valid
3. **Connection Validation**: Verifies all connections reference existing nodes
4. **Parameter Validation**: Confirms required parameters are present
5. **Structure Validation**: Warns about missing triggers or disconnected nodes

## Error Handling

The node provides clear error messages for common issues:

- **Invalid API Key**: Check your Claude or n8n credentials
- **Rate Limit Exceeded**: Wait and retry (429 error)
- **Invalid Request**: Simplify or clarify your workflow description
- **Validation Errors**: Lists specific issues with generated workflow
- **Connection Failed**: Verify n8n instance URL and API access

## Development

### Project Structure

```
n8n-nodes-workflow-generator/
├── credentials/
│   ├── ClaudeApi.credentials.ts
│   └── N8nApi.credentials.ts
├── nodes/
│   └── WorkflowGenerator/
│       ├── WorkflowGenerator.node.ts
│       ├── schemas/
│       │   ├── workflow-schema.ts
│       │   └── validation.ts
│       ├── services/
│       │   ├── claude-service.ts
│       │   ├── n8n-service.ts
│       │   └── schema-library.ts
│       └── utils/
│           └── error-handler.ts
├── test/
│   └── unit/
│       └── schema-library.test.ts
├── package.json
├── tsconfig.json
└── README.md
```

### Running Tests

```bash
npm test
```

### Running Tests with Coverage

```bash
npm run test:coverage
```

### Linting

```bash
npm run lint
npm run lint:fix
```

### Building

```bash
npm run build
```

### Development Mode (watch)

```bash
npm run dev
```

## Limitations

- Currently supports 10 common node types (extensible)
- No RAG-based schema retrieval (MVP uses curated library)
- No real-time canvas visualization (workflows created via API)
- Credentials must be manually configured in n8n
- Complex workflows may require multiple iterations

## Roadmap

- [ ] Add support for 50+ additional node types
- [ ] Implement RAG-based schema retrieval for all n8n nodes
- [ ] Add workflow template library
- [ ] Support for workflow updates (not just creation)
- [ ] Real-time streaming generation with progress updates
- [ ] Automatic credential detection and setup guidance
- [ ] Workflow optimization suggestions
- [ ] Support for sub-workflows
- [ ] Integration with n8n's AI Workflow Builder

## Contributing

Contributions are welcome! Please follow these steps:

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Run tests (`npm test`)
5. Run linter (`npm run lint:fix`)
6. Commit your changes (`git commit -m 'Add amazing feature'`)
7. Push to the branch (`git push origin feature/amazing-feature`)
8. Open a Pull Request

## Troubleshooting

### Node doesn't appear in n8n

- Ensure the node is properly built (`npm run build`)
- Check that n8n can find the node package
- Restart n8n after installation
- Check n8n logs for errors

### Claude API errors

- Verify your API key is correct
- Check you have sufficient credits
- Ensure you're using the correct model name
- Try reducing max_tokens if hitting limits

### n8n API errors

- Confirm API is enabled in n8n settings
- Verify your n8n API key is valid
- Check the instance URL is correct (include protocol)
- Ensure your n8n user has permission to create workflows

### Generated workflows are invalid

- Try simplifying your description
- Be more specific about node parameters
- Check the validation errors in the output
- Report issues with example descriptions

## License

MIT

## Credits

Built with:
- [n8n](https://n8n.io/) - Workflow automation platform
- [Claude (Anthropic)](https://www.anthropic.com/) - AI language model
- [Zod](https://github.com/colinhacks/zod) - TypeScript schema validation

## Support

- GitHub Issues: [Report bugs or request features](https://github.com/yourusername/n8n-nodes-workflow-generator/issues)
- n8n Community: [n8n Community Forum](https://community.n8n.io/)
- Documentation: [n8n Documentation](https://docs.n8n.io/)

## Author

Your Name - [@yourtwitter](https://twitter.com/yourtwitter)

Project Link: [https://github.com/yourusername/n8n-nodes-workflow-generator](https://github.com/yourusername/n8n-nodes-workflow-generator)
