chatGPT API 호출시, json 형태로 응답받는 방법은 2가지가 있다.

 

방법1) JSON Mode

 

- 사용방법 : API 호출시, response_format: { type: "json_object" } 으로 설정

- 장점 : 간단하고 직관적임 / 적용 가능한 model 이 다양함 (gpt-3.5-turbo, gpt-4-* and gpt-4o-* models)

- 단점 : 매우 간헐적으로 json 형태를 보장하지 못하는 경우 발생 / 특정 key 의 존재나 type 을 항상 보장하지 않음

- 가장 기본적으로 많이 알려진 방법으로,  ChatGPT가 항상 유효한 JSON 형식으로 응답하도록 강제하는 설정임.

 

import openai

response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo-1106",
    response_format={ "type": "json_object" },
    messages=[
        {"role": "system", "content": "You are a helpful assistant designed to output JSON."},
        {"role": "user", "content": "Give me a JSON object with keys for 'name' and 'age' for a fictional person"}
    ]
)

print(response['choices'][0]['message']['content'])
#출력예시
{
  "name": "Alice Johnson",
  "age": 28
}

 

방법 2) Structured Outputs ( 2024 기준 새로운 방법 )

 

- 사용방법 : response_format: { type: "json_schema", json_schema: {"strict": true, "schema": ...} }

- 장점 : 항상 동일한 구조로 데이터 response 받을 수 있음 / required 항목을 통해 특정 필드가 반드시 포함되도록 할 수 있음 / 매우 구체적으로 데이터 type 정의 가능 / 복잡한 중첩 구조 쉽게 정의 가능 / 더 엄격하게 json 구조 명시 가능

- 단점 : 설정 복잡함 / 최신 model version 에만 적용가능 ( 2024.10 기준 gpt-4o-mini, gpt-4o-2024-08-06, and later 모델만 적용가능) 

- API 호출시, 특정 함수를 정의하고 정의한 함수의 파라미터에 맞는 구조화된 데이터를 반환받는 방식

 

import openai
import json

# OpenAI API 키 설정
openai.api_key = 'your-api-key-here'

def get_movie_info(movie_title):
    response = openai.ChatCompletion.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": "You are a helpful assistant that provides movie information."},
            {"role": "user", "content": f"Give me information about the movie '{movie_title}'."}
        ],
        # 함수정의(이 부분에서 원하는 데이터 구조를 정의함. 각 필드의 타입과 설명을 명시하고, 필수 필드를 지정)
        functions=[ 
            {
                "name": "provide_movie_info",
                "description": "Provide information about a specific movie",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "title": {"type": "string", "description": "The title of the movie"},
                        "director": {"type": "string", "description": "The name of the movie's director"},
                        "release_year": {"type": "integer", "description": "The year the movie was released"},
                        "genres": {"type": "array", "items": {"type": "string"}, "description": "List of genres for the movie"}
                    },
                    "required": ["title", "director", "release_year", "genres"]
                }
            }
        ],
        # 함수 호출 지정 (이 부분에서 ChatGPT에게 미리 위에서 정의한 함수를 호출하도록 지시함)
        function_call={"name": "provide_movie_info"} 
    )

    # 함수 호출 결과 추출 (API response 결과를 추출하고 JSON으로 파싱)
    function_args = json.loads(response['choices'][0]['message']['function_call']['arguments'])
    return function_args

# 사용 예시
movie_title = "The Matrix"
movie_info = get_movie_info(movie_title)
print(json.dumps(movie_info, indent=2))
# 실행결과
{
  "title": "The Matrix",
  "director": "The Wachowskis",
  "release_year": 1999,
  "genres": ["Science Fiction", "Action", "Cyberpunk"]
}

 

 

공식문서

https://platform.openai.com/docs/guides/structured-outputs/examples?context=ex4

반응형

+ Recent posts