0Pricing
AI Engineering Academy · 강의

채팅 완성 엔드포인트

시스템, 사용자, 어시스턴트 역할이 포함된 메시지 배열을 이해하고, 첫 프롬프트를 작성하며, API에서 반환되는 응답 객체를 해석합니다.

채팅 완성 엔드포인트은(는) CoddyKit의 무료 AI Engineering Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Engineering Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Engineering Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

메시지 배열 아키텍처

Chat Completions 엔드포인트는 메시지 배열에서 실행됩니다. 이 배열은 각 발화가 역할(system, user 또는 assistant)과 함께 담긴 목록입니다. 모델은 상태를 유지하지 않으므로 매번 대화 기록을 전송해야 합니다.

from openai import OpenAI

client = OpenAI()

response = client.chat.completions.create(
    model='gpt-4o-mini',
    messages=[
        {'role': 'system', 'content': 'You are a concise Python tutor.'},
        {'role': 'user', 'content': 'What is a list comprehension?'}
    ]
)

print(response.choices[0].message.content)

시스템 역할: 동작 정의하기

시스템 메시지는 가장 큰 영향력을 발휘합니다. 사용자가 한 단어를 입력하기 전부터 모델의 페르소나, 규칙, 형식을 설정합니다. 여기에 시간을 투자하십시오. 모든 결과의 방향을 결정합니다. 코드를 확인해 보십시오.

system_prompt = '''You are a customer support agent for TechShop.
You help customers with: order tracking, returns, and product questions.
You do NOT discuss pricing changes or competitor products.
Always respond in 2-3 sentences maximum.
If you cannot help, say: 'Let me connect you with a human agent.'
'''

response = client.chat.completions.create(
    model='gpt-4o-mini',
    messages=[
        {'role': 'system', 'content': system_prompt},
        {'role': 'user', 'content': 'Where is my order #12345?'}
    ]
)

여러 발화로 이루어진 대화 관리하기

대화를 계속 이어 가려면 각 발화를 메시지 배열에 append하고 전체 배열을 다시 전송해야 합니다. 모델이 기억하는 것처럼 보이는 이유는 전체 기록을 모델에 계속 제공하기 때문입니다.

history = [
    {'role': 'system', 'content': 'You are a helpful assistant.'}
]

def chat(user_message):
    history.append({'role': 'user', 'content': user_message})
    response = client.chat.completions.create(
        model='gpt-4o-mini',
        messages=history
    )
    assistant_reply = response.choices[0].message.content
    history.append({'role': 'assistant', 'content': assistant_reply})
    return assistant_reply

print(chat('My name is Alice.'))
print(chat('What is my name?'))  # model remembers 'Alice'

API 응답의 구성

응답은 단순한 텍스트가 아니라 객체입니다. choices에는 답변이 들어 있고, finish_reason은 중단된 이유를 나타내며, usage는 비용을 결정하는 토큰 수를 집계합니다. 프로덕션 환경에서는 이를 기록하십시오.

response = client.chat.completions.create(
    model='gpt-4o-mini',
    messages=[{'role': 'user', 'content': 'Say hello in one word.'}]
)

# Accessing response fields
print('Content:', response.choices[0].message.content)
print('Finish reason:', response.choices[0].finish_reason)  # 'stop'
print('Model:', response.model)  # exact version like gpt-4o-mini-2024-07-18
print('Prompt tokens:', response.usage.prompt_tokens)
print('Completion tokens:', response.usage.completion_tokens)
print('Total tokens:', response.usage.total_tokens)

finish_reason 이해하기

finish_reason은 생성이 중단된 이유를 알려 줍니다. 'stop'은 완료되었다는 뜻이고, 'length'는 max_tokens에 도달해 답변 중간에서 잘렸다는 뜻입니다. 항상 확인하십시오. 잘림은 조용히 발생하는 버그입니다.

def safe_completion(messages, max_tokens=500):
    response = client.chat.completions.create(
        model='gpt-4o-mini',
        messages=messages,
        max_tokens=max_tokens
    )
    choice = response.choices[0]
    
    if choice.finish_reason == 'length':
        print(f'WARNING: Response was truncated at {max_tokens} tokens!')
    elif choice.finish_reason == 'content_filter':
        print('WARNING: Response blocked by content filter!')
        return None
    
    return choice.message.content

알맞은 모델 선택하기

작업에 맞는 모델을 선택하십시오. gpt-4o는 어려운 추론을 위한 강력한 모델이고, gpt-4o-mini는 훨씬 저렴하면서 대부분의 작업을 잘 처리합니다. 더 큰 모델이 항상 더 좋은 결과를 내리라고 가정하기 전에 성능을 측정하십시오.

# Model comparison guidance
models = {
    'gpt-4o': {
        'use_for': 'Complex reasoning, code generation, nuanced analysis',
        'input_cost_per_1M': 2.50,  # USD
        'output_cost_per_1M': 10.00
    },
    'gpt-4o-mini': {
        'use_for': 'Classification, extraction, summarization, Q&A',
        'input_cost_per_1M': 0.15,
        'output_cost_per_1M': 0.60
    }
}
# gpt-4o is ~17x more expensive on input tokens

메시지의 콘텐츠 유형

메시지의 content는 텍스트에 한정되지 않습니다. gpt-4o 같은 비전 모델에는 텍스트와 이미지를 섞은 목록을 전달할 수 있으므로 차트나 스크린샷에 관해 질문할 수 있습니다.

