Open9

Agnoを、はじめるのー

noznoznoznoznoznoznoznoz

Agnoってなんなのー❓

役割としてはLangGraphと同じで、AIエージェントを作るためのパッケージ。ほんとか確かめてないけどLangGraphより10,000倍はえーらしい。LangGraphと違ってグラフの知識を前提としない。

Agno を使用してエージェントを構築する必要がある理由は次のとおりです。

  • 超高速: エージェントの作成は LangGraph よりも約 10,000 倍高速です (パフォーマンスを参照)。
  • モデルに依存しない: 任意のモデル、任意のプロバイダーを使用でき、ロックインはありません。
  • マルチモーダル: テキスト、画像、オーディオ、ビデオの入出力をネイティブにサポートします。
  • マルチエージェント: 専門のエージェントのチーム全体にタスクを委任します。
  • メモリ管理: エージェントのセッションと状態をデータベースに保存します。
  • ナレッジ ストア: Agentic RAG または動的少数ショットにベクター データベースを使用します。
  • 構造化出力: エージェントが構造化データで応答するようにします。
  • 監視: agno.comでエージェントのセッションとパフォーマンスをリアルタイムで追跡します。

GithubでのKey featuresのGoogle翻訳

noznoznoznoznoznoznoznoz

入門コード見てみる①:Basic Agent

from agno.agent import Agent
from agno.models.openai import OpenAIChat

agent = Agent(
    model=OpenAIChat(id="gpt-4o"),
    description="You are an enthusiastic news reporter with a flair for storytelling!",
    markdown=True
)
agent.print_response("Tell me about a breaking news story from New York.", stream=True)

基本的なコードでほかのLLM API向けパッケージと大きな違いはなさそう?
markdown=Trueの説明みあたらない

noznoznoznoznoznoznoznoz

入門コード見てみる②:Agent with tools

 from agno.agent import Agent
 from agno.models.openai import OpenAIChat
 from agno.tools.duckduckgo import DuckDuckGoTools

 agent = Agent(
     model=OpenAIChat(id="gpt-4o"),
     description="You are an enthusiastic news reporter with a flair for storytelling!",
+    tools=[DuckDuckGoTools()],
     show_tool_calls=True,
     markdown=True
 )
 agent.print_response("Tell me about a breaking news story from New York.", stream=True)

ツールは引数に入れればいいっぽい。デフォで入ってる関数でDuckDuckGoTools()が例として入れられてる。Web検索できるツールらしく、DuckDuckGoっていう検索エンジンをコールしてる。

64 ddgs = DDGS(
65            headers=self.headers, proxy=self.proxy, proxies=self.proxies, timeout=self.timeout, verify=self.verify_ssl
66        )

libs/agno/agno/tools/duckduckgo.py

DDGS関数を使うために下記を入れておく必要がある。

pip install -U duckduckgo-search

DuckDuckGo- Agno

初めて聞いた検索エンジン。検索履歴などを追わない特徴など。

利用者のプライバシーの保護と利用履歴等を記録保存しないことを運営方針としている[2]。
DuckDuckGo - wikipedia

上で出てきたddgs関数の使い方
https://qiita.com/gomi1994/items/2370f16708fe4182ec1e

noznoznoznoznoznoznoznoz

入門コード見てみる③:Agent with knowledge

from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.embedder.openai import OpenAIEmbedder
from agno.tools.duckduckgo import DuckDuckGoTools
from agno.knowledge.pdf_url import PDFUrlKnowledgeBase
from agno.vectordb.lancedb import LanceDb, SearchType

agent = Agent(
    model=OpenAIChat(id="gpt-4o"),
    description="You are a Thai cuisine expert!",
    instructions=[
        "Search your knowledge base for Thai recipes.",
        "If the question is better suited for the web, search the web to fill in gaps.",
        "Prefer the information in your knowledge base over the web results."
    ],
    knowledge=PDFUrlKnowledgeBase(
        urls=["https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"],
        vector_db=LanceDb(
            uri="tmp/lancedb",
            table_name="recipes",
            search_type=SearchType.hybrid,
            embedder=OpenAIEmbedder(id="text-embedding-3-small"),
        ),
    ),
    tools=[DuckDuckGoTools()],
    show_tool_calls=True,
    markdown=True
)

# Comment out after the knowledge base is loaded
if agent.knowledge is not None:
    agent.knowledge.load()

agent.print_response("How do I make chicken and galangal in coconut milk soup", stream=True)
agent.print_response("What is the history of Thai curry?", stream=True)

Agent関数の引数instructionsknowledgeが追加されてる。

引数 説明
instructions エージェントに対する指令?descriptionはエージェントの説明?って感じで分けて、他のエージェントは後者を参照して協働とかを決定できるものと予想。
knowledge ベクターDBをサクッと作ってくれる。PDFUrlKnowledgeBase見るにフォーマット(ここではPDF)ごとに読み込み用の関数がパッケージにありそう
noznoznoznoznoznoznoznoz

入門コード見てみる④:Multi Agent Teams

from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.tools.duckduckgo import DuckDuckGoTools
from agno.tools.yfinance import YFinanceTools

web_agent = Agent(
    name="Web Agent",
    role="Search the web for information",
    model=OpenAIChat(id="gpt-4o"),
    tools=[DuckDuckGoTools()],
    instructions="Always include sources",
    show_tool_calls=True,
    markdown=True,
)

