{
  "nodes": [
    {
      "id": "2f835c89-1303-49ce-8d37-332fd9ebe7c2",
      "name": "Structured Output Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        112,
        432
      ],
      "parameters": {
        "jsonSchemaExample": "{\n\t\"items\": 5, \n  \"session\": \"sessionid\",\n  \"blog\": \"blog\"\n}"
      },
      "typeVersion": 1.3
    },
    {
      "id": "79ddf772-9705-46c4-ab47-33edf4a8e8c1",
      "name": "OpenAI Chat Model2",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        -432,
        464
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-5",
          "cachedResultName": "gpt-5"
        },
        "options": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "c245a37f-d6c9-47d8-a2a2-7e43fcfdfb01",
      "name": "Simple Memory",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "position": [
        -64,
        352
      ],
      "parameters": {
        "contextWindowLength": 10
      },
      "typeVersion": 1.3
    },
    {
      "id": "c65be9d5-1baa-4d45-8fa5-a30346e5246c",
      "name": "When Executed by Another Workflow",
      "type": "n8n-nodes-base.executeWorkflowTrigger",
      "position": [
        656,
        384
      ],
      "parameters": {
        "inputSource": "passthrough"
      },
      "typeVersion": 1.1
    },
    {
      "id": "18ba841f-60a7-4d88-b6b9-c3f6a2f9412f",
      "name": "google",
      "type": "@n8n/n8n-nodes-langchain.toolWorkflow",
      "position": [
        480,
        400
      ],
      "parameters": {
        "source": "parameter",
        "description": "call this tool to count the number of rows for the session id. pass only the session id to the tool",
        "workflowJson": "{\n  \"nodes\": [\n    {\n      \"parameters\": {\n        \"inputSource\": \"passthrough\"\n      },\n      \"type\": \"n8n-nodes-base.executeWorkflowTrigger\",\n      \"typeVersion\": 1.1,\n      \"position\": [\n        1040,\n        1152\n      ],\n      \"id\": \"8053e2f5-5042-4d54-826b-dc80fb11cbb9\",\n      \"name\": \"When Executed by Another Workflow\"\n    },\n    {\n      \"parameters\": {\n        \"documentId\": {\n          \"__rl\": true,\n          \"value\": \"1NwnABaQIReMmG2sRGrC-lv-5kpmsKJkUlRm-KmvPsCE\",\n          \"mode\": \"list\",\n          \"cachedResultName\": \"n8n Memory\",\n          \"cachedResultUrl\": \"https://docs.google.com/spreadsheets/d/1NwnABaQIReMmG2sRGrC-lv-5kpmsKJkUlRm-KmvPsCE/edit?usp=drivesdk\"\n        },\n        \"sheetName\": {\n          \"__rl\": true,\n          \"value\": \"gid=0\",\n          \"mode\": \"list\",\n          \"cachedResultName\": \"Sheet1\",\n          \"cachedResultUrl\": \"https://docs.google.com/spreadsheets/d/1NwnABaQIReMmG2sRGrC-lv-5kpmsKJkUlRm-KmvPsCE/edit#gid=0\"\n        },\n        \"options\": {}\n      },\n      \"type\": \"n8n-nodes-base.googleSheets\",\n      \"typeVersion\": 4.7,\n      \"position\": [\n        1232,\n        1152\n      ],\n      \"id\": \"9df87454-5e48-494f-af01-82197750341f\",\n      \"name\": \"Get row(s) in sheet\",\n      \"alwaysOutputData\": true,\n      \"credentials\": {\n        \"googleSheetsOAuth2Api\": {\n          \"id\": \"HlBW2puZbuCCq8jJ\",\n          \"name\": \"Google Sheets account 3\"\n        }\n      }\n    },\n    {\n      \"parameters\": {\n        \"fieldsToSummarize\": {\n          \"values\": [\n            {\n              \"field\": \"row_number\"\n            }\n          ]\n        },\n        \"options\": {}\n      },\n      \"type\": \"n8n-nodes-base.summarize\",\n      \"typeVersion\": 1.1,\n      \"position\": [\n        1648,\n        1152\n      ],\n      \"id\": \"0ab8f131-b8ec-44f1-851f-0c08d202cf4e\",\n      \"name\": \"Summarize1\",\n      \"alwaysOutputData\": true\n    },\n    {\n      \"parameters\": {\n        \"conditions\": {\n          \"options\": {\n            \"caseSensitive\": true,\n            \"leftValue\": \"\",\n            \"typeValidation\": \"strict\",\n            \"version\": 2\n          },\n          \"conditions\": [\n            {\n              \"id\": \"2278feea-3c0a-407b-84dc-5d6c0591fde9\",\n              \"leftValue\": \"={{ $json.session }}\",\n              \"rightValue\": \"={{ $('When Executed by Another Workflow').item.json.query }}\",\n              \"operator\": {\n                \"type\": \"string\",\n                \"operation\": \"equals\",\n                \"name\": \"filter.operator.equals\"\n              }\n            }\n          ],\n          \"combinator\": \"and\"\n        },\n        \"options\": {}\n      },\n      \"type\": \"n8n-nodes-base.filter\",\n      \"typeVersion\": 2.2,\n      \"position\": [\n        1440,\n        1152\n      ],\n      \"id\": \"ff5158fd-60bb-4a43-b8f9-c07971c03fe5\",\n      \"name\": \"Filter\",\n      \"alwaysOutputData\": true\n    }\n  ],\n  \"connections\": {\n    \"When Executed by Another Workflow\": {\n      \"main\": [\n        [\n          {\n            \"node\": \"Get row(s) in sheet\",\n            \"type\": \"main\",\n            \"index\": 0\n          }\n        ]\n      ]\n    },\n    \"Get row(s) in sheet\": {\n      \"main\": [\n        [\n          {\n            \"node\": \"Filter\",\n            \"type\": \"main\",\n            \"index\": 0\n          }\n        ]\n      ]\n    },\n    \"Filter\": {\n      \"main\": [\n        [\n          {\n            \"node\": \"Summarize1\",\n            \"type\": \"main\",\n            \"index\": 0\n          }\n        ]\n      ]\n    }\n  },\n  \"pinData\": {\n    \"When Executed by Another Workflow\": [\n      {\n        \"query\": \"ccde0f38fdeb4b64a49f541041ec64f1\"\n      }\n    ]\n  },\n  \"meta\": {\n    \"templateCredsSetupCompleted\": true,\n    \"instanceId\": \"ad0113c344ee237399e44e9f11798b05baeb83a6196d514a9ae9d2ad71c3b5c9\"\n  }\n}"
      },
      "typeVersion": 2.2
    },
    {
      "id": "3d176927-6920-4611-a06b-b9af3ab83aea",
      "name": "Summarize1",
      "type": "n8n-nodes-base.summarize",
      "position": [
        1168,
        384
      ],
      "parameters": {
        "options": {},
        "fieldsToSummarize": {
          "values": [
            {
              "field": "row_number"
            }
          ]
        }
      },
      "typeVersion": 1.1,
      "alwaysOutputData": true
    },
    {
      "id": "5fa065dd-68a3-4a22-ba4b-b94620ee466b",
      "name": "Filter",
      "type": "n8n-nodes-base.filter",
      "position": [
        1008,
        384
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "2278feea-3c0a-407b-84dc-5d6c0591fde9",
              "operator": {
                "name": "filter.operator.equals",
                "type": "string",
                "operation": "equals"
              },
              "leftValue": "={{ $json.session }}",
              "rightValue": "={{ $('When Executed by Another Workflow').item.json.query }}"
            }
          ]
        }
      },
      "typeVersion": 2.2,
      "alwaysOutputData": true
    },
    {
      "id": "6e4ea5b3-9479-4390-a67b-b11a070bae3d",
      "name": "Sticky Note6",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1072,
        -432
      ],
      "parameters": {
        "width": 400,
        "height": 1072,
        "content": "\n## \u2699\ufe0f Setup Instructions\n\n### 1\ufe0f\u20e3 Set Up OpenAI Connection\n1. Go to [OpenAI Platform](https://platform.openai.com/api-keys)  \n2. Navigate to [OpenAI Billing](https://platform.openai.com/settings/organization/billing/overview)  \n3. Add funds to your billing account  \n4. Copy your API key into the **OpenAI credentials** in n8n\n\n### 2\ufe0f\u20e3 Prepare Your Google Sheet\n#### Connect your Data in Google Sheets\n- Use this format: **[Sample Sheet](https://docs.google.com/spreadsheets/d/1NwnABaQIReMmG2sRGrC-lv-5kpmsKJkUlRm-KmvPsCE/edit?gid=0#gid=0)**\n- Row 1 = **column names** (e.g., `session`, `Rows`, `output`)\n- Data in rows **2\u2013100** (or more if you prefer)\n- In n8n, use **Google Sheets OAuth2** \u2192 pick your **Spreadsheet** and **Worksheet**\n- (Optional) You can adapt this to **Airtable**, **Notion**, or a **Database**\n## \ud83e\udde0 How It Works\n- **Chat Trigger**: Provide a topic (write) or paste existing text (reword).  \n- **Code Node (\u201cChoose to Write or Edit Blog\u201d)**:  \n  - Builds a `system_prompt` + `user_prompt`  \n  - Instructs the agent to call the **Google tool** (sub-workflow) **with only the `sessionid`** to count existing rows.  \n- **Tool Workflow (\u201cgoogle\u201d)**:  \n  - Fetches rows from the sheet \u2192 **filters by `session`** \u2192 **summarizes row count**.  \n- **Agent (\u201cBlog Writer & Editor\u201d)**:  \n  - Returns **structured JSON** (items/rows, session, blog body).  \n- **Store (Google Sheets)**:  \n  - Appends `{ session, Rows, output }` to the sheet.  \n- **If Node**:  \n  - Example rule: `Rows > 3` \u2192 branch/limit/notify as needed.\n\n## \ud83d\udcec Contact\nNeed help tailoring this to Airtable/Notion/DB, or adding auto-publishing?\n\n- \ud83d\udce7 **rbreen@ynteractive.com**  \n- \ud83d\udd17 **[Robert Breen](https://www.linkedin.com/in/robert-breen-29429625/)**  \n- \ud83c\udf10 **[ynteractive.com](https://ynteractive.com)**"
      },
      "typeVersion": 1
    },
    {
      "id": "53f30495-bf04-4229-9018-35525cab1a75",
      "name": "Sticky Note55",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -640,
        -432
      ],
      "parameters": {
        "color": 7,
        "width": 2032,
        "height": 1072,
        "content": "# \u270d\ufe0f AI Blog Writer & Editor with Google Sheets Memory (n8n + OpenAI)\n\nChat to **write** or **reword** a blog post. The workflow stores each result in Google Sheets and uses a sub-workflow \u201cGoogle tool\u201d to **count rows per session** (your running context). If a session exceeds a row threshold, the flow can branch (e.g., stop or notify).\n"
      },
      "typeVersion": 1
    },
    {
      "id": "629474f3-48d0-4943-af3b-74e3d93bd79a",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        400,
        272
      ],
      "parameters": {
        "color": 3,
        "width": 912,
        "height": 304,
        "content": "## Google Sub-workflow-tool\n Count number of times the blog was written and edited  **Dont forget to update this google sheet as well**\n"
      },
      "typeVersion": 1
    },
    {
      "id": "1f4fa21c-a2e6-4b20-b314-3d97bcc721ce",
      "name": "Sticky Note7",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -528,
        272
      ],
      "parameters": {
        "color": 3,
        "width": 288,
        "height": 304,
        "content": "### 1\ufe0f\u20e3 Set Up OpenAI Connection\n1. Go to [OpenAI Platform](https://platform.openai.com/api-keys)  \n2. Navigate to [OpenAI Billing](https://platform.openai.com/settings/organization/billing/overview)  \n3. Add funds to your billing account  \n4. Copy your API key into the **OpenAI credentials** in n8n  "
      },
      "typeVersion": 1
    },
    {
      "id": "656b9532-873f-4260-ac02-c02607be1d6a",
      "name": "Blog Writer & Editor",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        -176,
        -16
      ],
      "parameters": {
        "text": "={{ $json.user_prompt }}",
        "options": {
          "systemMessage": "={{ $json.system_prompt }}"
        },
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 2.2
    },
    {
      "id": "3e4cb64e-bcfb-4b16-89f6-a1a94b5a2189",
      "name": "Choose to Write or Edit Blog",
      "type": "n8n-nodes-base.code",
      "position": [
        -288,
        -224
      ],
      "parameters": {
        "jsCode": "// Code node: build prompts using fields from \"When chat message received\"\n// Behavior:\n// - If `output` exists => system: \"Reword the blog...\" ; user prompt uses `output` + `sessionId`\n// - Else               => system: \"Write a blog...\"  ; user prompt uses `chatInput` + `sessionId`\n// Both instruct to use the Google tool (sub-workflow) to count rows, passing ONLY the session id.\n//\n// Output fields:\n//   - system_prompt\n//   - user_prompt\n\n// Pull from the trigger node if needed\nconst triggerItems = $items('Ask about blog topic', 0, 0) || [];\nconst trigger = triggerItems[0]?.json || {};\n\nconst schemaExample = JSON.stringify(\n  { items: 5, session: \"sessionid\", blog: \"blog\" },\n  null,\n  0\n);\n\nreturn items.map(item => {\n  const j = item.json || {};\n\n  // Resolve chat and session from either the current item or the trigger node\n  const chatInput = j.chatInput ?? j.chat ?? trigger.chatInput ?? \"\";\n  const sessionId = j.sessionId ?? j.sessionid ?? trigger.sessionId ?? \"\";\n\n  const hasOutput =\n    j.output !== undefined &&\n    j.output !== null &&\n    String(j.output).trim() !== \"\";\n\n  if (hasOutput) {\n    // Reword existing blog\n    item.json.system_prompt =\n      \"Reword the blog. Use the Google tool (sub-workflow) to count how many rows exist for this session. Pass ONLY the session id to the Google tool. it will send back the number.Include the session id from the input. Return ONLY valid JSON with the required keys.\";\n    item.json.user_prompt = [\n      `sessionid: ${sessionId}`,\n      `blog_to_reword: \"\"\"${String(j.output)}\"\"\"`,\n      `Respond as JSON exactly like: ${schemaExample}`\n    ].join(\"\\n\");\n  } else {\n    // Write a new blog from chat\n    item.json.system_prompt =\n      \"Write a blog. Use the Google tool (sub-workflow) to see how many rows exist for this session. Pass ONLY the session id to the Google tool. it will send back the number.  Include the session id from the input. Return ONLY valid JSON with the required keys.\";\n    item.json.user_prompt = [\n      `sessionid: ${sessionId}`,\n      `blog_topic_or_chat: \"\"\"${String(chatInput)}\"\"\"`,\n      `Respond as JSON exactly like: ${schemaExample}`\n    ].join(\"\\n\");\n  }\n\n  // Optional debug\n  item.json._resolved = { sessionId, chatInput, fromTrigger: !!triggerItems.length };\n\n  return item;\n});\n"
      },
      "typeVersion": 2
    },
    {
      "id": "32649be1-4bff-44db-bcde-574d2a67e745",
      "name": "Sticky Note10",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        176,
        -288
      ],
      "parameters": {
        "color": 3,
        "width": 352,
        "height": 384,
        "content": "### 2\ufe0f\u20e3 Prepare Your Google Sheet\n#### Connect your Data in Google Sheets\n- Use this format: **[Sample Sheet](https://docs.google.com/spreadsheets/d/1NwnABaQIReMmG2sRGrC-lv-5kpmsKJkUlRm-KmvPsCE/edit?gid=0#gid=0)**\n- Row 1 = **column names** (e.g., `session`, `Rows`, `output`)\n- Data in rows **2\u2013100** (or more if you prefer)\n- In n8n, use **Google Sheets OAuth2** \u2192 pick your **Spreadsheet** and **Worksheet**\n- (Optional) You can adapt this to **Airtable**, **Notion**, or a **Database**"
      },
      "typeVersion": 1
    },
    {
      "id": "1b2a04f8-ca25-4a04-9a9f-a4265a7b35ac",
      "name": "Ask about blog topic",
      "type": "@n8n/n8n-nodes-langchain.chatTrigger",
      "position": [
        -560,
        -240
      ],
      "parameters": {
        "options": {}
      },
      "typeVersion": 1.3
    },
    {
      "id": "fb399fde-0eba-456b-aca5-f1a991ef8983",
      "name": "n8n History",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        304,
        -32
      ],
      "parameters": {
        "columns": {
          "value": {
            "Rows": "={{ $json.output.items }}",
            "output": "={{ $json.output.blog }}",
            "session": "={{ $json.output.session }}"
          },
          "schema": [
            {
              "id": "session",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "session",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "output",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "output",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Rows",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "Rows",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "append",
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "gid=0",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1NwnABaQIReMmG2sRGrC-lv-5kpmsKJkUlRm-KmvPsCE/edit#gid=0",
          "cachedResultName": "Sheet1"
        },
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": "1NwnABaQIReMmG2sRGrC-lv-5kpmsKJkUlRm-KmvPsCE",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1NwnABaQIReMmG2sRGrC-lv-5kpmsKJkUlRm-KmvPsCE/edit?usp=drivesdk",
          "cachedResultName": "n8n Memory"
        }
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.7
    },
    {
      "id": "c476055f-91bb-4cf7-9ee2-6051f6e34df3",
      "name": "Check if Ran 4+ times",
      "type": "n8n-nodes-base.if",
      "position": [
        720,
        32
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "6dd3ba6e-400a-45bf-80d7-830594683094",
              "operator": {
                "type": "number",
                "operation": "gt"
              },
              "leftValue": "={{ $json.Rows }}",
              "rightValue": 3
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "e2e5a43c-3d13-49eb-9135-c5ae024cb503",
      "name": "Get History",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        832,
        384
      ],
      "parameters": {
        "options": {},
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "gid=0",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1NwnABaQIReMmG2sRGrC-lv-5kpmsKJkUlRm-KmvPsCE/edit#gid=0",
          "cachedResultName": "Sheet1"
        },
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": "1NwnABaQIReMmG2sRGrC-lv-5kpmsKJkUlRm-KmvPsCE",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1NwnABaQIReMmG2sRGrC-lv-5kpmsKJkUlRm-KmvPsCE/edit?usp=drivesdk",
          "cachedResultName": "n8n Memory"
        }
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.7,
      "alwaysOutputData": true
    }
  ],
  "connections": {
    "Filter": {
      "main": [
        [
          {
            "node": "Summarize1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "google": {
      "ai_tool": [
        [
          {
            "node": "Blog Writer & Editor",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Get History": {
      "main": [
        [
          {
            "node": "Filter",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "n8n History": {
      "main": [
        [
          {
            "node": "Check if Ran 4+ times",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Simple Memory": {
      "ai_memory": [
        [
          {
            "node": "Blog Writer & Editor",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Model2": {
      "ai_languageModel": [
        [
          {
            "node": "Blog Writer & Editor",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Ask about blog topic": {
      "main": [
        [
          {
            "node": "Choose to Write or Edit Blog",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Blog Writer & Editor": {
      "main": [
        [
          {
            "node": "n8n History",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check if Ran 4+ times": {
      "main": [
        [],
        [
          {
            "node": "Choose to Write or Edit Blog",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Structured Output Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Blog Writer & Editor",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Choose to Write or Edit Blog": {
      "main": [
        [
          {
            "node": "Blog Writer & Editor",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "When Executed by Another Workflow": {
      "main": [
        [
          {
            "node": "Get History",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}