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

# 将 LlamaIndex 与 CometAPI 一起使用

> 使用本指南通过设置 base URL、API key 以及 model 或 provider 选项来配置 LlamaIndex 与 CometAPI。

LlamaIndex 提供了 `CometLLM` 类，作为与 CometAPI 的一流集成。你可以使用它，通过 CometAPI 目录中的任意模型来驱动 RAG 流水线、智能体和 LLM 链。

## 前置条件

* Python 3.8+
* 一个拥有有效 API key 的 CometAPI 账户 —— [在这里获取](https://www.cometapi.com/console/token)

<Steps>
  <Step title="安装 LlamaIndex CometAPI 集成">
    ```bash theme={null}
    pip install llama-index-llms-cometapi llama-index
    ```
  </Step>

  <Step title="设置你的 API key">
    ```python theme={null}
    from llama_index.llms.cometapi import CometLLM
    import os

    os.environ["COMETAPI_KEY"] = "<COMETAPI_KEY>"
    api_key = os.getenv("COMETAPI_KEY")
    ```

    <Note>
      使用环境变量比在脚本中硬编码凭证更安全。
    </Note>
  </Step>

  <Step title="初始化模型并发起补全调用">
    ```python theme={null}
    from llama_index.core.llms import ChatMessage

    llm = CometLLM(
        api_key=api_key,
        max_tokens=256,
        context_window=4096,
        model="your-model-id",
    )

    # Chat call
    messages = [
        ChatMessage(role="system", content="You are a helpful assistant"),
        ChatMessage(role="user", content="Say 'Hi' only!"),
    ]
    resp = llm.chat(messages)
    print(resp)

    # Completion call
    resp = llm.complete("Who is Kaiming He?")
    print(resp)
    ```
  </Step>

  <Step title="启用流式输出">
    使用 `stream_chat` 或 `stream_complete` 进行实时分块输出：

    ```python theme={null}
    # Streaming chat
    message = ChatMessage(role="user", content="Tell me what ResNet is")
    for chunk in llm.stream_chat([message]):
        print(chunk.delta, end="")

    # Streaming completion
    for chunk in llm.stream_complete("Tell me about Large Language Models"):
        print(chunk.delta, end="")
    ```
  </Step>
</Steps>

<AccordionGroup>
  <Accordion title="提示与故障排查">
    * **模型**：请查看 [CometAPI 模型页面](/zh-Hans/overview/models) 了解所有可用选项。
    * **使用其他模型**：使用不同的当前 model ID 进行初始化，例如 `CometLLM(api_key=api_key, model="your-model-id", max_tokens=1024)`。
    * **微调（Fine-tuning）**：将 `temperature` 和 `max_tokens` 直接传给 `CometLLM(...)`。
    * **错误处理**：将调用包装在 `try/except` 中，以捕获 key 错误或网络问题。
    * **安全性**：不要将 API key 提交到版本控制中。请使用环境变量。
    * **更多文档**：[LlamaIndex 文档](https://docs.llamaindex.ai/) — [CometAPI 快速开始](/zh-Hans/overview/quick-start) — [Colab 示例](https://colab.research.google.com/github/run-llama/llama_index/blob/main/docs/docs/examples/llm/cometapi.ipynb)
  </Accordion>
</AccordionGroup>

<script type="application/ld+json">
  {`
    {
    "@context": "https://schema.org",
    "@graph": [
      {
        "@type": "HowTo",
        "@id": "https://apidoc.cometapi.com/integrations/llamaindex#howto",
        "name": "使用 LlamaIndex 与 CometAPI",
        "description": "使用本指南，通过设置 base URL、API key 以及模型或提供商选项来配置 LlamaIndex 与 CometAPI。",
        "step": [
          {
            "@type": "HowToStep",
            "@id": "https://apidoc.cometapi.com/integrations/llamaindex#step-1",
            "position": 1,
            "name": "安装 LlamaIndex CometAPI 集成",
            "text": "完成“使用 LlamaIndex 与 CometAPI”指南中的“安装 LlamaIndex CometAPI 集成”步骤。"
          },
          {
            "@type": "HowToStep",
            "@id": "https://apidoc.cometapi.com/integrations/llamaindex#step-2",
            "position": 2,
            "name": "设置你的 API key",
            "text": "将你的 CometAPI API key 存储在该集成所使用的环境变量或设置字段中。"
          },
          {
            "@type": "HowToStep",
            "@id": "https://apidoc.cometapi.com/integrations/llamaindex#step-3",
            "position": 3,
            "name": "初始化模型并发起补全调用",
            "text": "完成“使用 LlamaIndex 与 CometAPI”指南中的“初始化模型并发起补全调用”步骤。"
          },
          {
            "@type": "HowToStep",
            "@id": "https://apidoc.cometapi.com/integrations/llamaindex#step-4",
            "position": 4,
            "name": "启用流式输出",
            "text": "完成“使用 LlamaIndex 与 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": "使用 LlamaIndex 与 CometAPI",
            "item": "https://apidoc.cometapi.com/integrations/llamaindex"
          }
        ]
      }
    ]
    }
    `}
</script>
