Wemo.Learn

Step 3 of 11· AI Customer Support Chatbot

Knowledge base

Load the help center articles and split them into chunks that can be searched and cited.

Purpose#

Load the help center articles and split them into chunks. A chunk is the unit that search returns and that an answer cites. Good chunks are short enough to be specific and long enough to make sense alone.

In this step:

  • Write help articles in Markdown with front matter
  • Split articles at their headings
  • Split long sections at paragraph breaks

Articles#

The help center of Brightside Cleaning Co. has 5 articles. Each article is a Markdown file in knowledge_base/ with a title and a URL in front matter and one section per ## heading. The first one:

knowledge_base/cancellation.md
---
title: Cancellation and rescheduling
url: https://brightside.example/help/cancellation
---

## Free cancellation

You can cancel or reschedule a visit free of charge up to 24 hours before the start of the arrival window.

## Late cancellation

A cancellation less than 24 hours before the arrival window is charged 50% of the visit price.

## No-show and lockout

If the team cannot enter the property at the agreed time, they wait 15 minutes. After that the visit is charged in full (100% of the visit price).

## How to cancel

Cancel in the customer portal under "My visits", or call 555-0142 during support hours. A cancellation is valid when you see the status "Cancelled" in the portal.

## When we cancel

If Brightside has to cancel a visit, for example because of illness or severe weather, you are not charged and we offer the next available date.

Create the other 4 articles:

knowledge_base/booking.md
---
title: Booking a cleaning
url: https://brightside.example/help/booking
---

## How to book

Book a visit with the online booking form or by phone at 555-0142. Choose the service, the date, and a two-hour arrival window. You get a confirmation in the customer portal within one hour during support hours.

## Lead time

Bookings must be made at least 48 hours before the visit. Same-day and next-day bookings are not available.

## First visit

The first visit starts with a 10-minute walkthrough of your home with the team lead. The walkthrough is free. Tell the team about fragile items and rooms that should be skipped.

## Changing a booking

You can change the date, time or service of a booking in the customer portal up to 24 hours before the visit. Changes inside 24 hours follow the cancellation policy.
knowledge_base/pricing.md
---
title: Prices
url: https://brightside.example/help/pricing
---

## Home cleaning

Standard home cleaning costs $45 per hour per cleaner. The minimum booking is 2 hours. Most visits are done by a team of two cleaners.

## Deep cleaning

Deep cleaning costs $60 per hour per cleaner, with a minimum of 3 hours.

## Recurring discounts

Recurring plans get a discount on the hourly price: 15% for weekly visits, 10% for visits every two weeks, and 5% for monthly visits.

## Office cleaning

Office cleaning is priced per contract after a free site visit.

## Extra charges

There is no travel fee inside our service areas. Parking fees at your address are added to the invoice at cost.
knowledge_base/guarantee.md
---
title: Satisfaction guarantee and damage
url: https://brightside.example/help/guarantee
---

## Satisfaction guarantee

If you are not satisfied with a cleaning, report it within 48 hours of the visit. We return and clean the reported areas again free of charge within 3 business days.

## Refunds

We offer a re-clean first. If the re-clean does not solve the problem, the team lead reviews the case and can refund up to the full price of the visit.

## Damage

Report damage within 7 days of the visit, with photos. Brightside carries liability insurance up to $2,000,000. Claims are handled by the office, not by the cleaning team.

## How to report

Report a problem in the customer portal under "My visits" with the button "Report an issue", or call 555-0142.
knowledge_base/hours.md
---
title: Opening hours and holidays
url: https://brightside.example/help/hours
---

## Cleaning hours

Home cleaning visits take place Monday to Saturday between 7:00 and 19:00. We do not clean homes on Sundays.

## Support hours

Customer support is available Monday to Friday from 8:00 to 18:00, by phone at 555-0142 and through the chat on this website.

## Public holidays

We are closed on public holidays. A recurring visit that falls on a public holiday is moved to the next working day unless you choose another date.

To use your own help center, export the articles as Markdown files in this format. Most help center tools (Notion, Intercom, Zendesk, HelpScout) can export Markdown or HTML; convert HTML with a tool such as pandoc.

Writing articles that work well:

  • One topic per ## section. The heading is part of every chunk and helps search.
  • State facts with their numbers: "up to 24 hours before", not "with enough notice".
  • Avoid "see above" or "as mentioned". A chunk is read without the rest of the article.

