繁中 ▾
取得 API 金鑰

首頁指南

Llama API Python 設定,適用於 OpenAI 相容端點

設定 llama api python 很簡短,因為大多數託管的 Llama 風格服務都採用 OpenAI 格式。安裝 openai 套件,設定 Base URL 和金鑰,然後呼叫 chat completions。以下程式碼對任何相容的提供者都通用,且已在該端點以模型 <code>uncensored</code> 進行測試。

更新於

蛇形電纜連接伺服器立方體,同時串流輸出聊天氣泡
閘門允許有限數量的發光資料封包通過,說明 API 並行請求與速率限制
重點
  • 使用 openai 套件,base_url=https://api.llamaapis.com/v1 且模型為 uncensored。
  • 串流輸出、工具呼叫與 JSON 模式使用標準 OpenAI 參數。
  • 在 HTTP 429 時重試並讀取 Retry-After 標頭。
  • 透過更改三個設定,相同的腳本也能在其他相容的提供者上運作。
llamaapis.com

安裝並進行首次呼叫

Python 3.9 或更新版本即可。安裝 SDK 並將金鑰儲存在環境變數中,以免其進入版本控制。

pip install openai
export LLM_API_KEY="YOUR_KEY"
# base URL: https://api.llamaapis.com/v1   model: uncensored

接著是第一個請求:

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.llamaapis.com/v1",
    api_key=os.environ["LLM_API_KEY"],
)

resp = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "You are a concise assistant."},
        {"role": "user", "content": "Explain what a token is in two sentences."},
    ],
)
print(resp.choices[0].message.content)
print(resp.usage)

從 API 金鑰頁面取得金鑰。新用戶可以一鍵領取 $0.50 的免費試用額度,有效期 7 天且無需信用卡。此服務是單一開放權重模型的純文字 OpenAI 相容端點。它並非 Meta 或其他模型供應商的官方 API,因此模型名稱為 uncensored 而非 Llama 版本字串。

保持對話:角色與歷史

API 是無狀態的。要維持對話,每次都要傳送完整的訊息列表,並將每個回覆附加到列表中。

import os
from openai import OpenAI

client = OpenAI(base_url="https://api.llamaapis.com/v1", api_key=os.environ["LLM_API_KEY"])

history = [{"role": "system", "content": "You are a patient writing coach."}]

def chat(user_text):
    history.append({"role": "user", "content": user_text})
    r = client.chat.completions.create(model="uncensored", messages=history, temperature=0.7)
    reply = r.choices[0].message.content
    history.append({"role": "assistant", "content": reply})
    return reply

print(chat("Give me a prompt for a ghost story."))
print(chat("Make it set on a ferry."))

上下文視窗為 100,000 token,包含提示詞與補全,可支援長對話歷史。你仍須為每一輪的每個輸入 token 付費,因此當訊息列表變長時,請截斷或摘要舊訊息。費用計算很簡單:輸入每 1M token 費用為 $0.15,輸出每 1M token 費用為 $0.50。

Python 串流輸出

傳遞 stream=True 並進行迭代。加入 stream_options 以在最後一個資料片段取得 token 用量。

import os
from openai import OpenAI

client = OpenAI(base_url="https://api.llamaapis.com/v1", api_key=os.environ["LLM_API_KEY"])

stream = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Write a short scene at a night market."}],
    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 chunk.usage:
        print("\n", chunk.usage)

最後一個資料塊的 choices 列表為空,這就是迴圈先檢查列表的原因。請記住,串流請求會佔用其並行請求槽位直到結束,因此若使用者離開,請關閉串流。

工具與 JSON 模式

進行函式呼叫時,在 tools 描述你的函式,檢查 message.tool_calls,執行函式並用 role: "tool" 回傳輸出:

import json, os
from openai import OpenAI

client = OpenAI(base_url="https://api.llamaapis.com/v1", api_key=os.environ["LLM_API_KEY"])

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get the weather for a city",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    },
}]
messages = [{"role": "user", "content": "What is the weather in Lisbon?"}]
first = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
msg = first.choices[0].message

if msg.tool_calls:
    messages.append(msg)
    for call in msg.tool_calls:
        args = json.loads(call.function.arguments)
        result = {"city": args["city"], "temp_c": 21}  # your real lookup here
        messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})
    final = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
    print(final.choices[0].message.content)

對於純結構化輸出,設定 response_format={"type": "json_object"} 並在提示詞中說明需要 JSON。在 try 區塊內用 json.loads 解析結果,因為模型有時會回傳無效 JSON。

重試與速率限制

