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

# Sử dụng CrewAI với CometAPI

> Sử dụng bốn cấu hình truyền tải LLM của CrewAI với CometAPI trong một Crew đa tác tử tuần tự.

[CrewAI](https://docs.crewai.com/) là một framework Python để điều phối các AI agent và task. Hướng dẫn này cấu hình một Crew tuần tự để gọi CometAPI thông qua bốn cấu hình truyền tải CrewAI: OpenAI Chat Completions, OpenAI Responses, Anthropic Messages và Gemini `generateContent`.

## Điều kiện tiên quyết

* Python 3.10–3.13
* [`uv`](https://docs.astral.sh/uv/getting-started/installation/)
* Tài khoản CometAPI có API key đang hoạt động — [lấy API key của bạn trong dashboard](https://www.cometapi.com/console/token)
* Bốn model ID văn bản cho các cấu hình truyền tải dưới đây

## Cấu hình tích hợp

<Steps>
  <Step title="Tạo dự án và cài đặt CrewAI">
    Tạo một dự án `uv` mới và cài đặt CrewAI cùng các gói bổ sung Anthropic và Google Gen AI:

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

  <Step title="Thiết lập API key và model ID">
    Thiết lập CometAPI API key và một model ID cho mỗi cấu hình truyền tải:

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

    Thay thế mọi giá trị `your-model-id` bằng một model ID từ [trang CometAPI Models](/vi/overview/models). Bốn giá trị có thể khác nhau. Gán từng model ID cho cấu hình truyền tải tương ứng.
  </Step>

  <Step title="Tạo Crew tuần tự">
    Lưu ví dụ sau dưới dạng `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}")
    ```

    Các Agent không có tools, không thể ủy quyền và chạy lần lượt từng agent. Mỗi Task sau Task đầu tiên khai báo các Task đứng trước trong `context`, để CrewAI đưa các đầu ra trước đó vào Task tiếp theo.
  </Step>

  <Step title="Chạy Crew">
    Chạy ví dụ trong cùng phiên shell:

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

    Script in ra cả bốn đầu ra Task, bao gồm bản tóm tắt phát hành cuối cùng.
  </Step>
</Steps>

## Ánh xạ route

| Cấu hình CrewAI                                         | Route CometAPI                                | URL cơ sở                     |
| ------------------------------------------------------- | --------------------------------------------- | ----------------------------- |
| `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/` tiền tố model                              | `POST /v1/messages`                           | `https://api.cometapi.com`    |
| `gemini/` tiền tố model và `client_params.http_options` | `POST /v1beta/models/{model}:generateContent` | `https://api.cometapi.com`    |

Hai cấu hình OpenAI ở trên cần hậu tố `/v1` trong `base_url`. Các cấu hình Anthropic và Gemini tự thêm route có phiên bản riêng, vì vậy URL cơ sở của chúng là origin CometAPI không có `/v1`.

## Chọn model ID

Sử dụng [trang CometAPI Models](/vi/overview/models) để chọn một model ID văn bản cho mỗi cấu hình truyền tải. Lưu model ID trong các biến môi trường để có thể thay đổi chúng mà không cần chỉnh sửa tệp Python. Không thêm tiền tố nhà cung cấp vào biến môi trường. Ví dụ thêm `anthropic/` và `gemini/` tại vị trí CrewAI sử dụng các tiền tố đó để chọn nhà cung cấp.

## Khắc phục sự cố

<AccordionGroup>
  <Accordion title="Không thể import nhà cung cấp Anthropic hoặc Gemini">
    Chạy `uv add 'crewai[anthropic,google-genai]'` trong dự án. Gói CrewAI cơ sở không cài đặt sẵn cả hai SDK nhà cung cấp tùy chọn theo mặc định.
  </Accordion>

  <Accordion title="Yêu cầu Responses trả về lỗi tham số">
    Xóa các tham số tùy chọn không thuộc interface của model đã chọn. Ví dụ chỉ cấu hình giới hạn output token cho Responses.
  </Accordion>

  <Accordion title="Yêu cầu sử dụng sai route">
    So sánh cấu hình `LLM` với bảng ánh xạ route. Đặc biệt, sử dụng `custom_openai=True` với giá trị `api` chính xác và giữ URL cơ sở Gemini bên trong `client_params.http_options`.
  </Accordion>
</AccordionGroup>

## Tài nguyên liên quan

* [Tài liệu LLM CrewAI 1.15.12](https://docs.crewai.com/v1.15.12/en/concepts/llms)
* [CrewAI Agents](https://docs.crewai.com/v1.15.12/en/concepts/agents)
* [CrewAI Tasks](https://docs.crewai.com/v1.15.12/en/concepts/tasks)
* [CrewAI Crews](https://docs.crewai.com/v1.15.12/en/concepts/crews)
* [CometAPI Chat Completions](/vi/api/text/chat)
* [CometAPI Responses](/vi/api/text/responses)
* [CometAPI Anthropic Messages](/vi/api/text/anthropic-messages)
* [CometAPI Gemini generateContent](/vi/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": "Sử dụng CrewAI với CometAPI",
        "description": "Sử dụng bốn cấu hình truyền tải LLM của CrewAI với CometAPI trong một Crew đa tác tử tuần tự.",
        "step": [
          {
            "@type": "HowToStep",
            "@id": "https://apidoc.cometapi.com/integrations/crewai#step-1",
            "position": 1,
            "name": "Tạo dự án và cài đặt CrewAI",
            "text": "Tạo một dự án uv và cài đặt CrewAI cùng các gói bổ sung Anthropic và Google Gen AI."
          },
          {
            "@type": "HowToStep",
            "@id": "https://apidoc.cometapi.com/integrations/crewai#step-2",
            "position": 2,
            "name": "Thiết lập API key và model ID",
            "text": "Thiết lập CometAPI API key và một model ID hiện tại cho mỗi cấu hình truyền tải."
          },
          {
            "@type": "HowToStep",
            "@id": "https://apidoc.cometapi.com/integrations/crewai#step-3",
            "position": 3,
            "name": "Tạo Crew tuần tự",
            "text": "Cấu hình bốn adapter LLM, bốn Agent và bốn Task được liên kết ngữ cảnh trong một Crew tuần tự."
          },
          {
            "@type": "HowToStep",
            "@id": "https://apidoc.cometapi.com/integrations/crewai#step-4",
            "position": 4,
            "name": "Chạy Crew",
            "text": "Chạy Crew và kiểm tra cả bốn đầu ra Task."
          }
        ]
      },
      {
        "@type": "BreadcrumbList",
        "itemListElement": [
          {
            "@type": "ListItem",
            "position": 1,
            "name": "Tài liệu CometAPI",
            "item": "https://apidoc.cometapi.com/"
          },
          {
            "@type": "ListItem",
            "position": 2,
            "name": "Tích hợp",
            "item": "https://apidoc.cometapi.com/integrations"
          },
          {
            "@type": "ListItem",
            "position": 3,
            "name": "Sử dụng CrewAI với CometAPI",
            "item": "https://apidoc.cometapi.com/integrations/crewai"
          }
        ]
      }
    ]
    }
    `}
</script>
