OpenAI Chat Completions: JSON 모드

OpenAI의 새로 업데이트 된 API에서 JSON 출력을 지원합니다.

이전에도 프롬프트 엔지니어링을 통해 GPT 모델에서 출력을 JSON 형식으로 하도록 만들 수는 있었지만, 항상 JSON 형식으로 출력하는 것이 보장된 것은 아니었죠. 새로운 API에서는 JSON 모드를 사용하면 항상 JSON 형식으로 출력해줍니다.

JSON 모드를 사용하기 위해서는 두 가지 조건을 만족해야 합니다.

  1. API 호출시 response_format = {"type": "json_object"}을 지정해줍니다.
  2. 프롬프트에서 JSON으로 출력하라고 합니다.

예시 코드를 보겠습니다.

response = client.chat.completions.create(
  model="gpt-4-1106-preview",
  messages=[
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "LangChain은 무엇을 하는 라이브러리지? JSON으로 답해줘"}
  ],
  response_format = {'type':"json_object"}
)
print(response.choices[0].message.content)

## 출력
{
  "LangChain": {
    "Description": "LangChain is a library that provides a framework for building applications and systems that interact with language models. It facilitates the integration of different components necessary for creating robust language understanding and generation tasks, such as conversation agents, AI-powered assistants, and more.",
    "Purpose": "Facilitate the building and deployment of language-centric applications using state-of-the-art language models.",
    "Key Features": [
      "Modular design to plug in various language models",
      "High-level abstractions for language skills",
      "Support for multiple use cases including chatbots, data extraction, and content generation",
      "Tools for conversation context management and multi-turn dialogue handling"
    ],
    "Use Cases": [
      "Creating conversational agents",
      "Developing AI writing assistants",
      "Building systems for automated summarization",
      "Generating and manipulating natural language content"
    ]
  }
}

LangChain은 2022년 10월에 공개된 거대 언어 모델 라이브러리입니다. 기존 GPT 모델은 2021년 9월까지의 정보만 가지고 있었지만, 새로운 모델은 2023년 4월까지의 정보로 훈련시켰다고 합니다.

위 결과를 보면 JSON 형식으로 출력하는데, 키 값은 알아서 지정한 것을 볼 수 있습니다. 키를 지정하고 싶다면 다음과 같이 프롬프트에서 정해주면 됩니다.

response = client.chat.completions.create(
  model="gpt-4-1106-preview",
  messages=[
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "LangChain은 무엇을 하는 라이브러리지? JSON으로 답해줘. JSON 키워드는 Description, Features, Usage로 해줘."}
  ],
  response_format = {'type':"json_object"}
)

## 결과

{
  "Description": "LangChain은 자연어 처리(NLP) 작업을 위해 디자인된 파이썬 라이브러리입니다. 이 라이브러리는 NLP 모델을 쉽게 통합하고 사용할 수 있도록 다양한 기능과 도구를 제공하여 개발자들이 복잡한 NLP 관련 프로젝트를 빠르고 효율적으로 구현할 수 있게 돕습니다.",
  "Features": [
    "다양한 NLP 작업을 위한 사전 구축된 모듈과 인터페이스 지원",
    "간편한 사용자 정의 모델 통합 및 확장성",
    "다양한 NLP 프레임워크와 라이브러리(예: Hugging Face의 Transformers, spaCy 등)와의 호환성",
    "엔드-투-엔드 NLP 애플리케이션 구축을 위한 편리한 어플리케이션 프로그래밍 인터페이스(APIs)"
  ],
  "Usage": [
    "텍스트 분류, 개체명 인식, 기계 번역 등 다양한 NLP 태스크를 손쉽게 수행",
    "챗봇, 음성 인식 시스템, 감성 분석 도구 등의 NLP 기반 애플리케이션 개발",
    "구문 분석, 토픽 모델링, 문서 요약 등 고급 텍스트 분석 기능 구현",
    "NLP 모델들을 실험하고 최적화하기 위한 실험적 환경 제공"
  ]
}

프롬프트에서 지정한 키를 사용해 JSON 출력을 만들어준 것을 볼 수 있습니다. Text가 아닌, JSON 으로 출력하게 되면 결과를 프로그래밍 언어에서 가져다 쓰기 좋기 때문에 프로그래머들에게 편리한 기능이라 할 수 있습니다.

댓글 남기기