CLAP - Cognitive Layer Agent Package について
CLAPは、ツール利用、RAG、エージェント間の連携を必要とする開発者向けの、非同期Pythonフレームワークです。ReActやツールエージェント、複数エージェントのチーム、交換可能なLLMサービス、MCPサーバー接続を備えています。
主な機能
- 01ReActとツールエージェントのパターン
- 02逐次・並列のエージェントチーム
- 03ローカルPythonツールとMCPツール
- 04ChromaDBまたはQdrantによるRAG
- 05交換可能なLLMサービスバックエンド
- 06EVMブロックチェーン連携ツール
活用シーン
- 01ローカルまたはリモートツールを使うエージェントの構築
- 02ベクトルストアからのコンテキスト検索
- 03専門エージェントによるタスク分担
- 04EVMスマートコントラクト操作の自動化
MCP 対応
CLAPはMCPClientManagerを備え、SSE経由でMCPサーバーに接続します。エージェントはサーバーのツールを発見して利用できます。
詳細
CLAP - Cognitive Layer Agent Package
CLAP (Cognitive Layer Agent Package) は、最新のエージェントパターンに基づいた高度な AI エージェントを構築するための構成要素を提供する Python フレームワークです。推論、計画、外部ツール、システム、ナレッジベースとの相互作用が可能なエージェントを簡単に構築できるようにしています。
非同期コア(asyncio)で構築された CLAP は、複雑なエージェントワークフローに対して柔軟性とパフォーマンスを提供します。
- モジュール化されたエージェントパターン:
- ReAct エージェント: 思考プロンプティングとネイティブツール呼び出しを備えた Reason-Act ループを実装します。複雑な推論と RAG に最適です。
- ツールエージェント: 単一ステップのツール使用(シンプルな RAG を含む)のための直感的なエージェントです。
- マルチエージェントチーム: 依存関係を持つ専門化されたエージェントのチームを定義でき、協調的なタスク実行(シーケンシャルまたは並列)を可能にします。
- 高度なツール統合:
- ネイティブ LLM ツール呼び出し: 最新の LLM API を活用して信頼性の高いツール実行を実現します。
- ローカルツール:
@toolデコレータを使用して、ローカル Python 関数(同期・非同期両対応)をツールとして簡単に定義および使用できます。 - リモートツール(MCP): 付属の
MCPClientManagerを通じて Model Context Protocol(MCP) サーバーと統合し、エージェントが外部システムによって公開されたツールを発見して使用できるようにします(現在 SSE トランスポートをサポート)。 - 堅牢な検証と型強制: ツール引数の厳密な検証に
jsonschemaを使用し、一般的な LLM 出力の型強制を試みます(例:文字列の数値を整数に変換)。
- 検索強化生成(RAG)機能:
VectorStoreInterface: さまざまなベクトルデータベースと相互作用するための抽象化です。- サポートされるベクトルストア:
- ChromaDB: (
ChromaStore)ローカルまたはセルフホスト可能なベクトルストレージ用です。 - Qdrant: (
QdrantStore)ローカル(インメモリまたはファイルベース)のベクトルストレージ用です。
- ChromaDB: (
EmbeddingFunctionInterface: 異なる埋め込みモデルとの一貫した相互作用のためのプロトコルです。- サポートされている埋め込み関数ラッパー:
SentenceTransformerEmbeddings:sentence-transformersライブラリのモデルを使用します。OllamaEmbeddings: Ollama 経由でローカルに実行されているモデルを使用して埋め込みを生成します。FastEmbedEmbeddings: CPU 最適化された埋め込みのためにfastembedライブラリを利用します。(注:非同期ラッパー経由での大規模バッチ取得のパフォーマンスは CPU に基づいて異なる可能性があり、初期バルクロード時には SentenceTransformers より遅くなる可能性があります。)
- RAG 対応エージェント:
Agent(ReactAgent経由)とToolAgentの両方をvector_storeで装備でき、vector_queryツール呼び出しを実行して、応答する前にコンテキストを取得できます。 - ユーティリティ:
clap.utils.rag_utilsに基本的な PDF および CSV テキストローダーとチャンキング戦略が含まれています。
- プラガブル LLM バックエンド:
- ストラテジーパターン(
LLMServiceInterface)を使用して LLM 相互作用を抽象化します。 - 以下の即座に使用可能なサービス実装が含まれています:
- Groq: (
GroqService) - Google Generative AI(Gemini): (OpenAI 互換レイヤー経由の
GoogleOpenAICompatService) - Ollama(ローカル LLM): (OpenAI 互換レイヤー経由の
OllamaOpenAICompatService、別名OllamaService。Llama 3、Mistral などのローカルで実行されるモデルの使用を可能にします。)
- Groq: (
- 他の LLM プロバイダーをサポートするために簡単に拡張可能です。
- ストラテジーパターン(
- 非同期コア: I/O 操作の効率的な処理と潜在的な同時実行のために
asyncio全体で構築されています。 - 構造化されたコンテキスト受け渡し: チーム内のエージェント間での明確で組織的な情報フローを可能にします。
- 組み込みツール: ウェブ検索(
duckduckgo_search)用のヘルパーが含まれています。さらに多くのツールはオプション依存関係経由で利用可能です。
インストール
Python 3.10 以降がインストールされていることを確認してください。
pip install clap-agents
Python 3.10 以降がインストールされていることを確認してください。
pip install clap-agents
To use specific features, you might need to install optional dependencies:
# For Qdrant support (includes fastembed)
pip install "clap-agents[qdrant]"
# For ChromaDB support
pip install "clap-agents[chromadb]"
# For Ollama (LLM and/or Embeddings)
pip install "clap-agents[ollama]"
# For other tools like web crawling or visualization
pip install "clap-agents[standard_tools,viz]"
# To install all major optional dependencies
pip install "clap-agents[all]"
[project.optional-dependencies] の完全なリストについては pyproject.toml を確認してください。また、Ollama または Qdrant(ローカルで使用する場合)などの外部サービスが実行されている必要があります。 使用するツールまたは LLM バックエンドに応じて、pyproject.toml に記載された追加の依存関係(例:groq、openai、mcp、jsonschema、requests、duckduckgo-search、graphviz)が必要になる場合があります。[project.dependencies] と [project.optional-dependencies] セクションを確認してください。
クイックスタート:ローカルツールを使ったシンプルなツール呼び出しエージェント
この例では、Groq バックエンドとローカルツールを使って、ツール呼び出しエージェントを作成する方法を紹介します。
from dotenv import load_dotenv
from clap import ToolAgent
from clap import duckduckgo_search
load_dotenv()
async def main():
agent = ToolAgent(tools=duckduckgo_search, model="meta-llama/llama-4-scout-17b-16e-instruct")
user_query = "Search the web for recent news about AI advancements."
response = await agent.run(user_msg=user_query)
print(f"Response:\n{response}")
asyncio.run(main())
クイックスタート:ローカルツールを使ったシンプルな ReAct エージェント
この例では、Groq バックエンドとローカルツールを使って、ReAct エージェントを作成する方法を紹介します。
import asyncio
import os
from dotenv import load_dotenv
from clap import ReactAgent, tool, GroqService
load_dotenv()
@tool
def get_word_length(word: str) -> int:
"""Calculates the length of a word."""
print(f"[Local Tool] Calculating length of: {word}")
return len(word)
async def main():
groq_service = GroqService() # Your service of choice (either groq or Google)
agent = ReactAgent(
llm_service=groq_service,
model="llama-3.3-70b-versatile", # Or another Groq model
tools=[get_word_length], # Provide the local tool
# system_prompt="You are a helpful assistant." # Optional base prompt
)
user_query = "How many letters are in the word 'framework'?"
response = await agent.run(user_msg=user_query)
print(response)
asyncio.run(main())
クイックスタート:Ollama を使ったシンプルなツール呼び出しエージェント
この例では、ローカルの Ollama モデルとローカルツールを使う ToolAgent を紹介します。 Ollama が実行中で、モデルをプル済みであることを確認してください(例:ollama pull llama3)。
import asyncio
from dotenv import load_dotenv
from clap import ToolAgent, tool, OllamaService # Assuming OllamaService is your OllamaOpenAICompatService
load_dotenv()
@tool
def get_capital(country: str) -> str:
"""Returns the capital of a country."""
if country.lower() == "france": return "Paris"
return f"I don't know the capital of {country}."
async def main():
# Initialize the Ollama service
ollama_llm_service = OllamaService(default_model="llama3") # Specify your Ollama model
agent = ToolAgent(
llm_service=ollama_llm_service,
model="llama3", # Model name for this agent
tools=[get_capital]
)
user_query = "What is the capital of France?"
response = await agent.run(user_msg=user_query)
print(f"Query: {user_query}\nResponse:\n{response}")
await ollama_llm_service.close() # Important for OllamaService
if __name__ == "__main__":
asyncio.run(main())
クイックスタート:Qdrant と Ollama Embeddings を使った RAG エージェント
この例では、Ollama を埋め込みに、Qdrant をベクトルストアに使って、エージェントが RAG を実行する方法を紹介します。 Ollama(nomic-embed-text と llama3 をプル済み)と Qdrant(例:Docker 経由)が実行中であることを確認してください。
import asyncio
import os
import shutil
from dotenv import load_dotenv
from clap import Agent, QdrantStore, OllamaEmbeddings, OllamaService
from clap.utils.rag_utils import chunk_text_by_fixed_size
from qdrant_client import models as qdrant_models # If needed for distance
load_dotenv()
OLLAMA_HOST = "http://localhost:11434"
EMBED_MODEL = "nomic-embed-text"
LLM_MODEL = "llama3"
DB_PATH = "./temp_rag_db_ollama_qdrant"
COLLECTION = "my_rag_docs"
async def main():
if os.path.exists(DB_PATH): shutil.rmtree(DB_PATH)
ollama_ef = OllamaEmbeddings(model_name=EMBED_MODEL, ollama_host=OLLAMA_HOST)
vector_store = await QdrantStore.create(
collection_name=COLLECTION,
embedding_function=ollama_ef,
path=DB_PATH, # For local file-based Qdrant
recreate_collection_if_exists=True
)
sample_texts = ["The sky is blue due to Rayleigh scattering.", "Large language models are powerful."]
chunks = [chunk for text in sample_texts for chunk in chunk_text_by_fixed_size(text, 100, 10)]
ids = [str(i) for i in range(len(chunks))] # Qdrant needs UUIDs; QdrantStore handles this
if chunks:
await vector_store.add_documents(documents=chunks, ids=ids)
print(f"Ingested {len(chunks)} chunks.")
ollama_llm_service = OllamaService(default_model=LLM_MODEL, base_url=f"{OLLAMA_HOST}/v1")
rag_agent = Agent(
name="RAGMaster",
backstory="I answer questions using provided documents.",
task_description="Why is the sky blue according to the documents?", # This becomes the User Query
llm_service=ollama_llm_service,
model=LLM_MODEL,
vector_store=vector_store
)
response = await rag_agent.run()
print(f"Query: {rag_agent.task_description}\nResponse:\n{response.get('output')}")
await vector_store.close()
await ollama_llm_service.close()
if os.path.exists(DB_PATH): shutil.rmtree(DB_PATH)
asyncio.run(main())
v0.3.0 の新機能:Web3 とオンチェーンエージェント機能
CLAP には、Ethereum のような EVM 互換ブロックチェーンと直接やり取りできる自律型エージェントを構築するための強力なツールキットが追加されました。エージェントが資産を保有し、トランザクションを実行し、スマートコントラクトとやり取りできるようになり、DeFi、DAO、オンチェーン自動化に新たな可能性が広がります。 セットアップ Web3 機能を有効にするには、web3 extra をインストールしてください。
pip install "clap-agents[web3]"
また、.env ファイルに次の変数を設定する必要があります。
# Your connection to the blockchain (e.g., from Alchemy or Infura)
WEB3_PROVIDER_URL="https://sepolia.infura.io/v3/YOUR_API_KEY"
# The private key for your agent's wallet.
# WARNING: For testing only. Do not use a key with real funds.
AGENT_PRIVATE_KEY="0xYourTestnetPrivateKeyHere"
Web3 の主要ツール
このフレームワークには、オンチェーンでのやり取りに使える、事前構築済みの堅牢なツール一式が含まれるようになりました。
get_erc20_balance:ウォレット内の標準 ERC-20 トークンの残高を確認します。
wrap_eth:ネイティブ ETH を WETH(Wrapped Ether)に変換します。これは多くの DeFi プロトコルとやり取りするために必要な手順です。
swap_exact_tokens_for_tokens:Uniswap V3 で取引を実行し、エージェントがポートフォリオを自律的にリバランスできるようにします。
get_token_price:オンチェーンの Chainlink オラクルからリアルタイムの資産価格を取得し、データに基づく意思決定を可能にします。
interact_with_contract:アドレスと ABI を指定して、任意のスマートコントラクトの任意の関数を呼び出せる強力な汎用ツールです。
クイックスタート:シンプルな DeFi エージェント
この例では、ETH をラップした後、別のトークンにスワップするエージェントを紹介します。これは一般的な DeFi タスクです。
import os
import asyncio
from dotenv import load_dotenv
from clap import ReactAgent, GroqService
from clap.tools import wrap_eth, swap_exact_tokens_for_tokens
load_dotenv()
# --- Configuration ---
WETH_ADDRESS = "0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14" # WETH on Sepolia
USDC_ADDRESS = "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7a98" # USDC on Sepolia
async def main():
# We use a ReactAgent for multi-step reasoning
agent = ReactAgent(
llm_service=GroqService(),
tools=[wrap_eth, swap_exact_tokens_for_tokens],
model="llama-3.3-70b-versatile",
system_prompt="You are a DeFi agent. You execute financial transactions precisely as instructed.",
# For on-chain tasks, sequential execution is safer to avoid race conditions
parallel_tool_calls=False
)
# A clear, two-step task for the agent
user_query = f"""
First, wrap 0.01 ETH.
Second, after the wrap is successful, swap that 0.01 WETH for USDC.
The WETH address is {WETH_ADDRESS} and the USDC address is {USDC_ADDRESS}.
"""
print("--- Running Simple DeFi Agent ---")
response = await agent.run(user_msg=user_query, max_rounds=5)
print("\n--- Agent Final Response ---")
print(response)
if __name__ == "__main__":
asyncio.run(main())
この新機能により、CLAP エージェントは単なる観察者から、分散型経済に積極的に参加する存在へと変わります。
さらに詳しく
マルチエージェントチーム:順次または並列のエージェントワークフローを設定する方法については、examples/test_clap_comprehensive_suite.py とその他のチームの例を参照してください。
MCP 統合:examples/test_clap_comprehensive_suite.py を確認してください(examples/simple_mcp.py などに対応する MCP サーバーが実行中であることを確認してください)。
その他の LLM サービス(Groq、Google Gemini、Ollama):クイックスタートを変更して、GroqService または GoogleOpenAICompatService を使用してください(API キーが設定されていることを確認してください)。
さまざまなベクトルストアと埋め込み関数:包括的なテストスイートで紹介されている ChromaStore、QdrantStore、SentenceTransformerEmbeddings、FastEmbedEmbeddings、OllamaEmbeddings を試してみてください。
ライセンス このプロジェクトは Apache License 2.0 の条件に基づいてライセンスされています。詳細については LICENSE ファイルを参照してください。
コメント
AI アプリケーションが外部のツールやデータソースに統一的な方法で接続するためのオープンなプロトコルです。クライアントはモデルとの対話を担い、MCP サーバーはツール・リソース・プロンプトテンプレートを提供します。標準メッセージでやり取りするため、1 つのサーバーを複数のクライアントで再利用できます。