{"id":"6b08c25038c84264c20274d2","slug":"rag","title":"RAG: odpowiedzi na podstawie własnych dokumentów","summary":"Retrieval-Augmented Generation od podstaw do produkcji – chunking, wyszukiwanie hybrydowe z BM25 i RRF, reranking, odpowiedzi z cytatami w Claude, ewaluacja i sytuacje, w których RAG jest zbędny.","servedLang":"pl","availableLangs":["pl","en"],"topics":["rag","embeddings-vector-db","evals","prompt-engineering"],"techs":["python","typescript","dotnet"],"tags":["rag","retrieval","chunking","hybrid-search","bm25","reranking","citations","pgvector","claude"],"level":"intermediate","kind":"article","access":"members","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":21,"stats":{"views":1,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-26T23:35:44.262Z","updatedAt":"2026-11-27T10:04:36.531Z","requestedLang":"pl","theme":{"hero":"classic","heroMedia":null,"accent":"rose","background":"grid","weaveResources":true,"toc":"right"},"seoDescription":"RAG w praktyce: pipeline indeksowania, chunking, wyszukiwanie hybrydowe BM25 + wektory, Reciprocal Rank Fusion, reranking, cytaty w Claude API, prompt caching, ewaluacja i GraphRAG.","wordCount":4062,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Model językowy nie zna karty Pierogarni Haliny, godzin otwarcia nowego lokalu ani wczorajszej zmiany regulaminu dostaw. "},{"type":"text","text":"RAG","marks":[{"type":"bold"}]},{"type":"text","text":" ("},{"type":"text","text":"Retrieval-Augmented Generation","marks":[{"type":"italic"}]},{"type":"text","text":") to wzorzec, w którym przed wygenerowaniem odpowiedzi aplikacja "},{"type":"text","text":"wyszukuje","marks":[{"type":"bold"}]},{"type":"text","text":" pasujące fragmenty własnych dokumentów i dokleja je do promptu. Model odpowiada wtedy na podstawie dostarczonych faktów, a nie pamięci z treningu – i może wskazać, skąd je wziął."}]},{"type":"stats","attrs":{"items":[{"value":"2020","label":"rok pracy, która nazwała RAG","hint":"Lewis i in., Facebook AI Research"},{"value":"k = 60","label":"stała w Reciprocal Rank Fusion","hint":"wynik = Σ 1 / (k + pozycja)"},{"value":"67%","label":"mniej nieudanych wyszukiwań","hint":"Contextual Retrieval + reranking (pomiar Anthropic, 2024)"}]}},{"type":"callout","attrs":{"variant":"info","title":"W skrócie"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"RAG = "},{"type":"text","text":"wyszukaj","marks":[{"type":"bold"}]},{"type":"text","text":" (retrieval) → "},{"type":"text","text":"dołącz do promptu","marks":[{"type":"bold"}]},{"type":"text","text":" (augmentation) → "},{"type":"text","text":"wygeneruj","marks":[{"type":"bold"}]},{"type":"text","text":" (generation). Wiedza siedzi w Twojej bazie, nie w wagach modelu, więc aktualizujesz ją jak zwykłe dane."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Jakość RAG to w większości jakość "},{"type":"text","text":"wyszukiwania","marks":[{"type":"bold"}]},{"type":"text","text":": dobry chunking, wyszukiwanie hybrydowe (słowa + znaczenie) i reranking robią większą różnicę niż wybór modelu."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Zanim zbudujesz pipeline, sprawdź, czy korpus nie zmieści się w całości w prompcie z cache – często to prostsze i lepsze."}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"problem-40-lokali-40-kart-i-regulamin-ktory-zmienia-sie-co-miesiac"},"content":[{"type":"text","text":"Problem: 40 lokali, 40 kart i regulamin, który zmienia się co miesiąc"}]},{"type":"paragraph","content":[{"type":"text","text":"Pierogarnia Haliny urosła do 40 lokali. Każdy ma własną kartę, godziny, strefy dostaw i promocje; do tego dochodzą FAQ, regulamin, polityka alergenów i tysiące opinii klientów. Asystent na stronie ma odpowiadać na pytania typu „czy lokal na Kazimierzu dowozi w niedzielę?” albo „czy pierogi ze szpinakiem mają orzechy?”."}]},{"type":"paragraph","content":[{"type":"text","text":"Trzy podejścia, które "},{"type":"text","text":"nie","marks":[{"type":"bold"}]},{"type":"text","text":" działają dobrze:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Liczyć na wiedzę modelu","marks":[{"type":"bold"}]},{"type":"text","text":" – model jej nie ma, więc zmyśli (patrz "},{"type":"text","text":"Podstawy LLM","marks":[{"type":"link","attrs":{"href":"/pl/topics/llm-fundamentals"}}]},{"type":"text","text":")."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Fine-tuning","marks":[{"type":"bold"},{"type":"link","attrs":{"href":"/pl/topics/fine-tuning"}}]},{"type":"text","text":" – uczy stylu i formatu, ale słabo zapamiętuje fakty, a każda zmiana karty wymagałaby ponownego trenowania."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Wklejanie wszystkiego do promptu","marks":[{"type":"bold"}]},{"type":"text","text":" – przy kilku milionach tokenów to drogie, wolne i pogarsza trafność."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"RAG rozwiązuje to tak, jak robi to człowiek: najpierw znajduje właściwe strony w segregatorze, potem odpowiada."}]},{"type":"heading","attrs":{"level":2,"id":"czy-na-pewno-potrzebujesz-rag"},"content":[{"type":"text","text":"Czy na pewno potrzebujesz RAG?"}]},{"type":"paragraph","content":[{"type":"text","text":"Uczciwe pytanie przed pierwszą linijką kodu. Karta, FAQ i regulamin "},{"type":"text","text":"jednego","marks":[{"type":"bold"}]},{"type":"text","text":" lokalu to może 30 tysięcy tokenów. Przy oknie kontekstu rzędu miliona tokenów i "},{"type":"text","text":"prompt caching","marks":[{"type":"italic"}]},{"type":"text","text":" najprostsze rozwiązanie to wysłać całość w stałym prefiksie promptu – bez bazy wektorowej, chunkingu i błędów wyszukiwania."}]},{"type":"codeGroup","attrs":{"title":"Bez RAG: cały mały korpus w cache"},"content":[{"type":"codeBlock","attrs":{"language":"python","filename":"faq_cached.py"},"content":[{"type":"text","text":"import anthropic\nfrom pathlib import Path\n\nclient = anthropic.Anthropic()\n\n# Menu + FAQ + terms of one restaurant: ~30k tokens. Small enough to send whole - no retrieval needed.\ncorpus = \"\\n\\n\".join(p.read_text(encoding=\"utf-8\") for p in sorted(Path(\"knowledge\").glob(\"*.md\")))\n\ndef ask(question: str) -> str:\n    response = client.messages.create(\n        model=\"claude-opus-5-5\",\n        max_tokens=1024,\n        system=[\n            {\"type\": \"text\", \"text\": \"Answer only from the knowledge base below. If it is not there, say so.\"},\n            # Stable prefix -> cached: later calls pay a fraction of the price for these tokens.\n            {\"type\": \"text\", \"text\": corpus, \"cache_control\": {\"type\": \"ephemeral\"}},\n        ],\n        messages=[{\"role\": \"user\", \"content\": question}],  # the variable part goes after the cache breakpoint\n    )\n    u = response.usage\n    print(f\"cache read={u.cache_read_input_tokens} written={u.cache_creation_input_tokens} fresh={u.input_tokens}\")\n    return next(b.text for b in response.content if b.type == \"text\")\n\nprint(ask(\"Do you deliver on Sundays?\"))"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"faq-cached.ts"},"content":[{"type":"text","text":"import Anthropic from \"@anthropic-ai/sdk\";\nimport { readFileSync, readdirSync } from \"node:fs\";\n\nconst client = new Anthropic();\n\n// Menu + FAQ + terms of one restaurant: ~30k tokens. Small enough to send whole.\nconst corpus = readdirSync(\"knowledge\")\n  .filter((f) => f.endsWith(\".md\"))\n  .sort()\n  .map((f) => readFileSync(`knowledge/${f}`, \"utf8\"))\n  .join(\"\\n\\n\");\n\nexport async function ask(question: string): Promise<string> {\n  const response = await client.messages.create({\n    model: \"claude-opus-5-5\",\n    max_tokens: 1024,\n    system: [\n      { type: \"text\", text: \"Answer only from the knowledge base below. If it is not there, say so.\" },\n      // Stable prefix -> cached; keep timestamps and user data out of it.\n      { type: \"text\", text: corpus, cache_control: { type: \"ephemeral\" } },\n    ],\n    messages: [{ role: \"user\", content: question }],\n  });\n  const u = response.usage;\n  console.log(`cache read=${u.cache_read_input_tokens} written=${u.cache_creation_input_tokens}`);\n  return response.content.flatMap((b) => (b.type === \"text\" ? [b.text] : [])).join(\"\");\n}"}]}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Sytuacja"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Lepszy wybór"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"korpus do ~kilkuset tysięcy tokenów, zmienia się rzadko"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"całość w prompcie + prompt caching"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"korpus duży (miliony tokenów) lub rośnie"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"RAG"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"różne uprawnienia do dokumentów (lokale, role, klienci)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"RAG z filtrowaniem po uprawnieniach"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"dane zmieniają się co minutę (stan zamówienia, dostępność)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"narzędzia – "},{"type":"text","text":"tool use","marks":[{"type":"link","attrs":{"href":"/pl/topics/tool-use"}}]},{"type":"text","text":" – zamiast indeksu"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Nasza sieć z 40 lokalami, opiniami i historią regulaminów to klasyczny przypadek dla RAG."}]},{"type":"heading","attrs":{"level":2,"id":"architektura-dwie-sciezki"},"content":[{"type":"text","text":"Architektura: dwie ścieżki"}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart TB\n  subgraph Indeksowanie[\"Indeksowanie (offline, przy każdej zmianie dokumentów)\"]\n    A[\"Źródła: karty, FAQ,<br/>regulamin, opinie\"] --> B[\"Wczytanie i czyszczenie<br/>HTML/PDF → tekst + metadane\"]\n    B --> C[\"Chunking<br/>struktura + rozmiar + overlap\"]\n    C --> D[\"Embeddingi + indeks pełnotekstowy\"]\n    D --> E[(\"Baza: wektory, BM25,<br/>metadane, uprawnienia\")]\n  end\n  subgraph Zapytanie[\"Zapytanie (online, przy każdym pytaniu)\"]\n    Q[\"Pytanie klienta\"] --> R[\"Przepisanie zapytania<br/>(opcjonalnie)\"]\n    R --> S[\"Wyszukiwanie hybrydowe<br/>top 20–50 + filtry\"]\n    S --> T[\"Reranking → top 5\"]\n    T --> U[\"Prompt: instrukcje + fragmenty + pytanie\"]\n    U --> V[\"LLM: odpowiedź z cytatami\"]\n  end\n  E --> S","caption":"RAG: indeksowanie offline i odpowiadanie online"}},{"type":"paragraph","content":[{"type":"text","text":"Ścieżka indeksowania działa w tle (job, kolejka, webhook z CMS-a). Ścieżka zapytania musi zmieścić się w budżecie opóźnienia rozmowy – typowo kilkadziesiąt milisekund na wyszukiwanie, do kilkuset na reranking i reszta na generowanie."}]},{"type":"heading","attrs":{"level":2,"id":"indeksowanie-smieci-na-wejsciu-halucynacje-na-wyjsciu"},"content":[{"type":"text","text":"Indeksowanie: śmieci na wejściu, halucynacje na wyjściu"}]},{"type":"paragraph","content":[{"type":"text","text":"Najwięcej problemów RAG zaczyna się przed embeddingami. Usuń nawigację, stopki i banery cookie z HTML-a, zachowaj tabele (godziny otwarcia w PDF-ie to częsty kłopot), usuń duplikaty i "},{"type":"text","text":"dołącz metadane","marks":[{"type":"bold"}]},{"type":"text","text":": lokal, język, typ dokumentu, data obowiązywania, uprawnienia. Metadane służą do filtrowania („tylko lokal 7”, „tylko aktualna wersja regulaminu”) i do pokazania źródła w odpowiedzi."}]},{"type":"heading","attrs":{"level":3,"id":"chunking"},"content":[{"type":"text","text":"Chunking"}]},{"type":"paragraph","content":[{"type":"text","text":"Fragment ("},{"type":"text","text":"chunk","marks":[{"type":"italic"}]},{"type":"text","text":") to jednostka wyszukiwania i cytowania. Za duży „rozmywa” znaczenie i zabiera miejsce w kontekście, za mały traci sens („Dostawa trwa 45 minut” – ale w którym lokalu?)."}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Strategia"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Jak"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Kiedy"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Stały rozmiar + overlap"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"okna np. 300–500 tokenów, zakładka 10–20%"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"punkt startowy, teksty bez struktury"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Rekursywnie po strukturze"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"najpierw nagłówki/akapity, potem rozmiar"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"dokumentacja, regulaminy, FAQ – najczęstszy wybór"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Semantyczny"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"cięcie tam, gdzie zmienia się temat (podobieństwo sąsiednich zdań)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"długie teksty narracyjne"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Jeden rekord = jeden chunk"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"pozycja menu, opinia, pytanie FAQ"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"dane już podzielone przez naturę"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Dobra praktyka: doklejaj do fragmentu "},{"type":"text","text":"ścieżkę nagłówków","marks":[{"type":"bold"}]},{"type":"text","text":" („Regulamin > Dostawa > Strefy”) i nazwę lokalu – wtedy fragment jest zrozumiały w izolacji. Anthropic opisał rozwinięcie tej idei jako "},{"type":"text","text":"Contextual Retrieval","marks":[{"type":"italic"}]},{"type":"text","text":": model dopisuje do każdego fragmentu krótki kontekst z całego dokumentu przed osadzeniem; w ich pomiarach połączenie z BM25 zmniejszyło odsetek nieudanych wyszukiwań o 49%, a z rerankingiem o 67%."}]},{"type":"codeGroup","attrs":{"title":"Chunking: najpierw struktura, potem rozmiar"},"content":[{"type":"codeBlock","attrs":{"language":"python","filename":"chunking.py"},"content":[{"type":"text","text":"import re\nfrom dataclasses import dataclass\n\nMAX_CHARS = 1200  # ~250-350 tokens of English, fewer for Polish - measure with your tokenizer\nOVERLAP = 200     # repeated tail so a sentence cut at the border is still findable\n\n@dataclass\nclass Chunk:\n    doc_id: str\n    heading_path: str  # e.g. \"Terms > Delivery > Zones\" - keeps the chunk self-explanatory\n    text: str\n\ndef split_by_headings(markdown: str) -> list[tuple[str, str]]:\n    \"\"\"Structure first: one section per Markdown heading, with the full heading path.\"\"\"\n    sections, path, buf = [], [], []\n    for line in markdown.splitlines():\n        m = re.match(r\"^(#{1,4})\\s+(.*)\", line)\n        if m:\n            if buf:\n                sections.append((\" > \".join(path), \"\\n\".join(buf).strip()))\n                buf = []\n            level = len(m.group(1))\n            path = path[: level - 1] + [m.group(2).strip()]\n        else:\n            buf.append(line)\n    if buf:\n        sections.append((\" > \".join(path), \"\\n\".join(buf).strip()))\n    return [(p, t) for p, t in sections if t]\n\ndef window(text: str) -> list[str]:\n    \"\"\"Size second: long sections become overlapping windows, cut at paragraph or sentence ends.\"\"\"\n    out, start = [], 0\n    while start < len(text):\n        end = min(start + MAX_CHARS, len(text))\n        if end < len(text):\n            cut = max(text.rfind(\"\\n\\n\", start, end), text.rfind(\". \", start, end))\n            end = cut + 1 if cut > start + MAX_CHARS // 2 else end\n        out.append(text[start:end].strip())\n        if end >= len(text):\n            break\n        start = max(end - OVERLAP, start + 1)\n    return out\n\ndef chunk_document(doc_id: str, markdown: str) -> list[Chunk]:\n    return [\n        Chunk(doc_id, path, f\"{path}\\n\\n{piece}\")  # the heading path is embedded together with the text\n        for path, body in split_by_headings(markdown)\n        for piece in window(body)\n    ]"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"chunking.ts"},"content":[{"type":"text","text":"export interface Chunk {\n  docId: string;\n  headingPath: string; // e.g. \"Terms > Delivery > Zones\"\n  text: string;\n}\n\nconst MAX_CHARS = 1200; // measure in tokens for your model and language\nconst OVERLAP = 200;\n\nfunction splitByHeadings(markdown: string): Array<[path: string, body: string]> {\n  const sections: Array<[string, string]> = [];\n  let path: string[] = [];\n  let buf: string[] = [];\n  const flush = () => {\n    const body = buf.join(\"\\n\").trim();\n    if (body) sections.push([path.join(\" > \"), body]);\n    buf = [];\n  };\n  for (const line of markdown.split(\"\\n\")) {\n    const m = /^(#{1,4})\\s+(.*)/.exec(line);\n    if (m) {\n      flush();\n      path = [...path.slice(0, m[1].length - 1), m[2].trim()];\n    } else buf.push(line);\n  }\n  flush();\n  return sections;\n}\n\nfunction windows(text: string): string[] {\n  const out: string[] = [];\n  let start = 0;\n  while (start < text.length) {\n    let end = Math.min(start + MAX_CHARS, text.length);\n    if (end < text.length) {\n      const cut = Math.max(text.lastIndexOf(\"\\n\\n\", end), text.lastIndexOf(\". \", end));\n      if (cut > start + MAX_CHARS / 2) end = cut + 1;\n    }\n    out.push(text.slice(start, end).trim());\n    if (end >= text.length) break;\n    start = Math.max(end - OVERLAP, start + 1);\n  }\n  return out;\n}\n\nexport function chunkDocument(docId: string, markdown: string): Chunk[] {\n  return splitByHeadings(markdown).flatMap(([headingPath, body]) =>\n    windows(body).map((piece) => ({ docId, headingPath, text: `${headingPath}\\n\\n${piece}` })),\n  );\n}"}]},{"type":"codeBlock","attrs":{"language":"csharp","filename":"Chunker.cs"},"content":[{"type":"text","text":"using System.Text.RegularExpressions;\n\nvar terms = \"\"\"\n    # Terms\n    ## Delivery\n    We deliver within 5 km of each restaurant. Orders above 80 PLN are delivered for free.\n    ## Allergens\n    Every dish lists the 14 EU allergens. The walnut sauce contains nuts.\n    \"\"\";\nforeach (var c in Chunker.Chunk(\"terms-v3\", terms))\n    Console.WriteLine($\"[{c.HeadingPath}] {c.Text.Length} chars\");\n\npublic sealed record Chunk(string DocId, string HeadingPath, string Text);\n\npublic static partial class Chunker\n{\n    const int MaxChars = 1200, Overlap = 200;\n\n    [GeneratedRegex(@\"^(#{1,4})\\s+(.*)$\")]\n    private static partial Regex Heading();\n\n    public static IEnumerable<Chunk> Chunk(string docId, string markdown)\n    {\n        var path = new List<string>();\n        var buf = new List<string>();\n        foreach (var line in markdown.Split('\\n').Append(\"# \"))  // sentinel flushes the last section\n        {\n            var m = Heading().Match(line);\n            if (!m.Success) { buf.Add(line); continue; }\n            var body = string.Join('\\n', buf).Trim();\n            var headingPath = string.Join(\" > \", path);\n            foreach (var piece in Windows(body))\n                yield return new Chunk(docId, headingPath, $\"{headingPath}\\n\\n{piece}\");\n            buf.Clear();\n            int level = m.Groups[1].Length;\n            path = [.. path.Take(level - 1), m.Groups[2].Value.Trim()];\n        }\n    }\n\n    static IEnumerable<string> Windows(string text)\n    {\n        for (int start = 0; start < text.Length;)\n        {\n            int end = Math.Min(start + MaxChars, text.Length);\n            if (end < text.Length)\n            {\n                int cut = Math.Max(text.LastIndexOf(\"\\n\\n\", end - 1), text.LastIndexOf(\". \", end - 1));\n                if (cut > start + MaxChars / 2) end = cut + 1;\n            }\n            yield return text[start..end].Trim();\n            if (end >= text.Length) yield break;\n            start = Math.Max(end - Overlap, start + 1);\n        }\n    }\n}"}]}]}]},"toc":[{"id":"problem-40-lokali-40-kart-i-regulamin-ktory-zmienia-sie-co-miesiac","text":"Problem: 40 lokali, 40 kart i regulamin, który zmienia się co miesiąc","level":2,"locked":false},{"id":"czy-na-pewno-potrzebujesz-rag","text":"Czy na pewno potrzebujesz RAG?","level":2,"locked":false},{"id":"architektura-dwie-sciezki","text":"Architektura: dwie ścieżki","level":2,"locked":false},{"id":"indeksowanie-smieci-na-wejsciu-halucynacje-na-wyjsciu","text":"Indeksowanie: śmieci na wejściu, halucynacje na wyjściu","level":2,"locked":false},{"id":"chunking","text":"Chunking","level":3,"locked":false},{"id":"wyszukiwanie-hybrydowe-slowa-i-znaczenie","text":"Wyszukiwanie hybrydowe: słowa i znaczenie","level":2,"locked":true},{"id":"reranking-najpierw-szeroko-potem-dokladnie","text":"Reranking: najpierw szeroko, potem dokładnie","level":2,"locked":true},{"id":"generowanie-odpowiedz-z-cytatami","text":"Generowanie: odpowiedź z cytatami","level":2,"locked":true},{"id":"ewaluacja-mierz-wyszukiwanie-i-generowanie-osobno","text":"Ewaluacja: mierz wyszukiwanie i generowanie osobno","level":2,"locked":true},{"id":"techniki-zaawansowane","text":"Techniki zaawansowane","level":2,"locked":true},{"id":"kiedy-rag-a-kiedy-cos-innego","text":"Kiedy RAG, a kiedy coś innego","level":2,"locked":true},{"id":"lista-kontrolna-przed-produkcja","text":"Lista kontrolna przed produkcją","level":2,"locked":true},{"id":"sprawdz-sie","text":"Sprawdź się","level":2,"locked":true},{"id":"co-dalej","text":"Co dalej","level":2,"locked":true}],"locked":true,"paywall":null,"previewRatio":0.3,"totalBlocks":61,"visibleBlocks":23,"resources":[{"id":"6b0857be3c96f2d34d0b4204","type":"article","provider":"web","url":"https://www.anthropic.com/news/contextual-retrieval","embedUrl":null,"title":"Contextual retrieval in AI systems","description":"Contextual retrieval improves how AI systems access and use information, reducing retrieval failures in large knowledge bases.","author":"Anthropic","thumbnailUrl":"https://assets.claude.com/e81642c949d3942e998d6ba331abf4074dd5050a.jpg","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["ai"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":"2024-09-19T00:00:00.000Z","popularity":75,"verifiedAt":"2026-11-26T11:25:46.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:59.965Z","updatedAt":"2026-11-26T16:00:59.965Z"},{"id":"6b0857b23c96f2d34d0b3407","type":"repo","provider":"github","url":"https://github.com/NirDiamant/RAG_Techniques","embedUrl":null,"title":"NirDiamant/RAG_Techniques","description":"This repository showcases various advanced techniques for Retrieval-Augmented Generation (RAG) systems. Each technique has a detailed notebook tutorial.","author":"NirDiamant","thumbnailUrl":"https://opengraph.githubassets.com/1/NirDiamant/RAG_Techniques","durationSec":null,"lang":"en","topics":["rag","embeddings-vector-db","ai-agents","ai-in-python"],"techs":["python"],"tags":["agentic-rag","ai","embeddings","generative-ai","gpt","langchain","databases","machine-learning","llm","llama-index"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"github","publishedAt":"2024-07-13T16:08:36.000Z","popularity":87,"verifiedAt":"2026-11-26T11:00:12.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:49.541Z","updatedAt":"2026-11-26T16:00:49.541Z"},{"id":"6b0857c23c96f2d34d0b44e9","type":"article","provider":"web","url":"https://docs.ragas.io/en/stable","embedUrl":null,"title":"Ragas","description":"Evaluation framework for your AI Application","author":"Ragas","thumbnailUrl":"https://docs.ragas.io/en/stable/assets/images/social/index.png","durationSec":null,"lang":"en","topics":["rag","evals"],"techs":["general"],"tags":["ai"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":50,"verifiedAt":"2026-11-26T11:26:44.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:04.995Z","updatedAt":"2026-11-26T16:01:04.995Z"},{"id":"6b0857b23c96f2d34d0b33f9","type":"repo","provider":"github","url":"https://github.com/microsoft/graphrag","embedUrl":null,"title":"microsoft/graphrag","description":"A modular graph-based Retrieval-Augmented Generation (RAG) system","author":"microsoft","thumbnailUrl":"https://opengraph.githubassets.com/1/microsoft/graphrag","durationSec":null,"lang":"en","topics":["rag","llm-fundamentals","ai-in-python"],"techs":["python"],"tags":["gpt","gpt-4","gpt4","graphrag","llm","llms","ai","rag"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"github","publishedAt":"2024-03-27T17:57:52.000Z","popularity":88,"verifiedAt":"2026-11-26T10:53:11.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:49.541Z","updatedAt":"2026-11-26T16:00:49.541Z"},{"id":"6b0857bf3c96f2d34d0b433c","type":"article","provider":"web","url":"https://www.pinecone.io/learn/retrieval-augmented-generation","embedUrl":null,"title":"Retrieval-Augmented Generation (RAG) | Pinecone","description":"Explore the limitations of foundation models and how retrieval-augmented generation (RAG) can address these limitations so chat, search, and agentic workflows can all benefit.","author":"Pinecone","thumbnailUrl":"https://www.pinecone.io/api/og/?title=Retrieval-Augmented%20Generation%20(RAG)&category=Learn","durationSec":null,"lang":"en","topics":["rag","embeddings-vector-db"],"techs":["general"],"tags":["ai"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":55,"verifiedAt":"2026-11-26T11:26:43.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"},{"id":"6b0857a93c96f2d34d0b3246","type":"repo","provider":"github","url":"https://github.com/run-llama/llama_index","embedUrl":null,"title":"run-llama/llama_index","description":"LlamaIndex is the document processing platform for AI","author":"run-llama","thumbnailUrl":"https://opengraph.githubassets.com/1/run-llama/llama_index","durationSec":null,"lang":"en","topics":["rag","ai-in-python"],"techs":["python"],"tags":[],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"seed","publishedAt":null,"popularity":94,"verifiedAt":"2026-11-26T00:00:00.000Z","curated":true,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:40.963Z","updatedAt":"2026-11-26T16:00:40.963Z"}],"challenges":[],"attachments":[],"hasCode":true,"repoUrl":null,"series":[{"slug":"ai-path","title":"AI dla programisty","items":[{"slug":"llm-fundamentals","title":"Podstawy LLM: tokeny, okno kontekstu i przewidywanie następnego słowa","current":false},{"slug":"prompt-engineering","title":"Prompt engineering: jak pisać instrukcje, które model naprawdę wykona","current":false},{"slug":"embeddings-vector-db","title":"Embeddingi i bazy wektorowe: wyszukiwanie po znaczeniu","current":false},{"slug":"rag","title":"RAG: odpowiedzi na podstawie własnych dokumentów","current":true},{"slug":"tool-use","title":"Tool use: jak model językowy wywołuje funkcje Twojej aplikacji","current":false},{"slug":"ai-agents","title":"Agenci AI: model w pętli z narzędziami – i kiedy wystarczy zwykły workflow","current":false},{"slug":"mcp","title":"MCP (Model Context Protocol): jeden standard łączenia AI z narzędziami i danymi","current":false},{"slug":"evals","title":"Ewaluacja aplikacji LLM (evals): testy dla systemów, które nie są deterministyczne","current":false},{"slug":"llm-ops","title":"LLMOps: bramka do modeli, cache, limity, obserwowalność i koszty w produkcji","current":false},{"slug":"ai-guardrails","title":"Guardrails i bezpieczeństwo aplikacji LLM: prompt injection, wycieki danych i uprawnienia narzędzi","current":false},{"slug":"local-llms","title":"Lokalne modele językowe: Ollama, llama.cpp, vLLM, kwantyzacja i realne kompromisy","current":false},{"slug":"fine-tuning","title":"Fine-tuning modeli językowych: kiedy się opłaca, LoRA i QLoRA w praktyce","current":false},{"slug":"ai-coding-assistants","title":"Asystenci programowania AI: od podpowiedzi w edytorze do agenta, który otwiera pull requesty","current":false}]}],"prev":{"slug":"embeddings-vector-db","title":"Embeddingi i bazy wektorowe: wyszukiwanie po znaczeniu"},"next":{"slug":"tool-use","title":"Tool use: jak model językowy wywołuje funkcje Twojej aplikacji"},"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":68,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Autorytet","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Autorytet","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Autorytet","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Autorytet","articles":38}]}}