{
  "id": "zncb3ZRHYeJMrDYv",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "name": "AI Chat Response Generation with Google Sheets Context and Pinecone RAG Memory",
  "tags": [],
  "nodes": [
    {
      "id": "33071869-c1ec-4cde-9cac-9e654b609658",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        960,
        -32
      ],
      "parameters": {
        "width": 419,
        "height": 544,
        "content": "## \ud83e\udd16 AI Chat Assistant with RAG & Auto-Logging\n\n### How it works\nThis workflow powers an intelligent chat assistant that retrieves context from a Pinecone knowledge base and Google Sheets, responds naturally using OpenAI GPT-5, and logs all conversations automatically. It also includes a weekly email export feature that sends chat history summaries via Gmail.\n\n### Setup steps\n1. **Connect credentials**: OpenAI API, Google Sheets OAuth2, Pinecone API, Google Drive OAuth2, Gmail OAuth2\n2. **Configure Google Sheet**: Update the document ID to point to your conversation log sheet\n3. **Set Pinecone index**: Replace `whatsappchatbot` with your vector database index name\n4. **Test the chat**: Use the chat trigger URL to send a test message\n5. **Upload knowledge**: Add files to the Google Drive folder to auto-index into Pinecone"
      },
      "typeVersion": 1
    },
    {
      "id": "41cffb83-bd63-44cb-8504-a04315ce6025",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        960,
        560
      ],
      "parameters": {
        "color": 2,
        "width": 331,
        "height": 354,
        "content": "## \ud83d\udcac Chat Interface & Pre-Processing\nReceives user messages via webhook, enriches them with intent/topic metadata, then routes to the AI agent for context-aware responses."
      },
      "typeVersion": 1
    },
    {
      "id": "0318e95a-3c1d-404d-8610-20ce2dd360dd",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1312,
        560
      ],
      "parameters": {
        "color": 2,
        "width": 668,
        "height": 579,
        "content": "## \ud83e\udde0 AI Agent Core\nGPT-5 agent with memory, JSON output enforcement, and dual tools: retrieves context from Google Sheets (structured data) and Pinecone (semantic knowledge base)."
      },
      "typeVersion": 1
    },
    {
      "id": "29cffe39-e931-4389-8c80-cf83dabc1a89",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1984,
        560
      ],
      "parameters": {
        "color": 2,
        "width": 314,
        "height": 434,
        "content": "## \ud83d\udcca Conversation Logging\nEvery chat interaction is logged to Google Sheets with timestamp, user input, detected intent, and AI response for analytics and audit trails."
      },
      "typeVersion": 1
    },
    {
      "id": "7a5c8124-a076-423a-b351-d33a9a127395",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1168,
        2080
      ],
      "parameters": {
        "color": 2,
        "width": 827,
        "height": 705,
        "content": "## \ud83d\udcc2 Knowledge Base Auto-Indexing\nMonitors a Google Drive folder for new files (PDFs, docs), downloads them, splits into chunks, generates embeddings, and stores in Pinecone for RAG retrieval."
      },
      "typeVersion": 1
    },
    {
      "id": "ac997af3-8cd9-4ffc-92b9-71a9837cb367",
      "name": "Sticky Note5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1184,
        1440
      ],
      "parameters": {
        "color": 2,
        "width": 1457,
        "height": 465,
        "content": "## \ud83d\udce7 Weekly Chat History Export\nRuns every Monday at 10 PM, aggregates all logged conversations from Google Sheets, converts to a text file, and emails it as an attachment for record-keeping."
      },
      "typeVersion": 1
    },
    {
      "id": "3acb4a69-4716-4afb-9d23-48e61f4a1896",
      "name": "Sticky Note6",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        2432,
        2576
      ],
      "parameters": {
        "color": 3,
        "width": 340.45801526717554,
        "height": 184.88549618320613,
        "content": "## \ud83d\udd10 Credentials & Security\nRequires OAuth2 for Google services, API keys for OpenAI and Pinecone. Replace all credential IDs and document/folder IDs with your own. Never share API keys publicly."
      },
      "typeVersion": 1
    },
    {
      "id": "b3752497-5f33-4afb-88f9-7dcb1670f364",
      "name": "Short-Term Memory",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "position": [
        1568,
        960
      ],
      "parameters": {
        "sessionKey": "chat-rag-session",
        "sessionIdType": "customKey",
        "contextWindowLength": 7
      },
      "typeVersion": 1.3
    },
    {
      "id": "07e78867-bb70-43d4-9229-636f9a8d6193",
      "name": "AI Agent (Chat Composer)",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        1600,
        752
      ],
      "parameters": {
        "text": "=User message: {{ $json.content }}\nIntent: {{ $json.intent }}\nTopic: {{ $json.topic || \"general\" }}\nContext (from Google Sheets or memory): {{ $json.context || $memory || \"No context retrieved\" }}\n",
        "options": {
          "systemMessage": "=You are \"Content Agent Chat Responder\", a professional AI assistant inside an n8n automation system.\n\nYour role:\n- Communicate naturally, professionally, and concisely.\n- Use provided context from Google Sheets or memory when available.\n- If the user greets you (like \"hi\", \"hello\", \"hey\"), respond politely and ask how you can help.\n- If the user asks about SEO, content drafts, briefs, optimization, or publishing, respond specifically based on context or ask clarifying questions if missing.\n- If the intent is \"chat\" but the content clearly mentions a topic, treat it as a mixed chat + content query.\n- If context is missing, ask the user for more information. \n\n\n### Behavior Rules:\n- Always greet politely and warmly.\n- If the user asks about our company, products, or projects, **use the context retrieved from Pinecone (knowledge base) as your source of truth**.\n- Give clear, structured, and easy-to-understand answers \u2014 avoid long walls of text.\n- When appropriate, format answers into short paragraphs, bullet points, or step-by-step explanations.\n- Sound confident, approachable, and \"sales-ready\" \u2014 as if you are introducing the company to a client.\n- If the knowledge base does not contain the answer, respond naturally but say you will get back with more details.\n- Maintain a human-like flow: use follow-up questions, confirmations, and conversational phrases (e.g., \"That's a great question!\" or \"Let me explain in simple terms\u2026\").\n\n### Example Scenarios:\n- If a client asks: \"What is this project about?\" \u2192 Provide a short overview from Pinecone, structured like a pitch.\n- If they ask: \"Can you explain in detail?\" \u2192 Give a more thorough breakdown in a clear format.\n- If they greet or ask something general \u2192 continue the chat naturally, like a real human. \n\n- Always output concise structured JSON in the format:\n{\n  \"reply\": \"Your full response text\",\n  \"context_used\": [\"list of any context used or none\"]\n}\n"
        },
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 2.1
    },
    {
      "id": "2e25a1fd-88b8-44e8-bde1-17acd49729cd",
      "name": "Output Parser (JSON Enforcement)",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        1856,
        896
      ],
      "parameters": {
        "jsonSchemaExample": "{\n  \"reply\": \"string\",\n  \"context_used\": [\"string\"]\n}\n"
      },
      "typeVersion": 1.3
    },
    {
      "id": "68c48bd8-ff0b-4c94-b9f7-2c3fb9def1d5",
      "name": "OpenAI Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        1408,
        976
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "="
        },
        "options": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "6cc6c210-636a-46ad-8e1a-cc3292639d6e",
      "name": "When chat message received",
      "type": "@n8n/n8n-nodes-langchain.chatTrigger",
      "position": [
        1120,
        752
      ],
      "parameters": {
        "options": {}
      },
      "typeVersion": 1.3
    },
    {
      "id": "d686aa69-9e35-43b7-9f89-64690528db5b",
      "name": "Google Drive Trigger",
      "type": "n8n-nodes-base.googleDriveTrigger",
      "position": [
        1200,
        2224
      ],
      "parameters": {
        "event": "fileCreated",
        "options": {},
        "pollTimes": {
          "item": [
            {
              "mode": "everyMinute"
            }
          ]
        },
        "triggerOn": "specificFolder",
        "folderToWatch": {
          "__rl": true,
          "mode": "id",
          "value": "="
        }
      },
      "credentials": {
        "googleDriveOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "954d129c-2d36-4ff1-8474-3b2f3384c8d5",
      "name": "Download file",
      "type": "n8n-nodes-base.googleDrive",
      "position": [
        1408,
        2224
      ],
      "parameters": {
        "fileId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $json.id }}"
        },
        "options": {},
        "operation": "download"
      },
      "credentials": {
        "googleDriveOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 3
    },
    {
      "id": "c763f13b-0e7f-4abe-ae0d-f029ab45c8e2",
      "name": "Default Data Loader",
      "type": "@n8n/n8n-nodes-langchain.documentDefaultDataLoader",
      "position": [
        1696,
        2448
      ],
      "parameters": {
        "options": {
          "metadata": {
            "metadataValues": [
              {
                "name": "file-name",
                "value": "={{ $('Download file').item.json.name }}"
              }
            ]
          }
        },
        "dataType": "binary",
        "textSplittingMode": "custom"
      },
      "typeVersion": 1.1
    },
    {
      "id": "3f237c12-20f4-4e77-a991-f231875dad10",
      "name": "Recursive Character Text Splitter",
      "type": "@n8n/n8n-nodes-langchain.textSplitterRecursiveCharacterTextSplitter",
      "position": [
        1776,
        2624
      ],
      "parameters": {
        "options": {},
        "chunkSize": 500,
        "chunkOverlap": 200
      },
      "typeVersion": 1
    },
    {
      "id": "14e92af7-eeb2-4afa-9543-62c87ba2074f",
      "name": "Embeddings OpenAI",
      "type": "@n8n/n8n-nodes-langchain.embeddingsOpenAi",
      "position": [
        1520,
        2464
      ],
      "parameters": {
        "options": {
          "dimensions": 512
        }
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "fccdff58-7a8a-44a8-9a1c-a20d681b0438",
      "name": "Schedule Trigger",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [
        1216,
        1552
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "weeks",
              "triggerAtDay": [
                1
              ],
              "triggerAtHour": 22
            }
          ]
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "b357b118-d803-4c9d-ae3d-324eee2cca08",
      "name": "Aggregate",
      "type": "n8n-nodes-base.aggregate",
      "position": [
        1744,
        1552
      ],
      "parameters": {
        "options": {},
        "aggregate": "aggregateAllItemData"
      },
      "typeVersion": 1
    },
    {
      "id": "8ad58732-4dec-4649-a1c6-0b9a6b08eb6a",
      "name": "Get Previous Content from Sheet",
      "type": "n8n-nodes-base.googleSheetsTool",
      "position": [
        1696,
        992
      ],
      "parameters": {
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "",
          "cachedResultUrl": "",
          "cachedResultName": ""
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "="
        }
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.7
    },
    {
      "id": "8add9b4b-4086-4a8c-be4e-47c591c864ea",
      "name": "Conversation Logging",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        2080,
        752
      ],
      "parameters": {
        "operation": "appendOrUpdate",
        "sheetName": {
          "__rl": true,
          "mode": "id",
          "value": ""
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "="
        }
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.7
    },
    {
      "id": "ef7c257c-accd-47db-a799-21b9f38a933c",
      "name": "Pinecone Vector Store Insert",
      "type": "@n8n/n8n-nodes-langchain.vectorStorePinecone",
      "position": [
        1648,
        2224
      ],
      "parameters": {
        "mode": "insert",
        "options": {},
        "pineconeIndex": {
          "__rl": true,
          "mode": "id",
          "value": "="
        },
        "embeddingBatchSize": 1000
      },
      "credentials": {
        "pineconeApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "3e139499-ba6e-465d-b464-12d74fa0884f",
      "name": "Pinecone Vector Store Query for Knowledge Base",
      "type": "@n8n/n8n-nodes-langchain.vectorStorePinecone",
      "position": [
        1856,
        1152
      ],
      "parameters": {
        "mode": "retrieve-as-tool",
        "topK": 5,
        "options": {},
        "pineconeIndex": {
          "__rl": true,
          "mode": "list",
          "value": "whatsappchatbot",
          "cachedResultName": "whatsappchatbot"
        },
        "toolDescription": "=Retrieve data from the Pinecone knowledge base and use it to answer user queries about the company, products, or projects in a well-structured, human-like manner"
      },
      "credentials": {
        "pineconeApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "c3d32f3d-4804-49dd-8ee2-7da94bea33e0",
      "name": "Embeddings OpenAI Query for Chat modal",
      "type": "@n8n/n8n-nodes-langchain.embeddingsOpenAi",
      "position": [
        1808,
        1312
      ],
      "parameters": {
        "options": {
          "dimensions": 512
        }
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "83b6174f-12c9-440f-a021-7703570a3b48",
      "name": "Get Data from Sheet.",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        1456,
        1552
      ],
      "parameters": {
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "",
          "cachedResultUrl": "",
          "cachedResultName": ""
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "="
        }
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.7
    },
    {
      "id": "561655e9-9810-4cd4-a770-794d7a60f6cb",
      "name": "Convert Data  to file",
      "type": "n8n-nodes-base.convertToFile",
      "position": [
        1968,
        1552
      ],
      "parameters": {
        "options": {},
        "operation": "toText",
        "sourceProperty": "data"
      },
      "typeVersion": 1.1
    },
    {
      "id": "5f10e45a-6910-4cc3-897b-ba198d43943d",
      "name": "Check File Exist",
      "type": "n8n-nodes-base.if",
      "position": [
        2176,
        1552
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "a10217a0-9aa9-47eb-9179-b1760ae4fbd4",
              "operator": {
                "name": "filter.operator.equals",
                "type": "string",
                "operation": "equals"
              },
              "leftValue": "={{ $binary.data.mimeType }}",
              "rightValue": "application/json"
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "e1faaf7b-1b72-460d-94fa-dbdb719e9256",
      "name": "Send Chat History with attachment",
      "type": "n8n-nodes-base.gmail",
      "position": [
        2464,
        1536
      ],
      "parameters": {
        "message": "=Hi [Name], \n\nPlease find attached your chat history from our conversation on chat_history_{{ $now.format('DD') }}.   Feel free to refer back to this anytime, and let me know if you have any questions! \n\nBest regards, [Your Name]",
        "options": {
          "attachmentsUi": {
            "attachmentsBinary": [
              {}
            ]
          }
        },
        "subject": "=chat_history_{{ $now.format('DD') }}",
        "emailType": "text"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "8a43b13d-92ea-4847-8080-fa1a8b373253",
      "name": "Format Data For AI Agent ",
      "type": "n8n-nodes-base.set",
      "position": [
        1376,
        752
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "d917c6d3-ae35-4140-99c8-ae390866e735",
              "name": "intent",
              "type": "string",
              "value": "=Chat"
            },
            {
              "id": "e697ec89-26ed-4fb3-95a9-4a0cc6eed36d",
              "name": "topic",
              "type": "string",
              "value": "=AI Seo Basics"
            },
            {
              "id": "f5a88ad2-7f57-4971-88ea-bad9e1c10992",
              "name": "content_id",
              "type": "string",
              "value": "=C001"
            },
            {
              "id": "06fb1d17-f233-4b22-af27-cd3351c971a0",
              "name": "parameter",
              "type": "object",
              "value": "={{ $json.parameter }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    }
  ],
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "b76952bf-3c23-4299-8602-50580cbc6117",
  "connections": {
    "Aggregate": {
      "main": [
        [
          {
            "node": "Convert Data  to file",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Download file": {
      "main": [
        [
          {
            "node": "Pinecone Vector Store Insert",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check File Exist": {
      "main": [
        [
          {
            "node": "Send Chat History with attachment",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Schedule Trigger": {
      "main": [
        [
          {
            "node": "Get Data from Sheet.",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Embeddings OpenAI": {
      "ai_embedding": [
        [
          {
            "node": "Pinecone Vector Store Insert",
            "type": "ai_embedding",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent (Chat Composer)",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Short-Term Memory": {
      "ai_memory": [
        [
          {
            "node": "AI Agent (Chat Composer)",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "Default Data Loader": {
      "ai_document": [
        [
          {
            "node": "Pinecone Vector Store Insert",
            "type": "ai_document",
            "index": 0
          }
        ]
      ]
    },
    "Get Data from Sheet.": {
      "main": [
        [
          {
            "node": "Aggregate",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Drive Trigger": {
      "main": [
        [
          {
            "node": "Download file",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Convert Data  to file": {
      "main": [
        [
          {
            "node": "Check File Exist",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Agent (Chat Composer)": {
      "main": [
        [
          {
            "node": "Conversation Logging",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Format Data For AI Agent ": {
      "main": [
        [
          {
            "node": "AI Agent (Chat Composer)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "When chat message received": {
      "main": [
        [
          {
            "node": "Format Data For AI Agent ",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Previous Content from Sheet": {
      "ai_tool": [
        [
          {
            "node": "AI Agent (Chat Composer)",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Output Parser (JSON Enforcement)": {
      "ai_outputParser": [
        [
          {
            "node": "AI Agent (Chat Composer)",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Recursive Character Text Splitter": {
      "ai_textSplitter": [
        [
          {
            "node": "Default Data Loader",
            "type": "ai_textSplitter",
            "index": 0
          }
        ]
      ]
    },
    "Embeddings OpenAI Query for Chat modal": {
      "ai_embedding": [
        [
          {
            "node": "Pinecone Vector Store Query for Knowledge Base",
            "type": "ai_embedding",
            "index": 0
          }
        ]
      ]
    },
    "Pinecone Vector Store Query for Knowledge Base": {
      "ai_tool": [
        [
          {
            "node": "AI Agent (Chat Composer)",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    }
  }
}