응답 속도 개선

api를 구현하고 테스트를 해보면 평균 응답시간이 약 1분~2분 사이였다…

만약 내가 이 서비스를 사용하는 유저라면 2분동안 기다릴 수 있을까?

생각만해도 끔찍하다…

답변 GPT 모델 추가

가장 효과적이면서 효율적인? 방법이라고 생각한다. 바로 응답용 GPT를 늘려버리는 것이다.

성분이 적을때는 답변하는 시간대가 느리지 않지만, 성분이 많아지면 각 성분에 대해 답변을 작성하기 때문에 성분이 많을 때에는 성분 시간이 많아진 만큼 시간이 오래걸린다.

개선된 방식

분석해야할 성분의 갯수에 따라 답변하는 모델을 점차 늘릴 수 있도록 코드를 변경해준다!

적용 후 약

주의 - GPT 모델을 늘렸다는 것은 세팅하는 과정까지 추가되기 때문에 비용이 추가된다. 이를 고려해서 모델을 늘리는 정도를 고려해야함!!!

private splitIngredients(ingredients: string[]): string[][] {
    if (ingredients.length <= 3) {
      return [ingredients];
    }

    let numberOfArrays = 2;

    if (ingredients.length >= 12) {
      //요소가 12개 이상일때부터 모델 4개 사용
      numberOfArrays = 4;
    } else if (ingredients.length >= 9) {
      numberOfArrays = 3;
    }
    const totalIngredients = ingredients.length;
    const ingredientsPerArray = Math.ceil(totalIngredients / numberOfArrays);

    const splitArrays: string[][] = [];
    for (let i = 0; i < numberOfArrays; i++) {
      const startIndex = i * ingredientsPerArray;
      const endIndex = startIndex + ingredientsPerArray;
      const newArray = ingredients.slice(startIndex, endIndex);
      splitArrays.push(newArray);
    }

    return splitArrays;
  }
private createSplitMessages(
    getAdviseDto: GetAdviseDto,
    ingredients: string[],
    baseMessages: ChatCompletionRequestMessage[],
  ) {
    const splitIngredientArrays = this.splitIngredients(ingredients);

    const splitMessages: ChatCompletionRequestMessage[][] = [];

    for (const splitIngredientArray of splitIngredientArrays) {
      if (splitIngredientArray.length) {
        const messages: ChatCompletionRequestMessage[] = [
          ...baseMessages,
          {
            role: 'user',
            content: `diseases:${getAdviseDto.diseases}, ingredients:${splitIngredientArray}`,
          },
        ];
        splitMessages.push(messages);
      }
    }

    return splitMessages;
  }
private async fetchChatGptAdvise(messages) {
      let openAiInstances: OpenAIApi[] = [this.openAiOne];

      if (messages.length === 2) {
        openAiInstances = [this.openAiOne, this.openAiTwo];
      }
      if (messages.length === 3) {
        openAiInstances = [this.openAiOne, this.openAiTwo, this.openAiThree];
      }

      if (messages.length === 4) {
        openAiInstances = [
          this.openAiOne,
          this.openAiTwo,
          this.openAiThree,
          this.openAiFour,
        ];
      }

      const modelResponses = await Promise.all(
        messages.map((msg, index) =>
          this.createModelResponse(openAiInstances[index], msg),
        ),
      );

      return modelResponses.flat();
    }

비용 절약