> ## 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 を使用する

> 1つの順次実行マルチエージェント Crew で、CometAPI と4つの CrewAI LLM トランスポート構成を使用します。

[CrewAI](https://docs.crewai.com/) は、AI エージェントとタスクを連携させるための Python フレームワークです。このガイドでは、OpenAI チャット補完、OpenAI レスポンス、Anthropic メッセージ、Gemini `generateContent` の4つの CrewAI トランスポート構成を通じて CometAPI を呼び出す、1つの順次実行 Crew を設定します。

## 前提条件

* Python 3.10～3.13
* [`uv`](https://docs.astral.sh/uv/getting-started/installation/)
* 有効な API キーを持つ CometAPI アカウント — [ダッシュボードで取得](https://www.cometapi.com/console/token)
* 以下に示すトランスポート用の4つのテキストモデル ID

## 統合を設定する

<Steps>
  <Step title="プロジェクトを作成して CrewAI をインストールする">
    新しい `uv` プロジェクトを作成し、Anthropic および Google Gen AI の追加機能を含めて CrewAI をインストールします。

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

  <Step title="API キーとモデル ID を設定する">
    CometAPI API キーと、各トランスポート用のモデル ID を1つずつ設定します。

    ```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` の値を [CometAPI Models ページ](/ja/overview/models)に記載されているモデル ID に置き換えてください。4つの値はそれぞれ異なっていても構いません。各モデル ID を対応するトランスポートに割り当てます。
  </Step>

  <Step title="順次実行 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 にはツールがなく、委任できず、1つずつ実行されます。最初の Task 以降のすべての Task では、先行する Task を `context` で宣言するため、CrewAI はそれらの以前の出力を次の Task に含めます。
  </Step>

  <Step title="Crew を実行する">
    同じシェルセッションで例を実行します。

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

    スクリプトは、最終リリース概要を含む4つすべての Task 出力を表示します。
  </Step>
</Steps>

## ルートマッピング

| 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`    |

上記の2つの OpenAI 設定では、`/v1` の末尾を `base_url` に追加する必要があります。Anthropic と Gemini の設定ではそれぞれ独自のバージョン付きルートが追加されるため、ベース URL には `/v1` を含めない CometAPI オリジンを指定します。

## モデル ID を選択する

各トランスポート用のテキストモデル ID を選択するには、 [CometAPI Models ページ](/ja/overview/models) を使用してください。Python ファイルを編集せずに変更できるよう、モデル ID は環境変数に保存します。環境変数にプロバイダープレフィックスを追加しないでください。例では、CrewAI がこれらのプレフィックスをプロバイダー選択に使用する箇所で、`anthropic/` と `gemini/` を追加しています。

## トラブルシューティング

<AccordionGroup>
  <Accordion title="Anthropic または Gemini プロバイダーのインポートに失敗する">
    プロジェクト内で `uv add 'crewai[anthropic,google-genai]'` を実行してください。基本の CrewAI パッケージでは、両方のオプションのプロバイダー SDK がデフォルトでインストールされません。
  </Accordion>

  <Accordion title="レスポンス リクエストでパラメータエラーが返される">
    選択したモデルのインターフェースに含まれないオプションパラメータを削除してください。例では、レスポンスに対して出力トークン（Token）の上限のみを設定しています。
  </Accordion>

  <Accordion title="リクエストで誤ったルートが使用される">
    `LLM` の構成をルートマッピング表と比較してください。特に、正しい `custom_openai=True` 値とともに `api` を使用し、Gemini のベース URL は `client_params.http_options` 内に保持してください。
  </Accordion>
</AccordionGroup>

## 関連リソース

* [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 クルー](https://docs.crewai.com/v1.15.12/en/concepts/crews)
* [CometAPI チャット補完](/ja/api/text/chat)
* [CometAPI レスポンス](/ja/api/text/responses)
* [CometAPI Anthropic メッセージ](/ja/api/text/anthropic-messages)
* [CometAPI Gemini generateContent](/ja/api/text/gemini-generating-content)

<script type="application/ld+json">
  {`
    {
    "@context": "https://schema.org",
    "@graph": [
      {
        "@type": "HowTo",
        "@id": "https://apidoc.cometapi.com/integrations/crewai#howto",
        "name": "CrewAI と CometAPI を使用する",
        "description": "1つの順次実行マルチエージェント Crew で、CometAPI と4つの CrewAI LLM トランスポート構成を使用します。",
        "step": [
          {
            "@type": "HowToStep",
            "@id": "https://apidoc.cometapi.com/integrations/crewai#step-1",
            "position": 1,
            "name": "プロジェクトを作成して CrewAI をインストールする",
            "text": "uv プロジェクトを作成し、Anthropic および Google Gen AI の追加機能を含めて CrewAI をインストールします。"
          },
          {
            "@type": "HowToStep",
            "@id": "https://apidoc.cometapi.com/integrations/crewai#step-2",
            "position": 2,
            "name": "API キーとモデル ID を設定する",
            "text": "CometAPI API キーと、各トランスポート用の現在のモデル ID を1つずつ設定します。"
          },
          {
            "@type": "HowToStep",
            "@id": "https://apidoc.cometapi.com/integrations/crewai#step-3",
            "position": 3,
            "name": "順次実行 Crew を作成する",
            "text": "4つの LLM アダプター、4つの Agent、コンテキストで連結された4つの Task を順次実行 Crew で設定します。"
          },
          {
            "@type": "HowToStep",
            "@id": "https://apidoc.cometapi.com/integrations/crewai#step-4",
            "position": 4,
            "name": "Crew を実行する",
            "text": "Crew を実行し、4つすべての Task 出力を確認します。"
          }
        ]
      },
      {
        "@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": "CrewAI と CometAPI を使用する",
            "item": "https://apidoc.cometapi.com/integrations/crewai"
          }
        ]
      }
    ]
    }
    `}
</script>
