> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coreweave.com/llms.txt
> Use this file to discover all available pages before exploring further.

# CrewAI

> CrewAI を Weave と統合して、マルチエージェントアプリケーションのモニタリングとトレースを行います

<a target="_blank" href="https://github.com/wandb/examples/blob/master/weave/docs/quickstart_crewai.ipynb">
  <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab" />
</a>

このガイドでは、Weave を使用して [CrewAI](https://docs.crewai.com/introduction) のマルチエージェントアプリケーションを監視およびトレースする方法を説明します。対象には [Crews](https://docs.crewai.com/guides/crews/first-crew) と [Flows](https://docs.crewai.com/guides/flows/first-flow) の両方が含まれます。

CrewAI は、自律型 AI エージェントを構築するための Python フレームワークです。LangChain などのエージェントフレームワークには依存せず、高レベルの [Crews](https://docs.crewai.com/guides/crews/first-crew) と低レベルの [Flows](https://docs.crewai.com/guides/flows/first-flow) という 2 つの抽象化をサポートしています。

CrewAI アプリケーションは、複数のエージェントが連携して動作する構成になっていることが多いため、エージェント同士がどのように協力し、通信しているかを把握することが重要です。Weave は CrewAI アプリケーションのトレースを自動的に取得するため、エージェントのパフォーマンスややり取りを監視・分析できます。

以下のセクションでは、Crew のトレース、ツールの使用のトラッキング、Flow のトレース、guardrail 関数を Weave op としてラップする方法について順に説明します。

<h2 id="get-started-with-crew">
  Crew を使ってみる
</h2>

この例を実行するには、CrewAI と Weave をインストールしてください。CrewAI のインストール方法の詳細については、[CrewAI インストールガイド](https://docs.crewai.com/installation)を参照してください。

```bash theme={"system"}
pip install crewai weave
```

次の例では、CrewAI の Crew を作成し、その実行を Weave でトレースします。トレースを有効にするには、スクリプトの冒頭で `weave.init()` を呼び出します。`weave.init()` の引数には、Weave がトレースをログする先のプロジェクト名を指定します。

```python lines {5} theme={"system"}
import weave
from crewai import Agent, Task, Crew, LLM, Process

# プロジェクト名を指定して Weave を初期化します
weave.init(project_name="crewai_demo")

# 出力を決定論的にするため、temperature を 0 に設定して LLM を作成します
llm = LLM(model="gpt-4o-mini", temperature=0)

# エージェントを作成します
researcher = Agent(
    role='Research Analyst',
    goal='Find and analyze the best investment opportunities',
    backstory='Expert in financial analysis and market research',
    llm=llm,
    verbose=True,
    allow_delegation=False,
)

writer = Agent(
    role='Report Writer',
    goal='Write clear and concise investment reports',
    backstory='Experienced in creating detailed financial reports',
    llm=llm,
    verbose=True,
    allow_delegation=False,
)

# タスクを作成します
research_task = Task(
    description='Deep research on the {topic}',
    expected_output='Comprehensive market data including key players, market size, and growth trends.',
    agent=researcher
)

writing_task = Task(
    description='Write a detailed report based on the research',
    expected_output='The report should be easy to read and understand. Use bullet points where applicable.',
    agent=writer
)

# crew を作成します
crew = Crew(
    agents=[researcher, writer],
    tasks=[research_task, writing_task],
    verbose=True,
    process=Process.sequential,
)

# crew を実行します
result = crew.kickoff(inputs={"topic": "AI in material science"})
print(result)
```

Weave は、エージェントのインタラクション、タスクの実行、LLM Call など、CrewAI ライブラリを通じて行われるすべての Call をトラッキングしてログします。トレースは Weave の Web インターフェースで確認できます。

[<img src="https://mintcdn.com/coreweave-dbfa0e8d/3Dv_sw2eg8feUJlx/products/wandb/weave/_media/crew.png?fit=max&auto=format&n=3Dv_sw2eg8feUJlx&q=85&s=554c4c7b788d65db6a5090e9ae24b332" alt="crew_trace.png" width="3344" height="1880" data-path="products/wandb/weave/_media/crew.png" />](https://forge.coreweave.com/wandb/ayut/crewai_demo/weave/traces?filter=%7B%22opVersionRefs%22%3A%5B%22weave%3A%2F%2F%2Fayut%2Fcrewai_demo%2Fop%2Fcrewai.Crew.kickoff%3A*%22%5D%7D\&peekPath=%2Fayut%2Fcrewai_demo%2Fcalls%2F0195c7ac-bd52-7390-95a7-309370e9e058%3FhideTraceTree%3D0\&cols=%7B%22wb_run_id%22%3Afalse%2C%22attributes.weave.client_version%22%3Afalse%2C%22attributes.weave.os_name%22%3Afalse%2C%22attributes.weave.os_release%22%3Afalse%2C%22attributes.weave.os_version%22%3Afalse%2C%22attributes.weave.source%22%3Afalse%2C%22attributes.weave.sys_version%22%3Afalse%7D)

<Note>
  CrewAI には、kickoff プロセスをより細かく制御するためのメソッドとして `kickoff()`、`kickoff_for_each()`、`kickoff_async()`、`kickoff_for_each_async()` が用意されています。このインテグレーションは、これらすべてのメソッドのトレースのログをサポートしています。
</Note>

<h2 id="track-tools">
  ツールをトラッキングする
</h2>

CrewAI のツールを使うと、Web 検索、データ分析、コラボレーション、同僚間でのタスクの委任といった機能をエージェントに持たせることができます。このインテグレーションでは、これらのツールもトレースされます。

次の例では、インターネットを検索して最も関連性の高い結果を返すツールをエージェントが利用できるようにし、前の例で生成したレポートの品質を向上させます。

まず、追加の依存関係をインストールします。

```bash theme={"system"}
pip install 'crewai[tools]'
```

この例では、`SerperDevTool` を使用して、'Research Analyst' エージェントがインターネット上で関連情報を検索できるようにしています。このツールとその API 要件の詳細については、[SerperDevTool のドキュメント](https://docs.crewai.com/tools/serperdevtool)を参照してください。

```python lines {12} theme={"system"}
# .... 既存のインポート ....
from crewai_tools import SerperDevTool

# エージェントにツールを渡します。
researcher = Agent(
    role='Research Analyst',
    goal='Find and analyze the best investment opportunities',
    backstory='Expert in financial analysis and market research',
    llm=llm,
    verbose=True,
    allow_delegation=False,
    tools=[SerperDevTool()],
)

# .... 既存のコード ....
```

インターネットにアクセスできるエージェントでこの Crew を実行すると、より関連性の高い結果が得られます。次の画像のように、Weave はツールの使用を自動的にトレースします。

[<img src="https://mintcdn.com/coreweave-dbfa0e8d/3Dv_sw2eg8feUJlx/products/wandb/weave/_media/crew_with_tool.png?fit=max&auto=format&n=3Dv_sw2eg8feUJlx&q=85&s=a0f5a311ab892762bb8f33b821a39f1c" alt="crew_with_tool_trace.png" width="3344" height="1880" data-path="products/wandb/weave/_media/crew_with_tool.png" />](https://forge.coreweave.com/wandb/ayut/crewai_demo/weave/traces?filter=%7B%22opVersionRefs%22%3A%5B%22weave%3A%2F%2F%2Fayut%2Fcrewai_demo%2Fop%2Fcrewai.Crew.kickoff%3A*%22%5D%7D\&peekPath=%2Fayut%2Fcrewai_demo%2Fcalls%2F0195c7c7-0213-7f42-b130-caa93a79316c%3FdescendentCallId%3D0195c7c7-0a16-7f11-8cfd-9dedf1d03b3b\&cols=%7B%22wb_run_id%22%3Afalse%2C%22attributes.weave.client_version%22%3Afalse%2C%22attributes.weave.os_name%22%3Afalse%2C%22attributes.weave.os_release%22%3Afalse%2C%22attributes.weave.os_version%22%3Afalse%2C%22attributes.weave.source%22%3Afalse%2C%22attributes.weave.sys_version%22%3Afalse%7D)

<Note>
  このインテグレーションは、[`crewAI-tools`](https://github.com/crewAIInc/crewAI-tools) リポジトリにあるすべてのツールに自動的にパッチを適用します。
</Note>

<h2 id="get-started-with-flow">
  Flow を使ってみる
</h2>

次の例では、CrewAI Flow を定義し、Weave でトレースします。Crew の場合と同様に、Flow を定義する前に `weave.init()` を呼び出してください。これにより、Weave は `Flow.kickoff` エントリポイントと、`@start`、`@listen`、`@router`、`@or_`、`@and_` の各デコレーターを自動的に取得します。

```python lines {3} theme={"system"}
import weave
# プロジェクト名を指定して Weave を初期化します
weave.init("crewai_demo")

from crewai.flow.flow import Flow, listen, router, start
from litellm import completion


class CustomerFeedbackFlow(Flow):
    model = "gpt-4o-mini"

    @start()
    def fetch_feedback(self):
        print("Fetching customer feedback")
        # 実際の運用では、ここを API 呼び出しに置き換えることができます。
        # この例では、顧客フィードバックを模擬的に生成します。
        feedback = (
            "I had a terrible experience with the product. "
            "It broke after one use and customer service was unhelpful."
        )
        self.state["feedback"] = feedback
        return feedback

    @router(fetch_feedback)
    def analyze_feedback(self, feedback):
        # 言語モデルを使用して感情分析を行います
        prompt = (
            f"Analyze the sentiment of this customer feedback and "
            "return only 'positive' or 'negative':\n\n"
            f"Feedback: {feedback}"
        )
        response = completion(
            model=self.model,
            messages=[{"role": "user", "content": prompt}],
        )
        sentiment = response["choices"][0]["message"]["content"].strip().lower()
        # 応答があいまいな場合は、negative として扱います
        if sentiment not in ["positive", "negative"]:
            sentiment = "negative"
        return sentiment

    @listen("positive")
    def handle_positive_feedback(self):
        # 肯定的なフィードバックに対するお礼のメッセージを生成します
        prompt = "Generate a thank you message for a customer who provided positive feedback."
        response = completion(
            model=self.model,
            messages=[{"role": "user", "content": prompt}],
        )
        thank_you_message = response["choices"][0]["message"]["content"].strip()
        self.state["response"] = thank_you_message
        return thank_you_message

    @listen("negative")
    def handle_negative_feedback(self):
        # 否定的なフィードバックに対して、サービス改善を約束するお詫びのメッセージを生成します
        prompt = (
            "Generate an apology message to a customer who provided negative feedback and offer assistance or a solution."
        )
        response = completion(
            model=self.model,
            messages=[{"role": "user", "content": prompt}],
        )
        apology_message = response["choices"][0]["message"]["content"].strip()
        self.state["response"] = apology_message
        return apology_message

# Flow をインスタンス化して実行を開始します
flow = CustomerFeedbackFlow()
result = flow.kickoff()
print(result)
```

[<img src="https://mintcdn.com/coreweave-dbfa0e8d/3Dv_sw2eg8feUJlx/products/wandb/weave/_media/flow.png?fit=max&auto=format&n=3Dv_sw2eg8feUJlx&q=85&s=23ea552bad2c0f2dbece5ce40fd46da1" alt="flow.png" width="3344" height="1880" data-path="products/wandb/weave/_media/flow.png" />](https://forge.coreweave.com/wandb/ayut/crewai_demo/weave/traces?filter=%7B%22opVersionRefs%22%3A%5B%22weave%3A%2F%2F%2Fayut%2Fcrewai_demo%2Fop%2Fcrewai.Flow.kickoff%3A*%22%5D%7D\&peekPath=%2Fayut%2Fcrewai_demo%2Fcalls%2F0195c7e3-7a63-7283-bef4-9e0eb2f0eab1\&cols=%7B%22wb_run_id%22%3Afalse%2C%22attributes.weave.client_version%22%3Afalse%2C%22attributes.weave.os_name%22%3Afalse%2C%22attributes.weave.os_release%22%3Afalse%2C%22attributes.weave.os_version%22%3Afalse%2C%22attributes.weave.source%22%3Afalse%2C%22attributes.weave.sys_version%22%3Afalse%7D)

<Note>
  このインテグレーションは、`Flow.kickoff` エントリポイントと、利用可能なすべてのデコレーター (`@start`、`@listen`、`@router`、`@or_`、`@and_`) に自動でパッチを適用します。
</Note>

<h2 id="crew-guardrail-track-your-own-ops">
  Crew のガードレール: 独自の Op をトラッキングする
</h2>

タスクのガードレールを使用すると、CrewAI がタスクの出力を次のタスクに渡す前に、その出力を検証および変換できます。Python の関数を使用すれば、エージェントの実行をその場で検証できます。

guardrail 関数を `@weave.op` でラップすると、その入力、出力、アプリケーションロジックが取得されるため、エージェント間でデータがどのように検証されるかをデバッグできます。また、実験を進める中でコードが自動的にバージョン管理されるため、git にコミットしていないアドホックな変更内容も取得されます。

次の例では、生成されたレポートの長さを検証するガードレールを追加して、リサーチアナリストとライターの Crew を拡張します。

```python lines {4,36} theme={"system"}
# .... 既存のインポートと weave の初期化 ....

# guardrail 関数を `@weave.op()` でデコレートします
@weave.op(name="guardrail-validate_blog_content")
def validate_blog_content(result: TaskOutput) -> Tuple[bool, Any]:
    # 結果を生の string として取得します
    result = result.raw

    """Validate blog content meets requirements."""
    try:
        # 単語数を確認します
        word_count = len(result.split())

        if word_count > 200:
            return (False, {
                "error": "Blog content exceeds 200 words",
                "code": "WORD_COUNT_ERROR",
                "context": {"word_count": word_count}
            })

        # 追加の検証ロジックはここに記述します
        return (True, result.strip())
    except Exception as e:
        return (False, {
            "error": "Unexpected error during validation",
            "code": "SYSTEM_ERROR"
        })


# .... 既存のエージェントとリサーチアナリストのタスク ....

writing_task = Task(
    description='Write a detailed report based on the research under 200 words',
    expected_output='The report should be easy to read and understand. Use bullet points where applicable.',
    agent=writer,
    guardrail=validate_blog_content,
)

# .... crew を実行する既存のコード ....
```

guardrail 関数を `@weave.op` でデコレートすると、この関数の入力と出力に加え、実行時間、トークン情報 (関数が LLM を使用する場合)、コードのバージョンなどをトラッキングできます。

[<img src="https://mintcdn.com/coreweave-dbfa0e8d/3Dv_sw2eg8feUJlx/products/wandb/weave/_media/crew_with_guardrail.png?fit=max&auto=format&n=3Dv_sw2eg8feUJlx&q=85&s=fbe828b47e37cd3490b3660a2e002ddf" alt="guardrail.png" width="3344" height="1880" data-path="products/wandb/weave/_media/crew_with_guardrail.png" />](https://forge.coreweave.com/wandb/ayut/crewai_demo/weave/traces?filter=%7B%22opVersionRefs%22%3A%5B%22weave%3A%2F%2F%2Fayut%2Fcrewai_demo%2Fop%2Fcrewai.Crew.kickoff%3A*%22%5D%7D\&peekPath=%2Fayut%2Fcrewai_demo%2Fcalls%2F0195c838-38cb-71a2-8a15-651ecddf9d89%3FdescendentCallId%3D0195c838-8632-7173-846d-f230e7272c20\&cols=%7B%22wb_run_id%22%3Afalse%2C%22attributes.weave.client_version%22%3Afalse%2C%22attributes.weave.os_name%22%3Afalse%2C%22attributes.weave.os_release%22%3Afalse%2C%22attributes.weave.os_version%22%3Afalse%2C%22attributes.weave.source%22%3Afalse%2C%22attributes.weave.sys_version%22%3Afalse%7D)

<h2 id="conclusion">
  まとめ
</h2>

これで、エージェントのやり取り、ツールの使用、Flow の実行、ガードレールの検証を取得できる、Weave でトレースされた CrewAI アプリケーションが完成しました。このインテグレーションについての改善提案や問題の報告は、[GitHub で issue を作成](https://github.com/wandb/weave/issues/new/choose)してください。

CrewAI を使ったマルチエージェントシステムの構築について詳しくは、CrewAI の[サンプル](https://github.com/crewAIInc/crewAI-examples)と[ドキュメント](https://docs.crewai.com/introduction)を参照してください。


## Related topics

- [サンプルコードとノートブック](/ja/products/wandb/examples.md)
