반응형

이 글은 NestJS 프로젝트에서 OpenAI의 API를 이용하는 방법에 대해 설명합니다.

 

다음은 이 글의 유튜브 강의 입니다.

https://youtu.be/2DRxtCwjFtE

순서

- OpenAI API Key 생성

- Nestjs 프로젝트 생성

- OpenAI 패키지 설치

- 프로그램 개발

- 테스트

 

OpenAI API 키 생성하기

- OpenAI 사이트에서 회원 가입을 합니다.

https://platform.openai.com/

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

- 우측 상단의 계정 아이콘을 클릭하고, 메뉴에서 View API Key를 선택합니다.

- "+ Create new Secret key"를 클릭하여 새로운 키를 생성합니다.

- API 사용법은 사이트 상단의 "API Reference" 메뉴에 자세히 나와 있으니 참고하시기 바랍니다.

https://platform.openai.com/docs/api-reference/introduction

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

 

NestJS 프로젝트 생성

- 아래와 같이 프로젝트를 생성합니다.

nest new 프로젝트명

- Editor에서 프로젝트 열기를 하고 프로젝트를 선택합니다.

 

OpenAI 패키지 설치

Nestjs에서 OpenAI API를 사용하기 위해서는 "openai" 패키지를 설치해야합니다.

- 아래와 같이 패키지를 설치합니다.

npm install openai

 

프로그램 개발

app.service.ts를 다음과 같이 작성합니다.

- 아래와 같이 패키지를 import 하고 openai를 선언합니다.

import { Configuration, OpenAIApi } from "openai";
const configuration = new Configuration({
    organization: "org-xxxxxxxxxxxxxxxxxxxxxxxxxxx",
    apiKey: "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxx",
});
const openai = new OpenAIApi(configuration);

- getHello()를 아래와 같이 작성합니다.

async getHello() {
    const response = await openai.createCompletion({
      model: "text-davinci-003",
      prompt: ""나는 인공지능 AI Chatbot이야. 질문을 하면 내가 답변을 해줄께. 만약 모른다면 \"모름\"이라고 할께.\n\nQ: 한국인의 기대 수명은 얼마야?\nA:",
      temperature: 0,
      max_tokens: 100,
      top_p: 1,
      frequency_penalty: 0.0,
      presence_penalty: 0.0,
      stop: ["\n"],
    });
    return { result: response.data.choices[0].text };
  }

- 여기선 model로 text-davinci-003을 사용하였습니다.

- 모델의 종류를 보시려면 다음과 같이 api를 호출하면 됩니다.

const response = await openai.listModels();
return { result: response.data };

- 주로 많이 사용하는 모델은 gpt-3.5-turbo, text-davinch-003 입니다.

테스트

- 브라우저에서 다음 주소를 입력합니다.

http://localhost:3000/

아래와 같이 결과가 나옵니다.

 

 

반응형

'AI & ML' 카테고리의 다른 글

개발자도 AI(인공지능)를 배워야 할까요?  (0) 2023.02.12

+ Recent posts