{
  "name": "Polish AI RAG Agent - OpenRouter",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "rag-agent",
        "responseMode": "lastNode",
        "options": {}
      },
      "id": "2e2db8f6-9fbd-4b79-93cb-df2ae2d4f30a",
      "name": "Webhook: RAG Question",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [
        240,
        300
      ]
    },
    {
      "parameters": {
        "model": "anthropic/claude-3.5-sonnet",
        "options": {
          "baseURL": "https://openrouter.ai/api/v1",
          "temperature": 0.3
        }
      },
      "id": "def9e6bf-0f92-4318-8f27-baa2deb73581",
      "name": "OpenRouter: Analyze Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.3,
      "position": [
        560,
        420
      ],
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "description": "Analyzes the user question and determines optimal RAG search parameters including top_k value (10-15)",
        "jsCode": "const question = $fromAI('question', 'User question', 'string');\nconst lowerQ = question.toLowerCase();\nconst result = { query: question, top_k: 10 };\nif (lowerQ.includes('szczeg\u00f3\u0142') || lowerQ.includes('jak')) result.top_k = 15;\nelse if (lowerQ.includes('przyk\u0142ad')) result.top_k = 12;\nreturn JSON.stringify(result, null, 2);"
      },
      "id": "279baa2f-4c45-4acb-91cf-770016011dcb",
      "name": "Code Tool: Build RAG Parameters",
      "type": "@n8n/n8n-nodes-langchain.toolCode",
      "typeVersion": 1.3,
      "position": [
        680,
        420
      ]
    },
    {
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n  \"type\": \"object\",\n  \"properties\": {\n    \"query\": {\n      \"type\": \"string\",\n      \"description\": \"The search query text\"\n    },\n    \"top_k\": {\n      \"type\": \"number\",\n      \"description\": \"Number of results to retrieve (10-15)\"\n    }\n  },\n  \"required\": [\"query\", \"top_k\"]\n}"
      },
      "id": "ad6f2f0e-5938-40e7-a702-a3e0e8d2497b",
      "name": "Structured Output Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "typeVersion": 1.3,
      "position": [
        800,
        420
      ]
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "={{ $json.body.question }}",
        "hasOutputParser": true,
        "options": {
          "systemMessage": "Jeste\u015b ekspertem analizy zapyta\u0144 u\u017cytkownik\u00f3w dla systemu RAG. Twoim zadaniem jest przeanalizowanie pytania u\u017cytkownika i okre\u015blenie optymalnych parametr\u00f3w wyszukiwania.\n\nPytanie u\u017cytkownika: {{ $json.body.question }}\n\nPrzeanalizuj pytanie i u\u017cyj narz\u0119dzia Build RAG Parameters aby okre\u015bli\u0107:\n1. Liczb\u0119 wynik\u00f3w do pobrania (top_k: 10-15)\n2. Strategi\u0119 wyszukiwania\n\nZwr\u00f3\u0107 struktur\u0119 JSON z parametrami wyszukiwania (query i top_k)."
        }
      },
      "id": "35e5cd44-d781-44ba-ae5f-52e00f1ce86a",
      "name": "AI Agent: Analyze Question",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 3.1,
      "position": [
        480,
        300
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://mobby-rag-search-api.hf.space/search",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "={{ $env.HF_API_TOKEN }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ $json.output }}",
        "options": {
          "response": {
            "response": {
              "neverError": true
            }
          },
          "timeout": 60000
        }
      },
      "id": "5b264885-dd34-4817-ad05-43e94b5a29e2",
      "name": "HTTP Request: RAG Search",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        720,
        300
      ]
    },
    {
      "parameters": {
        "jsCode": "const r = $input.item.json;\nif (!r || r.error) return {json: {context: `B\u0142\u0105d RAG: ${r?.error || 'Brak odpowiedzi'}`, hasResults: false, resultCount: 0, results: []}};\nif (!r.results || r.results.length === 0) return {json: {context: 'Brak wynik\u00f3w. Spr\u00f3buj przeformu\u0142owa\u0107 pytanie.', hasResults: false, resultCount: 0, results: []}};\nreturn {json: r};"
      },
      "id": "68b0f452-0580-4765-bf23-80c411b2d242",
      "name": "Code: Check API Errors",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        960,
        300
      ]
    },
    {
      "parameters": {
        "jsCode": "// Format RAG search results into readable context\nconst results = $input.item.json.results || $input.item.json;\n\nif (!results || !Array.isArray(results) || results.length === 0) {\n  return {\n    json: {\n      context: 'Brak wynik\u00f3w wyszukiwania. System RAG nie znalaz\u0142 odpowiednich artyku\u0142\u00f3w.',\n      hasResults: false,\n      resultCount: 0,\n      results: []\n    }\n  };\n}\n\n// Build formatted context\nlet context = `Znaleziono ${results.length} wynik\u00f3w z bazy wiedzy:\\n\\n`;\n\nresults.forEach((result, index) => {\n  context += `--- Wynik ${index + 1} (Score: ${(result.score * 100).toFixed(1)}%) ---\\n`;\n  context += `Tytu\u0142: ${result.title}\\n`;\n  context += `URL: ${result.url}\\n`;\n  context += `Typ sekcji: ${result.section_type || 'content'}\\n`;\n  \n  if (result.publication_date) {\n    context += `Data publikacji: ${result.publication_date}\\n`;\n  }\n  \n  if (result.tags && result.tags.length > 0) {\n    context += `Tagi: ${result.tags.join(', ')}\\n`;\n  }\n  \n  if (result.categories && result.categories.length > 0) {\n    context += `Kategorie: ${result.categories.join(', ')}\\n`;\n  }\n  \n  context += `\\nTre\u015b\u0107:\\n${result.text}\\n\\n`;\n});\n\nreturn {\n  json: {\n    context,\n    hasResults: true,\n    resultCount: results.length,\n    results,\n    originalQuestion: $('Webhook: RAG Question').item.json.body.question\n  }\n};"
      },
      "id": "1185f2fe-1676-4240-b9ce-361b158a74d0",
      "name": "Code: Format RAG Context",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1200,
        300
      ]
    },
    {
      "parameters": {
        "model": "anthropic/claude-3.5-sonnet",
        "options": {
          "baseURL": "https://openrouter.ai/api/v1",
          "temperature": 0.5
        }
      },
      "id": "c9546432-7099-407b-b6a0-95af5318662c",
      "name": "OpenRouter: Answer Generator",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.3,
      "position": [
        1560,
        420
      ],
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "={{ $('Code: Format RAG Context').item.json.originalQuestion }}",
        "options": {
          "systemMessage": "Jeste\u015b pomocnym asystentem AI, kt\u00f3ry odpowiada na pytania u\u017cytkownik\u00f3w w j\u0119zyku polskim na podstawie kontekstu z bazy wiedzy RAG.\n\n=== PYTANIE U\u017bYTKOWNIKA ===\n{{ $('Code: Format RAG Context').item.json.originalQuestion }}\n\n=== KONTEKST Z BAZY WIEDZY ===\n{{ $('Code: Format RAG Context').item.json.context }}\n\n=== INSTRUKCJE ===\n1. Odpowiedz zwi\u0119\u017ale i konkretnie w j\u0119zyku polskim\n2. Bazuj TYLKO na dostarczonym kontek\u015bcie z bazy wiedzy\n3. Cytuj \u017ar\u00f3d\u0142a - podawaj tytu\u0142y artyku\u0142\u00f3w i linki\n4. Uwzgl\u0119dnij score i daty publikacji w ocenie aktualno\u015bci informacji\n5. Je\u015bli kontekst nie zawiera odpowiedzi, powiedz o tym wprost i zasugeruj przeformu\u0142owanie pytania\n6. U\u017cywaj formatowania markdown dla lepszej czytelno\u015bci\n7. Je\u015bli s\u0105 dost\u0119pne checklisty lub key insights, wyr\u00f3\u017cnij je\n\nOdpowiedz teraz na pytanie u\u017cytkownika:"
        }
      },
      "id": "70949f8c-1eae-4907-a20a-53dfd16caff0",
      "name": "AI Agent: Generate Polish Answer",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 3.1,
      "position": [
        1440,
        300
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ {\n  \"question\": $('Code: Format RAG Context').item.json.originalQuestion,\n  \"answer\": $json.output,\n  \"sources\": $('Code: Format RAG Context').item.json.results.map(r => ({\"title\": r.title, \"url\": r.url, \"score\": r.score})),\n  \"sources_count\": $('Code: Format RAG Context').item.json.resultCount,\n  \"has_results\": $('Code: Format RAG Context').item.json.hasResults\n} }}",
        "options": {}
      },
      "id": "a4e85aa6-4485-4081-9e6e-93a1002a262f",
      "name": "Respond to Webhook",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.5,
      "position": [
        1680,
        300
      ]
    }
  ],
  "connections": {
    "Webhook: RAG Question": {
      "main": [
        [
          {
            "node": "AI Agent: Analyze Question",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenRouter: Analyze Model": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent: Analyze Question",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Code Tool: Build RAG Parameters": {
      "ai_tool": [
        [
          {
            "node": "AI Agent: Analyze Question",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Structured Output Parser": {
      "ai_outputParser": [
        [
          {
            "node": "AI Agent: Analyze Question",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "AI Agent: Analyze Question": {
      "main": [
        [
          {
            "node": "HTTP Request: RAG Search",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "HTTP Request: RAG Search": {
      "main": [
        [
          {
            "node": "Code: Check API Errors",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code: Check API Errors": {
      "main": [
        [
          {
            "node": "Code: Format RAG Context",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code: Format RAG Context": {
      "main": [
        [
          {
            "node": "AI Agent: Generate Polish Answer",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenRouter: Answer Generator": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent: Generate Polish Answer",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "AI Agent: Generate Polish Answer": {
      "main": [
        [
          {
            "node": "Respond to Webhook",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "corrected-openrouter-v1",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "tags": []
}