Agno : コンセプト : ツール – 独自のツールキットの作成

多くの高度なユースケースではカスタム・ツールキットの作成が必要です。その作成方法は agno.tools.Toolki クラスを継承するクラスを作成し、関数をクラスに追加します。

Agno : ユーザガイド : コンセプト : ツール – 独自のツールキットの作成

作成 : クラスキャット・セールスインフォメーション
作成日時 : 08/11/2025
バージョン : Agno 1.7.7

* 本記事は docs.agno.com の以下のページを独自に翻訳した上で、補足説明を加えてまとめ直しています :

* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。

 

クラスキャット 人工知能 研究開発支援サービス ⭐️ リニューアルしました 😉

クラスキャット は人工知能に関する各種サービスを提供しています。お気軽にご相談ください :

  • 人工知能導入個別相談会(無償)実施中! [詳細]

  • 人工知能研究開発支援 [詳細]
    1. 自社特有情報を含むチャットボット構築支援
    2. 画像認識 (医療系含む) / 画像生成

  • PoC(概念実証)を失敗させないための支援 [詳細]

お問合せ : 下記までお願いします。

  • クラスキャット セールス・インフォメーション
  • sales-info@classcat.com
  • ClassCatJP

 

 

Agno ユーザガイド : コンセプト : ツール – 独自のツールキットの作成

多くの高度なユースケースではカスタム・ツールキットの作成が必要です。一般的な流れは :

  1. agno.tools.Toolki クラスを継承するクラスを作成します。

  2. 関数をクラスに追加します。

  3. Important: すべての関数を Toolkit コンストラクタの tools 引数に含めてください。

これでツールキットはエージェントで使用できるようになりました。例えば :

shell_toolkit.py

from typing import List

from agno.agent import Agent
from agno.tools import Toolkit
from agno.utils.log import logger

class ShellTools(Toolkit):
    def __init__(self, **kwargs):
        super().__init__(name="shell_tools", tools=[self.run_shell_command], **kwargs)

    def run_shell_command(self, args: List[str], tail: int = 100) -> str:
        """
        Runs a shell command and returns the output or error.

        Args:
            args (List[str]): The command to run as a list of strings.
            tail (int): The number of lines to return from the output.
        Returns:
            str: The output of the command.
        """
        import subprocess

        logger.info(f"Running shell command: {args}")
        try:
            logger.info(f"Running shell command: {args}")
            result = subprocess.run(args, capture_output=True, text=True)
            logger.debug(f"Result: {result}")
            logger.debug(f"Return code: {result.returncode}")
            if result.returncode != 0:
                return f"Error: {result.stderr}"
            # return only the last n lines of the output
            return "\n".join(result.stdout.split("\n")[-tail:])
        except Exception as e:
            logger.warning(f"Failed to run shell command: {e}")
            return f"Error: {e}"

agent = Agent(tools=[ShellTools()], show_tool_calls=True, markdown=True)
agent.print_response("List all the files in my home directory.")

(訳註: 上述のコードは ~ がうまく展開されないなどの問題があります。)

修正版

from typing import List

from agno.agent import Agent
from agno.tools import Toolkit
from agno.utils.log import logger

class ShellTools(Toolkit):
    def __init__(self, **kwargs):
        super().__init__(name="shell_tools", tools=[self.run_shell_command], **kwargs)

    def run_shell_command(self, args: List[str], tail: int = 100) -> str:
        """
        Runs a shell command and returns the output or error.

        Args:
            args (List[str]): The command to run as a list of strings.
            tail (int): The number of lines to return from the output.
        Returns:
            str: The output of the command.
        """
        import subprocess

        # 引数内の~を展開
        expanded_args = []
        for arg in args:
            if arg.startswith('~'):
                expanded_args.append(os.path.expanduser(arg))
            else:
                expanded_args.append(arg)

        logger.info(f"Running shell command: {expanded_args}")
        try:
            logger.info(f"Running shell command: {expanded_args}")
            result = subprocess.run(expanded_args, capture_output=True, text=True)
            logger.debug(f"Result: {result}")
            logger.debug(f"Return code: {result.returncode}")
            if result.returncode != 0:
                return f"Error: {result.stderr}"
            # return only the last n lines of the output
            output_lines = result.stdout.split("\n")
            # Remove empty lines at the end
            while output_lines and output_lines[-1] == "":
                output_lines.pop()
            return "\n".join(output_lines[-tail:]) if output_lines else ""
        except Exception as e:
            logger.warning(f"Failed to run shell command: {e}")
            return f"Error: {e}"

agent = Agent(tools=[ShellTools()], show_tool_calls=True, markdown=True)
agent.print_response("List all the files in my home directory.")

 

以上