跳轉到主要內容
LiteLLM 為 100 多家 LLM 供應商提供統一的 Python API。CometAPI 已原生支援——使用 cometapi/ 前綴即可透過 CometAPI 的模型目錄路由請求。

先決條件

  • Python 3.6+
  • 擁有啟用中 API 金鑰的 CometAPI 帳戶 — 在此取得
1

安裝 LiteLLM

pip install litellm
2

設定您的 API 金鑰

將 API 金鑰設為環境變數(建議)或直接內嵌傳入:
import os
from litellm import completion

# Recommended: environment variable
os.environ["COMETAPI_KEY"] = "<COMETAPI_KEY>"

# Alternative: pass inline
api_key = "<COMETAPI_KEY>"
使用環境變數可避免在腳本中硬編碼敏感憑證。
3

發出 completion 呼叫

使用 cometapi/<model-name> 格式來指定模型。您可以透過環境變數傳入金鑰,或明確指定:
messages = [{"content": "Hello, how are you?", "role": "user"}]

# Method 1: environment variable (recommended)
response = completion(model="cometapi/your-model-id", messages=messages)

# Method 2: explicit API key
response = completion(model="cometapi/your-model-id", messages=messages, api_key=api_key)

print(response.choices[0].message.content)
4

非同步與串流呼叫

搭配 stream=True 使用 acompletion,以取得非阻塞的即時回應:
from litellm import acompletion
import asyncio, traceback

async def stream_call():
    try:
        response = await acompletion(
      model="cometapi/your-model-id",
            messages=[{"content": "Hello, how are you?", "role": "user"}],
            stream=True,
        )
        async for chunk in response:
            print(chunk)
    except Exception:
        print(f"Error: {traceback.format_exc()}")

asyncio.run(stream_call())
  • 模型格式:CometAPI 模型使用前綴 cometapi/<model-name>,例如 cometapi/your-model-id。可用模型請參閱 CometAPI Models 頁面
  • 微調回應:LiteLLM 支援 temperaturemax_tokenstop_p——可將它們加入任何 completion() 呼叫中,例如 completion(..., temperature=0.7)
  • 錯誤處理:請使用 try/except 包裝呼叫,以捕捉無效金鑰錯誤或網路問題。
  • 安全性:切勿將 API 金鑰提交到版本控制。請使用環境變數或祕密管理工具。
  • 速率限制:請在 CometAPI 主控台 監控使用情況。
  • 更多文件LiteLLM 文件CometAPI 快速開始