# n8n Integration

This document provides detailed instructions on how to integrate multiple MaiAgent AI assistants using the n8n workflow automation tool. Through n8n, you can easily create workflows to achieve multi-assistant integration effects.

## Prerequisites

1. Registered n8n account
2. Valid MaiAgent API key
3. Completed AI assistant setup with assistant ID
4. Basic understanding of APIs and workflows

## Basic Concepts

MaiAgent API provides functionality to interact with AI assistants. We will use n8n to automate these processes and integrate multiple AI assistants.

## Workflow Examples

### Example 1: Creating a Simple AI Assistant Chain Workflow

This workflow will receive user chat messages and process them sequentially through two different AI assistants, forming a chained processing flow.

### Step 1: Set Up Chat Trigger Node

1. Add a "When chat message received" node in the n8n workflow
2. This will serve as the workflow's starting point, triggered when users send messages

### Step 2: Set Up First HTTP Request Node

1. Add an "HTTP Request" node, connected to the "When chat message received" node
2. Configure the following settings:

   * Method: POST
   * URL: `https://api.maiagent.ai/api/v1/chatbots/{id}/completions/`
   * id: Assistant ID
   * Authentication: Headers
   * Headers: Add `Authorization` header with value `Api-Key YOUR_API_KEY` (replace with your actual API key)
   * Request Content Type: JSON
   * Request Content:

   ```json
   {
     "conversation": "",
     "message": {
       "content": "{{ $json.chatInput }}",
       "attachments": []
     },
     "is_streaming": false
   }
   ```

### Step 3: Set Up Second HTTP Request Node

1. Add another "HTTP Request" node, connected to the first HTTP Request node
2. Configure the following settings:

   * Method: POST
   * URL: `https://api.maiagent.ai/api/v1/chatbots/{id}/completions/`
   * id: Assistant ID
   * Authentication: Headers
   * Headers: Add `Authorization` header with value `Api-Key YOUR_API_KEY`
   * Request Content Type: JSON
   * Request Content:

   ```json
   {
     "conversation": "",
     "message": {
       "content": {{ JSON.stringify($json.content) }},
       "attachments": []
     },
     "is_streaming": false
   }
   ```

This setup passes the response from the first AI assistant as input to the second AI assistant, achieving chained processing.

## Integration Scenarios

### Scenario 1: Multi-Expert Opinion Aggregation

Gather perspectives from different specialized assistants and aggregate them into a comprehensive response:

1. Legal assistant analyzes legal issues
2. Technical assistant analyzes technical feasibility
3. Business assistant analyzes business impact
4. Final aggregation assistant provides comprehensive recommendations

### Scenario 2: Translation Improvement Process

1. Initial assistant performs translation
2. Secondary assistant checks translation quality
3. Final assistant polishes and optimizes expression

### Scenario 3: Content Generation and Review Workflow

1. Creative assistant generates content
2. Review assistant checks accuracy and appropriateness
3. Editor assistant polishes and optimizes formatting

## Advanced Application: Building Multi-Round Conversation Workflow

### Example 2: Using Conversation ID for Multi-Round Dialogues

### Step 1: Create Conversation Initialization Node

1. Add an HTTP Request node for initial conversation
2. Configure similar to previous settings, but store conversation ID:

```jsx
// Store conversation ID for subsequent use
const conversationId = $json.conversationId;
$workflow.vars.conversationId = conversationId;

return {
  json: {
    ...$json,
    savedConversationId: conversationId
  }
};
```

### Step 2: Set Up Subsequent Conversation Node

1. Add new HTTP Request node, configured to use saved conversation ID:

   ```json
   {
     "conversation": "{{$workflow.vars.conversationId}}",
     "message": {
       "content": "Continue from the previous question, please provide more details"
     },
     "is_streaming": false
   }
   ```

## Troubleshooting

Common issues and solutions:

1. **API Authentication Error**: Ensure correct API key format, including "Api-Key" prefix
2. **Request Timeout**: Increase HTTP request node timeout for complex queries
3. **Streaming Mode Handling**: Use `is_streaming: true` to change response mode to streaming

## Conclusion

Through n8n, you can easily integrate and automate multiple MaiAgent AI assistants, creating powerful AI workflows that enable different specialized assistants to collaborate on complex tasks. From simple conversations to complex multi-assistant chain processing, n8n provides flexible and powerful automation capabilities.

## Appendix: Complete Workflow JSON

Below is the complete workflow JSON configuration for Example 1, which you can directly import into n8n:

```json
{
  "name": "My workflow",
  "nodes": [
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.maiagent.ai/api/v1/chatbots/{id}/completions/",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Api-Key YOUR_API_KEY"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"conversation\": \"\",\n  \"message\": {\n    \"content\": \"{{ $json.chatInput }}\",\n    \"attachments\": []\n  },\n  \"is_streaming\": false\n} ",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        -240,
        -180
      ],
      "id": "dfc1157d-7569-4caf-8b1d-256aa74515ac",
      "name": "HTTP Request"
    },
    {
      "parameters": {
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.chatTrigger",
      "typeVersion": 1.1,
      "position": [
        -500,
        -180
      ],
      "id": "82748324-6021-4660-98ef-481bdfc73569",
      "name": "When chat message received",
      "webhookId": "5f833c90-a7f9-4c66-8fff-cecc3568cd2a"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.maiagent.ai/api/v1/chatbots/{id}/completions/",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Api-Key YOUR_API_KEY"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"conversation\": \"\",\n  \"message\": {\n    \"content\": {{ JSON.stringify($json.content) }},\n    \"attachments\": []\n  },\n  \"is_streaming\": false\n} ",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        20,
        -180
      ],
      "id": "f0a80b1f-1bed-491b-bc5e-cddb87ccd2d5",
      "name": "HTTP Request1"
    }
  ],
  "pinData": {},
  "connections": {
    "When chat message received": {
      "main": [
        [
          {
            "node": "HTTP Request",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "HTTP Request": {
      "main": [
        [
          {
            "node": "HTTP Request1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "HTTP Request1": {
      "main": [
        []
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "c914db70-985a-48d0-a1ca-47c2a0d4f244",
  "meta": {
    "instanceId": "2eb51fcaa84ba34149e7fc138f6cac3b20a0038764b284579d6ceaea90b669f8"
  },
  "id": "pvMcKA5hHmwAKuZT",
  "tags": []
}
```

## Import Result

<figure><img src="https://3415477754-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNBTi475lqozGpB7xObpE%2Fuploads%2Fgit-blob-ee0995ddc1dd81aa82909b569b9c36b85566d08c%2F%E6%88%AA%E5%9C%96%202025-03-10%20%E6%99%9A%E4%B8%8A7.45.13.png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

***

For any questions, please refer to [MaiAgent's Official API Documentation](https://docs.maiagent.ai/api) or [n8n's Official Documentation](https://docs.n8n.io/).
