关于 semantic-frame
semantic-frame 分析数值序列和表格,并将结果转为供 LLM 应用使用的精简文本或结构化输出。它面向需要先确定性计算趋势、异常等数据特征,再将结果交给 Agent 的开发者和数据团队。
主要功能
- 01趋势、波动与异常分析
- 02季节性和分布分析
- 03阶跃变化与数据质量检测
- 04叙述文本、JSON 和完整结果
- 05批量及 DataFrame 分析
适用场景
- 01汇总 CPU 和内存监控数据
- 02描述销售或市场时间序列
- 03为 Agent 准备精简数据上下文
MCP 相关
MCP 服务向 MCP 客户端提供 `describe_data` 和批量分析工具,包括 `describe_batch` 与 `describe_json`。
配置
本地服务的配置在各客户端中通用,复制后粘贴到客户端的 MCP 配置文件即可。
工具
本地服务需要在你的电脑上运行后才能读取工具,维护者暂未提供工具列表。
详细介绍
Semantic Frame
面向数值数据的高效语义压缩。
Semantic Frame 可将原始数值数据(NumPy、Pandas、Polars)转换为针对大模型优化的自然语言描述。无需向 AI Agent 发送数千个数据点,只需发送一段 50 词的语义摘要。
问题所在
大模型不擅长算术。当你将 [100, 102, 99, 101, 500, 100, 98] 这样的原始数据发送给 GPT-4 或 Claude 时:
- 浪费 Token:1000 个数据点 = 约 2000 个 Token
- 幻觉风险:大模型会猜测趋势,而不是实际计算
- 上下文溢出:大型数据集会占满上下文窗口
解决方案
Semantic Frame 使用 NumPy 进行确定性分析,然后将结果转换为高效的 Token 叙述:
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).
结果:Token 减少 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-score / IQR 自适应 | 每个离群值的索引、值、z-score |
| 季节性 | 自相关 | NONE、WEAK、MODERATE、STRONG |
| 分布 | 偏度 + 峰度 | NORMAL、LEFT_SKEWED、RIGHT_SKEWED、BIMODAL、UNIFORM |
| 阶跃变化 | 基线偏移检测 | NONE、STEP_UP、STEP_DOWN |
| 数据质量 | 缺失值百分比 | PRISTINE、GOOD、SPARSE、FRAGMENTED |
大模型集成
注入系统提示词
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": {...}}
多列 Agent 上下文
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 的 Agent 框架
- Claude Desktop:Anthropic 的桌面应用
- Claude Code:Anthropic 面向 Claude 的命令行工具
- 任何兼容 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 工具。
高级工具使用(Beta)
Semantic Frame 支持 Anthropic 的高级工具使用功能,可在复杂的 Agent 工作流中高效编排工具。
功能
| 功能 | 优势 | 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)
为交易 Agent、投资组合经理和金融应用提供专门的语义分析。
交易工具
| 工具 | 描述 |
|---|---|
describe_drawdown | 带严重程度评估的权益曲线回撤分析 |
describe_trading_performance | 胜率、夏普比率、盈利因子指标 |
describe_rankings | 多 Agent/策略比较 |
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"(字典)或"full"(SemanticResult)
返回: 按所请求格式提供的语义描述。
describe_dataframe(df, context=None)
分析 DataFrame 中的所有数值列。
参数:
df:Pandas 或 Polars DataFramecontext:列上下文标签的可选前缀
返回: 将列名映射到 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:可选的 int(发生阶跃变化的索引)profile:包含统计信息的 SeriesProfilecompression_ratio:Token 缩减率
开发
# 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 文件。
评论
一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。