完整金鑰允許 8 個併行請求和每分鐘 300 個請求;試用金鑰允許 2 個和 60 個。若超過限制,API 會回傳 HTTP 429 並附帶程式碼 rate_limited 或 concurrency。在暫時過載時也會回傳 429 並附帶 Retry-After: 5。SDK 會拋出 RateLimitError,因此請這樣包裝呼叫:

import os, time
from openai import OpenAI, RateLimitError

client = OpenAI(base_url="https://api.llamaapis.com/v1", api_key=os.environ["LLM_API_KEY"], max_retries=0)

def call_with_retry(messages, tries=4):
    for attempt in range(tries):
        try:
            return client.chat.completions.create(model="uncensored", messages=messages)
        except RateLimitError as e:
            if attempt == tries - 1:
                raise
            wait = int(e.response.headers.get("retry-after", 2 ** attempt))
            time.sleep(wait)

設定 max_retries=0 可關閉 SDK 內建的重試,讓你的重試邏輯成為唯一運作的重試。用量限制文章 有更多模式,包括用於限制併行呼叫的訊號量。

用於大量請求的非同步呼叫

對於批次工作,請使用非同步客戶端並將並行度限制在你的並行限制內,以免因超出限制而被 API 以 429 回應:

import asyncio, os
from openai import AsyncOpenAI

client = AsyncOpenAI(base_url="https://api.llamaapis.com/v1", api_key=os.environ["LLM_API_KEY"])
sem = asyncio.Semaphore(8)  # use 2 on a trial key

async def one(prompt):
    async with sem:
        r = await client.chat.completions.create(
            model="uncensored",
            messages=[{"role": "user", "content": prompt}],
        )
        return r.choices[0].message.content

async def main():
    prompts = [f"Give a name for fantasy town number {i}." for i in range(20)]
    for text in await asyncio.gather(*(one(p) for p in prompts)):
        print(text)

asyncio.run(main())

常見錯誤及其修正方法

  • 基本 URL 中缺少 /v1。 SDK 會自動附加 /chat/completions,因此若基本 URL 不含 /v1,通常會導致找不到資源錯誤。
  • 使用模型供應商名稱。諸如 Llama 版本的字串在此無效。傳送 uncensored。
  • 在最後一個串流資料片段讀取 choices[0]。該片段可能沒有 choices,因此請先檢查列表。
  • 遺忘歷史。 如果模型似乎遺忘了上一則訊息,你可能沒有將其附加到列表中。
  • 盲目解析工具參數。 將 json.loads 包裝在 try 區塊中,若失敗則回傳錯誤訊息作為工具結果,這通常能讓模型自行修正。
  • 空白回覆。 極小的 max_tokens 或提前觸發的停止序列會立即結束輸出。除錯時請移除兩者。

當發生異常時,請記錄 X-Request-Id 回應標頭。透過 SDK 的原始回應,client.chat.completions.with_raw_response.create(...) 可取得 X-Balance-USD 等標頭及速率限制標頭。

從程式碼檢查餘額

端點 GET /v1/balance 會回傳剩餘額度,且存在 OpenAI 風格的路由 /v1/dashboard/billing/credit_grants。在大量批次前進行小檢查,可避免工作因餘額耗盡而中途停止。

相同的程式碼、其他提供者與成本

由於格式共用,此程式碼可與任何相容服務運行。更改 base_url、金鑰和模型名稱,然後測試各供應商不同的參數。OpenAI 相容 API 伺服器 文章說明相容性的界限。

在此端點,使用 1,500 個輸入 token 和 400 個輸出 token 的呼叫成本為 1,500 x $0.15 / 1M + 400 x $0.50 / 1M = $0.000225 + $0.0002 = $0.000425。$0.50 的試用額度可涵蓋約 1,176 次此類呼叫。此後請從 $20 儲值至 $500;定價頁面 列出獎金。提示詞不用於訓練,失敗或拒絕的請求不收費。文件 涵蓋其餘內容。

問答

llamaapis.com
我需要哪個 Python 套件?

官方 openai 套件。將 base_url 設為 https://api.llamaapis.com/v1 並輸入金鑰建立客戶端,然後使用模型 ID uncensored。

相同的程式碼能與其他 Llama 風格的主機搭配運作嗎?

通常可以,只要該主機與 OpenAI 相容。更改 Base URL、金鑰和模型名稱,並檢查它支援哪些選用參數。

我如何在 Python 中串流輸出 token?

設定 stream=True 並遍歷區塊。加入 stream_options 並設定 include_usage,以便在結尾取得 token 計數。

遇到 429 錯誤時該怎麼辦?

若有提供 Retry-After 秒數,請等待該時間後再重試;否則請退避後重試。若程式碼涉及並行請求,請降低並行請求的數量。

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

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

取得 API 金鑰