openai.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  1. import assert from 'node:assert';
  2. import { Readable, Transform } from 'stream';
  3. import { pipeline } from 'stream/promises';
  4. import type {
  5. IUser, Ref, Lang, IPage,
  6. } from '@growi/core';
  7. import {
  8. PageGrant, getIdForRef, getIdStringForRef, isPopulated, type IUserHasId,
  9. } from '@growi/core';
  10. import { deepEquals } from '@growi/core/dist/utils';
  11. import { isGlobPatternPath } from '@growi/core/dist/utils/page-path-utils';
  12. import escapeStringRegexp from 'escape-string-regexp';
  13. import createError from 'http-errors';
  14. import mongoose, { type HydratedDocument, type Types } from 'mongoose';
  15. import { type OpenAI, toFile } from 'openai';
  16. import ExternalUserGroupRelation from '~/features/external-user-group/server/models/external-user-group-relation';
  17. import ThreadRelationModel, { type ThreadRelationDocument } from '~/features/openai/server/models/thread-relation';
  18. import VectorStoreModel, { type VectorStoreDocument } from '~/features/openai/server/models/vector-store';
  19. import VectorStoreFileRelationModel, {
  20. type VectorStoreFileRelation,
  21. prepareVectorStoreFileRelations,
  22. } from '~/features/openai/server/models/vector-store-file-relation';
  23. import type { PageDocument, PageModel } from '~/server/models/page';
  24. import UserGroupRelation from '~/server/models/user-group-relation';
  25. import { configManager } from '~/server/service/config-manager';
  26. import { createBatchStream } from '~/server/util/batch-stream';
  27. import loggerFactory from '~/utils/logger';
  28. import { OpenaiServiceTypes } from '../../interfaces/ai';
  29. import type { UpsertAiAssistantData } from '../../interfaces/ai-assistant';
  30. import {
  31. type AccessibleAiAssistants, type AiAssistant, AiAssistantAccessScope, AiAssistantShareScope,
  32. } from '../../interfaces/ai-assistant';
  33. import type { MessageListParams } from '../../interfaces/message';
  34. import { ThreadType } from '../../interfaces/thread-relation';
  35. import type { IVectorStore } from '../../interfaces/vector-store';
  36. import { removeGlobPath } from '../../utils/remove-glob-path';
  37. import AiAssistantModel, { type AiAssistantDocument } from '../models/ai-assistant';
  38. import { convertMarkdownToHtml } from '../utils/convert-markdown-to-html';
  39. import { generateGlobPatterns } from '../utils/generate-glob-patterns';
  40. import { getClient } from './client-delegator';
  41. import { openaiApiErrorHandler } from './openai-api-error-handler';
  42. import { replaceAnnotationWithPageLink } from './replace-annotation-with-page-link';
  43. const { isDeepEquals } = deepEquals;
  44. const BATCH_SIZE = 100;
  45. const logger = loggerFactory('growi:service:openai');
  46. type VectorStoreFileRelationsMap = Map<string, VectorStoreFileRelation>
  47. const convertPathPatternsToRegExp = (pagePathPatterns: string[]): Array<string | RegExp> => {
  48. return pagePathPatterns.map((pagePathPattern) => {
  49. if (isGlobPatternPath(pagePathPattern)) {
  50. const trimedPagePathPattern = pagePathPattern.replace('/*', '');
  51. const escapedPagePathPattern = escapeStringRegexp(trimedPagePathPattern);
  52. // https://regex101.com/r/x5KIZL/1
  53. return new RegExp(`^${escapedPagePathPattern}($|/)`);
  54. }
  55. return pagePathPattern;
  56. });
  57. };
  58. export interface IOpenaiService {
  59. createThread(userId: string, type: ThreadType, aiAssistantId?: string, initialUserMessage?: string): Promise<ThreadRelationDocument>;
  60. getThreadsByAiAssistantId(aiAssistantId: string): Promise<ThreadRelationDocument[]>
  61. deleteThread(threadRelationId: string): Promise<ThreadRelationDocument>;
  62. deleteExpiredThreads(limit: number, apiCallInterval: number): Promise<void>; // for CronJob
  63. deleteObsoletedVectorStoreRelations(): Promise<void> // for CronJob
  64. deleteVectorStore(vectorStoreRelationId: string): Promise<void>;
  65. getMessageData(threadId: string, lang?: Lang, options?: MessageListParams): Promise<OpenAI.Beta.Threads.Messages.MessagesPage>;
  66. createVectorStoreFile(vectorStoreRelation: VectorStoreDocument, pages: PageDocument[]): Promise<void>;
  67. createVectorStoreFileOnPageCreate(pages: PageDocument[]): Promise<void>;
  68. updateVectorStoreFileOnPageUpdate(page: HydratedDocument<PageDocument>): Promise<void>;
  69. deleteVectorStoreFile(vectorStoreRelationId: Types.ObjectId, pageId: Types.ObjectId): Promise<void>;
  70. deleteVectorStoreFilesByPageIds(pageIds: Types.ObjectId[]): Promise<void>;
  71. deleteObsoleteVectorStoreFile(limit: number, apiCallInterval: number): Promise<void>; // for CronJob
  72. isAiAssistantUsable(aiAssistantId: string, user: IUserHasId): Promise<boolean>;
  73. createAiAssistant(data: UpsertAiAssistantData, user: IUserHasId): Promise<AiAssistantDocument>;
  74. updateAiAssistant(aiAssistantId: string, data: UpsertAiAssistantData, user: IUserHasId): Promise<AiAssistantDocument>;
  75. getAccessibleAiAssistants(user: IUserHasId): Promise<AccessibleAiAssistants>
  76. isLearnablePageLimitExceeded(user: IUserHasId, pagePathPatterns: string[]): Promise<boolean>;
  77. }
  78. class OpenaiService implements IOpenaiService {
  79. private get client() {
  80. const openaiServiceType = configManager.getConfig('openai:serviceType');
  81. return getClient({ openaiServiceType });
  82. }
  83. async generateThreadTitle(message: string): Promise<string | null> {
  84. const systemMessage = [
  85. 'Create a brief title (max 5 words) from your message.',
  86. 'Respond in the same language the user uses in their input.',
  87. 'Response should only contain the title.',
  88. ].join('');
  89. const threadTitleCompletion = await this.client.chatCompletion({
  90. model: 'gpt-4.1-nano',
  91. messages: [
  92. {
  93. role: 'system',
  94. content: systemMessage,
  95. },
  96. {
  97. role: 'user',
  98. content: message,
  99. },
  100. ],
  101. });
  102. const threadTitle = threadTitleCompletion.choices[0].message.content;
  103. return threadTitle;
  104. }
  105. async createThread(userId: string, type: ThreadType, aiAssistantId?: string, initialUserMessage?: string): Promise<ThreadRelationDocument> {
  106. let threadTitle: string | null = null;
  107. if (initialUserMessage != null) {
  108. try {
  109. threadTitle = await this.generateThreadTitle(initialUserMessage);
  110. }
  111. catch (err) {
  112. logger.error(err);
  113. }
  114. }
  115. try {
  116. const aiAssistant = aiAssistantId != null
  117. ? await AiAssistantModel.findOne({ _id: { $eq: aiAssistantId } }).populate<{ vectorStore: IVectorStore }>('vectorStore')
  118. : null;
  119. const thread = await this.client.createThread(aiAssistant?.vectorStore?.vectorStoreId);
  120. const threadRelation = await ThreadRelationModel.create({
  121. userId,
  122. type,
  123. aiAssistant: aiAssistantId,
  124. threadId: thread.id,
  125. title: threadTitle,
  126. });
  127. return threadRelation;
  128. }
  129. catch (err) {
  130. throw err;
  131. }
  132. }
  133. async updateThreads(aiAssistantId: string, vectorStoreId: string): Promise<void> {
  134. const threadRelations = await this.getThreadsByAiAssistantId(aiAssistantId);
  135. for await (const threadRelation of threadRelations) {
  136. try {
  137. const updatedThreadResponse = await this.client.updateThread(threadRelation.threadId, vectorStoreId);
  138. logger.debug('Update thread', updatedThreadResponse);
  139. }
  140. catch (err) {
  141. logger.error(err);
  142. }
  143. }
  144. }
  145. async getThreadsByAiAssistantId(aiAssistantId: string, type: ThreadType = ThreadType.KNOWLEDGE): Promise<ThreadRelationDocument[]> {
  146. const threadRelations = await ThreadRelationModel.find({ aiAssistant: aiAssistantId, type });
  147. return threadRelations;
  148. }
  149. async deleteThread(threadRelationId: string): Promise<ThreadRelationDocument> {
  150. const threadRelation = await ThreadRelationModel.findById(threadRelationId);
  151. if (threadRelation == null) {
  152. throw createError(404, 'ThreadRelation document does not exist');
  153. }
  154. try {
  155. const deletedThreadResponse = await this.client.deleteThread(threadRelation.threadId);
  156. logger.debug('Delete thread', deletedThreadResponse);
  157. await threadRelation.remove();
  158. }
  159. catch (err) {
  160. await openaiApiErrorHandler(err, { notFoundError: async() => { await threadRelation.remove() } });
  161. throw err;
  162. }
  163. return threadRelation;
  164. }
  165. public async deleteExpiredThreads(limit: number, apiCallInterval: number): Promise<void> {
  166. const expiredThreadRelations = await ThreadRelationModel.getExpiredThreadRelations(limit);
  167. if (expiredThreadRelations == null) {
  168. return;
  169. }
  170. const deletedThreadIds: string[] = [];
  171. for await (const expiredThreadRelation of expiredThreadRelations) {
  172. try {
  173. const deleteThreadResponse = await this.client.deleteThread(expiredThreadRelation.threadId);
  174. logger.debug('Delete thread', deleteThreadResponse);
  175. deletedThreadIds.push(expiredThreadRelation.threadId);
  176. // sleep
  177. await new Promise(resolve => setTimeout(resolve, apiCallInterval));
  178. }
  179. catch (err) {
  180. logger.error(err);
  181. }
  182. }
  183. await ThreadRelationModel.deleteMany({ threadId: { $in: deletedThreadIds } });
  184. }
  185. async getMessageData(threadId: string, lang?: Lang, options?: MessageListParams): Promise<OpenAI.Beta.Threads.Messages.MessagesPage> {
  186. const messages = await this.client.getMessages(threadId, options);
  187. for await (const message of messages.data) {
  188. for await (const content of message.content) {
  189. if (content.type === 'text') {
  190. await replaceAnnotationWithPageLink(content, lang);
  191. }
  192. }
  193. }
  194. return messages;
  195. }
  196. async getVectorStoreRelationsByPageIds(pageIds: Types.ObjectId[]): Promise<VectorStoreDocument[]> {
  197. const pipeline = [
  198. // Stage 1: Match documents with the given pageId
  199. {
  200. $match: {
  201. page: {
  202. $in: pageIds,
  203. },
  204. },
  205. },
  206. // Stage 2: Lookup VectorStore documents
  207. {
  208. $lookup: {
  209. from: 'vectorstores',
  210. localField: 'vectorStoreRelationId',
  211. foreignField: '_id',
  212. as: 'vectorStore',
  213. },
  214. },
  215. // Stage 3: Unwind the vectorStore array
  216. {
  217. $unwind: '$vectorStore',
  218. },
  219. // Stage 4: Match non-deleted vector stores
  220. {
  221. $match: {
  222. 'vectorStore.isDeleted': false,
  223. },
  224. },
  225. // Stage 5: Replace the root with vectorStore document
  226. {
  227. $replaceRoot: {
  228. newRoot: '$vectorStore',
  229. },
  230. },
  231. // Stage 6: Group by _id to remove duplicates
  232. {
  233. $group: {
  234. _id: '$_id',
  235. doc: { $first: '$$ROOT' },
  236. },
  237. },
  238. // Stage 7: Restore the document structure
  239. {
  240. $replaceRoot: {
  241. newRoot: '$doc',
  242. },
  243. },
  244. ];
  245. const vectorStoreRelations = await VectorStoreFileRelationModel.aggregate<VectorStoreDocument>(pipeline);
  246. return vectorStoreRelations;
  247. }
  248. private async createVectorStore(name: string): Promise<VectorStoreDocument> {
  249. try {
  250. const newVectorStore = await this.client.createVectorStore(name);
  251. const newVectorStoreDocument = await VectorStoreModel.create({
  252. vectorStoreId: newVectorStore.id,
  253. }) as VectorStoreDocument;
  254. return newVectorStoreDocument;
  255. }
  256. catch (err) {
  257. throw new Error(err);
  258. }
  259. }
  260. private async uploadFile(pageId: Types.ObjectId, pagePath: string, revisionBody: string): Promise<OpenAI.Files.FileObject> {
  261. const convertedHtml = await convertMarkdownToHtml({ pagePath, revisionBody });
  262. const file = await toFile(Readable.from(convertedHtml), `${pageId}.html`);
  263. const uploadedFile = await this.client.uploadFile(file);
  264. return uploadedFile;
  265. }
  266. async deleteVectorStore(vectorStoreRelationId: string): Promise<void> {
  267. const vectorStoreDocument: VectorStoreDocument | null = await VectorStoreModel.findOne({ _id: vectorStoreRelationId, isDeleted: false });
  268. if (vectorStoreDocument == null) {
  269. return;
  270. }
  271. try {
  272. const deleteVectorStoreResponse = await this.client.deleteVectorStore(vectorStoreDocument.vectorStoreId);
  273. logger.debug('Delete vector store', deleteVectorStoreResponse);
  274. await vectorStoreDocument.markAsDeleted();
  275. }
  276. catch (err) {
  277. await openaiApiErrorHandler(err, { notFoundError: vectorStoreDocument.markAsDeleted });
  278. throw new Error(err);
  279. }
  280. }
  281. async createVectorStoreFile(vectorStoreRelation: VectorStoreDocument, pages: Array<HydratedDocument<PageDocument>>): Promise<void> {
  282. // const vectorStore = await this.getOrCreateVectorStoreForPublicScope();
  283. const vectorStoreFileRelationsMap: VectorStoreFileRelationsMap = new Map();
  284. const processUploadFile = async(page: HydratedDocument<PageDocument>) => {
  285. if (page._id != null && page.revision != null) {
  286. if (isPopulated(page.revision) && page.revision.body.length > 0) {
  287. const uploadedFile = await this.uploadFile(page._id, page.path, page.revision.body);
  288. prepareVectorStoreFileRelations(vectorStoreRelation._id, page._id, uploadedFile.id, vectorStoreFileRelationsMap);
  289. return;
  290. }
  291. const pagePopulatedToShowRevision = await page.populateDataToShowRevision();
  292. if (pagePopulatedToShowRevision.revision != null && pagePopulatedToShowRevision.revision.body.length > 0) {
  293. const uploadedFile = await this.uploadFile(page._id, page.path, pagePopulatedToShowRevision.revision.body);
  294. prepareVectorStoreFileRelations(vectorStoreRelation._id, page._id, uploadedFile.id, vectorStoreFileRelationsMap);
  295. }
  296. }
  297. };
  298. // Start workers to process results
  299. const workers = pages.map(processUploadFile);
  300. // Wait for all processing to complete.
  301. assert(workers.length <= BATCH_SIZE, 'workers.length must be less than or equal to BATCH_SIZE');
  302. const fileUploadResult = await Promise.allSettled(workers);
  303. fileUploadResult.forEach((result) => {
  304. if (result.status === 'rejected') {
  305. logger.error(result.reason);
  306. }
  307. });
  308. const vectorStoreFileRelations = Array.from(vectorStoreFileRelationsMap.values());
  309. const uploadedFileIds = vectorStoreFileRelations.map(data => data.fileIds).flat();
  310. if (uploadedFileIds.length === 0) {
  311. return;
  312. }
  313. const pageIds = pages.map(page => page._id);
  314. try {
  315. // Save vector store file relation
  316. await VectorStoreFileRelationModel.upsertVectorStoreFileRelations(vectorStoreFileRelations);
  317. // Create vector store file
  318. const createVectorStoreFileBatchResponse = await this.client.createVectorStoreFileBatch(vectorStoreRelation.vectorStoreId, uploadedFileIds);
  319. logger.debug('Create vector store file', createVectorStoreFileBatchResponse);
  320. // Set isAttachedToVectorStore: true when the uploaded file is attached to VectorStore
  321. await VectorStoreFileRelationModel.markAsAttachedToVectorStore(pageIds);
  322. }
  323. catch (err) {
  324. logger.error(err);
  325. // Delete all uploaded files if createVectorStoreFileBatch fails
  326. for await (const pageId of pageIds) {
  327. await this.deleteVectorStoreFile(vectorStoreRelation._id, pageId);
  328. }
  329. }
  330. }
  331. // Deletes all VectorStore documents that are marked as deleted (isDeleted: true) and have no associated VectorStoreFileRelation documents
  332. async deleteObsoletedVectorStoreRelations(): Promise<void> {
  333. const deletedVectorStoreRelations = await VectorStoreModel.find({ isDeleted: true });
  334. if (deletedVectorStoreRelations.length === 0) {
  335. return;
  336. }
  337. const currentVectorStoreRelationIds: Types.ObjectId[] = await VectorStoreFileRelationModel.aggregate([
  338. {
  339. $group: {
  340. _id: '$vectorStoreRelationId',
  341. relationCount: { $sum: 1 },
  342. },
  343. },
  344. { $match: { relationCount: { $gt: 0 } } },
  345. { $project: { _id: 1 } },
  346. ]);
  347. if (currentVectorStoreRelationIds.length === 0) {
  348. return;
  349. }
  350. await VectorStoreModel.deleteMany({ _id: { $nin: currentVectorStoreRelationIds }, isDeleted: true });
  351. }
  352. async deleteVectorStoreFile(vectorStoreRelationId: Types.ObjectId, pageId: Types.ObjectId, apiCallInterval?: number): Promise<void> {
  353. // Delete vector store file and delete vector store file relation
  354. const vectorStoreFileRelation = await VectorStoreFileRelationModel.findOne({ vectorStoreRelationId, page: pageId });
  355. if (vectorStoreFileRelation == null) {
  356. return;
  357. }
  358. const deletedFileIds: string[] = [];
  359. for await (const fileId of vectorStoreFileRelation.fileIds) {
  360. try {
  361. const deleteFileResponse = await this.client.deleteFile(fileId);
  362. logger.debug('Delete vector store file', deleteFileResponse);
  363. deletedFileIds.push(fileId);
  364. if (apiCallInterval != null) {
  365. // sleep
  366. await new Promise(resolve => setTimeout(resolve, apiCallInterval));
  367. }
  368. }
  369. catch (err) {
  370. await openaiApiErrorHandler(err, { notFoundError: async() => { deletedFileIds.push(fileId) } });
  371. logger.error(err);
  372. }
  373. }
  374. const undeletedFileIds = vectorStoreFileRelation.fileIds.filter(fileId => !deletedFileIds.includes(fileId));
  375. if (undeletedFileIds.length === 0) {
  376. await vectorStoreFileRelation.remove();
  377. return;
  378. }
  379. vectorStoreFileRelation.fileIds = undeletedFileIds;
  380. await vectorStoreFileRelation.save();
  381. }
  382. async deleteVectorStoreFilesByPageIds(pageIds: Types.ObjectId[]): Promise<void> {
  383. const vectorStoreRelations = await this.getVectorStoreRelationsByPageIds(pageIds);
  384. if (vectorStoreRelations != null && vectorStoreRelations.length !== 0) {
  385. for await (const pageId of pageIds) {
  386. const deleteVectorStoreFilePromises = vectorStoreRelations.map(vectorStoreRelation => this.deleteVectorStoreFile(vectorStoreRelation._id, pageId));
  387. await Promise.allSettled(deleteVectorStoreFilePromises);
  388. }
  389. }
  390. }
  391. async deleteObsoleteVectorStoreFile(limit: number, apiCallInterval: number): Promise<void> {
  392. // Retrieves all VectorStore documents that are marked as deleted
  393. const deletedVectorStoreRelations = await VectorStoreModel.find({ isDeleted: true });
  394. if (deletedVectorStoreRelations.length === 0) {
  395. return;
  396. }
  397. // Retrieves VectorStoreFileRelation documents associated with deleted VectorStore documents
  398. const obsoleteVectorStoreFileRelations = await VectorStoreFileRelationModel.find(
  399. { vectorStoreRelationId: { $in: deletedVectorStoreRelations.map(deletedVectorStoreRelation => deletedVectorStoreRelation._id) } },
  400. ).limit(limit);
  401. if (obsoleteVectorStoreFileRelations.length === 0) {
  402. return;
  403. }
  404. // Delete obsolete VectorStoreFile
  405. for await (const vectorStoreFileRelation of obsoleteVectorStoreFileRelations) {
  406. try {
  407. await this.deleteVectorStoreFile(vectorStoreFileRelation.vectorStoreRelationId, vectorStoreFileRelation.page, apiCallInterval);
  408. }
  409. catch (err) {
  410. logger.error(err);
  411. }
  412. }
  413. }
  414. async filterPagesByAccessScope(aiAssistant: AiAssistantDocument, pages: HydratedDocument<PageDocument>[]) {
  415. const isPublicPage = (page :HydratedDocument<PageDocument>) => page.grant === PageGrant.GRANT_PUBLIC;
  416. const isUserGroupAccessible = (page :HydratedDocument<PageDocument>, ownerUserGroupIds: string[]) => {
  417. if (page.grant !== PageGrant.GRANT_USER_GROUP) return false;
  418. return page.grantedGroups.some(group => ownerUserGroupIds.includes(getIdStringForRef(group.item)));
  419. };
  420. const isOwnerAccessible = (page: HydratedDocument<PageDocument>, ownerId: Ref<IUser>) => {
  421. if (page.grant !== PageGrant.GRANT_OWNER) return false;
  422. return page.grantedUsers.some(user => getIdStringForRef(user) === getIdStringForRef(ownerId));
  423. };
  424. const getOwnerUserGroupIds = async(owner: Ref<IUser>) => {
  425. const userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(owner);
  426. const externalGroups = await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(owner);
  427. return [...userGroups, ...externalGroups].map(group => getIdStringForRef(group));
  428. };
  429. switch (aiAssistant.accessScope) {
  430. case AiAssistantAccessScope.PUBLIC_ONLY:
  431. return pages.filter(isPublicPage);
  432. case AiAssistantAccessScope.GROUPS: {
  433. const ownerUserGroupIds = await getOwnerUserGroupIds(aiAssistant.owner);
  434. return pages.filter(page => isPublicPage(page) || isUserGroupAccessible(page, ownerUserGroupIds));
  435. }
  436. case AiAssistantAccessScope.OWNER: {
  437. const ownerUserGroupIds = await getOwnerUserGroupIds(aiAssistant.owner);
  438. return pages.filter(page => isPublicPage(page) || isOwnerAccessible(page, aiAssistant.owner) || isUserGroupAccessible(page, ownerUserGroupIds));
  439. }
  440. default:
  441. return [];
  442. }
  443. }
  444. async createVectorStoreFileOnPageCreate(pages: HydratedDocument<PageDocument>[]): Promise<void> {
  445. const pagePaths = pages.map(page => page.path);
  446. const aiAssistants = await this.findAiAssistantByPagePath(pagePaths, { shouldPopulateOwner: true, shouldPopulateVectorStore: true });
  447. if (aiAssistants.length === 0) {
  448. return;
  449. }
  450. for await (const aiAssistant of aiAssistants) {
  451. if (!isPopulated(aiAssistant.owner)) {
  452. continue;
  453. }
  454. const isLearnablePageLimitExceeded = await this.isLearnablePageLimitExceeded(aiAssistant.owner, aiAssistant.pagePathPatterns);
  455. if (isLearnablePageLimitExceeded) {
  456. continue;
  457. }
  458. const pagesToVectorize = await this.filterPagesByAccessScope(aiAssistant, pages);
  459. const vectorStoreRelation = aiAssistant.vectorStore;
  460. if (vectorStoreRelation == null || !isPopulated(vectorStoreRelation)) {
  461. continue;
  462. }
  463. logger.debug('--------- createVectorStoreFileOnPageCreate ---------');
  464. logger.debug('AccessScopeType of aiAssistant: ', aiAssistant.accessScope);
  465. logger.debug('VectorStoreFile pagePath to be created: ', pagesToVectorize.map(page => page.path));
  466. logger.debug('-----------------------------------------------------');
  467. await this.createVectorStoreFile(vectorStoreRelation as VectorStoreDocument, pagesToVectorize);
  468. }
  469. }
  470. async updateVectorStoreFileOnPageUpdate(page: HydratedDocument<PageDocument>) {
  471. const aiAssistants = await this.findAiAssistantByPagePath([page.path], { shouldPopulateVectorStore: true });
  472. if (aiAssistants.length === 0) {
  473. return;
  474. }
  475. for await (const aiAssistant of aiAssistants) {
  476. const pagesToVectorize = await this.filterPagesByAccessScope(aiAssistant, [page]);
  477. const vectorStoreRelation = aiAssistant.vectorStore;
  478. if (vectorStoreRelation == null || !isPopulated(vectorStoreRelation)) {
  479. continue;
  480. }
  481. logger.debug('---------- updateVectorStoreOnPageUpdate ------------');
  482. logger.debug('AccessScopeType of aiAssistant: ', aiAssistant.accessScope);
  483. logger.debug('PagePath of VectorStoreFile to be deleted: ', page.path);
  484. logger.debug('pagePath of VectorStoreFile to be created: ', pagesToVectorize.map(page => page.path));
  485. logger.debug('-----------------------------------------------------');
  486. // Do not create a new VectorStoreFile if page is changed to a permission that AiAssistant does not have access to
  487. await this.createVectorStoreFile(vectorStoreRelation as VectorStoreDocument, pagesToVectorize);
  488. await this.deleteVectorStoreFile((vectorStoreRelation as VectorStoreDocument)._id, page._id);
  489. }
  490. }
  491. private async createVectorStoreFileWithStream(vectorStoreRelation: VectorStoreDocument, conditions: mongoose.FilterQuery<PageDocument>): Promise<void> {
  492. const Page = mongoose.model<HydratedDocument<PageDocument>, PageModel>('Page');
  493. const pagesStream = Page.find({ ...conditions })
  494. .populate('revision')
  495. .cursor({ batchSize: BATCH_SIZE });
  496. const batchStream = createBatchStream(BATCH_SIZE);
  497. const createVectorStoreFile = this.createVectorStoreFile.bind(this);
  498. const createVectorStoreFileStream = new Transform({
  499. objectMode: true,
  500. async transform(chunk: HydratedDocument<PageDocument>[], encoding, callback) {
  501. try {
  502. logger.debug('Search results of page paths', chunk.map(page => page.path));
  503. await createVectorStoreFile(vectorStoreRelation, chunk);
  504. this.push(chunk);
  505. callback();
  506. }
  507. catch (error) {
  508. callback(error);
  509. }
  510. },
  511. });
  512. await pipeline(pagesStream, batchStream, createVectorStoreFileStream);
  513. }
  514. private async createConditionForCreateVectorStoreFile(
  515. owner: AiAssistant['owner'],
  516. accessScope: AiAssistant['accessScope'],
  517. grantedGroupsForAccessScope: AiAssistant['grantedGroupsForAccessScope'],
  518. pagePathPatterns: AiAssistant['pagePathPatterns'],
  519. ): Promise<mongoose.FilterQuery<PageDocument>> {
  520. const convertedPagePathPatterns = convertPathPatternsToRegExp(pagePathPatterns);
  521. // Include pages in search targets when their paths with 'Anyone with the link' permission are directly specified instead of using glob pattern
  522. const nonGrabPagePathPatterns = pagePathPatterns.filter(pagePathPattern => !isGlobPatternPath(pagePathPattern));
  523. const baseCondition: mongoose.FilterQuery<PageDocument> = {
  524. grant: PageGrant.GRANT_RESTRICTED,
  525. path: { $in: nonGrabPagePathPatterns },
  526. };
  527. if (accessScope === AiAssistantAccessScope.PUBLIC_ONLY) {
  528. return {
  529. $or: [
  530. baseCondition,
  531. {
  532. grant: PageGrant.GRANT_PUBLIC,
  533. path: { $in: convertedPagePathPatterns },
  534. },
  535. ],
  536. };
  537. }
  538. if (accessScope === AiAssistantAccessScope.GROUPS) {
  539. if (grantedGroupsForAccessScope == null || grantedGroupsForAccessScope.length === 0) {
  540. throw new Error('grantedGroups is required when accessScope is GROUPS');
  541. }
  542. const extractedGrantedGroupIdsForAccessScope = grantedGroupsForAccessScope.map(group => getIdForRef(group.item).toString());
  543. return {
  544. $or: [
  545. baseCondition,
  546. {
  547. grant: { $in: [PageGrant.GRANT_PUBLIC, PageGrant.GRANT_USER_GROUP] },
  548. path: { $in: convertedPagePathPatterns },
  549. $or: [
  550. { 'grantedGroups.item': { $in: extractedGrantedGroupIdsForAccessScope } },
  551. { grant: PageGrant.GRANT_PUBLIC },
  552. ],
  553. },
  554. ],
  555. };
  556. }
  557. if (accessScope === AiAssistantAccessScope.OWNER) {
  558. const ownerUserGroups = [
  559. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(owner)),
  560. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(owner)),
  561. ].map(group => group.toString());
  562. return {
  563. $or: [
  564. baseCondition,
  565. {
  566. grant: { $in: [PageGrant.GRANT_PUBLIC, PageGrant.GRANT_USER_GROUP, PageGrant.GRANT_OWNER] },
  567. path: { $in: convertedPagePathPatterns },
  568. $or: [
  569. { 'grantedGroups.item': { $in: ownerUserGroups } },
  570. { grantedUsers: { $in: [getIdForRef(owner)] } },
  571. { grant: PageGrant.GRANT_PUBLIC },
  572. ],
  573. },
  574. ],
  575. };
  576. }
  577. throw new Error('Invalid accessScope value');
  578. }
  579. private async validateGrantedUserGroupsForAiAssistant(
  580. owner: AiAssistant['owner'],
  581. shareScope: AiAssistant['shareScope'],
  582. accessScope: AiAssistant['accessScope'],
  583. grantedGroupsForShareScope: AiAssistant['grantedGroupsForShareScope'],
  584. grantedGroupsForAccessScope: AiAssistant['grantedGroupsForAccessScope'],
  585. ) {
  586. // Check if grantedGroupsForShareScope is not specified when shareScope is not a “group”
  587. if (shareScope !== AiAssistantShareScope.GROUPS && grantedGroupsForShareScope != null) {
  588. throw new Error('grantedGroupsForShareScope is specified when shareScope is not “groups”.');
  589. }
  590. // Check if grantedGroupsForAccessScope is not specified when accessScope is not a “group”
  591. if (accessScope !== AiAssistantAccessScope.GROUPS && grantedGroupsForAccessScope != null) {
  592. throw new Error('grantedGroupsForAccessScope is specified when accsessScope is not “groups”.');
  593. }
  594. const ownerUserGroupIds = [
  595. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(owner)),
  596. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(owner)),
  597. ].map(group => group.toString());
  598. // Check if the owner belongs to the group specified in grantedGroupsForShareScope
  599. if (grantedGroupsForShareScope != null && grantedGroupsForShareScope.length > 0) {
  600. const extractedGrantedGroupIdsForShareScope = grantedGroupsForShareScope.map(group => getIdForRef(group.item).toString());
  601. const isValid = extractedGrantedGroupIdsForShareScope.every(groupId => ownerUserGroupIds.includes(groupId));
  602. if (!isValid) {
  603. throw new Error('A userGroup to which the owner does not belong is specified in grantedGroupsForShareScope');
  604. }
  605. }
  606. // Check if the owner belongs to the group specified in grantedGroupsForAccessScope
  607. if (grantedGroupsForAccessScope != null && grantedGroupsForAccessScope.length > 0) {
  608. const extractedGrantedGroupIdsForAccessScope = grantedGroupsForAccessScope.map(group => getIdForRef(group.item).toString());
  609. const isValid = extractedGrantedGroupIdsForAccessScope.every(groupId => ownerUserGroupIds.includes(groupId));
  610. if (!isValid) {
  611. throw new Error('A userGroup to which the owner does not belong is specified in grantedGroupsForAccessScope');
  612. }
  613. }
  614. }
  615. async isAiAssistantUsable(aiAssistantId: string, user: IUserHasId): Promise<boolean> {
  616. const aiAssistant = await AiAssistantModel.findOne({ _id: { $eq: aiAssistantId } });
  617. if (aiAssistant == null) {
  618. throw createError(404, 'AiAssistant document does not exist');
  619. }
  620. const isOwner = getIdStringForRef(aiAssistant.owner) === getIdStringForRef(user._id);
  621. if (aiAssistant.shareScope === AiAssistantShareScope.PUBLIC_ONLY) {
  622. return true;
  623. }
  624. if ((aiAssistant.shareScope === AiAssistantShareScope.OWNER) && isOwner) {
  625. return true;
  626. }
  627. if ((aiAssistant.shareScope === AiAssistantShareScope.SAME_AS_ACCESS_SCOPE) && (aiAssistant.accessScope === AiAssistantAccessScope.OWNER) && isOwner) {
  628. return true;
  629. }
  630. if ((aiAssistant.shareScope === AiAssistantShareScope.GROUPS)
  631. || ((aiAssistant.shareScope === AiAssistantShareScope.SAME_AS_ACCESS_SCOPE) && (aiAssistant.accessScope === AiAssistantAccessScope.GROUPS))) {
  632. const userGroupIds = [
  633. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  634. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  635. ].map(group => group.toString());
  636. const grantedGroupIdsForShareScope = aiAssistant.grantedGroupsForShareScope?.map(group => getIdStringForRef(group.item)) ?? [];
  637. const isShared = userGroupIds.some(userGroupId => grantedGroupIdsForShareScope.includes(userGroupId));
  638. return isShared;
  639. }
  640. return false;
  641. }
  642. async createAiAssistant(data: UpsertAiAssistantData, user: IUserHasId): Promise<AiAssistantDocument> {
  643. await this.validateGrantedUserGroupsForAiAssistant(
  644. user,
  645. data.shareScope,
  646. data.accessScope,
  647. data.grantedGroupsForShareScope,
  648. data.grantedGroupsForAccessScope,
  649. );
  650. const conditions = await this.createConditionForCreateVectorStoreFile(
  651. user,
  652. data.accessScope,
  653. data.grantedGroupsForAccessScope,
  654. data.pagePathPatterns,
  655. );
  656. const vectorStoreRelation = await this.createVectorStore(data.name);
  657. const aiAssistant = await AiAssistantModel.create({
  658. ...data, owner: user, vectorStore: vectorStoreRelation,
  659. });
  660. // VectorStore creation process does not await
  661. this.createVectorStoreFileWithStream(vectorStoreRelation, conditions);
  662. return aiAssistant;
  663. }
  664. async updateAiAssistant(aiAssistantId: string, data: UpsertAiAssistantData, user: IUserHasId): Promise<AiAssistantDocument> {
  665. const aiAssistant = await AiAssistantModel.findOne({ owner: user, _id: aiAssistantId });
  666. if (aiAssistant == null) {
  667. throw createError(404, 'AiAssistant document does not exist');
  668. }
  669. await this.validateGrantedUserGroupsForAiAssistant(
  670. user,
  671. data.shareScope,
  672. data.accessScope,
  673. data.grantedGroupsForShareScope,
  674. data.grantedGroupsForAccessScope,
  675. );
  676. const grantedGroupIdsForAccessScopeFromReq = data.grantedGroupsForAccessScope?.map(group => getIdStringForRef(group.item)) ?? []; // ObjectId[] -> string[]
  677. const grantedGroupIdsForAccessScopeFromDb = aiAssistant.grantedGroupsForAccessScope?.map(group => getIdStringForRef(group.item)) ?? []; // ObjectId[] -> string[]
  678. // If accessScope, pagePathPatterns, grantedGroupsForAccessScope have not changed, do not build VectorStore
  679. const shouldRebuildVectorStore = data.accessScope !== aiAssistant.accessScope
  680. || !isDeepEquals(data.pagePathPatterns, aiAssistant.pagePathPatterns)
  681. || !isDeepEquals(grantedGroupIdsForAccessScopeFromReq, grantedGroupIdsForAccessScopeFromDb);
  682. let newVectorStoreRelation: VectorStoreDocument | undefined;
  683. if (shouldRebuildVectorStore) {
  684. const conditions = await this.createConditionForCreateVectorStoreFile(
  685. user,
  686. data.accessScope,
  687. data.grantedGroupsForAccessScope,
  688. data.pagePathPatterns,
  689. );
  690. // Delete obsoleted VectorStore
  691. const obsoletedVectorStoreRelationId = getIdStringForRef(aiAssistant.vectorStore);
  692. await this.deleteVectorStore(obsoletedVectorStoreRelationId);
  693. newVectorStoreRelation = await this.createVectorStore(data.name);
  694. this.updateThreads(aiAssistantId, newVectorStoreRelation.vectorStoreId);
  695. // VectorStore creation process does not await
  696. this.createVectorStoreFileWithStream(newVectorStoreRelation, conditions);
  697. }
  698. const newData = {
  699. ...data,
  700. vectorStore: newVectorStoreRelation ?? aiAssistant.vectorStore,
  701. };
  702. aiAssistant.set({ ...newData });
  703. let updatedAiAssistant: AiAssistantDocument = await aiAssistant.save();
  704. if (data.shareScope !== AiAssistantShareScope.PUBLIC_ONLY && aiAssistant.isDefault) {
  705. updatedAiAssistant = await AiAssistantModel.setDefault(aiAssistant._id, false);
  706. }
  707. return updatedAiAssistant;
  708. }
  709. async getAccessibleAiAssistants(user: IUserHasId): Promise<AccessibleAiAssistants> {
  710. const userGroupIds = [
  711. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  712. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  713. ];
  714. const assistants = await AiAssistantModel.find({
  715. $or: [
  716. // Case 1: Assistants owned by the user
  717. { owner: user },
  718. // Case 2: Public assistants owned by others
  719. {
  720. $and: [
  721. { owner: { $ne: user } },
  722. { shareScope: AiAssistantShareScope.PUBLIC_ONLY },
  723. ],
  724. },
  725. // Case 3: Group-restricted assistants where user is in granted groups
  726. {
  727. $and: [
  728. { owner: { $ne: user } },
  729. { shareScope: AiAssistantShareScope.GROUPS },
  730. { 'grantedGroupsForShareScope.item': { $in: userGroupIds } },
  731. ],
  732. },
  733. ],
  734. })
  735. .populate('grantedGroupsForShareScope.item')
  736. .populate('grantedGroupsForAccessScope.item');
  737. return {
  738. myAiAssistants: assistants.filter(assistant => assistant.owner.toString() === user._id.toString()) ?? [],
  739. teamAiAssistants: assistants.filter(assistant => assistant.owner.toString() !== user._id.toString()) ?? [],
  740. };
  741. }
  742. async isLearnablePageLimitExceeded(user: IUserHasId, pagePathPatterns: string[]): Promise<boolean> {
  743. const normalizedPagePathPatterns = removeGlobPath(pagePathPatterns);
  744. const PageModel = mongoose.model<IPage, PageModel>('Page');
  745. const pagePathsWithDescendantCount = await PageModel.descendantCountByPaths(normalizedPagePathPatterns, user, null, true, true);
  746. const totalPageCount = pagePathsWithDescendantCount.reduce((total, pagePathWithDescendantCount) => {
  747. const descendantCount = pagePathPatterns.includes(pagePathWithDescendantCount.path)
  748. ? 0 // Treat as single page when included in "pagePathPatterns"
  749. : pagePathWithDescendantCount.descendantCount;
  750. const pageCount = descendantCount + 1;
  751. return total + pageCount;
  752. }, 0);
  753. logger.debug('TotalPageCount: ', totalPageCount);
  754. const limitLearnablePageCountPerAssistant = configManager.getConfig('openai:limitLearnablePageCountPerAssistant');
  755. return totalPageCount > limitLearnablePageCountPerAssistant;
  756. }
  757. async findAiAssistantByPagePath(
  758. pagePaths: string[], options?: { shouldPopulateOwner?: boolean, shouldPopulateVectorStore?: boolean },
  759. ): Promise<AiAssistantDocument[]> {
  760. const pagePathsWithGlobPattern = pagePaths.map(pagePath => generateGlobPatterns(pagePath)).flat();
  761. const query = AiAssistantModel.find({
  762. $or: [
  763. // Case 1: Exact match
  764. { pagePathPatterns: { $in: pagePaths } },
  765. // Case 2: Glob pattern match
  766. { pagePathPatterns: { $in: pagePathsWithGlobPattern } },
  767. ],
  768. });
  769. if (options?.shouldPopulateOwner) {
  770. query.populate('owner');
  771. }
  772. if (options?.shouldPopulateVectorStore) {
  773. query.populate('vectorStore');
  774. }
  775. const aiAssistants = await query.exec();
  776. return aiAssistants;
  777. }
  778. }
  779. let instance: OpenaiService;
  780. export const getOpenaiService = (): IOpenaiService | undefined => {
  781. if (instance != null) {
  782. return instance;
  783. }
  784. const aiEnabled = configManager.getConfig('app:aiEnabled');
  785. const openaiServiceType = configManager.getConfig('openai:serviceType');
  786. if (aiEnabled && openaiServiceType != null && OpenaiServiceTypes.includes(openaiServiceType)) {
  787. instance = new OpenaiService();
  788. return instance;
  789. }
  790. return;
  791. };