AutomationFlowsAI & RAG › Analyze Contract Risk From Google Drive with Openai and Log to Gmail & Sheets

Analyze Contract Risk From Google Drive with Openai and Log to Gmail & Sheets

ByAvkash Kakdiya @itechnotion on n8n.io

This workflow automates end-to-end contract analysis when a new file is uploaded to Google Drive. It downloads the contract, extracts its content, and uses AI to analyze legal terms, obligations, and risks. Based on the assessed risk level, it notifies stakeholders and logs…

Event trigger★★★★☆ complexityAI-powered14 nodesGoogle DriveOpenAIGmailGoogle Drive TriggerGoogle Sheets
AI & RAG Trigger: Event Nodes: 14 Complexity: ★★★★☆ AI nodes: yes Added:

This workflow corresponds to n8n.io template #12575 — we link there as the canonical source.

This workflow follows the Gmail → Google Drive recipe pattern — see all workflows that pair these two integrations.

The workflow JSON

Copy or download the full n8n JSON below. Paste it into a new n8n workflow, add your credentials, activate. Full import guide →

Download .json
{
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "nodes": [
    {
      "id": "94721676-0968-4cbf-8177-75e245c96fcd",
      "name": "Download file1",
      "type": "n8n-nodes-base.googleDrive",
      "position": [
        6608,
        4736
      ],
      "parameters": {
        "fileId": {
          "__rl": true,
          "mode": "list",
          "value": ""
        },
        "options": {},
        "operation": "download"
      },
      "typeVersion": 3
    },
    {
      "id": "a518d2ee-a14b-4696-9d66-0c9f63bad53a",
      "name": "Extract Text From Downloaded File1",
      "type": "n8n-nodes-base.code",
      "position": [
        6784,
        4736
      ],
      "parameters": {
        "jsCode": "/**\n * This node extracts readable text from a downloaded file.\n * Works best for TXT / HTML / MD files.\n * For PDF/DOCX it forwards base64 content to AI (still usable by OpenAI).\n */\n\nconst items = $input.all();\n\nreturn items.map(item => {\n  let extractedText = '';\n  let fileName = '';\n  let mimeType = '';\n\n  // Google Drive download puts file in binary\n  const binaryKeys = Object.keys(item.binary || {});\n\n  if (binaryKeys.length === 0) {\n    extractedText = 'No file found in binary data.';\n  } else {\n    const binaryData = item.binary[binaryKeys[0]];\n    fileName = binaryData.fileName || 'unknown';\n    mimeType = binaryData.mimeType || 'unknown';\n\n    // Convert base64 \u2192 string\n    const buffer = Buffer.from(binaryData.data, 'base64');\n\n    if (\n      mimeType.includes('text') ||\n      fileName.endsWith('.txt') ||\n      fileName.endsWith('.md') ||\n      fileName.endsWith('.html')\n    ) {\n      // Clean readable text files\n      extractedText = buffer.toString('utf-8');\n    } else {\n      // For PDF / DOCX / others \u2192 pass raw content to AI\n      extractedText =\n        `The following is raw extracted content from a ${fileName} contract file.\\n` +\n        `Analyze and summarize key terms, risks, and obligations:\\n\\n` +\n        buffer.toString('utf-8');\n    }\n  }\n\n  return {\n    json: {\n      fileName,\n      mimeType,\n      contractText: extractedText\n    }\n  };\n});\n"
      },
      "typeVersion": 2
    },
    {
      "id": "c6f6459d-6438-45db-9e61-b7b11dc5f5b6",
      "name": "AI Contract Analysis1",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "position": [
        6960,
        4736
      ],
      "parameters": {
        "modelId": {
          "__rl": true,
          "mode": "list",
          "value": "model-name",
          "cachedResultName": "GPT-4O-MINI"
        },
        "options": {},
        "responses": {
          "values": [
            {
              "role": "system",
              "content": "=You are a senior legal contract analyst AI with expertise in commercial, SaaS, vendor, and enterprise agreements.\n\nYour role is to analyze contract language, identify explicit terms, and intelligently infer potential risks based on standard industry practices and legal norms.\n\nYou are allowed to infer risks when they are not explicitly stated, but only when the inference is logically supported by the contract structure, missing safeguards, or commonly accepted contract standards.\n\nYou must:\n- Clearly distinguish between explicitly stated risks and inferred risks\n- Avoid speculation or extreme assumptions\n- Base all inferences on the actual contract text and widely accepted industry practices\n- Use professional, cautious, and neutral language\n- Never fabricate clauses that do not exist\n\nIf a risk is inferred due to missing protections, clearly label it as an \"Inferred Risk\".\n"
            },
            {
              "content": "=Analyze the following contract text in detail.\n\nYour tasks:\n1. Extract key commercial and legal terms.\n2. Identify all payment-related clauses (fees, billing cycle, late fees, penalties).\n3. Identify renewal, termination, and notice period clauses.\n4. Detect financial, legal, and operational risks using both:\n   - Explicit contract language\n   - Reasonable risk inference based on missing safeguards or standard industry expectations\n5. Extract obligations and responsibilities for each party.\n6. Identify important dates, deadlines, and milestones.\n7. Highlight penalties, liabilities, indemnities, or breach consequences.\n8. Identify hidden or implied risks caused by:\n   - Liability limitations\n   - Auto-renewal clauses\n   - Missing SLAs, compliance terms, or data protection obligations\n\nRisk Inference Rules:\n- If a risk is explicitly stated, classify it as \"Explicit Risk\".\n- If a risk is not stated but reasonably implied, classify it as \"Inferred Risk\".\n- Do NOT infer risks that cannot be reasonably justified by the contract text.\n- Avoid fear-based or exaggerated language.\n\nOutput Rules:\n- Return ONLY valid JSON.\n- Do NOT include explanations, markdown, or commentary.\n- Never return empty arrays.\n- If no explicit risk exists, infer potential risks where reasonable.\n- Clearly label each risk entry with either \"Explicit Risk\" or \"Inferred Risk\".\n\nUse clear, business-friendly language.\n\nOutput format:\n{\n  \"contractOverview\": {\n    \"contractType\": \"\",\n    \"partiesInvolved\": [],\n    \"effectiveDate\": \"\",\n    \"contractDuration\": \"\"\n  },\n  \"keyTerms\": {\n    \"scopeOfServices\": \"\",\n    \"pricingSummary\": \"\",\n    \"governingLaw\": \"\"\n  },\n  \"paymentClauses\": {\n    \"fees\": \"\",\n    \"billingCycle\": \"\",\n    \"latePaymentPenalties\": \"\"\n  },\n  \"renewalAndTermination\": {\n    \"renewalType\": \"\",\n    \"noticePeriod\": \"\",\n    \"terminationConditions\": \"\"\n  },\n  \"obligations\": {\n    \"partyA\": [],\n    \"partyB\": []\n  },\n  \"risksAndPenalties\": {\n    \"financialRisks\": [],\n    \"legalRisks\": [],\n    \"operationalRisks\": []\n  },\n  \"importantDatesAndDeadlines\": [],\n  \"overallRiskLevel\": \"Low | Medium | High\",\n  \"summaryForStakeholders\": \"\"\n}\n\nContract Text:\n{{ $json.contractText }}\n"
            }
          ]
        },
        "builtInTools": {}
      },
      "typeVersion": 2.1
    },
    {
      "id": "144bba7f-04e4-41ee-b901-07b90b8f4c41",
      "name": "Format AI Output1",
      "type": "n8n-nodes-base.code",
      "position": [
        7264,
        4736
      ],
      "parameters": {
        "jsCode": "/**\n * This code:\n * 1. Extracts AI text from LangChain output format\n * 2. Parses JSON safely\n * 3. Flattens data for alerts & Google Sheets\n */\n\nfunction safeJsonParse(text) {\n  try {\n    return JSON.parse(text);\n  } catch (e) {\n    const match = text.match(/\\{[\\s\\S]*\\}/);\n    if (!match) throw new Error(\"No JSON found\");\n    return JSON.parse(match[0]);\n  }\n}\n\nreturn $input.all().map(item => {\n  let rawText = \"\";\n\n  try {\n    rawText =\n      item.json.output?.[0]\n        ?.content?.find(c => c.type === \"output_text\")\n        ?.text || \"\";\n  } catch (e) {\n    rawText = \"\";\n  }\n\n  let parsed;\n  try {\n    parsed = safeJsonParse(rawText);\n  } catch (err) {\n    return {\n      json: {\n        error: \"Failed to parse AI response\",\n        rawResponse: rawText\n      }\n    };\n  }\n\n  function formatRisks(risksArray) {\n    if (!Array.isArray(risksArray) || risksArray.length === 0) {\n      return \"No significant risks identified\";\n    }\n  \n    return risksArray\n      .map(r => {\n        if (typeof r === \"string\") return r;\n        if (typeof r === \"object\") {\n          return `${r.classification}: ${r.risk}`;\n        }\n        return \"\";\n      })\n      .filter(Boolean)\n      .join(\"; \");\n  }\n\n  return {\n    json: {\n      // Contract Overview\n      contractType: parsed.contractOverview?.contractType || \"\",\n      partiesInvolved: (parsed.contractOverview?.partiesInvolved || []).join(\", \"),\n      effectiveDate: parsed.contractOverview?.effectiveDate || \"\",\n      contractDuration: parsed.contractOverview?.contractDuration || \"\",\n\n      // Key Terms\n      scopeOfServices: parsed.keyTerms?.scopeOfServices || \"\",\n      pricingSummary: parsed.keyTerms?.pricingSummary || \"\",\n      governingLaw: parsed.keyTerms?.governingLaw || \"\",\n\n      // Payment\n      fees: parsed.paymentClauses?.fees || \"\",\n      billingCycle: parsed.paymentClauses?.billingCycle || \"\",\n      latePaymentPenalties: parsed.paymentClauses?.latePaymentPenalties || \"\",\n\n      // Renewal & Termination\n      renewalType: parsed.renewalAndTermination?.renewalType || \"\",\n      noticePeriod: parsed.renewalAndTermination?.noticePeriod || \"\",\n      terminationConditions: parsed.renewalAndTermination?.terminationConditions || \"\",\n\n      // Obligations\n      obligationsPartyA: (parsed.obligations?.partyA || []).join(\"; \"),\n      obligationsPartyB: (parsed.obligations?.partyB || []).join(\"; \"),\n\n      // Risks (FIXED)\n      financialRisks: formatRisks(parsed.risksAndPenalties?.financialRisks),\n      legalRisks: formatRisks(parsed.risksAndPenalties?.legalRisks),\n      operationalRisks: formatRisks(parsed.risksAndPenalties?.operationalRisks),\n\n      // Dates\n      importantDatesAndDeadlines: (parsed.importantDatesAndDeadlines || []).join(\" | \"),\n\n      // Summary\n      overallRiskLevel: parsed.overallRiskLevel || \"Unknown\",\n      stakeholderSummary: parsed.summaryForStakeholders || \"\"\n    }\n  };\n});\n"
      },
      "typeVersion": 2
    },
    {
      "id": "2b3a4dbe-5e5e-4c6b-8e57-67fcaa8e3652",
      "name": "Alert Teams Automatically1",
      "type": "n8n-nodes-base.if",
      "position": [
        7456,
        4736
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 3,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "14c22811-06fc-4758-93b9-83d2513ad061",
              "operator": {
                "type": "string",
                "operation": "equals"
              },
              "leftValue": "={{ $json.overallRiskLevel }}",
              "rightValue": "Medium"
            },
            {
              "id": "c3ad5d74-b204-460b-9f4c-a22ea8d6494e",
              "operator": {
                "type": "string",
                "operation": "notContains"
              },
              "leftValue": "={{ $json.financialRisks }}",
              "rightValue": "No significant risks identified"
            },
            {
              "id": "5ae54f3d-0691-44fc-aabd-2ce44a5f7a82",
              "operator": {
                "type": "string",
                "operation": "notContains"
              },
              "leftValue": "={{ $json.operationalRisks }}",
              "rightValue": "No significant risks identified"
            }
          ]
        }
      },
      "typeVersion": 2.3
    },
    {
      "id": "27ac6f18-01b7-4bdb-986d-8f35566e055a",
      "name": "Send a message2",
      "type": "n8n-nodes-base.gmail",
      "position": [
        7664,
        4640
      ],
      "parameters": {
        "sendTo": "gmail-id",
        "message": "=<!DOCTYPE html>\n\n<html>\n<head>\n  <meta charset=\"UTF-8\" />\n  <title>Contract Risk Summary</title>\n</head>\n<body style=\"margin:0; padding:0; font-family: Arial, Helvetica, sans-serif; background-color:#f4f6f8;\">\n\n  <table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" style=\"background-color:#f4f6f8; padding:20px;\">\n    <tr>\n      <td align=\"center\">\n        <table width=\"700\" cellpadding=\"0\" cellspacing=\"0\" style=\"background-color:#ffffff; border-radius:8px; overflow:hidden; box-shadow:0 2px 8px rgba(0,0,0,0.08);\">\n\n```\n      <!-- Header -->\n      <tr>\n        <td style=\"background-color:#0f172a; color:#ffffff; padding:20px;\">\n          <h2 style=\"margin:0; font-size:20px;\">AI Contract Risk Summary</h2>\n          <p style=\"margin:4px 0 0; font-size:13px; opacity:0.9;\">\n            {{$json.contractType}} \u2022 Risk Level: <strong>{{$json.overallRiskLevel}}</strong>\n          </p>\n        </td>\n      </tr>\n\n      <!-- Body -->\n      <tr>\n        <td style=\"padding:24px; color:#111827; font-size:14px; line-height:1.6;\">\n\n          <p>Hello Team,</p>\n          <p>\n            Below is the <strong>AI-generated analysis</strong> of the contract.  \n            This summary highlights <strong>key terms, obligations, risks, and deadlines</strong> for quick review.\n          </p>\n\n          <!-- Contract Overview -->\n          <h3 style=\"border-bottom:1px solid #e5e7eb; padding-bottom:6px;\">\ud83d\udcc4 Contract Overview</h3>\n          <table width=\"100%\" cellpadding=\"6\">\n            <tr><td width=\"35%\"><strong>Contract Type</strong></td><td>{{$json.contractType}}</td></tr>\n            <tr><td><strong>Parties</strong></td><td>{{$json.partiesInvolved}}</td></tr>\n            <tr><td><strong>Effective Date</strong></td><td>{{$json.effectiveDate}}</td></tr>\n            <tr><td><strong>Duration</strong></td><td>{{$json.contractDuration}}</td></tr>\n            <tr><td><strong>Governing Law</strong></td><td>{{$json.governingLaw}}</td></tr>\n          </table>\n\n          <!-- Scope & Commercials -->\n          <h3 style=\"border-bottom:1px solid #e5e7eb; padding-bottom:6px;\">\ud83d\udcbc Scope & Commercial Terms</h3>\n          <p><strong>Scope of Services:</strong><br />{{$json.scopeOfServices}}</p>\n          <p><strong>Pricing Summary:</strong><br />{{$json.pricingSummary}}</p>\n\n          <!-- Payment -->\n          <h3 style=\"border-bottom:1px solid #e5e7eb; padding-bottom:6px;\">\ud83d\udcb0 Payment Details</h3>\n          <ul>\n            <li><strong>Fees:</strong> {{$json.fees}}</li>\n            <li><strong>Billing Cycle:</strong> {{$json.billingCycle}}</li>\n            <li><strong>Late Payment Penalties:</strong> {{$json.latePaymentPenalties}}</li>\n          </ul>\n\n          <!-- Renewal -->\n          <h3 style=\"border-bottom:1px solid #e5e7eb; padding-bottom:6px;\">\ud83d\udd04 Renewal & Termination</h3>\n          <ul>\n            <li><strong>Renewal Type:</strong> {{$json.renewalType}}</li>\n            <li><strong>Notice Period:</strong> {{$json.noticePeriod}}</li>\n            <li><strong>Termination Conditions:</strong> {{$json.terminationConditions}}</li>\n          </ul>\n\n          <!-- Obligations -->\n          <h3 style=\"border-bottom:1px solid #e5e7eb; padding-bottom:6px;\">\ud83e\uddfe Key Obligations</h3>\n          <p><strong>Service Provider:</strong><br />{{$json.obligationsPartyA}}</p>\n          <p><strong>Client:</strong><br />{{$json.obligationsPartyB}}</p>\n\n          <!-- Risks -->\n          <h3 style=\"border-bottom:1px solid #e5e7eb; padding-bottom:6px;\">\u26a0\ufe0f Risk Assessment</h3>\n          <p><strong>Overall Risk Level:</strong>\n            <span style=\"font-weight:bold; color:#b45309;\">{{$json.overallRiskLevel}}</span>\n          </p>\n\n          <p><strong>Financial Risks:</strong><br />{{$json.financialRisks}}</p>\n          <p><strong>Legal Risks:</strong><br />{{$json.legalRisks}}</p>\n          <p><strong>Operational Risks:</strong><br />{{$json.operationalRisks}}</p>\n\n          <!-- Dates -->\n          <h3 style=\"border-bottom:1px solid #e5e7eb; padding-bottom:6px;\">\u23f0 Important Dates & Deadlines</h3>\n          <p>{{$json.importantDatesAndDeadlines}}</p>\n\n          <!-- Summary -->\n          <h3 style=\"border-bottom:1px solid #e5e7eb; padding-bottom:6px;\">\ud83d\udcdd Stakeholder Summary</h3>\n          <p>{{$json.stakeholderSummary}}</p>\n\n          <p style=\"margin-top:24px;\">\n            If any risks require immediate attention, please review and advise on next steps.\n          </p>\n\n          <p style=\"margin-top:24px;\">\n            Regards,<br />\n            <strong>AI Contract Summary Bot</strong><br />\n            <span style=\"color:#6b7280;\">Automated Contract Intelligence</span>\n          </p>\n\n        </td>\n      </tr>\n\n      <!-- Footer -->\n      <tr>\n        <td style=\"background-color:#f9fafb; text-align:center; padding:14px; font-size:12px; color:#6b7280;\">\n          This email was generated automatically by an AI-powered contract analysis workflow.\n        </td>\n      </tr>\n\n    </table>\n  </td>\n</tr>\n```\n\n  </table>\n\n</body>\n</html>\n",
        "options": {},
        "subject": "=Contract Risk Summary \u2013 {{$json.contractType}} | Risk Level: {{$json.overallRiskLevel}}"
      },
      "typeVersion": 2.2
    },
    {
      "id": "36c8c170-5ed0-423f-a3ce-d1c7a2f8374e",
      "name": "Get The Data To Save In google Sheet2",
      "type": "n8n-nodes-base.code",
      "position": [
        7872,
        4640
      ],
      "parameters": {
        "jsCode": "/**\n * Get data from Alert Teams Automatically node\n * This works regardless of which path (true/false) was taken\n */\n\n// Get data from the IF node (Alert Teams Automatically)\nconst alertData = $('Alert Teams Automatically1').first().json;\n\nreturn [{\n  json: {\n    // Add timestamp\n    processedDate: new Date().toISOString(),\n    processedDateTime: new Date().toLocaleString('en-IN', { timeZone: 'Asia/Kolkata' }),\n    \n    // Contract basic info\n    contractType: alertData.contractType || '',\n    partiesInvolved: alertData.partiesInvolved || '',\n    effectiveDate: alertData.effectiveDate || '',\n    contractDuration: alertData.contractDuration || '',\n    \n    // Financial details\n    fees: alertData.fees || '',\n    billingCycle: alertData.billingCycle || '',\n    latePaymentPenalties: alertData.latePaymentPenalties || '',\n    \n    // Risk assessment\n    overallRiskLevel: alertData.overallRiskLevel || 'Unknown',\n    financialRisks: alertData.financialRisks || '',\n    legalRisks: alertData.legalRisks || '',\n    operationalRisks: alertData.operationalRisks || '',\n    \n    // Renewal & termination\n    renewalType: alertData.renewalType || '',\n    noticePeriod: alertData.noticePeriod || '',\n    terminationConditions: alertData.terminationConditions || '',\n    \n    // Obligations\n    obligationsPartyA: alertData.obligationsPartyA || '',\n    obligationsPartyB: alertData.obligationsPartyB || '',\n    \n    // Other details\n    scopeOfServices: alertData.scopeOfServices || '',\n    pricingSummary: alertData.pricingSummary || '',\n    governingLaw: alertData.governingLaw || '',\n    importantDatesAndDeadlines: alertData.importantDatesAndDeadlines || '',\n    stakeholderSummary: alertData.stakeholderSummary || '',\n    \n    // Email path taken\n    emailType: alertData.overallRiskLevel === 'Medium' ? 'Risk Alert' : 'Info Only'\n  }\n}];"
      },
      "typeVersion": 2
    },
    {
      "id": "161ea93f-db54-4723-af64-110088549671",
      "name": "Send a message3",
      "type": "n8n-nodes-base.gmail",
      "position": [
        7664,
        4832
      ],
      "parameters": {
        "sendTo": "gmail-id",
        "message": "=<!DOCTYPE html>\n\n<html>\n<head>\n  <meta charset=\"UTF-8\" />\n  <title>Contract Review Summary</title>\n</head>\n<body style=\"margin:0; padding:0; font-family: Arial, Helvetica, sans-serif; background-color:#f4f6f8;\">\n\n<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" style=\"padding:20px;\">\n  <tr>\n    <td align=\"center\">\n      <table width=\"700\" cellpadding=\"0\" cellspacing=\"0\" style=\"background:#ffffff; border-radius:8px; box-shadow:0 2px 6px rgba(0,0,0,0.08);\">\n\n```\n    <!-- Header -->\n    <tr>\n      <td style=\"background:#0f766e; color:#ffffff; padding:18px;\">\n        <h2 style=\"margin:0;\">Contract Review Completed</h2>\n        <p style=\"margin:4px 0 0; font-size:13px;\">\n          {{$json.contractType}} \u2022 Risk Level: {{$json.overallRiskLevel}}\n        </p>\n      </td>\n    </tr>\n\n    <!-- Body -->\n    <tr>\n      <td style=\"padding:24px; color:#111827; font-size:14px; line-height:1.6;\">\n        <p>Hello Team,</p>\n\n        <p>\n          The contract has been successfully reviewed by the AI Contract Summary Bot.\n          Based on the analysis, <strong>no immediate action is required</strong> at this time.\n        </p>\n\n        <h3>\ud83d\udcc4 Contract Snapshot</h3>\n        <ul>\n          <li><strong>Parties:</strong> {{$json.partiesInvolved}}</li>\n          <li><strong>Effective Date:</strong> {{$json.effectiveDate}}</li>\n          <li><strong>Duration:</strong> {{$json.contractDuration}}</li>\n          <li><strong>Governing Law:</strong> {{$json.governingLaw}}</li>\n        </ul>\n\n        <h3>\u26a0\ufe0f Risk Overview</h3>\n        <ul>\n          <li><strong>Overall Risk Level:</strong> {{$json.overallRiskLevel}}</li>\n          <li><strong>Financial Risks:</strong> {{$json.financialRisks}}</li>\n          <li><strong>Legal Risks:</strong> {{$json.legalRisks}}</li>\n          <li><strong>Operational Risks:</strong> {{$json.operationalRisks}}</li>\n        </ul>\n\n        <h3>\ud83d\udcdd Summary</h3>\n        <p>{{$json.stakeholderSummary}}</p>\n\n        <p>\n          This contract has been recorded for reference.  \n          Please reach out if a deeper review is required.\n        </p>\n\n        <p style=\"margin-top:24px;\">\n          Regards,<br/>\n          <strong>AI Contract Summary Bot</strong><br/>\n          <span style=\"color:#6b7280;\">Automated Contract Intelligence</span>\n        </p>\n      </td>\n    </tr>\n\n    <!-- Footer -->\n    <tr>\n      <td style=\"background:#f9fafb; text-align:center; padding:12px; font-size:12px; color:#6b7280;\">\n        Informational notification only \u2014 no action required.\n      </td>\n    </tr>\n\n  </table>\n</td>\n```\n\n  </tr>\n</table>\n\n</body>\n</html>\n",
        "options": {},
        "subject": "=Contract Review Completed \u2013 No Immediate Action Required | {{$json.contractType}}"
      },
      "typeVersion": 2.2
    },
    {
      "id": "ca506624-1189-41eb-8cb7-5d88932a4827",
      "name": "Get The Data To Save In google Sheet3",
      "type": "n8n-nodes-base.code",
      "position": [
        7872,
        4832
      ],
      "parameters": {
        "jsCode": "// Loop over input items and add a new field called 'myNewField' to the JSON of each one\nfor (const item of $input.all()) {\n  item.json.myNewField = 1;\n}\n\nreturn $input.all();"
      },
      "typeVersion": 2
    },
    {
      "id": "f0c7f8f7-e5e4-4b49-baa3-885c2453a0bd",
      "name": "Google Drive Trigger1",
      "type": "n8n-nodes-base.googleDriveTrigger",
      "position": [
        6448,
        4736
      ],
      "parameters": {
        "event": "fileCreated",
        "options": {},
        "pollTimes": {
          "item": [
            {
              "mode": "everyHour"
            }
          ]
        },
        "triggerOn": "specificFolder",
        "folderToWatch": {
          "__rl": true,
          "mode": "list",
          "value": ""
        }
      },
      "typeVersion": 1
    },
    {
      "id": "89317dde-a623-4865-b85b-434d877ed5d6",
      "name": "Append row in sheet1",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        8112,
        4736
      ],
      "parameters": {
        "columns": {
          "value": {
            "Fees": "={{ $json.fees }}",
            "Email Type": "={{ $json.emailType }}",
            "Legal Risks": "={{ $json.legalRisks }}",
            "Renewal Type": "={{ $json.renewalType }}",
            "Billing Cycle": "={{ $json.billingCycle }}",
            "Contract Type": "={{ $json.contractType }}",
            "Notice Period": "={{ $json.noticePeriod }}",
            "Effective Date": "={{ $json.effectiveDate }}",
            "Processed Date": "={{ $json.processedDate }}",
            "Financial Risks": "={{ $json.financialRisks }}",
            "Pricing Summary": "={{ $json.pricingSummary }}",
            "Parties Involved": "={{ $json.partiesInvolved }}",
            "Contract Duration": "={{ $json.contractDuration }}",
            "Operational Risks": "={{ $json.operationalRisks }}",
            "Scope of Services": "={{ $json.scopeOfServices }}",
            "Overall Risk Level": "={{ $json.overallRiskLevel }}",
            "Processed Date Time": "={{ $json.processedDateTime }}",
            "Stakeholder Summary": "={{ $json.stakeholderSummary }}",
            "Obligations (Client)": "={{ $json.obligationsPartyB }}",
            "Late Payment Penalties": "={{ $json.latePaymentPenalties }}",
            "Termination Conditions": "={{ $json.terminationConditions }}",
            "Important Dates & Deadlines": "={{ $json.importantDatesAndDeadlines }}",
            "Obligations (Service Provider)": "={{ $json.obligationsPartyA }}"
          },
          "schema": [
            {
              "id": "Processed Date",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Processed Date",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Processed Date Time",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Processed Date Time",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Contract Type",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Contract Type",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Parties Involved",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Parties Involved",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Effective Date",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Effective Date",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Contract Duration",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Contract Duration",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Scope of Services",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Scope of Services",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Pricing Summary",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Pricing Summary",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Fees",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Fees",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Billing Cycle",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Billing Cycle",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Late Payment Penalties",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Late Payment Penalties",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Renewal Type",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Renewal Type",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Notice Period",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Notice Period",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Termination Conditions",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Termination Conditions",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Obligations (Service Provider)",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Obligations (Service Provider)",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Obligations (Client)",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Obligations (Client)",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Financial Risks",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Financial Risks",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Legal Risks",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Legal Risks",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Operational Risks",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Operational Risks",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Overall Risk Level",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Overall Risk Level",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Important Dates & Deadlines",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Important Dates & Deadlines",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Stakeholder Summary",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Stakeholder Summary",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Email Type",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Email Type",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": []
        },
        "options": {},
        "operation": "append",
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "gid=0",
          "cachedResultUrl": "sheet-url",
          "cachedResultName": "Sheet1"
        },
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": "google-sheet-id",
          "cachedResultUrl": "sheet-url",
          "cachedResultName": "sheet-name"
        }
      },
      "typeVersion": 4.7
    },
    {
      "id": "a25edacc-6ddf-4eed-b994-5101857eb0fc",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        5712,
        4352
      ],
      "parameters": {
        "width": 720,
        "height": 784,
        "content": "## AI Contract Summary Bot \nThis workflow automates end-to-end contract analysis using AI. When a new contract is uploaded to a monitored Google Drive folder, the system automatically downloads the file, extracts its contents, analyzes legal and commercial terms, identifies risks, and notifies stakeholders when action is required. All results are logged for audit and compliance tracking.\n\n### How it works\n- Monitors a specific Google Drive folder for newly uploaded contract files\n- Automatically downloads the contract document\n- Extracts readable text from TXT/HTML/MD files and prepares raw content for PDF/DOCX\n- Sends contract content to an AI model trained for legal and commercial analysis\n- Extracts key terms, obligations, payment clauses, renewal and termination details\n- Identifies financial, legal, and operational risks (Explicit and Inferred)\n- Assigns an overall risk level (Low / Medium / High)\n- Sends a risk alert email for medium-risk contracts\n- Sends an informational summary email when no action is required\n- Logs structured contract data, risks, and timestamps into Google Sheets\n\n### Setup steps\n1. Connect Google Drive credentials and select the folder to monitor\n2. Configure Gmail for alert and summary emails\n3. Connect Google Sheets for audit logging\n4. Activate the workflow and upload a contract to test\n"
      },
      "typeVersion": 1
    },
    {
      "id": "880ec4bf-92c8-4bef-953a-8dea4e88f1dc",
      "name": "Sticky Note7",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        6448,
        4352
      ],
      "parameters": {
        "color": 7,
        "width": 960,
        "height": 784,
        "content": "## Step 1: Contract Ingestion & AI Analysis\nTriggers on new contract upload, downloads the file, extracts text, and sends it to AI for detailed legal and commercial analysis.\n"
      },
      "typeVersion": 1
    },
    {
      "id": "99fe4c8a-6f99-40ae-82b1-7b9a1608a8e6",
      "name": "Sticky Note8",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        7424,
        4352
      ],
      "parameters": {
        "color": 7,
        "width": 896,
        "height": 784,
        "content": "## Step 2: Risk Alerts & Audit Logging\nEvaluates contract risk, sends alert or info emails, and logs structured results with timestamps into Google Sheets.\n"
      },
      "typeVersion": 1
    }
  ],
  "connections": {
    "Download file1": {
      "main": [
        [
          {
            "node": "Extract Text From Downloaded File1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send a message2": {
      "main": [
        [
          {
            "node": "Get The Data To Save In google Sheet2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send a message3": {
      "main": [
        [
          {
            "node": "Get The Data To Save In google Sheet3",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Format AI Output1": {
      "main": [
        [
          {
            "node": "Alert Teams Automatically1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Contract Analysis1": {
      "main": [
        [
          {
            "node": "Format AI Output1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Drive Trigger1": {
      "main": [
        [
          {
            "node": "Download file1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Alert Teams Automatically1": {
      "main": [
        [
          {
            "node": "Send a message2",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Send a message3",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Text From Downloaded File1": {
      "main": [
        [
          {
            "node": "AI Contract Analysis1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get The Data To Save In google Sheet2": {
      "main": [
        [
          {
            "node": "Append row in sheet1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get The Data To Save In google Sheet3": {
      "main": [
        [
          {
            "node": "Append row in sheet1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
Pro

For the full experience including quality scoring and batch install features for each workflow upgrade to Pro

About this workflow

This workflow automates end-to-end contract analysis when a new file is uploaded to Google Drive. It downloads the contract, extracts its content, and uses AI to analyze legal terms, obligations, and risks. Based on the assessed risk level, it notifies stakeholders and logs…

Source: https://n8n.io/workflows/12575/ — original creator credit. Request a take-down →

More AI & RAG workflows → · Browse all categories →

Related workflows

Workflows that share integrations, category, or trigger type with this one. All free to copy and import.

AI & RAG

The Problem That it Solves

Google Drive Trigger, OpenAI, Google Drive +5
AI & RAG

Content creators, YouTubers, and social media managers who want to repurpose long form videos into short clips without doing it manually. Works on self hosted n8n instances.

Google Drive Trigger, Google Drive, N8N Nodes Renderio +3
AI & RAG

An n8n-based automation that generates client proposals from a form, lets you review everything in one place, and sends the proposal only when you approve it.

Form Trigger, Google Sheets Trigger, OpenAI +4
AI & RAG

Overview

Gmail Trigger, Google Drive, OpenAI +4
AI & RAG

💥 Automate YouTube thumbnail creation from video links -vide. Uses telegramTrigger, httpRequest, googleDrive, gmail. Event-driven trigger; 25 nodes.

Telegram Trigger, HTTP Request, Google Drive +6