繁中 ▾
取得 API 金鑰

Mistral API Python 範例:使用 OpenAI SDK:使用 OpenAI SDK

更新於

可直接複製的 Python 程式碼,適用於託管的 OpenAI 相容端點。每個程式碼片段均使用官方的 openai 套件並更改 Base URL 運作。

重點

  • 安裝 openai 套件,設定基礎 URL 與你的金鑰,並使用模型 ID uncensored。
  • 串流輸出、JSON 模式與函式呼叫可透過標準 SDK 參數運作。
  • 處理 HTTP 429 錯誤並進行短暫重試,並讓完整金鑰的並行請求保持在 8 或以下。
  • 一般短聊天請求的成本僅為幾分之一美分,費率為每 1M token 輸入 $0.15,輸出 $0.50。
等距終端機串流聊天對話框進入資料區塊,代表 Python 聊天 API 範例

簡短版本

如果你搜尋了 mistral api python example,這裡先提供誠實的說明。此網站並非運行官方的 Mistral API。它託管單一開放權重模型,針對合法成人用途調整為能回答且無內容拒絕的回應模式,並透過 OpenAI 相容端點提供服務。由於協定為 OpenAI 標準,你熟悉的 Python 程式碼即可使用:安裝 openai 套件,指向新的基礎 URL,並發送聊天請求。

最小程式如下。請將金鑰替換為你從 API 金鑰頁面取得的金鑰。模型 ID 固定為uncensored。

from openai import OpenAI

client = OpenAI(
    base_url="https://api.mistraluncensored.top/v1",
    api_key="YOUR_KEY",
)

resp = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Write a two-line poem about a lighthouse."}],
)
print(resp.choices[0].message.content)

這就是完整的整合。本文其餘內容僅是這些程式碼的變體:串流輸出、強制 JSON、呼叫工具、禮貌重試,以及同時執行多個請求。

安裝與設定客戶端

你需要 Python 3.8 或更新版本,以及一個套件:pip install openai。任何最新版本的 SDK 皆可運作,因為端點僅使用標準聊天補全路由。伺服器上有兩種方法:POST /v1/chat/completions 與 GET /v1/models。沒有嵌入路由或影像路由,因此不要嘗試透過同一個客戶端呼叫這些功能。

請將金鑰保留在原始碼檔案之外。從環境變數讀取金鑰並傳入。下方的範例也會列出可用模型,這同時也可作為連線測試。

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.mistraluncensored.top/v1",
    api_key=os.environ["API_KEY"],
)

# GET /v1/models: should list the model ID "uncensored"
for m in client.models.list():
    print(m.id)

# The model ID you send in chat requests
MODEL = "uncensored"

在已匯出 API_KEY 的終端機中執行一次。如果模型列表成功列印,表示您的 Base URL 和金鑰正確。如果呼叫立即失敗,常見原因包括金鑰中有多餘的空格、Base URL 缺少 /v1 後綴,或是餘額為空。回應標頭包含 X-Balance-USD,因此您可以在不開啟儀表板的情況下讀取剩餘額度。如果您想記錄這些標頭,SDK 會透過 client.chat.completions.with_raw_response.create(...) 暴露標頭。

帶有系統提示詞的對話

聊天模型為無狀態。伺服器不會記住先前的對話輪次,因此你的程式碼需保留訊息列表並在每次請求時傳送。一個小型類別可使程式碼更整潔。

from openai import OpenAI

client = OpenAI(base_url="https://api.mistraluncensored.top/v1", api_key="YOUR_KEY")

class Chat:
    def __init__(self, system):
        self.messages = [{"role": "system", "content": system}]

    def say(self, text, **kw):
        self.messages.append({"role": "user", "content": text})
        r = client.chat.completions.create(
            model="uncensored",
            messages=self.messages,
            temperature=0.8,
            **kw,
        )
        reply = r.choices[0].message.content
        self.messages.append({"role": "assistant", "content": reply})
        return reply

