Реализация
Build-промпт для AI-кодера: реализовать хранилище чатов, плоскость debug/трейсов и индекс chat-памяти — три хранилища за своими slice'ами. Сначала прочитай Обзор, Хранилище, Debug и трейсинг и Память.
Эта страница — промпт для агента
У каждого раздела есть страница Реализация — точный, готовый к копипасту таск-спек, который агент исполняет.
Промпт
text
ROLE: You are implementing the Chats subsystem of Agentfy.ai 2.0 (NestJS + Prisma + CleanSlice).
GOAL: Persist user↔agent conversations as the source of truth, emit a full debug trace per turn to a
SEPARATE telemetry system, and build a memory index the agent can search — each behind a slice so the
physical backend is swappable.
DELIVERABLES
1) `agent/chat` slice: Chat + Message models (Postgres), gateway-backed. Append messages, paginate by
chat, list by agent. Message.content is Json (text + tool refs + attachments). Store the per-turn
trace id on the message. Make the chat DB connection a CONFIG value (so it can later point to a
dedicated Postgres instance without code changes). Add time/agent partitioning + an archive path
to object storage for cold chats. Do NOT store raw prompts/traces here.
2) Tracing: instrument the orchestrator (api) to emit one trace per turn to self-hosted LANGFUSE
(prompts, LLM calls, MCP tool_calls/results as spans, tokens, latency). Backend: Langfuse +
ClickHouse. Retention policy: hot in ClickHouse, cold dropped/archived. No trace data in the chat DB.
3) `agent/memory` slice: an async deriver (queue job) that chunks + embeds NEW messages into a memory
index (pgvector, reusing the LightRAG Postgres). Expose `memory_search` as a brain tool. Keep the
backend behind the gateway so pgvector → Honcho/`tally` is a swap later.
CONTRACTS / CONVENTIONS
- CleanSlice: gateway pattern, `I`-prefixed DI tokens, ids `{slice}-{uuid}` in mapper.toCreate, no `any`.
- The deriver is async (BullMQ) — never block the chat write path.
- memory_search is a BRAIN tool (no secrets/KEK in any worker).
SECURITY: trace plane is internal (debug/eval), never surfaced to the user chat; PII retention policy
on traces; chat archive in tenant-scoped object storage.
ACCEPTANCE: see below. Start at the v0.2 scope (chat + trace); memory can follow.Справка
- Модели:
Chat/Messageточно как в Хранилище и Схеме БД. - Трейс: один трейс на турн, trace id хранится на
Message; spans для LLM + каждого MCPtools/call. - Память:
Message → chunk → embed → pgvector;memory_search(query) → top-kподаётся в цикл.
Упорядоченные задачи
- v0.2 —
agent/chat(Postgres, gateway, пагинация) + инструментирование турна через Langfuse. - + Память — асинхронный deriver +
memory_searchна pgvector. - + Масштаб — партиционируй/архивируй таблицу
Message; вынеси чат в выделенный Postgres, когда IO потребует. - + tally — поменяй бэкенд памяти на Honcho/
tally, когда понадобится peer-memory.
Критерии приёмки
- [ ] Сообщения персистятся и пагинируются по чату; коннекшн чат-БД — это config-значение (заменяемый).
- [ ] Каждый турн порождает трейс в Langfuse (промпты + вызовы тулов + токены); никаких блобов трейсов в Postgres.
- [ ] Сообщение линкуется на свой trace id (прыжок из чата → полный debug).
- [ ]
memory_searchвозвращает релевантные попадания из прошлых чатов через pgvector; deriver работает асинхронно, вне пути записи. - [ ] Бэкенд памяти за gateway (pgvector сегодня,
tallyпотом) — без правок вызывающего кода при замене.
См. также
- Обзор · Хранилище · Debug и трейсинг · Память
- Конвенции — правила CleanSlice, которым нужно следовать.