finance_agent = Agent(
    name="Finance Agent",
    role="Get financial data",
    model=OpenAIChat(id="gpt-4o"),
    tools=[YFinanceTools(stock_price=True, analyst_recommendations=True, company_info=True)],
    instructions="Use tables to display data",
    show_tool_calls=True,
    markdown=True,
)

agent_team = Agent(
    team=[web_agent, finance_agent],
    model=OpenAIChat(id="gpt-4o"),
    instructions=["Always include sources", "Use tables to display data"],
    show_tool_calls=True,
    markdown=True,
)

agent_team.print_response("What's the market outlook and financial performance of AI semiconductor companies?", stream=True)

Agent関数が3回使われてて、3人のエージェントを宣言している?ただ、最後は引数roleがなくteamがある。特定の役割を担当するエージェントを宣言するケースと、そういうエージェントを使うエージェントを宣言するケースがある?

  1. メンバー エージェントにパラメーターname, roleを追加します。
  2. チームメンバーにタスクを委任できるチームリーダーを作成します。
  3. 通常のエージェントと同じようにエージェント チームを使用します。
    How to build Agent Teams

上記見るに多分そう。

https://docs.agno.com/examples/getting-started/agent-team#agent-team

これはもうちょっとだけ肉付けした例

noznoznoznoznoznoznoznoz

パッケージ組み込みのツール①:Fileツールの例

全体

from agno.agent import Agent
from agno.tools.file import FileTools

agent = Agent(tools=[FileTools()], show_tool_calls=True)
agent.print_response("What is the most advanced LLM currently? Save the answer to a file.", markdown=True)

追ってみる

from agno.tools.file import FileTools

ここで読み込む

agent = Agent(tools=[FileTools()], show_tool_calls=True)

エージェントに読み込ませる場合はAgent関数のtools引数にわたす

noznoznoznoznoznoznoznoz

パッケージ組み込みのツール②:よく使いそうなツール

ツール名 説明
Python Pythonの書込み・実行するためのツール
Shell シェルをインタラクティブに実行できるツール
Email ユーザーにメールを送信するためのツール
Google Maps Googleマップ上の場所を検索するためのツール
Google Calendar Googleカレンダーのイベントを管理するためのツール
Google Search Googleでの検索を行うためのツール
Newspaper ニュース記事を読むためのツール
OpenBB OpenBBを使用して株式データを検索するためのツール
Sleep 指定された秒数だけ実行を一時停止するためのツール
Website ウェブサイトをスクレイピングするためのツール
YFinance Yahoo Financeを使用して金融データを取得するためのツール
noznoznoznoznoznoznoznoz

パッケージ組み込みのツール③:独自のツールを作成

既存ツールのクラス継承でカスタムする

  1. agno.tools.Toolkitクラスを継承するクラスを作成します
  2. クラスに関数を追加します。
  3. 重要:関数を登録するにはself.register(function_name)
    Writing your own Toolkit

「既存ツールをいじれば済むか」をまず考えた方が良さそう?

関数を作る

任意の Python 関数は、エージェントによるツールとして使用できます。ワークフローに固有の関数を作成し、エージェントに追加することを強くお勧めします。
Python Functions

普通の関数に見えるのでとっつきやすそう

noznoznoznoznoznoznoznoz

ローカルLLMで動かしたい

vLLM + Agnoはいかが

好きなオープンソースllmをvLLMではOpenAIと同じ仕様のAPIサーバーとして立てられる。
https://docs.vllm.ai/en/latest/getting_started/quickstart.html#openai-compatible-server

AgnoはOpenAIと同じ仕様を持つAPIに対してコールする既存のパッケージがある。
https://docs.agno.com/models/openai-like

書いてみた

0.5bだけど量子化しないと動かないかも。
https://colab.research.google.com/drive/1E93rlJzQVlxqrIpPX3DmrjKwMXxHbr_8?usp=sharing

ポイント①:vllmサーバーの起動部分

import subprocess
import time
import os

# vLLM サーバーをバックグラウンドで起動
# ログの作成
log_file = open("vllm_output.log", "w")

#model_name = "qwen/Qwen1.5-0.5B-Chat" # Hugging Faceのモデル名を使う場合
model_path = "./qwen_model" # ローカルにダウンロードしたモデルのパス

# --host, --port, --model, --tensor-parallel-size を適切に設定
process = subprocess.Popen([
    "python", "-m", "vllm.entrypoints.openai.api_server",
    "--host", "0.0.0.0",  # Colab 内でアクセス可能にする
    "--port", "8000",
    "--model", model_path, #model_name,
    "--tensor-parallel-size", "1", # ColabのGPU (T4) では1が無難
    "--dtype", "half",
    "--gpu-memory-utilization", "0.99"
    # 必要であれば、他オプション(gpu-memory-utilization など)も追加
], stdout=log_file, stderr=log_file)

ポイント②:Agnoからコールする部分

from os import getenv
from agno.agent import Agent, RunResponse
from agno.models.openai.like import OpenAILike

agent = Agent(
    model=OpenAILike(
        id=model_path,
        api_key="anything",
        base_url="http://localhost:8000/v1",
    )
)

# Print the response in the terminal
agent.print_response("Share a 2 sentence horror story.")