Skip to content

Commit

Permalink
feat: save document source on DB (#186)
Browse files Browse the repository at this point in the history
* feat: save document source on DB

* feat: update chat schema

* feat: fix PR comments
  • Loading branch information
romansharapov19 authored Sep 21, 2023
1 parent ce3c3c2 commit dafccaf
Show file tree
Hide file tree
Showing 11 changed files with 67 additions and 11 deletions.
6 changes: 3 additions & 3 deletions packages/api/src/ai/facades/ai.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { SimpleConversationChainService } from '@/ai/services/simple-conversatio
import { VectorDbService } from '@/ai/services/vector-db.service';
import { AppConfigService } from '@/app-config/app-config.service';
import { RedisChatMemoryNotFoundException } from '@/chats/exceptions/redis-chat-memory-not-found.exception';
import { AiResponse } from '@/common/types/ai-response';
import { ChatDocument } from '@/common/types/chat';
import { Injectable, Logger } from '@nestjs/common';
import {
Expand Down Expand Up @@ -42,7 +43,7 @@ Helpful answer:`
chatLlmId: string,
shouldSummarize: boolean,
documents: ChatDocument[]
): Promise<string> {
): Promise<AiResponse | ChainValues> {
let summary: ChainValues;
let aiExecutor: AIExecutor;

Expand All @@ -69,8 +70,7 @@ Helpful answer:`
}

try {
const aiResponse = await aiExecutor.call({ input });
return aiResponse.output;
return aiExecutor.call({ input });
} catch (e) {
this.logger.error(
`Failed to ask AI in room ${roomId} for a response for question: `,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,11 @@ export class DocumentConversationChain {
res.text,
this.args.summary
);
return { output: res.text, source: res.sourceDocuments };
return {
output: res.text,
source: res.sourceDocuments,
document: document.meta.filename,
};
}
}
const simpleConversationChain =
Expand Down
17 changes: 13 additions & 4 deletions packages/api/src/chats/chat-socket.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,11 @@ export class ChatSocketGateway {
await this.shouldSummarizeChat(data.roomId),
await this.fetchDocumentsForContext(data.roomId)
);

this.server.to(data.roomId).emit(
'message',
createSocketMessageResponseFactory({
id: data.id,
response: aiResponse,
response: aiResponse.output,
isAi: true,
createdAt: new Date().toISOString(),
})
Expand All @@ -112,12 +111,22 @@ export class ChatSocketGateway {
}),
AddMessageToChatRequestSchema.parse({
sender: { isAi: true },
content: aiResponse,
content: aiResponse.output,
meta: {
tokens: encode(aiResponse).length,
tokens: encode(aiResponse.output).length,
ai: {
llmModel: this.appConfigService.getAiAppConfig().defaultAiModel,
},
...(aiResponse.document
? {
source: {
filename: aiResponse.document,
snippets: aiResponse.source.map(
(source) => source.pageContent
),
},
}
: {}),
},
}),
data.userId
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ export class AddMessagePairToHistoryJobConsumer {
});

answer.meta.replyTo = savedQuestion.id;

await this.addMessageToChatUsecase.execute(roomId, answer);

this.logger.debug(`Answer saved in chat history: `, {
Expand Down
14 changes: 14 additions & 0 deletions packages/api/src/chats/schemas/chat.mongoose.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,20 @@ const MessageMetaSchema = new mongoose.Schema(
_id: false,
required: false,
},
source: {
type: {
filename: {
type: String,
required: true,
},
snippets: {
type: [String],
required: true,
},
},
_id: false,
required: false,
},
},
{ _id: false, required: true }
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ export function createChatMessageFactory(
userId?: string
): Omit<ChatMessage, 'id'> {
const { sender, content, meta } = addMessageToChatRequestDto;

return {
sender: {
...(userId ? { userId } : {}),
Expand All @@ -23,6 +22,14 @@ export function createChatMessageFactory(
},
}
: {}),
...(!!meta.source
? {
source: {
filename: meta.source.filename,
snippets: meta.source.snippets,
},
}
: {}),
},
createdAt: new Date().toISOString(),
};
Expand Down
5 changes: 5 additions & 0 deletions packages/api/src/common/types/ai-response.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export interface AiResponse {
output: string;
source?: string[];
document?: string;
}
6 changes: 6 additions & 0 deletions packages/api/src/common/types/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,16 @@ export interface AiMeta {
llmModel: string;
}

export interface SourceMeta {
filename: string;
snippets: string[];
}

export interface ChatMessageMeta {
tokens: number;
replyTo?: string;
ai?: AiMeta;
source?: SourceMeta;
}

export interface Sender {
Expand Down
6 changes: 6 additions & 0 deletions packages/contract/chats/add-message-to-chat.request.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,11 @@ export const AddMessageToChatRequestSchema = z.object({
llmModel: z.string(),
})
.optional(),
source: z
.object({
filename: z.string(),
snippets: z.array(z.string()),
})
.optional(),
}),
});
6 changes: 6 additions & 0 deletions packages/contract/chats/chat-message.response.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ export const ChatMessageResponseSchema = z.object({
llmModel: z.string(),
})
.optional(),
source: z
.object({
filename: z.string(),
snippets: z.array(z.string()),
})
.optional(),
}),
createdAt: z.string().datetime(),
});
2 changes: 1 addition & 1 deletion packages/web-ui/components/error-layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export default function ErrorLayout({ minHeight }: ErrorLayoutProps) {
An unexpected error has occurred
</h1>
<p className="mt-4 text-gray-500">
Unfortunately something goes wrong. Please attempt to refresh the
Unfortunately something went wrong. Please attempt to refresh the
page, if the problem persists, kindly consider creating a GitHub
issue for further assistance.
</p>
Expand Down

0 comments on commit dafccaf

Please sign in to comment.