在這篇教學中,我們將學習如何在Python中使用OpenAI API,包括標準版API和Azure OpenAI服務。這個教學適合已有基本Python知識的讀者。
- 建立環境
首先,安裝必要的套件:
pip install openai
2. 設定API金鑰
要使用OpenAI API,需要有API金鑰。我們可以從JSON檔案讀取金鑰:
import os
import json
from openai import OpenAI, AzureOpenAI
# 讀取API金鑰
dir_api_key = r"你的金鑰路徑"
basename_api_key = "api_key.json"
path_api_key = os.path.join(dir_api_key, basename_api_key)
with open(path_api_key, "r", encoding="utf-8") as f:
api_key_list = json.load(f)
AzureOpenAI除了api_key以外,
還需要端點網址,model不能替換:
- 配置客戶端
OpenAI提供兩種API服務: 標準版和Azure版。以下是如何設定:
# 配置選項
config = {"AzureOpenAI": True} # True使用Azure版,False使用標準版
if config.get("AzureOpenAI") == True:
# 使用Azure OpenAI
api_key = api_key_list[0].get("api_key")
model_name = api_key_list[0].get("model") # 例如: 'gpt-4'
endpoint = api_key_list[0].get("Target URI") # Azure端點
api_version = "2024-12-01-preview"
client = AzureOpenAI(
api_version=api_version,
api_key=api_key,
azure_endpoint=endpoint
)
else:
# 使用標準OpenAI API
api_key = api_key_list[1].get("api_key")
model_name = "gpt-4.1-nano" # 可自選模型
client = OpenAI(api_key=api_key)
AzureOpenAI比起標準openAI
除了需要api_key,
還多了api_version, azure_endpoint
AzureOpenAI?
4. 發送請求
現在可以向API發送請求:
response = client.chat.completions.create(
model=model_name,
messages=[
{"role": "user", "content": "Hello, how are you?"}
],
temperature=0.2,
max_completion_tokens=500
)
# 獲取回應內容
answer = response.choices[0].message.content
print(answer)
client.chat.completions.create?
輸出結果:
5. 追蹤用量和成本
OpenAI API是按使用量收費的,我們可以追蹤花費:
# 獲取token使用量
input_tokens = response.usage.prompt_tokens
output_tokens = response.usage.completion_tokens
# 計算費用 (美元)
price_per_million_input = 0.10
price_per_million_output = 0.40
input_cost = (input_tokens / 10**6) * price_per_million_input
output_cost = (output_tokens / 10**6) * price_per_million_output
total_cost = input_cost + output_cost
print(f"總花費: ${total_cost:.8f}")
print(f"輸入tokens: {input_tokens}, 花費: ${input_cost:.8f}")
print(f"輸出tokens: {output_tokens}, 花費: ${output_cost:.8f}")
輸出結果:
費用可以參考:
https://platform.openai.com/docs/pricing
"""# https://platform.openai.com/docs/pricing
Model Input Cached input Output
gpt-5 $1.25 $0.125 $10.00
gpt-5-mini $0.25 $0.025 $2.00
gpt-5-nano $0.05 $0.005 $0.40
"""
- 批次處理多筆資料
處理多筆資料時,建議逐筆處理並保存結果:
import time
json_data = [{"問題1": "內容1"}, {"問題2": "內容2"}] # 你的資料
results = []
for i, item in enumerate(json_data):
# 發送請求
response = client.chat.completions.create(
model=model_name,
messages=[
{"role": "user", "content": f"請回答: {json.dumps(item, ensure_ascii=False)}"}
]
)
# 獲取回應
result = item.copy() # 複製原始資料
result["回答"] = response.choices[0].message.content
results.append(result)
# 保存中間結果
with open("results_temp.json", "w", encoding="utf-8") as f:
json.dump(results, f, ensure_ascii=False, indent=4)
print(f"已處理 {i+1}/{len(json_data)} 筆資料")
# 完成後重命名
os.rename("results_temp.json", "results_final.json")
總結
使用OpenAI API時的要點:
- 選擇適合的API版本 (標準版或Azure版)
- 正確設定客戶端
- 追蹤用量和成本
- 逐筆處理並保存中間結果,避免資料遺失
這個簡化的教學應該能幫助你快速開始使用OpenAI API。
如有需要,可以進一步調整參數如temperature和top_p等來獲得不同的回應效果。
推薦hahow線上學習python: https://igrape.net/30afN