🚀 語義框架(Semantic Frame)
語義框架(Semantic Frame)可對數值數據進行高效的語義壓縮。 它能將原始數值數據(如NumPy、Pandas、Polars格式)轉換為適合大語言模型(LLM)處理的自然語言描述。你無需向AI代理發送數千個數據點,只需發送一個50字左右的語義摘要即可。
🚀 快速開始
分析單個序列
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)
分析數據框
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)
獲取結構化輸出
result = describe_series(data, output="full")
print(result.trend)
print(result.volatility)
print(result.anomalies)
print(result.compression_ratio)
用於API的JSON輸出
result = describe_series(data, output="json")
✨ 主要特性
- 高效壓縮:將原始數值數據轉換為簡潔的自然語言描述,實現95%以上的token縮減。
- 避免幻覺:提供確定性分析,降低大語言模型的幻覺風險。
- 多數據類型支持:支持NumPy、Pandas、Polars等多種數據類型。
- 多框架集成:可與Anthropic Claude、LangChain、CrewAI、MCP等框架集成。
- 高級工具支持:支持Anthropic的高級工具使用功能,實現複雜代理工作流中的高效工具編排。
- 交易模塊:提供專門的交易分析工具,適用於交易代理、投資組合經理和金融應用。
📦 安裝指南
pip install semantic-frame
或者使用uv進行安裝:
uv add semantic-frame
💻 使用示例
基礎用法
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).
高級用法
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)
📚 詳細文檔
支持的數據類型
- 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)
多列代理上下文
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()
CrewAI
pip install semantic-frame[crewai]
from semantic_frame.integrations.crewai import get_crewai_tool
tool = get_crewai_tool()
MCP(模型上下文協議)
pip install semantic-frame[mcp]
運行MCP服務器:
mcp run semantic_frame.integrations.mcp:mcp
為MCP客戶端(如ElizaOS、Claude Desktop、Claude Code等)提供describe_data工具。
Claude Code
在Claude Code中添加Semantic Frame作為原生工具:
pip install semantic-frame[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 mcp list
配置完成後,讓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")
DevOps監控
cpu_data = pd.Series(cpu_readings)
insight = describe_series(cpu_data, context="CPU Usage %")
銷售分析
sales = pd.Series(daily_sales)
insight = describe_series(sales, context="Daily Revenue")
IoT傳感器數據
temps = pl.Series("temperature", sensor_readings)
insight = describe_series(temps, context="Machine Temperature (C)")
交易模塊(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)
equity = [10000, 10500, 10200, 9800, 9500, 10100]
result = describe_drawdown(equity, context="Strategy")
print(result.narrative)
returns = [0.01, 0.015, 0.02, -0.01, 0.025, 0.018]
result = describe_regime(returns, context="BTC")
print(result.narrative)
assets = {"BTC": [40000, 42000, 44000], "ETH": [2500, 2650, 2800]}
result = describe_allocation(assets, method="risk_parity")
print(result.narrative)
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:可選的SeasonalityState
distribution:可選的DistributionShape
step_change:可選的StructuralChange(STEP_UP、STEP_DOWN、NONE)
step_change_index:可選的整數(階躍變化發生的索引)
profile:帶有統計信息的SeriesProfile
compression_ratio:token縮減比率
🔧 技術細節
Semantic Frame在處理數值數據時,先使用NumPy進行確定性分析,然後將結果轉換為token高效的敘述。它通過線性迴歸斜率分析數據趨勢,使用變異係數衡量波動性,利用Z - 分數或IQR自適應方法檢測異常值等。在與大語言模型集成時,通過特定的接口函數將分析結果格式化為適合系統提示、LangChain工具輸出或多列代理上下文的形式。在交易模塊中,針對金融數據的特點,提供了一系列專業的分析工具,如權益曲線回撤分析、交易績效評估、市場狀態檢測等。
📄 許可證
本項目採用MIT許可證,詳情請參閱LICENSE文件。