code/01-llm-basics/temperature_api.py
38 行 · 1.3 KBコードと実行結果は実際に動かしたときのまま載せているため、コメントと出力は中国語です。
"""同一个问题,在三种温度下各问 20 次,数一数有多少种不同的回答。
会发出 60 次请求,关掉了思考模式,按 2026 年 9 月的价格总共花费不到 0.01 美元。
"""
import os
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from openai import OpenAI
client = OpenAI(
api_key=os.environ["LLM_API_KEY"],
base_url=os.environ.get("LLM_BASE_URL", "https://api.deepseek.com"),
)
MODEL = os.environ.get("LLM_MODEL", "deepseek-flash")
QUESTION = "用一句话写一个关于秋天的比喻,不超过十五个字,只输出这句话。"
def ask(temperature):
response = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": QUESTION}],
temperature=temperature,
# 思考模式下 temperature 不起作用,所以要关掉思考
extra_body={"thinking": {"type": "disabled"}},
)
return response.choices[0].message.content.strip()
for t in [0, 0.7, 1.3]:
# 10 个线程同时发请求,省点时间
with ThreadPoolExecutor(10) as pool:
answers = list(pool.map(ask, [t] * 20))
counts = Counter(answers)
print(f"temperature={t}: 20 次里有 {len(counts)} 种")
for text, n in counts.most_common(5):
print(f" {n:2d}× {text}")