Контекст диалога на Mastra Memory вместо своей таблицы
- Контекст диалога хранит Mastra Memory (LibSQL, memory.db рядом с DB_PATH), тред на чат - Бюджет истории — messageHistory.maxTokens (CONTEXT_TOKEN_LIMIT, по умолчанию 12000) - ToolCallFilter: результаты инструментов не попадают в прошлые реплики, внутри ответа — только свежий шаг - Системный промпт стабилен для всего чата (кешируется провайдером); автор и упоминания — в <turn author_name> - Фото передаются через context и не сохраняются в памяти - maxSteps и maxOutputTokens (ANSWER_TOKEN_LIMIT) — в defaultOptions агента - /context и /clear работают через Memory recall/deleteThread - Удалены свои dialog_messages, dialog-repository и dialog-service Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,58 +1,72 @@
|
||||
import { Agent } from "@mastra/core/agent";
|
||||
import { ToolCallFilter } from "@mastra/core/processors";
|
||||
import { RequestContext } from "@mastra/core/request-context";
|
||||
import type { Memory } from "@mastra/memory";
|
||||
import { readPrompt } from "../../libs/prompts.js";
|
||||
import type { DialogTurn, Persona } from "../../types.js";
|
||||
import type { Persona } from "../../types.js";
|
||||
import type { ChatHistoryService } from "../chat-history-service.js";
|
||||
import type { ChatMemberService } from "../chat-member-service.js";
|
||||
import type { DialogService } from "../dialog-service.js";
|
||||
import { chatThreadId } from "./memory.js";
|
||||
import { buildInstructions, buildUserText, type Question } from "./prompts.js";
|
||||
import { createListChatMembersTool } from "./tools/list-chat-members-tool.js";
|
||||
import { createReadChatMessagesTool } from "./tools/read-chat-messages-tool.js";
|
||||
import { createReadMemberMessagesTool } from "./tools/read-member-messages-tool.js";
|
||||
import type { AssistantRequestContext } from "./tools/request-context.js";
|
||||
import { assistantRequestContextSchema, type AssistantRequestContext } from "./tools/request-context.js";
|
||||
|
||||
export type { Question } from "./prompts.js";
|
||||
|
||||
interface AssistantServiceDeps {
|
||||
model: string;
|
||||
/** Контекст диалога — Mastra Memory (см. memory.ts). */
|
||||
memory: Memory;
|
||||
/** Максимальная длина ответа в токенах. */
|
||||
answerTokenLimit: number;
|
||||
/** Умеет ли модель смотреть изображения; если нет — фото ей не отправляем. */
|
||||
imageInput: boolean;
|
||||
chatHistoryService: ChatHistoryService;
|
||||
chatMemberService: ChatMemberService;
|
||||
dialogService: DialogService;
|
||||
}
|
||||
|
||||
const MAX_AGENT_STEPS = 6;
|
||||
/** Хватает на «прочитать архив/участников → ответить»; каждый лишний шаг — ещё один полный промпт. */
|
||||
const MAX_AGENT_STEPS = 4;
|
||||
|
||||
/** Сообщение пользователя для модели: текст вопроса и скачанные картинки. */
|
||||
const buildUserMessage = (question: Question) => ({
|
||||
role: "user" as const,
|
||||
content: [
|
||||
{ type: "text" as const, text: buildUserText(question) },
|
||||
...question.images.map((image) => ({ type: "image" as const, image: image.data, mimeType: image.mimeType })),
|
||||
],
|
||||
});
|
||||
|
||||
/** Реплика прошлого диалога в формате сообщений Mastra (роль должна быть литералом). */
|
||||
const toModelMessage = (turn: DialogTurn) =>
|
||||
turn.role === "user"
|
||||
? { role: "user" as const, content: turn.content }
|
||||
: { role: "assistant" as const, content: turn.content };
|
||||
/**
|
||||
* Картинки уходят через `context`: модель видит их в этом запросе, но в память они не сохраняются —
|
||||
* иначе байты фото тащились бы в каждый следующий вопрос.
|
||||
*/
|
||||
const imagesContext = (question: Question) =>
|
||||
question.images.length === 0
|
||||
? []
|
||||
: [
|
||||
{
|
||||
role: "user" as const,
|
||||
content: question.images.map((image) => ({ type: "image" as const, image: image.data, mimeType: image.mimeType })),
|
||||
},
|
||||
];
|
||||
|
||||
export const createAssistantService = ({
|
||||
model,
|
||||
memory,
|
||||
answerTokenLimit,
|
||||
imageInput,
|
||||
chatHistoryService,
|
||||
chatMemberService,
|
||||
dialogService,
|
||||
}: AssistantServiceDeps) => {
|
||||
const systemRules = readPrompt("system.md");
|
||||
|
||||
const agent = new Agent({
|
||||
id: "boltun",
|
||||
name: "Boltun",
|
||||
instructions: systemRules,
|
||||
requestContextSchema: assistantRequestContextSchema,
|
||||
// Одинаковы для всех вопросов чата — провайдер может кешировать этот префикс.
|
||||
instructions: ({ requestContext }) =>
|
||||
buildInstructions(systemRules, requestContext.get("persona"), requestContext.get("chatTitle")),
|
||||
model,
|
||||
memory,
|
||||
defaultOptions: { maxSteps: MAX_AGENT_STEPS, modelSettings: { maxOutputTokens: answerTokenLimit } },
|
||||
// Результаты инструментов (сотни сообщений архива) не должны ездить в каждый запрос:
|
||||
// первый фильтр убирает их из прошлых реплик, второй внутри ответа оставляет только самый свежий шаг.
|
||||
inputProcessors: [new ToolCallFilter(), new ToolCallFilter({ filterAfterToolSteps: 1 })],
|
||||
tools: {
|
||||
readChatMessages: createReadChatMessagesTool(chatHistoryService),
|
||||
listChatMembers: createListChatMembersTool(chatMemberService),
|
||||
@@ -61,32 +75,36 @@ export const createAssistantService = ({
|
||||
});
|
||||
|
||||
/**
|
||||
* Ответ на вопрос в образе личности. Контекст диалога (прошлые вопросы и ответы) подкладываем сами,
|
||||
* архив чата агент подгружает инструментами, когда нужно.
|
||||
* Ответ на вопрос в образе личности. Прошлые вопросы и ответы чата подтягивает Mastra Memory,
|
||||
* архив переписки агент читает инструментами, когда нужно.
|
||||
*/
|
||||
const answer = async (question: Question, persona: Persona): Promise<string> => {
|
||||
const requestContext = new RequestContext<AssistantRequestContext>();
|
||||
|
||||
requestContext.set("chatId", question.chatId);
|
||||
requestContext.set("chatTitle", question.chatTitle);
|
||||
requestContext.set("persona", persona);
|
||||
|
||||
const history = dialogService.recent(question.chatId).map(toModelMessage);
|
||||
const thread = chatThreadId(question.chatId);
|
||||
|
||||
const result = await agent.generate([...history, buildUserMessage(question)], {
|
||||
instructions: buildInstructions(systemRules, question, persona),
|
||||
const result = await agent.generate(buildUserText(question), {
|
||||
context: imagesContext(question),
|
||||
memory: { thread, resource: thread },
|
||||
requestContext,
|
||||
maxSteps: MAX_AGENT_STEPS,
|
||||
});
|
||||
|
||||
const text = result.text.trim();
|
||||
|
||||
// Картинки в контекст не кладём — только текст вопроса; пустой ответ не запоминаем.
|
||||
if (text) dialogService.remember(question.chatId, buildUserText(question), text);
|
||||
|
||||
return text;
|
||||
return result.text.trim();
|
||||
};
|
||||
|
||||
/** Сколько сообщений в контексте диалога чата: recall отдаёт `total`, не загружая весь тред. */
|
||||
const dialogSize = async (chatId: number): Promise<number> =>
|
||||
(await memory.recall({ threadId: chatThreadId(chatId), perPage: 1 })).total;
|
||||
|
||||
/** Начать диалог с чистого листа: удаляем тред чата из Memory. Архив чата не трогаем. */
|
||||
const clearDialog = (chatId: number): Promise<void> => memory.deleteThread(chatThreadId(chatId));
|
||||
|
||||
/** Боту стоит скачивать фото, только если модель умеет их смотреть. */
|
||||
return { answer, canSeeImages: imageInput };
|
||||
return { answer, dialogSize, clearDialog, canSeeImages: imageInput };
|
||||
};
|
||||
|
||||
export type AssistantService = ReturnType<typeof createAssistantService>;
|
||||
|
||||
Reference in New Issue
Block a user