> ## 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.

# 在 CometAPI 中使用 LiteLLM

> 使用本指南通过设置 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>` 格式来指定模型。你可以通过环境变量传递 key，或显式传入：

    ```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="异步和流式调用">
    使用带有 `stream=True` 的 `acompletion` 来获得非阻塞、实时响应：

    ```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-Hans/overview/models)。
    * **微调响应**：LiteLLM 支持 `temperature`、`max_tokens` 和 `top_p` —— 可将它们添加到任何 `completion()` 调用中，例如 `completion(..., temperature=0.7)`。
    * **错误处理**：将调用包装在 `try/except` 中，以捕获无效 key 错误或网络问题。
    * **安全性**：不要将 API key 提交到版本控制中。请使用环境变量或密钥管理器。
    * **速率限制**：在 [CometAPI 控制台](https://www.cometapi.com/console) 中监控使用情况。
    * **更多文档**：[LiteLLM 文档](https://docs.litellm.ai/docs/) —— [CometAPI 快速开始](/zh-Hans/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 以及模型或提供商选项来配置 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>