Chunking#

support_desk/kb.py
"""Load the help center articles and split them into chunks."""
import hashlib
import re
from dataclasses import dataclass
from pathlib import Path

from support_desk import config

MAX_CHUNK_CHARS = 1200


@dataclass(frozen=True)
class Chunk:
    doc: str      # file name without .md
    title: str
    heading: str
    url: str
    content: str

    @property
    def text(self) -> str:
        """What gets embedded: the content with its title and heading, so a chunk makes sense alone."""
        return f"{self.title} > {self.heading}\n\n{self.content}"

    @property
    def content_hash(self) -> str:
        return hashlib.sha256(f"{self.doc}|{self.url}|{self.text}".encode()).hexdigest()


def parse(text: str) -> tuple[dict[str, str], str]:
    """Split a file into its front matter (title, url) and its body."""
    match = re.match(r"---\n(.*?)\n---\n(.*)", text, re.S)
    if not match:
        raise ValueError("missing front matter (--- title/url ---)")
    meta = dict(line.split(":", 1) for line in match.group(1).splitlines() if ":" in line)
    return {k.strip(): v.strip().strip("\"'") for k, v in meta.items()}, match.group(2)


def split_sections(body: str) -> list[tuple[str, str]]:
    """One section per '## heading'. Text before the first heading gets the heading 'Overview'."""
    sections, heading, lines = [], "Overview", []
    for line in body.splitlines():
        if line.startswith("## "):
            if "".join(lines).strip():
                sections.append((heading, "\n".join(lines).strip()))
            heading, lines = line[3:].strip(), []
        else:
            lines.append(line)
    if "".join(lines).strip():
        sections.append((heading, "\n".join(lines).strip()))
    return sections


def split_long(text: str, max_chars: int = MAX_CHUNK_CHARS) -> list[str]:
    """Keep sections whole when they fit. Split long ones at paragraph breaks."""
    if len(text) <= max_chars:
        return [text]
    parts, current = [], ""
    for paragraph in re.split(r"\n\s*\n", text):
        if current and len(current) + len(paragraph) + 2 > max_chars:
            parts.append(current)
            current = paragraph
        else:
            current = f"{current}\n\n{paragraph}" if current else paragraph
    return parts + [current] if current else parts


def load_chunks(kb_dir: str | None = None) -> list[Chunk]:
    chunks = []
    for path in sorted(Path(kb_dir or config.KB_DIR).glob("*.md")):
        try:
            # utf-8-sig drops an invisible byte-order mark; Windows line endings become plain newlines.
            meta, body = parse(path.read_text(encoding="utf-8-sig").replace("\r\n", "\n"))
            title, url = meta["title"], meta["url"]
        except (ValueError, KeyError) as e:
            raise ValueError(f"{path.name}: {e}") from None
        for heading, section in split_sections(body):
            for part in split_long(section):
                chunks.append(Chunk(path.stem, title, heading, url, part))
    return chunks


if __name__ == "__main__":
    all_chunks = load_chunks()
    print(f"{len(all_chunks)} chunks from {len({c.doc for c in all_chunks})} articles")
    print(f"longest chunk: {max(len(c.content) for c in all_chunks)} characters")
    print("\nExample:\n" + all_chunks[0].text)

Each ## section becomes one chunk, with the article title and heading in front so it makes sense on its own; long sections are split at paragraph breaks. Files saved with Windows line endings or a byte-order mark load correctly.

Chunk size: splitting by heading keeps each chunk on one topic. Fixed-size chunks (for example every 500 characters) cut sentences and mix topics. 1,200 characters is about 250 tokens; the answer step receives 5 chunks, about 1,300 tokens in total.

Checkpoint#

Terminal
uv run python -m support_desk.kb

Expected output:

Output
21 chunks from 5 articles
longest chunk: 211 characters

Example:
Booking a cleaning > How to book

Book a visit with the online booking form or by phone at 555-0142. Choose the service, the date, and a two-hour arrival window. You get a confirmation in the customer portal within one hour during support hours.

Troubleshooting#

  • ValueError: booking.md: missing front matter: the file must start with ---, then title: and url: lines, then ---.
  • KeyError for url: every article needs both title and url.
  • 0 chunks: KB_DIR points to the wrong folder. Run the command from support-desk.