openai.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. import assert from 'node:assert';
  2. import { Readable, Transform } from 'stream';
  3. import { pipeline } from 'stream/promises';
  4. import {
  5. PageGrant, getIdForRef, getIdStringForRef, isPopulated, type IUserHasId,
  6. } from '@growi/core';
  7. import { isGrobPatternPath } from '@growi/core/dist/utils/page-path-utils';
  8. import escapeStringRegexp from 'escape-string-regexp';
  9. import mongoose, { type HydratedDocument, type Types } from 'mongoose';
  10. import { type OpenAI, toFile } from 'openai';
  11. import ExternalUserGroupRelation from '~/features/external-user-group/server/models/external-user-group-relation';
  12. import ThreadRelationModel from '~/features/openai/server/models/thread-relation';
  13. import VectorStoreModel, { type VectorStoreDocument } from '~/features/openai/server/models/vector-store';
  14. import VectorStoreFileRelationModel, {
  15. type VectorStoreFileRelation,
  16. prepareVectorStoreFileRelations,
  17. } from '~/features/openai/server/models/vector-store-file-relation';
  18. import type { PageDocument, PageModel } from '~/server/models/page';
  19. import UserGroupRelation from '~/server/models/user-group-relation';
  20. import { configManager } from '~/server/service/config-manager';
  21. import { createBatchStream } from '~/server/util/batch-stream';
  22. import loggerFactory from '~/utils/logger';
  23. import { OpenaiServiceTypes } from '../../interfaces/ai';
  24. import type { AiAssistantUpdateData } from '../../interfaces/ai-assistant';
  25. import {
  26. type AccessibleAiAssistants, type AiAssistant, AiAssistantAccessScope, AiAssistantShareScope,
  27. } from '../../interfaces/ai-assistant';
  28. import AiAssistantModel, { type AiAssistantDocument } from '../models/ai-assistant';
  29. import { convertMarkdownToHtml } from '../utils/convert-markdown-to-html';
  30. import { getClient } from './client-delegator';
  31. // import { splitMarkdownIntoChunks } from './markdown-splitter/markdown-token-splitter';
  32. import { openaiApiErrorHandler } from './openai-api-error-handler';
  33. const BATCH_SIZE = 100;
  34. const logger = loggerFactory('growi:service:openai');
  35. // const isVectorStoreForPublicScopeExist = false;
  36. type VectorStoreFileRelationsMap = Map<string, VectorStoreFileRelation>
  37. const convertPathPatternsToRegExp = (pagePathPatterns: string[]): Array<string | RegExp> => {
  38. return pagePathPatterns.map((pagePathPattern) => {
  39. if (isGrobPatternPath(pagePathPattern)) {
  40. const trimedPagePathPattern = pagePathPattern.replace('/*', '');
  41. const escapedPagePathPattern = escapeStringRegexp(trimedPagePathPattern);
  42. return new RegExp(`^${escapedPagePathPattern}`);
  43. }
  44. return pagePathPattern;
  45. });
  46. };
  47. export interface IOpenaiService {
  48. getOrCreateThread(userId: string, vectorStoreId?: string, threadId?: string): Promise<OpenAI.Beta.Threads.Thread | undefined>;
  49. // getOrCreateVectorStoreForPublicScope(): Promise<VectorStoreDocument>;
  50. deleteExpiredThreads(limit: number, apiCallInterval: number): Promise<void>; // for CronJob
  51. deleteObsolatedVectorStoreRelations(): Promise<void> // for CronJob
  52. createVectorStoreFile(vectorStoreRelation: VectorStoreDocument, pages: PageDocument[]): Promise<void>;
  53. deleteVectorStoreFile(vectorStoreRelationId: Types.ObjectId, pageId: Types.ObjectId): Promise<void>;
  54. deleteObsoleteVectorStoreFile(limit: number, apiCallInterval: number): Promise<void>; // for CronJob
  55. // rebuildVectorStoreAll(): Promise<void>;
  56. // rebuildVectorStore(page: HydratedDocument<PageDocument>): Promise<void>;
  57. createAiAssistant(data: Omit<AiAssistant, 'vectorStore'>): Promise<AiAssistantDocument>;
  58. updateAiAssistant(ownerId: string, aiAssistantId: string, data: AiAssistantUpdateData): Promise<AiAssistantDocument>;
  59. getAccessibleAiAssistants(user: IUserHasId): Promise<AccessibleAiAssistants>
  60. deleteAiAssistant(ownerId: string, aiAssistantId: string): Promise<AiAssistantDocument>
  61. }
  62. class OpenaiService implements IOpenaiService {
  63. private get client() {
  64. const openaiServiceType = configManager.getConfig('openai:serviceType');
  65. return getClient({ openaiServiceType });
  66. }
  67. public async getOrCreateThread(userId: string, vectorStoreId?: string, threadId?: string): Promise<OpenAI.Beta.Threads.Thread> {
  68. if (vectorStoreId != null && threadId == null) {
  69. try {
  70. const thread = await this.client.createThread(vectorStoreId);
  71. await ThreadRelationModel.create({ userId, threadId: thread.id });
  72. return thread;
  73. }
  74. catch (err) {
  75. throw new Error(err);
  76. }
  77. }
  78. const threadRelation = await ThreadRelationModel.findOne({ threadId });
  79. if (threadRelation == null) {
  80. throw new Error('ThreadRelation document is not exists');
  81. }
  82. // Check if a thread entity exists
  83. // If the thread entity does not exist, the thread-relation document is deleted
  84. try {
  85. const thread = await this.client.retrieveThread(threadRelation.threadId);
  86. // Update expiration date if thread entity exists
  87. await threadRelation.updateThreadExpiration();
  88. return thread;
  89. }
  90. catch (err) {
  91. await openaiApiErrorHandler(err, { notFoundError: async() => { await threadRelation.remove() } });
  92. throw new Error(err);
  93. }
  94. }
  95. public async deleteExpiredThreads(limit: number, apiCallInterval: number): Promise<void> {
  96. const expiredThreadRelations = await ThreadRelationModel.getExpiredThreadRelations(limit);
  97. if (expiredThreadRelations == null) {
  98. return;
  99. }
  100. const deletedThreadIds: string[] = [];
  101. for await (const expiredThreadRelation of expiredThreadRelations) {
  102. try {
  103. const deleteThreadResponse = await this.client.deleteThread(expiredThreadRelation.threadId);
  104. logger.debug('Delete thread', deleteThreadResponse);
  105. deletedThreadIds.push(expiredThreadRelation.threadId);
  106. // sleep
  107. await new Promise(resolve => setTimeout(resolve, apiCallInterval));
  108. }
  109. catch (err) {
  110. logger.error(err);
  111. }
  112. }
  113. await ThreadRelationModel.deleteMany({ threadId: { $in: deletedThreadIds } });
  114. }
  115. // TODO: https://redmine.weseek.co.jp/issues/160332
  116. // public async getOrCreateVectorStoreForPublicScope(): Promise<VectorStoreDocument> {
  117. // const vectorStoreDocument: VectorStoreDocument | null = await VectorStoreModel.findOne({ scopeType: VectorStoreScopeType.PUBLIC, isDeleted: false });
  118. // if (vectorStoreDocument != null && isVectorStoreForPublicScopeExist) {
  119. // return vectorStoreDocument;
  120. // }
  121. // if (vectorStoreDocument != null && !isVectorStoreForPublicScopeExist) {
  122. // try {
  123. // // Check if vector store entity exists
  124. // // If the vector store entity does not exist, the vector store document is deleted
  125. // await this.client.retrieveVectorStore(vectorStoreDocument.vectorStoreId);
  126. // isVectorStoreForPublicScopeExist = true;
  127. // return vectorStoreDocument;
  128. // }
  129. // catch (err) {
  130. // await oepnaiApiErrorHandler(err, { notFoundError: vectorStoreDocument.markAsDeleted });
  131. // throw new Error(err);
  132. // }
  133. // }
  134. // const newVectorStore = await this.client.createVectorStore(VectorStoreScopeType.PUBLIC);
  135. // const newVectorStoreDocument = await VectorStoreModel.create({
  136. // vectorStoreId: newVectorStore.id,
  137. // scopeType: VectorStoreScopeType.PUBLIC,
  138. // }) as VectorStoreDocument;
  139. // isVectorStoreForPublicScopeExist = true;
  140. // return newVectorStoreDocument;
  141. // }
  142. private async createVectorStore(name: string): Promise<VectorStoreDocument> {
  143. try {
  144. const newVectorStore = await this.client.createVectorStore(name);
  145. const newVectorStoreDocument = await VectorStoreModel.create({
  146. vectorStoreId: newVectorStore.id,
  147. }) as VectorStoreDocument;
  148. return newVectorStoreDocument;
  149. }
  150. catch (err) {
  151. throw new Error(err);
  152. }
  153. }
  154. // TODO: https://redmine.weseek.co.jp/issues/160332
  155. // TODO: https://redmine.weseek.co.jp/issues/156643
  156. // private async uploadFileByChunks(pageId: Types.ObjectId, body: string, vectorStoreFileRelationsMap: VectorStoreFileRelationsMap) {
  157. // const chunks = await splitMarkdownIntoChunks(body, 'gpt-4o');
  158. // for await (const [index, chunk] of chunks.entries()) {
  159. // try {
  160. // const file = await toFile(Readable.from(chunk), `${pageId}-chunk-${index}.md`);
  161. // const uploadedFile = await this.client.uploadFile(file);
  162. // prepareVectorStoreFileRelations(pageId, uploadedFile.id, vectorStoreFileRelationsMap);
  163. // }
  164. // catch (err) {
  165. // logger.error(err);
  166. // }
  167. // }
  168. // }
  169. private async uploadFile(pageId: Types.ObjectId, pagePath: string, revisionBody: string): Promise<OpenAI.Files.FileObject> {
  170. const convertedHtml = await convertMarkdownToHtml({ pagePath, revisionBody });
  171. const file = await toFile(Readable.from(convertedHtml), `${pageId}.html`);
  172. const uploadedFile = await this.client.uploadFile(file);
  173. return uploadedFile;
  174. }
  175. private async deleteVectorStore(vectorStoreRelationId: string): Promise<void> {
  176. const vectorStoreDocument: VectorStoreDocument | null = await VectorStoreModel.findOne({ _id: vectorStoreRelationId, isDeleted: false });
  177. if (vectorStoreDocument == null) {
  178. return;
  179. }
  180. try {
  181. await this.client.deleteVectorStore(vectorStoreDocument.vectorStoreId);
  182. await vectorStoreDocument.markAsDeleted();
  183. }
  184. catch (err) {
  185. await openaiApiErrorHandler(err, { notFoundError: vectorStoreDocument.markAsDeleted });
  186. throw new Error(err);
  187. }
  188. }
  189. async createVectorStoreFile(vectorStoreRelation: VectorStoreDocument, pages: Array<HydratedDocument<PageDocument>>): Promise<void> {
  190. // const vectorStore = await this.getOrCreateVectorStoreForPublicScope();
  191. const vectorStoreFileRelationsMap: VectorStoreFileRelationsMap = new Map();
  192. const processUploadFile = async(page: HydratedDocument<PageDocument>) => {
  193. if (page._id != null && page.grant === PageGrant.GRANT_PUBLIC && page.revision != null) {
  194. if (isPopulated(page.revision) && page.revision.body.length > 0) {
  195. const uploadedFile = await this.uploadFile(page._id, page.path, page.revision.body);
  196. prepareVectorStoreFileRelations(vectorStoreRelation._id, page._id, uploadedFile.id, vectorStoreFileRelationsMap);
  197. return;
  198. }
  199. const pagePopulatedToShowRevision = await page.populateDataToShowRevision();
  200. if (pagePopulatedToShowRevision.revision != null && pagePopulatedToShowRevision.revision.body.length > 0) {
  201. const uploadedFile = await this.uploadFile(page._id, page.path, pagePopulatedToShowRevision.revision.body);
  202. prepareVectorStoreFileRelations(vectorStoreRelation._id, page._id, uploadedFile.id, vectorStoreFileRelationsMap);
  203. }
  204. }
  205. };
  206. // Start workers to process results
  207. const workers = pages.map(processUploadFile);
  208. // Wait for all processing to complete.
  209. assert(workers.length <= BATCH_SIZE, 'workers.length must be less than or equal to BATCH_SIZE');
  210. const fileUploadResult = await Promise.allSettled(workers);
  211. fileUploadResult.forEach((result) => {
  212. if (result.status === 'rejected') {
  213. logger.error(result.reason);
  214. }
  215. });
  216. const vectorStoreFileRelations = Array.from(vectorStoreFileRelationsMap.values());
  217. const uploadedFileIds = vectorStoreFileRelations.map(data => data.fileIds).flat();
  218. if (uploadedFileIds.length === 0) {
  219. return;
  220. }
  221. const pageIds = pages.map(page => page._id);
  222. try {
  223. // Save vector store file relation
  224. await VectorStoreFileRelationModel.upsertVectorStoreFileRelations(vectorStoreFileRelations);
  225. // Create vector store file
  226. const createVectorStoreFileBatchResponse = await this.client.createVectorStoreFileBatch(vectorStoreRelation.vectorStoreId, uploadedFileIds);
  227. logger.debug('Create vector store file', createVectorStoreFileBatchResponse);
  228. // Set isAttachedToVectorStore: true when the uploaded file is attached to VectorStore
  229. await VectorStoreFileRelationModel.markAsAttachedToVectorStore(pageIds);
  230. }
  231. catch (err) {
  232. logger.error(err);
  233. // Delete all uploaded files if createVectorStoreFileBatch fails
  234. for await (const pageId of pageIds) {
  235. await this.deleteVectorStoreFile(vectorStoreRelation._id, pageId);
  236. }
  237. }
  238. }
  239. // Deletes all VectorStore documents that are marked as deleted (isDeleted: true) and have no associated VectorStoreFileRelation documents
  240. async deleteObsolatedVectorStoreRelations(): Promise<void> {
  241. const deletedVectorStoreRelations = await VectorStoreModel.find({ isDeleted: true });
  242. if (deletedVectorStoreRelations.length === 0) {
  243. return;
  244. }
  245. const currentVectorStoreRelationIds: Types.ObjectId[] = await VectorStoreFileRelationModel.aggregate([
  246. {
  247. $group: {
  248. _id: '$vectorStoreRelationId',
  249. relationCount: { $sum: 1 },
  250. },
  251. },
  252. { $match: { relationCount: { $gt: 0 } } },
  253. { $project: { _id: 1 } },
  254. ]);
  255. if (currentVectorStoreRelationIds.length === 0) {
  256. return;
  257. }
  258. await VectorStoreModel.deleteMany({ _id: { $nin: currentVectorStoreRelationIds }, isDeleted: true });
  259. }
  260. async deleteVectorStoreFile(vectorStoreRelationId: Types.ObjectId, pageId: Types.ObjectId, apiCallInterval?: number): Promise<void> {
  261. // Delete vector store file and delete vector store file relation
  262. const vectorStoreFileRelation = await VectorStoreFileRelationModel.findOne({ vectorStoreRelationId, page: pageId });
  263. if (vectorStoreFileRelation == null) {
  264. return;
  265. }
  266. const deletedFileIds: string[] = [];
  267. for await (const fileId of vectorStoreFileRelation.fileIds) {
  268. try {
  269. const deleteFileResponse = await this.client.deleteFile(fileId);
  270. logger.debug('Delete vector store file', deleteFileResponse);
  271. deletedFileIds.push(fileId);
  272. if (apiCallInterval != null) {
  273. // sleep
  274. await new Promise(resolve => setTimeout(resolve, apiCallInterval));
  275. }
  276. }
  277. catch (err) {
  278. await openaiApiErrorHandler(err, { notFoundError: async() => { deletedFileIds.push(fileId) } });
  279. logger.error(err);
  280. }
  281. }
  282. const undeletedFileIds = vectorStoreFileRelation.fileIds.filter(fileId => !deletedFileIds.includes(fileId));
  283. if (undeletedFileIds.length === 0) {
  284. await vectorStoreFileRelation.remove();
  285. return;
  286. }
  287. vectorStoreFileRelation.fileIds = undeletedFileIds;
  288. await vectorStoreFileRelation.save();
  289. }
  290. async deleteObsoleteVectorStoreFile(limit: number, apiCallInterval: number): Promise<void> {
  291. // Retrieves all VectorStore documents that are marked as deleted
  292. const deletedVectorStoreRelations = await VectorStoreModel.find({ isDeleted: true });
  293. if (deletedVectorStoreRelations.length === 0) {
  294. return;
  295. }
  296. // Retrieves VectorStoreFileRelation documents associated with deleted VectorStore documents
  297. const obsoleteVectorStoreFileRelations = await VectorStoreFileRelationModel.find(
  298. { vectorStoreRelationId: { $in: deletedVectorStoreRelations.map(deletedVectorStoreRelation => deletedVectorStoreRelation._id) } },
  299. ).limit(limit);
  300. if (obsoleteVectorStoreFileRelations.length === 0) {
  301. return;
  302. }
  303. // Delete obsolete VectorStoreFile
  304. for await (const vectorStoreFileRelation of obsoleteVectorStoreFileRelations) {
  305. try {
  306. await this.deleteVectorStoreFile(vectorStoreFileRelation.vectorStoreRelationId, vectorStoreFileRelation.page, apiCallInterval);
  307. }
  308. catch (err) {
  309. logger.error(err);
  310. }
  311. }
  312. }
  313. // TODO: https://redmine.weseek.co.jp/issues/160332
  314. // async rebuildVectorStoreAll() {
  315. // await this.deleteVectorStore(VectorStoreScopeType.PUBLIC);
  316. // // Create all public pages VectorStoreFile
  317. // const Page = mongoose.model<HydratedDocument<PageDocument>, PageModel>('Page');
  318. // const pagesStream = Page.find({ grant: PageGrant.GRANT_PUBLIC }).populate('revision').cursor({ batch_size: BATCH_SIZE });
  319. // const batchStrem = createBatchStream(BATCH_SIZE);
  320. // const createVectorStoreFile = this.createVectorStoreFile.bind(this);
  321. // const createVectorStoreFileStream = new Transform({
  322. // objectMode: true,
  323. // async transform(chunk: HydratedDocument<PageDocument>[], encoding, callback) {
  324. // await createVectorStoreFile(chunk);
  325. // this.push(chunk);
  326. // callback();
  327. // },
  328. // });
  329. // await pipeline(pagesStream, batchStrem, createVectorStoreFileStream);
  330. // }
  331. // async rebuildVectorStore(page: HydratedDocument<PageDocument>) {
  332. // const vectorStore = await this.getOrCreateVectorStoreForPublicScope();
  333. // await this.deleteVectorStoreFile(vectorStore._id, page._id);
  334. // await this.createVectorStoreFile([page]);
  335. // }
  336. private async createVectorStoreFileWithStream(vectorStoreRelation: VectorStoreDocument, conditions: mongoose.FilterQuery<PageDocument>): Promise<void> {
  337. const Page = mongoose.model<HydratedDocument<PageDocument>, PageModel>('Page');
  338. const pagesStream = Page.find({ ...conditions })
  339. .populate('revision')
  340. .cursor({ batchSize: BATCH_SIZE });
  341. const batchStream = createBatchStream(BATCH_SIZE);
  342. const createVectorStoreFile = this.createVectorStoreFile.bind(this);
  343. const createVectorStoreFileStream = new Transform({
  344. objectMode: true,
  345. async transform(chunk: HydratedDocument<PageDocument>[], encoding, callback) {
  346. try {
  347. logger.debug('Search results of page paths', chunk.map(page => page.path));
  348. await createVectorStoreFile(vectorStoreRelation, chunk);
  349. this.push(chunk);
  350. callback();
  351. }
  352. catch (error) {
  353. callback(error);
  354. }
  355. },
  356. });
  357. await pipeline(pagesStream, batchStream, createVectorStoreFileStream);
  358. }
  359. private async createConditionForCreateAiAssistant(
  360. owner: AiAssistant['owner'],
  361. accessScope: AiAssistant['accessScope'],
  362. grantedGroupsForAccessScope: AiAssistant['grantedGroupsForAccessScope'],
  363. pagePathPatterns: AiAssistant['pagePathPatterns'],
  364. ): Promise<mongoose.FilterQuery<PageDocument>> {
  365. const converterdPagePathPatterns = convertPathPatternsToRegExp(pagePathPatterns);
  366. // Include pages in search targets when their paths with 'Anyone with the link' permission are directly specified instead of using glob pattern
  367. const nonGrabPagePathPatterns = pagePathPatterns.filter(pagePathPattern => !isGrobPatternPath(pagePathPattern));
  368. const baseCondition: mongoose.FilterQuery<PageDocument> = {
  369. grant: PageGrant.GRANT_RESTRICTED,
  370. path: { $in: nonGrabPagePathPatterns },
  371. };
  372. if (accessScope === AiAssistantAccessScope.PUBLIC_ONLY) {
  373. return {
  374. $or: [
  375. baseCondition,
  376. {
  377. grant: PageGrant.GRANT_PUBLIC,
  378. path: { $in: converterdPagePathPatterns },
  379. },
  380. ],
  381. };
  382. }
  383. if (accessScope === AiAssistantAccessScope.GROUPS) {
  384. if (grantedGroupsForAccessScope == null || grantedGroupsForAccessScope.length === 0) {
  385. throw new Error('grantedGroups is required when accessScope is GROUPS');
  386. }
  387. const extractedGrantedGroupIdsForAccessScope = grantedGroupsForAccessScope.map(group => getIdForRef(group.item).toString());
  388. return {
  389. $or: [
  390. baseCondition,
  391. {
  392. grant: { $in: [PageGrant.GRANT_PUBLIC, PageGrant.GRANT_USER_GROUP] },
  393. path: { $in: converterdPagePathPatterns },
  394. $or: [
  395. { 'grantedGroups.item': { $in: extractedGrantedGroupIdsForAccessScope } },
  396. { grant: PageGrant.GRANT_PUBLIC },
  397. ],
  398. },
  399. ],
  400. };
  401. }
  402. if (accessScope === AiAssistantAccessScope.OWNER) {
  403. const ownerUserGroups = [
  404. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(owner)),
  405. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(owner)),
  406. ].map(group => group.toString());
  407. return {
  408. $or: [
  409. baseCondition,
  410. {
  411. grant: { $in: [PageGrant.GRANT_PUBLIC, PageGrant.GRANT_USER_GROUP, PageGrant.GRANT_OWNER] },
  412. path: { $in: converterdPagePathPatterns },
  413. $or: [
  414. { 'grantedGroups.item': { $in: ownerUserGroups } },
  415. { grantedUsers: { $in: [getIdForRef(owner)] } },
  416. { grant: PageGrant.GRANT_PUBLIC },
  417. ],
  418. },
  419. ],
  420. };
  421. }
  422. throw new Error('Invalid accessScope value');
  423. }
  424. private async validateGrantedUserGroupsForCreateAiAssistant(
  425. owner: AiAssistant['owner'],
  426. shareScope: AiAssistant['shareScope'],
  427. accessScope: AiAssistant['accessScope'],
  428. grantedGroupsForShareScope: AiAssistant['grantedGroupsForShareScope'],
  429. grantedGroupsForAccessScope: AiAssistant['grantedGroupsForAccessScope'],
  430. ) {
  431. // Check if grantedGroupsForShareScope is not specified when shareScope is not a “group”
  432. if (shareScope !== AiAssistantShareScope.GROUPS && grantedGroupsForShareScope != null) {
  433. throw new Error('grantedGroupsForShareScope is specified when shareScope is not “groups”.');
  434. }
  435. // Check if grantedGroupsForAccessScope is not specified when accessScope is not a “group”
  436. if (accessScope !== AiAssistantAccessScope.GROUPS && grantedGroupsForAccessScope != null) {
  437. throw new Error('grantedGroupsForAccessScope is specified when accsessScope is not “groups”.');
  438. }
  439. const ownerUserGroupIds = [
  440. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(owner)),
  441. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(owner)),
  442. ].map(group => group.toString());
  443. // Check if the owner belongs to the group specified in grantedGroupsForShareScope
  444. if (grantedGroupsForShareScope != null && grantedGroupsForShareScope.length > 0) {
  445. const extractedGrantedGroupIdsForShareScope = grantedGroupsForShareScope.map(group => getIdForRef(group.item).toString());
  446. const isValid = extractedGrantedGroupIdsForShareScope.every(groupId => ownerUserGroupIds.includes(groupId));
  447. if (!isValid) {
  448. throw new Error('A userGroup to which the owner does not belong is specified in grantedGroupsForShareScope');
  449. }
  450. }
  451. // Check if the owner belongs to the group specified in grantedGroupsForAccessScope
  452. if (grantedGroupsForAccessScope != null && grantedGroupsForAccessScope.length > 0) {
  453. const extractedGrantedGroupIdsForAccessScope = grantedGroupsForAccessScope.map(group => getIdForRef(group.item).toString());
  454. const isValid = extractedGrantedGroupIdsForAccessScope.every(groupId => ownerUserGroupIds.includes(groupId));
  455. if (!isValid) {
  456. throw new Error('A userGroup to which the owner does not belong is specified in grantedGroupsForAccessScope');
  457. }
  458. }
  459. }
  460. async createAiAssistant(data: Omit<AiAssistant, 'vectorStore'>): Promise<AiAssistantDocument> {
  461. await this.validateGrantedUserGroupsForCreateAiAssistant(
  462. data.owner,
  463. data.shareScope,
  464. data.accessScope,
  465. data.grantedGroupsForShareScope,
  466. data.grantedGroupsForAccessScope,
  467. );
  468. const conditions = await this.createConditionForCreateAiAssistant(
  469. data.owner,
  470. data.accessScope,
  471. data.grantedGroupsForAccessScope,
  472. data.pagePathPatterns,
  473. );
  474. const vectorStoreRelation = await this.createVectorStore(data.name);
  475. const aiAssistant = await AiAssistantModel.create({
  476. ...data, vectorStore: vectorStoreRelation,
  477. });
  478. // VectorStore creation process does not await
  479. this.createVectorStoreFileWithStream(vectorStoreRelation, conditions);
  480. return aiAssistant;
  481. }
  482. async getAccessibleAiAssistants(user: IUserHasId): Promise<AccessibleAiAssistants> {
  483. const userGroupIds = [
  484. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  485. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  486. ];
  487. const assistants = await AiAssistantModel.find({
  488. $or: [
  489. // Case 1: Assistants owned by the user
  490. { owner: user },
  491. // Case 2: Public assistants owned by others
  492. {
  493. $and: [
  494. { owner: { $ne: user } },
  495. { shareScope: AiAssistantShareScope.PUBLIC_ONLY },
  496. ],
  497. },
  498. // Case 3: Group-restricted assistants where user is in granted groups
  499. {
  500. $and: [
  501. { owner: { $ne: user } },
  502. { shareScope: AiAssistantShareScope.GROUPS },
  503. { 'grantedGroupsForShareScope.item': { $in: userGroupIds } },
  504. ],
  505. },
  506. ],
  507. });
  508. return {
  509. myAiAssistants: assistants.filter(assistant => assistant.owner.toString() === user._id.toString()) ?? [],
  510. teamAiAssistants: assistants.filter(assistant => assistant.owner.toString() !== user._id.toString()) ?? [],
  511. };
  512. }
  513. async updateAiAssistant(ownerId: string, aiAssistantId: string, data: AiAssistantUpdateData): Promise<AiAssistantDocument> {
  514. const aiAssistant = await AiAssistantModel.findOne({ owner: ownerId, _id: aiAssistantId });
  515. if (aiAssistant == null) {
  516. throw new Error('AiAssistant document does not exist');
  517. }
  518. // Implement the logic to update AiAssistant
  519. return aiAssistant;
  520. }
  521. async deleteAiAssistant(ownerId: string, aiAssistantId: string): Promise<AiAssistantDocument> {
  522. const aiAssistant = await AiAssistantModel.findOne({ owner: ownerId, _id: aiAssistantId });
  523. if (aiAssistant == null) {
  524. throw new Error('AiAssistant document does not exist');
  525. }
  526. const vectorStoreRelationId = getIdStringForRef(aiAssistant.vectorStore);
  527. await this.deleteVectorStore(vectorStoreRelationId);
  528. const deletedAiAssistant = await aiAssistant.remove();
  529. return deletedAiAssistant;
  530. }
  531. }
  532. let instance: OpenaiService;
  533. export const getOpenaiService = (): IOpenaiService | undefined => {
  534. if (instance != null) {
  535. return instance;
  536. }
  537. const aiEnabled = configManager.getConfig('app:aiEnabled');
  538. const openaiServiceType = configManager.getConfig('openai:serviceType');
  539. if (aiEnabled && openaiServiceType != null && OpenaiServiceTypes.includes(openaiServiceType)) {
  540. instance = new OpenaiService();
  541. return instance;
  542. }
  543. return;
  544. };