OpenAI 통합

OpenAI 통합

LangChain JavaScript로 OpenAI와 통합하는 방법을 알아봅니다.

LangChain은 @langchain/openai 패키지를 통해 OpenAI 및 Azure OpenAI와 통합해요.

OpenAI는 비영리 단체인 OpenAI Incorporated와 영리 자회사인 OpenAI Limited Partnership으로 구성된 미국 인공지능(AI) 연구 기관입니다. OpenAI는 친근한(friendly) AI를 장려하고 개발하겠다는 공언된 의도로 AI 연구를 수행합니다. OpenAI 시스템은 MicrosoftAzure 기반 슈퍼컴퓨팅 플랫폼에서 실행됩니다.

OpenAI API는 다양한 기능과 가격대를 가진 다양한 모델 세트로 구동됩니다.

ChatGPTOpenAI가 개발한 AI 챗봇입니다.

출처: 문서

본문

설치 및 설정(Installation and setup)

  • OpenAI API 키를 받아 환경 변수로 설정하세요(OPENAI_API_KEY)

채팅 모델(Chat model)

사용 예시를 참조하세요.

import { ChatOpenAI } from "@langchain/openai";

LLM

사용 예시를 참조하세요.

LangChain 패키지 설치에 대한 일반적인 지침은 이 섹션을 참조하세요.

npm install @langchain/openai @langchain/core
import { OpenAI } from "@langchain/openai";

텍스트 임베딩 모델(Text embedding model)

사용 예시를 참조하세요.

import { OpenAIEmbeddings } from "@langchain/openai";

체인(Chain)

import { OpenAIModerationChain } from "@langchain/classic/chains";

미들웨어(Middleware)

OpenAI 모델을 위해 특별히 설계된 미들웨어예요. 미들웨어에 대해 더 알아보세요.

미들웨어(Middleware) 설명(Description)
콘텐츠 조정(Content moderation) OpenAI의 moderation 엔드포인트로 에이전트 트래픽 조정

콘텐츠 조정(Content moderation)

OpenAI의 moderation 엔드포인트를 사용해 에이전트 트래픽(사용자 입력, 모델 출력, 도구 결과)을 조정하여 안전하지 않은 콘텐츠를 감지하고 처리합니다. 콘텐츠 조정은 다음과 같은 경우에 유용합니다:

  • 콘텐츠 안전과 규정 준수를 요구하는 애플리케이션
  • 유해하거나 혐오스럽거나 부적절한 콘텐츠 필터링
  • 안전 가드레일이 필요한 고객 대면 에이전트
  • 플랫폼 조정 요구 사항 충족

OpenAI의 moderation 모델과 카테고리에 대해 더 알아보세요.

API reference: openAIModerationMiddleware

import { createAgent, openAIModerationMiddleware } from "langchain";

const agent = createAgent({
  model: "openai:gpt-5.5",
  tools: [searchTool, databaseTool],
  middleware: [
    openAIModerationMiddleware({
      model: "openai:gpt-5.5",
      moderationModel: "omni-moderation-latest",
      checkInput: true,
      checkOutput: true,
      exitBehavior: "end",
    }),
  ],
});

구성 옵션(Configuration options)

model (string | BaseChatModel, 필수): 조정에 사용할 OpenAI 모델. 모델 이름 문자열(예: "openai:gpt-5.5") 또는 BaseChatModel 인스턴스일 수 있습니다. 미들웨어는 이 모델의 클라이언트를 사용해 moderation 엔드포인트에 접근합니다.

moderationModel (ModerationModel, 기본값 omni-moderation-latest): 사용할 OpenAI moderation 모델. 옵션: 'omni-moderation-latest', 'omni-moderation-2024-09-26', 'text-moderation-latest', 'text-moderation-stable'

checkInput (boolean, 기본값 true): 모델 호출 전에 사용자 입력 메시지를 검사할지 여부

checkOutput (boolean, 기본값 true): 모델 호출 후 모델 출력 메시지를 검사할지 여부

checkToolResults (boolean, 기본값 false): 모델 호출 전에 도구 결과 메시지를 검사할지 여부

exitBehavior ('error' | 'end' | 'replace', 기본값 'end'): 콘텐츠가 플래그될 때 위반 처리 방법. 옵션:

  • 'end' - 위반 메시지와 함께 에이전트 실행 즉시 종료
  • 'error' - OpenAIModerationError 예외 발생
  • 'replace' - 플래그된 콘텐츠를 위반 메시지로 교체하고 계속

violationMessage (string | undefined): 위반 메시지용 커스텀 템플릿. 템플릿 변수 지원:

  • {categories} - 쉼표로 구분된 플래그된 카테고리 목록
  • {category_scores} - 카테고리 점수의 JSON 문자열
  • {original_content} - 원래 플래그된 콘텐츠

기본값: "I'm sorry, but I can't comply with that request. It was flagged for {categories}."

전체 예제(Full example)

미들웨어는 OpenAI의 moderation 엔드포인트를 통합해 여러 단계에서 콘텐츠를 검사합니다:

조정 단계(Moderation stages):

  • checkInput - 모델 호출 전 사용자 메시지
  • checkOutput - 모델 호출 후 AI 메시지
  • checkToolResults - 모델 호출 전 도구 출력

종료 동작(Exit behaviors):

  • 'end' (기본값) - 위반 메시지로 실행 중지
  • 'error' - 애플리케이션 처리를 위해 예외 발생
  • 'replace' - 플래그된 콘텐츠를 교체하고 계속
import { createAgent, openAIModerationMiddleware } from "langchain";

// Basic moderation
const agent = createAgent({
  model: "openai:gpt-5.5",
  tools: [searchTool, customerDataTool],
  middleware: [
    openAIModerationMiddleware({
      model: "openai:gpt-5.5",
      moderationModel: "omni-moderation-latest",
      checkInput: true,
      checkOutput: true,
    }),
  ],
});

// Strict moderation with custom message
const agentStrict = createAgent({
  model: "openai:gpt-5.5",
  tools: [searchTool, customerDataTool],
  middleware: [
    openAIModerationMiddleware({
      model: "openai:gpt-5.5",
      moderationModel: "omni-moderation-latest",
      checkInput: true,
      checkOutput: true,
      checkToolResults: true,
      exitBehavior: "error",
      violationMessage:
        "Content policy violation detected: {categories}. " +
        "Please rephrase your request.",
    }),
  ],
});

// Moderation with replacement behavior
const agentReplace = createAgent({
  model: "openai:gpt-5.5",
  tools: [searchTool],
  middleware: [
    openAIModerationMiddleware({
      model: "openai:gpt-5.5",
      checkInput: true,
      exitBehavior: "replace",
      violationMessage: "[Content removed due to safety policies]",
    }),
  ],
});

더 알아보기 (Learn more)