> ## Documentation Index
> Fetch the complete documentation index at: https://wb-21fd5541-wbdocs-1882.mintlify.site/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="Colab で開く" />
</a>

CrewAI は、LangChain や他のエージェントフレームワークに完全に依存せず、一から構築された軽量かつ非常に高速な Python フレームワークです。CrewAI は、高レベルでシンプルな操作性 ([Crews](https://docs.crewai.com/guides/crews/first-crew)) と、低レベルでのきめ細かな制御 ([Flows](https://docs.crewai.com/guides/flows/first-flow)) の両方を開発者に提供し、あらゆるシナリオに合わせた自律型 AI エージェントの構築に適しています。[CrewAI の詳細はこちら](https://docs.crewai.com/introduction)。

AI エージェントを扱う際は、それらのやり取りをデバッグして監視することが重要です。CrewAI アプリケーションは複数のエージェントが連携して動作することが多いため、それらがどのように協調し、やり取りしているかを理解することが不可欠です。Weave は、CrewAI アプリケーションのトレースを自動的に収集することでこのプロセスを簡素化し、エージェントのパフォーマンスや相互作用を監視・分析できるようにします。

このインテグレーションは、Crews と Flows の両方をサポートします。

<div id="getting-started-with-crew">
  ## Crew を使い始める
</div>

この例を実行するには、CrewAI ([詳細はこちら](https://docs.crewai.com/installation)) と Weave をインストールする必要があります。

```
pip install crewai weave
```

これから CrewAI Crew を作成し、Weave を使用して実行をトレースします。まずは、スクリプトの先頭で `weave.init()` を呼び出すだけです。weave.init() の引数には、トレースのログを記録するプロジェクト名を指定します。

```python lines {5} theme={null}
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 は、CrewAI ライブラリを介して行われるすべての calls をトラッキングし、ログします。これには、エージェント のやり取り、タスクの実行、LLM calls が含まれます。トレースは Weave の Web インターフェースで確認できます。

[<img src="https://mintcdn.com/wb-21fd5541-wbdocs-1882/kTNBEU9hU1PbozeW/weave/guides/integrations/imgs/crewai/crew.png?fit=max&auto=format&n=kTNBEU9hU1PbozeW&q=85&s=a734dd93e0e77a1e7183bccaa2b2267d" alt="crew_trace.png" width="3456" height="1998" data-path="weave/guides/integrations/imgs/crewai/crew.png" />](https://wandb.ai/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 プロセスをより細かく制御するための複数の method (`kickoff()`, `kickoff_for_each()`, `kickoff_async()`, `kickoff_for_each_async()`) があります。このインテグレーションは、これらすべての method からのトレースのログをサポートしています。
</Note>

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

CrewAI のツールは、Web 検索やデータ分析から、共同作業や同僚へのタスク委任まで、さまざまな機能をエージェントに提供します。インテグレーションでは、それらもトレースできます。

インターネットを検索して最も関連性の高い結果を返せるツールを使えるようにすることで、上記の例で生成されるレポートの品質を向上させます。

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

```
pip install 'crewai[tools]'
```

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

```python lines {12} theme={null}
# .... 既存のインポート ....
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 を実行すると、より適切で質の高い結果が得られます。ツールの使用は、以下の画像のように自動的にトレースされます。

[<img src="https://mintcdn.com/wb-21fd5541-wbdocs-1882/kTNBEU9hU1PbozeW/weave/guides/integrations/imgs/crewai/crew_with_tool.png?fit=max&auto=format&n=kTNBEU9hU1PbozeW&q=85&s=0db567e6926dbb34106c78f95b3c352a" alt="crew_with_tool_trace.png" width="3454" height="1996" data-path="weave/guides/integrations/imgs/crewai/crew_with_tool.png" />](https://wandb.ai/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>

<div id="getting-started-with-flow">
  ## Flow 入門
</div>

```python lines {3} theme={null}
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 callに置き換えることができます。
        # この例では、顧客フィードバックをシミュレートします。
        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 = CustomerFeedbackFlow()
result = flow.kickoff()
print(result)
```

[<img src="https://mintcdn.com/wb-21fd5541-wbdocs-1882/kTNBEU9hU1PbozeW/weave/guides/integrations/imgs/crewai/flow.png?fit=max&auto=format&n=kTNBEU9hU1PbozeW&q=85&s=b5aeb7746339d0d4f29b6f110e26a8d1" alt="flow.png" width="3456" height="1996" data-path="weave/guides/integrations/imgs/crewai/flow.png" />](https://wandb.ai/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>

<div id="crew-guardrail-track-your-own-ops">
  ## Crew Guardrail - 独自の ops をトラッキングする
</div>

タスクガードレールを使うと、タスクの出力を次のタスクに渡す前に検証や変換を行えます。エージェント の実行内容をその場で検証するには、シンプルな Python 関数を使用できます。

この関数を `@weave.op` でラップすると、inputs、outputs、アプリケーションロジックのキャプチャが始まり、エージェント を通じてデータがどのように検証されるかをデバッグできるようになります。さらに、実験を進める中で git にコミットされていないアドホックな詳細も記録できるよう、コードのバージョン管理も自動的に開始されます。

リサーチアナリストとライターの例を見てみましょう。ここでは、生成されたレポートの長さを検証するためのガードレールを追加します。

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

# ガードレール関数を`@weave.op()`でデコレートする
@weave.op(name="guardrail-validate_blog_content")
def validate_blog_content(result: TaskOutput) -> Tuple[bool, Any]:
    # 生の文字列結果を取得する
    result = result.raw

    """ブログコンテンツが要件を満たしているか検証する。"""
    try:
        # 単語数を確認する
        word_count = len(result.split())

        if word_count > 200:
            return (False, {
                "error": "ブログコンテンツが200語を超えています",
                "code": "WORD_COUNT_ERROR",
                "context": {"word_count": word_count}
            })

        # 追加の検証ロジックをここに記述
        return (True, result.strip())
    except Exception as e:
        return (False, {
            "error": "検証中に予期しないエラーが発生しました",
            "code": "SYSTEM_ERROR"
        })


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

writing_task = Task(
    description='調査に基づいて200語以内の詳細なレポートを作成する',
    expected_output='レポートは読みやすく理解しやすいものにすること。必要に応じて箇条書きを使用すること。',
    agent=writer,
    guardrail=validate_blog_content,
)

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

ガードレール関数を `@weave.op` でデコレートするだけで、この関数の入力と出力に加え、実行時間、内部で LLM を使用している場合のトークン情報、コード version などをトラッキングできます。

[<img src="https://mintcdn.com/wb-21fd5541-wbdocs-1882/kTNBEU9hU1PbozeW/weave/guides/integrations/imgs/crewai/crew_with_guardrail.png?fit=max&auto=format&n=kTNBEU9hU1PbozeW&q=85&s=bb46461959aa96687c89e9fa4df6b8f7" alt="guardrail.png" width="3456" height="1994" data-path="weave/guides/integrations/imgs/crewai/crew_with_guardrail.png" />](https://wandb.ai/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)

<div id="conclusion">
  ## まとめ
</div>

このインテグレーションの改善点について、ぜひご意見をお寄せください。問題が発生した場合は、[こちら](https://github.com/wandb/weave/issues/new/choose) から issue を作成してください。

CrewAI を使って強力なマルチエージェントシステムを構築する方法については、同社の[豊富なサンプル](https://github.com/crewAIInc/crewAI-examples)や[ドキュメント](https://docs.crewai.com/introduction)をご覧ください。
