聊天完成
透過統一 API 使用各種 AI 模型建立對話式回應。
建立聊天完成
POST https://aiberm.com/v1/chat/completions
1curl https://aiberm.com/v1/chat/completions \2-H "Content-Type: application/json" \3-H "Authorization: Bearer YOUR_API_KEY" \4-d '{5 "model": "gpt-4",6 "messages": [7 {"role": "system", "content": "You are a helpful assistant."},8 {"role": "user", "content": "What is the capital of France?"}9 ],10 "temperature": 0.711}'請求參數
| 參數 | 類型 | 必填 | 說明 |
|---|---|---|---|
model | string | 是 | 要使用的模型 ID |
messages | array | 是 | 訊息物件陣列 |
temperature | number | 否 | 取樣溫度 (0-2)。預設值:1 |
max_tokens | integer | 否 | 產生的最大 token 數 |
top_p | number | 否 | 核取樣參數 |
stream | boolean | 否 | 是否串流傳輸回應 |
訊息角色
訊息必須包含 role 和 content:
- system - 設定助手的行為/個性
- user - 來自最終使用者的訊息
- assistant - AI 的先前回應
串流回應
啟用串流傳輸以增量接收回應:
1from openai import OpenAI2 3client = OpenAI(4 api_key="YOUR_API_KEY",5 base_url="https://aiberm.com/v1"6)7 8stream = client.chat.completions.create(9 model="gpt-4",10 messages=[{"role": "user", "content": "Tell me a story"}],11 stream=True12)13 14for chunk in stream:15 if chunk.choices[0].delta.content:16 print(chunk.choices[0].delta.content, end="")最佳實務
最佳化您的請求
- 設定
max_tokens以限制成本 - 使用適當的
temperature值(較低用於事實性,較高用於創意性) - 包含系統訊息以引導行為
- 串流傳輸回應以獲得更好的使用者體驗
注意
注意每個模型的 token 限制。較長的對話可能需要對話歷史紀錄管理。