> 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-ai-assistant/python.md). Agents can also search and read this documentation through its [MCP server](https://dnotifier.gitbook.io/product-docs/~gitbook/mcp).

# Python

Self-contained **async HTTP assistant** with per-user **session** storage.

{% hint style="info" %}
This example uses **aiohttp** for the HTTP server — install separately: `pip install aiohttp`
{% endhint %}

## Complete example

```python
import asyncio
import json
import os
from aiohttp import web
from dnotifier import DNotifier

SERVICE_USER_ID = "api-assistant"
sessions: dict[str, str] = {}
notifier: DNotifier | None = None

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 handle_chat(request: web.Request) -> web.Response:
    body = await request.json()
    user_id = body.get("userId")
    message = body.get("message")

    if not user_id or not message:
        return web.json_response({"error": "userId and message required"}, status=400)

    existing_session = sessions.get(user_id)

    response = await notifier.send_ai(
        sender_id=user_id,
        session_id=existing_session,
        message={
            "messages": [
                {
                    "role": "system",
                    "content": "You are a friendly product assistant. Be concise and accurate.",
                },
                {"role": "user", "content": message},
            ],
        },
        save_history=True,
    )

    if existing_session is None:
        new_session = session_id_from_response(response)
        if new_session:
            sessions[user_id] = new_session

    return web.json_response({
        "answer": extract_content(response),
        "sessionId": sessions.get(user_id),
    })

async def handle_delete(request: web.Request) -> web.Response:
    user_id = request.match_info["user_id"]
    sessions.pop(user_id, None)
    return web.Response(status=204)

async def main():
    global notifier
    notifier = DNotifier(
        app_id=os.environ["DNOTIFIER_APP_ID"],
        secret=os.environ["DNOTIFIER_SECRET"],
        transport="http",
        user_id=SERVICE_USER_ID,
        logs=True,
        on_connected=lambda: print("AI service ready"),
    )
    await notifier.connect()

    app = web.Application()
    app.router.add_post("/api/chat", handle_chat)
    app.router.add_delete("/api/chat/{user_id}", handle_delete)

    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, "127.0.0.1", 3000)
    await site.start()
    print("Assistant API on :3000")

    await asyncio.Event().wait()

asyncio.run(main())
```

## Client request

```python
import httpx

async def ask_assistant(message: str) -> dict:
    async with httpx.AsyncClient() as client:
        resp = await client.post(
            "http://localhost:3000/api/chat",
            json={"userId": "user-alice", "message": message},
        )
        return resp.json()
```

## Learn more

* [**Sessions**](https://dnotifier.gitbook.io/product-docs/ai/sessions/python.md)
* [**Example: RAG bot**](https://dnotifier.gitbook.io/product-docs/ai/example-rag-bot/python.md)
