매개변수로 모델 동작 제어하기
temperature, max_tokens, top_p를 조정해 출력의 스타일, 길이, 창의성이 어떻게 달라지는지 확인하고, 사용 사례에 맞는 설정을 선택합니다.
매개변수로 모델 동작 제어하기은(는) CoddyKit의 무료 AI Engineering Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Engineering Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Engineering Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
중요한 핵심 매개변수
몇 가지 매개변수가 출력에 가장 큰 영향을 줍니다. temperature, max_tokens, top_p, frequency_penalty, presence_penalty입니다. 이 다섯 가지를 익히면 모델을 제어할 수 있습니다.
Temperature: 무작위성 제어하기
Temperature는 무작위성을 제어합니다. 0에 가까우면 모델이 가장 안전한 단어를 선택하며 일관성을 유지하므로 사실을 다루는 작업에 적합합니다. 0.7~1.0 정도에서는 결과가 다양하고 창의적으로 변합니다. 코드를 확인해 보십시오.
from openai import OpenAI
client = OpenAI()
for temp in [0.0, 0.7, 1.5]:
response = client.chat.completions.create(
model='gpt-4o-mini',
messages=[{'role': 'user', 'content': 'Name a color.'}],
temperature=temp,
max_tokens=5
)
print(f'Temp {temp}: {response.choices[0].message.content}')
# Temp 0.0: Red (always most common)
# Temp 0.7: Blue (varied but sensible)
# Temp 1.5: Vermillion (surprising choices)max_tokens: 응답 길이 제어하기
max_tokens는 답변의 최대 길이를 제한합니다. 이는 목표 길이가 아니라 안전 제한입니다. 너무 낮으면 답변이 잘리고, 너무 높으면 비용과 시간이 낭비됩니다. 여유분을 추가하고 finish_reason을 확인하십시오.
# Different max_tokens for different use cases
# Classification: short answer expected
classification_response = client.chat.completions.create(
model='gpt-4o-mini',
messages=[{'role': 'user', 'content': 'Is this positive or negative? "Great product!"'}],
max_tokens=5 # Only need 1-2 words
)
# Detailed analysis: longer output needed
analysis_response = client.chat.completions.create(
model='gpt-4o-mini',
messages=[{'role': 'user', 'content': 'Analyze the pros and cons of microservices.'}],
max_tokens=800 # Need space for detailed explanation
)top_p: 누적 확률 샘플링
top_p는 또 다른 무작위성 조절 장치입니다. 확률을 더했을 때 top_p가 되는 상위 토큰만을 대상으로 샘플링합니다. 팁: temperature와 top_p를 동시에 조정하지 말고 둘 중 하나만 조정하십시오.
# top_p usage example
response_narrow = client.chat.completions.create(
model='gpt-4o-mini',
messages=[{'role': 'user', 'content': 'Continue: The sky is...'}],
top_p=0.1, # only very likely tokens (conservative, predictable)
temperature=1.0 # keep temperature at 1 when using top_p
)
response_wide = client.chat.completions.create(
model='gpt-4o-mini',
messages=[{'role': 'user', 'content': 'Continue: The sky is...'}],
top_p=0.95, # most tokens eligible (creative, varied)
temperature=1.0
)Frequency Penalty: 반복 줄이기
frequency_penalty는 같은 단어가 등장한 횟수에 비례하여 모델이 해당 단어를 반복하지 않도록 합니다. 긴 답변이 반복적으로 느껴질 때 사용해 보십시오. 0.3~0.7부터 시도하면 됩니다.
# Frequency penalty to reduce repetition in long outputs
response = client.chat.completions.create(
model='gpt-4o-mini',
messages=[{
'role': 'user',
'content': 'Write 5 tips for better sleep.'
}],
max_tokens=300,
frequency_penalty=0.5 # reduces repeating the same words/phrases
)
print(response.choices[0].message.content)Presence Penalty: 주제 다양성 높이기
presence_penalty는 모델이 새로운 주제를 다루도록 유도합니다. 이미 한 번이라도 등장한 단어에 불이익을 줍니다. 새롭고 다양한 아이디어가 필요한 브레인스토밍에 적합합니다.
# Presence penalty for diverse brainstorming output
response = client.chat.completions.create(
model='gpt-4o-mini',
messages=[{
'role': 'user',
'content': 'List 10 creative ways to use AI in a small business.'
}],
max_tokens=400,
presence_penalty=0.8 # encourages introducing different topics per item
)
print(response.choices[0].message.content)stop 시퀀스: 사용자 지정 중단 지점
stop 매개변수에는 해당 문자열이 나타나는 즉시 생성을 중단하는 문자열을 지정합니다(해당 문자열은 결과에서 제외됩니다). 줄바꿈에서 중단하면 깔끔한 한 줄 답변을 얻을 수 있습니다. 코드를 확인해 보십시오.
# Use stop sequences to get clean single-line output
response = client.chat.completions.create(
model='gpt-4o-mini',
messages=[{
'role': 'user',
'content': 'What is the Python keyword for a function definition?\nAnswer:'
}],
max_tokens=20,
stop=['\n', '.'] # stop at newline or period - gets just the keyword
)
print(repr(response.choices[0].message.content)) # 'def'seed: 재현 가능한 출력
seed 매개변수를 사용하면 출력을 재현할 수 있습니다. 같은 seed와 temperature 0을 사용하면 같은 답변이 나옵니다. 테스트에 유용하지만 백엔드가 변경되었는지 확인하려면 system_fingerprint를 살펴보십시오.
# Reproducible output with seed parameter
response1 = client.chat.completions.create(
model='gpt-4o-mini',
messages=[{'role': 'user', 'content': 'Pick a random number from 1 to 10.'}],
temperature=0,
seed=42
)
response2 = client.chat.completions.create(
model='gpt-4o-mini',
messages=[{'role': 'user', 'content': 'Pick a random number from 1 to 10.'}],
temperature=0,
seed=42
)
print(response1.choices[0].message.content) # same
print(response2.choices[0].message.content) # same
print('Fingerprint:', response1.system_fingerprint)일반적인 사용 사례에 맞는 매개변수 선택하기
빠른 사전 설정으로 추측을 줄이십시오. 분류에는 temperature 0, 사실 기반 질의응답에는 0.2, 창작 글쓰기에는 0.8~1.0을 사용합니다. 여기서 시작한 다음 작업에 맞게 조정하십시오. 코드를 확인해 보십시오.
# Parameter presets for different task types
PRESETS = {
'classify': {'temperature': 0, 'max_tokens': 20},
'factual_qa': {'temperature': 0.2, 'max_tokens': 400},
'creative': {'temperature': 0.9, 'max_tokens': 1000, 'frequency_penalty': 0.3},
'code': {'temperature': 0.1, 'max_tokens': 2000},
'summary': {'temperature': 0.3, 'max_tokens': 300, 'frequency_penalty': 0.2},
}
def complete(prompt, task_type='factual_qa', **overrides):
params = {**PRESETS[task_type], **overrides}
return client.chat.completions.create(
model='gpt-4o-mini',
messages=[{'role': 'user', 'content': prompt}],
**params
)Logprobs: 모델의 확신도 이해하기
logprobs는 모델이 각 토큰을 얼마나 확신했는지와 함께 검토한 대안도 반환합니다. 사실에 대한 확신도가 낮다면 환각의 징후일 수 있으므로 더 안전한 시스템을 만드는 데 유용합니다.
import math
response = client.chat.completions.create(
model='gpt-4o-mini',
messages=[{'role': 'user', 'content': 'The capital of France is?'}],
max_tokens=3,
logprobs=True,
top_logprobs=3 # show top 3 alternative tokens at each position
)
for token_log in response.choices[0].logprobs.content:
prob = math.exp(token_log.logprob) # convert log prob to probability
print(f'Token: {token_log.token!r} | Probability: {prob:.2%}')
for alt in token_log.top_logprobs:
print(f' Alt: {alt.token!r} -> {math.exp(alt.logprob):.2%}')매개변수 효과를 체계적으로 테스트하기
매개변수를 추측하지 말고 테스트하십시오. 동일한 프롬프트를 여러 조합에 적용하고 각각 점수를 매기는 작은 격자 탐색을 구현하십시오. 이렇게 하면 조정 작업이 감에서 벗어나 공학적인 과정이 됩니다. 코드를 확인해 보십시오.
from itertools import product
# Systematic parameter grid search
temperatures = [0.0, 0.3, 0.7]
max_tokens_options = [100, 300]
test_prompt = 'Summarize the benefits of unit testing in 2 sentences.'
results = []
for temp, max_tok in product(temperatures, max_tokens_options):
resp = client.chat.completions.create(
model='gpt-4o-mini',
messages=[{'role': 'user', 'content': test_prompt}],
temperature=temp,
max_tokens=max_tok
)
results.append({
'temperature': temp,
'max_tokens': max_tok,
'output': resp.choices[0].message.content,
'actual_tokens': resp.usage.completion_tokens
})빠른 확인
이 단원에서 배운 AI Engineering 개념을 얼마나 이해했는지 테스트해 보십시오.
단원 요약
모델을 조정하는 방법을 배웠습니다. temperature는 무작위성을 설정하고, max_tokens는 길이를 제한하며(finish_reason을 확인하십시오!), 페널티는 반복을 줄이고 다양성을 높입니다. 다음 주제: 오류 처리입니다.
자주 묻는 질문
“매개변수로 모델 동작 제어하기” 강의는 무료인가요?
네 — “매개변수로 모델 동작 제어하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Engineering Academy 강의 전체를 잠금 해제할 수 있습니다. AI Engineering Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“매개변수로 모델 동작 제어하기”에서 뭘 배우나요?
temperature, max_tokens, top_p를 조정해 출력의 스타일, 길이, 창의성이 어떻게 달라지는지 확인하고, 사용 사례에 맞는 설정을 선택합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Engineering Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
AI Engineering Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 AI Engineering Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“매개변수로 모델 동작 제어하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 AI Engineering Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 AI Engineering Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Python 환경 설정하기
- 채팅 완성 엔드포인트
- 매개변수로 모델 동작 제어하기
- 오류 처리와 요청 한도