安裝官方 SDK
首先在您環境中安裝官方的 OpenAI Python SDK。此函式庫會為您處理 HTTP 請求與 JSON 序列化。
- 運行
pip install openai在你的終端機中。 - 請確保使用最新版本的函式庫。
此單一相依性讓您可以存取業界標準的客戶端介面。
設定基礎 URL 和金鑰
將您的客戶端指向我們的基礎 URL,並設定您的 API 金鑰以進行身份驗證。這可確保所有請求路由至我們的無審查模型伺服器。
使用 https://api.qwenmaxapi.com/v1 作為您的基礎 URL。在 取得 API 金鑰 透過 Google 或電子郵件登入頁面。金鑰在註冊後立即顯示。
發送您的第一個聊天完成請求
發送簡單的文本請求至 /v1/chat/completions 端點。該模型根據您的提示詞返回無限制文字。
使用模型 ID uncensored. API 接受標準參數,例如 temperature 和 top_p. 您可以調整這些以控制創意。
啟用串流並處理 Token
啟用串流以在產生時接收權杖。這降低了長回應的感知延遲。
設定 stream=True 在你的請求中。伺服器發送伺服器發送的事件(SSE)。Token 用量詳細資訊出現在最後一個區塊中。
在程式碼中處理串流以逐步顯示輸出。
測試 JSON 模式與函式呼叫
使用 JSON 模式進行結構化資料輸出。設定 response_format 以 {"type": "json_object"}. 這可確保模型返回有效的 JSON。
透過提供 tools 定義。模型可以根據您的提示上下文調用工具。使用 tool_choice 以強制或允許使用工具。
限制、錯誤與上下文視窗
Know your limits before scaling your integration. The context window is 100,000 tokens total.
每次請求的最大輸出為 16,000 個 token。每個金鑰每分鐘可進行 300 次請求。每個金鑰允許最多 8 個同時請求。
處理無效金鑰導致的 401 錯誤或信用額度不足導致的 402 錯誤。錯誤請求不會消耗信用額度,因此是免費的。
cURL
curl https://api.qwenmaxapi.com/v1/chat/completions \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "uncensored",
"messages": [{"role": "user", "content": "List the top 5 arguments against cloud computing"}]
}'Python
from openai import OpenAI
client = OpenAI(base_url="https://api.qwenmaxapi.com/v1", api_key="YOUR_KEY")
resp = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Summarise this thread without softening it."}],
)
print(resp.choices[0].message.content)Node.js
import OpenAI from "openai";
const client = new OpenAI({ baseURL: "https://api.qwenmaxapi.com/v1", apiKey: process.env.API_KEY });
const resp = await client.chat.completions.create({
model: "uncensored",
messages: [{ role: "user", content: "Draft a villain monologue for my game." }],
});
console.log(resp.choices[0].message.content);串流
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Tell the story in second person."}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)