{"workflow":{"id":12508,"name":"Research US legal regulations with CourtListener, LegiScan, OpenRouter and web search","views":114,"recentViews":0,"totalViews":114,"createdAt":"2026-01-06T00:07:51.101Z","description":"## Who is this for\n\nThis workflow is designed for legal professionals, policy analysts, and compliance teams who need to:\n- Research case law, legislation, and regulatory developments on specific topics\n- Build comprehensive legal intelligence reports from authoritative sources\n- Track enforcement trends and regulatory patterns\n- Support litigation strategy with thorough background research\n\nIt's ideal for animal law attorneys, advocacy organizations tracking animal welfare legislation, policy teams monitoring ag-gag laws and farm animal protection bills, and researchers building legal cases against animal cruelty.\n\n## What it does\n\nThis specialized legal research agent conducts comprehensive US legal and regulatory research:\n1. **Discovery phase**: Casts a wide net across legal databases\n   - CourtListener for federal and state court opinions and dockets\n   - LegiScan for legislation across all 50 states\n   - DocumentCloud for government enforcement documents\n   - Serper for legal analysis, news, and academic papers\n2. **Prioritization phase**: AI evaluates all discovered items and selects the most relevant (3-10 items) with scoring rationale\n3. **Retrieval phase**: Fetches complete text of prioritized court opinions, bill text, and documents\n4. **Analysis phase**: Synthesizes patterns, contradictions, and strategic insights\n5. **Verification phase**: Validates factual claims against source documents with hallucination detection\n\nThe verification phase uses a specialized legal-focused prompt that distinguishes between legitimate legal strategy (which should never be flagged) and actual factual errors like wrong case citations or non-existent statutes.\n\n## How to set up\n\n1. Import the workflow into your n8n instance\n2. Configure the required API credentials:\n   - **CourtListener API** for case law searches\n   - **LegiScan API** for legislation searches\n   - **Serper API** for web searches\n   - **Jina AI API** for article extraction\n   - **OpenRouter API** for AI analysis\n3. Test with a well-documented legal topic to verify integrations\n4. Activate the workflow\n\n### Example usage\n\n```json\n{\n  \"prompt\": \"Research the current legal challenges to California Proposition 12 (farm animal confinement standards), including constitutional commerce clause arguments and enforcement status\"\n}\n```\n\n## Requirements\n\n- CourtListener API key (free tier available)\n- LegiScan API key\n- Serper API key\n- Jina AI API key\n- OpenRouter API key\n\n## How to customize\n\n- **Add jurisdiction filters**: Limit searches to specific federal circuits or states with active animal welfare legislation\n- **Adjust time ranges**: Focus on recent developments or historical case law in animal protection\n- **Extend source types**: Add USDA enforcement records, state animal cruelty databases, or international animal law sources\n- **Modify verification strictness**: Adjust the hallucination detection threshold for legal accuracy\n- **Create specialized variants**: Fork for specific areas (ag-gag laws, farmed animal welfare, animal testing regulations, wildlife protection)\n- **Add citation formatting**: Post-process reports to use proper legal citation formats (Bluebook, etc.)\n- **Integrate with legal tools**: Connect to Clio, case management systems, or your organization's legal database\n","workflow":{"id":"PbTGOOYr8wqoBYsBnDYAR","meta":{"instanceId":"d0d0919ee2a246670c2a80cd2e44e3e0f7b3b2437f3e73af8501f9599a4a888b"},"name":"Research US regulations using AI agents with web search and report generation","tags":[],"nodes":[{"id":"05ae5f0c-e4bc-4d62-a587-a87338a28f8e","name":"Court Listener Discovery","type":"n8n-nodes-base.httpRequestTool","position":[816,496],"parameters":{"url":"={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('URL', ``, 'string') }}","options":{"batching":{"batch":{"batchSize":1}}},"sendHeaders":true,"authentication":"genericCredentialType","genericAuthType":"httpHeaderAuth","toolDescription":"=**Discovery Phase - Find ALL Court Cases**\n**Base URL:** https://www.courtlistener.com/api/rest/v4/\n**ALWAYS include full base URL in requests**\n\n## Search Endpoint (CORRECTED)\nhttps://www.courtlistener.com/api/rest/v4/search/?type=o&q={query}&page_size=20\n\n## Critical Parameters\n- **type=o** (opinions - most common)\n- **type=r** (RECAP docket documents)\n- **q={search terms}** (URL encode special characters)\n- **page_size=20** (API maximum)\n- **order_by=-score** (best matches first)\n- **court__jurisdiction=F** (F=federal, S=state, optional)\n\n## WORKING Discovery Search URLs\nCompany name searches:\nhttps://www.courtlistener.com/api/rest/v4/search/?type=o&q=cargill&page_size=20\nhttps://www.courtlistener.com/api/rest/v4/search/?type=o&q=\"cargill+meat\"&page_size=20\nhttps://www.courtlistener.com/api/rest/v4/search/?type=o&q=cargill+violation&page_size=20\n\nIssue/violation searches:\nhttps://www.courtlistener.com/api/rest/v4/search/?type=o&q=animal+welfare+cargill&page_size=20\nhttps://www.courtlistener.com/api/rest/v4/search/?type=o&q=environmental+violation+cargill&page_size=20\n\nDocket searches (different endpoint):\nhttps://www.courtlistener.com/api/rest/v4/dockets/?case_name__icontains=cargill&page_size=20\nhttps://www.courtlistener.com/api/rest/v4/dockets/?case_name__icontains=cargill&date_filed__gte=2020-01-01\n\n## Response Structure\n```json\n{\n  \"count\": 123,\n  \"next\": \"https://www.courtlistener.com/api/rest/v4/search/?page=2...\",\n  \"results\": [{\n    \"id\": 456789,  // CAPTURE THIS for retrieval phase\n    \"cluster_id\": 123456,  // Alternative ID for cluster retrieval\n    \"case_name\": \"NPPC v. Ross\",\n    \"absolute_url\": \"/opinion/456789/nppc-v-ross/\",  // Note: partial path\n    \"court\": \"Court of Appeals for the Ninth Circuit\",\n    \"date_filed\": \"2022-03-15\",\n    \"snippet\": \"...text preview with <mark>highlighted</mark> terms...\"\n  }]\n}","headerParameters":{"parameters":[{"name":"Accept","value":"application/json"}]}},"credentials":{"httpHeaderAuth":{"id":"ZfXzQhBFNaxjYbP6","name":"CourtListener Key"}},"retryOnFail":true,"typeVersion":4.2},{"id":"ecfc05f2-4305-4b4d-9f31-76ddea0a4340","name":"Google Search Discovery","type":"@n8n/n8n-nodes-langchain.toolHttpRequest","position":[368,496],"parameters":{"url":"https://google.serper.dev/{endpoint}","sendQuery":true,"sendHeaders":true,"specifyQuery":"model","authentication":"genericCredentialType","genericAuthType":"httpHeaderAuth","toolDescription":"=**Discovery Phase - Find ALL Legal Analysis & News**\n\nSearches Google for comprehensive coverage of the query. Cast wide net.\n\n## Endpoint Selection\nYou must specify one of these endpoints:\n- search (general web search) - for legal analysis, expert commentary\n- news (news articles) - for recent coverage, breaking developments\n- scholar (academic papers) - for law review articles\n\n## Query Parameters\n{\n  \"q\": \"search query\",           // REQUIRED\n  \"location\": \"United States\",   // optional\n  \"tbs\": \"qdr:y\"                 // optional time filter\n}\n\n## Time Parameters (tbs)\n- \"qdr:d\" (past day)\n- \"qdr:w\" (past week) \n- \"qdr:m\" (past month)\n- \"qdr:y\" (past year)\n\n## Discovery Examples\nsearch endpoint: {\"q\": \"prop 12 legal analysis\", \"tbs\": \"qdr:y\"}\nnews endpoint: {\"q\": \"prop 12 constitutional challenge\", \"tbs\": \"qdr:m\"}\nsearch endpoint: {\"q\": \"proposition 12 california farm\"}\nscholar endpoint: {\"q\": \"prop 12 dormant commerce clause\"}\n\n**In Discovery Phase:**\n- Use multiple search variations\n- Try different endpoints\n- Don't filter results yet\n- Find everything relevant for later prioritization","parametersHeaders":{"values":[{"name":"Content-Type","value":"application/json","valueProvider":"fieldValue"}]},"placeholderDefinitions":{"values":[{"name":"{endpoint}","description":"search - General web search \n\nnews - News articles \n\nscholar - Academic papers \n\npatents - Patent searches \n\nmaps - Location-based searches \n\nreviews - Business/product reviews"}]}},"credentials":{"httpHeaderAuth":{"id":"PmK8h96T6iczF7fT","name":"Serper API"}},"retryOnFail":true,"typeVersion":1.1},{"id":"09bdaf84-2695-4f0d-a9ed-0ace7e37527d","name":"LegiScan Discovery","type":"n8n-nodes-base.httpRequestTool","position":[512,496],"parameters":{"url":"={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('URL', ``, 'string') }}","options":{"batching":{"batch":{"batchSize":1}}},"authentication":"genericCredentialType","genericAuthType":"httpQueryAuth","toolDescription":"=**Discovery Phase - Find ALL Related Legislation**\n\n**CRITICAL: ALWAYS use full base URL**\n**Base URL:** https://api.legiscan.com/\n**Every request MUST start with:** https://api.legiscan.com/?op=\n\n## Search Operation\nhttps://api.legiscan.com/?op=getSearch&state={state}&query={query}&year={year}\n\n## Parameters\n- state: ALL (searches all states) or specific state code (CA, TX, etc.)\n- query: search terms (URL encoded)\n- year: 1 (all years), 2 (current session), or specific year\n\n## CORRECT Discovery URLs\n✅ https://api.legiscan.com/?op=getSearch&state=ALL&query=prop%2012&year=2\n✅ https://api.legiscan.com/?op=getSearch&state=ALL&query=proposition%2012\n✅ https://api.legiscan.com/?op=getSearch&state=CA&query=farm%20animal%20confinement\n\n## WRONG (Missing base URL)\n❌ ?op=getSearch&state=ALL&query=prop%2012\n❌ getSearch&state=ALL&query=prop%2012\n\n## Response Structure\n{\n  \"status\": \"OK\",\n  \"searchresult\": {\n    \"summary\": {\"count\": 15},\n    \"0\": {\n      \"bill_id\": 1234567,\n      \"bill_number\": \"AB 123\",\n      \"title\": \"Farm Animal Confinement Standards\"\n    }\n  }\n}\n\n**In Discovery Phase:**\n- ALWAYS use state=ALL for comprehensive search\n- Try multiple search terms\n- Note bill_id for later retrieval\n- Don't get full text yet"},"credentials":{"httpQueryAuth":{"id":"Lx8WUa2pIjcSpWJx","name":"Legiscan Key"}},"retryOnFail":true,"typeVersion":4.2},{"id":"10cd7049-4495-44d8-abaf-e23e5212c9a3","name":"Court Listener Retrieveal","type":"n8n-nodes-base.httpRequestTool","position":[2224,496],"parameters":{"url":"={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('URL', ``, 'string') }}","options":{"batching":{"batch":{"batchSize":1}}},"sendHeaders":true,"authentication":"genericCredentialType","genericAuthType":"httpHeaderAuth","toolDescription":"=**Retrieval Phase - Get Full Opinion Text**\n\nBase URL: https://www.courtlistener.com/api/rest/v4/\n\nYour job: Retrieve ONLY opinions Agent 2 selected. NO NEW SEARCHES.\n\nRetrieval URLs:\nhttps://www.courtlistener.com/api/rest/v4/opinions/{opinion_id}/\nhttps://www.courtlistener.com/api/rest/v4/clusters/{cluster_id}/\n\nAdd parameters to get full text:\n?fields=plain_text,html_with_citations,case_name\n\nExample:\nhttps://www.courtlistener.com/api/rest/v4/opinions/456789/?fields=plain_text,case_name\n\nResponse contains:\n- plain_text: Full opinion text\n- case_name: Title\n- date_filed: Date\n\nInclude complete opinion text in output for Agent 4.","headerParameters":{"parameters":[{"name":"Accept","value":"application/json"}]}},"credentials":{"httpHeaderAuth":{"id":"ZfXzQhBFNaxjYbP6","name":"CourtListener Key"}},"retryOnFail":true,"typeVersion":4.2},{"id":"761fbb8b-0afc-44c5-9f8e-fa09f630934a","name":"Think Tool Prioritization","type":"@n8n/n8n-nodes-langchain.toolThink","position":[1392,496],"parameters":{"description":"=**Prioritization Phase - Score and Select Best Items**\n\nYour CRITICAL job: Analyze ALL discovery results and select 3-10 most relevant.\n\nRequired Process:\n1. Count everything found:\n   \"Found 23 DocumentCloud docs, 15 bills, 8 cases, 12 articles\"\n\n2. Score each item (1-10):\n   - 9-10: Direct query match + recent + authoritative\n   - 7-8: Strong relevance, important source\n   - 5-6: Moderate relevance\n   - 1-4: Tangential, skip\n\n3. Select top items with reasoning:\n   \"Doc 789123 (Score: 9/10) - 2024 enforcement report, direct match\n    Case 456 NPPC v. Ross (Score: 10/10) - Main constitutional challenge\n    Bill CA-1234 (Score: 8/10) - Original Prop 12 text\"\n\n4. Document what you're skipping:\n   \"Skipping: 18 older docs (pre-2020), duplicate news coverage, \n    tangential references, draft bills that didn't pass\"\n\nOutput Format:\n\"Analysis complete. Selected for retrieval:\nDocumentCloud: [List IDs, slugs, reasons]\nBills: [List bill IDs, reasons]  \nCases: [List case IDs, reasons]\nURLs: [List URLs, reasons]\"\n\nThis is your ONLY chance to prioritize - be strategic!"},"typeVersion":1},{"id":"a38d1b00-948b-451d-b6ab-c8890508f8cf","name":"LegiScan Retrieval","type":"n8n-nodes-base.httpRequestTool","position":[2096,496],"parameters":{"url":"={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('URL', ``, 'string') }}","options":{"batching":{"batch":{"batchSize":1}}},"authentication":"genericCredentialType","genericAuthType":"httpQueryAuth","toolDescription":"=**Retrieval Phase - Get Full Bill Text**\n\nBase URL: https://api.legiscan.com/\nCRITICAL: ALWAYS use full URL!\n\nYour job: Retrieve ONLY bills Agent 2 selected. NO NEW SEARCHES.\n\nBill Retrieval URL:\n✅ https://api.legiscan.com/?op=getBill&id={bill_id}\n❌ ?op=getBill&id={bill_id} (WRONG - missing base URL!)\n\nExample:\nhttps://api.legiscan.com/?op=getBill&id=1234567\n\nResponse contains:\n{\n  \"bill\": {\n    \"bill_id\": 1234567,\n    \"title\": \"Full title\",\n    \"description\": \"Summary\",\n    \"sponsors\": [...],\n    \"texts\": [{\"doc_id\": 890, \"type\": \"Introduced\", \"url\": \"...\"}],\n    \"history\": [...],\n    \"votes\": [...]\n  }\n}\n\nTo get actual text:\nhttps://api.legiscan.com/?op=getBillText&id={doc_id}\n\nInclude full bill text and metadata for Agent 4."},"credentials":{"httpQueryAuth":{"id":"Lx8WUa2pIjcSpWJx","name":"Legiscan Key"}},"retryOnFail":true,"typeVersion":4.2},{"id":"865b9800-88c7-4114-a018-236b5c18298b","name":"DocumentCloud Retrieval","type":"n8n-nodes-base.httpRequestTool","position":[2352,496],"parameters":{"url":"={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('URL', ``, 'string') }}","options":{"batching":{"batch":{"batchSize":1}}},"toolDescription":"=**Retrieval Phase - Get Document Full Text**\n\nBase URL: https://s3.documentcloud.org/\n\nYour job: Retrieve text for ONLY documents Agent 2 selected.\n\nCRITICAL URL PATTERN:\nhttps://s3.documentcloud.org/documents/{id}/{slug}.txt.json\n\nALWAYS INCLUDE THE SLASHES!\n\n✅ CORRECT: https://s3.documentcloud.org/documents/789123/report.txt.json\n❌ WRONG: https://s3.documentcloud.org/documents/789123-report.txt.json\n\nConstruction:\n1. Take ID from Agent 2: \"789123\"\n2. Take slug from Agent 2: \"usda-report\"\n3. Build full URL: https://s3.documentcloud.org/documents/789123/usda-report.txt.json\n\nResponse:\n{\n  \"pages\": [\n    {\"page\": 0, \"contents\": \"Full text of page 1...\"},\n    {\"page\": 1, \"contents\": \"Full text of page 2...\"}\n  ]\n}"},"retryOnFail":true,"typeVersion":4.2},{"id":"4da35866-71e3-4bc5-afa9-37a6854d8ba1","name":"Jina URL Text Extraction","type":"n8n-nodes-base.jinaAiTool","position":[1952,496],"parameters":{"url":"={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('URL', ``, 'string') }}","options":{},"requestOptions":{},"descriptionType":"manual","toolDescription":"=**Retrieval Phase - Extract Article Content**\n\nYour job: Get full text from ONLY URLs Agent 2 selected.\n\nSimply pass each prioritized URL:\nhttps://example.com/legal-analysis-article\n\nJina will:\n- Extract main content\n- Remove ads, navigation\n- Return clean text\n- Include title, author, date\n\nOutput: Complete article text for Agent 4's analysis.\n\nNo searching - only extract from Agent 2's selected URLs."},"credentials":{"jinaAiApi":{"id":"6Grs8YZjZxafzxAm","name":"Jina AI account"}},"retryOnFail":true,"typeVersion":1},{"id":"82349c07-ce6f-4ae1-94de-da7309a507b7","name":"Think Tool Analysis","type":"@n8n/n8n-nodes-langchain.toolThink","position":[3120,512],"parameters":{"description":"=**Analysis Phase - Synthesize All Retrieved Texts**\n\nYour job: Analyze retrieved content to create strategic insights.\n\nRequired Analysis:\n1. Map findings to user query:\n   \"User asked about Prop 12 challenges\"\n   \n2. Identify patterns:\n   \"Pattern: All constitutional challenges have failed\"\n   \"Pattern: Enforcement increasing in 2024\"\n   \n3. Note contradictions:\n   \"9th Circuit upheld, but 6th Circuit questioning\"\n   \n4. Identify gaps:\n   \"No enforcement data after July 2024\"\n   \n5. Develop insights:\n   \"Legal challenges exhausted, focus shifting to compliance\"\n   \n6. Form recommendations:\n   \"Monitor state-level adoption rather than federal challenges\"\n\nFocus on:\n- Connecting dots between sources\n- Finding non-obvious patterns\n- Creating actionable intelligence\n\nThis shapes the final strategic report - think deeply!"},"typeVersion":1},{"id":"1c55a7b6-46e2-4579-b6d0-ab7ef04d305b","name":"Step 5: Verification","type":"@n8n/n8n-nodes-langchain.chainLlm","position":[3680,240],"parameters":{"text":"=# 🔍 LEGAL INTELLIGENCE VERIFICATION AGENT\n\n## THE CURRENT DATE & TIME IS {{ $now }}\n\n## Mission\nIdentify **only clear factual fabrications about legal matters that would materially mislead on the law**. The report writer creates adaptive, strategically-focused legal intelligence - respect and protect this approach. Focus only on catching completely false legal claims, not questioning legal strategy or analysis.\n\n## Your Inputs\n1. **Final Legal Intelligence Report** - The report (likely adapted to specific legal query)\n2. **Retrieved Legal Documents** - Court opinions, statutes, regulations, etc.\n\n## CRITICAL PRINCIPLE: Protect Legal Analysis\n\n### The Report Writer Is Supposed To:\n- **Adapt structure to legal query** - Litigation strategy differs from compliance review\n- **Lead with most relevant legal findings** - Not comprehensive case law surveys\n- **Provide strategic legal recommendations** - This is the core value\n- **Connect precedents creatively** - Building legal arguments is the point\n- **Assess probability and risk** - Professional judgment is expected\n- **Make tactical suggestions** - Discovery strategies, negotiation points, etc.\n\n### Only Flag Clear Legal Fabrications:\n- **Completely wrong case names or citations**\n- **Entirely fictional legal rulings**\n- **Statutes that don't exist**\n- **Drastically misrepresented holdings**\n\n## WHAT IS DEFINITELY NOT HALLUCINATION\n\n### 1. ADAPTIVE LEGAL STRUCTURE\n**Always Acceptable:**\n- Starting with \"You have strong claims\" instead of \"Background Law\"\n- Organizing by litigation strategy rather than chronological case law\n- Custom sections like \"Discovery Opportunities\" or \"Settlement Leverage\"\n- Focusing entirely on compliance gaps if that's what was asked\n- Omitting legal history if not relevant to query\n\n### 2. LEGAL STRATEGY & RECOMMENDATIONS\n**Always Acceptable (This is the value!):**\n- \"File motion for summary judgment based on...\"\n- \"Strongest argument is promissory estoppel\"\n- \"Discovery should focus on emails regarding...\"\n- \"Settlement range likely $X-Y based on comparable cases\"\n- \"Judge Smith typically favors this argument\"\n- \"Regulatory risk is high given recent enforcement\"\n\n### 3. LEGAL ANALYSIS & INTERPRETATION\n**Always Acceptable:**\n- \"This precedent suggests courts would likely...\"\n- \"The statutory language implies...\"\n- \"Recent enforcement trends indicate...\"\n- \"This creates a circuit split with...\"\n- \"Distinguished from Smith because...\"\n- \"Analogous to Jones reasoning...\"\n\n### 4. RISK ASSESSMENTS & PREDICTIONS\n**Always Acceptable:**\n- \"70% likelihood of surviving motion to dismiss\"\n- \"High probability of regulatory scrutiny\"\n- \"Low risk given safe harbor provisions\"\n- \"Expect counterclaims for...\"\n- \"Agency likely to focus on...\"\n- \"Court would probably apply...\"\n\n### 5. PROCEDURAL RECOMMENDATIONS\n**Always Acceptable:**\n- \"File in Eastern District for favorable precedent\"\n- \"Request expedited discovery on...\"\n- \"Move to compel within 30 days\"\n- \"Seek preliminary injunction immediately\"\n- \"Consider removal to federal court\"\n- \"Demand jury trial for sympathy factor\"\n\n### 6. REASONABLE LEGAL INFERENCES\n**Always Acceptable:**\n- How courts typically interpret similar language\n- Standard litigation timelines\n- Usual settlement patterns\n- Common regulatory positions\n- Typical damages calculations\n- Expected procedural rulings\n\n## ACTUAL HALLUCINATIONS TO FLAG (VERY RARE)\n\n### 1. COMPLETELY WRONG CASE LAW\n**Only Flag If Entirely Fabricated:**\n- Case that never existed (Smith v. Jones when no such case)\n- Drastically wrong holding (opposite of actual ruling)\n- Wrong court level (Supreme Court when actually district court)\n\n**Don't Flag:**\n- Paraphrased holdings that capture essence\n- Combined reasoning from multiple cases\n- Slightly imprecise case names\n- Minor date variations\n\n### 2. FICTIONAL STATUTES/REGULATIONS\n**Only Flag If Doesn't Exist:**\n- Statute number that's completely wrong\n- Regulation that was never enacted\n- Law from wrong jurisdiction claimed\n\n**Don't Flag:**\n- Paraphrased statutory language\n- Summarized regulatory requirements\n- Combined provisions\n- General references to \"regulations\"\n\n### 3. MATERIALLY FALSE LEGAL FACTS\n**Only Flag If Would Change Legal Analysis:**\n- Statute of limitations off by years\n- Wrong burden of proof entirely\n- Incorrect jurisdiction fundamentally\n- False procedural requirements\n\n**Don't Flag:**\n- Minor procedural variations\n- Approximate timelines\n- General legal principles\n- Strategic assessments\n\n## VERIFICATION APPROACH FOR LEGAL INTELLIGENCE\n\n### First, Understand the Legal Context\n- What legal question was asked?\n- Is this litigation, compliance, or risk assessment?\n- Does the structure serve that purpose?\n- Is the legal strategy sound even if citations imperfect?\n\n### Apply Maximum Permissiveness\n- **Default to acceptable** for all strategic content\n- **Protect legal analysis** as core value\n- **Preserve tactical recommendations** completely\n- **Allow creative legal arguments**\n- **Respect professional judgment**\n\n### Only Flag If All True:\n1. It's a specific legal fact (not strategy/analysis)\n2. It's completely wrong (not just imprecise)\n3. It would materially change the legal conclusion\n4. It can't be a reasonable legal interpretation\n5. It's not based on standard legal practice\n\n## SIMPLIFIED DECISION TREE FOR LEGAL\n\nFor each potential issue:\n\n1. **Is it legal strategy, tactics, or recommendations?**\n   - YES → NEVER FLAG (this is the point)\n   - NO → Continue\n\n2. **Is it legal analysis or interpretation?**\n   - YES → NEVER FLAG (professional judgment)\n   - NO → Continue\n\n3. **Is it risk assessment or prediction?**\n   - YES → NEVER FLAG (expert opinion)\n   - NO → Continue\n\n4. **Is the legal principle generally correct?**\n   - YES → DON'T FLAG (minor variations OK)\n   - NO → Continue\n\n5. **Would it change the legal advice?**\n   - NO → DON'T FLAG\n   - YES → FLAG IT (very rare)\n\n## OUTPUT FORMAT\n\nOnly flag the clearest legal fabrications:\n\n```\nHALLUCINATION #[X]:\n**False Legal Claim:** \"[Exact quote]\"\n**Why It's Legally Wrong:** [Not just missing, but false law]\n**Impact on Legal Analysis:** [How this changes the legal conclusion]\n**Severity:** [Only High or Medium - no Minor]\n```\n\n### Summary:\n```\nLEGAL VERIFICATION COMPLETE\nMaterial Legal Errors: [X] (typically 0-2)\nReport Assessment: [Strong legal analysis / Sound with minor issues / Generally reliable]\n\nNote: Legal strategy and risk assessments are professional judgment, not errors.\n```\n\n## EXAMPLES - MAXIMUM PERMISSIVENESS\n\n### NEVER Flag These (All Good Legal Intelligence):\n- \"Strong case for summary judgment\"\n- \"Discovery will likely reveal...\"\n- \"Courts typically award...\"\n- \"Regulatory risk is high\"\n- \"File in Southern District\"\n- \"Seek TRO immediately\"\n- \"Settlement value $1-2M\"\n- \"70% chance of success\"\n- \"Similar to Smith reasoning\"\n- \"Distinguishable from Jones\"\n- \"Statute suggests...\"\n- \"Regulation implies...\"\n- \"Judge likely to...\"\n- \"Jury would probably...\"\n- \"Recent trend shows...\"\n- \"Enforcement focus on...\"\n- \"Comparable cases settled for...\"\n- \"Standard practice is...\"\n\n### ONLY Flag These Clear Legal Errors:\n- \"Smith v. Jones, 123 U.S. 456\" (if case doesn't exist at all)\n- \"15 U.S.C. § 9999\" (if statute doesn't exist)\n- \"Burden on defendant\" (if actually on plaintiff - changes everything)\n- \"10-year statute of limitations\" (if actually 2 years)\n- \"Federal jurisdiction required\" (if actually state only)\n- \"Ninth Circuit ruling\" (if actually Second Circuit - when circuit matters)\n\n## SPECIAL PROTECTION FOR LEGAL CONTENT\n\n### Strategic Recommendations (NEVER FLAG):\n- All litigation tactics\n- Discovery strategies\n- Settlement approaches\n- Negotiation positions\n- Forum selection\n- Timing recommendations\n\n### Legal Analysis (NEVER FLAG):\n- Case interpretations\n- Statutory construction\n- Regulatory analysis\n- Precedent application\n- Legal reasoning\n- Analogy arguments\n\n### Risk Assessments (NEVER FLAG):\n- Probability estimates\n- Damage calculations\n- Enforcement predictions\n- Outcome assessments\n- Cost-benefit analysis\n- Strategic evaluations\n\n### Procedural Guidance (NEVER FLAG):\n- Filing recommendations\n- Motion practice\n- Discovery planning\n- Timeline suggestions\n- Jurisdictional strategy\n- Judge management\n\n## CRITICAL REMINDERS FOR LEGAL\n\n1. **Legal strategy is the core value** - Never flag it\n2. **Professional judgment is expected** - Protect it\n3. **Adaptive structure serves the query** - Don't expect templates\n4. **Risk assessments are expert opinion** - Never question them\n5. **Minor citation errors don't matter** - Focus on substance\n6. **Creative legal arguments are good** - Don't punish innovation\n7. **When in doubt, don't flag** - We want strategic legal intelligence\n\n## FINAL INSTRUCTION\n\nBe extremely permissive with legal intelligence reports. Only flag things that are completely false legal claims that would fundamentally change the legal advice. Remember: a report full of litigation strategies, risk assessments, and tactical recommendations is doing exactly what it should do. That's legal intelligence, not hallucination.\n\nThe goal is actionable legal guidance. If the strategy is sound even with minor citation imperfections, that's success.\n\n# RETRIEVED DOCUMENTS\n{{ \n  (() => {\n    const docs = $json['Retrieved Documents'] || '';\n    // 2.4M chars (~600K tokens) - main legal documents, cases, statutes\n    const maxChars = 2400000;\n    const processedDocs = typeof docs === 'string' ? docs : JSON.stringify(docs, null, 1);\n    \n    if (processedDocs.length > maxChars) {\n      // Try to truncate at a natural boundary for legal documents\n      let truncPoint = maxChars;\n      const boundaries = [\n        processedDocs.lastIndexOf('\\n\\n', maxChars),     // Section break\n        processedDocs.lastIndexOf('}\\n{', maxChars),     // Between JSON objects\n        processedDocs.lastIndexOf('\\n##', maxChars),     // Markdown section\n        processedDocs.lastIndexOf('Case:', maxChars),    // Case boundary\n        processedDocs.lastIndexOf('\\n', maxChars)        // Line break\n      ];\n      \n      for (const boundary of boundaries) {\n        if (boundary > maxChars * 0.95) {\n          truncPoint = boundary + 1;\n          break;\n        }\n      }\n      \n      return processedDocs.substring(0, truncPoint) + \n        '\\n\\n... [TRUNCATED - Verify only visible portion]';\n    }\n    return processedDocs;\n  })()\n}}\n\n# FINAL LEGAL REPORT TO VERIFY\n{{ \n  (() => {\n    const report = $json['Final Report'] || '';\n    // 800K chars (~200K tokens) - full legal analysis report\n    const maxChars = 800000;\n    const processedReport = typeof report === 'string' ? report : JSON.stringify(report, null, 1);\n    \n    if (processedReport.length > maxChars) {\n      // Try to truncate at a natural boundary for legal analysis\n      let truncPoint = maxChars;\n      const boundaries = [\n        processedReport.lastIndexOf('\\n## ', maxChars),      // Major section\n        processedReport.lastIndexOf('\\n### ', maxChars),     // Subsection\n        processedReport.lastIndexOf('\\n\\n', maxChars),       // Paragraph break\n        processedReport.lastIndexOf('. ', maxChars)          // Sentence end\n      ];\n      \n      for (const boundary of boundaries) {\n        if (boundary > maxChars * 0.9) {\n          truncPoint = boundary + 1;\n          break;\n        }\n      }\n      \n      return processedReport.substring(0, truncPoint) + \n        '\\n\\n... [TRUNCATED - Verify only visible portion]';\n    }\n    return processedReport;\n  })()\n}}","batching":{},"promptType":"define","needsFallback":true,"hasOutputParser":true},"retryOnFail":true,"typeVersion":1.7},{"id":"3e678562-4d1c-42ea-8fb5-3171aebf0ec6","name":"Structured Output Parser","type":"@n8n/n8n-nodes-langchain.outputParserStructured","position":[3824,512],"parameters":{"autoFix":true,"schemaType":"manual","inputSchema":"{\n  \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n  \"title\": \"Verification Report\",\n  \"type\": \"object\",\n  \"required\": [\"contains_hallucinations\", \"hallucinations\", \"summary\"],\n  \"properties\": {\n    \"contains_hallucinations\": {\n      \"type\": \"boolean\",\n      \"description\": \"True if ANY critical factual claim is not supported by retrieved documents\"\n    },\n    \"hallucinations\": {\n      \"type\": \"array\",\n      \"description\": \"List of specific unsupported claims\",\n      \"items\": {\n        \"type\": \"object\",\n        \"required\": [\"exact_text\", \"issue_type\", \"severity\"],\n        \"properties\": {\n          \"exact_text\": {\n            \"type\": \"string\",\n            \"description\": \"The EXACT text from the report that is unsupported\"\n          },\n          \"issue_type\": {\n            \"type\": \"string\",\n            \"enum\": [\"unsupported_number\", \"unsupported_date\", \"false_quote\", \"missing_entity\", \"unsupported_event\", \"unsupported_claim\"],\n            \"description\": \"Category of hallucination\"\n          },\n          \"severity\": {\n            \"type\": \"string\",\n            \"enum\": [\"critical\", \"moderate\", \"minor\"],\n            \"description\": \"How problematic this hallucination is\"\n          },\n          \"searched_in\": {\n            \"type\": \"string\",\n            \"description\": \"Which documents were checked for this claim\"\n          }\n        }\n      }\n    },\n    \"summary\": {\n      \"type\": \"string\",\n      \"description\": \"Brief summary - either 'All factual claims verified' or '3 critical hallucinations found: [list]'\"\n    }\n  }\n}"},"typeVersion":1.3},{"id":"9d5b8503-cb5e-4236-9248-ffb9368d4902","name":"If hallucinations present","type":"n8n-nodes-base.if","position":[4144,240],"parameters":{"options":{},"conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"3ac4aa73-45ff-4140-90d6-58cb115f069c","operator":{"type":"boolean","operation":"true","singleValue":true},"leftValue":"={{ $json.output.contains_hallucinations }}","rightValue":""},{"id":"e8b43be4-9505-4861-b915-801b10c87c06","operator":{"type":"number","operation":"lt"},"leftValue":"={{ $runIndex }}","rightValue":4}]}},"typeVersion":2.2},{"id":"9b61eec6-09ef-4697-9cc0-fc17cf3b3cdc","name":"Think Tool Analysis1","type":"@n8n/n8n-nodes-langchain.toolThink","position":[4656,512],"parameters":{"description":"=**Analysis Phase - Synthesize All Retrieved Texts**\n\nYour job: Analyze retrieved content to create strategic insights.\n\nRequired Analysis:\n1. Map findings to user query:\n   \"User asked about Prop 12 challenges\"\n   \n2. Identify patterns:\n   \"Pattern: All constitutional challenges have failed\"\n   \"Pattern: Enforcement increasing in 2024\"\n   \n3. Note contradictions:\n   \"9th Circuit upheld, but 6th Circuit questioning\"\n   \n4. Identify gaps:\n   \"No enforcement data after July 2024\"\n   \n5. Develop insights:\n   \"Legal challenges exhausted, focus shifting to compliance\"\n   \n6. Form recommendations:\n   \"Monitor state-level adoption rather than federal challenges\"\n\nFocus on:\n- Connecting dots between sources\n- Finding non-obvious patterns\n- Creating actionable intelligence\n\nThis shapes the final strategic report - think deeply!"},"typeVersion":1},{"id":"d2dc98b7-2572-4000-bfcf-10e957cd51f5","name":"Set Report","type":"n8n-nodes-base.set","position":[3504,240],"parameters":{"options":{},"assignments":{"assignments":[{"id":"0381fedf-0f65-4435-bd6f-197614916315","name":"Final Report","type":"string","value":"={{ $json.output }}"},{"id":"e68ea8cd-497f-4734-8581-912436d883fe","name":"Retrieved Documents","type":"string","value":"={{\n  (() => {\n    const steps = $('Step 3: Retrieval').item.json.intermediateSteps;\n    if (!steps || !Array.isArray(steps)) return 'No retrieval data available';\n    \n    // First pass: extract essential info from n8n LangChain structure\n    const cleanedData = steps.map((step, index) => {\n      const observation = step.observation || 'No response';\n      return {\n        step: index + 1,\n        tool: step.action?.tool || 'Unknown Tool',\n        input: step.action?.toolInput || {},\n        response: observation\n      };\n    }).filter(step => step.response && step.response !== 'No response');\n    \n    // Calculate per-response limit based on number of responses\n    const totalMaxLength = 400000; // Total character budget (~100k tokens)\n    const responseCount = cleanedData.length;\n    const overheadPerResponse = 200; // Estimate for step, tool, input fields\n    const totalOverhead = responseCount * overheadPerResponse;\n    const availableForResponses = totalMaxLength - totalOverhead;\n    \n    // Dynamic per-response limit (min 1000 chars, max 50000 chars per response)\n    const perResponseLimit = Math.min(\n      50000, \n      Math.max(1000, Math.floor(availableForResponses / responseCount))\n    );\n    \n    // Truncate individual responses if needed\n    const truncatedData = cleanedData.map(step => {\n      let response = step.response;\n      \n      // Convert to string if needed\n      if (typeof response !== 'string') {\n        response = JSON.stringify(response, null, 1);\n      }\n      \n      // Truncate if too long\n      if (response.length > perResponseLimit) {\n        response = response.substring(0, perResponseLimit) + \n          `\\n... [TRUNCATED from ${response.length} to ${perResponseLimit} chars]`;\n      }\n      \n      return {\n        ...step,\n        response: response.trim()\n      };\n    });\n    \n    // Final safety check on total size\n    let finalStr = JSON.stringify(truncatedData, null, 1);\n    if (finalStr.length > totalMaxLength) {\n      // If still too big, be more aggressive with largest responses\n      const sorted = [...truncatedData].sort((a, b) => \n        b.response.length - a.response.length\n      );\n      \n      // Truncate the largest responses more aggressively\n      for (let i = 0; i < Math.min(5, sorted.length); i++) {\n        const newLimit = Math.floor(perResponseLimit * 0.5);\n        if (sorted[i].response.length > newLimit) {\n          sorted[i].response = sorted[i].response.substring(0, newLimit) + \n            `\\n... [FURTHER TRUNCATED to ${newLimit} chars]`;\n        }\n      }\n      \n      // Re-sort by original order\n      truncatedData.sort((a, b) => a.step - b.step);\n      finalStr = JSON.stringify(truncatedData, null, 1);\n    }\n    \n    return finalStr;\n  })()\n}}"}]}},"typeVersion":3.4},{"id":"55a18db3-d5bc-423a-ab3e-70557411ba05","name":"Set Output","type":"n8n-nodes-base.set","position":[4832,240],"parameters":{"options":{},"assignments":{"assignments":[{"id":"b943ce2b-92a7-4fb5-b49a-df2894d5e445","name":"Final Report","type":"string","value":"={{ $('Set Report').item.json['Final Report'] }}"}]}},"typeVersion":3.4},{"id":"3802cd56-6381-4b60-9d88-286cd801ae9d","name":"Retry if Tools Not Used","type":"n8n-nodes-base.if","position":[784,240],"parameters":{"options":{},"conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"9bc6faa2-c596-4d24-8e2f-6f7888987d29","operator":{"type":"object","operation":"empty","singleValue":true},"leftValue":"={{ $json.intermediateSteps[0] }}","rightValue":""},{"id":"2aa597be-e115-4022-8abc-99909f29fd83","operator":{"type":"number","operation":"lt"},"leftValue":"={{ $runIndex }}","rightValue":4}]}},"typeVersion":2.2},{"id":"423a5281-89d2-49da-a2f9-8e3a434056be","name":"Retry if Tools Not Used1","type":"n8n-nodes-base.if","position":[2224,240],"parameters":{"options":{},"conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"9bc6faa2-c596-4d24-8e2f-6f7888987d29","operator":{"type":"object","operation":"empty","singleValue":true},"leftValue":"={{ $json.intermediateSteps[0] }}","rightValue":""},{"id":"2aa597be-e115-4022-8abc-99909f29fd83","operator":{"type":"number","operation":"lt"},"leftValue":"={{ $runIndex }}","rightValue":4}]}},"typeVersion":2.2},{"id":"95aec7d7-a6da-4ecf-a996-b3e1c33362d1","name":"Retry if Response Empty","type":"n8n-nodes-base.if","position":[1504,240],"parameters":{"options":{},"conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"9bc6faa2-c596-4d24-8e2f-6f7888987d29","operator":{"type":"object","operation":"empty","singleValue":true},"leftValue":"={{ $json.intermediateSteps[0] }}","rightValue":""},{"id":"2aa597be-e115-4022-8abc-99909f29fd83","operator":{"type":"number","operation":"lt"},"leftValue":"={{ $runIndex }}","rightValue":4}]}},"typeVersion":2.2},{"id":"fe4ca7f3-c372-4194-b37a-4fec37dc45de","name":"Retry if Response Empty1","type":"n8n-nodes-base.if","position":[3280,240],"parameters":{"options":{},"conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"9bc6faa2-c596-4d24-8e2f-6f7888987d29","operator":{"type":"string","operation":"empty","singleValue":true},"leftValue":"={{ $json.output }}","rightValue":""},{"id":"2aa597be-e115-4022-8abc-99909f29fd83","operator":{"type":"number","operation":"lt"},"leftValue":"={{ $runIndex }}","rightValue":4}]}},"typeVersion":2.2},{"id":"ff9633b7-bb51-4c7b-862d-94583e0fdf86","name":"Step 1: Discovery","type":"@n8n/n8n-nodes-langchain.agent","position":[384,240],"parameters":{"text":"=Current Date & Time: {{ $now }}\n\n{{ $('Trigger legal research request (Webhook)').item.json.body.prompt }}","options":{"maxIterations":10,"systemMessage":"=# 🔍 DISCOVERY AGENT\n\n## CRITICAL: Automated System Instructions\n**YOU ARE PART OF AN AUTOMATED PIPELINE. You CANNOT interact with the user, ask questions, or request clarification. You MUST process the exact query provided, regardless of its clarity or completeness. No exceptions.**\n\n## Mission\nSearch all legal databases for everything related to the query. Cast a wide net using the query AS PROVIDED.\n\n## Required Tools (Run ALL - NO EXCEPTIONS)\n1. **LegiScan** - Bills and legislation\n2. **Court Listener** - Cases and opinions  \n3. **DocumentCloud Search** - FOIA documents\n4. **Serper** - High-quality legal analysis\n\n## Output Format\n```\nDISCOVERY COMPLETE:\n- LegiScan: [X results found across Y searches]\n- Court Listener: [X results found across Y searches]  \n- DocumentCloud: [X results found across Y searches]\n- Serper: [X results found across Y searches]\nTotal: [X] items discovered for prioritization\n```","enableStreaming":true,"returnIntermediateSteps":true},"promptType":"define","needsFallback":true},"retryOnFail":true,"typeVersion":2.2},{"id":"743bad4c-949e-450f-9a27-2d9bd8e04aff","name":"Auto Fallback","type":"@n8n/n8n-nodes-langchain.lmChatOpenRouter","position":[224,496],"parameters":{"model":"openrouter/auto","options":{"temperature":0.8}},"credentials":{"openRouterApi":{"id":"nkdLVRx4aA33ZZgL","name":"Legal Research Agent"}},"typeVersion":1},{"id":"d08257a9-51c2-4a3b-8478-f7cc858fe0c0","name":"Auto Fallback1","type":"@n8n/n8n-nodes-langchain.lmChatOpenRouter","position":[1248,496],"parameters":{"model":"openrouter/auto","options":{"temperature":0.3}},"credentials":{"openRouterApi":{"id":"nkdLVRx4aA33ZZgL","name":"Legal Research Agent"}},"typeVersion":1},{"id":"6586b64f-126c-4546-92e5-4ca40fc2f39c","name":"Step 2: Prioritization","type":"@n8n/n8n-nodes-langchain.agent","position":[1200,240],"parameters":{"text":"=Current Date & Time: {{ $now }}\n\n# OUTPUT FROM PREVIOUS AGENT (Discovery Results)\n{{\n  (() => {\n    const steps = $json.intermediateSteps;\n    if (!steps || !Array.isArray(steps)) return 'No discovery data retrieved';\n    \n    // First pass: extract essential info from n8n LangChain structure\n    const cleanedData = steps.map((step, index) => {\n      const observation = step.observation || 'No response';\n      return {\n        step: index + 1,\n        tool: step.action?.tool || 'Unknown Tool',\n        input: step.action?.toolInput || {},\n        response: observation\n      };\n    }).filter(step => step.response && step.response !== 'No response');\n    \n    // Calculate per-response limit based on number of responses\n    const totalMaxLength = 2400000; // Total character budget for discovery data (~600K tokens)\n    const responseCount = cleanedData.length;\n    const overheadPerResponse = 200; // Estimate for step, tool, input fields\n    const totalOverhead = responseCount * overheadPerResponse;\n    const availableForResponses = totalMaxLength - totalOverhead;\n    \n    // Dynamic per-response limit (min 5000 chars, max 400000 chars per response)\n    const perResponseLimit = Math.min(\n      400000, \n      Math.max(5000, Math.floor(availableForResponses / responseCount))\n    );\n    \n    // Truncate individual responses if needed\n    const truncatedData = cleanedData.map(step => {\n      let response = step.response;\n      \n      // Convert to string if needed\n      if (typeof response !== 'string') {\n        response = JSON.stringify(response, null, 1);\n      }\n      \n      // Truncate if too long\n      if (response.length > perResponseLimit) {\n        // Try to truncate at a natural break point\n        let truncPoint = perResponseLimit;\n        \n        // Check multiple break point options in order of preference\n        const breakPoints = [\n          { pos: response.lastIndexOf('\\n\\n', perResponseLimit), type: 'paragraph' },\n          { pos: response.lastIndexOf('}\\n', perResponseLimit), type: 'json_object' },\n          { pos: response.lastIndexOf('\\n', perResponseLimit), type: 'newline' },\n          { pos: response.lastIndexOf('. ', perResponseLimit), type: 'sentence' },\n          { pos: response.lastIndexOf('}', perResponseLimit), type: 'brace' }\n        ];\n        \n        // Find the best break point that's at least 90% of the limit\n        for (const breakPoint of breakPoints) {\n          if (breakPoint.pos > perResponseLimit * 0.9) {\n            truncPoint = breakPoint.type === 'sentence' ? breakPoint.pos + 1 : breakPoint.pos;\n            if (breakPoint.type === 'brace' || breakPoint.type === 'json_object') {\n              truncPoint += 1;\n            }\n            break;\n          }\n        }\n        \n        response = response.substring(0, truncPoint) + \n          `\\n... [TRUNCATED from ${response.length.toLocaleString()} to ${truncPoint.toLocaleString()} chars]`;\n      }\n      \n      return {\n        ...step,\n        response: response.trim()\n      };\n    });\n    \n    // Final safety check on total size\n    let finalStr = JSON.stringify(truncatedData, null, 1);\n    if (finalStr.length > totalMaxLength) {\n      // If still too big, be more aggressive with largest responses\n      const sorted = [...truncatedData].sort((a, b) => \n        b.response.length - a.response.length\n      );\n      \n      // Truncate the largest responses more aggressively\n      const aggressiveLimit = Math.floor(perResponseLimit * 0.5);\n      for (let i = 0; i < Math.min(5, sorted.length); i++) {\n        if (sorted[i].response.length > aggressiveLimit) {\n          sorted[i].response = sorted[i].response.substring(0, aggressiveLimit) + \n            `\\n... [FURTHER TRUNCATED to ${aggressiveLimit.toLocaleString()} chars]`;\n        }\n      }\n      \n      // Re-sort by original order\n      truncatedData.sort((a, b) => a.step - b.step);\n      finalStr = JSON.stringify(truncatedData, null, 1);\n    }\n    \n    return finalStr;\n  })()\n}}\n\n# USER QUERY\n\n{{ $('Trigger legal research request (Webhook)').item.json.body.prompt }}\n\nAnalyze the discovery results and select the most relevant items for deep analysis based on the user query. Use the Think Tool to systematically score and rank all items.","options":{"maxIterations":10,"systemMessage":"=# 🎯 PRIORITIZATION AGENT\n\n## CRITICAL: Automated System Instructions\n\n**YOU ARE PART OF AN AUTOMATED PIPELINE. You CANNOT interact with the user, ask questions, or request clarification. You MUST process the discovery results exactly as provided, regardless of quality or completeness. No exceptions.**\n\n## Mission\n\nAnalyze discovery results and select the most relevant items for deep analysis based on the user query. Process whatever results you receive.\n\n## Required Tool\n\n**Think Tool** – MUST USE to systematically score and rank all items. No exceptions.\n\n## Scoring Criteria\n\nApply these criteria FRESH each time:\n\n* **Query match:** How directly it addresses user query\n* **Recency:** Newer generally scores higher\n* **Authority:** Federal > State, Higher courts > Lower\n* **Source quality:** Official > Secondary\n* **Uniqueness:** Avoid duplicates\n\n## Selection Targets\n\nSelect from whatever is available:\n\n* DocumentCloud: 1–5 documents (or all if fewer)\n* LegiScan Bills: 1–5 most significant (or all if fewer)\n* OpenStates Bills: 1–5 most significant (or all if fewer)\n* Cases: 1–5 key precedents (or all if fewer)\n* URLs: 1–5 best sources (or all if fewer)\n\n## Output: Prioritization Report\n\n```\nSELECTED FOR RETRIEVAL:\n\nDocumentCloud Documents:\n1. ID: [id], Slug: [slug]\n   Title: [title]\n   Why: [specific reason for selection]\n[Or \"None found in discovery results\"]\n\nLegiScan Bills:\n1. ID: [id], Number: [bill number]\n   Title: [title]\n   Why: [relevance to query]\n[Or \"None found in discovery results\"]\n\nOpenStates Bills:\n1. ID: [full id, e.g. ocd-bill/123e4567-…]\n   UUID: [uuid only, e.g. 123e4567-…]\n   Identifier: [bill number]\n   Title: [title]\n   Why: [relevance to query]\n[Or \"None found in discovery results\"]\n\nCourt Cases:\n1. ID: [id], Name: [case name]\n   Why: [precedential value]\n[Or \"None found in discovery results\"]\n\nURLs:\n1. [full URL]\n   Title: [title]\n   Why: [authority/insight value]\n[Or \"None found in discovery results\"]\n```","enableStreaming":true,"returnIntermediateSteps":true},"promptType":"define","needsFallback":true},"retryOnFail":true,"typeVersion":2.2},{"id":"cc278656-cdbb-41aa-845b-17ecf23e57eb","name":"Auto Fallback2","type":"@n8n/n8n-nodes-langchain.lmChatOpenRouter","position":[1808,496],"parameters":{"model":"openrouter/auto","options":{"temperature":0.2}},"credentials":{"openRouterApi":{"id":"nkdLVRx4aA33ZZgL","name":"Legal Research Agent"}},"typeVersion":1},{"id":"bf2e1b99-1c7b-46d6-be52-e602fc74b860","name":"Step 3: Retrieval","type":"@n8n/n8n-nodes-langchain.agent","position":[1904,240],"parameters":{"text":"=Current Date & Time: {{ $now }}\n\n{{ \n  JSON.stringify($json.output).slice(0, 1000000)\n}}\n\nRetrieve the full text of every prioritized item listed above. Use the appropriate retrieval method for each type of resource.\n\nEXTREMELY IMPORTANT: USE ALL OF YOUR TOOLS TO FIND THESE DOCUMENTS, NEVER RETURN A RESPONSE UNTIL ALL TOOLS HAVE BEEN USED","options":{"maxIterations":10,"systemMessage":"=# 📥 RETRIEVAL AGENT\n\n## CRITICAL: Automated System Instructions\n**YOU ARE PART OF AN AUTOMATED PIPELINE. You CANNOT interact with the user, ask questions, or request clarification. You MUST retrieve whatever items are specified, regardless of errors or issues. No exceptions.**\n\n## Mission\nGet the full text of every prioritized item. No analysis, just retrieval.\n\n## Retrieval Methods\n\n**DocumentCloud:**\n```\nhttps://s3.documentcloud.org/documents/{id}/{slug}.txt.json\n```\n- Always include \"/\" between ID and slug\n\n**LegiScan:**\n```\nhttps://api.legiscan.com/?op=getBill&id={bill_id}\n```\n\n**Court Listener:**\n- Extract full opinion text using provided ID\n\n**URLs:**\n- Use Jina Reader for each URL\n\n## Output Format\n```\nDocumentCloud Texts:\n- [ID]: [Success - X pages retrieved / Failed - 404]\n\nLegiScan Bills:\n- [Bill ID]: [Success - full text retrieved / Failed - error]\n\nCourt Opinions:\n- [Case ID]: [Success - opinion text retrieved / Failed - error]\n\nArticle URLs:\n- [URL]: [Success - content extracted / Failed - error]\n```\n\nEXTREMELY IMPORTANT: USE ALL OF YOUR TOOLS TO FIND THESE DOCUMENTS, NEVER RETURN A RESPONSE UNTIL ALL TOOLS HAVE BEEN USED","enableStreaming":true,"returnIntermediateSteps":true},"promptType":"define","needsFallback":true},"retryOnFail":true,"typeVersion":2.2},{"id":"6cd8e053-713a-48cb-85f2-ecce5c344256","name":"Auto Fallback3","type":"@n8n/n8n-nodes-langchain.lmChatOpenRouter","position":[2976,512],"parameters":{"model":"openrouter/auto","options":{"temperature":0.6}},"credentials":{"openRouterApi":{"id":"nkdLVRx4aA33ZZgL","name":"Legal Research Agent"}},"typeVersion":1},{"id":"1ec98802-8617-4816-8c22-2f785c2131e4","name":"Step 4: Report Writing","type":"@n8n/n8n-nodes-langchain.agent","position":[2960,240],"parameters":{"text":"=Current Date & Time: {{ $now }}\n\n# RETRIEVED DOCUMENTS\n\n{{\n  (() => {\n    const steps = $json.intermediateSteps;\n    if (!steps || !Array.isArray(steps)) return 'No data retrieved';\n    \n    // First pass: extract essential info\n    const cleanedData = steps.map((step, index) => {\n      const observation = step.observation || 'No response';\n      return {\n        step: index + 1,\n        tool: step.action?.tool || 'Unknown Tool',\n        input: step.action?.toolInput || {},\n        response: observation\n      };\n    }).filter(step => step.response && step.response !== 'No response');\n    \n    // Calculate per-response limit based on number of responses\n    const totalMaxLength = 500000; // Total character budget (~125K tokens)\n    const responseCount = cleanedData.length;\n    const overheadPerResponse = 200; // Estimate for step, tool, input fields\n    const totalOverhead = responseCount * overheadPerResponse;\n    const availableForResponses = totalMaxLength - totalOverhead;\n    \n    // Dynamic per-response limit (min 1000 chars, max 100000 chars per response)\n    const perResponseLimit = Math.min(\n      100000, \n      Math.max(1000, Math.floor(availableForResponses / responseCount))\n    );\n    \n    // Truncate individual responses if needed\n    const truncatedData = cleanedData.map(step => {\n      let response = step.response;\n      \n      // Convert to string if needed\n      if (typeof response !== 'string') {\n        response = JSON.stringify(response, null, 1);\n      }\n      \n      // Truncate if too long\n      if (response.length > perResponseLimit) {\n        response = response.substring(0, perResponseLimit) + \n          `\\n... [TRUNCATED from ${response.length} to ${perResponseLimit} chars]`;\n      }\n      \n      return {\n        ...step,\n        response: response.trim()\n      };\n    });\n    \n    // Final safety check on total size\n    const finalStr = JSON.stringify(truncatedData, null, 1);\n    if (finalStr.length > totalMaxLength) {\n      // If still too big, be more aggressive with largest responses\n      const sorted = truncatedData.sort((a, b) => \n        b.response.length - a.response.length\n      );\n      \n      // Truncate the largest responses more aggressively\n      for (let i = 0; i < Math.min(5, sorted.length); i++) {\n        const newLimit = Math.floor(perResponseLimit * 0.5);\n        if (sorted[i].response.length > newLimit) {\n          sorted[i].response = sorted[i].response.substring(0, newLimit) + \n            `\\n... [TRUNCATED to ${newLimit} chars]`;\n        }\n      }\n      \n      // Re-sort by original order\n      truncatedData.sort((a, b) => a.step - b.step);\n    }\n    \n    return JSON.stringify(truncatedData, null, 1);\n  })()\n}}\n\n# INSTRUCTIONS\n\nWrite a comprehensive strategic report based on all provided texts that directly addresses the user's query.\n\n# USER QUERY\n\n{{ $('Trigger legal research request (Webhook)').item.json.body.prompt }}","options":{"maxIterations":10,"systemMessage":"=# 📝 LEGAL INTELLIGENCE REPORT WRITING AGENT\n\n## Your Mission\nCreate a highly responsive legal intelligence report that **directly answers what the user needs to know**. Focus on immediate utility - lead with what matters most for their specific legal question, whether that's understanding precedent, assessing compliance risk, finding litigation strategies, or analyzing regulatory exposure.\n\n## CRITICAL: Automated System Instructions\n\n**YOU ARE PART OF AN AUTOMATED PIPELINE. This is a ONE-SHOT report generation with NO follow-up possible.**\n\n### Absolute Requirements:\n- You CANNOT interact with the user after this report\n- You CANNOT ask questions or request clarification  \n- You CANNOT offer to do additional research or analysis\n- You MUST produce a complete, final report right now\n- You MUST work with whatever information you have\n\n### NEVER write phrases like:\n- \"Would you like me to...\"\n- \"I can also look into...\"\n- \"Let me know if you need...\"\n- \"Feel free to ask for...\"\n- \"I could further analyze...\"\n- \"If you want more detail on...\"\n- \"Should you need additional...\"\n- \"I'm happy to explore...\"\n- \"Would you prefer...\"\n- \"Shall I continue with...\"\n\n### INSTEAD:\n- Write a complete, self-contained report\n- Include all relevant analysis in THIS response\n- Make definitive statements and recommendations\n- Provide all insights you can generate NOW\n- Present findings as final deliverables\n\n### CITATION REQUIREMENTS:\n- **EVERY factual claim must include its source**\n- **ALWAYS include the full URL** when available\n- **Use inline citations** with [Source: URL] AND footnotes\n- **Never make unsourced claims** about verifiable facts\n- **If multiple sources support a claim**, cite all relevant ones\n\n### COMPREHENSIVENESS PRINCIPLE:\n**Create a LONG, DETAILED report with MOST IMPORTANT findings at the top**\n- **Executive Summary first** with key findings and recommendations\n- **Include ALL relevant information** from retrieved documents\n- **Don't summarize or condense** - be exhaustive with details\n- **Use extensive quotes** from source materials\n- **Provide complete analysis** of every relevant aspect\n- **Length is NOT a concern** - thoroughness is paramount\n- **Organize by importance** - critical findings first, supporting details follow\n- **Extract maximum value** from every document retrieved\n\n**This is your ONLY opportunity to provide value to the user. Make the report comprehensive, detailed, and complete. The user would rather have too much information than too little.**\n\n## CORE PRINCIPLES\n\n### 1. BE RESPONSIVE TO THE LEGAL QUERY\n- **Understand what they're really asking** - Litigation strategy? Compliance guidance? Risk assessment? Legislative tracking?\n- **Lead with the answer** - Put the most relevant legal findings first\n- **Adapt structure to the query** - Don't force legal documents into generic templates\n- **Match their legal context** - Litigation needs different focus than regulatory compliance\n\n### 2. SYNTHESIZE LEGAL INTELLIGENCE\n- **Connect across sources** - Link court opinions to regulations to legislation\n- **Build legal arguments** - Show how precedents support positions\n- **Identify legal patterns** - Recurring judicial reasoning, regulatory trends\n- **Create actionable intelligence** - What can they actually DO with this?\n\n### 3. PROVIDE PRACTICAL LEGAL VALUE\n- **Make it actionable** - Specific legal strategies, not just summaries\n- **Cite authoritatively** - Full citations lawyers can use\n- **Assess strength** - How solid is this precedent? How likely to succeed?\n- **Recommend next steps** - Concrete legal actions to take\n\n## ADAPTIVE WRITING APPROACH\n\n### Lead with Maximum Legal Impact\n- First paragraph should **directly answer their legal question**\n- Provide the most important precedent, statute, or finding immediately\n- Make clear whether the law supports or opposes their position\n\n### Organize by Legal Relevance\n\n**For Litigation Strategy Queries:**\n1. Strongest precedents and arguments (first!)\n2. Weaknesses and counterarguments\n3. Procedural considerations\n4. Discovery opportunities\n5. Settlement leverage points\n6. Recommended litigation approach\n\n**For Compliance/Regulatory Queries:**\n1. Clear compliance requirements (first!)\n2. Regulatory enforcement patterns\n3. Safe harbors and exemptions\n4. Risk areas and violations\n5. Best practices from settlements\n6. Compliance roadmap\n\n**For Legislative/Policy Queries:**\n1. Current legal landscape (first!)\n2. Pending changes and timeline\n3. Legislative history and intent\n4. Stakeholder positions\n5. Amendment opportunities\n6. Strategic recommendations\n\n**For Risk Assessment Queries:**\n1. Primary legal exposures (first!)\n2. Probability and severity analysis\n3. Recent enforcement actions\n4. Mitigation strategies\n5. Insurance/indemnity considerations\n6. Action priorities\n\n**For Precedent Research Queries:**\n1. Controlling cases (first!)\n2. Factual similarities/distinctions\n3. Circuit splits or conflicts\n4. Trend in recent decisions\n5. Strategic use of precedents\n\n## CONTENT OPTIMIZATION FOR LEGAL INTELLIGENCE\n\n### Emphasize High-Value Legal Content:\n- **Binding precedent** with similar facts\n- **Recent regulatory actions** showing enforcement priorities  \n- **Successful arguments** from similar cases\n- **Settlement patterns** revealing negotiation points\n- **Judge-specific** tendencies and preferences\n- **Procedural advantages** and deadlines\n\n### Minimize Low-Value Filler:\n- Generic legal background\n- Outdated precedents (unless showing evolution)\n- Peripheral regulatory guidance\n- Non-binding opinions without persuasive value\n- Academic commentary without practical application\n\n### Source Integration Hierarchy:\n1. **Most Authoritative:** Supreme Court, Circuit Courts for jurisdiction\n2. **Highly Relevant:** District Courts in same jurisdiction, key regulations\n3. **Persuasive:** Other circuits, state courts, agency guidance\n4. **Contextual:** Legislative history, policy documents, settlements\n5. **Supplementary:** News, analysis, commentary\n\n## WRITING STYLE FOR LEGAL INTELLIGENCE\n\n### Be Direct and Authoritative\n**Strong:** \"The Fifth Circuit's holding in Smith directly supports your position that...\"\n**Weak:** \"There may be some cases that could potentially be relevant...\"\n\n### Connect Legal Authorities\n**Strong:** \"This builds on Jones, where the court similarly found that when combined with the SEC's recent enforcement action...\"\n**Weak:** \"Jones is a case. The SEC did an enforcement.\"\n\n### Make Strategic Assessments\n**Strong:** \"This creates a compelling argument for summary judgment, particularly given Judge Chen's prior rulings favoring...\"\n**Weak:** \"This might be useful in litigation.\"\n\n### Quantify When Possible\n**Strong:** \"Courts have granted this motion 73% of the time when these three factors are present\"\n**Weak:** \"Courts sometimes grant this motion\"\n\n## ADAPTIVE STRUCTURE EXAMPLES\n\n### For \"Can we sue [Company] for [Issue]?\"\nStart with:\n> \"**Litigation Viability: Strong/Moderate/Weak.** You have viable claims under [specific laws] based on [key precedent]. The primary cause of action would be [claim] supported by [case law]. Similar cases have resulted in [outcomes]. Key challenges include [issues]. Recommended approach: [strategy]...\"\n\n### For \"Are we compliant with [Regulation]?\"\nStart with:\n> \"**Compliance Assessment: [Compliant/Non-Compliant/Partially Compliant].** Based on [regulation section] and recent enforcement actions, your current practices [meet/fail/partially meet] requirements. Specific gaps: [issues]. The FDA's 2024 warning letters show enforcement focus on [priorities]. Required actions: [steps]...\"\n\n### For \"What's our exposure for [Activity]?\"\nStart with:\n> \"**Risk Level: [High/Medium/Low].** Your exposure primarily stems from [legal theory] under [statute/regulation]. Recent cases show damages ranging from [range] with [probability]. The [Agency] has brought [number] similar actions with [success rate]. Mitigation strategies include...\"\n\n### For \"Find precedent for [Legal Argument]\"\nStart with:\n> \"**Precedent Strength: [Strong/Moderate/Developing].** [Case] provides direct support, holding that [quote]. This has been followed by [courts] and distinguished only when [factors]. Applied to your facts: [analysis]. Counter-precedent exists in [case] but is distinguishable because...\"\n\n## SECTION FLEXIBILITY\n\nUse sections that serve the legal purpose:\n- \"Winning Arguments\"\n- \"Litigation Risks and Mitigation\"  \n- \"Regulatory Enforcement Patterns\"\n- \"Settlement Leverage Points\"\n- \"Procedural Opportunities\"\n- \"Discovery Strategies\"\n- \"Compliance Roadmap\"\n- \"Legislative Strategy\"\n- \"Risk Matrix\"\n- \"Action Items with Deadlines\"\n\n## CITATION STANDARDS\n\n### In-Text Citations:\n- **Cases:** Smith v. Jones, 123 F.3d 456, 459 (5th Cir. 2023)\n- **Statutes:** 15 U.S.C. § 78dd-1(a)(1)\n- **Regulations:** 17 C.F.R. § 240.10b-5\n- **Direct quotes:** Include pincites always\n\n### Source References:\n- Include hyperlinks to DocumentCloud, CourtListener, LegiScan\n- Note which database each document came from\n- Provide full citations lawyers can use in briefs\n\n## PRACTICAL LEGAL DELIVERABLES\n\n### Always Include When Relevant:\n- **Key deadlines** (statute of limitations, filing dates)\n- **Specific causes of action** with elements\n- **Burden of proof** and who bears it\n- **Discovery opportunities** and what to request\n- **Settlement ranges** from comparable cases\n- **Judge assignments** and their tendencies\n- **Jury verdict data** if applicable\n\n### Strategic Additions:\n- Proposed legal arguments in order of strength\n- Anticipated counterarguments and responses\n- Alternative legal theories if primary fails\n- Negotiation talking points\n- Compliance checklist\n- Risk mitigation steps\n\n## OUTPUT GUIDELINES\n\n### Start Immediately\nBegin with the report - no preamble about process.\n\n### Match Depth to Need\n- Quick legal question = concise answer with key authorities\n- Complex litigation = comprehensive strategy with all precedents\n- Compliance review = detailed requirements and gap analysis\n\n### End with Action\nClose with specific next steps, not just source lists.\n\n## QUALITY CHECKLIST\n\nBefore finishing:\n1. ✓ First paragraph directly answers their legal question\n2. ✓ Most relevant authorities cited first\n3. ✓ Legal reasoning clearly explained\n4. ✓ Strategic recommendations specific and actionable\n5. ✓ Structure adapted to their query type\n6. ✓ Citations complete and accurate\n7. ✓ Practical next steps identified\n\n## FINAL INSTRUCTION\n\n**Write the report immediately.** Start with the direct answer to their legal question. Build structure around their specific needs - litigation strategy needs different organization than compliance review. Every legal finding should be actionable. The goal is legal intelligence they can use immediately.\n\nRemember: They need practical legal guidance, not academic analysis. Focus on what they can DO with the legal information.","enableStreaming":true,"returnIntermediateSteps":true},"promptType":"define","needsFallback":true},"retryOnFail":true,"typeVersion":2.2},{"id":"08607ef2-2ca2-48cd-8c7b-e88b80c4303f","name":"Auto Fallback4","type":"@n8n/n8n-nodes-langchain.lmChatOpenRouter","position":[3696,512],"parameters":{"model":"openrouter/auto","options":{"temperature":0.2}},"credentials":{"openRouterApi":{"id":"nkdLVRx4aA33ZZgL","name":"Legal Research Agent"}},"typeVersion":1},{"id":"b754e32c-7411-42fd-a32c-04845d7f03d7","name":"Auto Fallback5","type":"@n8n/n8n-nodes-langchain.lmChatOpenRouter","position":[4384,512],"parameters":{"model":"openrouter/auto","options":{"temperature":0.1}},"credentials":{"openRouterApi":{"id":"nkdLVRx4aA33ZZgL","name":"Legal Research Agent"}},"typeVersion":1},{"id":"f2833edb-c79d-40f0-a92e-627406d3ba16","name":"Step 6: Fixing Hallucinations","type":"@n8n/n8n-nodes-langchain.agent","position":[4352,240],"parameters":{"text":"=Current Date & Time: {{ $now }}\n# **User's Original Query**\n{{ $('Trigger legal research request (Webhook)').item.json.body.prompt }}\n\n# **Retrieved Documents** - All full texts with their source URLs\n{{ \n  (() => {\n    const docs = JSON.stringify($('Step 3: Retrieval').item.json.intermediateSteps);\n    // 1.6M chars (~400K tokens) - this is your main content\n    return docs.length > 1600000 ? docs.slice(0, 1600000) + '\\n... [TRUNCATED]' : docs;\n  })()\n}}\n# **Failed Report** - The report that contains hallucinations\n{{ \n  (() => {\n    const report = $('Set Report').item.json['Final Report'] || '';\n    // 800K chars (~200K tokens) - full report should fit\n    return report.length > 800000 ? report.substring(0, 800000) + '\\n... [TRUNCATED]' : report;\n  })()\n}}\n# **Hallucinations** - FIX THESE PROBLEMS\n{{ \n  (() => {\n    const h = JSON.stringify($json.output.hallucinations, null, 2);\n    // 80K chars (~20K tokens) - comprehensive hallucination list\n    return h.length > 80000 ? h.slice(0, 80000) + '\\n... [TRUNCATED]' : h;\n  })()\n}}","options":{"maxIterations":10,"systemMessage":"=# 📝 LEGAL INTELLIGENCE REWRITE AGENT\n\n## Mission\nFix all identified hallucinations in the legal report while preserving valid strategic analysis. You must correct errors properly - don't leave false information in the report.\n\n## CRITICAL: Automated System Instructions\n\n**YOU ARE PART OF AN AUTOMATED PIPELINE. This is a ONE-SHOT report generation with NO follow-up possible.**\n\n### Absolute Requirements:\n- You CANNOT interact with the user after this report\n- You CANNOT ask questions or request clarification  \n- You CANNOT offer to do additional research or analysis\n- You MUST produce a complete, final report right now\n- You MUST work with whatever information you have\n\n### NEVER write phrases like:\n- \"Would you like me to...\"\n- \"I can also look into...\"\n- \"Let me know if you need...\"\n- \"Feel free to ask for...\"\n- \"I could further analyze...\"\n- \"If you want more detail on...\"\n- \"Should you need additional...\"\n- \"I'm happy to explore...\"\n- \"Would you prefer...\"\n- \"Shall I continue with...\"\n\n### INSTEAD:\n- Write a complete, self-contained report\n- Include all relevant analysis in THIS response\n- Make definitive statements and recommendations\n- Provide all insights you can generate NOW\n- Present findings as final deliverables\n\n### CITATION REQUIREMENTS:\n- **EVERY factual claim must include its source**\n- **ALWAYS include the full URL** when available\n- **Use inline citations** with [Source: URL] AND footnotes\n- **Never make unsourced claims** about verifiable facts\n- **If multiple sources support a claim**, cite all relevant ones\n\n### COMPREHENSIVENESS PRINCIPLE:\n**Create a LONG, DETAILED report with MOST IMPORTANT findings at the top**\n- **Executive Summary first** with key findings and recommendations\n- **Include ALL relevant information** from retrieved documents\n- **Don't summarize or condense** - be exhaustive with details\n- **Use extensive quotes** from source materials\n- **Provide complete analysis** of every relevant aspect\n- **Length is NOT a concern** - thoroughness is paramount\n- **Organize by importance** - critical findings first, supporting details follow\n- **Extract maximum value** from every document retrieved\n\n**This is your ONLY opportunity to provide value to the user. Make the report comprehensive, detailed, and complete. The user would rather have too much information than too little.**\n\n\n## CORE RESPONSIBILITY\n\n### You MUST Fix Hallucinations\n- **If a case is cited wrong** - Correct it or remove the citation\n- **If a statute doesn't exist** - Find the right one or remove the claim  \n- **If a fact is false** - Correct it with accurate information\n- **If a quote is fabricated** - Remove or replace with actual quote\n- **If data is wrong** - Fix with correct data or remove\n\n### You SHOULD Preserve\n- **Valid legal analysis** based on correct law\n- **Strategic recommendations** that don't depend on false facts\n- **Risk assessments** grounded in real evidence\n- **Procedural suggestions** that are legally sound\n- **Tactical insights** based on actual patterns\n\n## HOW TO FIX HALLUCINATIONS PROPERLY\n\n### For Each Identified Error:\n\n**Step 1: Assess the Error**\n- What exactly is wrong?\n- What would be correct?\n- Does the conclusion depend on this error?\n\n**Step 2: Choose Appropriate Fix**\n\n**If Correctable:** \n- Replace with accurate information from sources\n- Update case citations to real cases\n- Fix statute numbers to actual statutes\n- Correct dates, names, amounts with real data\n\n**If Partially Salvageable:**\n- Remove false specifics, keep valid general principle\n- Delete wrong citation, preserve sound legal argument\n- Fix incorrect details, maintain strategic point\n- Correct the error, retain the analysis if still valid\n\n**If Uncorrectable:**\n- Remove the false claim entirely\n- Delete unsupported conclusions\n- Cut sections that depend on the error\n- Eliminate recommendations based on false premises\n\n## WHAT TO ACTUALLY DO\n\n### With False Case Citations:\n- ❌ DON'T keep \"Smith v. Jones\" if it doesn't exist\n- ✅ DO find the actual case that supports the principle\n- ✅ DO remove the citation if no case supports it\n- ✅ DO keep the legal argument ONLY if another source supports it\n\n### With Wrong Statutes/Regulations:\n- ❌ DON'T leave incorrect statute numbers\n- ✅ DO find the correct statutory citation\n- ✅ DO remove claims about non-existent laws\n- ✅ DO preserve compliance strategies based on real requirements\n\n### With Fabricated Facts:\n- ❌ DON'T keep false settlement amounts, dates, or data\n- ✅ DO replace with accurate information if available\n- ✅ DO remove specific claims you can't verify\n- ✅ DO keep general assessments if pattern is real\n\n### With Misrepresented Holdings:\n- ❌ DON'T leave incorrect descriptions of what courts held\n- ✅ DO correct the holding to what court actually said\n- ✅ DO remove if the case doesn't support the point\n- ✅ DO find alternative support if principle is valid\n\n## PRESERVE VALID ANALYSIS\n\n### Keep Strategic Content That's Based on Real Law:\n- Litigation strategies grounded in actual precedent\n- Risk assessments based on real enforcement patterns\n- Discovery plans targeting actual issues\n- Settlement strategies based on verified comparables\n- Procedural recommendations following real rules\n\n### Keep Professional Judgments That Don't Depend on Errors:\n- \"This approach typically succeeds\" (if true)\n- \"Courts in this jurisdiction favor...\" (if pattern exists)\n- \"Discovery should focus on...\" (if targets are real)\n- \"Settlement range likely...\" (if based on real data)\n\n### Remove or Fix Analysis Built on False Foundations:\n- If strategy depends on non-existent case → Remove or rebuild\n- If risk assessment based on false data → Correct or cut\n- If recommendation assumes wrong law → Fix or eliminate\n\n## QUALITY STANDARDS\n\n### Your Output Must:\n1. **Contain NO identified hallucinations** - All must be fixed or removed\n2. **Preserve valid strategic insights** - Keep what's legally sound\n3. **Maintain coherent flow** - Add transitions if needed\n4. **Provide accurate legal guidance** - Based on real law\n5. **Support the original query** - Stay responsive to what was asked\n\n### Acceptable Corrections:\n- Replacing false cases with real precedents\n- Correcting statute numbers to actual law\n- Fixing wrong dates/amounts with accurate data\n- Removing unsupported specific claims\n- Generalizing when specifics can't be verified\n\n### Unacceptable Approaches:\n- Leaving false citations with minor tweaks\n- Keeping fabricated facts with qualifiers\n- Preserving errors with hedging language\n- Maintaining false legal claims as \"analysis\"\n\n## REWRITE PROCESS\n\n1. **Identify each hallucination** from the verification\n2. **Determine correct information** from sources\n3. **Fix or remove the error** completely\n4. **Assess impact on surrounding analysis**\n5. **Preserve valid points** that don't depend on error\n6. **Ensure coherent flow** after corrections\n7. **Maintain strategic value** where legally sound\n\n## OUTPUT REQUIREMENTS\n\n### Final Report Must:\n- Be factually accurate on all legal claims\n- Contain no identified hallucinations\n- Preserve valuable strategic content where valid\n- Maintain professional legal analysis\n- Remain responsive to original query\n\n### Start Immediately:\n- No preamble about corrections\n- Output the fixed report directly\n- Ensure smooth, professional reading\n\n## FINAL INSTRUCTION\n\nFix every identified hallucination properly - either correct it with accurate information or remove it entirely. Preserve strategic analysis and recommendations that are based on sound legal foundations. The goal is an accurate legal report that maintains its strategic value while containing no false legal claims.\n\nRemember: False legal information is dangerous. Fix it properly. But valid legal strategy based on correct law is valuable - preserve it.","enableStreaming":true,"returnIntermediateSteps":true},"promptType":"define","needsFallback":true},"retryOnFail":true,"typeVersion":2.2},{"id":"fa83043e-f9c8-4c0c-845e-d002577a3c6b","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[0,0],"parameters":{"color":7,"width":2656,"height":800,"content":"## Research & Tool Use\nThis section of the workflow focuses on finding the information that the next section will use to write and verify its report"},"typeVersion":1},{"id":"87532eeb-50a7-4ae3-bc8a-389d234d5315","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[2736,0],"parameters":{"color":7,"width":2320,"height":800,"content":"## Report Writing & Verification\nThis section of the workflow focuses on writing the user-facing report and ensuring it is accurate and free from hallucinations"},"typeVersion":1},{"id":"43e75cc9-9b65-45d7-919a-d713f3c063f9","name":"If Empty Output","type":"n8n-nodes-base.if","position":[4640,240],"parameters":{"options":{},"conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"loose"},"combinator":"and","conditions":[{"id":"7c9099fa-f4dd-49de-a916-a344368bbeda","operator":{"type":"string","operation":"empty","singleValue":true},"leftValue":"={{ $json.output }}","rightValue":""}]},"looseTypeValidation":true},"typeVersion":2.2},{"id":"3ad4fc38-631c-4d6f-af57-bba54e2dd414","name":"If Empty Output1","type":"n8n-nodes-base.if","position":[3968,240],"parameters":{"options":{},"conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"loose"},"combinator":"and","conditions":[{"id":"7c9099fa-f4dd-49de-a916-a344368bbeda","operator":{"type":"object","operation":"empty","singleValue":true},"leftValue":"={{ $json.output }}","rightValue":""}]},"looseTypeValidation":true},"typeVersion":2.2},{"id":"27d55619-9178-4f6c-a5e1-6bb2fe9de94b","name":"Plural Retrieval","type":"n8n-nodes-base.httpRequestTool","position":[2480,496],"parameters":{"url":"={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('URL', ``, 'string') }}","options":{"batching":{"batch":{"batchSize":1}}},"sendHeaders":true,"authentication":"genericCredentialType","genericAuthType":"httpHeaderAuth","toolDescription":"=# Retrieval Phase – Get Full Details for SELECTED Items\n\n**CRITICAL:** ALWAYS use the full base URL. **No new searching.** Only retrieve the specific bills/entities chosen in Discovery. Include your API key via `X-API-KEY` header (recommended) or `?apikey=`.\n\n**Base URL:** `https://v3.openstates.org/`\n\n---\n\n## Bill Detail (by internal UUID)\n\n**Endpoint:**\n`GET https://v3.openstates.org/bills/ocd-bill/{uuid}`\n\nUse when you stored the Open States internal bill ID (recommended). The **UUID** is the part **after** `ocd-bill/` in the bill’s `id` (e.g., for `id=\"ocd-bill/123e...\"`, pass `123e...`).\n\n**Example:**\n\n```\nhttps://v3.openstates.org/bills/ocd-bill/123e4567-e89b-12d3-a456-426614174000?include=actions&include=votes&include=versions&include=documents&include=sources&include=sponsorships\n```\n\n**What you get:** canonical bill metadata (title, identifier, session, subjects, etc.) + any **included** related data you request:\n\n* `sponsorships` (with roles like primary/cosponsor)\n* `actions` (timeline)\n* `votes` (roll calls)\n* `versions` (bill text files)\n* `documents` (analyses, summaries)\n* `sources` (original URLs)\n\n---\n\n## Bill Detail (by friendly components)\n\n**Endpoint:**\n`GET https://v3.openstates.org/bills/{jurisdiction}/{session}/{identifier}`\n\nUse if you have the human-readable parts (e.g., `California/2023-2024/AB 123`).\n\n**Example:**\n\n```\nhttps://v3.openstates.org/bills/California/2023-2024/AB%20123?include=actions&include=votes&include=versions\n```\n\n---\n\n## Getting the Actual Text\n\nOpen States returns **links** to bill texts under `versions` (and related `documents`). Use the `url` fields there to download the PDF/HTML from the official legislature site; there is **no separate “bill text body” endpoint**—you follow `versions[].url`.\n\n---\n\n## People, Committees, Events (detail)\n\nIf Discovery saved specific IDs:\n\n* **Person:** `GET https://v3.openstates.org/people/{person_id}`\n* **Committee:** `GET https://v3.openstates.org/committees/{committee_id}`\n* **Event:** `GET https://v3.openstates.org/events/{event_id}`\n\nUse `include=` as needed (e.g., `memberships` for people/committees, `participants&include=agenda` for events). Coverage may vary by jurisdiction.\n\n---\n\n## CORRECT Retrieval URLs\n\n✅\n\n```\nhttps://v3.openstates.org/bills/ocd-bill/123e4567-e89b-12d3-a456-426614174000?include=actions&include=votes&include=versions&include=documents\n```\n\n✅\n\n```\nhttps://v3.openstates.org/bills/California/2023-2024/SB%2050?include=documents&include=actions\n```\n\n## WRONG (Missing base URL or doing discovery)\n\n❌ `/bills/ocd-bill/{uuid}` *(missing base URL)*\n❌ `https://v3.openstates.org/bills?q=housing` *(that’s a **search**, not retrieval—don’t do new discovery here)*\n❌ `https://v3.openstates.org/bills/ocd-bill/ocd-bill/{uuid}` *(double `ocd-bill/` segment – invalid)*\n❌ `?include=sponsors,actions` *(comma list and invalid field name)*\n\n---\n\n## Minimal Response Shape (detail with includes)\n\n```json\n{\n  \"id\": \"ocd-bill/…\",\n  \"identifier\": \"AB 123\",\n  \"title\": \"Full title…\",\n  \"jurisdiction\": \"California\",\n  \"session\": \"2023-2024\",\n  \"subjects\": [\"Housing\"],\n  \"sponsorships\": [{ \"name\": \"Jane Doe\", \"classification\": \"primary\" }],\n  \"actions\": [{ \"date\": \"2025-02-01\", \"description\": \"Introduced\" }],\n  \"votes\": [{ \"motion_text\": \"...\", \"result\": \"pass\" }],\n  \"versions\": [{ \"note\": \"Introduced\", \"url\": \"https://...\" }],\n  \"documents\": [{ \"note\": \"Analysis\", \"url\": \"https://...\" }],\n  \"sources\": [{ \"url\": \"https://...\" }]\n}\n```","headerParameters":{"parameters":[{"name":"accept","value":"application/json"}]}},"credentials":{"httpHeaderAuth":{"id":"Wu3yVZpycXiRxkTa","name":"Plural API Key"}},"retryOnFail":true,"typeVersion":4.2},{"id":"7e40db3a-8b17-4c0f-9fc7-062d86e46882","name":"Plural Discovery1","type":"n8n-nodes-base.httpRequestTool","position":[672,496],"parameters":{"url":"={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('URL', ``, 'string') }}","options":{"batching":{"batch":{"batchSize":1}}},"sendHeaders":true,"authentication":"genericCredentialType","genericAuthType":"httpHeaderAuth","toolDescription":"=# Discovery Phase – Find ALL Relevant Items (bills, people, committees, events)\n\n**CRITICAL:** ALWAYS use the full base URL.\n\n**Base URL:** `https://v3.openstates.org/`\n\n---\n\n## Primary Search: Bills\n\n**Endpoint:** `GET https://v3.openstates.org/bills`\n\n**Rule:** You must provide **either** a **`jurisdiction`** **or** a full-text query **`q`**. Additional filters further narrow results (per ReDoc/Postman).\n\n### Common Query Parameters (most used for discovery)\n\n* `q=` Full-text query string (URL-encoded).\n* `jurisdiction=` A state/territory name/slug (e.g., `California`, `Texas`, `District of Columbia`). Use `/jurisdictions` to discover valid values.\n* `session=` Legislative session label for that jurisdiction. (Get via `/jurisdictions/{id}`, which includes sessions.)\n* `chamber=` `upper` or `lower` (varies by state).\n* **Date filters:** `created_since=YYYY-MM-DD`, `updated_since=YYYY-MM-DD`.\n* **People/metadata filters (when available):** `sponsor=`, `sponsor_classification=` (primary/cosponsor), `subject=`, `classification=` (bill/resolution/etc.).\n* **Pagination & sort:**\n\n  * `page=` (1, 2, 3, …)\n  * `per_page=` (**1–20 only; default 20**)\n  * `sort=` (`updated_desc`/`updated_asc`)\n* **Includes (hydration):** `include=` (e.g., `sponsors,actions,votes,versions,documents`) to expand related entities inline.\n\n### CORRECT Discovery URLs\n\n✅ `https://v3.openstates.org/bills?q=Proposition%2012&per_page=10` *(full-text search)*\n✅ `https://v3.openstates.org/bills?jurisdiction=California&updated_since=2024-01-01&sort=updated_desc`\n✅ `https://v3.openstates.org/bills?jurisdiction=Texas&session=2023&chamber=lower&q=water`\n✅ `https://v3.openstates.org/bills?jurisdiction=Florida&subject=Elections&include=sponsors,actions`\n\n### WRONG\n\n❌ `/bills?q=prop%2012` *(missing base URL)*\n❌ `…&per_page=50` *(invalid; must be 1–20)*\n\n### Response Shape (abridged)\n\n```json\n{\n  \"results\": [\n    {\n      \"id\": \"ocd-bill/…uuid…\",\n      \"identifier\": \"AB 123\",\n      \"title\": \"An act relating to …\",\n      \"jurisdiction\": \"California\",\n      \"session\": \"2023-2024\",\n      \"updated_at\": \"2025-05-01T12:34:56Z\",\n      \"openstates_url\": \"https://open.pluralpolicy.com/…\"\n      // + optional includes if requested: sponsors, actions, votes, versions, documents\n    }\n  ],\n  \"pagination\": { \"page\": 1, \"per_page\": 20, \"max_page\": 4 }\n}\n```\n\n---\n\n## Supporting Discovery Endpoints\n\n### Jurisdictions (to find valid names/sessions)\n\n* `GET https://v3.openstates.org/jurisdictions`\n* `GET https://v3.openstates.org/jurisdictions/{jurisdiction_id}` *(includes session metadata)*\n  Use these to confirm **jurisdiction names** and **session labels** before bill queries.\n\n### People (legislators, executives)\n\n* `GET https://v3.openstates.org/people?name={name}` *(fuzzy name search)*\n* `GET https://v3.openstates.org/people.geo?lat={lat}&lng={lng}` *(find reps for a location)*\n  Useful to discover sponsor names/IDs for later bill filtering.\n\n### Committees & Events (coverage varies)\n\n* `GET https://v3.openstates.org/committees`\n* `GET https://v3.openstates.org/events`\n  Handy for topical discovery.\n\n---\n\n### In Discovery Phase (Agent rules of thumb)\n\n* Prefer **broad queries** first (`q=` or just `jurisdiction=`), then narrow with filters.\n* Use **`/jurisdictions`** to pull valid session strings before filtering by `session=`.\n* Record each candidate’s `id` (`ocd-bill/…`) **and extract the UUID** (the part after `ocd-bill/`) for Retrieval.\n* Don’t fetch full texts yet; just gather candidates + minimal fields.\n* If you need more results, **paginate with `page=`**; keep `per_page` **≤ 20**.","headerParameters":{"parameters":[{"name":"accept","value":"application/json"}]}},"credentials":{"httpHeaderAuth":{"id":"Wu3yVZpycXiRxkTa","name":"Plural API Key"}},"retryOnFail":true,"typeVersion":4.2},{"id":"a64f86b3-bdf6-4fba-b9a5-3e61abae8668","name":"Qwen3","type":"@n8n/n8n-nodes-langchain.lmChatOpenRouter","position":[96,496],"parameters":{"model":"qwen/qwen3-235b-a22b","options":{"temperature":0.8}},"credentials":{"openRouterApi":{"id":"nkdLVRx4aA33ZZgL","name":"Legal Research Agent"}},"typeVersion":1},{"id":"a7d85394-dbf5-4387-b7d3-a05ee710a7b8","name":"Qwen4","type":"@n8n/n8n-nodes-langchain.lmChatOpenRouter","position":[1664,496],"parameters":{"model":"qwen/qwen3-235b-a22b","options":{"temperature":0.2}},"credentials":{"openRouterApi":{"id":"nkdLVRx4aA33ZZgL","name":"Legal Research Agent"}},"typeVersion":1},{"id":"8d1a23b5-8ad6-4ae4-8220-9a5acdde7caa","name":"Sonnet 4.5","type":"@n8n/n8n-nodes-langchain.lmChatOpenRouter","position":[1104,496],"parameters":{"model":"anthropic/claude-sonnet-4.5","options":{"temperature":0.3}},"credentials":{"openRouterApi":{"id":"nkdLVRx4aA33ZZgL","name":"Legal Research Agent"}},"typeVersion":1},{"id":"814bb796-5e3a-40c9-b7f3-5494adcbd112","name":"Sonnet 4.","type":"@n8n/n8n-nodes-langchain.lmChatOpenRouter","position":[3568,512],"parameters":{"model":"anthropic/claude-sonnet-4.5","options":{"temperature":0.2}},"credentials":{"openRouterApi":{"id":"nkdLVRx4aA33ZZgL","name":"Legal Research Agent"}},"typeVersion":1},{"id":"c886df5a-bc6d-4ca8-8d33-a9c42efe42a3","name":"Opus","type":"@n8n/n8n-nodes-langchain.lmChatOpenRouter","position":[2848,512],"parameters":{"model":"anthropic/claude-opus-4.5","options":{"temperature":0.6}},"credentials":{"openRouterApi":{"id":"nkdLVRx4aA33ZZgL","name":"Legal Research Agent"}},"typeVersion":1},{"id":"c54d933e-c733-4e74-afa0-61ff29849cbe","name":"Opus1","type":"@n8n/n8n-nodes-langchain.lmChatOpenRouter","position":[4256,512],"parameters":{"model":"anthropic/claude-opus-4.5","options":{"temperature":0.1}},"credentials":{"openRouterApi":{"id":"nkdLVRx4aA33ZZgL","name":"Legal Research Agent"}},"typeVersion":1},{"id":"18da61d4-5a79-4147-8e9f-2f57c405cfba","name":"Document Cloud Discovery","type":"n8n-nodes-base.httpRequestTool","position":[960,496],"parameters":{"url":"={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('URL', ``, 'string') }}","options":{"batching":{"batch":{"batchSize":1}}},"toolDescription":"=**Discovery Phase - Find ALL Government Documents**\n\n**Base URL:** https://api.www.documentcloud.org/api/\n**Search Endpoint:** documents/search/\n\n## Full Search URL Pattern\nhttps://api.www.documentcloud.org/api/documents/search/?q={query}&per_page=25\n\n## Query Parameters\n- q: search terms (URL encoded)\n- per_page: up to 25\n- created_at__gte: date filter (YYYY-MM-DD)\n\n## Discovery Search URLs\nhttps://api.www.documentcloud.org/api/documents/search/?q=prop%2012&per_page=25\nhttps://api.www.documentcloud.org/api/documents/search/?q=proposition%2012%20california&per_page=25\nhttps://api.www.documentcloud.org/api/documents/search/?q=CDFA%20enforcement&per_page=25\n\n## Response Structure\n{\n  \"results\": [{\n    \"id\": \"23456789\",\n    \"slug\": \"cdfa-inspection-report\",  // CRITICAL: Save this for text retrieval\n    \"title\": \"CDFA Prop 12 Inspection Report\",\n    \"page_count\": 45,\n    \"canonical_url\": \"https://www.documentcloud.org/documents/23456789\"\n  }]\n}\n\n**CRITICAL for later retrieval:**\n- Save both \"id\" and \"slug\" fields\n- These are needed to construct text retrieval URL in Phase 3\n- canonical_url is for reference, not for text retrieval\n\n**In Discovery Phase:**\n- Search broadly with multiple terms\n- Save id AND slug for each document\n- Don't retrieve text yet"},"retryOnFail":true,"typeVersion":4.2},{"id":"82bdd3ed-48b6-420c-a503-544daf908b30","name":"Trigger legal research request (Webhook)","type":"n8n-nodes-base.webhook","position":[96,240],"webhookId":"7e2d5aab-02ed-4e74-ba34-38955780bf18","parameters":{"path":"legal-research","options":{},"httpMethod":"POST","responseMode":"streaming"},"typeVersion":2.1},{"id":"43b75f2e-4cca-4e65-940f-0ac781703f60","name":"Sticky Note2","type":"n8n-nodes-base.stickyNote","position":[16,-656],"parameters":{"width":816,"height":592,"content":"## Research US regulations using AI agents with web search and report generation\n\n## How it works\n\nThis workflow accepts a research request via webhook or from another workflow.\nIt performs structured research using AI agents that search multiple sources,\ngather relevant information, and synthesize the findings into a clear report.\n\nAfter the report is generated, the workflow verifies the content to reduce\nhallucinations and unsupported claims. If issues are detected, a fixing step\nis triggered before returning the final output.\n\nThe result is a structured, verified research report that can be safely used\nfor further analysis or downstream workflows.\n\n## Setup steps\n\n1. Add your AI provider credentials.\n2. Configure any web search or document source APIs used for research.\n3. Choose how the workflow is triggered (Webhook or Execute Workflow).\n4. Activate the workflow and send a research request.\n"},"typeVersion":1}],"active":false,"pinData":{"Trigger legal research request (Webhook)":[{"json":{"body":{"prompt":"Your legal research question here"},"query":{},"params":{},"headers":{"host":"n8n.openpaws.ai","accept":"*/*","x-real-ip":"103.171.120.173","connection":"close","user-agent":"curl/8.7.1","content-type":"application/json","content-length":"47","x-forwarded-for":"103.171.120.173","x-forwarded-port":"443","x-forwarded-proto":"https"},"webhookUrl":"https://n8n.openpaws.ai/webhook-test/legal-research","executionMode":"test"}}]},"settings":{"availableInMCP":false,"executionOrder":"v1"},"versionId":"e18a12e5-5911-4b44-bea4-d2f07993b31b","connections":{"Opus":{"ai_languageModel":[[{"node":"Step 4: Report Writing","type":"ai_languageModel","index":0}]]},"Opus1":{"ai_languageModel":[[{"node":"Step 6: Fixing Hallucinations","type":"ai_languageModel","index":0}]]},"Qwen3":{"ai_languageModel":[[{"node":"Step 1: Discovery","type":"ai_languageModel","index":0}]]},"Qwen4":{"ai_languageModel":[[{"node":"Step 3: Retrieval","type":"ai_languageModel","index":0}]]},"Sonnet 4.":{"ai_languageModel":[[{"node":"Step 5: Verification","type":"ai_languageModel","index":0}]]},"Set Report":{"main":[[{"node":"Step 5: Verification","type":"main","index":0}]]},"Sonnet 4.5":{"ai_languageModel":[[{"node":"Step 2: Prioritization","type":"ai_languageModel","index":0}]]},"Auto Fallback":{"ai_languageModel":[[{"node":"Step 1: Discovery","type":"ai_languageModel","index":1}]]},"Auto Fallback1":{"ai_languageModel":[[{"node":"Step 2: Prioritization","type":"ai_languageModel","index":1}]]},"Auto Fallback2":{"ai_languageModel":[[{"node":"Step 3: Retrieval","type":"ai_languageModel","index":1}]]},"Auto Fallback3":{"ai_languageModel":[[{"node":"Step 4: Report Writing","type":"ai_languageModel","index":1}]]},"Auto Fallback4":{"ai_languageModel":[[{"node":"Step 5: Verification","type":"ai_languageModel","index":1},{"node":"Structured Output Parser","type":"ai_languageModel","index":0}]]},"Auto Fallback5":{"ai_languageModel":[[{"node":"Step 6: Fixing Hallucinations","type":"ai_languageModel","index":1}]]},"If Empty Output":{"main":[[{"node":"Step 6: Fixing Hallucinations","type":"main","index":0}],[{"node":"Set Report","type":"main","index":0}]]},"If Empty Output1":{"main":[[{"node":"Step 5: Verification","type":"main","index":0}],[{"node":"If hallucinations present","type":"main","index":0}]]},"Plural Retrieval":{"ai_tool":[[{"node":"Step 3: Retrieval","type":"ai_tool","index":0}]]},"Plural Discovery1":{"ai_tool":[[{"node":"Step 1: Discovery","type":"ai_tool","index":0}]]},"Step 1: Discovery":{"main":[[{"node":"Retry if Tools Not Used","type":"main","index":0}]]},"Step 3: Retrieval":{"main":[[{"node":"Retry if Tools Not Used1","type":"main","index":0}]]},"LegiScan Discovery":{"ai_tool":[[{"node":"Step 1: Discovery","type":"ai_tool","index":0}]]},"LegiScan Retrieval":{"ai_tool":[[{"node":"Step 3: Retrieval","type":"ai_tool","index":0}]]},"Think Tool Analysis":{"ai_tool":[[{"node":"Step 4: Report Writing","type":"ai_tool","index":0}]]},"Step 5: Verification":{"main":[[{"node":"If Empty Output1","type":"main","index":0}]]},"Think Tool Analysis1":{"ai_tool":[[{"node":"Step 6: Fixing Hallucinations","type":"ai_tool","index":0}]]},"Step 2: Prioritization":{"main":[[{"node":"Retry if Response Empty","type":"main","index":0}]]},"Step 4: Report Writing":{"main":[[{"node":"Retry if Response Empty1","type":"main","index":0}]]},"DocumentCloud Retrieval":{"ai_tool":[[{"node":"Step 3: Retrieval","type":"ai_tool","index":0}]]},"Google Search Discovery":{"ai_tool":[[{"node":"Step 1: Discovery","type":"ai_tool","index":0}]]},"Retry if Response Empty":{"main":[[{"node":"Step 2: Prioritization","type":"main","index":0}],[{"node":"Step 3: Retrieval","type":"main","index":0}]]},"Retry if Tools Not Used":{"main":[[{"node":"Step 1: Discovery","type":"main","index":0}],[{"node":"Step 2: Prioritization","type":"main","index":0}]]},"Court Listener Discovery":{"ai_tool":[[{"node":"Step 1: Discovery","type":"ai_tool","index":0}]]},"Document Cloud Discovery":{"ai_tool":[[{"node":"Step 1: Discovery","type":"ai_tool","index":0}]]},"Jina URL Text Extraction":{"ai_tool":[[{"node":"Step 3: Retrieval","type":"ai_tool","index":0}]]},"Retry if Response Empty1":{"main":[[{"node":"Step 4: Report Writing","type":"main","index":0}],[{"node":"Set Report","type":"main","index":0}]]},"Retry if Tools Not Used1":{"main":[[{"node":"Step 3: Retrieval","type":"main","index":0}],[{"node":"Step 4: Report Writing","type":"main","index":0}]]},"Structured Output Parser":{"ai_outputParser":[[{"node":"Step 5: Verification","type":"ai_outputParser","index":0}]]},"Court Listener Retrieveal":{"ai_tool":[[{"node":"Step 3: Retrieval","type":"ai_tool","index":0}]]},"If hallucinations present":{"main":[[{"node":"Step 6: Fixing Hallucinations","type":"main","index":0}],[{"node":"Set Output","type":"main","index":0}]]},"Think Tool Prioritization":{"ai_tool":[[{"node":"Step 2: Prioritization","type":"ai_tool","index":0}]]},"Step 6: Fixing Hallucinations":{"main":[[{"node":"If Empty Output","type":"main","index":0}]]},"Trigger legal research request (Webhook)":{"main":[[{"node":"Step 1: Discovery","type":"main","index":0}]]}}},"lastUpdatedBy":1,"workflowInfo":{"nodeCount":45,"nodeTypes":{"n8n-nodes-base.if":{"count":7},"n8n-nodes-base.set":{"count":2},"n8n-nodes-base.webhook":{"count":1},"n8n-nodes-base.jinaAiTool":{"count":1},"n8n-nodes-base.stickyNote":{"count":3},"@n8n/n8n-nodes-langchain.agent":{"count":5},"n8n-nodes-base.httpRequestTool":{"count":8},"@n8n/n8n-nodes-langchain.chainLlm":{"count":1},"@n8n/n8n-nodes-langchain.toolThink":{"count":3},"@n8n/n8n-nodes-langchain.toolHttpRequest":{"count":1},"@n8n/n8n-nodes-langchain.lmChatOpenRouter":{"count":12},"@n8n/n8n-nodes-langchain.outputParserStructured":{"count":1}}},"status":"published","readyToDemo":null,"user":{"name":"Open Paws","username":"openpaws","bio":"Open Paws is a nonprofit building open-source AI tools to accelerate animal advocacy. \n\nWe create machine learning models and automation workflows trained on real-world campaign data to help end industrial animal exploitation. \n\nAll tools are free, transparent, and designed for real-world impact.","verified":true,"links":["https://www.openpaws.ai/"],"avatar":"https://gravatar.com/avatar/c23bc104617a5a562fe9efe0dad98e78652efd6171b81a960cbbcdf236d09cc8?r=pg&d=retro&size=200"},"nodes":[{"id":20,"icon":"fa:map-signs","name":"n8n-nodes-base.if","codex":{"data":{"alias":["Router","Filter","Condition","Logic","Boolean","Branch"],"details":"The IF node can be used to implement binary conditional logic in your workflow. You can set up one-to-many conditions to evaluate each item of data being inputted into the node. That data will either evaluate to TRUE or FALSE and route out of the node accordingly.\n\nThis node has multiple types of conditions: Bool, String, Number, and Date & Time.","resources":{"generic":[{"url":"https://n8n.io/blog/learn-to-automate-your-factorys-incident-reporting-a-step-by-step-guide/","icon":"🏭","label":"Learn to Automate Your Factory's Incident Reporting: A Step by Step Guide"},{"url":"https://n8n.io/blog/2021-the-year-to-automate-the-new-you-with-n8n/","icon":"☀️","label":"2021: The Year to Automate the New You with n8n"},{"url":"https://n8n.io/blog/why-business-process-automation-with-n8n-can-change-your-daily-life/","icon":"🧬","label":"Why business process automation with n8n can change your daily life"},{"url":"https://n8n.io/blog/create-a-toxic-language-detector-for-telegram/","icon":"🤬","label":"Create a toxic language detector for Telegram in 4 step"},{"url":"https://n8n.io/blog/no-code-ecommerce-workflow-automations/","icon":"store","label":"6 e-commerce workflows to power up your Shopify s"},{"url":"https://n8n.io/blog/how-to-build-a-low-code-self-hosted-url-shortener/","icon":"🔗","label":"How to build a low-code, self-hosted URL shortener in 3 steps"},{"url":"https://n8n.io/blog/automate-your-data-processing-pipeline-in-9-steps-with-n8n/","icon":"⚙️","label":"Automate your data processing pipeline in 9 steps"},{"url":"https://n8n.io/blog/how-to-get-started-with-crm-automation-and-no-code-workflow-ideas/","icon":"👥","label":"How to get started with CRM automation (with 3 no-code workflow ideas"},{"url":"https://n8n.io/blog/5-tasks-you-can-automate-with-notion-api/","icon":"⚡️","label":"5 tasks you can automate with the new Notion API "},{"url":"https://n8n.io/blog/automate-google-apps-for-productivity/","icon":"💡","label":"15 Google apps you can combine and automate to increase productivity"},{"url":"https://n8n.io/blog/automation-for-maintainers-of-open-source-projects/","icon":"🏷️","label":"How to automatically manage contributions to open-source projects"},{"url":"https://n8n.io/blog/how-uproc-scraped-a-multi-page-website-with-a-low-code-workflow/","icon":" 🕸️","label":"How uProc scraped a multi-page website with a low-code workflow"},{"url":"https://n8n.io/blog/5-workflow-automations-for-mattermost-that-we-love-at-n8n/","icon":"🤖","label":"5 workflow automations for Mattermost that we love at n8n"},{"url":"https://n8n.io/blog/why-this-product-manager-loves-workflow-automation-with-n8n/","icon":"🧠","label":"Why this Product Manager loves workflow automation with n8n"},{"url":"https://n8n.io/blog/sending-automated-congratulations-with-google-sheets-twilio-and-n8n/","icon":"🙌","label":"Sending Automated Congratulations with Google Sheets, Twilio, and n8n "},{"url":"https://n8n.io/blog/how-to-set-up-a-ci-cd-pipeline-with-no-code/","icon":"🎡","label":"How to set up a no-code CI/CD pipeline with GitHub and TravisCI"},{"url":"https://n8n.io/blog/benefits-of-automation-and-n8n-an-interview-with-hubspots-hugh-durkin/","icon":"🎖","label":"Benefits of automation and n8n: An interview with HubSpot's Hugh Durkin"},{"url":"https://n8n.io/blog/aws-workflow-automation/","label":"7 no-code workflow automations for Amazon Web Services"}],"primaryDocumentation":[{"url":"https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.if/"}]},"categories":["Core Nodes"],"nodeVersion":"1.0","codexVersion":"1.0","subcategories":{"Core Nodes":["Flow"]}}},"group":"[\"transform\"]","defaults":{"name":"If","color":"#408000"},"iconData":{"icon":"map-signs","type":"icon"},"displayName":"If","typeVersion":2,"nodeCategories":[{"id":9,"name":"Core Nodes"}]},{"id":38,"icon":"fa:pen","name":"n8n-nodes-base.set","codex":{"data":{"alias":["Set","JS","JSON","Filter","Transform","Map"],"resources":{"generic":[{"url":"https://n8n.io/blog/learn-to-automate-your-factorys-incident-reporting-a-step-by-step-guide/","icon":"🏭","label":"Learn to Automate Your Factory's Incident Reporting: A Step by Step Guide"},{"url":"https://n8n.io/blog/2021-the-year-to-automate-the-new-you-with-n8n/","icon":"☀️","label":"2021: The Year to Automate the New You with n8n"},{"url":"https://n8n.io/blog/automatically-pulling-and-visualizing-data-with-n8n/","icon":"📈","label":"Automatically pulling and visualizing data with n8n"},{"url":"https://n8n.io/blog/database-monitoring-and-alerting-with-n8n/","icon":"📡","label":"Database Monitoring and Alerting with n8n"},{"url":"https://n8n.io/blog/automatically-adding-expense-receipts-to-google-sheets-with-telegram-mindee-twilio-and-n8n/","icon":"🧾","label":"Automatically Adding Expense Receipts to Google Sheets with Telegram, Mindee, Twilio, and n8n"},{"url":"https://n8n.io/blog/no-code-ecommerce-workflow-automations/","icon":"store","label":"6 e-commerce workflows to power up your Shopify s"},{"url":"https://n8n.io/blog/how-to-build-a-low-code-self-hosted-url-shortener/","icon":"🔗","label":"How to build a low-code, self-hosted URL shortener in 3 steps"},{"url":"https://n8n.io/blog/automate-your-data-processing-pipeline-in-9-steps-with-n8n/","icon":"⚙️","label":"Automate your data processing pipeline in 9 steps"},{"url":"https://n8n.io/blog/how-to-get-started-with-crm-automation-and-no-code-workflow-ideas/","icon":"👥","label":"How to get started with CRM automation (with 3 no-code workflow ideas"},{"url":"https://n8n.io/blog/5-tasks-you-can-automate-with-notion-api/","icon":"⚡️","label":"5 tasks you can automate with the new Notion API "},{"url":"https://n8n.io/blog/automate-google-apps-for-productivity/","icon":"💡","label":"15 Google apps you can combine and automate to increase productivity"},{"url":"https://n8n.io/blog/how-uproc-scraped-a-multi-page-website-with-a-low-code-workflow/","icon":" 🕸️","label":"How uProc scraped a multi-page website with a low-code workflow"},{"url":"https://n8n.io/blog/building-an-expense-tracking-app-in-10-minutes/","icon":"📱","label":"Building an expense tracking app in 10 minutes"},{"url":"https://n8n.io/blog/the-ultimate-guide-to-automate-your-video-collaboration-with-whereby-mattermost-and-n8n/","icon":"📹","label":"The ultimate guide to automate your video collaboration with Whereby, Mattermost, and n8n"},{"url":"https://n8n.io/blog/5-workflow-automations-for-mattermost-that-we-love-at-n8n/","icon":"🤖","label":"5 workflow automations for Mattermost that we love at n8n"},{"url":"https://n8n.io/blog/learn-to-build-powerful-api-endpoints-using-webhooks/","icon":"🧰","label":"Learn to Build Powerful API Endpoints Using Webhooks"},{"url":"https://n8n.io/blog/how-a-membership-development-manager-automates-his-work-and-investments/","icon":"📈","label":"How a Membership Development Manager automates his work and investments"},{"url":"https://n8n.io/blog/a-low-code-bitcoin-ticker-built-with-questdb-and-n8n-io/","icon":"📈","label":"A low-code bitcoin ticker built with QuestDB and n8n.io"},{"url":"https://n8n.io/blog/how-to-set-up-a-ci-cd-pipeline-with-no-code/","icon":"🎡","label":"How to set up a no-code CI/CD pipeline with GitHub and TravisCI"},{"url":"https://n8n.io/blog/benefits-of-automation-and-n8n-an-interview-with-hubspots-hugh-durkin/","icon":"🎖","label":"Benefits of automation and n8n: An interview with HubSpot's Hugh Durkin"},{"url":"https://n8n.io/blog/how-goomer-automated-their-operations-with-over-200-n8n-workflows/","icon":"🛵","label":"How Goomer automated their operations with over 200 n8n workflows"},{"url":"https://n8n.io/blog/aws-workflow-automation/","label":"7 no-code workflow automations for Amazon Web Services"}],"primaryDocumentation":[{"url":"https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.set/"}]},"categories":["Core Nodes"],"nodeVersion":"1.0","codexVersion":"1.0","subcategories":{"Core Nodes":["Data Transformation"]}}},"group":"[\"input\"]","defaults":{"name":"Edit Fields"},"iconData":{"icon":"pen","type":"icon"},"displayName":"Edit Fields (Set)","typeVersion":3,"nodeCategories":[{"id":9,"name":"Core Nodes"}]},{"id":47,"icon":"file:webhook.svg","name":"n8n-nodes-base.webhook","codex":{"data":{"alias":["HTTP","API","Build","WH"],"resources":{"generic":[{"url":"https://n8n.io/blog/learn-how-to-automatically-cross-post-your-content-with-n8n/","icon":"✍️","label":"Learn how to automatically cross-post your content with n8n"},{"url":"https://n8n.io/blog/running-n8n-on-ships-an-interview-with-maranics/","icon":"🛳","label":"Running n8n on ships: An interview with Maranics"},{"url":"https://n8n.io/blog/how-to-build-a-low-code-self-hosted-url-shortener/","icon":"🔗","label":"How to build a low-code, self-hosted URL shortener in 3 steps"},{"url":"https://n8n.io/blog/what-are-apis-how-to-use-them-with-no-code/","icon":" 🪢","label":"What are APIs and how to use them with no code"},{"url":"https://n8n.io/blog/5-tasks-you-can-automate-with-notion-api/","icon":"⚡️","label":"5 tasks you can automate with the new Notion API "},{"url":"https://n8n.io/blog/how-a-digital-strategist-uses-n8n-for-online-marketing/","icon":"💻","label":"How a digital strategist uses n8n for online marketing"},{"url":"https://n8n.io/blog/the-ultimate-guide-to-automate-your-video-collaboration-with-whereby-mattermost-and-n8n/","icon":"📹","label":"The ultimate guide to automate your video collaboration with Whereby, Mattermost, and n8n"},{"url":"https://n8n.io/blog/how-to-automatically-give-kudos-to-contributors-with-github-slack-and-n8n/","icon":"👏","label":"How to automatically give kudos to contributors with GitHub, Slack, and n8n"},{"url":"https://n8n.io/blog/5-workflow-automations-for-mattermost-that-we-love-at-n8n/","icon":"🤖","label":"5 workflow automations for Mattermost that we love at n8n"},{"url":"https://n8n.io/blog/why-this-product-manager-loves-workflow-automation-with-n8n/","icon":"🧠","label":"Why this Product Manager loves workflow automation with n8n"},{"url":"https://n8n.io/blog/creating-custom-incident-response-workflows-with-n8n/","label":"How to automate every step of an incident response workflow"},{"url":"https://n8n.io/blog/learn-to-build-powerful-api-endpoints-using-webhooks/","icon":"🧰","label":"Learn to Build Powerful API Endpoints Using Webhooks"},{"url":"https://n8n.io/blog/learn-how-to-use-webhooks-with-mattermost-slash-commands/","icon":"🦄","label":"Learn how to use webhooks with Mattermost slash commands"},{"url":"https://n8n.io/blog/how-goomer-automated-their-operations-with-over-200-n8n-workflows/","icon":"🛵","label":"How Goomer automated their operations with over 200 n8n workflows"}],"primaryDocumentation":[{"url":"https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.webhook/"}]},"categories":["Development","Core Nodes"],"nodeVersion":"1.0","codexVersion":"1.0","subcategories":{"Core Nodes":["Helpers"]}}},"group":"[\"trigger\"]","defaults":{"name":"Webhook"},"iconData":{"type":"file","fileBuffer":"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0OCIgaGVpZ2h0PSI0OCI+PHBhdGggZmlsbD0iIzM3NDc0ZiIgZD0iTTM1IDM3Yy0yLjIgMC00LTEuOC00LTRzMS44LTQgNC00IDQgMS44IDQgNC0xLjggNC00IDQiLz48cGF0aCBmaWxsPSIjMzc0NzRmIiBkPSJNMzUgNDNjLTMgMC01LjktMS40LTcuOC0zLjdsMy4xLTIuNWMxLjEgMS40IDIuOSAyLjMgNC43IDIuMyAzLjMgMCA2LTIuNyA2LTZzLTIuNy02LTYtNmMtMSAwLTIgLjMtMi45LjdsLTEuNyAxTDIzLjMgMTZsMy41LTEuOSA1LjMgOS40YzEtLjMgMi0uNSAzLS41IDUuNSAwIDEwIDQuNSAxMCAxMFM0MC41IDQzIDM1IDQzIi8+PHBhdGggZmlsbD0iIzM3NDc0ZiIgZD0iTTE0IDQzQzguNSA0MyA0IDM4LjUgNCAzM2MwLTQuNiAzLjEtOC41IDcuNS05LjdsMSAzLjlDOS45IDI3LjkgOCAzMC4zIDggMzNjMCAzLjMgMi43IDYgNiA2czYtMi43IDYtNnYtMmgxNXY0SDIzLjhjLS45IDQuNi01IDgtOS44IDgiLz48cGF0aCBmaWxsPSIjZTkxZTYzIiBkPSJNMTQgMzdjLTIuMiAwLTQtMS44LTQtNHMxLjgtNCA0LTQgNCAxLjggNCA0LTEuOCA0LTQgNCIvPjxwYXRoIGZpbGw9IiMzNzQ3NGYiIGQ9Ik0yNSAxOWMtMi4yIDAtNC0xLjgtNC00czEuOC00IDQtNCA0IDEuOCA0IDQtMS44IDQtNCA0Ii8+PHBhdGggZmlsbD0iI2U5MWU2MyIgZD0ibTE1LjcgMzQtMy40LTIgNS45LTkuN2MtMi0xLjktMy4yLTQuNS0zLjItNy4zIDAtNS41IDQuNS0xMCAxMC0xMHMxMCA0LjUgMTAgMTBjMCAuOS0uMSAxLjctLjMgMi41bC0zLjktMWMuMS0uNS4yLTEgLjItMS41IDAtMy4zLTIuNy02LTYtNnMtNiAyLjctNiA2YzAgMi4xIDEuMSA0IDIuOSA1LjFsMS43IDF6Ii8+PC9zdmc+"},"displayName":"Webhook","typeVersion":2,"nodeCategories":[{"id":5,"name":"Development"},{"id":9,"name":"Core Nodes"}]},{"id":565,"icon":"fa:sticky-note","name":"n8n-nodes-base.stickyNote","codex":{"data":{"alias":["Comments","Notes","Sticky"],"categories":["Core Nodes"],"nodeVersion":"1.0","codexVersion":"1.0","subcategories":{"Core Nodes":["Helpers"]}}},"group":"[\"input\"]","defaults":{"name":"Sticky Note","color":"#FFD233"},"iconData":{"icon":"sticky-note","type":"icon"},"displayName":"Sticky Note","typeVersion":1,"nodeCategories":[{"id":9,"name":"Core Nodes"}]},{"id":1119,"icon":"fa:robot","name":"@n8n/n8n-nodes-langchain.agent","codex":{"data":{"alias":["LangChain","Chat","Conversational","Plan and Execute","ReAct","Tools"],"resources":{"primaryDocumentation":[{"url":"https://docs.n8n.io/integrations/builtin/cluster-nodes/root-nodes/n8n-nodes-langchain.agent/"}]},"categories":["AI","Langchain"],"subcategories":{"AI":["Agents","Root Nodes"]}}},"group":"[\"transform\"]","defaults":{"name":"AI Agent","color":"#404040"},"iconData":{"icon":"robot","type":"icon"},"displayName":"AI Agent","typeVersion":3,"nodeCategories":[{"id":25,"name":"AI"},{"id":26,"name":"Langchain"}]},{"id":1123,"icon":"fa:link","name":"@n8n/n8n-nodes-langchain.chainLlm","codex":{"data":{"alias":["LangChain"],"resources":{"primaryDocumentation":[{"url":"https://docs.n8n.io/integrations/builtin/cluster-nodes/root-nodes/n8n-nodes-langchain.chainllm/"}]},"categories":["AI","Langchain"],"subcategories":{"AI":["Chains","Root Nodes"]}}},"group":"[\"transform\"]","defaults":{"name":"Basic LLM Chain","color":"#909298"},"iconData":{"icon":"link","type":"icon"},"displayName":"Basic LLM Chain","typeVersion":2,"nodeCategories":[{"id":25,"name":"AI"},{"id":26,"name":"Langchain"}]},{"id":1179,"icon":"fa:code","name":"@n8n/n8n-nodes-langchain.outputParserStructured","codex":{"data":{"alias":["json","zod"],"resources":{"primaryDocumentation":[{"url":"https://docs.n8n.io/integrations/builtin/cluster-nodes/sub-nodes/n8n-nodes-langchain.outputparserstructured/"}]},"categories":["AI","Langchain"],"subcategories":{"AI":["Output Parsers"]}}},"group":"[\"transform\"]","defaults":{"name":"Structured Output Parser"},"iconData":{"icon":"code","type":"icon"},"displayName":"Structured Output Parser","typeVersion":1,"nodeCategories":[{"id":25,"name":"AI"},{"id":26,"name":"Langchain"}]},{"id":1268,"icon":"file:httprequest.svg","name":"@n8n/n8n-nodes-langchain.toolHttpRequest","codex":{"data":{"resources":{"primaryDocumentation":[{"url":"https://docs.n8n.io/integrations/builtin/cluster-nodes/sub-nodes/n8n-nodes-langchain.toolhttprequest/"}]},"categories":["AI","Langchain"],"subcategories":{"AI":["Tools"],"Tools":["Recommended Tools"]}}},"group":"[\"output\"]","defaults":{"name":"HTTP Request"},"iconData":{"type":"file","fileBuffer":"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0MCA0MCI+PHBhdGggZmlsbD0iIzAwMDRGNSIgZmlsbC1ydWxlPSJldmVub2RkIiBkPSJNNDAgMjBDNDAgOC45NTMgMzEuMDQ3IDAgMjAgMFMwIDguOTUzIDAgMjBzOC45NTMgMjAgMjAgMjAgMjAtOC45NTMgMjAtMjBNMjAgMzYuOTQ2Yy0xLjExNSAwLTIuODYyLS45NzktNC41LTQuMjQ3LS43MDQtMS40MDctMS4zMDQtMy4xNTYtMS43NDctNS4wMTRIMjYuMTljLS4zODYgMS44NTUtLjk4NiAzLjYwNS0xLjY5IDUuMDE0LTEuNjM4IDMuMjY4LTMuMzg1IDQuMjQ3LTQuNSA0LjI0N00xMi45MDYgMjBjMCAxLjYxLjEwMyAzLjE2NC4yOTQgNC42M2gxMy42YTM2IDM2IDAgMCAwIC4yOTQtNC42M2MwLTEuNjEtLjEwMy0zLjE2NC0uMjk0LTQuNjNIMTMuMmEzNiAzNiAwIDAgMC0uMjk0IDQuNjNNMjAgMy4wNTRjMS4xMTUgMCAyLjg2Mi45NzcgNC41IDQuMjQ2LjcwNyAxLjQxNCAxLjMwNyAzLjEwNyAxLjY5MiA1LjAxNUgxMy43NWMuNDQzLTEuOTEgMS4wNDQtMy42MDIgMS43NS01LjAxNCAxLjYzOC0zLjI3IDMuMzg1LTQuMjQ3IDQuNS00LjI0N00zMC4xNDggMjBjMC0xLjU5LS4wOTQtMy4xMzgtLjMyNS00LjYzaDYuNDgxYy40MjEgMS40NzIuNjQyIDMuMDI2LjY0MiA0LjYzcy0uMjIgMy4xNTgtLjY0MiA0LjYzaC02LjQ4MWMuMjMxLTEuNDkyLjMyNS0zLjA0LjMyNS00LjYzTTI2LjI3NyA0LjI1NWMxLjM2IDIuMTA1IDIuNDM0IDQuODc3IDMuMSA4LjA2aDUuNzI4YTE2Ljk4IDE2Ljk4IDAgMCAwLTguODI4LTguMDZtLTE1LjY1NCA4LjA2aC01LjczYzEuODU4LTMuNjQ3IDUtNi41MzIgOC44My04LjA2LTEuMzYgMi4xMDUtMi40MzQgNC44NzctMy4xIDguMDZNMy4wNTQgMjBjMCAxLjYwMy4yMjMgMy4xNTcuNjQgNC42M2g2LjQyOGE0MCA0MCAwIDAgMS0uMjctNC42M2MwLTEuNTk0LjA5NC0zLjE0Mi4yNy00LjYzSDMuNjk1YTE3IDE3IDAgMCAwLS42NCA0LjYzbTIzLjIyMyAxNS43NDNjMS4zNi0yLjEwNCAyLjQzNC00Ljg3NSAzLjEtOC4wNThoNS43MjhhMTYuOTYgMTYuOTYgMCAwIDEtOC44MjggOC4wNThtLTEyLjU1NCAwYTE3IDE3IDAgMCAxLTguODMtOC4wNThoNS43M2MuNjY2IDMuMTgzIDEuNzQgNS45NTQgMy4xIDguMDU4IiBjbGlwLXJ1bGU9ImV2ZW5vZGQiLz48L3N2Zz4="},"displayName":"HTTP Request Tool","typeVersion":1,"nodeCategories":[{"id":25,"name":"AI"},{"id":26,"name":"Langchain"}]},{"id":1281,"icon":"file:openrouter.svg","name":"@n8n/n8n-nodes-langchain.lmChatOpenRouter","codex":{"data":{"resources":{"primaryDocumentation":[{"url":"https://docs.n8n.io/integrations/builtin/cluster-nodes/sub-nodes/n8n-nodes-langchain.lmchatopenrouter/"}]},"categories":["AI","Langchain"],"subcategories":{"AI":["Language Models","Root Nodes"],"Language Models":["Chat Models (Recommended)"]}}},"group":"[\"transform\"]","defaults":{"name":"OpenRouter Chat Model"},"iconData":{"type":"file","fileBuffer":"data:image/svg+xml;base64,PHN2ZyBmaWxsPSIjOTRBM0I4IiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgdmlld0JveD0iMCAwIDI0IDI0IiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjx0aXRsZT5PcGVuUm91dGVyPC90aXRsZT48cGF0aCBkPSJNMTYuODA0IDEuOTU3bDcuMjIgNC4xMDV2LjA4N0wxNi43MyAxMC4yMWwuMDE3LTIuMTE3LS44MjEtLjAzYy0xLjA1OS0uMDI4LTEuNjExLjAwMi0yLjI2OC4xMS0xLjA2NC4xNzUtMi4wMzguNTc3LTMuMTQ3IDEuMzUyTDguMzQ1IDExLjAzYy0uMjg0LjE5NS0uNDk1LjMzNi0uNjguNDU1bC0uNTE1LjMyMi0uMzk3LjIzNC4zODUuMjMuNTMuMzM4Yy40NzYuMzE0IDEuMTcuNzk2IDIuNzAxIDEuODY2IDEuMTEuNzc1IDIuMDgzIDEuMTc3IDMuMTQ3IDEuMzUybC4zLjA0NWMuNjk0LjA5MSAxLjM3NS4wOTQgMi44MjUuMDMzbC4wMjItMi4xNTkgNy4yMiA0LjEwNXYuMDg3TDE2LjU4OSAyMmwuMDE0LTEuODYyLS42MzUuMDIyYy0xLjM4Ni4wNDItMi4xMzcuMDAyLTMuMTM4LS4xNjItMS42OTQtLjI4LTMuMjYtLjkyNi00Ljg4MS0yLjA1OWwtMi4xNTgtMS41YTIxLjk5NyAyMS45OTcgMCAwMC0uNzU1LS40OThsLS40NjctLjI4YTU1LjkyNyA1NS45MjcgMCAwMC0uNzYtLjQzQzIuOTA4IDE0LjczLjU2MyAxNC4xMTYgMCAxNC4xMTZWOS44ODhsLjE0LjAwNGMuNTY0LS4wMDcgMi45MS0uNjIyIDMuODA5LTEuMTI0bDEuMDE2LS41OC40MzgtLjI3NGMuNDI4LS4yOCAxLjA3Mi0uNzI2IDIuNjg2LTEuODUzIDEuNjIxLTEuMTMzIDMuMTg2LTEuNzggNC44ODEtMi4wNTkgMS4xNTItLjE5IDEuOTc0LS4yMTMgMy44MTQtLjEzOGwuMDItMS45MDd6Ij48L3BhdGg+PC9zdmc+Cg=="},"displayName":"OpenRouter Chat Model","typeVersion":1,"nodeCategories":[{"id":25,"name":"AI"},{"id":26,"name":"Langchain"}]},{"id":1289,"icon":"fa:brain","name":"@n8n/n8n-nodes-langchain.toolThink","codex":{"data":{"resources":{"primaryDocumentation":[{"url":"https://docs.n8n.io/integrations/builtin/cluster-nodes/sub-nodes/n8n-nodes-langchain.toolthink/"}]},"categories":["AI","Langchain"],"subcategories":{"AI":["Tools"],"Tools":["Other Tools"]}}},"group":"[\"transform\"]","defaults":{"name":"Think"},"iconData":{"icon":"brain","type":"icon"},"displayName":"Think Tool","typeVersion":1,"nodeCategories":[{"id":25,"name":"AI"},{"id":26,"name":"Langchain"}]}],"categories":[{"id":32,"name":"Market Research"},{"id":48,"name":"AI RAG"}],"image":[]}}