logs
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Req,
|
||||
UnauthorizedException,
|
||||
@@ -16,6 +17,17 @@ import type { AssistantChatRequest } from './assistant.types';
|
||||
export class AssistantController {
|
||||
constructor(private readonly assistantService: AssistantService) {}
|
||||
|
||||
@Get('chat/logs')
|
||||
listChatLogs(@Req() request: AuthenticatedRequest) {
|
||||
const userId = request.user?.sub;
|
||||
|
||||
if (!userId) {
|
||||
throw new UnauthorizedException('Authenticated user is required.');
|
||||
}
|
||||
|
||||
return this.assistantService.listChatLogs(userId);
|
||||
}
|
||||
|
||||
@Post('chat')
|
||||
chat(
|
||||
@Req() request: AuthenticatedRequest,
|
||||
|
||||
@@ -12,6 +12,7 @@ describe('AssistantService', () => {
|
||||
const originalAgentId = process.env.MISTRAL_AGENT_ID;
|
||||
let chatLogsRepository: {
|
||||
create: jest.Mock;
|
||||
find: jest.Mock;
|
||||
save: jest.Mock;
|
||||
};
|
||||
let listRealtimeService: {
|
||||
@@ -29,6 +30,7 @@ describe('AssistantService', () => {
|
||||
global.fetch = jest.fn();
|
||||
chatLogsRepository = {
|
||||
create: jest.fn((input) => input),
|
||||
find: jest.fn(),
|
||||
save: jest.fn(async (input) => input),
|
||||
};
|
||||
listRealtimeService = {
|
||||
@@ -605,6 +607,15 @@ describe('AssistantService', () => {
|
||||
messages: [{ role: 'user', content: 'Hallo' }],
|
||||
}),
|
||||
).rejects.toThrow(ServiceUnavailableException);
|
||||
expect(chatLogsRepository.save).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
userId: 'user-1',
|
||||
statusCode: null,
|
||||
responsePayload: null,
|
||||
assistantContent: null,
|
||||
errorMessage: 'Mistral API key is not configured.',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('fails clearly when the agent id is missing', async () => {
|
||||
@@ -615,14 +626,62 @@ describe('AssistantService', () => {
|
||||
messages: [{ role: 'user', content: 'Hallo' }],
|
||||
}),
|
||||
).rejects.toThrow(ServiceUnavailableException);
|
||||
expect(chatLogsRepository.save).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
userId: 'user-1',
|
||||
agentId: null,
|
||||
statusCode: null,
|
||||
responsePayload: null,
|
||||
assistantContent: null,
|
||||
errorMessage: 'Mistral agent id is not configured.',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('lists the latest chat logs for the current user', async () => {
|
||||
chatLogsRepository.find.mockResolvedValue([
|
||||
{
|
||||
id: 'log-1',
|
||||
userId: 'user-1',
|
||||
provider: 'mistral',
|
||||
endpoint: 'https://api.mistral.ai/v1/agents/completions',
|
||||
agentId: 'agent-listify',
|
||||
statusCode: 502,
|
||||
durationMs: 123,
|
||||
requestPayload: { messages: [] },
|
||||
responsePayload: { message: 'connector failed' },
|
||||
assistantContent: null,
|
||||
errorMessage: 'Mistral agent request failed.',
|
||||
createdAt: new Date('2026-06-24T08:00:00.000Z'),
|
||||
},
|
||||
]);
|
||||
|
||||
const logs = await service.listChatLogs('user-1');
|
||||
|
||||
expect(chatLogsRepository.find).toHaveBeenCalledWith({
|
||||
where: { userId: 'user-1' },
|
||||
order: { createdAt: 'DESC' },
|
||||
take: 50,
|
||||
});
|
||||
expect(logs).toEqual([
|
||||
{
|
||||
id: 'log-1',
|
||||
provider: 'mistral',
|
||||
endpoint: 'https://api.mistral.ai/v1/agents/completions',
|
||||
agentId: 'agent-listify',
|
||||
statusCode: 502,
|
||||
durationMs: 123,
|
||||
requestPayload: { messages: [] },
|
||||
responsePayload: { message: 'connector failed' },
|
||||
assistantContent: null,
|
||||
errorMessage: 'Mistral agent request failed.',
|
||||
createdAt: '2026-06-24T08:00:00.000Z',
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
function mockMistralResponse(
|
||||
response: object,
|
||||
ok = true,
|
||||
status = 200,
|
||||
): void {
|
||||
function mockMistralResponse(response: object, ok = true, status = 200): void {
|
||||
jest.mocked(global.fetch).mockResolvedValue({
|
||||
ok,
|
||||
status,
|
||||
|
||||
@@ -17,12 +17,15 @@ import { AssistantChatLogEntity } from './assistant-chat-log.entity';
|
||||
import {
|
||||
AssistantAction,
|
||||
AssistantChatMessage,
|
||||
AssistantChatLog,
|
||||
AssistantPageContext,
|
||||
AssistantChatRequest,
|
||||
AssistantChatResponse,
|
||||
} from './assistant.types';
|
||||
|
||||
type MistralMessage = AssistantChatMessage | { role: 'system'; content: string };
|
||||
type MistralMessage =
|
||||
| AssistantChatMessage
|
||||
| { role: 'system'; content: string };
|
||||
|
||||
interface NormalizedContextItem {
|
||||
id: string;
|
||||
@@ -122,7 +125,8 @@ export class AssistantService {
|
||||
const response = await this.callMistralAgent(userId, messages, context);
|
||||
const actions = this.extractActions(response);
|
||||
const content =
|
||||
this.extractAssistantContent(response) ?? this.createActionContent(actions);
|
||||
this.extractAssistantContent(response) ??
|
||||
this.createActionContent(actions);
|
||||
const latestUserMessage = this.latestUserMessage(messages);
|
||||
|
||||
actions.forEach((action) => {
|
||||
@@ -144,6 +148,21 @@ export class AssistantService {
|
||||
}
|
||||
|
||||
if (!content) {
|
||||
await this.recordChatLog({
|
||||
userId,
|
||||
provider: 'listify',
|
||||
endpoint: 'assistant:emptyResponse',
|
||||
agentId: null,
|
||||
requestPayload: {
|
||||
latestUserMessage: latestUserMessage?.content,
|
||||
actionCount: actions.length,
|
||||
},
|
||||
responsePayload: { actions },
|
||||
statusCode: null,
|
||||
durationMs: 0,
|
||||
assistantContent: null,
|
||||
errorMessage: 'Mistral response was empty.',
|
||||
});
|
||||
throw new ServiceUnavailableException('Mistral response was empty.');
|
||||
}
|
||||
|
||||
@@ -156,6 +175,28 @@ export class AssistantService {
|
||||
};
|
||||
}
|
||||
|
||||
async listChatLogs(userId: string): Promise<AssistantChatLog[]> {
|
||||
const logs = await this.chatLogsRepository.find({
|
||||
where: { userId },
|
||||
order: { createdAt: 'DESC' },
|
||||
take: 50,
|
||||
});
|
||||
|
||||
return logs.slice(0, 50).map((log) => ({
|
||||
id: log.id,
|
||||
provider: log.provider,
|
||||
endpoint: log.endpoint,
|
||||
agentId: log.agentId,
|
||||
statusCode: log.statusCode,
|
||||
durationMs: log.durationMs,
|
||||
requestPayload: log.requestPayload,
|
||||
responsePayload: log.responsePayload,
|
||||
assistantContent: log.assistantContent,
|
||||
errorMessage: log.errorMessage,
|
||||
createdAt: log.createdAt.toISOString(),
|
||||
}));
|
||||
}
|
||||
|
||||
private async tryHandleLocalListQuery(
|
||||
userId: string,
|
||||
messages: AssistantChatMessage[],
|
||||
@@ -173,7 +214,10 @@ export class AssistantService {
|
||||
const visibleLists = wantsOpenLists
|
||||
? lists.filter((list) => !this.isCompletedList(list))
|
||||
: lists;
|
||||
const assistantContent = this.formatListsAnswer(visibleLists, wantsOpenLists);
|
||||
const assistantContent = this.formatListsAnswer(
|
||||
visibleLists,
|
||||
wantsOpenLists,
|
||||
);
|
||||
|
||||
await this.recordChatLog({
|
||||
userId,
|
||||
@@ -210,7 +254,9 @@ export class AssistantService {
|
||||
}
|
||||
|
||||
const latestUserMessage = this.latestUserMessage(messages);
|
||||
const itemTitle = this.extractItemTitleToAdd(latestUserMessage?.content ?? '');
|
||||
const itemTitle = this.extractItemTitleToAdd(
|
||||
latestUserMessage?.content ?? '',
|
||||
);
|
||||
|
||||
if (!itemTitle) {
|
||||
return null;
|
||||
@@ -384,15 +430,6 @@ export class AssistantService {
|
||||
): Promise<MistralAgentCompletionResponse> {
|
||||
const apiKey = process.env.MISTRAL_API_KEY;
|
||||
const agentId = process.env.MISTRAL_AGENT_ID;
|
||||
|
||||
if (!apiKey) {
|
||||
throw new ServiceUnavailableException('Mistral API key is not configured.');
|
||||
}
|
||||
|
||||
if (!agentId) {
|
||||
throw new ServiceUnavailableException('Mistral agent id is not configured.');
|
||||
}
|
||||
|
||||
const contextMessage = this.createContextSystemMessage(context);
|
||||
const requestPayload = {
|
||||
agent_id: agentId,
|
||||
@@ -419,6 +456,39 @@ export class AssistantService {
|
||||
type: 'text',
|
||||
},
|
||||
};
|
||||
|
||||
if (!apiKey) {
|
||||
await this.recordChatLog({
|
||||
userId,
|
||||
agentId: agentId ?? null,
|
||||
requestPayload,
|
||||
responsePayload: null,
|
||||
statusCode: null,
|
||||
durationMs: 0,
|
||||
assistantContent: null,
|
||||
errorMessage: 'Mistral API key is not configured.',
|
||||
});
|
||||
throw new ServiceUnavailableException(
|
||||
'Mistral API key is not configured.',
|
||||
);
|
||||
}
|
||||
|
||||
if (!agentId) {
|
||||
await this.recordChatLog({
|
||||
userId,
|
||||
agentId: null,
|
||||
requestPayload,
|
||||
responsePayload: null,
|
||||
statusCode: null,
|
||||
durationMs: 0,
|
||||
assistantContent: null,
|
||||
errorMessage: 'Mistral agent id is not configured.',
|
||||
});
|
||||
throw new ServiceUnavailableException(
|
||||
'Mistral agent id is not configured.',
|
||||
);
|
||||
}
|
||||
|
||||
const startedAt = Date.now();
|
||||
let statusCode: number | null = null;
|
||||
let responsePayload: unknown = null;
|
||||
@@ -658,13 +728,17 @@ export class AssistantService {
|
||||
}
|
||||
|
||||
private createActionContent(actions: AssistantAction[]): string | null {
|
||||
const createdList = actions.find((action) => action.type === 'list.created');
|
||||
const createdList = actions.find(
|
||||
(action) => action.type === 'list.created',
|
||||
);
|
||||
|
||||
if (createdList) {
|
||||
return `Ich habe die Liste **${createdList.list.name}** angelegt.`;
|
||||
}
|
||||
|
||||
const addedItem = actions.find((action) => action.type === 'list.item_added');
|
||||
const addedItem = actions.find(
|
||||
(action) => action.type === 'list.item_added',
|
||||
);
|
||||
|
||||
if (addedItem) {
|
||||
return `Ich habe **${addedItem.itemTitle}** zu **${addedItem.list.name}** hinzugefuegt.`;
|
||||
|
||||
@@ -41,6 +41,20 @@ export interface AssistantChatResponse {
|
||||
actions: AssistantAction[];
|
||||
}
|
||||
|
||||
export interface AssistantChatLog {
|
||||
id: string;
|
||||
provider: string;
|
||||
endpoint: string;
|
||||
agentId?: string | null;
|
||||
statusCode?: number | null;
|
||||
durationMs?: number | null;
|
||||
requestPayload: Record<string, unknown>;
|
||||
responsePayload?: unknown;
|
||||
assistantContent?: string | null;
|
||||
errorMessage?: string | null;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface CreateListToolInput {
|
||||
name?: string;
|
||||
description?: string;
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||
|
||||
export class CreateAssistantChatLogs1781700000000 implements MigrationInterface {
|
||||
name = 'CreateAssistantChatLogs1781700000000';
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
if (await queryRunner.hasTable('assistant_chat_logs')) {
|
||||
return;
|
||||
}
|
||||
|
||||
await queryRunner.query(`
|
||||
CREATE TABLE \`assistant_chat_logs\` (
|
||||
\`id\` varchar(36) NOT NULL,
|
||||
\`userId\` varchar(36) NOT NULL,
|
||||
\`provider\` varchar(120) NOT NULL,
|
||||
\`endpoint\` varchar(255) NOT NULL,
|
||||
\`agentId\` varchar(255) NULL,
|
||||
\`statusCode\` int NULL,
|
||||
\`durationMs\` int NULL,
|
||||
\`requestPayload\` json NOT NULL,
|
||||
\`responsePayload\` json NULL,
|
||||
\`assistantContent\` text NULL,
|
||||
\`errorMessage\` text NULL,
|
||||
\`createdAt\` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
INDEX \`IDX_assistant_chat_logs_user_id\` (\`userId\`),
|
||||
INDEX \`IDX_assistant_chat_logs_created_at\` (\`createdAt\`),
|
||||
PRIMARY KEY (\`id\`)
|
||||
) ENGINE=InnoDB
|
||||
`);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
if (await queryRunner.hasTable('assistant_chat_logs')) {
|
||||
await queryRunner.query('DROP TABLE `assistant_chat_logs`');
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user