Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIAi2 WildChat-4.8M (AI2)

help me build AI agents on n8n: Creating a personal AI assistant using open-source…

  1. User

    help me build AI agents on n8n: Creating a personal AI assistant using open-source models like Queen enables users to automate tasks such as sending emails and managing schedules. This approach simplifies communication and enhances productivity through AI-driven workflows. The video demonstrates how to leverage AI agents for internet searches, allowing users to obtain real-time information efficiently. This enhances the utility of personal assistants. Integrating multiple AI agents, such as calendar and email agents, allows for seamless scheduling and communication. This showcases the versatility of AI in managing personal tasks. The tutorial emphasizes the importance of using automation tools like NN for building AI agents. This makes it accessible for users with little to no coding experience. Creating a bot on the platform is straightforward and requires a unique name and username. This setup allows for seamless interaction via text and voice messages. Setting up the bot involves obtaining an API token, facilitating the connection to the platform for interaction. This token is essential for the bot's functionalities. The switch module is created to differentiate between voice and text inputs, ensuring the AI can effectively process and respond to various message types. This categorization is crucial for accurate communication. Integrating an AI agent allows for dynamic conversations, utilizing memory for context and tools for executing tasks. The selected AI model significantly impacts the bot's performance. Connecting your API key to your AI model allows for enhanced functionality and integration. This setup is essential for utilizing various AI tools and models effectively. To find compatible models, navigate to the models section and use filters to identify which tools can be integrated with your AI agents. This ensures optimal performance. Adding memory to your AI agent is crucial for context retention. Configuring memory settings allows the agent to recall past interactions for more coherent responses. Integrating tools such as email and calendar agents enhances the capabilities of your AI workflows. These tools streamline communication and scheduling tasks effectively. Integrating a personal AI assistant requires setting up multiple agents and defining their roles effectively. This video outlines how to configure agents for specific tasks using a JSON format. The importance of defining agent roles ensures efficient task delegation and appropriate tool selection based on user requests. This enhances the overall functionality of the AI assistant. Utilizing system messages is crucial for instructing agents on how to handle tasks and queries. This helps maintain clarity in communication between the user and the AI. Error handling mechanisms, such as prompting users for missing information, are essential for improving user experience. This ensures that the agent can maintain a smooth workflow. The video discusses the development of an AI email agent that dynamically retrieves and sends email information based on user inputs. This system enhances personalization and efficiency in email management tasks. The video explains how to utilize the 'from AI' function to retrieve variable email components like sender, subject, and message body. This allows for tailored email interactions. It also details setting up API access through the Google Cloud console, emphasizing the importance of proper authentication for seamless operation of the email agent. The tutorial highlights the creation of different agents, such as a calendar agent, demonstrating the versatility of the AI in handling various tasks beyond email management. Implementing AI agents can streamline tasks and enhance productivity. By connecting multiple agents, users can automate processes like sending emails and managing contacts efficiently. Setting up success and error fields helps AI understand task outcomes. This feedback mechanism is crucial for troubleshooting and ensuring smooth operation of workflows. The contact agent allows users to add or update contacts seamlessly. Utilizing a table structure simplifies the process of managing contact information effectively. Combining various AI tools amplifies their capabilities. For instance, sending personalized emails requires integrating internet searches and contact lists, showcasing AI's potential in complex tasks.

  2. Assistant

    Certainly! To build AI agents on n8n that function as a personal AI assistant — integrating email, calendar, contacts, and internet search — while using open-source or cloud AI models like Queen, here’s a structured approach based on your description and best practices.


    Step-by-step Guide to Building AI Agents on n8n


    1. Platform Setup

    • Sign up/register on n8n.cloud or self-host n8n.
    • Create a new workflow which will be your AI assistant bot.

    2. Bot Setup

    • Create a bot entity with a unique name and username.
    • Obtain the API token from the platform you are integrating with (e.g., Telegram, Slack, WhatsApp, or native n8n webhook).
    • Configure the Webhook Trigger node in n8n to receive messages (both text and voice input possible).

    3. Input Differentiation

    • Use the Switch node to differentiate between voice and text input.
      • For voice, transcribe audio input to text (using speech-to-text AI tool, e.g., OpenAI Whisper, or Google Speech API).
      • For text input, directly pass it forward.

    4. Integrate AI Model

    • Connect to your AI model like Queen (open-source) or cloud models (OpenAI GPT, Hugging Face, etc.).
    • Store your API Key securely in n8n Credentials.

    Use the HTTP Request node or dedicated AI node (if available) to send the user prompt to the AI.


    5. Memory & Context

    • Add memory capability by using n8n’s Set node and Database node (e.g., PostgreSQL, SQLite), or n8n’s native data storage, to store past conversation.
    • Configure memory logic:
      • Retrieve past interactions on each message request.
      • Append new messages to memory after response.

    6. Multiple AI Agents

    Create multiple AI agents specialized for different tasks—e.g.:

    • Email Agent

      • Use Google Cloud APIs (Gmail API) with OAuth.
      • Send and receive emails dynamically.
      • Use 'from AI' function to extract sender, subject, body from user query.
    • Calendar Agent

      • Connect to Google Calendar API or Microsoft Outlook Calendar API.
      • Add/update events based on AI instructions.
    • Contact Agent

      • Manage contacts stored in Airtable, Google Sheets, or database table.
      • Add/update contact records easily.

    7. Agent Role Management with JSON

    • Define roles & responsibilities using a JSON structure inside Function node or environment variables:
    {
      "emailAgent": {
        "role": "handles all email-related requests",
        "tools": ["sendEmail", "fetchEmails"]
      },
      "calendarAgent": {
        "role": "manages scheduling and calendar events",
        "tools": ["createEvent", "fetchEvents"]
      },
      "contactAgent": {
        "role": "manages the contact list for personalized communication",
        "tools": ["addContact", "updateContact"]
      }
    }
    
    • Use this JSON to route requests to appropriate agent nodes using the Switch node.

    8. System Messages & Prompt Engineering

    • Use System Messages to help AI understand:
      • How to respond.
      • Which agent/tools to call.
      • What “success” and “error" mean in context.

    Example system message for email agent:

    You are an email assistant. Only send emails if all required details (recipient, subject, body) are present. If any data is missing, ask the user to provide it.


    9. Error Handling

    • Use If/Else nodes after key actions.
    • Prompt users for missing data before proceeding (e.g., email address or event time).
    • Log errors and notify user gracefully.

    10. Dynamic Internet Search Agent

    • Integrate APIs like Bing Search API, Google Custom Search, or open-source alternatives.
    • Use this agent to respond to queries needing real-time info.
    • Send results back as messages or as triggers to other agents (e.g., sending found info by email).

    11. Workflow Example

    Build a workflow that:

    1. Receives user input (text/voice)
    2. Differentiates input type (Switch node)
    3. Sends prompt to AI model with memory context included.
    4. AI responds with task & intent (from JSON definitions)
    5. Switch node routes to:
      • Email agent workflow (send or get email)
      • Calendar agent workflow (create or get event)
      • Contact agent workflow (add/update contact)
      • Search agent workflow (internet search)
    6. Tools perform actions via API nodes
    7. Return final message to user (success/error)
    8. Store conversation context/memory

    Sample Resources and Nodes to Use in n8n

    Taskn8n NodeDescription
    Listen to messagesWebhook TriggerReceive messages to the bot
    Message type switchSwitchIdentify voice or text input
    Transcribe voiceHTTP Request (Whisper API, Google Speech)Convert voice to text
    AI processingHTTP Request or dedicated AI nodeConnect to Queen or OpenAI GPT
    API integrationsHTTP Request, Google API nodePerform email/calendar/contact requests
    JSON role managementFunctionParse and decide agent based on roles
    Store memoryDatabase nodes (Postgres/SQLite/Google Sheets)Save conversations or states
    Error handlingIf nodeHandle missing info and prompt user
    Dynamic routingSwitchDirect user requests to correct agent

    Tips

    • Test smaller portions first: Just get AI responding to text input properly.
    • Add memory support early for better context management.
    • Secure API keys via environment variables and n8n credentials.
    • Use the n8n community forums and docs for integrating specific APIs.
    • Consider open-source AI models running locally or on a cloud server with available REST APIs (e.g., Queen, GPT4All).

    If you want, I can help you by creating an example n8n workflow JSON or script for part of this setup — just let me know which agent or functionality you want to start with!

  3. User

    what are the settings for each node on n8n

  4. Assistant

    Certainly! Here's a detailed walkthrough of common n8n nodes and their key settings you'll configure for building AI agents like a personal AI assistant integrating text/voice inputs, AI processing, and tools (email/calendar/contact). To keep it clear, I’ll describe typical settings node-by-node based on the workflow steps.


    1. Webhook Trigger (Receive Messages)

    • Purpose: Receives incoming user messages (text or voice) from chat platforms or HTTP requests.
    • Settings:
      • HTTP Method: POST (or GET depending on platform)
      • Path: /webhook-ai-assistant (unique path for your bot)
      • Response Mode: On Received or Last Node
      • Authentication: Set if needed (e.g., Basic Auth, API Key)
      • Accept body params like:
        • message.text (string)
        • message.voice (audio file/base64) if applicable

    2. Switch Node (Text vs Voice Input)

    • Purpose: Determines if input is text or voice to route properly.

    • Settings:

      • Add two rules:

        1. Text Input

          • Value 1: {{$json["message"]["text"]}}
          • Condition: Is Not Empty
        2. Voice Input

          • Value 1: {{$json["message"]["voice"]}} (or audio field)
          • Condition: Is Not Empty
      • Default route: Return error or ask user to send valid input.


    3. HTTP Request Node (Voice Transcription API)

    • Purpose: Convert voice audio to text (optional, for voice messages).

    • Settings:

      • HTTP Method: POST
      • URL: E.g., Whisper API or Google Speech API endpoint
      • Authentication: Use API Key, OAuth, or Bearer Token (store via Credentials)
      • Headers:
        • Content-Type: audio/* or multipart/form-data depending on API
      • Body Parameters:
        • Audio file attachment or base64
      • Response Format: JSON
      • Output: Extract transcribed text from response (use Set or Function node next)

    4. Set Node (Prepare prompt for AI model)

    • Purpose: Build and format the prompt including user input and context memory.

    • Settings:

      • In Values to Set:
        • prompt: Use an expression like:
          {{ 
            "systemMessage": "You are a helpful assistant.",
            "userMessage": $json["message"]["text"] || $json["transcribedText"],
            "memory": $json["memory"] || ""
          }}
          
      • This JSON or formatted string will be sent to the AI API.

    5. HTTP Request Node (AI Model Integration)

    • Purpose: Send prompt to AI backend (Queen, OpenAI, etc.) and receive completion.

    • Settings:

      • HTTP Method: POST
      • URL: AI model API endpoint (eg. https://api.openai.com/v1/chat/completions)
      • Authentication: Bearer Token, API Key (via credentials)
      • Headers:
        • Content-Type: application/json
        • Authorization: Bearer {{ $credentials.apiKey }}
      • Body Parameters (JSON):
        {
          "model": "gpt-4",
          "messages": [
            {"role": "system", "content": "You are an AI assistant..."},
            {"role": "user", "content": "{{ $json.prompt.userMessage }}"}
          ],
          "temperature": 0.7,
          "max_tokens": 500
        }
        
      • Set Response Format: JSON
      • Extract AI reply from response, typically in choices[0].message.content

    6. Function Node (Parse AI Response & Route to Agents)

    • Purpose: Parse AI response, identify intent/agent (email, calendar, contact), and prepare data for next steps.

    • Settings:

      • Write JS logic to analyze AI reply, e.g.:
        const response = $json["aiResponse"];
        let agent = "default";
        
        if (response.includes("send email")) {
          agent = "emailAgent";
        } else if (response.includes("schedule meeting")) {
          agent = "calendarAgent";
        } else if (response.includes("add contact")) {
          agent = "contactAgent";
        }
        
        return [{ json: { agent, text: response } }];
        

    7. Switch Node (Agent Routing Based on Role)

    • Settings:
      • Add condition based on agent assignment from Function node
      • 3 branches:
        • {{$json.agent}} === 'emailAgent'
        • {{$json.agent}} === 'calendarAgent'
        • {{$json.agent}} === 'contactAgent'
      • Default branch handles unknown tasks or fallback response.

    8. Email Agent: HTTP Request Node (Gmail API)

    • Purpose: Send/Read email via Gmail API.

    • Settings:

      • HTTP Method: POST (for send)
      • URL: https://gmail.googleapis.com/gmail/v1/users/me/messages/send
      • OAuth2 credentials configured in n8n for Gmail.
      • Headers:
        • Content-Type: application/json
      • Body:
        • Email RFC 2822 formatted base64 encoded message or structured JSON as per Gmail API.
    • Example body for sending:

      {
        "raw": "{{ base64EncodedEmail }}"
      }
      
      • Use a Function node before to create encoded email message from sender, recipients, subject, and body extracted from AI response.

    9. Calendar Agent: HTTP Request Node (Google Calendar API)

    • Purpose: Create or update calendar events.

    • Settings:

      • HTTP Method: POST or PATCH
      • URL: https://www.googleapis.com/calendar/v3/calendars/primary/events
      • OAuth2 credentials for Google Calendar.
      • Body (JSON):
        {
          "summary": "Meeting with Bob",
          "start": {
            "dateTime": "2024-07-19T10:00:00-07:00"
          },
          "end": {
            "dateTime": "2024-07-19T11:00:00-07:00"
          },
          "attendees": [
            {"email": "bob@example.com"}
          ]
        }
        
      • Extract schedule info via AI response parsing.

    10. Contact Agent: Table Node (Google Sheets or Airtable)

    • Purpose: Add or update contacts in a table.

    • Settings:

      • Connect to Airtable or Google Sheets.
      • Select table where contacts are stored.
      • Use Append mode to add or Update mode based on matching criteria.
      • Map fields:
        • Name
        • Email
        • Phone
        • Notes
      • Data is extracted dynamically from AI response.

    11. Set Node (Prepare Final Response)

    • Purpose: Build a user-friendly message after task completion.

    • Settings:

      • Set field replyText:
        Task completed successfully: [summary].
        
      • Provide error messages if any failure occurred.

    12. Respond (Webhook Response or Output Node)

    • Purpose: Sends final message back to the user.

    • Settings:

      • If using Webhook mode:
        • Return replyText within HTTP response body JSON:
          {
             "reply": "{{ $json.replyText }}"
          }
          
      • If via chat integration node (Telegram, Slack, etc.), configure send message action with response text.

    13. Error Handling

    • Use If Node after key steps to check for missing info or API errors.
    • Route to a Set Node to create user prompt for missing parameters.
    • Use Return Node to send prompt and halt processing until info is provided.

    Summary Table

    Node TypeKey Settings Summary
    Webhook TriggerPOST method, unique path, accepts msg & voice inputs
    SwitchCheck if text or voice input is empty/not empty
    HTTP RequestAPI endpoint, authentication (API key/OAuth), JSON body/payload
    Set NodeSetup prompt, final responses, or prepare email/calendar/contacts
    Function NodeParse AI response, detect agent role and intent
    Switch (Routing)Route requests based on detected agent role
    Email API (HTTP)Gmail OAuth, send email with base64 encoded message
    Calendar APICalendar OAuth, create/update event JSON
    Contact AgentAirtable/Google Sheets, create or update records
    If/ElseCheck errors or missing parameters
    Respond NodeReturn bot reply to user via webhook or chat node

    Let me know if you want example JSON exports of any specific workflow fragments or detailed GitHub links or tutorials related to these integrations!