ИИ-мастер подземелий, который не выдумывает правила
Браузерная игра, где ИИ управляет процессом и отвечает на вопросы по правилам. Все ответы проверяются по официной базе знаний. ИИ не придумывает правила, а только находит их в документе.
- Для кого
- Разработчик
Что понадобится
Как повторить
- Создать проект в системе управления контентом Sanity.
- Загрузить в проект правила, заклинания и монстров.
- Настроить базу знаний для поиска текстовых ответов.
- Настроить прямой доступ к данным для поиска цифр.
- Подключить нейросеть к обоим источникам через специальный интерфейс.
- Написать код игры, который отправляет запросы к ИИ.
- Запустить игру в браузере и проверять ответы ИИ.
Здесь — короткая схема. Пошаговые детали и скриншоты — в оригинале.
Подробная инструкция — у автораПромпт
Вставьте этот текст в ИИ-ассистента.
You are the "dmkb" agent for The Goblin Warren, a browser D&D game entered in the DEV.to × Sanity challenge, Path 1 (an agent on Sanity Context, judged partly on meaningful use of Knowledge Bases). Project: [REDACTED]/Documents/projects/devto/D_D/game. FIRST read docs/PHASE2_BRIEF.md (Contract E) and docs/POLISH_BRIEF.md. Do NOT spawn subagents. Teammates: core2 (controller; sends you exploration beats), maps, scene2, hud2.
You own ONLY src/app/api/dm/route.ts, src/lib/, src/components/DmPanel.tsx, src/components/dm/, src/components/RichText.tsx, src/styles/dm.css, a new e2e/dm-live.spec.ts, and docs/sanity-setup.md.
Setup:
- Inference: Baseten deepseek-ai/DeepSeek-V4.1-Flash via @ai-sdk/baseten, reasoning off through providerOptions.
- Live keys are in .env.local. Don't print or log secret values. You may read them with set -a; . .env.local; set +a inside a command.
- Two Sanity Context MCP endpoints:
- SANITY_CONTEXT_MCP_URL (GROQ mode): initial_context, groq_query, schema_explorer, array_field_reader
- SANITY_KB_MCP_URL (KB mode): initial_context, knowledge_base_search, knowledge_base_read
- The route already has a tool allowlist, a GROQ guard, untrusted-input blocks, rate limits, server-side prefetch of the cited docs for one-step narration, a schema primer, and guaranteed final replies.
What the live test showed:
- The model never called a KB tool. Everything went through groq_query.
- Answers sometimes run long (150–200 words).
- Rules Q&A takes 6–12s and narration about 4s.
Tasks:
1. Make the Knowledge Base a real, visible part of the agent.
- First probe the KB endpoint directly: call initial_context, then knowledge_base_search and knowledge_base_read with a real query such as "grappled 2024 changes", using JSON-RPC over curl like docs/sanity-setup.md shows. Learn the exact input schema and output shape.
- Find out whether the KB exposes contradiction or conflict information (the Sanity docs mention KB contradiction reports). If it does, surface it.
- Then change the agent strategy, through tool descriptions, prompt and step design:
- Rules-prose questions ("how does X work", "what changed in 2014 vs 2024") go first through knowledge_base_search, then knowledge_base_read when needed.
- Exact numbers and stats (monster AC/HP, spell dice) go through groq_query.
- Consider making step 0 a forced knowledge_base_search for ask-mode rules questions (prepareStep with toolChoice). Note that Baseten DeepSeek ignored toolChoice:'none' earlier, but removing tools via activeTools worked. Test whether a forced or required tool choice works; if it doesn't, run the KB search server-side as a prefetch, the same way narration already prefetches.
- The lookup trace in DmPanel must clearly show the violet "Sanity Knowledge Base" badge with the search query, plus the "Sanity Context (GROQ)" steps. Make sure lookups[].ids gets real doc ids from KB results (adapt extractIds to the KB output format if needed).
- In the narrate prompt, for exploration beats (room entry, lore stones, loot), let the DM narrate richly with no citations needed unless rules apply.
2. Polish the DM's answers.
- Rules answers: at most about 90 words. A direct answer first, then the key mechanics, then an optional "Rules changed:" line. Cite every rules sentence.
- Narration: 2–3 sentences, at most about 55 words, second person, vivid. Never mention lookups, tools or queries. Never invent numbers.
- Enforce this with a prompt tune, maxOutputTokens tuning, and a post-processor that trims to the last complete sentence if over the limit, removes markdown headers, bullets and bold, keeps [[ids]], and strips any leaked tool markup (cleanReply exists already).
- Make the citations reliable: drop any [[id]] that isn't in the returned or cited ids, and the known-id set from fallback.json, rather than showing a broken chip.
- Latency: aim for under 6s for rules questions. Ideas: parallel KB+GROQ prefetch, fewer steps, a smaller maxOutputTokens, and caching initial_context per instance.
3. e2e/dm-live.spec.ts (it uses real API calls, so keep it to about 8 requests total). It calls /api/dm directly and asserts:
- backend is sanity-context
- the text is non-empty and under the word caps
- the citations resolve to known ids
- at least one lookup has via=knowledge-base for a rules question
- the injection test is refused
- narration has no "lookup/query/tool" words
Run it and record the latencies.
4. Update the "How it works" part of docs/sanity-setup.md, or add a short docs/architecture.md section: which questions go to the KB versus GROQ, and why.
Commit in small steps via /tmp/gc.sh. Final report to main with before/after sample answers, latencies, and how the KB is used.Подробности
Автор создал браузерную игру в стиле подземелий. Игрок управляет группой героев. ИИ выступает в роли ведущего. Он описывает события и отвечает на вопросы. Главная особенность — ИИ никогда не выдумывает правила. На каждый вопрос он ищет ответ в официальной базе знаний. Если правило найдено, ИИ приводит ссылку на источник. Игрок может проверить, откуда взялся ответ. ИИ различает два типа запросов. Для текстовых вопросов он использует базу знаний. Для точных цифр (здоровье, защита) он делает прямой запрос к данным. Это исключает ошибки и выдумки. ИИ работает быстро. Ответы приходят за пару секунд. Система автоматически удаляет ссылки, на которые не нашла данных. Это гарантирует честность игры.
Источник
Оригинал: The Goblin Warren: an AI Dungeon Master that never invents a rule (dev.to, англ.)
Переведено и упрощено ahamoment
Добавлено 28 октября 2026 г.