インストール
コンテンツ詳細
代替品
インストール
{
"mcpServers": {
"semantic-frame": {
"command": "uvx",
"args": ["--from", "semantic-frame[mcp]", "semantic-frame-mcp"]
}
}
}🚀 Semantic Frame
数値データのトークン効率的なセマンティック圧縮を実現します。
Semantic Frameは、生の数値データ(NumPy、Pandas、Polars)を、LLMでの消費に最適化された自然言語の説明に変換します。何千ものデータポイントをAIエージェントに送信する代わりに、50語程度のセマンティックな要約を送信することができます。
🚀 クイックスタート
シリーズの分析
from semantic_frame import describe_series
import numpy as np
# NumPy配列でも動作します
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..."
データフレームの分析
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")
# JSONシリアライズ可能な辞書を返します
✨ 主な機能
問題の所在
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
💻 使用例
基本的な使用法
# シリーズの分析
from semantic_frame import describe_series
import numpy as np
data = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
result = describe_series(data, context="Daily Sales")
print(result)
高度な使用法
# 高度なツールの使用(ベータ版)
import anthropic
from semantic_frame.integrations.anthropic import get_advanced_tool, handle_tool_call
client = anthropic.Anthropic()
tool = get_advanced_tool() # すべての高度な機能が有効になっています
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..."}]
)
📚 ドキュメント
サポートされるデータ型
- 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)
# システムプロンプト用のフォーマットされたコンテキストブロックを返します
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)
# すべての列の結合されたナラティブと注意フラグ
フレームワーク統合
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]"}]
)
# レスポンス内のツール使用を処理する
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()
# LangChainのBaseToolとしてエージェントで使用する
CrewAI
pip install semantic-frame[crewai]
from semantic_frame.integrations.crewai import get_crewai_tool
tool = get_crewai_tool()
# CrewAIエージェントと一緒に使用する
MCP (Model Context Protocol)
pip install semantic-frame[mcp]
MCPサーバーを起動する:
mcp run semantic_frame.integrations.mcp:mcp
以下のようなMCPクライアント向けに describe_data ツールを公開します:
- ElizaOS: TypeScriptベースのエージェントフレームワーク
- Claude Desktop: Anthropicのデスクトップアプリ
- Claude Code: AnthropicのClaude用CLI
- 任意のMCP互換クライアント
Claude Code
Claude Code でSemantic Frameをネイティブツールとして追加する:
# MCP依存関係をインストールする
pip install semantic-frame[mcp]
# Claude CodeにMCPサーバーを追加する
claude mcp add semantic-frame -- uv run --project /path/to/semantic-frame mcp run /path/to/semantic-frame/semantic_frame/integrations/mcp.py
# Claude Codeを再起動し、接続を確認する
claude mcp list
# semantic-frame: ... - ✓ Connected
設定が完了すると、Claudeにデータを分析するように依頼すると、自動的に describe_data ツールが使用されます。
高度なツールの使用 (ベータ版)
機能
| 機能 | 利点 | 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() # すべての高度な機能が有効になっています
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, # 標準 (入力例を含む)
get_tool_for_discovery, # ツール検索用
get_tool_for_batch_processing, # コード実行用
get_advanced_tool, # すべての機能が有効になっています
)
MCPバッチ分析
from semantic_frame.integrations.mcp import describe_batch
# 一度に複数のシリーズを分析する
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 |
PnLコンテキストを持つ強化された異常検出 |
describe_windows |
複数の時間枠のトレンドの一致 |
describe_regime |
市場レジームの検出 (強気/弱気/横ばい) |
describe_allocation |
ポートフォリオの配分提案 ⚠️ |
クイックサンプル
from semantic_frame.trading import (
describe_trading_performance,
describe_drawdown,
describe_regime,
describe_allocation,
)
# 取引パフォーマンス
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..."
# ドローダウン分析
equity = [10000, 10500, 10200, 9800, 9500, 10100]
result = describe_drawdown(equity, context="Strategy")
print(result.narrative)
# "Strategy max drawdown: 9.5% (moderate). Currently recovering..."
# 市場レジーム
returns = [0.01, 0.015, 0.02, -0.01, 0.025, 0.018] # 日次リターン
result = describe_regime(returns, context="BTC")
print(result.narrative)
# "BTC is in a strong bullish regime. Conditions favor trend-following..."
# ポートフォリオ配分 (⚠️ 教育目的のみ、金融的なアドバイスではありません)
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"(辞書), または"full"(SemanticResult)
戻り値: 要求されたフォーマットのセマンティックな説明。
describe_dataframe(df, context=None)
データフレーム内のすべての数値列を分析します。
パラメータ:
df: PandasまたはPolarsのデータフレームcontext: 列のコンテキストラベルのオプションの接頭辞
戻り値: 列名をSemanticResultオブジェクトにマッピングする辞書。
SemanticResult
完全な分析結果で、以下の属性を持ちます。
narrative: 人間が読めるテキストの説明trend: TrendState列挙型volatility: VolatilityState列挙型data_quality: DataQuality列挙型anomaly_state: AnomalyState列挙型anomalies: AnomalyInfoオブジェクトのリストseasonality: オプションのSeasonalityStatedistribution: オプションのDistributionShapestep_change: オプションのStructuralChange (STEP_UP, STEP_DOWN, NONE)step_change_index: オプションの整数 (段階的な変化が発生したインデックス)profile: 統計情報を持つSeriesProfilecompression_ratio: トークン削減率
🔧 技術詳細
開発
# クローンしてインストールする
git clone https://github.com/yourusername/semantic-frame
cd semantic-frame
uv sync
# テストを実行する
uv run pytest
# カバレッジを伴って実行する
uv run pytest --cov=semantic_frame
📄 ライセンス
MITライセンス - LICENSEファイルを参照してください。
代替品









