Агент всегда отвечает текстом: пометка о последнем шаге, меньше перечитывания архива

- На последнем шаге к системному промпту дописывается «инструменты недоступны, ответь сейчас» и инструменты снимаются:
  Gemini, видя прошлые вызовы, выдумывал ещё один вызов и ответ оставался пустым (finishReason=tool-calls)
- Правило в system.md: обычно хватает 1–2 вызовов инструментов, не дочитывать архив «на всякий случай»
- Лимиты чтения 150 (чат) и 100 (участник); запрос больше лимита урезается, а не падает на валидации
- Понятный ответ, если текста всё же нет: попросить уточнить вопрос

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
yunogasai
2026-09-25 15:23:41 +02:00
parent 11efe48ee2
commit 1702ad885e
5 changed files with 21 additions and 8 deletions

View File

@@ -87,7 +87,7 @@ export const createQuestionHandlers = ({
try {
const answer = await withTyping(ctx, ask);
await reply(ctx, answer || "Мне нечего ответить 🤷");
await reply(ctx, answer || "Закопался в архиве и не успел ответить 🤷 Спроси конкретнее — например, про кого или за какой период.");
} catch (error) {
console.error("Ошибка генерации ответа:", error);
await reply(ctx, "Не получилось получить ответ от модели, попробуй ещё раз позже.");

View File

@@ -31,6 +31,13 @@ interface AssistantServiceDeps {
/** Шаги агента: несколько на чтение архива и участников, последний — всегда текстовый ответ. */
const MAX_AGENT_STEPS = 6;
/**
* Дописывается к системному промпту на последнем шаге. Одного снятия инструментов мало: Gemini, видя в этом
* ответе прошлые вызовы, может «выдумать» ещё один вызов — и тогда текста нет вовсе.
*/
const FINAL_STEP_NOTE =
"Это последний шаг: инструменты больше недоступны, не вызывай их. Ответь пользователю сейчас по тому, что уже нашёл.";
/**
* Картинки уходят через `context`: модель видит их в этом запросе, но в память они не сохраняются —
* иначе байты фото тащились бы в каждый следующий вопрос.
@@ -69,7 +76,14 @@ export const createAssistantService = ({
modelSettings: { maxOutputTokens: answerTokenLimit },
// На последнем шаге инструменты запрещены: иначе модель может потратить все шаги на чтение архива
// и так и не ответить (в ответе бота было бы пусто).
prepareStep: ({ stepNumber }) => (stepNumber >= MAX_AGENT_STEPS - 1 ? { toolChoice: "none" } : undefined),
prepareStep: ({ stepNumber, systemMessages }) =>
stepNumber >= MAX_AGENT_STEPS - 1
? {
toolChoice: "none",
activeTools: [],
systemMessages: [...systemMessages, { role: "system", content: FINAL_STEP_NOTE }],
}
: undefined,
// Провайдеры (OpenRouter/Gemini) присылают ошибку частью ответа — без этого в логе только «finishReason: other».
onError: ({ error }) => console.error("Ошибка провайдера модели:", error),
},

View File

@@ -4,7 +4,7 @@ import type { ChatHistoryService } from "../../chat-history-service.js";
import { formatChatMessages } from "../format-chat-messages.js";
import { assistantRequestContextSchema } from "./request-context.js";
const MAX_HISTORY_READ = 300;
const MAX_HISTORY_READ = 150;
export const createReadChatMessagesTool = (chatHistoryService: ChatHistoryService) =>
createTool({
@@ -18,13 +18,12 @@ export const createReadChatMessagesTool = (chatHistoryService: ChatHistoryServic
.number()
.int()
.min(1)
.max(MAX_HISTORY_READ)
.default(50)
.describe(`Сколько последних сообщений загрузить (1–${MAX_HISTORY_READ}).`),
}),
requestContextSchema: assistantRequestContextSchema,
execute: async ({ limit }, { requestContext }) => {
const messages = chatHistoryService.latest(requestContext.get("chatId"), limit);
const messages = chatHistoryService.latest(requestContext.get("chatId"), Math.min(limit, MAX_HISTORY_READ));
return {
count: messages.length,

View File

@@ -7,7 +7,7 @@ import { formatChatMembers } from "../format-chat-members.js";
import { formatChatMessages } from "../format-chat-messages.js";
import { assistantRequestContextSchema } from "./request-context.js";
const MAX_MEMBER_MESSAGES = 200;
const MAX_MEMBER_MESSAGES = 100;
interface ReadMemberMessagesToolDeps {
chatHistoryService: ChatHistoryService;
@@ -27,7 +27,6 @@ export const createReadMemberMessagesTool = ({ chatHistoryService, chatMemberSer
.number()
.int()
.min(1)
.max(MAX_MEMBER_MESSAGES)
.default(50)
.describe(`Сколько последних сообщений участника загрузить (1–${MAX_MEMBER_MESSAGES}).`),
}),
@@ -45,7 +44,7 @@ export const createReadMemberMessagesTool = ({ chatHistoryService, chatMemberSer
return { status: "ambiguous", result: `Под «${member}» подходят несколько человек:\n${formatChatMembers([found, ...others])}` };
}
const messages = chatHistoryService.latestByUser(chatId, found.userId, limit);
const messages = chatHistoryService.latestByUser(chatId, found.userId, Math.min(limit, MAX_MEMBER_MESSAGES));
return {
status: "ok",