semantic-frame について
semantic-frame は数値系列や表を分析し、LLM アプリケーション向けの簡潔な文章や構造化データに変換します。傾向や異常などを決定的に計算してからエージェントへ渡したい開発者やデータチーム向けです。
主な機能
- 01傾向・変動・異常の分析
- 02季節性と分布の分析
- 03ステップ変化とデータ品質の検出
- 04文章・JSON・詳細結果の出力
- 05バッチおよび DataFrame の分析
活用シーン
- 01CPU とメモリの監視データの要約
- 02売上や市場の時系列データの記述
- 03エージェント用の簡潔なデータコンテキスト作成
MCP 対応
MCP サーバーは MCP クライアントに `describe_data` とバッチ分析ツールを公開します。利用可能なツールには `describe_batch` と `describe_json` があります。
設定
ローカルサーバーの設定はどのクライアントでも共通です。コピーしてクライアントの MCP 設定ファイルに貼り付けてください。
ツール
ローカルサーバーのツールはマシン上で起動して初めて取得できます。メンテナーはまだツール一覧を提供していません。
詳細
Semantic Frame
数値データをトークン効率よく意味圧縮します。
Semantic Frame は、生の数値データ(NumPy、Pandas、Polars)を、LLM が扱いやすい自然言語の説明に変換します。何千ものデータポイントを AI エージェントに送る代わりに、50 語の意味的な要約を送信できます。
問題点
LLM は算術処理が苦手です。[100, 102, 99, 101, 500, 100, 98] のような生データを GPT-4 や Claude に送信すると、次のような問題が発生します。
- トークンの浪費:1000 個のデータポイントで約 2000 トークンを消費します
- ハルシネーションのリスク:LLM は傾向を計算する代わりに推測します
- コンテキストの超過:大規模なデータセットがコンテキストウィンドウを埋め尽くします
解決策
Semantic Frame は NumPy を使って決定論的な分析を行い、結果をトークン効率のよい説明文に変換します。
from semantic_frame import describe_series
import pandas as pd
data = pd.Series([100, 102, 99, 101, 500, 100, 98])
print(describe_series(data, context="Server Latency (ms)"))
出力:
The Server Latency (ms) data shows a flat/stationary pattern with stable
variability. 1 anomaly detected at index 4 (value: 500.00).
Baseline: 100.00 (range: 98.00-500.00).
結果:トークンを 95% 以上削減し、ハルシネーションのリスクをゼロにします。
インストール
pip install semantic-frame
または uv を使用します。
uv add semantic-frame
🤖 Claude との連携(MCP)
Semantic Frame は公式 MCP Registryで利用でき、Claude と直接連携できます。
Claude Code CLI:
claude mcp add semantic-frame
Claude Desktop - claude_desktop_config.json に追加します。
macOS:~/Library/Application Support/Claude/claude_desktop_config.json
Windows:%APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"semantic-frame": {
"command": "uvx",
"args": ["--from", "semantic-frame[mcp]", "semantic-frame-mcp"]
}
}
}
設定が完了すると、Claude は次のツールを使用できます。
describe_data- 単一のデータ系列を分析しますdescribe_batch- 複数の系列を一度に分析しますdescribe_json- 構造化された JSON 出力を取得します
クイックスタート
系列を分析する
from semantic_frame import describe_series
import numpy as np
# Works with NumPy arrays
data = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
result = describe_series(data, context="Daily Sales")
print(result)
# "The Daily Sales data shows a rapidly rising pattern with moderate variability..."
DataFrame を分析する
from semantic_frame import describe_dataframe
import pandas as pd
df = pd.DataFrame({
'cpu': [40, 42, 41, 95, 40, 41],
'memory': [60, 61, 60, 60, 61, 60],
})
results = describe_dataframe(df, context="Server Metrics")
print(results['cpu'].narrative)
# "The Server Metrics - cpu data shows a flat/stationary pattern..."
構造化された出力を取得する
result = describe_series(data, output="full")
print(result.trend) # TrendState.RISING_SHARP
print(result.volatility) # VolatilityState.MODERATE
print(result.anomalies) # [AnomalyInfo(index=4, value=500.0, z_score=4.2)]
print(result.compression_ratio) # 0.95
API 用の JSON 出力
result = describe_series(data, output="json")
# Returns dict ready for JSON serialization
対応データ型
- NumPy:
np.ndarray - Pandas:
pd.Series、pd.DataFrame - Polars:
pl.Series、pl.DataFrame - Python:
list
分析機能
| 機能 | 手法 | 出力 |
|---|---|---|
| 傾向 | 線形回帰の傾き | RISING_SHARP、RISING_STEADY、FLAT、FALLING_STEADY、FALLING_SHARP |
| 変動性 | 変動係数 | COMPRESSED、STABLE、MODERATE、EXPANDING、EXTREME |
| 異常値 | Z スコア/IQR 適応型 | 各外れ値のインデックス、値、Z スコア |
| 季節性 | 自己相関 | NONE、WEAK、MODERATE、STRONG |
| 分布 | 歪度+尖度 | NORMAL、LEFT_SKEWED、RIGHT_SKEWED、BIMODAL、UNIFORM |
| ステップ変化 | ベースラインのシフト検出 | NONE、STEP_UP、STEP_DOWN |
| データ品質 | 欠損値の割合 | PRISTINE、GOOD、SPARSE、FRAGMENTED |
LLM との連携
システムプロンプトへの挿入
from semantic_frame.interfaces import format_for_system_prompt
result = describe_series(data, output="full")
prompt = format_for_system_prompt(result)
# Returns formatted context block for system prompts
LangChain ツールの出力
from semantic_frame.interfaces import format_for_langchain
output = format_for_langchain(result)
# {"output": "narrative...", "metadata": {...}}
複数列のエージェントコンテキスト
from semantic_frame.interfaces import create_agent_context
results = describe_dataframe(df)
context = create_agent_context(results)
# Combined narrative for all columns with attention flags
フレームワークとの連携
Anthropic Claude(ネイティブなツール使用)
pip install semantic-frame[anthropic]
import anthropic
from semantic_frame.integrations.anthropic import get_anthropic_tool, handle_tool_call
client = anthropic.Anthropic()
tool = get_anthropic_tool()
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
tools=[tool],
messages=[{"role": "user", "content": "Analyze this sales data: [100, 120, 115, 500, 118]"}]
)
# Handle tool use in response
for block in response.content:
if block.type == "tool_use" and block.name == "semantic_analysis":
result = handle_tool_call(block.input)
print(result)
LangChain
pip install semantic-frame[langchain]
from semantic_frame.integrations.langchain import get_semantic_tool
tool = get_semantic_tool()
# Use as a LangChain BaseTool in your agent
CrewAI
pip install semantic-frame[crewai]
from semantic_frame.integrations.crewai import get_crewai_tool
tool = get_crewai_tool()
# Use with CrewAI agents
MCP(Model Context Protocol)
pip install semantic-frame[mcp]
MCP サーバーを起動します。
mcp run semantic_frame.integrations.mcp:mcp
describe_data ツールを公開し、次のような MCP クライアントから利用できます。
- ElizaOS:TypeScript ベースのエージェントフレームワーク
- Claude Desktop:Anthropic のデスクトップアプリ
- Claude Code:Claude 用の Anthropic の CLI
- その他すべての MCP 対応クライアント
Claude Code
Claude Code に Semantic Frame をネイティブツールとして追加します。
# Install MCP dependencies
pip install semantic-frame[mcp]
# Add MCP server to Claude Code
claude mcp add semantic-frame -- uv run --project /path/to/semantic-frame mcp run /path/to/semantic-frame/semantic_frame/integrations/mcp.py
# Restart Claude Code, then verify connection
claude mcp list
# semantic-frame: ... - ✓ Connected
設定が完了すると、Claude にデータ分析を依頼した際に describe_data ツールが自動的に使用されます。
高度なツール使用(ベータ版)
Semantic Frame は、複雑なエージェントのワークフローで効率的にツールをオーケストレーションするため、Anthropic の Advanced Tool Use 機能に対応しています。
機能
| 機能 | メリット | API |
|---|---|---|
| 入力例 | パラメーターの精度が+18%向上 | デフォルトで含まれます |
| ツール検索 | コンテキストを肥大化させずに1000以上のツールを利用 | defer_loading=True |
| プログラムによる呼び出し | コード実行によるバッチ分析 | allowed_callers=["code_execution"] |
クイックスタート(上級者向け)
import anthropic
from semantic_frame.integrations.anthropic import get_advanced_tool, handle_tool_call
client = anthropic.Anthropic()
tool = get_advanced_tool() # All advanced features enabled
response = client.beta.messages.create(
betas=["advanced-tool-use-2025-11-20"],
model="claude-sonnet-4-5-20250929",
max_tokens=4096,
tools=[
{"type": "tool_search_tool_regex_20251119", "name": "tool_search"},
{"type": "code_execution_20250825", "name": "code_execution"},
tool,
],
messages=[{"role": "user", "content": "Analyze all columns in this dataset..."}]
)
設定オプション
from semantic_frame.integrations.anthropic import (
get_anthropic_tool, # Standard (includes examples)
get_tool_for_discovery, # For Tool Search
get_tool_for_batch_processing, # For code execution
get_advanced_tool, # All features enabled
)
MCP バッチ分析
from semantic_frame.integrations.mcp import describe_batch
# Analyze multiple series in one call
result = describe_batch(
datasets='{"cpu": [45, 47, 95, 44], "memory": [60, 61, 60, 61]}',
)
詳しいドキュメントについては、docs/advanced-tool-use.mdをご覧ください。
ユースケース
暗号資産取引
btc_prices = pd.Series(hourly_btc_prices)
insight = describe_series(btc_prices, context="BTC/USD Hourly")
# "The BTC/USD Hourly data shows a rapidly rising pattern with extreme variability.
# Step up detected at index 142. 2 anomalies detected at indices 89, 203."
DevOps のモニタリング
cpu_data = pd.Series(cpu_readings)
insight = describe_series(cpu_data, context="CPU Usage %")
# "The CPU Usage % data shows a flat/stationary pattern with stable variability
# until index 850, where a critical anomaly was detected..."
営業分析
sales = pd.Series(daily_sales)
insight = describe_series(sales, context="Daily Revenue")
# "The Daily Revenue data shows a steadily rising pattern with weak cyclic pattern
# detected. Baseline: $12,450 (range: $8,200-$18,900)."
IoT センサーデータ
temps = pl.Series("temperature", sensor_readings)
insight = describe_series(temps, context="Machine Temperature (C)")
# "The Machine Temperature (C) data is expanding with extreme outliers.
# 3 anomalies detected at indices 142, 156, 161."
📈 取引モジュール(v0.4.0)
取引エージェント、ポートフォリオマネージャー、金融アプリケーション向けの、専門的なセマンティック分析機能です。
取引ツール
| ツール | 説明 |
|---|---|
describe_drawdown | ドローダウンの深刻度を含むエクイティカーブ分析 |
describe_trading_performance | 勝率、シャープレシオ、プロフィットファクターの指標 |
describe_rankings | 複数のエージェント/戦略の比較 |
describe_anomalies | 損益情報を加味した高度な異常検知 |
describe_windows | 複数の時間枠におけるトレンドの一致度 |
describe_regime | 市場レジームの検知(強気/弱気/横ばい) |
describe_allocation | ポートフォリオ配分の提案 ⚠️ |
使用例
from semantic_frame.trading import (
describe_trading_performance,
describe_drawdown,
describe_regime,
describe_allocation,
)
# Trading Performance
pnl = [100, -50, 75, -25, 150, -30, 80]
result = describe_trading_performance(pnl, context="My Bot")
print(result.narrative)
# "My Bot shows good performance with 57.1% win rate. Profit factor: 2.53..."
# Drawdown Analysis
equity = [10000, 10500, 10200, 9800, 9500, 10100]
result = describe_drawdown(equity, context="Strategy")
print(result.narrative)
# "Strategy max drawdown: 9.5% (moderate). Currently recovering..."
# Market Regime
returns = [0.01, 0.015, 0.02, -0.01, 0.025, 0.018] # Daily returns
result = describe_regime(returns, context="BTC")
print(result.narrative)
# "BTC is in a strong bullish regime. Conditions favor trend-following..."
# Portfolio Allocation (⚠️ Educational only, not financial advice)
assets = {"BTC": [40000, 42000, 44000], "ETH": [2500, 2650, 2800]}
result = describe_allocation(assets, method="risk_parity")
print(result.narrative)
# "Suggested allocation: BTC (55%), ETH (45%). Risk: high..."
MCP 統合
すべての取引ツールをMCP経由で利用できます。
semantic-frame-mcp
ツール:describe_drawdown、describe_trading_performance、describe_rankings、describe_anomalies、describe_windows、describe_regime、describe_allocation
API リファレンス
describe_series(data, context=None, output="text")
単一のデータ系列を分析します。
パラメーター:
data:入力データ(NumPy 配列、Pandas Series、Polars Series、またはリスト)context:データの任意のラベル(説明文に表示されます)output:形式。"text"(文字列)、"json"(dict)、または"full"(SemanticResult)
戻り値: 指定された形式のセマンティックな説明。
describe_dataframe(df, context=None)
DataFrame内のすべての数値列を分析します。
パラメーター:
df:Pandas または Polars の DataFramecontext:列のコンテキストラベルに付加する任意の接頭辞
戻り値: 列名をSemanticResultオブジェクトに対応付けるdict。
SemanticResult
次の情報を含む完全な分析結果:
narrative:人が読みやすいテキスト形式の説明trend:TrendState enumvolatility:VolatilityState enumdata_quality:DataQuality enumanomaly_state:AnomalyState enumanomalies:AnomalyInfoオブジェクトのリストseasonality:任意のSeasonalityStatedistribution:任意のDistributionShapestep_change:任意のStructuralChange(STEP_UP、STEP_DOWN、NONE)step_change_index:任意のint(ステップ変化が発生したインデックス)profile:統計情報を含むSeriesProfilecompression_ratio:トークン削減率
開発
# Clone and install
git clone https://github.com/yourusername/semantic-frame
cd semantic-frame
uv sync
# Run tests
uv run pytest
# Run with coverage
uv run pytest --cov=semantic_frame
ライセンス
MIT License。LICENSEファイルをご覧ください。
コメント
AI アプリケーションが外部のツールやデータソースに統一的な方法で接続するためのオープンなプロトコルです。クライアントはモデルとの対話を担い、MCP サーバーはツール・リソース・プロンプトテンプレートを提供します。標準メッセージでやり取りするため、1 つのサーバーを複数のクライアントで再利用できます。