replace-annotation-with-page-link.ts 1.4 KB

1234567891011121314151617181920212223242526272829
  1. // See: https://platform.openai.com/docs/assistants/tools/file-search#step-5-create-a-run-and-check-the-output
  2. import type { IPageHasId, Lang } from '@growi/core/dist/interfaces';
  3. import type { MessageContentDelta } from 'openai/resources/beta/threads/messages.mjs';
  4. import VectorStoreFileRelationModel from '~/features/openai/server/models/vector-store-file-relation';
  5. import { getTranslation } from '~/server/service/i18next';
  6. export const replaceAnnotationWithPageLink = async(messageContentDelta: MessageContentDelta, lang?: Lang): Promise<void> => {
  7. if (messageContentDelta?.type === 'text' && messageContentDelta?.text?.annotations != null) {
  8. const annotations = messageContentDelta?.text?.annotations;
  9. for await (const annotation of annotations) {
  10. if (annotation.type === 'file_citation' && annotation.text != null) {
  11. const vectorStoreFileRelation = await VectorStoreFileRelationModel
  12. .findOne({ fileIds: { $in: [annotation.file_citation?.file_id] } })
  13. .populate<{page: Pick<IPageHasId, 'path' | '_id'>}>('page', 'path');
  14. if (vectorStoreFileRelation != null) {
  15. const { t } = await getTranslation(lang);
  16. messageContentDelta.text.value = messageContentDelta.text.value?.replace(
  17. annotation.text,
  18. ` [${t('source')}: [${vectorStoreFileRelation.page.path}](/${vectorStoreFileRelation.page._id})]`,
  19. );
  20. }
  21. }
  22. }
  23. }
  24. };