GPT-4o 모델로 구조화 출력 얻기
GPT-4o 모델로 구조화 출력 얻기 (Structured output using GPT-4o models)
이 쿡북은 GPT-4o 모델로 구조화 출력을 얻는 방법을 보여줘요. OpenAI beta 클라이언트 SDK는 JSON 스키마를 직접 정의할 필요 없이 여러분의 Pydantic 모델을 그대로 사용할 수 있는 parse 헬퍼를 제공해요. 이 접근 방식은 지원되는 모델에 권장됩니다.
현재 이 기능은 다음에서 지원돼요.
- OpenAI의 gpt-4o-mini
- OpenAI의 gpt-4o-2024-08-06
- Azure의 gpt-4o-2024-08-06
수학 문제의 설명(explanation)과 출력(output)을 담는 간단한 메시지 타입을 정의해 볼게요.
from pydantic import BaseModel
class MathReasoning(BaseModel):
class Step(BaseModel):
explanation: str
output: str
steps: list[Step]
final_answer: str
import os
# Set the environment variable
os.environ["AZURE_OPENAI_ENDPOINT"] = "https://YOUR_ENDPOINT_DETAILS.openai.azure.com/"
os.environ["AZURE_OPENAI_API_KEY"] = "YOUR_API_KEY"
os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"] = "gpt-4o-2024-08-06"
os.environ["AZURE_OPENAI_API_VERSION"] = "2024-08-01-preview"
import json
import os
from typing import Optional
from autogen_core.models import UserMessage
from autogen_ext.models.openai import AzureOpenAIChatCompletionClient
# Function to get environment variable and ensure it is not None
def get_env_variable(name: str) -> str:
value = os.getenv(name)
if value is None:
raise ValueError(f"Environment variable {name} is not set")
return value
# Create the client with type-checked environment variables
client = AzureOpenAIChatCompletionClient(
azure_deployment=get_env_variable("AZURE_OPENAI_DEPLOYMENT_NAME"),
model=get_env_variable("AZURE_OPENAI_MODEL"),
api_version=get_env_variable("AZURE_OPENAI_API_VERSION"),
azure_endpoint=get_env_variable("AZURE_OPENAI_ENDPOINT"),
api_key=get_env_variable("AZURE_OPENAI_API_KEY"),
)
# Define the user message
messages = [
UserMessage(content="What is 16 + 32?", source="user"),
]
# Call the create method on the client, passing the messages and additional arguments
# The extra_create_args dictionary includes the response format as MathReasoning model we defined above
# Providing the response format and pydantic model will use the new parse method from beta SDK
response = await client.create(messages=messages, extra_create_args={"response_format": MathReasoning})
# Ensure the response content is a valid JSON string before loading it
response_content: Optional[str] = response.content if isinstance(response.content, str) else None
if response_content is None:
raise ValueError("Response content is not a valid JSON string")
# Print the response content after loading it as JSON
print(json.loads(response_content))
# Validate the response content with the MathReasoning model
MathReasoning.model_validate(json.loads(response_content))
핵심을 짚어볼게요. extra_create_args에 response_format으로 위에서 정의한 MathReasoning 모델을 넘기면, beta SDK의 parse 메서드를 사용하게 돼요. 그러면 모델이 JSON 스키마 정의 없이도 우리가 정의한 Pydantic 구조 그대로 응답을 만들어요. 마지막 단계에서 MathReasoning.model_validate()로 응답이 우리 모델 스키마에 맞는지 검증하는 것도 잊지 마세요.