> ## Documentation Index
> Fetch the complete documentation index at: https://apidoc.cometapi.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 將 LiteLLM 與 CometAPI 搭配使用

> 使用本指南透過設定 base URL、API key，以及 model 或 provider 選項來配置 LiteLLM 與 CometAPI。

LiteLLM 為 100 多個 LLM 提供者提供統一的 Python API。CometAPI 原生支援此整合——使用 `cometapi/` 前綴即可透過 CometAPI 的模型目錄路由請求。

## 先決條件

* Python 3.6+
* 具有有效 API key 的 CometAPI 帳戶 — [在這裡取得](https://www.cometapi.com/console/token)

<Steps>
  <Step title="安裝 LiteLLM">
    ```bash theme={null}
    pip install litellm
    ```
  </Step>

  <Step title="設定您的 API key">
    將 API key 設為環境變數（建議）或直接內嵌傳入：

    ```python theme={null}
    import os
    from litellm import completion

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

    # Alternative: pass inline
    api_key = "<COMETAPI_KEY>"
    ```

    <Note>
      使用環境變數可避免在腳本中硬編碼敏感憑證。
    </Note>
  </Step>

  <Step title="發出補全呼叫">
    使用 `cometapi/<model-name>` 格式來指定模型。您可以透過環境變數傳入金鑰，或明確指定：

    ```python theme={null}
    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)
    ```
  </Step>

  <Step title="非同步與串流呼叫">
    使用 `acompletion` 搭配 `stream=True` 以取得非阻塞、即時回應：

    ```python theme={null}
    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())
    ```
  </Step>
</Steps>

<AccordionGroup>
  <Accordion title="提示與疑難排解">
    * **模型格式**：CometAPI 模型使用前綴 `cometapi/<model-name>`，例如 `cometapi/your-model-id`。可用模型請參閱 [CometAPI Models 頁面](/zh-Hant/overview/models)。
    * **微調回應**：LiteLLM 支援 `temperature`、`max_tokens` 和 `top_p` — 您可以將它們加入任何 `completion()` 呼叫中，例如 `completion(..., temperature=0.7)`。
    * **錯誤處理**：請用 `try/except` 包裝呼叫，以攔截無效金鑰錯誤或網路問題。
    * **安全性**：切勿將 API key 提交到版本控制。請使用環境變數或 secrets manager。
    * **速率限制**：請在 [CometAPI console](https://www.cometapi.com/console) 中監控使用量。
    * **更多文件**：[LiteLLM documentation](https://docs.litellm.ai/docs/) — [CometAPI 快速開始](/zh-Hant/overview/quick-start)
  </Accordion>
</AccordionGroup>

<script type="application/ld+json">
  {`
    {
    "@context": "https://schema.org",
    "@graph": [
      {
        "@type": "HowTo",
        "@id": "https://apidoc.cometapi.com/integrations/litellm#howto",
        "name": "將 LiteLLM 與 CometAPI 搭配使用",
        "description": "使用本指南，透過設定 base URL、API key，以及模型或 provider 選項來配置 LiteLLM 與 CometAPI。",
        "step": [
          {
            "@type": "HowToStep",
            "@id": "https://apidoc.cometapi.com/integrations/litellm#step-1",
            "position": 1,
            "name": "安裝 LiteLLM",
            "text": "完成「將 LiteLLM 與 CometAPI 搭配使用」指南中的「安裝 LiteLLM」步驟。"
          },
          {
            "@type": "HowToStep",
            "@id": "https://apidoc.cometapi.com/integrations/litellm#step-2",
            "position": 2,
            "name": "設定您的 API key",
            "text": "將您的 CometAPI API key 儲存在整合所使用的環境變數或設定欄位中。"
          },
          {
            "@type": "HowToStep",
            "@id": "https://apidoc.cometapi.com/integrations/litellm#step-3",
            "position": 3,
            "name": "發出補全呼叫",
            "text": "完成「將 LiteLLM 與 CometAPI 搭配使用」指南中的「發出補全呼叫」步驟。"
          },
          {
            "@type": "HowToStep",
            "@id": "https://apidoc.cometapi.com/integrations/litellm#step-4",
            "position": 4,
            "name": "非同步與串流呼叫",
            "text": "完成「將 LiteLLM 與 CometAPI 搭配使用」指南中的「非同步與串流呼叫」步驟。"
          }
        ]
      },
      {
        "@type": "BreadcrumbList",
        "itemListElement": [
          {
            "@type": "ListItem",
            "position": 1,
            "name": "CometAPI 文件",
            "item": "https://apidoc.cometapi.com/"
          },
          {
            "@type": "ListItem",
            "position": 2,
            "name": "整合",
            "item": "https://apidoc.cometapi.com/integrations"
          },
          {
            "@type": "ListItem",
            "position": 3,
            "name": "將 LiteLLM 與 CometAPI 搭配使用",
            "item": "https://apidoc.cometapi.com/integrations/litellm"
          }
        ]
      }
    ]
    }
    `}
</script>