bot = Chat("You are a blunt editor for adult fiction writers. Keep answers short.")
print(bot.say("Give me three ways to open a scene in a night train."))
print(bot.say("Expand the second one."))

temperature、top_p、stop、seed等採樣參數及頻率與存在懲罰會傳遞給模型。seed搭配低溫度可產生可重複的輸出供測試,但你不應將其視為跨模型更新時的絕對保證。

上下文視窗為 100,000 token,包含提示詞與補全。長對話歷史最終會觸及上限,請修剪舊輪次或摘要。max_tokens為選填,因為補全可使用視窗剩餘空間。若需限制每次呼叫成本,請設定上限。

串流接收到達的 token

互動工具需要即時顯示文字。請傳遞stream=True並進行迭代。伺服器會發送 Server-Sent Events,SDK 會為你解析,並在串流末端傳送用量區塊。

from openai import OpenAI

client = OpenAI(base_url="https://api.mistraluncensored.top/v1", api_key="YOUR_KEY")

stream = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Describe a storm over a harbor in 120 words."}],
    stream=True,
    stream_options={"include_usage": True},
)

for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if getattr(chunk, "usage", None):
        print("\n\ntokens:", chunk.usage.prompt_tokens, chunk.usage.completion_tokens)

生產環境程式需注意:串流請求會佔用並行槽位直到串流結束。若開啟串流卻停止讀取,槽位會保持忙碌。請務必讀取完畢,或在使用者取消時以stream.close()明確關閉。

JSON 模式與工具呼叫

JSON 模式

程式需解析回覆時,請以response_format開啟 JSON 模式。並在提示詞告知模型需要 JSON,以及預期鍵名。此設定保證為 JSON 物件而非特定結構,請在程式碼中驗證欄位。

import json
from openai import OpenAI

client = OpenAI(base_url="https://api.mistraluncensored.top/v1", api_key="YOUR_KEY")

r = client.chat.completions.create(
    model="uncensored",
    response_format={"type": "json_object"},
    messages=[
        {"role": "system", "content": "Reply with JSON: {\"title\": str, \"tags\": [str]}"},
        {"role": "user", "content": "Suggest a title and tags for a noir story set in a flooded city."},
    ],
)
data = json.loads(r.choices[0].message.content)
print(data["title"], data["tags"])

工具

工具呼叫遵循 OpenAI 格式:宣告tools,可選設定tool_choice,當模型要求時自行執行函式,然後以role: "tool"將輸出作為訊息回傳。

import json
from openai import OpenAI

client = OpenAI(base_url="https://api.mistraluncensored.top/v1", api_key="YOUR_KEY")

tools = [{
    "type": "function",
    "function": {
        "name": "roll_dice",
        "description": "Roll a die with the given number of sides",
        "parameters": {
            "type": "object",
            "properties": {"sides": {"type": "integer"}},
            "required": ["sides"],
        },
    },
}]

messages = [{"role": "user", "content": "Roll a 20-sided die for my character."}]
first = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
call = first.choices[0].message.tool_calls[0]
sides = json.loads(call.function.arguments)["sides"]

messages.append(first.choices[0].message)
messages.append({"role": "tool", "tool_call_id": call.id, "content": "17"})
final = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
print(final.choices[0].message.content)

實際程式中,請以函式結果取代硬編碼的"17"。在索引前請檢查tool_calls是否非空,因為模型可能以純文字回答。

速率限制、重試與非同步批次

完整金鑰允許 8 個並行請求與每分鐘 300 個請求。試用金鑰允許 2 個並行與每分鐘 60 個請求。超過限制會收到 HTTP 429。錯誤碼會告知是哪一種:rate_limited表示每分鐘請求過多,concurrency表示同時請求過多。伺服器在暫時過載時也會回傳 429 並附帶Retry-After: 5標頭。

