1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

CrewAIでToolを活用したAIエージェントの構築

Posted at

CrewAIのToolを使ったAIエージェント構築

CrewAIは複数のエージェントを連携させ、役割(Role)目標(Goal)バックストーリー(Backstory) に基づいて動作するフレームワークです。
さらに、CrewAIには「Tool(ツール)」という強力な拡張機能があり、AIがプログラムの関数を自律的に呼び出して外部処理を行うことができます。

この記事では、Tool を活用して 「文の文字数を数えるAIエージェント」 を作成します。

関連Qiita記事

CrewAIで超簡単な翻訳エージェントを作ってみた

0.Toolとは?

CrewAIのToolは、エージェントが外部のPython関数を呼び出して、
データ処理・API呼び出し・数値計算 などの具体的なタスクを実行できる仕組みです。

例えば以下のように、@tool デコレーターを付けることで関数をToolとして定義します。

tools.py
from crewai.tools import tool

@tool
def count_letters(sentence: str):
    """
    This function is to count the amount of letters in a sentence.
    The input is a `sentence` string.
    The output is a number.
    """
    print("tool called with input:", sentence)
    return len(sentence)

@tool は、CrewAIがこの関数をAIエージェントが使用できるツールとして登録するためのデコレーターです。
これにより、エージェントが「自分が実行できる関数」として認識し、自然言語から動的に呼び出すことが可能になります。

""" は単なるコメントではなく、AIエージェントにとっての説明書です。
CrewAIフレームワークでは、このdocstringの内容をもとにツールの使い方を理解します。

1.エージェントの定義

agents.yaml
counter_agent:
  role: >
    To count the length of things.
  goal: >
    To be a good counter that never lies or makes things up.
  backstory: >
    You are a genius counter.
属性名 説明 参考URL
role エージェントの役割や専門分野を定義 https://docs.crewai.com/concepts/agents
goal タスクを達成するための目的 同上
backstory エージェントのバックグラウンド。人格や文体に影響を与える 同上

2. タスクの定義

tasks.yaml
count_task:
  description: >
    Count the amount of letters in a sentence.
  expected_output: >
    The number of letters in a sentence.
  agent: counter_agent
属性名 説明 参考URL
description タスクの説明。AIが何をすべきかを定義 https://docs.crewai.com/concepts/tasks
expected_output タスクの理想的な出力の形を定義 同上
agent このタスクを担当するエージェント名を指定 同上

3. main.pyの構成

省略されているロジックはCrewAIで超簡単な翻訳エージェントを作ってみたを確認してください!

main.py
import dotenv
dotenv.load_dotenv()

from crewai import Crew, Agent, Task
from crewai.project import CrewBase, agent, task, crew
from tools import count_letters

@CrewBase
class TranslatorCrew:

    @agent
    def counter_agent(self):
        return Agent(
            config=self.agents_config["counter_agent"],
            tools=[count_letters],
        )

    @task
    def count_task(self):
        return Task(
            config=self.tasks_config["count_task"],
        )

    @crew
    def assemble_crew(self):
        return Crew(
            agents=self.agents,
            tasks=self.tasks,
            verbose=True,
        )

TranslatorCrew().assemble_crew().kickoff(
    inputs={
        "sentence": "I'm Jung and I like to ride my bicicle in Napoli",
    }
)
要素 説明
@CrewBase CrewAIの基本クラス定義。エージェントとタスクをまとめる「チーム構成」を定義する。
@agent 各エージェントを定義するデコレーター。ここでは counter_agent が文字数カウント専用のAIを表す。
config=self.agents_config["counter_agent"] agents.yaml に定義された設定を参照。エージェントの役割・目標・背景がここで読み込まれる。
tools=[count_letters] 外部ツール count_letters() をエージェントに紐付け。AIが必要に応じてこのツールを呼び出す。
@task CrewAIのタスクを定義。ここでは count_task が「文章の文字数を数える」指示を表す。
Crew(...) 全てのエージェントとタスクをまとめたチームを生成。
kickoff() 実際にチームを起動して処理を開始するメソッド。inputs にユーザーからの入力を渡す。

プログラムを実行すると、CrewAIは以下のような流れで動作します。

  1. kickoff() により Crew が起動
  2. count_task が counter_agent に割り当てられる
  3. counter_agent が count_letters() ツールを呼び出す
  4. ツールが文字数を計算して結果を返す
  5. CrewAI が結果を出力

4. 実行結果

% uv run main.py
tool called with input: 저는 정이고, 나폴리에서 자전거 타는 것을 좋아합니다.

╭────────────────────────────────────────────────────────────────────────── 🔧 Agent Tool Execution ──────────────────────────────────────────────────────────────────────────╮
│  Agent: To count the lenght of things.                                                                                                                                      │
│  Thought: I need to count the number of letters in the given sentence.                                                                                                      │
│  Using Tool: count_letters                                                                                                                                                  │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

╭──────────────────────────────────────────────────────────────────────────────── Tool Input ─────────────────────────────────────────────────────────────────────────────────╮
│  { "sentence": "저는 정이고, 나폴리에서 자전거 타는 것을 좋아합니다." }                                                                                                     │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

╭──────────────────────────────────────────────────────────────────────────────── Tool Output ────────────────────────────────────────────────────────────────────────────────╮
│  30                                                                                                                                                                         │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯


上は実際にプログラムを実行したときのログの一部です。

ステップ 動作 詳細
Crew起動 kickoff() によりタスクが開始される
タスク割り当て count_taskcounter_agent に割り当てられる
エージェント思考 「文の長さを数える必要がある」と判断
Tool呼び出し count_letters() 関数を実行
結果出力 関数の戻り値(30)がCrewの最終出力として返る

5. まとめ

この例では、CrewAIの「Tool」機能を通じて
AIが自律的にPython関数を選択して実行する様子を見ることができました。

ポイントをまとめると以下の通りです:

  1. @tool を使うとAIが理解可能な関数になる
  2. DocstringでAIに関数の意図を伝えることができる
  3. tools=[関数] としてAgentに登録することで、CrewAIが自動で関数を呼び出せる
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?