# Sending an image to a vision-capable model
response = client.chat.completions.create(
    model='gpt-4o',
    messages=[
        {
            'role': 'user',
            'content': [
                {
                    'type': 'text',
                    'text': 'What is in this image? Describe in one sentence.'
                },
                {
                    'type': 'image_url',
                    'image_url': {'url': 'https://example.com/photo.jpg'}
                }
            ]
        }
    ]
)

n 매개변수: 여러 완성 결과

n 매개변수는 하나의 프롬프트에 대해 여러 완성 결과를 반환합니다. 가장 좋은 결과를 고를 때 유용하며, 신뢰도를 판단하는 데도 쓸 수 있습니다. n개의 결과가 모두 일치하면 모델이 확신한다는 뜻이고, 서로 다르면 주의해야 합니다.

response = client.chat.completions.create(
    model='gpt-4o-mini',
    messages=[{'role': 'user', 'content': 'Name the capital of Germany.'}],
    n=3,  # generate 3 independent completions
    temperature=0.5
)

for i, choice in enumerate(response.choices):
    print(f'Completion {i+1}: {choice.message.content}')

# Check if all completions agree (confidence signal)
answers = [c.message.content.strip() for c in response.choices]
print('All agree:', len(set(answers)) == 1)

응답을 문자열로 처리하기

답변을 텍스트로 가져오려면 경로는 항상 response.choices[0].message.content입니다. 이를 도우미 함수로 감싸고, 도구 호출이나 필터로 인해 발생할 수 있는 None도 처리하십시오.

def get_completion(prompt, system='You are a helpful assistant.', model='gpt-4o-mini'):
    '''Simple helper that returns the response text as a string.'''
    response = client.chat.completions.create(
        model=model,
        messages=[
            {'role': 'system', 'content': system},
            {'role': 'user', 'content': prompt}
        ]
    )
    content = response.choices[0].message.content
    if content is None:
        raise ValueError(f'No content in response. Finish reason: {response.choices[0].finish_reason}')
    return content

result = get_completion('Explain recursion in one sentence.')
print(result)

원시 요청과 응답 살펴보기

이상한 답변을 디버깅하고 계십니까? 원시 요청과 응답을 살펴보십시오. OPENAI_LOG=debug를 설정하면 전체 본문이 터미널에 출력되므로 네트워크를 통해 실제로 전송된 내용을 가장 빠르게 확인할 수 있습니다.

import json
import httpx

# Enable debug logging (shows full request/response)
import os
os.environ['OPENAI_LOG'] = 'debug'

# Or use a custom logging client:
class LoggingClient(httpx.Client):
    def send(self, request, *args, **kwargs):
        print('REQUEST:', request.method, request.url)
        print('BODY:', json.loads(request.content))
        response = super().send(request, *args, **kwargs)
        print('STATUS:', response.status_code)
        return response

최소한의 채팅 반복문 만들기

이제 최소한의 채팅 반복문을 만들 수 있습니다. 메시지 목록을 유지하고, 각 발화를 추가하고, 전체를 전송한 뒤 반복하십시오. 이 단순한 패턴이 API를 사용하는 모든 채팅 앱의 기반이 됩니다. 코드에서 확인할 수 있습니다.

import openai

client = openai.OpenAI()

SYSTEM_PROMPT = 'You are a helpful assistant. Be concise.'

def simple_chat_loop():
    messages = [{'role': 'system', 'content': SYSTEM_PROMPT}]
    print('Chat started. Type "quit" to exit.')

    while True:
        user_input = input('You: ').strip()
        if user_input.lower() == 'quit':
            break
        if not user_input:
            continue

        messages.append({'role': 'user', 'content': user_input})

        response = client.chat.completions.create(
            model='gpt-4o-mini',
            messages=messages,
            max_tokens=500
        )

        assistant_reply = response.choices[0].message.content
        messages.append({'role': 'assistant', 'content': assistant_reply})
        print(f'Assistant: {assistant_reply}\n')

print('Example chat loop defined. Run simple_chat_loop() to start.')

빠른 확인

이 단원에서 배운 AI Engineering 개념을 얼마나 이해했는지 테스트해 보십시오.

단원 요약

채팅의 핵심을 배웠습니다. 메시지 배열이 대화를 제어하고, 응답에는 content, finish_reason, 토큰 수가 포함됩니다. 다음 주제: 매개변수입니다.

자주 묻는 질문

“채팅 완성 엔드포인트” 강의는 무료인가요?

네 — “채팅 완성 엔드포인트” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Engineering Academy 강의 전체를 잠금 해제할 수 있습니다. AI Engineering Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“채팅 완성 엔드포인트”에서 뭘 배우나요?

시스템, 사용자, 어시스턴트 역할이 포함된 메시지 배열을 이해하고, 첫 프롬프트를 작성하며, API에서 반환되는 응답 객체를 해석합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Engineering Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

AI Engineering Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 AI Engineering Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“채팅 완성 엔드포인트” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 AI Engineering Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 AI Engineering Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Python 환경 설정하기
  2. 채팅 완성 엔드포인트
  3. 매개변수로 모델 동작 제어하기
  4. 오류 처리와 요청 한도
← AI Engineering Academy(으)로 돌아가기