import { Inject, Provide, Scope, ScopeEnum } from '@midwayjs/core';
import { FlowNode } from '../../runner/node';
import { FlowContext } from '../../runner/context';
import { KnowRetrieverService } from '../../../know/service/retriever';

/**
 * 知识库节点
 */
@Provide()
@Scope(ScopeEnum.Prototype)
export class NodeKnow extends FlowNode {
  @Inject()
  knowRetrieverService: KnowRetrieverService;

  /**
   * 执行
   * @param context
   * @returns
   */
  async run(context: FlowContext) {
    const { knowIds, size } = this.config.options;
    const params = this.inputParams;
    const { text } = params;
    const documents = await this.knowRetrieverService.search(knowIds, text, {
      size,
    });
    context.set(`${this.getPrefix()}.documents`, documents, 'output');
    const str = documents.map(item => item.pageContent).join('/n/r');
    context.set(`${this.getPrefix()}.text`, str, 'output');
    return {
      success: true,
      result: {
        documents,
        text: str,
      },
    };
  }
}