openai SDK 預設會重試幾次,但在批次處理工作時,明確控制會更好。下方的模式使用根據你的金鑰調整大小的訊號量與小型重試包裝函式。

import asyncio
from openai import AsyncOpenAI, RateLimitError

client = AsyncOpenAI(base_url="https://api.mistraluncensored.top/v1", api_key="YOUR_KEY", max_retries=0)
sem = asyncio.Semaphore(8)  # use 2 on a trial key

async def ask(prompt, tries=4):
    async with sem:
        for attempt in range(tries):
            try:
                r = await client.chat.completions.create(
                    model="uncensored",
                    messages=[{"role": "user", "content": prompt}],
                    max_tokens=300,
                )
                return r.choices[0].message.content
            except RateLimitError:
                await asyncio.sleep(5 * (attempt + 1))
        return None

async def main():
    prompts = [f"Give one story idea about harbor number {i}." for i in range(40)]
    results = await asyncio.gather(*(ask(p) for p in prompts))
    print(sum(r is not None for r in results), "done")

asyncio.run(main())

失敗或遭拒的請求不會收費,因此重試迴圈不會讓你重複付費。主體限制為 8 MB,僅在你將非常大的文件貼入提示詞時才有意義。

呼叫的成本

定價為預付額度按用量付費:每 1M 輸入 token 為 $0.15,每 1M 輸出 token 為 $0.50。每個回應上的用量物件會提供計數,因此你可以在同一個腳本中計算帳單。

# endpoint https://api.mistraluncensored.top/v1, model "uncensored"
def cost(prompt_tokens, completion_tokens):
    return prompt_tokens * 0.15 / 1_000_000 + completion_tokens * 0.50 / 1_000_000

print(cost(2_000, 500))      # 0.00055
print(cost(50_000, 2_000))   # 0.0085

請手動檢查算術。一次包含 2,000 個輸入 token 與 500 個輸出 token 的聊天,輸入成本為 2,000 × $0.15 / 1M = $0.0003,輸出成本為 500 × $0.50 / 1M = $0.00025,總計 $0.00055。一次耗盡一半視窗的重度請求(50,000 輸入與 2,000 輸出)成本為 $0.0075 + $0.001 = $0.0085。一萬次上述的小型請求總計為 $5.50。

新帳戶可在金鑰頁面一鍵領取 $0.50 試用額度,有效期 7 天且無需綁卡。這大約可執行 900 次上述小型呼叫。完整儲值起價 $20,$50 起贈 5%、$100 起贈 10%、$200 起贈 15%,支援加密貨幣付款。定價頁面有完整表格,文件列出所有參數。提示詞不用於訓練。

若要快速了解此服務的範圍與限制,請閱讀 Mistral API 說明。最後一點:涉及未成年人的性內容會直接被封鎖,無論其語境為何。

01

問答

這是官方的 Mistral Python SDK 嗎?

不是。你使用標準的 openai 套件,但設定不同的基礎 URL。此服務是一項獨立託管單一開放權重模型的服務,並非 Mistral 或其他廠商的官方 API。

我要傳送的模型名稱是什麼?

始終為 uncensored。你可以透過使用 API 金鑰呼叫 GET /v1/models 來確認。

我可以改用 LangChain 或 LlamaIndex 而不是原始 SDK 嗎?

可以,任何允許你設定 OpenAI 相容基礎 URL 和 API 金鑰的客戶端都能運作。使用相同的基礎 URL 與模型 ID uncensored。

為什麼會收到 429 錯誤?

你觸發了每分鐘限制(code rate_limited)、並行限制(code concurrency),或遇到 5 秒 Retry-After 的暫時過載。請等待並重試,並讓完整 API 金鑰的並行請求保持在 8 以內,或試用 API 金鑰保持在 2 以內。

只差一張表單,即可取得金鑰

建立帳號、複製 API 金鑰、更改基礎 URL。這就是整個設定過程。

取得 API 金鑰