التحكم في سلوك النموذج باستخدام المعلمات
جرّبوا temperature وmax_tokens وtop_p لمعرفة كيفية تغييرها لأسلوب المخرجات وطولها وإبداعها، ثم اختاروا الإعدادات المناسبة لحالة الاستخدام الخاصة بكم.
التحكم في سلوك النموذج باستخدام المعلمات درس مجاني في AI Engineering Academy على CoddyKit. هذا هو الدرس 3 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في AI Engineering Academy، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة AI Engineering Academy 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
The Core Parameters That Matter
A handful of parameters shape your output the most: temperature, max_tokens, top_p, frequency_penalty, and presence_penalty. Master these five and you control the model.
Temperature: Controlling Randomness
Temperature controls randomness. Near 0, the model picks the safest word and stays consistent — great for facts. Around 0.7-1.0, it gets varied and creative. See the code.
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: Controlling Response Length
max_tokens caps how long the reply can get — a safety limit, not a target. Too low and answers get cut off; too high wastes money and time. Add a buffer and watch 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: Nucleus Sampling
top_p is another randomness dial: it samples only from the top tokens that add up to top_p of the probability. Tip: tune either temperature or top_p, not both at once.
# 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: Reducing Repetition
frequency_penalty discourages the model from repeating the same words, scaling with how often they appear. Reach for it when long answers get repetitive — try 0.3 to 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: Encouraging Topic Diversity
presence_penalty nudges the model toward new topics: it penalizes any word that already appeared, even once. Great for brainstorming where you want fresh, varied ideas.
# 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 Sequences: Custom Stopping Points
The stop parameter lists strings that halt generation the moment they appear (and they're left out). Stop at a newline to grab a clean single-line answer. See the code.
# 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: Reproducible Outputs
The seed parameter makes output reproducible: same seed plus temperature 0 gives the same reply. Great for testing — just watch the system_fingerprint for backend changes.
# 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)Choosing Parameters for Common Use Cases
Skip the guesswork with quick presets: temperature 0 for classification, 0.2 for factual Q&A, 0.8-1.0 for creative writing. Start there, then adjust to your task. See the code.
# 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: Understanding Model Confidence
logprobs returns how confident the model was in each token, plus alternatives it weighed. Low confidence on a fact is a hallucination warning — useful for safer systems.
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%}')Testing Parameter Effects Systematically
Don't guess parameters — test them. Build a small grid search that runs the same prompt across combos and scores each. That turns tuning from art into engineering. See the code.
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
})Quick Check
Test your understanding of AI Engineering concepts from this lesson.
Lesson Recap
You learned to steer the model: temperature sets randomness, max_tokens caps length (watch finish_reason!), and the penalties cut repetition and add variety. Next: error handling.
الأسئلة الشائعة
هل درس «التحكم في سلوك النموذج باستخدام المعلمات» مجاني؟
نعم — نص درس «التحكم في سلوك النموذج باستخدام المعلمات» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة AI Engineering Academy، انتقل إلى CoddyKit PRO. تتضمن دورة AI Engineering Academy 4 دروس في المجموع.
ماذا ستتعلم في «التحكم في سلوك النموذج باستخدام المعلمات»؟
جرّبوا temperature وmax_tokens وtop_p لمعرفة كيفية تغييرها لأسلوب المخرجات وطولها وإبداعها، ثم اختاروا الإعدادات المناسبة لحالة الاستخدام الخاصة بكم. تتمرن على AI Engineering Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ AI Engineering Academy؟
لا تُشترط خبرة سابقة. AI Engineering Academy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 4.
كم من الوقت يستغرق درس «التحكم في سلوك النموذج باستخدام المعلمات»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس AI Engineering Academy هذا؟
نعم. كل درس في AI Engineering Academy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- إعداد بيئة Python الخاصة بكم
- نقطة نهاية إكمالات المحادثة
- التحكم في سلوك النموذج باستخدام المعلمات
- معالجة الأخطاء وحدود معدل الطلبات