> For the complete documentation index, see [llms.txt](https://dnotifier.gitbook.io/product-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dnotifier.gitbook.io/product-docs/ai/example-rag-bot/python.md).

# Python

Index FAQ content, then answer questions with **`useKnowledgeBase: true`**.

## Step 1 — Index documents

```python
import asyncio
from dnotifier import DNotifier

INDEXER_ID = "kb-indexer"

async def index_faqs(notifier: DNotifier):
    faqs = [
        {
            "record_id": "faq-refund",
            "content": "Refunds are processed within 5 business days after approval.",
        },
        {
            "record_id": "faq-password",
            "content": "Reset your password under Settings → Security → Reset password.",
        },
        {
            "record_id": "faq-shipping",
            "content": "Standard shipping takes 3–7 business days domestically.",
        },
    ]

    for faq in faqs:
        await notifier.add_document(
            sender_id=INDEXER_ID,
            record_id=faq["record_id"],
            content=faq["content"],
            doc_type="faq",
            metadata={"source": "help-center"},
        )
    print(f"Indexed {len(faqs)} documents")

async def main():
    notifier = DNotifier(
        app_id="your-app-id",
        secret="your-app-secret",
        transport="http",
        user_id=INDEXER_ID,
    )
    await notifier.connect()
    await index_faqs(notifier)

asyncio.run(main())
```

## Step 2 — RAG Q\&A function

```python
sessions: dict[str, str] = {}

def extract_content(response) -> str:
    if isinstance(response, dict) and isinstance(response.get("data"), dict):
        return str(response["data"].get("content", ""))
    return str(response)

def session_id_from_response(response) -> str | None:
    if isinstance(response, dict):
        meta = response.get("metadata")
        if isinstance(meta, dict):
            packet = meta.get("packet")
            if isinstance(packet, dict):
                return packet.get("id")
            return meta.get("id")
    return None

async def ask_support(notifier: DNotifier, user_id: str, question: str) -> str:
    response = await notifier.send_ai(
        sender_id=user_id,
        session_id=sessions.get(user_id),
        message={
            "useKnowledgeBase": True,
            "messages": [
                {
                    "role": "system",
                    "content": (
                        "You are a support bot. Answer only from retrieved knowledge. "
                        "If the answer is not in the knowledge base, say you do not know."
                    ),
                },
                {"role": "user", "content": question},
            ],
        },
        save_history=True,
    )

    sid = session_id_from_response(response)
    if sid and user_id not in sessions:
        sessions[user_id] = sid

    return extract_content(response)
```

## Step 3 — Manual search variant

```python
async def ask_support_manual(notifier: DNotifier, user_id: str, question: str) -> dict:
    hits = await notifier.search(
        sender_id=user_id,
        query=question,
        limit=5,
        min_similarity=0.5,
        filterby_source="help-center",
    )

    response = await notifier.send_ai(
        sender_id=user_id,
        message={
            "messages": [
                {"role": "system", "content": f"Context:\n{hits}"},
                {"role": "user", "content": question},
            ],
        },
    )

    return {
        "answer": extract_content(response),
        "sources": hits,
    }
```

## Learn more

* [**Semantic search**](https://dnotifier.gitbook.io/product-docs/ai/semantic-search/python.md)
* [**Intent router workflow**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/example-intent-router/python.md)
