> ## Documentation Index
> Fetch the complete documentation index at: https://wb-21fd5541-feature-automate-reference-docs-generation.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Crewai

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

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の両方をサポートしています。

## Crewを使い始める

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

```
pip install crewai weave
```

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

```python
import weave
from crewai import Agent, Task, Crew, LLM, Process

# Initialize Weave with your project name
# highlight-next-line
weave.init(project_name="crewai_demo")

# Create an LLM with a temperature of 0 to ensure deterministic outputs
llm = LLM(model="gpt-4o-mini", temperature=0)

# Create agents
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,
)

# Create tasks
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
)

# Create a crew
crew = Crew(
    agents=[researcher, writer],
    tasks=[research_task, writing_task],
    verbose=True,
    process=Process.sequential,
)

# Run the crew
result = crew.kickoff(inputs={"topic": "AI in material science"})
print(result)
```

Weaveは、エージェントのインタラクション、タスクの実行、LLM呼び出しなど、CrewAIライブラリを通じて行われるすべての呼び出しを追跡し、ログに記録します。Weaveウェブインターフェースでトレースを確認できます。

[![crew\_trace.png](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/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()`、`kickoff_for_each()`、`kickoff_async()`、および`kickoff_for_each_async()`。この統合は、これらすべてのメソッドからのトレースのログ記録をサポートしています。
</Note>

## ツールの追跡

CrewAIツールは、ウェブ検索やデータ分析から、同僚間のコラボレーションやタスク委任まで、さまざまな機能をエージェントに提供します。この統合はそれらもトレースすることができます。

上記の例で生成されるレポートの品質を向上させるために、インターネットを検索して最も関連性の高い結果を返すツールへのアクセスを提供します。

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

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

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

```python
# .... existing imports ....
from crewai_tools import SerperDevTool

# We provide the agent with the tool.
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,
    # highlight-next-line
    tools=[SerperDevTool()],
)

# .... existing code ....
```

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

[![crew\_with\_tool\_trace.png](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/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>

## Flowを使い始める

```python
import weave
# Initialize Weave with your project name
# highlight-next-line
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")
        # In a real-world scenario, this could be replaced by an API call.
        # For this example, we simulate customer feedback.
        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):
        # Use the language model to analyze sentiment
        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()
        # If the response is ambiguous, default to negative
        if sentiment not in ["positive", "negative"]:
            sentiment = "negative"
        return sentiment

    @listen("positive")
    def handle_positive_feedback(self):
        # Generate a thank you message for positive feedback
        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):
        # Generate an apology message with a promise to improve service for negative feedback
        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

# Instantiate and kickoff the flow
flow = CustomerFeedbackFlow()
result = flow.kickoff()
print(result)
```

[![flow.png](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/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>

## Crewガードレール - 独自のオペレーションを追跡する

タスクガードレールは、タスク出力を次のタスクに渡す前に検証および変換する方法を提供します。シンプルなPython関数を使用して、エージェントの実行をリアルタイムで検証できます。

この関数を`@weave.op`でラップすると、入力、出力、アプリケーションロジックの取得が開始され、データがエージェントを通じてどのように検証されるかをデバッグできます。これにより、実験時にコードの自動バージョン管理も開始され、gitにコミットされていないアドホックな詳細が取得されます。

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

```python
# .... existing imports and weave initialization ....

# Decorate your guardrail function with `@weave.op()`
# highlight-next-line
@weave.op(name="guardrail-validate_blog_content")
def validate_blog_content(result: TaskOutput) -> Tuple[bool, Any]:
    # Get raw string result
    result = result.raw

    """Validate blog content meets requirements."""
    try:
        # Check word count
        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}
            })

        # Additional validation logic here
        return (True, result.strip())
    except Exception as e:
        return (False, {
            "error": "Unexpected error during validation",
            "code": "SYSTEM_ERROR"
        })


# .... existing agents and research analyst task ....

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,
    # highlight-next-line
    guardrail=validate_blog_content,
)

# .... existing code to run crew ....
```

ガードレール関数を単に`@weave.op`でデコレートするだけで、この関数への入力と出力を、実行時間、LLMが内部で使用されている場合のトークン情報、コードバージョンなどと共に追跡できます。

[![guardrail.png](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/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)

## 結論

この統合について改善すべき点があれば、ぜひお知らせください。問題が発生した場合は、[こちら](https://github.com/wandb/weave/issues/new/choose)で問題を開いてください。

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