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

# 使用 CrewAI 搭配 CometAPI

> 在一個循序多代理 Crew 中，使用四種 CrewAI LLM 傳輸設定搭配 CometAPI。

[CrewAI](https://docs.crewai.com/) 是一個用於協調 AI 代理與任務的 Python 框架。本指南會設定一個循序 Crew，透過四種 CrewAI 傳輸設定呼叫 CometAPI：OpenAI 聊天補全、OpenAI 回應、Anthropic 訊息，以及 Gemini `generateContent`。

## 必要條件

* Python 3.10–3.13
* [`uv`](https://docs.astral.sh/uv/getting-started/installation/)
* 具備有效 API 金鑰的 CometAPI 帳戶 — [在儀表板中取得您的金鑰](https://www.cometapi.com/console/token)
* 適用於下方所示傳輸的四個文字模型 ID

## 設定整合

**1. 建立專案並安裝 CrewAI**

建立新的 `uv` 專案，並安裝包含 Anthropic 與 Google Gen AI 額外套件的 CrewAI：

```bash theme={null}
uv init crewai-cometapi
cd crewai-cometapi
uv add 'crewai[anthropic,google-genai]'
```

**2. 設定 API 金鑰和模型 ID**

設定 CometAPI API 金鑰，以及每種傳輸各一個模型 ID：

```bash theme={null}
read -rsp "CometAPI API key: " COMETAPI_KEY
printf '\n'
export COMETAPI_KEY

export COMETAPI_CHAT_MODEL_ID=your-model-id
export COMETAPI_RESPONSES_MODEL_ID=your-model-id
export COMETAPI_ANTHROPIC_MODEL_ID=your-model-id
export COMETAPI_GEMINI_MODEL_ID=your-model-id
```

將每個 `your-model-id` 值替換為以下頁面中的模型 ID [CometAPI 模型頁面](https://apidoc.cometapi.com/zh-Hant/overview/models.md)。這四個值可以不同。請將每個模型 ID 指派給其對應的傳輸。

**3. 建立循序 Crew**

將下列範例儲存為 `crew.py`：

```python theme={null}
import os

from crewai import Agent, Crew, LLM, Process, Task


api_key = os.environ["COMETAPI_KEY"]

chat_llm = LLM(
    model=os.environ["COMETAPI_CHAT_MODEL_ID"],
    custom_openai=True,
    api="completions",
    base_url="https://api.cometapi.com/v1",
    api_key=api_key,
    max_tokens=512,
    max_retries=0,
)

responses_llm = LLM(
    model=os.environ["COMETAPI_RESPONSES_MODEL_ID"],
    custom_openai=True,
    api="responses",
    base_url="https://api.cometapi.com/v1",
    api_key=api_key,
    max_completion_tokens=512,
    max_retries=0,
)

anthropic_llm = LLM(
    model=f"anthropic/{os.environ['COMETAPI_ANTHROPIC_MODEL_ID']}",
    base_url="https://api.cometapi.com",
    api_key=api_key,
    max_tokens=512,
    max_retries=0,
)

gemini_llm = LLM(
    model=f"gemini/{os.environ['COMETAPI_GEMINI_MODEL_ID']}",
    api_key=api_key,
    max_output_tokens=512,
    thinking_config={"thinking_budget": 0, "include_thoughts": False},
    client_params={
        "http_options": {
            "base_url": "https://api.cometapi.com",
            "api_version": "v1beta",
        }
    },
)

audience_agent = Agent(
    role="Audience researcher",
    goal="Define the audience for an API migration brief",
    backstory="You turn product goals into a precise audience statement.",
    llm=chat_llm,
    tools=[],
    allow_delegation=False,
    max_iter=1,
    max_retry_limit=0,
    verbose=False,
)

requirements_agent = Agent(
    role="Requirements planner",
    goal="Turn an audience statement into implementation requirements",
    backstory="You write concise, testable requirements for API teams.",
    llm=responses_llm,
    tools=[],
    allow_delegation=False,
    max_iter=1,
    max_retry_limit=0,
    verbose=False,
)

risk_agent = Agent(
    role="Risk reviewer",
    goal="Identify the most important migration risk",
    backstory="You review plans for practical delivery risks.",
    llm=anthropic_llm,
    tools=[],
    allow_delegation=False,
    max_iter=1,
    max_retry_limit=0,
    verbose=False,
)

editor_agent = Agent(
    role="Release brief editor",
    goal="Combine research, requirements, and risk into one brief",
    backstory="You preserve source findings while producing clear summaries.",
    llm=gemini_llm,
    tools=[],
    allow_delegation=False,
    max_iter=1,
    max_retry_limit=0,
    verbose=False,
)

audience_task = Task(
    description=(
        "Define one target audience for a team moving an existing OpenAI "
        "integration to a multi-provider API. Return only an Audience heading "
        "and one sentence of at most 20 words."
    ),
    expected_output="An Audience heading followed by one concise sentence.",
    agent=audience_agent,
)

requirements_task = Task(
    description=(
        "Using the audience statement in your context, return only a "
        "Requirements heading and exactly two numbered requirements. Keep each "
        "requirement to at most 18 words."
    ),
    expected_output="A Requirements heading followed by two numbered items.",
    agent=requirements_agent,
    context=[audience_task],
)

risk_task = Task(
    description=(
        "Using the audience and requirements in your context, return only a "
        "Risk heading, one risk sentence, and one mitigation sentence. Keep "
        "each sentence to at most 18 words."
    ),
    expected_output="A Risk heading with one risk and one mitigation.",
    agent=risk_agent,
    context=[audience_task, requirements_task],
)

brief_task = Task(
    description=(
        "Create a release brief from all prior task outputs. Return only these "
        "sections: Audience with one sentence; Requirements with two numbered "
        "items; Risk with one risk and one mitigation. Keep the exact headings "
        "Audience, Requirements, and Risk."
    ),
    expected_output=(
        "A concise release brief with Audience, Requirements, and Risk headings."
    ),
    agent=editor_agent,
    context=[audience_task, requirements_task, risk_task],
)

crew = Crew(
    agents=[
        audience_agent,
        requirements_agent,
        risk_agent,
        editor_agent,
    ],
    tasks=[audience_task, requirements_task, risk_task, brief_task],
    process=Process.sequential,
    verbose=False,
)

result = crew.kickoff()

for index, task_output in enumerate(result.tasks_output, start=1):
    print(f"\n--- Task {index} ---\n{task_output.raw}")
```

這些 Agent 不使用工具、無法委派，並會依序一次執行一個。第一個之後的每個 Task 都會在 `context` 中宣告其前置 Task，因此 CrewAI 會將這些先前輸出納入下一個 Task。

**4. 執行 Crew**

在相同的 Shell 工作階段中執行範例：

```bash theme={null}
uv run python crew.py
```

指令碼會列印所有四個 Task 的輸出，包括最終的發行簡報。

## 路由對照

| CrewAI 設定 | CometAPI 路由 | 基礎 URL |
| - | - | - |
| `custom_openai=True`, `api="completions"` | `POST /v1/chat/completions` | `https://api.cometapi.com/v1` |
| `custom_openai=True`, `api="responses"` | `POST /v1/responses` | `https://api.cometapi.com/v1` |
| `anthropic/` 模型前綴 | `POST /v1/messages` | `https://api.cometapi.com` |
| `gemini/` 模型前綴與 `client_params.http_options` | `POST /v1beta/models/{model}:generateContent` | `https://api.cometapi.com` |

上述兩種 OpenAI 設定需要 `/v1` 後綴，並將其加入 `base_url`。Anthropic 與 Gemini 設定會自行加入各自具版本的路由，因此其基礎 URL 是不含 `/v1` 的 CometAPI 原點。

## 選擇模型 ID

使用 [CometAPI 模型頁面](https://apidoc.cometapi.com/zh-Hant/overview/models.md) 為每種傳輸選擇一個文字模型 ID。將模型 ID 儲存在環境變數中，以便無須編輯 Python 檔案即可變更它們。請勿在環境變數中加入提供者前綴。範例會在 CrewAI 使用這些前綴進行提供者選擇的位置加入 `anthropic/` 和 `gemini/`。

## 疑難排解

> [accordion] Anthropic 或 Gemini 提供者匯入失敗
>
> 在專案中執行 `uv add 'crewai[anthropic,google-genai]'`。基礎 CrewAI 套件預設不會同時安裝兩個選用的提供者 SDK。

> [accordion] 回應請求傳回參數錯誤
>
> 移除不屬於所選模型介面的選用參數。範例僅設定回應的輸出 Token 上限。

> [accordion] 請求使用錯誤的路由
>
> 將 `LLM` 設定與路由對照表比較。尤其請使用 `custom_openai=True` 並搭配正確的 `api` 值，且將 Gemini 基礎 URL 保留在 `client_params.http_options` 內。

## 相關資源

* [CrewAI 1.15.12 LLM 文件](https://docs.crewai.com/v1.15.12/en/concepts/llms)
* [CrewAI 代理](https://docs.crewai.com/v1.15.12/en/concepts/agents)
* [CrewAI 任務](https://docs.crewai.com/v1.15.12/en/concepts/tasks)
* [CrewAI Crews](https://docs.crewai.com/v1.15.12/en/concepts/crews)
* [CometAPI 聊天補全](https://apidoc.cometapi.com/zh-Hant/api/text/chat.md)
* [CometAPI 回應](https://apidoc.cometapi.com/zh-Hant/api/text/responses.md)
* [CometAPI Anthropic 訊息](https://apidoc.cometapi.com/zh-Hant/api/text/anthropic-messages.md)
* [CometAPI Gemini generateContent](https://apidoc.cometapi.com/zh-Hant/api/text/gemini-generating-content.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.