{
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "nodes": [
    {
      "id": "ad61fda0-c5a3-4945-89a0-c015460d1cb5",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -2120,
        180
      ],
      "parameters": {
        "width": 400,
        "height": 380,
        "content": "# \ud83e\udd16 AI Telegram Bot Workflow\n\n**Overview:**\nThis workflow creates an intelligent Telegram bot that:\n- Remembers conversation history\n- Responds to commands (/start, /clear)\n- Uses NVIDIA's mistralai/mistral-nemotron model for AI responses\n- Handles different message types appropriately\n\n**Required Credentials:**\n- Telegram Bot API token\n- NVIDIA API Bearer YOUR_TOKEN_HERE"
      },
      "typeVersion": 1
    },
    {
      "id": "4cf4e12f-0545-4f5b-9171-a11618780b19",
      "name": "Telegram Trigger",
      "type": "n8n-nodes-base.telegramTrigger",
      "position": [
        -1680,
        460
      ],
      "parameters": {
        "updates": [
          "message"
        ],
        "additionalFields": {}
      },
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "76f5bbcc-92ee-4928-bdb7-07b5d0478ed9",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1560,
        -260
      ],
      "parameters": {
        "width": 450,
        "height": 310,
        "content": "## \ud83d\udd00 Message Routing Logic\n\n**Step 1:** All incoming messages are processed through multiple IF nodes to determine the appropriate response:\n\n1. **Start Command** \u2192 Welcome message\n2. **Clear Command** \u2192 Clear chat history\n3. **Regular Text** \u2192 AI processing\n4. **Non-text Messages** \u2192 Error message\n\nThis ensures each message type gets handled correctly."
      },
      "typeVersion": 1
    },
    {
      "id": "448f7ad6-797e-4578-979c-09633668038f",
      "name": "Check Start Command",
      "type": "n8n-nodes-base.if",
      "position": [
        -1360,
        60
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 1,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "check-start-command",
              "operator": {
                "type": "string",
                "operation": "equals"
              },
              "leftValue": "={{ $json.message.text }}",
              "rightValue": "/start"
            }
          ]
        }
      },
      "typeVersion": 2
    },
    {
      "id": "021a44ce-b973-4bc3-a8b3-0dd3dc6e3333",
      "name": "Check Clear Command",
      "type": "n8n-nodes-base.if",
      "position": [
        -1360,
        240
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 1,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "check-clear-command",
              "operator": {
                "type": "string",
                "operation": "equals"
              },
              "leftValue": "={{ $json.message.text }}",
              "rightValue": "/clear"
            }
          ]
        }
      },
      "typeVersion": 2
    },
    {
      "id": "40d044e9-c11a-4aa0-88da-23b90bd3cbd2",
      "name": "Filter Regular Messages",
      "type": "n8n-nodes-base.if",
      "position": [
        -1360,
        380
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 1,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "check-text-message",
              "operator": {
                "type": "string",
                "operation": "exists",
                "singleValue": true
              },
              "leftValue": "={{ $json.message.text }}",
              "rightValue": ""
            },
            {
              "id": "not-start-command",
              "operator": {
                "type": "string",
                "operation": "notEquals"
              },
              "leftValue": "={{ $json.message.text }}",
              "rightValue": "/start"
            },
            {
              "id": "not-clear-command",
              "operator": {
                "type": "string",
                "operation": "notEquals"
              },
              "leftValue": "={{ $json.message.text }}",
              "rightValue": "/clear"
            }
          ]
        }
      },
      "typeVersion": 2
    },
    {
      "id": "25495fbc-7b32-4b6a-8668-583322306fd4",
      "name": "Check Non-Text Messages",
      "type": "n8n-nodes-base.if",
      "position": [
        -1360,
        600
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 1,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "check-text-exists",
              "operator": {
                "type": "string",
                "operation": "notExists",
                "singleValue": true
              },
              "leftValue": "={{ $json.message.text }}",
              "rightValue": ""
            }
          ]
        }
      },
      "typeVersion": 2
    },
    {
      "id": "f0c4260e-3c1d-4f0f-b65f-2f25eb9435f2",
      "name": "Send Welcome Message",
      "type": "n8n-nodes-base.telegram",
      "position": [
        -1060,
        -20
      ],
      "parameters": {
        "text": "\ud83e\udd16 *Welcome to AI Assistant Bot!* \ud83e\udd16\n\nI'm here to help answer your questions with memory of our conversation. Just send me any text message!\n\n*Features:*\n\u2022 Remember our conversation\n\u2022 Contextual responses\n\u2022 Answer follow-up questions\n\u2022 Quick and intelligent responses\n\u2022 Use `/clear` to restart the chat\n\nJust type your question and I'll get back to you! \ud83d\ude80",
        "chatId": "={{ $('Telegram Trigger').item.json.message.chat.id }}",
        "additionalFields": {
          "parse_mode": "Markdown",
          "appendAttribution": false
        }
      },
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.1
    },
    {
      "id": "8b2174fb-293d-4780-bb50-a432762d3461",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -960,
        160
      ],
      "parameters": {
        "width": 350,
        "height": 300,
        "content": "## \ud83d\uddc2\ufe0f Chat History Management\n\n**Key Features:**\n- Stores conversation per user ID\n- Limits to last 10 messages (5 exchanges)\n- Prevents token limit issues\n- Maintains context across messages\n\n**Clear Function:**\nCompletely removes user's chat history from memory for fresh start."
      },
      "typeVersion": 1
    },
    {
      "id": "07866025-b899-44dd-9427-7d824882222c",
      "name": "Clear Chat History",
      "type": "n8n-nodes-base.code",
      "position": [
        -1080,
        220
      ],
      "parameters": {
        "jsCode": "// Clear chat history for this user\nconst userId = $input.item.json.message.from.id;\nconst chatId = $input.item.json.message.chat.id;\n\n// Clear the chat history for this user\ndelete $getWorkflowStaticData('global')[`chat_${userId}`];\n\nreturn {\n  userId: userId,\n  chatId: chatId,\n  cleared: true\n};"
      },
      "typeVersion": 2
    },
    {
      "id": "df4f3420-f7bf-4368-84de-d3687ada4be2",
      "name": "Send Clear Confirmation",
      "type": "n8n-nodes-base.telegram",
      "position": [
        -440,
        80
      ],
      "parameters": {
        "text": "\ud83d\uddd1\ufe0f Chat history cleared! Starting fresh conversation.",
        "chatId": "={{ $json.chatId }}",
        "additionalFields": {
          "appendAttribution": false
        }
      },
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.1
    },
    {
      "id": "487e247b-a1be-41dd-8d2c-c28ba1839075",
      "name": "Manage Chat History",
      "type": "n8n-nodes-base.code",
      "position": [
        -1100,
        400
      ],
      "parameters": {
        "jsCode": "// Get user ID and current message\nconst userId = $input.item.json.message.from.id;\nconst userMessage = $input.item.json.message.text;\nconst chatId = $input.item.json.message.chat.id;\n\n// Initialize or get existing chat history\nlet chatHistory = $getWorkflowStaticData('global')[`chat_${userId}`] || [];\n\n// Add user message to history\nchatHistory.push({\n  role: \"user\",\n  content: userMessage\n});\n\n// Keep only last 10 messages (5 exchanges) to manage token limits\nif (chatHistory.length > 10) {\n  chatHistory = chatHistory.slice(-10);\n}\n\n// Save updated history\n$getWorkflowStaticData('global')[`chat_${userId}`] = chatHistory;\n\nreturn {\n  userId: userId,\n  chatId: chatId,\n  currentMessage: userMessage,\n  chatHistory: chatHistory\n};"
      },
      "typeVersion": 2
    },
    {
      "id": "317db760-9ea5-4810-9a56-03609a624896",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -460,
        440
      ],
      "parameters": {
        "width": 400,
        "height": 300,
        "content": "## \ud83e\udde0 AI Processing Pipeline\n\n**Step 2:** Regular messages go through AI processing:\n\n1. **Prepare Request** \u2192 Format for NVIDIA API\n2. **API Call** \u2192 Send to mistralai/mistral-nemotron model\n3. **Save Response** \u2192 Add to chat history\n4. **Send Reply** \u2192 Return to user\n\n**Model:** mistralai/mistral-nemotron\n**Features:** Context-aware, limited to 200 words"
      },
      "typeVersion": 1
    },
    {
      "id": "d75f4b21-e3fc-4691-8638-069ddc9ae91e",
      "name": "Prepare API Request",
      "type": "n8n-nodes-base.code",
      "position": [
        -820,
        640
      ],
      "parameters": {
        "jsCode": "// Prepare the messages array with system message + chat history\nconst systemMessage = {\n  role: \"system\",\n  content: \"You are a helpful Coddzz AI assistant for a Telegram bot. Be concise, friendly, and helpful. Keep responses under 200 words unless specifically asked for longer explanations.\"\n};\n\nconst chatHistory = $input.item.json.chatHistory || [];\nconst messages = [systemMessage, ...chatHistory];\n\nconst requestBody = {\n  model: \"mistralai/mistral-nemotron\",\n  messages: messages,\n  temperature: 0.6,\n  top_p: 0.7,\n  frequency_penalty: 0,\n  presence_penalty: 0,\n  max_tokens: 4096,\n  stream: false\n};\n\nreturn {\n  requestBody: requestBody,\n  chatHistory: chatHistory\n};"
      },
      "typeVersion": 2
    },
    {
      "id": "8f22b609-451c-4b2f-9e8f-e74e620166f1",
      "name": "NVIDIA LLaMA Chat Model",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        -320,
        760
      ],
      "parameters": {
        "url": "https://integrate.api.nvidia.com/v1/chat/completions",
        "method": "POST",
        "options": {},
        "jsonBody": "={{ $json.requestBody }}",
        "sendBody": true,
        "sendHeaders": true,
        "specifyBody": "json",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBearerAuth",
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            },
            {
              "name": "Accept",
              "value": "application/json"
            }
          ]
        }
      },
      "credentials": {
        "httpBearerAuth": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.1
    },
    {
      "id": "570d45bb-7110-48a5-80f2-796cc9876304",
      "name": "Save AI Response to History",
      "type": "n8n-nodes-base.code",
      "position": [
        40,
        760
      ],
      "parameters": {
        "jsCode": "// Get the AI response\nconst aiResponse = $input.item.json.choices[0].message.content;\nconst userId = $('Manage Chat History').item.json.userId;\n\n// Get current chat history\nlet chatHistory = $getWorkflowStaticData('global')[`chat_${userId}`] || [];\n\n// Add AI response to history\nchatHistory.push({\n  role: \"assistant\",\n  content: aiResponse\n});\n\n// Keep only last 10 messages\nif (chatHistory.length > 10) {\n  chatHistory = chatHistory.slice(-10);\n}\n\n// Save updated history\n$getWorkflowStaticData('global')[`chat_${userId}`] = chatHistory;\n\nreturn {\n  aiResponse: aiResponse,\n  userId: userId,\n  chatHistory: chatHistory\n};"
      },
      "typeVersion": 2
    },
    {
      "id": "f5151aaf-1b31-446e-b8da-c7c1282ddfa9",
      "name": "Send AI Response",
      "type": "n8n-nodes-base.telegram",
      "position": [
        320,
        620
      ],
      "parameters": {
        "text": "={{ $json.aiResponse }}",
        "chatId": "={{ $('Manage Chat History').item.json.chatId }}",
        "additionalFields": {
          "parse_mode": "Markdown",
          "appendAttribution": false,
          "reply_to_message_id": "={{ $('Telegram Trigger').item.json.message.message_id }}"
        }
      },
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.1
    },
    {
      "id": "07d96072-56e9-4742-98c2-49d162fea6aa",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1420,
        780
      ],
      "parameters": {
        "width": 350,
        "height": 270,
        "content": "## \u26a0\ufe0f Error Handling\n\n**Non-text Messages:**\nImages, videos, documents, etc. are not supported and receive a friendly error message directing users to send text only.\n\n**Future Enhancement:**\nCould be extended to handle document processing or image analysis."
      },
      "typeVersion": 1
    },
    {
      "id": "542bd5d0-6752-40d3-9b8a-005abb3ed1af",
      "name": "Send Error Message",
      "type": "n8n-nodes-base.telegram",
      "position": [
        -1100,
        580
      ],
      "parameters": {
        "text": "Sorry, I can only respond to text messages right now. Please send me a text message!",
        "chatId": "={{ $('Telegram Trigger').item.json.message.chat.id }}",
        "additionalFields": {
          "appendAttribution": false,
          "reply_to_message_id": "={{ $('Telegram Trigger').item.json.message.message_id }}"
        }
      },
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.1
    },
    {
      "id": "47bb0a28-c853-42c7-bd43-d5ce44c3663b",
      "name": "Sticky Note5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        120,
        120
      ],
      "parameters": {
        "width": 400,
        "height": 460,
        "content": "## \ud83d\udd27 Setup Instructions\n\n**Required Credentials:**\n1. **Telegram Bot Token:**\n   - Create bot with @BotFather\n   - Get API token\n   - Add to Telegram credentials\n\n2. **NVIDIA API Key:**\n   - Register at NVIDIA developer portal\n   - Generate API key\n   - Add as Bearer YOUR_TOKEN_HERE credential\n\n**Testing:**\n- Send `/start` to test welcome message\n- Send `/clear` to test history clearing\n- Send regular messages to test AI responses"
      },
      "typeVersion": 1
    }
  ],
  "connections": {
    "Telegram Trigger": {
      "main": [
        [
          {
            "node": "Check Start Command",
            "type": "main",
            "index": 0
          },
          {
            "node": "Check Clear Command",
            "type": "main",
            "index": 0
          },
          {
            "node": "Filter Regular Messages",
            "type": "main",
            "index": 0
          },
          {
            "node": "Check Non-Text Messages",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Clear Chat History": {
      "main": [
        [
          {
            "node": "Send Clear Confirmation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Clear Command": {
      "main": [
        [
          {
            "node": "Clear Chat History",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Start Command": {
      "main": [
        [
          {
            "node": "Send Welcome Message",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Manage Chat History": {
      "main": [
        [
          {
            "node": "Prepare API Request",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare API Request": {
      "main": [
        [
          {
            "node": "NVIDIA LLaMA Chat Model",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Non-Text Messages": {
      "main": [
        [
          {
            "node": "Send Error Message",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Filter Regular Messages": {
      "main": [
        [
          {
            "node": "Manage Chat History",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "NVIDIA LLaMA Chat Model": {
      "main": [
        [
          {
            "node": "Save AI Response to History",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save AI Response to History": {
      "main": [
        [
          {
            "node": "Send AI Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}