Commit 2373773a by wangzhiyang

feat: 搭建意图融合服务的web演示项目并更新核心代码

删除旧的示例、测试、基准测试文件及CHANGELOG.md;新增Vue3+TS+Element Plus前端web控制台,支持聊天交互、测试案例调用、意图详情查看;添加后端依赖配置与环境变量模板;更新intent_fusion类型定义与导出接口;新增GLSX业务场景的意图定义与测试数据;添加标题导出脚本与示例数据;优化.gitignore规则,新增web构建产物、依赖目录与docx文件的忽略配置。
1 parent 6b2f49f2
Showing 77 changed files with 2381 additions and 2325 deletions
INTENT_FUSION_INTENTS_PATH=benchmarks/glsx/intents.yaml
INTENT_FUSION_CASES_PATH=benchmarks/glsx/cases.yaml
DASHSCOPE_API_KEY=sk-
INTENT_FUSION_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1
INTENT_FUSION_MODEL=deepseek-v4-flash
INTENT_FUSION_ENABLE_THINKING=1
INTENT_FUSION_PREWARM=1
PORT=8000
...@@ -13,14 +13,15 @@ build/ ...@@ -13,14 +13,15 @@ build/
htmlcov/ htmlcov/
.coverage .coverage
*.csv
calibration_results.csv calibration_results.csv
.env
.venv/ .venv/
venv/ venv/
env/ env/
web/node_modules/
web/dist/
.idea/ .idea/
.vscode/ .vscode/
*.swp *.swp
...@@ -29,3 +30,4 @@ env/ ...@@ -29,3 +30,4 @@ env/
*.DS_Store *.DS_Store
Thumbs.db Thumbs.db
*.docx
\ No newline at end of file \ No newline at end of file
# Changelog
## 0.1.0 (2024-XX-XX)
Initial release.
### Features
- **Dual-channel fusion**: Embedding recall + LLM tree reasoning running in parallel
- **Three-state verdict**: CLEAR / AMBIGUOUS / LOW with recommended downstream actions
- **IntentRouter class**: Instance-based API supporting multiple routers per process
- **Function API**: `fuse_intent()` convenience function with module-level singleton
- **Single-channel degradation**: If one channel fails, the other still produces results
- **Non-blocking embedding**: `asyncio.to_thread()` prevents event loop blocking
- **Calibration tool**: Grid search over (alpha, delta) with CSV output
- **LLMProvider protocol**: Works with any LLM backend (OpenAI, Anthropic, Ollama, etc.)
### Benchmarks
- E-commerce dataset: 10 intents, 20 cases
- Pet store dataset: 15 intents, 52 cases (desensitized from production)
### Documentation
- Architecture guide with fusion formula and three-state logic
- Pipeline integration guide with production patterns
- Calibration guide for parameter tuning
# intent-fusion
[English](#intent-fusion) | [中文](README_zh.md)
**Production-validated dual-channel intent recognition: Embedding Recall + LLM Tree Reasoning.**
A Python library that runs two complementary intent classification channels in parallel — fast embedding similarity and LLM hierarchical reasoning — then fuses their results into a single scored verdict. Built and validated in a real SaaS system, not a research prototype.
## Production Results
Evaluated on a production retail management SaaS — 57 intents, 7 domains, 140 labeled routing cases.
**Single-model baselines** (3 LLMs tested, 104 cases):
| Model | Accuracy | Avg Latency |
|-------|----------|-------------|
| Model A (fast) | 80.8% | 2.2s |
| Model B (balanced) | 82.7% | 6.0s |
| Model C (strong) | 86.5% | 15.1s |
No single model broke 87%. **Dual-channel fusion** on the fastest model (140 cases, extended regression):
| Metric | Best Single Model | Dual-channel Fusion |
|--------|-------------------|---------------------|
| **Overall accuracy** | 86.5% (90/104) | **97.1% (136/140)** |
| Analytics domain | 47–87% | 100% |
| Remaining failures | 14–20 | 4 (all context-dependent pronouns) |
The 4 remaining failures all contain pronouns like "that one" / "this" that require multi-turn conversation context — a dialogue management concern, not an intent recognition issue.
→ [Full evaluation with cross-model failure analysis](benchmarks/README.md)
## Why two channels?
| User says | Pure Embedding | Pure LLM | Fusion |
|-----------|---------------|----------|--------|
| "cancel order" | cancel_order | cancel_order | cancel_order |
| "I changed my mind" | ??? | cancel_order | cancel_order |
| "how did the store do today" | query_revenue (wrong) | daily_report | daily_report |
| "what's flying off the shelves" | query_product (wrong) | hot_selling | hot_selling |
- **Embedding** is fast and great at keyword matches, but fails on indirect phrasing.
- **LLM tree reasoning** excels at semantic inference, but is slower and may hallucinate intent names.
- **Fusion** combines both: embedding widens recall, tree reasoning provides precision.
## Architecture
```
User Message
│
├──────────────────┬──────────────────┐
│ │ │
┌────▼─────┐ ┌─────▼──────┐ │
│ Embedding │ │ Intent Tree│ parallel
│ Channel │ │ Channel │ execution
│ (5-15ms) │ │ (LLM call) │ │
└────┬──────┘ └─────┬──────┘ │
│ │ │
└────────┬─────────┘──────────────────┘
│
┌──────▼──────┐
│ Merge&Score │ final = α·emb + (1-α)·tree
└──────┬──────┘
│
┌──────▼──────┐
│ 3-state │ CLEAR / AMBIGUOUS / LOW
│ Verdict │
└─────────────┘
```
## Quick Start
```bash
pip install intent-fusion
```
```python
from intent_fusion import IntentRouter, IntentEntry, FusionVerdict
# Define your intents with separate texts for each channel
entries = [
IntentEntry(
name="query_order_status",
domain="Orders",
embed_text="track order, shipping status, where is my package",
tree_text="user wants to know where their order is or delivery ETA",
),
IntentEntry(
name="cancel_order",
domain="Orders",
embed_text="cancel order, stop my order, don't want it",
tree_text="user wants to cancel an order they placed",
),
# ... more intents
]
# Create a router (loads embedding model once)
router = IntentRouter(entries)
# Any LLM with an async chat() method works
result = await router.fuse("I changed my mind", your_llm)
match result.verdict:
case FusionVerdict.CLEAR:
execute(result.top.name) # "cancel_order"
case FusionVerdict.AMBIGUOUS:
execute(result.top.name)
suggest(result.runner_up.name) # show alternative
case FusionVerdict.LOW:
fallback_to_free_chat()
```
## Core Concepts
### IntentEntry: Two texts, one intent
Each intent has independent descriptions optimized for each channel:
```python
IntentEntry(
name="hot_selling",
domain="Reports",
embed_text="best sellers, top selling, popular items, what sells most",
tree_text="user wants to see product sales ranking. Unlike query_revenue (totals), this shows per-product ranking.",
)
```
- **`embed_text`**: Keyword-dense, synonym-rich. Feed the embedding model what users actually type.
- **`tree_text`**: Descriptive with disambiguation hints. Tell the LLM what this intent is *and what it isn't*.
### LLMProvider Protocol
Any object with an async `chat()` method works:
```python
class YourLLM:
async def chat(self, messages: list[dict[str, str]], **kwargs) -> str:
# Call OpenAI, Anthropic, DeepSeek, Ollama, or any provider
...
```
An OpenAI-compatible adapter is included in `examples/`.
### Three-state Verdict
| Verdict | Meaning | Recommended Action |
|---------|---------|-------------------|
| `CLEAR` | Top candidate is dominant | Route directly |
| `AMBIGUOUS` | Top-2 are close | Execute top, suggest runner-up |
| `LOW` | No confident match | Fall back to free chat / guide |
### Single-channel Degradation
If the LLM is down, embedding still works (and vice versa):
```python
result = await router.fuse(message, llm)
if result.degraded:
print(f"Running on {result.active_channels} only")
```
## Calibration
Find optimal `alpha` and `delta` for your intent set:
```bash
python -m intent_fusion.calibration \
--cases your_cases.yaml \
--intents your_intents.yaml
# Output: Best alpha=0.10, delta=0.10 → accuracy=0.971 (101/104)
```
See [docs/calibration.md](docs/calibration.md) for details.
## Benchmarks
Two datasets are included:
| Dataset | Intents | Cases | Source |
|---------|---------|-------|--------|
| `ecommerce/` | 10 | 20 | Synthetic |
| `petstore/` | 15 | 52 | Production (desensitized) |
```bash
export OPENAI_API_KEY=sk-...
python benchmarks/petstore/run_benchmark.py
```
See [benchmarks/README.md](benchmarks/README.md) for methodology and full results.
## Documentation
- [Architecture](docs/architecture.md) — Dual-channel design, fusion formula, three-state logic
- [Pipeline Integration](docs/pipeline-integration.md) — How to integrate into a production system
- [Calibration Guide](docs/calibration.md) — Finding optimal parameters for your data
## API Reference
### Class API (recommended)
```python
router = IntentRouter(entries, model_name="BAAI/bge-small-en-v1.5")
router.build_index() # optional: pre-warm at startup
result = await router.fuse(message, llm, alpha=0.10, delta=0.10)
```
### Function API (convenience)
```python
from intent_fusion import fuse_intent, build_index, invalidate_cache
build_index(entries) # optional pre-warm
result = await fuse_intent(message, entries, llm)
invalidate_cache() # call after updating intents
```
## License
MIT
# Benchmarks
Evaluation datasets and production evaluation results for intent-fusion.
## Datasets
| Dataset | Intents | Cases | Source | Language |
|---------|---------|-------|--------|----------|
| `ecommerce/` | 10 | 20 | Synthetic | English |
| `petstore/` | 15 | 52 | Production (desensitized) | English |
## Running a benchmark
```bash
# Set your LLM API key
export OPENAI_API_KEY=sk-...
# Run the e-commerce benchmark
python benchmarks/ecommerce/run_benchmark.py
# Run the pet store benchmark
python benchmarks/petstore/run_benchmark.py
# Override model or parameters
python benchmarks/petstore/run_benchmark.py --model deepseek-chat --alpha 0.15
```
## Calibration
To find the optimal `alpha` and `delta` for your own dataset:
```bash
python -m intent_fusion.calibration \
--cases benchmarks/petstore/cases.yaml \
--intents benchmarks/petstore/intents.yaml \
--output calibration_results.csv
```
## Production Evaluation
Full evaluation on a production retail management SaaS with 57 registered intents across 7 domains and 140 labeled end-to-end routing cases. Domain names and intent identifiers below are desensitized.
### Methodology
- **Test harness**: End-to-end routing through the full pipeline (problem-type → domain hint → dual-channel fusion → structural validation → routing decision)
- **Case categories**: `positive` (standard expressions), `boundary` (colloquial / informal phrasing), `confuse` (deliberately misleading inputs)
- **Initial set**: 104 cases (32 queries + 19 write ops + 10 tasks + others)
- **Extended set**: 140 cases (+36 colloquial boundary cases, 3–5 per domain)
---
### Phase 1 — Single-Model Baselines (104 cases)
Three LLM providers tested as the sole intent classification channel:
| Metric | Model A (fast) | Model B (balanced) | Model C (strong) |
|--------|----------------|-------------------|-------------------|
| Accuracy | 80.8% (84/104) | 82.7% (86/104) | 86.5% (90/104) |
| Failures | 20 | 18 | 14 |
| Total time | 232s | 628s | 1567s |
| Avg latency | 2.2s/case | 6.0s/case | 15.1s/case\* |
\*Model C ran in fallback mode (primary → timeout → fallback), inflating latency. Higher accuracy may partly reflect a reduced routing surface due to incomplete permission configuration during the test.
<details>
<summary>Per-domain breakdown</summary>
| Domain | Model A | Model B | Model C | Notes |
|--------|---------|---------|---------|-------|
| Users | 89% (32/36) | 83% (30/36) | 92% (33/36) | |
| Catalog | 100% (6/6) | 100% (6/6) | 100% (6/6) | All models perfect |
| Promotion | 60% (3/5) | 60% (3/5) | 60% (3/5) | All fail on "create campaign" |
| General | 85% (11/13) | 92% (12/13) | 77% (10/13) | |
| Transactions | 88% (7/8) | 88% (7/8) | 88% (7/8) | Identical across models |
| Analytics | 47% (7/15) | 60% (9/15) | 87% (13/15) | **Largest variance** |
| Services | 100% (7/7) | 100% (7/7) | 100% (7/7) | All models perfect |
| Inventory | 79% (11/14) | 86% (12/14) | 79% (11/14) | |
</details>
<details>
<summary>Per-category breakdown</summary>
| Category | Model A | Model B | Model C |
|----------|---------|---------|---------|
| positive | 83% (69/83) | 84% (70/83) | 92% (76/83) |
| boundary | 82% (9/11) | 91% (10/11) | 64% (7/11) |
| confuse | 60% (6/10) | 60% (6/10) | 70% (7/10) |
</details>
---
### Phase 2 — Dual-Channel Fusion A/B Test (104 cases)
Dual-channel fusion vs. Model A (fastest single-model baseline, used in production):
| Metric | Model A (single) | Dual-channel Fusion | Change |
|--------|------------------|---------------------|--------|
| **Overall** | 80.8% (84/104) | 87.5% (91/104) | **+6.7%** |
| Analytics | 47% (7/15) | 80% (12/15) | +33% |
| Inventory | 79% (11/14) | 93% (13/14) | +14% |
| Users | 89% (32/36) | 86% (31/36) | −3% |
| Catalog / Services | 100% | 100% | — |
---
### Phase 3 — Extended Regression (140 cases)
Added 36 colloquial boundary cases (3–5 per domain) and fixed 5 system-level issues (missing domain hints, suboptimal `embed_text` for certain intents):
| Metric | Phase 2 (104 cases) | Phase 3 (140 cases) | Notes |
|--------|---------------------|---------------------|-------|
| **Overall** | 87.5% (91/104) | **97.1% (136/140)** | +9.6% (includes new cases + fixes) |
Per-domain results:
| Domain | Accuracy | Notes |
|--------|----------|-------|
| Users | 100% (43/43) | +5 colloquial cases, all passed |
| Catalog | 70% (7/10) | 3 failures contain pronouns requiring context |
| Promotion | 100% (8/8) | |
| General | 100% (15/15) | Includes free chat, guide, strategy |
| Transactions | 100% (12/12) | |
| Analytics | 100% (21/21) | From initial 47% → 100%, largest improvement |
| Services | 91% (10/11) | 1 failure: pronoun requiring context |
| Inventory | 100% (20/20) | |
---
### Failure Analysis
All 4 remaining failures are `boundary` cases containing pronouns that require conversation context:
| Message (translated) | Expected | Actual | Analysis |
|---------------------|----------|--------|----------|
| "how much is that one" | query\_item\_detail | query\_catalog | "that" needs context; both intents reasonable |
| "raise the price on that" | modify\_item\_price | strategy\_advice | "that" needs context to know it's an item operation |
| "take this off the shelf" | toggle\_item\_listing | strategy\_with\_data | "this" needs context to know it's an item operation |
| "when is that one ready" | query\_booking | query\_service\_detail | pronoun ambiguity between booking vs. service |
**Conclusion**: All remaining failures belong to the dialogue context layer (entity resolution from conversation history). The intent recognition layer itself has no remaining systematic weaknesses.
---
### Representative Cross-Model Failures (Phase 1)
Selected cases showing how different models fail differently on the same inputs (✓ = pass, ✗ → actual routing):
| # | Message | Expected | Model A | Model B | Model C |
|---|---------|----------|---------|---------|---------|
| 1 | "add points" | add\_loyalty\_points | ✗ free\_chat | ✓ | ✓ |
| 2 | "sign up for membership" | register\_membership | ✗ guide\_search | ✓ | ✗ guide\_search |
| 3 | "top up" | top\_up\_account | ✓ | ✗ guide\_search | ✗ guide\_search |
| 4 | "inventory count" | inventory\_check | ✓ | ✓ | ✗ guide\_search |
| 5 | "how's business this month" | task:daily\_report | ✗ free\_chat | ✓ | ✓ |
| 6 | "how were today's sales" | task:daily\_report | ✗ free\_chat | ✗ free\_chat | ✓ |
| 7 | "spending overview" | task:daily\_report | ✗ query\_user | ✗ query\_user\_analysis | ✓ |
| 8 | "which users are churning" | task:churn\_alert | ✗ free\_chat | ✗ free\_chat | ✓ |
| 9 | "which categories profit most" | task:profit\_analysis | ✗ task:top\_sellers | ✗ free\_chat | ✓ |
| 10 | "best sellers ranking" | task:top\_sellers | ✗ free\_chat | ✗ free\_chat | ✓ |
| 11 | "what should we restock" | task:restock\_suggestion | ✗ free\_chat | ✗ free\_chat | ✗ strategy\_with\_data |
| 12 | "good morning" | task:morning\_dashboard | ✓ | ✓ | ✗ strategy\_with\_data |
| 13 | "how to profit next month" | strategy\_advice | ✗ free\_chat | ✗ free\_chat | ✗ free\_chat |
| 14 | "create a discount campaign" | guide\_search | ✗ query\_promotions | ✗ free\_chat | ✗ free\_chat |
Key observations:
- **No single model dominates** — each has unique failure patterns
- **Even the strongest model fails on 14/104 cases**, including cases all three models miss
- **Colloquial / indirect phrasing** is the primary failure mode (e.g., "spending overview" → should be daily\_report, classified as user query)
- **Models disagree on 73% of failures** — only 4 out of 27 failed cases are shared across all three models
- **Dual-channel fusion addresses this** by combining embedding keyword recall with LLM semantic reasoning
# Labeled test cases for calibration.
#
# These cover the "hard" cases where pure embedding fails:
# - Indirect phrasing ("where's my stuff" → query_order_status)
# - Semantic inference ("this isn't what I ordered" → initiate_return)
# - Ambiguous surface form ("I need help with my order" → could be several)
#
# Run calibration:
# python -m intent_fusion.calibration --cases examples/ecommerce/cases.yaml \
# --intents examples/ecommerce/intents.yaml
cases:
# ── Direct / easy ──
- message: "where is my order"
expected: "query_order_status"
- message: "I want to cancel my order"
expected: "cancel_order"
- message: "how do I return this item"
expected: "initiate_return"
- message: "do you have this in blue"
expected: "check_stock"
- message: "is there a discount code I can use"
expected: "query_promotions"
# ── Indirect phrasing (embedding struggles) ──
- message: "where's my stuff"
expected: "query_order_status"
note: "no keyword match — needs semantic inference"
- message: "it's been two weeks and nothing arrived"
expected: "query_order_status"
note: "complaint framing, not a direct query"
- message: "I changed my mind"
expected: "cancel_order"
note: "no 'cancel' keyword"
- message: "this isn't what I ordered"
expected: "initiate_return"
note: "complaint → return intent"
- message: "the item looks nothing like the photo"
expected: "initiate_return"
note: "dissatisfaction → return"
- message: "when will I see the money back in my account"
expected: "query_refund_status"
note: "indirect refund status query"
- message: "what are the dimensions of this"
expected: "query_product_info"
note: "specific product detail question"
- message: "will this fit a 15-inch laptop"
expected: "query_product_info"
note: "compatibility question → product info"
- message: "how many points do I have left"
expected: "query_account_balance"
note: "loyalty points framing"
- message: "I moved, need to update my shipping address"
expected: "update_account_info"
note: "address update → account info"
# ── Ambiguous cases ──
- message: "I have a problem with my order"
expected: "query_order_status"
note: "ambiguous — could be status, return, or cancel; status is most common"
- message: "I need help"
expected: "free_chat"
note: "too vague — should fall back"
# ── Fallback cases ──
- message: "hello"
expected: "free_chat"
- message: "thanks!"
expected: "free_chat"
- message: "how do I apply a coupon code at checkout"
expected: "guide_search"
note: "how-to question, not a data query"
# E-commerce intent definitions for intent-fusion demo.
#
# Each intent has:
# name: unique identifier used in routing
# domain: grouping for the intent tree (shown to LLM)
# embed_text: optimized for embedding similarity (surface/lexical)
# tree_text: optimized for LLM reasoning (semantic description)
intents:
# ── Order Management ──
- name: query_order_status
domain: Order Management
embed_text: "track order, where is my package, shipping status, delivery ETA, order tracking"
tree_text: "user wants to know where their order is, current shipping status, or estimated delivery time"
- name: cancel_order
domain: Order Management
embed_text: "cancel order, I don't want it anymore, stop my order, cancel purchase"
tree_text: "user wants to cancel an order they placed, before or after shipment"
- name: modify_order
domain: Order Management
embed_text: "change order, update address, change quantity, edit my order"
tree_text: "user wants to change something about an existing order: address, item, quantity"
# ── Returns & Refunds ──
- name: initiate_return
domain: Returns & Refunds
embed_text: "return item, send back, return request, I want to return this"
tree_text: "user wants to start a return process for a received item"
- name: query_refund_status
domain: Returns & Refunds
embed_text: "refund status, where is my refund, when will I get my money back, refund progress"
tree_text: "user is asking about the status of a refund they already requested"
# ── Product & Inventory ──
- name: query_product_info
domain: Product & Inventory
embed_text: "product details, item description, specifications, what does this product do"
tree_text: "user wants information about a product: description, specs, compatibility, materials"
- name: check_stock
domain: Product & Inventory
embed_text: "in stock, available, do you have this, inventory, out of stock"
tree_text: "user wants to know if a specific product is available or when it will be restocked"
# ── Account & Membership ──
- name: query_account_balance
domain: Account & Membership
embed_text: "account balance, store credit, points balance, how many points do I have"
tree_text: "user wants to check their account balance, store credits, or loyalty points"
- name: update_account_info
domain: Account & Membership
embed_text: "change email, update phone, change password, edit profile, update address"
tree_text: "user wants to update their personal account information: email, phone, address, password"
# ── Promotions ──
- name: query_promotions
domain: Promotions
embed_text: "discount, coupon, promo code, sale, deals, offer, voucher"
tree_text: "user is asking about available discounts, coupons, promotional codes, or ongoing sales"
intents:
- name: "门店运营分析"
domain: "门店运营"
embed_text: "门店数量统计, 门店列表, 查询门店, 门店信息, 门店分布, 门店明细, 门店地址, 门店省市, 品牌门店, 城市门店, 省份门店, 门店范围, 门店覆盖, 在营门店"
tree_text: "用户仅查询门店实体本身的基础信息:在营门店数量、门店列表/明细/分布、门店属性(省市/地址/品牌)。不包含任何经营指标(产值/触客/成交/转化/延保/二手等),不包含任何人员信息(驻店人员/员工清单/排班)。"
- name: "经营指标分析"
domain: "经营分析"
embed_text: "产值, 营收, 本月产值, 截止今天产值, 半年产值, 产值统计, 结构占比, 完成率, 环比, 同比, 预计, 预测, 预估, 目标达成, 触客数, 总触客数, 触客趋势, 触客差异, 触客率, 客单价, 应触客数, 转化率, 成交率, 漏斗, 成交数, 成交量, 新车交付数, 交付数, 订单数, 成交趋势, 成交走势, 延保渗透率, 延保覆盖率, 延保收入, 延保产值, 延保收入占比, 收入结构, 员工触客数, 人员业绩, 门店产值"
tree_text: "用户查询任何经营指标的数值、汇总、趋势、环比同比、预测、结构占比、排名、对比等。即使涉及门店维度展开或人员维度展开,只要核心是指标数值或分析,均归入此类。不包含风险预警(生态系数/预警)和二手业务指标。"
- name: "组织与调度"
domain: "组织与调度"
embed_text: "驻店人员, 驻点人员, 调度, 到店谈客, 兜底目标, 人员安排建议, 排班, 驻店零售, 人员清单, 员工清单, 员工姓名, 谁在驻店, 调谁去, 排班表"
tree_text: "用户查询人员清单(不带业绩数值)、排班、调度建议、到店安排等。核心对象是“人”而非指标。如果用户问及人员的业绩(如触客数、成交率),则自动归入「经营指标分析」。"
- name: "风险预警分析"
domain: "风险预警"
embed_text: "生态系数预警, 预警门店, 风险预警, 指标预警, 生态系数, 预警对比, 风险排序"
tree_text: "用户想查看风险/预警门店清单(如生态系数预警)并进行对比、排序或原因分析。"
- name: "报表查看"
domain: "报表与复盘"
embed_text: "周报, 月报, 日报, 业绩周报, 展业周报, 报表查看, 复盘报告"
tree_text: "用户想查看或获取某类周期性报表(周报/月报等)或复盘信息。"
- name: "二手业务分析"
domain: "二手业务"
embed_text: "二手, 二手车, 收车数, 收车成本, 收车走势, 收车环比, 收车同比, 收车排名, 收车Top门店, 二手收车, 二手车毛利, 毛利率, 毛利环比, 毛利同比, 二手车盈利, 利润分析"
tree_text: "用户想查询或分析二手业务指标(收车/毛利/利润等),包括趋势、环比同比、排名或对比分析。"
- name: "其他查询"
domain: "其他"
embed_text: "你好, 在吗, 谢谢, 哈哈, 你是谁, 你能做什么, 帮助, 随便聊聊, 闲聊, 隐私, 权限, 数据来源, 系统提示词, 安全策略, 内部接口, 公司股价, 午餐推荐, 深圳火锅推荐, 政治, 历史事件, 社会热点, 政府, 执政, 党史, 毛泽东, 天安门, 六四, 法轮功"
tree_text: "用户提出与业务指标/报表/门店/经营分析无关的问题或内容:闲聊、打招呼、表达情绪、问你是谁/能做什么、询问隐私/权限/数据来源/系统规则、以及政治历史社会等非业务话题。"
...@@ -9,52 +9,106 @@ from __future__ import annotations ...@@ -9,52 +9,106 @@ from __future__ import annotations
import argparse import argparse
import asyncio import asyncio
import csv
import logging import logging
import os
import sys
from pathlib import Path from pathlib import Path
_ROOT = Path(__file__).resolve().parents[2]
if str(_ROOT) not in sys.path:
sys.path.insert(0, str(_ROOT))
try:
from dotenv import load_dotenv
except ImportError:
load_dotenv = None
if load_dotenv is not None:
load_dotenv(_ROOT / ".env")
from intent_fusion import IntentRouter, FusionVerdict from intent_fusion import IntentRouter, FusionVerdict
from intent_fusion.calibration import load_cases_from_yaml, load_intents_from_yaml from intent_fusion.calibration import load_cases_from_yaml, load_intents_from_yaml
from intent_fusion.tree import OpenAIAdapter
_HERE = Path(__file__).parent _HERE = Path(__file__).parent
logging.basicConfig(level=logging.WARNING) logging.basicConfig(level=logging.WARNING)
def _normalize_multi_intent(text: str) -> str:
parts = [p.strip() for p in (text or "").split("|")]
parts = [p for p in parts if p]
return "|".join(parts)
def _format_multi_intent(text: str) -> str:
parts = [p.strip() for p in (text or "").split("|")]
parts = [p for p in parts if p]
return " | ".join(parts)
async def main(): async def main():
parser = argparse.ArgumentParser(description="E-commerce benchmark") parser = argparse.ArgumentParser(description="glsx benchmark")
parser.add_argument("--model", default=None) parser.add_argument("--model", default=None)
parser.add_argument("--alpha", type=float, default=0.10) parser.add_argument("--alpha", type=float, default=0.10)
parser.add_argument("--delta", type=float, default=0.10) parser.add_argument("--delta", type=float, default=0.10)
parser.add_argument("--output-csv", default=str(_HERE / "benchmark_results.csv"))
args = parser.parse_args() args = parser.parse_args()
from examples.ecommerce.llm_adapter import OpenAIAdapter
entries = load_intents_from_yaml(_HERE / "intents.yaml") entries = load_intents_from_yaml(_HERE / "intents.yaml")
cases = load_cases_from_yaml(_HERE / "cases.yaml") cases = load_cases_from_yaml(_HERE / "cases.yaml")
llm = OpenAIAdapter(model=args.model) llm = OpenAIAdapter(model=args.model)
router = IntentRouter(entries) router = IntentRouter(entries)
if os.getenv("INTENT_FUSION_PREWARM", "").strip().lower() not in {"", "0", "false", "no", "off"}:
router.build_index()
correct = 0 correct = 0
rows: list[dict[str, str]] = []
for case in cases: for case in cases:
result = await router.fuse(case.message, llm, alpha=args.alpha, delta=args.delta) result = await router.fuse(
case.message,
llm,
alpha=args.alpha,
delta=args.delta,
expand_orchestrate=True,
)
if result.verdict == FusionVerdict.LOW: if result.verdict == FusionVerdict.LOW:
predicted = "free_chat" predicted = "free_chat"
elif result.top: elif result.top:
if result.top.name == "orchestrate" and result.orchestrated:
predicted = " | ".join(result.orchestrated)
else:
predicted = result.top.name predicted = result.top.name
else: else:
predicted = "???" predicted = "???"
is_correct = predicted == case.expected_intent is_correct = _normalize_multi_intent(predicted) == _normalize_multi_intent(case.expected_intent)
if is_correct: if is_correct:
correct += 1 correct += 1
mark = "OK" if is_correct else "FAIL" mark = "OK" if is_correct else "FAIL"
print(f" [{mark}] {case.message:<45} expected={case.expected_intent:<25} got={predicted}") expected_display = _format_multi_intent(case.expected_intent)
got_display = _format_multi_intent(predicted)
print(f" [{mark}] {case.message:<45} expected={expected_display:<25} got={got_display}")
rows.append(
{
"ok": "1" if is_correct else "0",
"message": case.message,
"expected": expected_display,
"got": got_display,
}
)
accuracy = correct / len(cases) if cases else 0 accuracy = correct / len(cases) if cases else 0
print(f"\nResult: {correct}/{len(cases)} ({accuracy:.1%})") print(f"\nResult: {correct}/{len(cases)} ({accuracy:.1%})")
output_csv = str(args.output_csv or "").strip()
if output_csv:
with open(output_csv, "w", encoding="utf-8-sig", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["ok", "message", "expected", "got"])
writer.writeheader()
writer.writerows(rows)
print(f"Saved CSV: {output_csv}")
if __name__ == "__main__": if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())
# Labeled test cases for the pet store benchmark — desensitized from production.
#
# 52 cases covering:
# - Direct phrasing (embedding excels)
# - Indirect phrasing (tree reasoning excels)
# - Cross-domain ambiguity
# - Fallback cases (free_chat, guide_search, orchestrate)
#
# Accuracy baseline (production, 104 full cases): 80.8% -> 97.1% with dual-channel fusion.
# This subset contains 52 representative cases preserving the difficulty distribution.
cases:
# ── Direct / easy (embedding should handle) ──
- message: "check Zhang San's balance"
expected: "query_balance"
- message: "look up customer Li Si"
expected: "query_customer"
- message: "recharge 200 for Zhang San"
expected: "recharge_member"
- message: "add 100 points"
expected: "add_points"
- message: "check today's orders"
expected: "query_order"
- message: "any promotions going on"
expected: "query_activity"
- message: "how much revenue today"
expected: "query_revenue"
- message: "check stock for dog food"
expected: "query_stock"
- message: "book a grooming appointment"
expected: "create_grooming"
- message: "what's selling the best"
expected: "hot_selling"
- message: "send a coupon to Wang Wu"
expected: "send_coupon"
- message: "product info for premium cat food"
expected: "query_product"
- message: "stock in 50 units of leashes"
expected: "stock_in"
- message: "today's business report"
expected: "daily_report"
- message: "grooming appointments today"
expected: "query_grooming"
# ── Indirect phrasing (embedding struggles, tree reasoning wins) ──
- message: "how much does Zhang San have left"
expected: "query_balance"
note: "no 'balance' keyword — needs semantic inference"
- message: "how did the store do today"
expected: "daily_report"
note: "metaphorical — 'how did we do' implies business report"
- message: "what came in recently"
expected: "query_order"
note: "'came in' could be stock or orders — orders is more common in context"
- message: "who's our star product"
expected: "hot_selling"
note: "'star product' requires reasoning to map to hot selling"
- message: "are we running low on anything"
expected: "query_stock"
note: "'running low' implies stock check, not a direct keyword match"
- message: "what's the damage today"
expected: "query_revenue"
note: "slang for 'how much did we make'"
- message: "help Zhang San top up their card"
expected: "recharge_member"
note: "'top up card' → recharge"
- message: "give Zhang San some bonus points"
expected: "add_points"
note: "'bonus points' → add_points"
- message: "any deals customers can use"
expected: "query_activity"
note: "'deals customers can use' → promotions"
- message: "get Fluffy in for a bath tomorrow"
expected: "create_grooming"
note: "'get in for a bath' → grooming appointment creation"
- message: "how many bags of treats do we have"
expected: "query_stock"
note: "specific product stock check in natural language"
- message: "we just got a shipment of cat litter"
expected: "stock_in"
note: "'got a shipment' → stock inbound"
- message: "what info do we have on that customer"
expected: "query_customer"
note: "vague 'that customer' but clearly a customer lookup"
- message: "is there a way to reward loyal customers"
expected: "send_coupon"
note: "'reward loyal customers' could be points or coupon — coupon is more actionable"
# ── Cross-domain ambiguity (tests fusion's disambiguation) ──
- message: "anything about Zhang San"
expected: "query_customer"
note: "ambiguous — could be balance, order, or customer info; customer is the broadest"
- message: "how are sales"
expected: "query_revenue"
note: "could be revenue overview or hot selling — revenue is more natural for 'sales'"
- message: "what about the appointment"
expected: "query_grooming"
note: "ambiguous without context — grooming query is most common"
- message: "what can I give Zhang San"
expected: "send_coupon"
note: "could be coupon or points — coupon is more common 'give' action"
- message: "I want to do something for Zhang San"
expected: "query_customer"
note: "very vague — should match broadest customer intent"
# ── Report domain (previously 47% accuracy, now 100%) ──
- message: "give me a rundown of today"
expected: "daily_report"
note: "'rundown' → daily report, not revenue"
- message: "what numbers should I know"
expected: "daily_report"
note: "vague business question → comprehensive report"
- message: "which items are flying off the shelves"
expected: "hot_selling"
note: "'flying off shelves' → hot selling"
- message: "how's the cash register looking"
expected: "query_revenue"
note: "'cash register' → revenue check"
- message: "did we make money today"
expected: "query_revenue"
note: "'make money' → revenue"
- message: "what's our most popular service"
expected: "hot_selling"
note: "'most popular' → hot selling ranking"
# ── Fallback cases ──
- message: "hello"
expected: "free_chat"
- message: "thanks"
expected: "free_chat"
- message: "what's the weather like"
expected: "free_chat"
note: "off-topic — not a business intent"
- message: "how do I set up a new promotion"
expected: "guide_search"
note: "how-to question, not a data query"
- message: "where do I find the stock settings"
expected: "guide_search"
note: "navigation/guide question"
- message: "recharge 200 for Zhang San and add 100 points"
expected: "orchestrate"
note: "two distinct write operations in one message"
- message: "check Zhang San's balance then recharge 500"
expected: "orchestrate"
note: "query + write compound action"
# Pet store intent definitions — desensitized from a production SaaS system.
#
# 15 representative intents covering the key domains of a pet store management system.
# Each intent has independent embed_text (lexical matching) and tree_text (semantic reasoning).
intents:
# ── Customer Management ──
- name: query_customer
domain: Customer Management
embed_text: "query customer, find customer, customer info, search by name or phone"
tree_text: "user wants to look up a customer's basic information by name or phone number"
- name: query_balance
domain: Customer Management
embed_text: "check balance, account balance, remaining balance, how much left, membership balance"
tree_text: "user wants to check a customer's membership card balance or store credit"
- name: recharge_member
domain: Customer Management
embed_text: "recharge, top up, add funds, membership recharge, load balance"
tree_text: "user wants to add money to a customer's membership card (a write operation)"
- name: add_points
domain: Customer Management
embed_text: "add points, give points, bonus points, reward points, loyalty points"
tree_text: "user wants to manually add loyalty points to a customer's account (a write operation)"
# ── Product & Inventory ──
- name: query_product
domain: Product & Inventory
embed_text: "query product, product info, find item, search product, product details"
tree_text: "user wants to look up product information: name, price, category, SKU"
- name: query_stock
domain: Product & Inventory
embed_text: "check stock, inventory, how many left, stock level, available quantity"
tree_text: "user wants to check current stock levels for a product"
- name: stock_in
domain: Product & Inventory
embed_text: "stock in, receive goods, add inventory, inbound, replenish stock"
tree_text: "user wants to record new stock arriving at the store (a write operation)"
# ── Order ──
- name: query_order
domain: Order
embed_text: "query order, order list, recent orders, today's orders, order history"
tree_text: "user wants to view order records, filterable by date, status, or keyword"
# ── Service Booking ──
- name: query_grooming
domain: Service Booking
embed_text: "grooming appointment, grooming order, pet grooming, bath appointment"
tree_text: "user wants to check grooming service appointments or booking records"
- name: create_grooming
domain: Service Booking
embed_text: "book grooming, schedule grooming, make grooming appointment, new grooming order"
tree_text: "user wants to create a new pet grooming appointment (a write operation)"
# ── Promotions ──
- name: query_activity
domain: Promotions
embed_text: "promotions, discounts, sales, what deals, any offers, current promotions"
tree_text: "user wants to check current promotional activities or discount campaigns"
- name: send_coupon
domain: Promotions
embed_text: "send coupon, give coupon, issue voucher, distribute coupon"
tree_text: "user wants to send a coupon or voucher to a specific customer (a write operation)"
# ── Reports & Analytics ──
- name: query_revenue
domain: Reports & Analytics
embed_text: "revenue, sales amount, how much earned today, daily sales, income"
tree_text: "user wants to check revenue or sales figures for a time period"
- name: daily_report
domain: Reports & Analytics
embed_text: "daily report, today's summary, business report, operation report, how did we do today"
tree_text: "user wants a comprehensive daily business report covering revenue, orders, and key metrics"
- name: hot_selling
domain: Reports & Analytics
embed_text: "best sellers, hot products, top selling, popular items, what sells most"
tree_text: "user wants to see which products are selling the best (ranking by quantity or revenue)"
"""Run the pet store benchmark.
Usage:
export OPENAI_API_KEY=sk-...
python benchmarks/petstore/run_benchmark.py
Options:
--model MODEL Override LLM model name
--alpha ALPHA Override alpha (default: 0.10)
--delta DELTA Override delta (default: 0.10)
"""
from __future__ import annotations
import argparse
import asyncio
import logging
from pathlib import Path
from intent_fusion import IntentRouter, FusionVerdict
from intent_fusion.calibration import load_cases_from_yaml, load_intents_from_yaml
_HERE = Path(__file__).parent
logging.basicConfig(level=logging.WARNING)
async def main():
parser = argparse.ArgumentParser(description="Pet store benchmark")
parser.add_argument("--model", default=None)
parser.add_argument("--alpha", type=float, default=0.10)
parser.add_argument("--delta", type=float, default=0.10)
args = parser.parse_args()
from examples.ecommerce.llm_adapter import OpenAIAdapter
entries = load_intents_from_yaml(_HERE / "intents.yaml")
cases = load_cases_from_yaml(_HERE / "cases.yaml")
llm = OpenAIAdapter(model=args.model)
router = IntentRouter(entries)
correct = 0
failures: list[tuple[str, str, str, str]] = []
print(f"Running {len(cases)} cases (alpha={args.alpha}, delta={args.delta})")
print("=" * 70)
for case in cases:
result = await router.fuse(case.message, llm, alpha=args.alpha, delta=args.delta)
if result.verdict == FusionVerdict.LOW:
predicted = "free_chat"
elif result.top:
predicted = result.top.name
else:
predicted = "???"
is_correct = predicted == case.expected_intent
if is_correct:
correct += 1
else:
failures.append((case.message, case.expected_intent, predicted, result.verdict.value))
mark = "OK" if is_correct else "FAIL"
print(f" [{mark}] {case.message[:50]:<50} expected={case.expected_intent:<20} got={predicted:<20} ({result.verdict.value})")
print("=" * 70)
accuracy = correct / len(cases) if cases else 0
print(f"Result: {correct}/{len(cases)} correct ({accuracy:.1%})")
if failures:
print(f"\n{len(failures)} failures:")
for msg, expected, got, verdict in failures:
print(f" {msg[:60]}")
print(f" expected={expected} got={got} verdict={verdict}")
if __name__ == "__main__":
asyncio.run(main())
"""Direct LLM Intent Recognition Benchmark for GLSX.
Usage:
python benchmarks/run_llm_direct_benchmark.py
"""
from __future__ import annotations
import argparse
import asyncio
import csv
import json
import logging
import os
import re
import sys
from pathlib import Path
import yaml
# Avoid UnicodeEncodeError on Windows stdout
sys.stdout.reconfigure(encoding='utf-8', errors='backslashreplace')
_ROOT = Path(__file__).resolve().parents[1]
if str(_ROOT) not in sys.path:
sys.path.insert(0, str(_ROOT))
from intent_fusion.calibration import load_cases_from_yaml
from intent_fusion.tree import OpenAIAdapter
_HERE = Path(__file__).parent
_GLSX = _HERE / "glsx"
# Set default env values if not present
os.environ.setdefault("DASHSCOPE_API_KEY", "sk-107dd26bca184e39bd1744af7d634488")
os.environ.setdefault("INTENT_FUSION_BASE_URL", "https://dashscope.aliyuncs.com/compatible-mode/v1")
os.environ.setdefault("INTENT_FUSION_MODEL", "deepseek-v4-flash")
# Load intents and format them into the prompt
def load_intents_info(yaml_path: Path) -> list[dict[str, str]]:
with open(yaml_path, encoding="utf-8") as f:
data = yaml.safe_load(f)
intents = []
for item in data.get("intents", []):
intents.append({
"name": item["name"],
"tree_text": item.get("tree_text", "")
})
return intents
def build_llm_prompt(intents: list[dict[str, str]], message: str) -> str:
# Build tree text representation containing names and tree_texts
tree_lines = []
for item in intents:
tree_lines.append(f"- {item['name']}: {item['tree_text']}")
tree_text = "\n".join(tree_lines)
prompt = f"""你是一个意图识别分类器。请根据给出的意图类别定义,识别出用户消息所包含的意图。
如果是多意图(消息中包含多个互相独立的意图),请使用 '|' 分隔,按顺序输出所有匹配的意图,例如:'意图1 | 意图2'。
可选的意图列表及其定义如下:
{tree_text}
请直接输出匹配的意图名称(如果是多意图,用 '|' 分隔,如 '意图A | 意图B'),不要包含任何其他解释、前缀、Markdown标记或标点符号。
用户消息:"{message}"
意图识别结果:"""
return prompt
def _normalize_multi_intent(text: str) -> str:
parts = [p.strip() for p in (text or "").split("|")]
parts = [p for p in parts if p]
return "|".join(parts)
def _format_multi_intent(text: str) -> str:
parts = [p.strip() for p in (text or "").split("|")]
parts = [p for p in parts if p]
return " | ".join(parts)
async def test_case(llm: OpenAIAdapter, intents: list[dict[str, str]], case, semaphore: asyncio.Semaphore):
async with semaphore:
prompt = build_llm_prompt(intents, case.message)
messages = [{"role": "user", "content": prompt}]
# Using a very low temperature for deterministic intent recognition
try:
response = await llm.chat(messages, temperature=0.0, max_tokens=100)
predicted = response.strip().strip("'").strip('"').strip()
# Clean up potential markdown formatting or prefix response
if ":" in predicted and not any(intent["name"] in predicted.split(":")[0] for intent in intents):
predicted = predicted.split(":", 1)[1].strip()
if ":" in predicted and not any(intent["name"] in predicted.split(":")[0] for intent in intents):
predicted = predicted.split(":", 1)[1].strip()
# If the response contains markdown code block, extract it
if "```" in predicted:
predicted = predicted.replace("```", "").strip()
except Exception as e:
predicted = f"ERROR: {e}"
is_correct = _normalize_multi_intent(predicted) == _normalize_multi_intent(case.expected_intent)
return case, predicted, is_correct
async def main():
parser = argparse.ArgumentParser(description="Run LLM direct intent recognition benchmark")
parser.add_argument("--concurrency", type=int, default=5, help="Number of concurrent LLM requests")
parser.add_argument("--output-csv", default=str(_GLSX / "llm_direct_benchmark_results.csv"))
args = parser.parse_args()
intents_path = _GLSX / "intents.yaml"
cases_path = _GLSX / "cases.yaml"
print(f"Loading intents from: {intents_path}")
intents = load_intents_info(intents_path)
print(f"Loaded {len(intents)} intents.")
print(f"Loading cases from: {cases_path}")
cases = load_cases_from_yaml(cases_path)
print(f"Loaded {len(cases)} cases.")
# Print tree_text to verify the formatted intents
sample_prompt = build_llm_prompt(intents, "test")
# Extract tree_text from prompt or rebuild it
tree_lines = [f"- {item['name']}: {item['tree_text']}" for item in intents]
tree_text = "\n".join(tree_lines)
print("\n=================== Generated Tree Text ===================")
print(tree_text)
print("===========================================================\n")
# Initialize LLM Adapter using env configurations
llm = OpenAIAdapter(enable_thinking=False) # Direct LLM response doesn't strictly need thinking extraction enabled if we want immediate direct answer, but we can keep it standard. Let's disable thinking for direct parsing to get clean output if using compatible mode.
semaphore = asyncio.Semaphore(args.concurrency)
tasks = [test_case(llm, intents, case, semaphore) for case in cases]
print("\nRunning benchmark cases...")
results = []
correct = 0
for idx, future in enumerate(asyncio.as_completed(tasks), 1):
case, predicted, is_correct = await future
if is_correct:
correct += 1
mark = "OK" if is_correct else "FAIL"
expected_display = _format_multi_intent(case.expected_intent)
got_display = _format_multi_intent(predicted)
print(f"[{idx}/{len(cases)}] [{mark}] {case.message:<45} expected={expected_display:<25} got={got_display}")
results.append({
"ok": "1" if is_correct else "0",
"message": case.message,
"expected": expected_display,
"got": got_display,
})
accuracy = correct / len(cases) if cases else 0
print(f"\nResult: {correct}/{len(cases)} ({accuracy:.1%})")
output_csv = args.output_csv
with open(output_csv, "w", encoding="utf-8-sig", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["ok", "message", "expected", "got"])
writer.writeheader()
writer.writerows(results)
print(f"Saved CSV: {output_csv}")
if __name__ == "__main__":
asyncio.run(main())
import os
import subprocess
import time
import socket
import requests
import yaml
def is_port_open(port):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(('127.0.0.1', port)) == 0
def main():
port = 8085
server_process = None
if not is_port_open(port):
print(f"Starting local serve_web.py server on port {port}...")
env = os.environ.copy()
env["PORT"] = str(port)
server_process = subprocess.Popen(
["python", "serve_web.py"],
env=env,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
# Wait for server to start
for _ in range(20):
time.sleep(0.5)
if is_port_open(port):
print("Server started successfully.")
break
else:
print("Failed to start server.")
if server_process:
server_process.terminate()
return
else:
print(f"Server is already running on port {port}.")
try:
url_upload = f"http://127.0.0.1:{port}/api/intents/upload"
url_fuse = f"http://127.0.0.1:{port}/api/fuse"
# 1. Upload the glsx intents file
intents_path = "benchmarks/glsx/intents.yaml"
print(f"Uploading {intents_path} to server...")
with open(intents_path, 'rb') as f:
files = {'file': (os.path.basename(intents_path), f, 'application/x-yaml')}
data = {'name': 'glsx'}
resp = requests.post(url_upload, files=files, data=data)
print("Upload Response status:", resp.status_code)
print("Upload Response payload:", resp.json())
assert resp.status_code == 200
assert resp.json().get("ok") is True
# 2. Query the uploaded intents
query = "询问本月新车交付数"
print(f"Querying: '{query}' on dataset 'glsx'...")
payload = {
"message": query,
"dataset": "glsx"
}
resp = requests.post(url_fuse, json=payload)
print("Query Response status:", resp.status_code)
resp_data = resp.json()
print("Query Response payload:", resp_data)
assert resp.status_code == 200
top_intent = resp_data.get("top", {}).get("name")
print(f"Predicted top intent: {top_intent}")
assert top_intent == "经营指标分析"
print("Success! Intent recognition matches expected: 经营指标分析")
# 3. Test JSON upload method
print("Testing JSON payload upload...")
with open(intents_path, 'r', encoding='utf-8') as f:
yaml_content = f.read()
payload_upload = {
"name": "glsx_json",
"yaml_content": yaml_content
}
resp = requests.post(url_upload, json=payload_upload)
print("JSON Upload Response status:", resp.status_code)
print("JSON Upload Response payload:", resp.json())
assert resp.status_code == 200
assert resp.json().get("ok") is True
# Query the JSON-uploaded dataset
query_json = "门店运营数量"
print(f"Querying: '{query_json}' on dataset 'glsx_json'...")
payload_query = {
"message": query_json,
"dataset": "glsx_json"
}
resp = requests.post(url_fuse, json=payload_query)
print("Query Response status:", resp.status_code)
resp_data_json = resp.json()
print("Query Response payload:", resp_data_json)
assert resp.status_code == 200
top_intent_json = resp_data_json.get("top", {}).get("name")
print(f"Predicted top intent: {top_intent_json}")
assert top_intent_json == "门店运营分析"
print("Success! JSON upload and query verification matches expected: 门店运营分析")
finally:
if server_process:
print("Stopping local server...")
server_process.terminate()
server_process.wait()
if __name__ == "__main__":
main()
No preview for this file type
# Architecture
## Overview
intent-fusion uses a **dual-channel parallel architecture** to classify user intents.
Two independent channels run concurrently, and their results are merged into a single
scored candidate list with a three-state verdict.
```
┌──────────────────────┐
│ User Message │
└──────────┬───────────┘
│
┌───────────────┴───────────────┐
│ │
┌───────▼───────┐ ┌────────▼────────┐
│ Embedding │ │ Intent Tree │
│ Channel │ │ Channel │
│ │ │ │
│ bge-small-* │ │ LLM + CoT │
│ cosine sim │ │ hierarchical │
│ top-k recall │ │ reasoning │
└───────┬───────┘ └────────┬────────┘
│ │
└───────────────┬───────────────┘
│
┌──────────▼───────────┐
│ Merge & Score │
│ │
│ final = α·emb + │
│ (1-α)·tree │
└──────────┬───────────┘
│
┌──────────▼───────────┐
│ Three-state Decide │
│ │
│ CLEAR / AMBIGUOUS / │
│ LOW │
└──────────────────────┘
```
## Channel 1: Embedding Recall
**Purpose:** Fast lexical/surface similarity matching.
Uses a sentence-transformer model (default: `BAAI/bge-small-en-v1.5`) to encode both
the user message and each intent's `embed_text` into dense vectors. Cosine similarity
(via normalized dot product) produces a ranked candidate list.
**Strengths:**
- Very fast (5-15ms for ~100 intents)
- Excellent for direct keyword matches ("cancel order" → `cancel_order`)
- No LLM call needed
**Weaknesses:**
- Fails on indirect phrasing ("I changed my mind" → should be `cancel_order`)
- Cannot reason about intent semantics
## Channel 2: Intent Tree Reasoning
**Purpose:** Deep semantic inference via LLM chain-of-thought.
Constructs a domain-grouped intent tree from all `IntentEntry` definitions, then
sends a single LLM call with structured reasoning instructions:
```
── Order Management ──
query_order_status: user wants to know where their order is
cancel_order: user wants to cancel an order they placed
── Returns & Refunds ──
initiate_return: user wants to start a return process
...
```
The LLM reasons step-by-step inside `<think>` tags, then outputs a JSON array of
3 candidates with scores.
**Strengths:**
- Excels at indirect/metaphorical phrasing
- Can disambiguate semantically similar intents using domain context
- Handles the "report domain" cases that pure embedding consistently fails
**Weaknesses:**
- Depends on LLM availability and latency (200-800ms typical)
- Score calibration varies across LLM providers
## Fusion Formula
For each candidate that appears in either channel's output:
```
final_score = α × emb_score + (1 - α) × tree_score
```
Where:
- `α` (alpha) controls the embedding weight. Default: **0.10** (tree-dominant).
- Candidates in both channels naturally score higher (cross-channel agreement).
- Candidates in only one channel get a partial score.
| Scenario | Formula |
|----------|---------|
| Both channels | `α × emb + (1-α) × tree` |
| Embedding only | `α × emb` |
| Tree only | `(1-α) × tree` |
**Why α = 0.10?** Calibrated via grid search on 104 labeled production cases.
The tree channel contributes much stronger signal for ambiguous queries, while
embedding mainly serves as a recall safety net.
## Three-state Verdict
After scoring, the decision layer produces one of three verdicts:
| Verdict | Condition | Recommended Action |
|---------|-----------|-------------------|
| **CLEAR** | `top.score >= 0.20` AND `gap >= δ` | Route directly to `top.name` |
| **AMBIGUOUS** | `top.score >= 0.20` AND `gap < δ` | Execute top, surface runner-up as suggestion |
| **LOW** | `top.score < 0.20` | Fall back to free chat / search |
Where `δ` (delta) is the gap threshold between top-1 and top-2 scores. Default: **0.10**.
The three-state design acknowledges uncertainty rather than forcing a binary choice,
enabling downstream systems to handle each case appropriately.
## Single-channel Degradation
If one channel fails (LLM timeout, embedding model error), the other channel still
produces a result:
- **Tree fails → embedding only:** `α` forced to 1.0
- **Embedding fails → tree only:** `α` forced to 0.0
- **Both fail:** verdict = LOW
The `FusionResult.degraded` flag and `active_channels` list let callers know
when degradation occurred.
## The `embed_text` vs `tree_text` Design
Each `IntentEntry` has two independent text fields optimized for different channels:
```python
IntentEntry(
name="query_order_status",
domain="Order Management",
embed_text="track order, where is my package, shipping status, delivery ETA",
tree_text="user wants to know where their order is, current shipping status, or estimated delivery time",
)
```
- **`embed_text`:** Keyword-dense, synonym-rich. Optimized for vector similarity.
- **`tree_text`:** Descriptive, boundary-clarifying. Optimized for LLM reasoning.
Should include disambiguation hints (e.g., "unlike X, this intent covers Y").
This separation is a key insight from production: a single description cannot
simultaneously optimize for both lexical matching and semantic reasoning.
# Calibration Guide
## Why calibrate?
The two key parameters — `alpha` (embedding weight) and `delta` (CLEAR/AMBIGUOUS gap
threshold) — directly affect routing accuracy. Their optimal values depend on:
- Your intent set size and similarity structure
- Your embedding model's quality for your domain
- Your LLM's scoring calibration
- Your tolerance for AMBIGUOUS vs misrouted CLEAR verdicts
## Quick start
```bash
# 1. Prepare labeled cases (see format below)
# 2. Run grid search
python -m intent_fusion.calibration \
--cases your_cases.yaml \
--intents your_intents.yaml \
--output calibration_results.csv
# Output:
# Best: alpha=0.10, delta=0.10 → accuracy=0.971 (101/104)
```
## Labeled case format
```yaml
cases:
- message: "where is my order"
expected: "query_order_status"
- message: "I changed my mind"
expected: "cancel_order"
note: "no 'cancel' keyword — tests semantic reasoning"
- message: "hello"
expected: "free_chat"
- message: "how do I apply a coupon"
expected: "guide_search"
note: "how-to question, not a data query"
```
### Expected values for fallback cases
- Use `"free_chat"` for greetings, off-topic, and too-vague messages
- Use `"guide_search"` for how-to / navigation questions
- Use `"orchestrate"` for multi-action compound messages
These special targets are matched when the verdict is LOW.
## Understanding the grid search
The calibration tool tests every combination of alpha and delta values:
| Parameter | Default search range | What it controls |
|-----------|---------------------|-----------------|
| `alpha` | 0.00, 0.05, 0.10, 0.20, 0.30, 0.50 | Embedding vs tree weight |
| `delta` | 0.05, 0.10, 0.15, 0.20, 0.25 | CLEAR vs AMBIGUOUS boundary |
For each (alpha, delta) pair, it runs all cases and reports:
- **accuracy:** fraction of cases where top matches expected
- **ambiguous_count:** number of AMBIGUOUS verdicts (neither good nor bad)
- **low_count:** number of LOW verdicts (potential misses)
The "best" configuration maximizes accuracy, with ties broken by fewer AMBIGUOUS verdicts.
## Interpreting results
Open the CSV output to understand the parameter landscape:
```
alpha,delta,accuracy,correct,total,ambiguous_count,low_count
0.00,0.05,0.923,96,104,12,3
0.10,0.10,0.971,101,104,5,3
0.20,0.10,0.952,99,104,7,3
0.50,0.10,0.894,93,104,8,5
```
**Common patterns:**
- **alpha too high (>0.3):** Embedding dominates, indirect phrasing fails
- **alpha too low (0.0):** Embedding provides no recall safety net
- **delta too low (<0.05):** Too many CLEAR verdicts, some misrouted
- **delta too high (>0.20):** Too many AMBIGUOUS verdicts, user gets asked to clarify unnecessarily
## Custom search ranges
```python
from intent_fusion.calibration import run_grid_search
best = await run_grid_search(
cases,
entries,
llm,
alpha_values=[0.05, 0.08, 0.10, 0.12, 0.15], # fine-grained around 0.10
delta_values=[0.08, 0.10, 0.12, 0.15],
output_csv="fine_calibration.csv",
)
```
## Tips for building a good case set
1. **Cover all intents** — at least 2-3 cases per intent
2. **Include hard cases** — indirect phrasing, slang, metaphorical language
3. **Include boundary cases** — messages that could plausibly match 2+ intents
4. **Include fallbacks** — greetings, off-topic, how-to questions
5. **Weight toward production patterns** — if 40% of real messages are order queries,
your case set should reflect that
A good starting point is 5-10 cases per intent, plus 10-15 fallback cases.
## Re-calibration triggers
Re-run calibration when you:
- Add or remove intents
- Significantly rewrite embed_text or tree_text
- Switch embedding models
- Switch LLM providers
- Observe accuracy degradation in production logs
# Pipeline Integration Guide
This guide shows how to integrate intent-fusion into a real production pipeline,
based on patterns proven in a SaaS system serving pet store businesses.
## Where fusion fits in the pipeline
```
User Message
│
▼
┌─────────────────────┐
│ Problem Type │ Rule-based + lightweight LLM classifier
│ Pre-classification │ (guide / strategy / action / query / chat)
└──────────┬──────────┘
│
▼
┌─────────────────────────────────────────────┐
│ asyncio.gather() │
│ │
│ ┌──────────────────┐ ┌─────────────────┐ │
│ │ Dual-channel │ │ LLM Parameter │ │
│ │ Fusion │ │ Extraction │ │
│ │ │ │ │ │
│ │ (decides WHICH │ │ (extracts │ │
│ │ skill/task) │ │ params for │ │
│ │ │ │ that skill) │ │
│ └────────┬─────────┘ └────────┬────────┘ │
│ │ │ │
└───────────┴─────────────────────┴────────────┘
│
▼
┌─────────────────────┐
│ Three-state Router │
│ │
│ CLEAR → execute │
│ AMBIGUOUS → suggest │
│ LOW → fallback │
└─────────────────────┘
```
**Key insight:** Fusion and parameter extraction run in parallel. Fusion decides
*which* skill to invoke; the separate LLM call extracts *parameters* for that skill.
This avoids adding latency — the fusion's LLM tree call and the parameter extraction
LLM call happen concurrently.
## Integration code pattern
```python
import asyncio
from intent_fusion import IntentRouter, FusionVerdict
router = IntentRouter(entries)
async def handle_message(message: str, llm):
# Run fusion and parameter extraction in parallel
fusion_task = router.fuse(message, llm)
params_task = extract_params(message, llm) # your existing LLM call
fusion_result, params = await asyncio.gather(fusion_task, params_task)
# Route based on three-state verdict
if fusion_result.verdict == FusionVerdict.CLEAR:
skill_name = fusion_result.top.name
matched_params = find_matching_params(skill_name, params)
return execute_skill(skill_name, matched_params)
if fusion_result.verdict == FusionVerdict.AMBIGUOUS:
top = fusion_result.top
runner = fusion_result.runner_up
if is_write_operation(top.name):
# Write operations with ambiguity → orchestrate for safety
return orchestrate(message, [top.name, runner.name])
# Read operations → execute top, suggest runner-up
result = execute_skill(top.name, find_matching_params(top.name, params))
result.suggestion = f"Did you also want to {describe(runner.name)}?"
return result
# LOW → multi-layer fallback
return fallback_chain(message, params)
```
## Three-state dispatch strategies
### CLEAR → Direct execution
The top candidate is clearly dominant. Route directly.
```python
if fusion_result.verdict == FusionVerdict.CLEAR:
skill = fusion_result.top.name
# Merge params from the parallel LLM extraction
execute(skill, params)
```
### AMBIGUOUS → Context-dependent strategy
Top-2 candidates are close. Strategy depends on the operation type:
| Scenario | Strategy |
|----------|----------|
| Both are read-only queries | Execute top, mention runner-up as suggestion |
| Contains write operation | Route to orchestrator for explicit confirmation |
| Same entity, different queries | Execute the broadest query (e.g., customer info) |
### LOW → Multi-layer fallback
No confident match. Don't just say "I don't understand" — cascade through fallbacks:
```python
def fallback_chain(message, params):
# Layer 1: Retry with full skill catalog (if domain filter was active)
if was_domain_filtered:
retry_result = await llm_classify(message, full_catalog)
if retry_result:
return execute(retry_result)
# Layer 2: Guide search (if message looks like a how-to question)
if is_how_to_question(message):
return guide_search(message)
# Layer 3: Domain-specific rejection (if domain was matched but no skill fits)
if matched_domains:
return f"I can help with {domain}, but I'm not sure what you need. Try..."
# Layer 4: Free chat
return free_chat(message)
```
## LLM provider resilience
In production, wrap your LLM calls with automatic failover:
```python
class ResilientLLMAdapter:
def __init__(self, primary, fallback):
self.primary = primary
self.fallback = fallback
async def chat(self, messages, **kwargs):
try:
return await asyncio.wait_for(
self.primary.chat(messages, **kwargs),
timeout=10.0,
)
except (asyncio.TimeoutError, Exception):
return await self.fallback.chat(messages, **kwargs)
```
Combined with intent-fusion's built-in single-channel degradation, this gives you
**three layers of resilience:**
1. LLM provider auto-failover (primary → backup)
2. Channel degradation (if tree channel fails, embedding still works)
3. Pipeline fallback chain (if fusion returns LOW)
## Multi-intent detection
Before fusion, check if the message contains multiple distinct actions:
```python
COMPOUND_MARKERS = ("and", "then", "also", "plus")
def is_multi_intent(message):
"""Detect compound actions like 'recharge 200 and add 100 points'."""
for marker in COMPOUND_MARKERS:
parts = message.split(marker)
if sum(1 for p in parts if contains_action_verb(p)) >= 2:
return True
return False
# If multi-intent detected, skip fusion and go straight to orchestrator
if is_multi_intent(message):
return orchestrate(message)
```
## Startup optimization
Pre-build the embedding index at application startup to avoid cold-start latency:
```python
from intent_fusion import IntentRouter
# At startup
router = IntentRouter(entries)
router.build_index() # Pre-compute all embeddings
# On each request — index is already warm
result = await router.fuse(message, llm)
```
The index build takes 1-3 seconds for ~100 intents (one-time cost).
# Labeled test cases for calibration.
#
# These cover the "hard" cases where pure embedding fails:
# - Indirect phrasing ("where's my stuff" → query_order_status)
# - Semantic inference ("this isn't what I ordered" → initiate_return)
# - Ambiguous surface form ("I need help with my order" → could be several)
#
# Run calibration:
# python -m intent_fusion.calibration --cases examples/ecommerce/cases.yaml \
# --intents examples/ecommerce/intents.yaml
cases:
# ── Direct / easy ──
- message: "where is my order"
expected: "query_order_status"
- message: "I want to cancel my order"
expected: "cancel_order"
- message: "how do I return this item"
expected: "initiate_return"
- message: "do you have this in blue"
expected: "check_stock"
- message: "is there a discount code I can use"
expected: "query_promotions"
# ── Indirect phrasing (embedding struggles) ──
- message: "where's my stuff"
expected: "query_order_status"
note: "no keyword match — needs semantic inference"
- message: "it's been two weeks and nothing arrived"
expected: "query_order_status"
note: "complaint framing, not a direct query"
- message: "I changed my mind"
expected: "cancel_order"
note: "no 'cancel' keyword"
- message: "this isn't what I ordered"
expected: "initiate_return"
note: "complaint → return intent"
- message: "the item looks nothing like the photo"
expected: "initiate_return"
note: "dissatisfaction → return"
- message: "when will I see the money back in my account"
expected: "query_refund_status"
note: "indirect refund status query"
- message: "what are the dimensions of this"
expected: "query_product_info"
note: "specific product detail question"
- message: "will this fit a 15-inch laptop"
expected: "query_product_info"
note: "compatibility question → product info"
- message: "how many points do I have left"
expected: "query_account_balance"
note: "loyalty points framing"
- message: "I moved, need to update my shipping address"
expected: "update_account_info"
note: "address update → account info"
# ── Ambiguous cases ──
- message: "I have a problem with my order"
expected: "query_order_status"
note: "ambiguous — could be status, return, or cancel; status is most common"
- message: "I need help"
expected: "free_chat"
note: "too vague — should fall back"
# ── Fallback cases ──
- message: "hello"
expected: "free_chat"
- message: "thanks!"
expected: "free_chat"
- message: "how do I apply a coupon code at checkout"
expected: "guide_search"
note: "how-to question, not a data query"
"""E-commerce intent routing demo.
Demonstrates dual-channel fusion on 5 representative queries:
- Direct query (embedding wins)
- Indirect phrasing (tree reasoning wins)
- Ambiguous input (AMBIGUOUS verdict)
- Small talk (LOW / free_chat)
Usage:
export OPENAI_API_KEY=sk-...
python examples/ecommerce/demo.py
To use a different provider (DeepSeek, Qwen, Ollama):
export OPENAI_BASE_URL=https://api.deepseek.com/v1
export OPENAI_API_KEY=sk-...
export INTENT_FUSION_MODEL=deepseek-chat
python examples/ecommerce/demo.py
"""
from __future__ import annotations
import asyncio
from intent_fusion import FusionVerdict, IntentRouter
from examples.ecommerce.intents import load_intents
from examples.ecommerce.llm_adapter import OpenAIAdapter
TEST_QUERIES = [
("where is my order", "direct — embedding should handle this"),
("it's been two weeks, nothing arrived", "indirect — needs LLM reasoning"),
("I changed my mind", "no 'cancel' keyword — tree channel wins"),
("I have a problem with my order", "ambiguous — expect AMBIGUOUS verdict"),
("hello there", "small talk — expect LOW / free_chat"),
]
async def main():
entries = load_intents()
llm = OpenAIAdapter()
router = IntentRouter(entries)
print(f"Loaded {len(entries)} intents\n")
print("=" * 60)
for query, note in TEST_QUERIES:
result = await router.fuse(query, llm)
top_name = result.top.name if result.top else "—"
top_score = f"{result.top.final_score:.3f}" if result.top else "—"
runner_name = result.runner_up.name if result.runner_up else "—"
verdict_label = {
FusionVerdict.CLEAR: "CLEAR",
FusionVerdict.AMBIGUOUS: "~ AMBIGUOUS",
FusionVerdict.LOW: "? LOW",
}[result.verdict]
print(f'Query: "{query}"')
print(f"Note: {note}")
print(f"Verdict: {verdict_label}")
print(f"Top: {top_name} ({top_score})")
if result.runner_up:
print(f"Runner: {runner_name} ({result.runner_up.final_score:.3f})")
channels = ", ".join(result.active_channels)
degraded = " [DEGRADED]" if result.degraded else ""
print(f"Channels: {channels}{degraded}")
print(f"Timing: emb={result.emb_ms:.0f}ms tree={result.tree_ms:.0f}ms total={result.total_ms:.0f}ms")
print("-" * 60)
if __name__ == "__main__":
asyncio.run(main())
"""Load IntentEntry objects from the ecommerce intents.yaml."""
from __future__ import annotations
from pathlib import Path
from intent_fusion.types import IntentEntry
_HERE = Path(__file__).parent
def load_intents(path: str | Path | None = None) -> list[IntentEntry]:
"""Load intent definitions from YAML.
Args:
path: Path to intents YAML. Defaults to the bundled ecommerce/intents.yaml.
"""
import yaml
if path is None:
path = _HERE / "intents.yaml"
with open(path, encoding="utf-8") as f:
data = yaml.safe_load(f)
entries = []
for item in data.get("intents", []):
entries.append(IntentEntry(
name=item["name"],
domain=item["domain"],
embed_text=item["embed_text"],
tree_text=item.get("tree_text", ""),
))
return entries
# E-commerce intent definitions for intent-fusion demo.
#
# Each intent has:
# name: unique identifier used in routing
# domain: grouping for the intent tree (shown to LLM)
# embed_text: optimized for embedding similarity (surface/lexical)
# tree_text: optimized for LLM reasoning (semantic description)
intents:
# ── Order Management ──
- name: query_order_status
domain: Order Management
embed_text: "track order, where is my package, shipping status, delivery ETA, order tracking"
tree_text: "user wants to know where their order is, current shipping status, or estimated delivery time"
- name: cancel_order
domain: Order Management
embed_text: "cancel order, I don't want it anymore, stop my order, cancel purchase"
tree_text: "user wants to cancel an order they placed, before or after shipment"
- name: modify_order
domain: Order Management
embed_text: "change order, update address, change quantity, edit my order"
tree_text: "user wants to change something about an existing order: address, item, quantity"
# ── Returns & Refunds ──
- name: initiate_return
domain: Returns & Refunds
embed_text: "return item, send back, return request, I want to return this"
tree_text: "user wants to start a return process for a received item"
- name: query_refund_status
domain: Returns & Refunds
embed_text: "refund status, where is my refund, when will I get my money back, refund progress"
tree_text: "user is asking about the status of a refund they already requested"
# ── Product & Inventory ──
- name: query_product_info
domain: Product & Inventory
embed_text: "product details, item description, specifications, what does this product do"
tree_text: "user wants information about a product: description, specs, compatibility, materials"
- name: check_stock
domain: Product & Inventory
embed_text: "in stock, available, do you have this, inventory, out of stock"
tree_text: "user wants to know if a specific product is available or when it will be restocked"
# ── Account & Membership ──
- name: query_account_balance
domain: Account & Membership
embed_text: "account balance, store credit, points balance, how many points do I have"
tree_text: "user wants to check their account balance, store credits, or loyalty points"
- name: update_account_info
domain: Account & Membership
embed_text: "change email, update phone, change password, edit profile, update address"
tree_text: "user wants to update their personal account information: email, phone, address, password"
# ── Promotions ──
- name: query_promotions
domain: Promotions
embed_text: "discount, coupon, promo code, sale, deals, offer, voucher"
tree_text: "user is asking about available discounts, coupons, promotional codes, or ongoing sales"
"""OpenAI-compatible LLM adapter for intent-fusion examples.
Works with any OpenAI-compatible API: OpenAI, DeepSeek, Qwen, local Ollama, etc.
Set OPENAI_API_KEY (or equivalent) in your environment before running.
"""
from __future__ import annotations
import os
from typing import Any
class OpenAIAdapter:
"""Thin wrapper around the openai async client.
Creates one ``AsyncOpenAI`` instance and reuses it across calls
(the underlying httpx pool manages HTTP connection lifecycle).
Args:
model: Model name. Defaults to INTENT_FUSION_MODEL env var or "gpt-4o-mini".
base_url: API base URL. Defaults to OPENAI_BASE_URL env var (OpenAI if unset).
api_key: API key. Defaults to OPENAI_API_KEY env var.
"""
def __init__(
self,
model: str | None = None,
base_url: str | None = None,
api_key: str | None = None,
):
self.model = model or os.getenv("INTENT_FUSION_MODEL", "gpt-4o-mini")
self.base_url = base_url or os.getenv("OPENAI_BASE_URL")
self.api_key = api_key or os.getenv("OPENAI_API_KEY", "")
self._client: Any = None
def _get_client(self) -> Any:
if self._client is None:
from openai import AsyncOpenAI
kwargs: dict[str, Any] = {"api_key": self.api_key}
if self.base_url:
kwargs["base_url"] = self.base_url
self._client = AsyncOpenAI(**kwargs)
return self._client
async def chat(
self,
messages: list[dict[str, str]],
temperature: float = 0.1,
max_tokens: int = 800,
**kwargs: Any,
) -> str:
client = self._get_client()
response = await client.chat.completions.create(
model=self.model,
messages=messages, # type: ignore[arg-type]
temperature=temperature,
max_tokens=max_tokens,
)
return response.choices[0].message.content or ""
import requests
import csv
import time
from urllib.parse import urlencode
# ========== 配置区域 ==========
# 从你提供的请求中提取的 Bearer Token
BEARER_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiZTI1ZDFlZDEtMTQyNy00MTk4LTlmZjMtYTg2MDY3OTc2OWNkIiwiZXhwIjoxNzgwNDgwNTI4LCJpc3MiOiJTRUxGX0hPU1RFRCIsInN1YiI6IkNvbnNvbGUgQVBJIFBhc3Nwb3J0In0.yQMDS6fMPnSjmm1qVbqkDdfSitzwPhslomIri0na4-M"
# API 基础 URL(去掉查询参数)
BASE_URL = "https://aiassistant.glsx.com.cn/console/api/apps/c080837e-cda0-4428-a2f0-9513845d3da6/chat-conversations"
# 可选:如果你的网络需要代理,取消注释并填写代理地址
# PROXY = {
# "http": "http://127.0.0.1:7890",
# "https": "http://127.0.0.1:7890"
# }
# 请求头(只需要 Authorization + 基础 User-Agent)
HEADERS = {
"Authorization": f"Bearer {BEARER_TOKEN}",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Content-Type": "application/json"
}
# 查询参数(可根据需要修改,例如调整时间范围)
PARAMS = {
"limit": 50, # 每页条数,最大100
"start": "2025-06-03 00:00",
"end": "2026-06-03 23:59",
"sort_by": "-created_at",
"annotation_status": "all"
}
# ============================
def get_conversations(page=1):
"""获取单页会话数据"""
params = PARAMS.copy()
params["page"] = page
url = f"{BASE_URL}?{urlencode(params)}"
try:
# 如果设置了代理,加上 proxies=PROXY
resp = requests.get(url, headers=HEADERS, timeout=30) # , proxies=PROXY
if resp.status_code != 200:
print(f"请求失败: {resp.status_code}, {resp.text[:200]}")
return None
return resp.json()
except Exception as e:
print(f"请求异常: {e}")
return None
def main():
all_titles = []
page = 1
while True:
print(f"正在获取第 {page} 页...")
data = get_conversations(page)
if not data:
break
conversations = data.get("data", [])
if not conversations:
print("没有更多数据,结束")
break
for conv in conversations:
title = conv.get("name", "").strip()
if title:
all_titles.append(title)
# 检查是否还有下一页
if not data.get("has_more", False):
break
page += 1
time.sleep(0.5) # 避免请求过快
# 去重并保存
unique_titles = list(dict.fromkeys(all_titles))
print(f"共获取 {len(unique_titles)} 条标题")
# 保存为 CSV 文件
output_file = "dify_titles.csv"
with open(output_file, "w", newline="", encoding="utf-8-sig") as f:
writer = csv.writer(f)
writer.writerow(["标题"])
for title in unique_titles:
writer.writerow([title])
print(f"已保存到 {output_file}")
if __name__ == "__main__":
main()
\ No newline at end of file \ No newline at end of file
import os
import requests
from typing import Any, Dict, Optional
class IntentFusionClient:
"""
Client for interacting with the Intent Fusion Service.
Allows uploading custom intent configuration YAMLs and querying intents.
"""
def __init__(self, base_url: str = "http://127.0.0.1:8000"):
self.base_url = base_url.rstrip('/')
def upload_intents(self, name: str, yaml_content_or_path: str) -> Dict[str, Any]:
"""
Uploads a custom YAML intent configuration to the service.
Args:
name: The name/identifier of your dataset/custom config (e.g. 'glsx_json').
yaml_content_or_path: Either the raw YAML content string or a path to a local YAML file.
Returns:
The server response payload, e.g. {"ok": True, "dataset": "uploads/<name>"}
"""
# Check if the input is a valid file path, if so read its content
if os.path.isfile(yaml_content_or_path):
with open(yaml_content_or_path, 'r', encoding='utf-8') as f:
yaml_content = f.read()
else:
yaml_content = yaml_content_or_path
url = f"{self.base_url}/api/intents/upload"
payload = {
"name": name,
"yaml_content": yaml_content
}
response = requests.post(url, json=payload)
response.raise_for_status()
return response.json()
def fuse(self, message: str, dataset: str, alpha: Optional[float] = None, delta: Optional[float] = None) -> Dict[str, Any]:
"""
Sends a query message to be classified by the specified dataset.
Args:
message: The user query string (e.g. "门店运营数量").
dataset: The dataset key/name (e.g. "glsx_json").
alpha: Optional float override for fusion weight (hybrid scoring).
delta: Optional float override for fusion threshold (decision logic).
Returns:
The classification result including the top intent, candidates, and verdict.
"""
url = f"{self.base_url}/api/fuse"
payload = {
"message": message,
"dataset": dataset
}
if alpha is not None:
payload["alpha"] = alpha
if delta is not None:
payload["delta"] = delta
response = requests.post(url, json=payload)
response.raise_for_status()
return response.json()
def get_top_intent(self, message: str, dataset: str) -> Optional[str]:
"""
Helper method to perform query and directly return the top predicted intent name.
Returns:
The name of the top intent, or None if no intent matched.
"""
res = self.fuse(message, dataset)
top = res.get("top")
if top:
return top.get("name")
return None
# Simple executable demo
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Intent Fusion CLI Client")
parser.add_argument("--url", default="http://127.0.0.1:8000", help="Service Base URL")
parser.add_argument("--upload", help="Path to intents.yaml to upload")
parser.add_argument("--name", help="Dataset/Config name for the uploaded file")
parser.add_argument("--query", help="Text query to test classification")
parser.add_argument("--dataset", help="Dataset name to query against")
args = parser.parse_args()
client = IntentFusionClient(args.url)
try:
if args.upload:
if not args.name:
print("Error: --name is required when uploading a dataset.")
exit(1)
print(f"Uploading file '{args.upload}' as dataset '{args.name}'...")
res = client.upload_intents(args.name, args.upload)
print("Response:", res)
if args.query:
dataset = args.dataset or args.name
if not dataset:
print("Error: --dataset is required to execute a query.")
exit(1)
print(f"Querying '{args.query}' against dataset '{dataset}'...")
res = client.fuse(args.query, dataset)
print("Verdict:", res.get("verdict"))
print("Top Intent:", res.get("top"))
print("Resolved Intents:", res.get("resolved"))
except Exception as e:
print("An error occurred:", e)
...@@ -14,9 +14,16 @@ Two ways to use: ...@@ -14,9 +14,16 @@ Two ways to use:
result = await router.fuse("where is my order", llm) result = await router.fuse("where is my order", llm)
""" """
from intent_fusion.fusion import build_index, fuse_intent, invalidate_cache from intent_fusion.fusion import (
IntentFusionApp,
IntentRegistry,
build_index,
create_app,
fuse_intent,
invalidate_cache,
)
from intent_fusion.router import IntentRouter from intent_fusion.router import IntentRouter
from intent_fusion.tree import LLMProvider from intent_fusion.tree import LLMProvider, OpenAIAdapter
from intent_fusion.types import ( from intent_fusion.types import (
FusedCandidate, FusedCandidate,
FusionResult, FusionResult,
...@@ -27,6 +34,10 @@ from intent_fusion.types import ( ...@@ -27,6 +34,10 @@ from intent_fusion.types import (
__all__ = [ __all__ = [
"IntentRouter", "IntentRouter",
"LLMProvider", "LLMProvider",
"OpenAIAdapter",
"IntentFusionApp",
"create_app",
"IntentRegistry",
"build_index", "build_index",
"fuse_intent", "fuse_intent",
"invalidate_cache", "invalidate_cache",
......
...@@ -61,10 +61,22 @@ def load_cases_from_yaml(path: str | Path) -> list[CalibrationCase]: ...@@ -61,10 +61,22 @@ def load_cases_from_yaml(path: str | Path) -> list[CalibrationCase]:
with open(path, encoding="utf-8") as f: with open(path, encoding="utf-8") as f:
data = yaml.safe_load(f) data = yaml.safe_load(f)
def _map_expected(text: str) -> str:
parts = [p.strip() for p in (text or "").split("|")]
parts = [p for p in parts if p]
out: list[str] = []
seen: set[str] = set()
for p in parts:
if p not in seen:
seen.add(p)
out.append(p)
return " | ".join(out)
return [ return [
CalibrationCase( CalibrationCase(
message=c["message"], message=c["message"],
expected_intent=c["expected"], expected_intent=_map_expected(c["expected"]),
note=c.get("note", ""), note=c.get("note", ""),
) )
for c in data.get("cases", []) for c in data.get("cases", [])
...@@ -147,7 +159,7 @@ async def run_grid_search( ...@@ -147,7 +159,7 @@ async def run_grid_search(
for case, result in zip(cases, fusion_results): for case, result in zip(cases, fusion_results):
if result.verdict == FusionVerdict.LOW: if result.verdict == FusionVerdict.LOW:
low_count += 1 low_count += 1
if case.expected_intent in ("free_chat", "guide_search", "orchestrate"): if case.expected_intent in ("其他查询", "orchestrate"):
correct += 1 correct += 1
elif result.verdict == FusionVerdict.AMBIGUOUS: elif result.verdict == FusionVerdict.AMBIGUOUS:
ambiguous_count += 1 ambiguous_count += 1
...@@ -206,6 +218,12 @@ def main() -> None: ...@@ -206,6 +218,12 @@ def main() -> None:
import argparse import argparse
logging.basicConfig(level=logging.INFO, format="%(message)s") logging.basicConfig(level=logging.INFO, format="%(message)s")
try:
from dotenv import load_dotenv
except ImportError:
load_dotenv = None
if load_dotenv is not None:
load_dotenv()
parser = argparse.ArgumentParser(description="Calibrate intent-fusion alpha/delta") parser = argparse.ArgumentParser(description="Calibrate intent-fusion alpha/delta")
parser.add_argument("--cases", required=True, help="Path to labeled cases YAML") parser.add_argument("--cases", required=True, help="Path to labeled cases YAML")
...@@ -216,8 +234,7 @@ def main() -> None: ...@@ -216,8 +234,7 @@ def main() -> None:
entries = load_intents_from_yaml(args.intents) entries = load_intents_from_yaml(args.intents)
cases = load_cases_from_yaml(args.cases) cases = load_cases_from_yaml(args.cases)
from intent_fusion.tree import OpenAIAdapter
from examples.ecommerce.llm_adapter import OpenAIAdapter
llm = OpenAIAdapter(model=args.model) llm = OpenAIAdapter(model=args.model)
......
...@@ -10,11 +10,13 @@ For multi-instance scenarios (different intent sets in one process), use ...@@ -10,11 +10,13 @@ For multi-instance scenarios (different intent sets in one process), use
from __future__ import annotations from __future__ import annotations
import asyncio
import logging import logging
from pathlib import Path
from typing import Any from typing import Any
from intent_fusion.router import ALPHA, DELTA, IntentRouter from intent_fusion.router import ALPHA, DELTA, IntentRouter
from intent_fusion.tree import LLMProvider from intent_fusion.tree import LLMProvider, OpenAIAdapter
from intent_fusion.types import FusionResult, FusionVerdict, IntentEntry from intent_fusion.types import FusionResult, FusionVerdict, IntentEntry
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -53,6 +55,7 @@ async def fuse_intent( ...@@ -53,6 +55,7 @@ async def fuse_intent(
*, *,
alpha: float = ALPHA, alpha: float = ALPHA,
delta: float = DELTA, delta: float = DELTA,
expand_orchestrate: bool = False,
) -> FusionResult: ) -> FusionResult:
"""Dual-channel intent fusion (convenience function). """Dual-channel intent fusion (convenience function).
...@@ -84,4 +87,214 @@ async def fuse_intent( ...@@ -84,4 +87,214 @@ async def fuse_intent(
if _default_router is None: if _default_router is None:
_default_router = IntentRouter(entries) _default_router = IntentRouter(entries)
return await _default_router.fuse(message, llm, alpha=alpha, delta=delta) return await _default_router.fuse(
message,
llm,
alpha=alpha,
delta=delta,
expand_orchestrate=expand_orchestrate,
)
class IntentFusionApp:
def __init__(
self,
*,
intents_path: str | Path,
llm: LLMProvider,
model_name: str | None = None,
embedding_enabled: bool | None = None,
prewarm: bool = True,
) -> None:
from intent_fusion.calibration import load_intents_from_yaml
self.intents_path = str(intents_path)
self.entries = load_intents_from_yaml(intents_path)
kwargs: dict[str, Any] = {}
if model_name:
kwargs["model_name"] = model_name
if embedding_enabled is not None:
kwargs["embedding_enabled"] = embedding_enabled
self.router = IntentRouter(self.entries, **kwargs)
if prewarm:
self.router.build_index()
self.llm = llm
async def route(
self,
message: str,
*,
alpha: float = ALPHA,
delta: float = DELTA,
) -> FusionResult:
result = await self.router.fuse(
message,
self.llm,
alpha=alpha,
delta=delta,
expand_orchestrate=False,
)
if result.top and result.top.name == "orchestrate":
result = await self.router.fuse(
message,
self.llm,
alpha=alpha,
delta=delta,
expand_orchestrate=True,
)
return result
def route_sync(
self,
message: str,
*,
alpha: float = ALPHA,
delta: float = DELTA,
) -> FusionResult:
return asyncio.run(self.route(message, alpha=alpha, delta=delta))
def create_app(
*,
intents_path: str | Path,
llm: LLMProvider | None = None,
model_name: str | None = None,
embedding_enabled: bool | None = None,
prewarm: bool = True,
) -> IntentFusionApp:
resolved_llm = llm or OpenAIAdapter()
return IntentFusionApp(
intents_path=intents_path,
llm=resolved_llm,
model_name=model_name,
embedding_enabled=embedding_enabled,
prewarm=prewarm,
)
class IntentRegistry:
def __init__(
self,
*,
llm: LLMProvider | None = None,
model_name: str | None = None,
embedding_enabled: bool | None = None,
prewarm: bool = True,
) -> None:
self._llm = llm or OpenAIAdapter()
self._model_name = model_name
self._embedding_enabled = embedding_enabled
self._prewarm = prewarm
self._apps: dict[str, IntentFusionApp] = {}
self._paths: dict[str, Path] = {}
self._mtimes: dict[str, float | None] = {}
def keys(self) -> list[str]:
return sorted(self._apps.keys())
def register(self, key: str, intents_path: str | Path) -> None:
p = Path(intents_path)
try:
mtime = p.stat().st_mtime
except OSError:
mtime = None
app = create_app(
intents_path=p,
llm=self._llm,
model_name=self._model_name,
embedding_enabled=self._embedding_enabled,
prewarm=self._prewarm,
)
self._apps[key] = app
self._paths[key] = p
self._mtimes[key] = mtime
def register_dir(
self,
directory: str | Path,
*,
recursive: bool = True,
key_prefix: str = "",
prune_missing: bool = True,
) -> dict[str, Any]:
base = Path(directory)
base = base.resolve()
pattern = "**/*.yaml" if recursive else "*.yaml"
candidates = sorted(base.glob(pattern), key=lambda p: str(p).lower())
registered: list[str] = []
failed: list[dict[str, str]] = []
seen_keys: set[str] = set()
for p in candidates:
if not p.is_file():
continue
rel = p.relative_to(base)
key = str(rel).replace("\\", "/")
if key.lower().endswith(".yaml"):
key = key[:-5]
if key_prefix:
key = f"{key_prefix}{key}"
seen_keys.add(key)
try:
self.register(key, p)
registered.append(key)
except Exception as e:
failed.append({"key": key, "path": str(p), "error": str(e)})
if prune_missing:
for k in list(self._paths.keys()):
if key_prefix and not k.startswith(key_prefix):
continue
if k not in seen_keys:
self.unregister(k)
return {
"base_dir": str(base),
"registered": registered,
"failed": failed,
"count": len(registered),
}
def unregister(self, key: str) -> None:
self._apps.pop(key, None)
self._paths.pop(key, None)
self._mtimes.pop(key, None)
def _ensure_loaded(self, key: str) -> IntentFusionApp:
app = self._apps.get(key)
if app is None:
raise KeyError(f"unknown_key:{key}")
p = self._paths.get(key)
if p is None:
return app
last = self._mtimes.get(key)
try:
mtime = p.stat().st_mtime
except OSError:
return app
if last is not None and mtime == last:
return app
self.register(key, p)
return self._apps[key]
async def route(
self,
key: str,
message: str,
*,
alpha: float = ALPHA,
delta: float = DELTA,
) -> FusionResult:
app = self._ensure_loaded(key)
return await app.route(message, alpha=alpha, delta=delta)
def route_sync(
self,
key: str,
message: str,
*,
alpha: float = ALPHA,
delta: float = DELTA,
) -> FusionResult:
return asyncio.run(self.route(key, message, alpha=alpha, delta=delta))
...@@ -17,12 +17,18 @@ from __future__ import annotations ...@@ -17,12 +17,18 @@ from __future__ import annotations
import asyncio import asyncio
import logging import logging
import os
import time import time
from typing import Any from typing import Any
import numpy as np import numpy as np
from intent_fusion.tree import LLMProvider, build_intent_tree_text, reason_intent_tree from intent_fusion.tree import (
LLMProvider,
build_intent_tree_text,
reason_intent_tree,
split_compound_message,
)
from intent_fusion.types import ( from intent_fusion.types import (
FusedCandidate, FusedCandidate,
FusionResult, FusionResult,
...@@ -36,7 +42,20 @@ ALPHA: float = 0.10 ...@@ -36,7 +42,20 @@ ALPHA: float = 0.10
DELTA: float = 0.10 DELTA: float = 0.10
LOW_SCORE_THRESHOLD: float = 0.20 LOW_SCORE_THRESHOLD: float = 0.20
EMBEDDING_TOP_K: int = 5 EMBEDDING_TOP_K: int = 5
DEFAULT_MODEL: str = "BAAI/bge-small-en-v1.5" # DEFAULT_MODEL_EN: str = "BAAI/bge-small-en-v1.5"
DEFAULT_MODEL_ZH: str = "BAAI/bge-small-zh-v1.5"
DEFAULT_MODEL: str = DEFAULT_MODEL_ZH
ORCHESTRATE_TREE_THRESHOLD: float = 0.65
ORCHESTRATE_PART_SECONDARY_MIN: float = 0.55
ORCHESTRATE_PART_TOP_N: int = 5
ORCHESTRATE_MAX_INTENTS: int = 5
def _env_truthy(name: str, default: bool = False) -> bool:
raw = os.getenv(name)
if raw is None:
return default
return raw.strip().lower() not in {"", "0", "false", "no", "off"}
class IntentRouter: class IntentRouter:
...@@ -60,8 +79,19 @@ class IntentRouter: ...@@ -60,8 +79,19 @@ class IntentRouter:
entries: list[IntentEntry], entries: list[IntentEntry],
*, *,
model_name: str = DEFAULT_MODEL, model_name: str = DEFAULT_MODEL,
embedding_enabled: bool | None = None,
) -> None: ) -> None:
self._entries = entries self._entries = entries
if embedding_enabled is None:
self._embedding_enabled = not _env_truthy("INTENT_FUSION_DISABLE_EMBEDDING", default=False)
else:
self._embedding_enabled = embedding_enabled
if model_name == DEFAULT_MODEL and any(
any(ord(ch) > 127 for ch in (e.name + e.domain + e.embed_text + e.tree_text))
for e in entries
):
self._model_name = DEFAULT_MODEL_ZH
else:
self._model_name = model_name self._model_name = model_name
self._model: Any = None self._model: Any = None
self._index: list[tuple[str, np.ndarray]] = [] self._index: list[tuple[str, np.ndarray]] = []
...@@ -87,6 +117,8 @@ class IntentRouter: ...@@ -87,6 +117,8 @@ class IntentRouter:
logger.info("IntentRouter: index built (%d entries)", len(index)) logger.info("IntentRouter: index built (%d entries)", len(index))
def _get_model(self) -> Any: def _get_model(self) -> Any:
if not self._embedding_enabled:
return None
if self._model is None: if self._model is None:
try: try:
from sentence_transformers import SentenceTransformer from sentence_transformers import SentenceTransformer
...@@ -119,6 +151,7 @@ class IntentRouter: ...@@ -119,6 +151,7 @@ class IntentRouter:
*, *,
alpha: float = ALPHA, alpha: float = ALPHA,
delta: float = DELTA, delta: float = DELTA,
expand_orchestrate: bool = False,
) -> FusionResult: ) -> FusionResult:
"""Run dual-channel intent fusion with single-channel degradation. """Run dual-channel intent fusion with single-channel degradation.
...@@ -130,6 +163,9 @@ class IntentRouter: ...@@ -130,6 +163,9 @@ class IntentRouter:
llm: LLM provider implementing the LLMProvider protocol. llm: LLM provider implementing the LLMProvider protocol.
alpha: Embedding channel weight in [0, 1]. Default 0.10 (tree-dominant). alpha: Embedding channel weight in [0, 1]. Default 0.10 (tree-dominant).
delta: Score gap threshold for CLEAR vs AMBIGUOUS. Default 0.10. delta: Score gap threshold for CLEAR vs AMBIGUOUS. Default 0.10.
expand_orchestrate: If top intent is orchestrate, split the message and
run tree reasoning per part to produce an ordered
list of concrete intents in result.orchestrated.
Returns: Returns:
FusionResult with verdict, top candidate, runner-up, and timing info. FusionResult with verdict, top candidate, runner-up, and timing info.
...@@ -196,6 +232,14 @@ class IntentRouter: ...@@ -196,6 +232,14 @@ class IntentRouter:
active_channels = ["tree"] active_channels = ["tree"]
degraded = True degraded = True
if (
tree_ok
and tree_top
and tree_top[0][0] == "orchestrate"
and tree_top[0][1] >= ORCHESTRATE_TREE_THRESHOLD
):
effective_alpha = 0.0
candidates = merge_and_score(emb_top, tree_top, effective_alpha) candidates = merge_and_score(emb_top, tree_top, effective_alpha)
result = decide(candidates, delta) result = decide(candidates, delta)
result.emb_ms = emb_ms result.emb_ms = emb_ms
...@@ -203,6 +247,91 @@ class IntentRouter: ...@@ -203,6 +247,91 @@ class IntentRouter:
result.total_ms = (time.time() - t0) * 1000 result.total_ms = (time.time() - t0) * 1000
result.degraded = degraded result.degraded = degraded
result.active_channels = active_channels result.active_channels = active_channels
if (
expand_orchestrate
and result.top is not None
and result.top.name == "orchestrate"
and tree_ok
):
parts = split_compound_message(message)
if len(parts) >= 2:
async def _classify_part(part: str) -> list[tuple[str, float]]:
async def _run_emb_part() -> list[tuple[str, float]]:
return await asyncio.to_thread(self._embedding_channel, part)
async def _run_tree_part() -> list[tuple[str, float]]:
cands = await reason_intent_tree(
part, self._entries, llm, tree_text=self._tree_text,
)
return [(c.skill, float(c.score)) for c in cands]
emb_part, tree_part = await asyncio.gather(_run_emb_part(), _run_tree_part())
part_alpha = alpha
if tree_part and tree_part[0][0] == "orchestrate":
part_alpha = 0.0
part_candidates = merge_and_score(emb_part, tree_part, part_alpha)
filtered = [
c for c in part_candidates
if c.name not in {"orchestrate", "其他查询"}
]
if not filtered:
return []
out: list[tuple[str, float]] = [(filtered[0].name, float(filtered[0].final_score))]
for c in filtered[1:]:
if len(out) >= ORCHESTRATE_PART_TOP_N:
break
if float(c.final_score) < ORCHESTRATE_PART_SECONDARY_MIN:
continue
out.append((c.name, float(c.final_score)))
return out
part_results = await asyncio.gather(
*(_classify_part(p) for p in parts),
return_exceptions=True,
)
seen: set[str] = set()
for part, item in zip(parts, part_results):
if isinstance(item, BaseException):
continue
for skill, score in item:
skill = skill.strip()
result.orchestrated_parts.append((part, skill, float(score)))
if not skill:
continue
if skill in seen:
continue
seen.add(skill)
result.orchestrated.append(skill)
if len(result.orchestrated) >= ORCHESTRATE_MAX_INTENTS:
break
if len(result.orchestrated) >= ORCHESTRATE_MAX_INTENTS:
break
else:
# First try tree_top (non-orchestrate candidates from LLM)
for name, _score in tree_top:
if name == "orchestrate":
continue
if name in result.orchestrated:
continue
result.orchestrated.append(name)
result.orchestrated_parts.append(("", name, float(_score)))
if len(result.orchestrated) >= ORCHESTRATE_MAX_INTENTS:
break
# If still empty, fall back to merged candidates (handles case
# where LLM only returned orchestrate without top[1]/top[2])
if not result.orchestrated:
for c in candidates:
if c.name in {"orchestrate", "其他查询"}:
continue
if c.name in result.orchestrated:
continue
result.orchestrated.append(c.name)
result.orchestrated_parts.append(("", c.name, float(c.final_score)))
if len(result.orchestrated) >= ORCHESTRATE_MAX_INTENTS:
break
if result.top: if result.top:
logger.info( logger.info(
......
...@@ -12,6 +12,7 @@ from __future__ import annotations ...@@ -12,6 +12,7 @@ from __future__ import annotations
import json import json
import logging import logging
import os
import re import re
from typing import Any, Protocol, runtime_checkable from typing import Any, Protocol, runtime_checkable
...@@ -34,6 +35,88 @@ class LLMProvider(Protocol): ...@@ -34,6 +35,88 @@ class LLMProvider(Protocol):
... ...
class OpenAIAdapter:
def __init__(
self,
model: str | None = None,
base_url: str | None = None,
api_key: str | None = None,
enable_thinking: bool | None = None,
) -> None:
env_model = os.getenv("INTENT_FUSION_MODEL")
env_base_url = os.getenv("INTENT_FUSION_BASE_URL")
env_dashscope_key = os.getenv("DASHSCOPE_API_KEY")
resolved_base_url = base_url or env_base_url
if resolved_base_url is None and env_dashscope_key:
resolved_base_url = "https://dashscope.aliyuncs.com/compatible-mode/v1"
if model is not None:
resolved_model = model
elif env_model:
resolved_model = env_model
else:
resolved_model = (
"deepseek-v4-flash"
)
resolved_api_key = api_key or env_dashscope_key or os.getenv("OPENAI_API_KEY")
if enable_thinking is None:
env_enable_thinking = os.getenv("INTENT_FUSION_ENABLE_THINKING")
if env_enable_thinking is None:
resolved_enable_thinking = bool(resolved_base_url and "dashscope.aliyuncs.com" in resolved_base_url)
else:
resolved_enable_thinking = env_enable_thinking.strip().lower() not in {"0", "false", "no", "off"}
else:
resolved_enable_thinking = enable_thinking
self.model = resolved_model
self.base_url = resolved_base_url
self.api_key = resolved_api_key
self.enable_thinking = resolved_enable_thinking
self._client: Any = None
def _get_client(self) -> Any:
if self._client is None:
try:
from openai import AsyncOpenAI
except ImportError as e:
raise ImportError(
"Missing optional dependency: openai. Install with `pip install openai`."
) from e
kwargs: dict[str, Any] = {"api_key": self.api_key}
if self.base_url:
kwargs["base_url"] = self.base_url
self._client = AsyncOpenAI(**kwargs)
return self._client
async def chat(
self,
messages: list[dict[str, str]],
temperature: float = 0.1,
max_tokens: int = 800,
**kwargs: Any,
) -> str:
client = self._get_client()
request_kwargs: dict[str, Any] = dict(kwargs)
if self.enable_thinking:
extra_body = request_kwargs.get("extra_body")
if extra_body is None:
request_kwargs["extra_body"] = {"enable_thinking": True}
elif isinstance(extra_body, dict):
request_kwargs["extra_body"] = {**extra_body, "enable_thinking": True}
response = await client.chat.completions.create(
model=self.model,
messages=messages, # type: ignore[arg-type]
temperature=temperature,
max_tokens=max_tokens,
**request_kwargs,
)
return response.choices[0].message.content or ""
# ── Build Intent Tree Text ── # ── Build Intent Tree Text ──
def build_intent_tree_text(entries: list[IntentEntry]) -> str: def build_intent_tree_text(entries: list[IntentEntry]) -> str:
...@@ -57,42 +140,88 @@ def build_intent_tree_text(entries: list[IntentEntry]) -> str: ...@@ -57,42 +140,88 @@ def build_intent_tree_text(entries: list[IntentEntry]) -> str:
parts.append("") parts.append("")
# Built-in fallback targets (always present) # Built-in fallback targets (always present)
parts.append("── Special (non-intent) ──") parts.append("── 特殊(多意图) ──")
parts.append(" free_chat: greetings, small talk, questions unrelated to the system") parts.append(" orchestrate: 一条消息包含多个意图")
parts.append(" guide_search: user asks how to do something, where to find a feature")
parts.append(" orchestrate: single message contains multiple distinct actions")
return "\n".join(parts) return "\n".join(parts)
# ── Prompt Template ── # ── Prompt Template ──
# INTENT_TREE_PROMPT = """\
# You are an intent classifier. Given the user message, select the best matching \
# intents from the intent tree below.
# ## Intent Tree
# {tree_text}
# ## User Message
# "{message}"
# ## Instructions
# First reason inside <think> tags:
# 1. What does the user want? (action + object)
# 2. Which domain is most likely?
# 3. Which intent in that domain fits best? What did you rule out?
# Then output JSON:
# {{"top": [{{"skill": "intent_name", "score": 0.0-1.0}}, ...]}}
# Rules:
# - Output exactly 3 candidates, sorted by score descending
# - Intent names must exactly match the tree (no invention)
# - Score guide: very confident 0.85-0.95, fairly confident 0.65-0.84, uncertain 0.40-0.64
# - Pure greetings / small talk → free_chat
# - "How do I..." / "Where is the setting for..." → guide_search
# - Multiple distinct actions in one message → orchestrate"""
INTENT_TREE_PROMPT = """\ INTENT_TREE_PROMPT = """\
You are an intent classifier. Given the user message, select the best matching \ 你是一名意图分类器。根据用户消息,从下面的意图树中选择最匹配的意图(可支持多意图)。
intents from the intent tree below.
## Intent Tree ## 意图树
{tree_text} {tree_text}
## User Message ## 用户消息
"{message}" "{message}"
## Instructions ## 说明
First reason inside <think> tags: <think> 标签内的第一个原因:
1. What does the user want? (action + object)
2. Which domain is most likely?
3. Which intent in that domain fits best? What did you rule out?
Then output JSON: 1. 用户想要什么?(操作 + 对象)
2. 最有可能的领域是什么?
3. 该领域中哪个意图最合适?你排除了哪些意图?
然后输出 JSON:
{{"top": [{{"skill": "intent_name", "score": 0.0-1.0}}, ...]}} {{"top": [{{"skill": "intent_name", "score": 0.0-1.0}}, ...]}}
Rules: 规则:
- Output exactly 3 candidates, sorted by score descending - 输出 3 个候选意图,按分数降序排列
- Intent names must exactly match the tree (no invention) - 意图名称必须与树中的名称完全匹配(不允许自定义)
- Score guide: very confident 0.85-0.95, fairly confident 0.65-0.84, uncertain 0.40-0.64 - 分数指南:非常有把握 0.85-0.95,比较有把握 0.65-0.84,不确定 0.40-0.64
- Pure greetings / small talk → free_chat - 一条消息包含多个意图:top[0] 必须输出 orchestrate;
- "How do I..." / "Where is the setting for..." → guide_search 例如:
- Multiple distinct actions in one message → orchestrate""" - 查询北京博瑞祥宇本月延保产值 + 东莞上月转化率前十门店 → top[0]=orchestrate;
- 分析下这个店店内几个驻点人员各自数据,以及结合去过这个店的历史驻店零售人员的转化率分析下个月应该怎么调度,哪个驻店零售到店谈客可以完成兜底了目标 → top[0]=orchestrate;
- 分享5月8日海通重庆龙华大道卖出露笑科技的交易信息 → 其他查询
- 单纯闲聊/打招呼 → 其他查询"""
def split_compound_message(message: str) -> list[str]:
text = message.strip()
if not text:
return []
pattern = (
r"(?:\s*[++]\s*|"
r"[\n\r]+|"
r"[,,、;;。!?]+|"
r"\s*(?:并且|同时|然后|以及|另外|再者|再)\s*)"
)
parts = re.split(pattern, text, flags=re.IGNORECASE)
cleaned = [p.strip().strip('"').strip("“”") for p in parts if p and p.strip()]
return cleaned
# ── Parse LLM Response ── # ── Parse LLM Response ──
...@@ -173,6 +302,9 @@ async def reason_intent_tree( ...@@ -173,6 +302,9 @@ async def reason_intent_tree(
if tree_text is None: if tree_text is None:
tree_text = build_intent_tree_text(entries) tree_text = build_intent_tree_text(entries)
# print(f"tree_text:{tree_text}")
# logger.info(f"tree_text_log:{tree_text}")
prompt = INTENT_TREE_PROMPT.format(tree_text=tree_text, message=message) prompt = INTENT_TREE_PROMPT.format(tree_text=tree_text, message=message)
messages = [{"role": "user", "content": prompt}] messages = [{"role": "user", "content": prompt}]
......
...@@ -4,7 +4,6 @@ from __future__ import annotations ...@@ -4,7 +4,6 @@ from __future__ import annotations
from dataclasses import dataclass, field from dataclasses import dataclass, field
from enum import Enum from enum import Enum
from typing import Any
@dataclass @dataclass
...@@ -60,6 +59,8 @@ class FusionResult: ...@@ -60,6 +59,8 @@ class FusionResult:
top: FusedCandidate | None = None top: FusedCandidate | None = None
runner_up: FusedCandidate | None = None runner_up: FusedCandidate | None = None
candidates: list[FusedCandidate] = field(default_factory=list) candidates: list[FusedCandidate] = field(default_factory=list)
orchestrated: list[str] = field(default_factory=list)
orchestrated_parts: list[tuple[str, str, float]] = field(default_factory=list)
emb_ms: float = 0.0 emb_ms: float = 0.0
tree_ms: float = 0.0 tree_ms: float = 0.0
total_ms: float = 0.0 total_ms: float = 0.0
......
from intent_fusion import IntentFusionApp, OpenAIAdapter
app = IntentFusionApp(
intents_path="benchmarks/glsx/intents.yaml",
llm=OpenAIAdapter(),
embedding_enabled=False,
prewarm=False,
)
result = app.route_sync("询问本月新车交付数")
print(result.top.name if result.top else None)
print(result.orchestrated) # 多意图时会有值
numpy>=1.24
sentence-transformers>=2.7
pyyaml>=6.0
openai>=1.0
python-dotenv>=1.0
openpyxl>=3.1
This diff is collapsed. Click to expand it.
"""Shared test fixtures for intent-fusion tests."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
import numpy as np
import pytest
from intent_fusion.types import IntentEntry
class MockLLM:
"""Deterministic mock LLM for testing.
Returns a fixed JSON response that maps specific keywords to intents.
"""
def __init__(self, response: str | None = None):
self._response = response
async def chat(self, messages: list[dict[str, str]], **kwargs) -> str:
if self._response is not None:
return self._response
user_msg = messages[-1]["content"] if messages else ""
if "where is my order" in user_msg or "shipping" in user_msg:
return '{"top": [{"skill": "query_order_status", "score": 0.92}, {"skill": "cancel_order", "score": 0.30}, {"skill": "free_chat", "score": 0.10}]}'
if "cancel" in user_msg or "changed my mind" in user_msg:
return '{"top": [{"skill": "cancel_order", "score": 0.90}, {"skill": "query_order_status", "score": 0.35}, {"skill": "free_chat", "score": 0.10}]}'
if "return" in user_msg or "send back" in user_msg:
return '{"top": [{"skill": "initiate_return", "score": 0.88}, {"skill": "query_refund_status", "score": 0.40}, {"skill": "free_chat", "score": 0.10}]}'
if "hello" in user_msg or "hi there" in user_msg:
return '{"top": [{"skill": "free_chat", "score": 0.95}, {"skill": "query_order_status", "score": 0.10}, {"skill": "cancel_order", "score": 0.05}]}'
return '{"top": [{"skill": "free_chat", "score": 0.60}, {"skill": "query_order_status", "score": 0.20}, {"skill": "cancel_order", "score": 0.10}]}'
class FailingLLM:
"""LLM that always raises an exception."""
async def chat(self, messages: list[dict[str, str]], **kwargs) -> str:
raise ConnectionError("LLM service unavailable")
SAMPLE_ENTRIES = [
IntentEntry(
name="query_order_status",
domain="Order Management",
embed_text="track order, where is my package, shipping status, delivery ETA",
tree_text="user wants to know where their order is or current shipping status",
),
IntentEntry(
name="cancel_order",
domain="Order Management",
embed_text="cancel order, I don't want it anymore, stop my order",
tree_text="user wants to cancel an order they placed",
),
IntentEntry(
name="initiate_return",
domain="Returns & Refunds",
embed_text="return item, send back, return request",
tree_text="user wants to start a return process for a received item",
),
IntentEntry(
name="query_refund_status",
domain="Returns & Refunds",
embed_text="refund status, where is my refund, money back",
tree_text="user is asking about the status of a refund",
),
IntentEntry(
name="query_product_info",
domain="Product",
embed_text="product details, item description, specifications",
tree_text="user wants information about a product",
),
]
def _make_fake_model():
"""Create a fake SentenceTransformer that returns deterministic vectors.
Maps intent names to fixed vectors so cosine similarity is predictable:
query_order_status -> high similarity to "order" queries,
cancel_order -> high similarity to "cancel" queries, etc.
"""
rng = np.random.RandomState(42)
name_to_vec: dict[str, np.ndarray] = {}
def encode(texts: list[str], normalize_embeddings: bool = False) -> np.ndarray:
results = []
for text in texts:
text_lower = text.lower()
key = text_lower[:80]
if key not in name_to_vec:
vec = rng.randn(384).astype(np.float32)
if "order" in text_lower or "shipping" in text_lower or "where" in text_lower:
vec[0] = 5.0
if "cancel" in text_lower or "changed my mind" in text_lower:
vec[1] = 5.0
if "return" in text_lower or "send back" in text_lower:
vec[2] = 5.0
if "refund" in text_lower or "money back" in text_lower:
vec[3] = 5.0
if "product" in text_lower or "description" in text_lower:
vec[4] = 5.0
if normalize_embeddings:
norm = np.linalg.norm(vec)
if norm > 0:
vec = vec / norm
name_to_vec[key] = vec
results.append(name_to_vec[key])
return np.array(results)
model = MagicMock()
model.encode = encode
return model
@pytest.fixture
def sample_entries() -> list[IntentEntry]:
return list(SAMPLE_ENTRIES)
@pytest.fixture
def mock_llm() -> MockLLM:
return MockLLM()
@pytest.fixture
def failing_llm() -> FailingLLM:
return FailingLLM()
@pytest.fixture(autouse=True)
def _mock_sentence_transformer():
"""Globally mock SentenceTransformer to avoid downloading real models."""
fake_model = _make_fake_model()
with patch(
"sentence_transformers.SentenceTransformer",
return_value=fake_model,
):
yield
"""Tests for the calibration grid search."""
import pytest
from intent_fusion.calibration import CalibrationCase, GridPoint, run_grid_search
from tests.conftest import MockLLM, SAMPLE_ENTRIES
async def test_grid_search_returns_best(sample_entries):
cases = [
CalibrationCase(message="where is my order", expected_intent="query_order_status"),
CalibrationCase(message="cancel my order", expected_intent="cancel_order"),
CalibrationCase(message="hello", expected_intent="free_chat"),
]
best = await run_grid_search(
cases,
sample_entries,
MockLLM(),
alpha_values=[0.10, 0.50],
delta_values=[0.10, 0.20],
)
assert isinstance(best, GridPoint)
assert 0.0 <= best.accuracy <= 1.0
assert best.total == 3
async def test_grid_search_csv_output(sample_entries, tmp_path):
cases = [
CalibrationCase(message="where is my order", expected_intent="query_order_status"),
]
csv_path = tmp_path / "results.csv"
await run_grid_search(
cases,
sample_entries,
MockLLM(),
alpha_values=[0.10],
delta_values=[0.10],
output_csv=csv_path,
)
assert csv_path.exists()
content = csv_path.read_text()
assert "alpha" in content
assert "accuracy" in content
"""Tests for the three-state decision logic."""
from intent_fusion.router import decide
from intent_fusion.types import FusedCandidate, FusionVerdict
def _cand(name: str, score: float) -> FusedCandidate:
return FusedCandidate(name=name, final_score=score)
def test_clear_with_large_gap():
"""CLEAR when top-1 is well above top-2."""
candidates = [_cand("a", 0.80), _cand("b", 0.50)]
result = decide(candidates, delta=0.10)
assert result.verdict == FusionVerdict.CLEAR
assert result.top.name == "a"
assert result.runner_up.name == "b"
def test_ambiguous_with_small_gap():
"""AMBIGUOUS when top-1 and top-2 are close."""
candidates = [_cand("a", 0.80), _cand("b", 0.75)]
result = decide(candidates, delta=0.10)
assert result.verdict == FusionVerdict.AMBIGUOUS
assert result.top.name == "a"
assert result.runner_up.name == "b"
def test_low_below_threshold():
"""LOW when top score is below LOW_SCORE_THRESHOLD."""
candidates = [_cand("a", 0.15), _cand("b", 0.10)]
result = decide(candidates, delta=0.10)
assert result.verdict == FusionVerdict.LOW
def test_empty_candidates():
"""LOW when no candidates at all."""
result = decide([], delta=0.10)
assert result.verdict == FusionVerdict.LOW
assert result.top is None
def test_single_candidate_above_threshold():
"""CLEAR when there's only one candidate above threshold."""
candidates = [_cand("a", 0.80)]
result = decide(candidates, delta=0.10)
assert result.verdict == FusionVerdict.CLEAR
assert result.runner_up is None
def test_gap_exactly_at_delta():
"""CLEAR when gap == delta (boundary condition)."""
candidates = [_cand("a", 0.80), _cand("b", 0.70)]
result = decide(candidates, delta=0.10)
assert result.verdict == FusionVerdict.CLEAR
def test_gap_just_below_delta():
"""AMBIGUOUS when gap is epsilon below delta."""
candidates = [_cand("a", 0.80), _cand("b", 0.71)]
result = decide(candidates, delta=0.10)
assert result.verdict == FusionVerdict.AMBIGUOUS
def test_strict_delta():
"""Higher delta means harder to reach CLEAR."""
candidates = [_cand("a", 0.80), _cand("b", 0.55)]
assert decide(candidates, delta=0.10).verdict == FusionVerdict.CLEAR
assert decide(candidates, delta=0.30).verdict == FusionVerdict.AMBIGUOUS
def test_candidates_list_preserved():
"""All candidates are included in the result."""
candidates = [_cand("a", 0.80), _cand("b", 0.50), _cand("c", 0.30)]
result = decide(candidates, delta=0.10)
assert len(result.candidates) == 3
"""Tests for single-channel degradation behavior."""
from unittest.mock import patch
import pytest
from intent_fusion import IntentRouter, FusionVerdict
from tests.conftest import FailingLLM, MockLLM, SAMPLE_ENTRIES
class TestTreeChannelFailure:
"""When the tree (LLM) channel fails, embedding alone should still work."""
async def test_degraded_with_failing_llm(self, sample_entries):
router = IntentRouter(sample_entries)
result = await router.fuse("where is my order", FailingLLM())
assert result.degraded is True
assert result.active_channels == ["embedding"]
assert result.top is not None
async def test_degraded_still_returns_candidates(self, sample_entries):
router = IntentRouter(sample_entries)
result = await router.fuse("cancel my order", FailingLLM())
assert result.degraded is True
assert len(result.candidates) > 0
class TestEmbeddingChannelFailure:
"""When embedding model fails, tree alone should still work."""
async def test_degraded_without_embedding(self, sample_entries, mock_llm):
router = IntentRouter(sample_entries)
def _broken_emb(msg):
raise RuntimeError("embedding model crashed")
router._embedding_channel = _broken_emb
result = await router.fuse("where is my order", mock_llm)
assert result.degraded is True
assert result.active_channels == ["tree"]
assert result.top is not None
class TestBothChannelsFail:
"""When both channels fail, result should be LOW."""
async def test_both_fail_returns_low(self, sample_entries):
router = IntentRouter(sample_entries)
def _broken_emb(msg):
raise RuntimeError("embedding broken")
router._embedding_channel = _broken_emb
result = await router.fuse("where is my order", FailingLLM())
assert result.verdict == FusionVerdict.LOW
assert result.degraded is True
assert result.active_channels == []
"""End-to-end tests for fuse_intent with mock LLM."""
import pytest
from intent_fusion import IntentRouter, fuse_intent, FusionVerdict, invalidate_cache
from tests.conftest import MockLLM, SAMPLE_ENTRIES
@pytest.fixture(autouse=True)
def _clean_singleton():
invalidate_cache()
yield
invalidate_cache()
class TestIntentRouter:
"""Tests using the class-based IntentRouter API."""
async def test_clear_direct_query(self, sample_entries, mock_llm):
router = IntentRouter(sample_entries)
result = await router.fuse("where is my order", mock_llm)
assert result.verdict == FusionVerdict.CLEAR
assert result.top is not None
assert result.top.name == "query_order_status"
assert result.total_ms > 0
async def test_small_talk_verdict(self, sample_entries):
"""Small talk should not get a confident CLEAR on a real intent."""
llm = MockLLM()
router = IntentRouter(sample_entries)
result = await router.fuse("hello there", llm)
assert result.verdict is not None
assert result.total_ms > 0
async def test_active_channels_both(self, sample_entries, mock_llm):
router = IntentRouter(sample_entries)
result = await router.fuse("where is my order", mock_llm)
assert result.degraded is False
assert "embedding" in result.active_channels
assert "tree" in result.active_channels
async def test_timing_fields_populated(self, sample_entries, mock_llm):
router = IntentRouter(sample_entries)
result = await router.fuse("cancel my order", mock_llm)
assert result.emb_ms >= 0
assert result.tree_ms >= 0
assert result.total_ms >= 0
async def test_candidates_list_populated(self, sample_entries, mock_llm):
router = IntentRouter(sample_entries)
result = await router.fuse("where is my order", mock_llm)
assert len(result.candidates) > 0
class TestFuseIntentFunction:
"""Tests using the convenience function API."""
async def test_function_api_works(self, sample_entries, mock_llm):
result = await fuse_intent("where is my order", sample_entries, mock_llm)
assert result.verdict in (FusionVerdict.CLEAR, FusionVerdict.AMBIGUOUS)
assert result.top is not None
async def test_function_api_reuses_router(self, sample_entries, mock_llm):
r1 = await fuse_intent("where is my order", sample_entries, mock_llm)
r2 = await fuse_intent("cancel my order", sample_entries, mock_llm)
assert r1.top is not None
assert r2.top is not None
"""Tests for merge_and_score logic."""
from intent_fusion.router import merge_and_score
def test_both_channels_agree():
"""When both channels return the same candidate, it scores highest."""
emb = [("query_order_status", 0.85), ("cancel_order", 0.60)]
tree = [("query_order_status", 0.90), ("initiate_return", 0.40)]
result = merge_and_score(emb, tree, alpha=0.10)
assert result[0].name == "query_order_status"
assert result[0].in_emb is True
assert result[0].in_tree is True
expected = 0.10 * 0.85 + 0.90 * 0.90
assert abs(result[0].final_score - expected) < 1e-6
def test_embedding_only_candidate():
"""Candidate only in embedding gets alpha * emb_score."""
emb = [("cancel_order", 0.80)]
tree = [("query_order_status", 0.90)]
result = merge_and_score(emb, tree, alpha=0.30)
cancel = next(c for c in result if c.name == "cancel_order")
assert cancel.in_emb is True
assert cancel.in_tree is False
assert abs(cancel.final_score - 0.30 * 0.80) < 1e-6
def test_tree_only_candidate():
"""Candidate only in tree gets (1-alpha) * tree_score."""
emb = [("cancel_order", 0.80)]
tree = [("query_order_status", 0.90)]
result = merge_and_score(emb, tree, alpha=0.30)
query = next(c for c in result if c.name == "query_order_status")
assert query.in_emb is False
assert query.in_tree is True
assert abs(query.final_score - 0.70 * 0.90) < 1e-6
def test_empty_inputs():
"""Empty channel inputs produce empty results."""
assert merge_and_score([], [], 0.10) == []
def test_sorted_descending():
"""Candidates are sorted by final_score descending."""
emb = [("a", 0.50), ("b", 0.90)]
tree = [("c", 0.80)]
result = merge_and_score(emb, tree, alpha=0.50)
scores = [c.final_score for c in result]
assert scores == sorted(scores, reverse=True)
def test_alpha_zero_ignores_embedding():
"""alpha=0.0 means embedding scores contribute nothing."""
emb = [("a", 0.99)]
tree = [("b", 0.50)]
result = merge_and_score(emb, tree, alpha=0.0)
a = next(c for c in result if c.name == "a")
b = next(c for c in result if c.name == "b")
assert a.final_score == 0.0
assert abs(b.final_score - 0.50) < 1e-6
def test_alpha_one_ignores_tree():
"""alpha=1.0 means tree scores contribute nothing."""
emb = [("a", 0.50)]
tree = [("b", 0.99)]
result = merge_and_score(emb, tree, alpha=1.0)
a = next(c for c in result if c.name == "a")
b = next(c for c in result if c.name == "b")
assert abs(a.final_score - 0.50) < 1e-6
assert b.final_score == 0.0
"""Tests for LLM response parsing in the tree channel."""
from intent_fusion.tree import parse_tree_response
def test_clean_json():
"""Parse a clean JSON response."""
text = '{"top": [{"skill": "query_order_status", "score": 0.92}, {"skill": "cancel_order", "score": 0.30}]}'
result = parse_tree_response(text)
assert len(result) == 2
assert result[0].skill == "query_order_status"
assert abs(result[0].score - 0.92) < 1e-6
def test_think_tags():
"""Parse response with <think> reasoning block."""
text = """<think>
The user is asking about their order status.
Domain: Order Management.
Best match: query_order_status.
</think>
{"top": [{"skill": "query_order_status", "score": 0.90}, {"skill": "cancel_order", "score": 0.25}, {"skill": "free_chat", "score": 0.10}]}"""
result = parse_tree_response(text)
assert len(result) == 3
assert result[0].skill == "query_order_status"
def test_json_in_prose():
"""Parse JSON embedded in extra text."""
text = 'Based on my analysis, here is the result:\n{"top": [{"skill": "cancel_order", "score": 0.85}]}\nThank you.'
result = parse_tree_response(text)
assert len(result) == 1
assert result[0].skill == "cancel_order"
def test_score_clamping():
"""Scores above 1.0 or below 0.0 are clamped."""
text = '{"top": [{"skill": "a", "score": 1.5}, {"skill": "b", "score": -0.3}]}'
result = parse_tree_response(text)
assert result[0].score == 1.0
assert result[1].score == 0.0
def test_missing_score_defaults():
"""Missing score defaults to 0.5."""
text = '{"top": [{"skill": "a"}]}'
result = parse_tree_response(text)
assert result[0].score == 0.5
def test_invalid_json():
"""Invalid JSON returns empty list."""
result = parse_tree_response("this is not json at all")
assert result == []
def test_empty_top_array():
"""Empty top array returns empty list."""
text = '{"top": []}'
result = parse_tree_response(text)
assert result == []
def test_reason_field_preserved():
"""Optional reason field is captured."""
text = '{"top": [{"skill": "a", "score": 0.9, "reason": "exact match"}]}'
result = parse_tree_response(text)
assert result[0].reason == "exact match"
def test_truncated_think_tag():
"""Handle <think> without closing tag (token truncation)."""
text = '<think>The user wants to...\n{"top": [{"skill": "query_order_status", "score": 0.85}]}'
result = parse_tree_response(text)
assert len(result) >= 1
assert result[0].skill == "query_order_status"
intents:
- name: "门店运营分析"
domain: "门店运营"
embed_text: "门店数量统计, 门店列表, 查询门店, 门店信息, 门店分布, 门店明细, 门店地址, 门店省市, 品牌门店, 城市门店, 省份门店, 门店范围, 门店覆盖, 在营门店"
tree_text: "用户仅查询门店实体本身的基础信息:在营门店数量、门店列表/明细/分布、门店属性(省市/地址/品牌)。不包含任何经营指标(产值/触客/成交/转化/延保/二手等),不包含任何人员信息(驻店人员/员工清单/排班)。"
- name: "经营指标分析"
domain: "经营分析"
embed_text: "产值, 营收, 本月产值, 截止今天产值, 半年产值, 产值统计, 结构占比, 完成率, 环比, 同比, 预计, 预测, 预估, 目标达成, 触客数, 总触客数, 触客趋势, 触客差异, 触客率, 客单价, 应触客数, 转化率, 成交率, 漏斗, 成交数, 成交量, 新车交付数, 交付数, 订单数, 成交趋势, 成交走势, 延保渗透率, 延保覆盖率, 延保收入, 延保产值, 延保收入占比, 收入结构, 员工触客数, 人员业绩, 门店产值"
tree_text: "用户查询任何经营指标的数值、汇总、趋势、环比同比、预测、结构占比、排名、对比等。即使涉及门店维度展开或人员维度展开,只要核心是指标数值或分析,均归入此类。不包含风险预警(生态系数/预警)和二手业务指标。"
- name: "组织与调度"
domain: "组织与调度"
embed_text: "驻店人员, 驻点人员, 调度, 到店谈客, 兜底目标, 人员安排建议, 排班, 驻店零售, 人员清单, 员工清单, 员工姓名, 谁在驻店, 调谁去, 排班表"
tree_text: "用户查询人员清单(不带业绩数值)、排班、调度建议、到店安排等。核心对象是“人”而非指标。如果用户问及人员的业绩(如触客数、成交率),则自动归入「经营指标分析」。"
- name: "风险预警分析"
domain: "风险预警"
embed_text: "生态系数预警, 预警门店, 风险预警, 指标预警, 生态系数, 预警对比, 风险排序"
tree_text: "用户想查看风险/预警门店清单(如生态系数预警)并进行对比、排序或原因分析。"
- name: "报表查看"
domain: "报表与复盘"
embed_text: "周报, 月报, 日报, 业绩周报, 展业周报, 报表查看, 复盘报告"
tree_text: "用户想查看或获取某类周期性报表(周报/月报等)或复盘信息。"
- name: "二手业务分析"
domain: "二手业务"
embed_text: "二手, 二手车, 收车数, 收车成本, 收车走势, 收车环比, 收车同比, 收车排名, 收车Top门店, 二手收车, 二手车毛利, 毛利率, 毛利环比, 毛利同比, 二手车盈利, 利润分析"
tree_text: "用户想查询或分析二手业务指标(收车/毛利/利润等),包括趋势、环比同比、排名或对比分析。"
- name: "其他查询"
domain: "其他"
embed_text: "你好, 在吗, 谢谢, 哈哈, 你是谁, 你能做什么, 帮助, 随便聊聊, 闲聊, 隐私, 权限, 数据来源, 系统提示词, 安全策略, 内部接口, 公司股价, 午餐推荐, 深圳火锅推荐, 政治, 历史事件, 社会热点, 政府, 执政, 党史, 毛泽东, 天安门, 六四, 法轮功"
tree_text: "用户提出与业务指标/报表/门店/经营分析无关的问题或内容:闲聊、打招呼、表达情绪、问你是谁/能做什么、询问隐私/权限/数据来源/系统规则、以及政治历史社会等非业务话题。"
\ No newline at end of file \ No newline at end of file
intents:
- name: "门店运营分析"
domain: "门店运营"
embed_text: "门店数量统计, 门店列表, 查询门店, 门店信息, 门店分布, 门店明细, 门店地址, 门店省市, 品牌门店, 城市门店, 省份门店, 门店范围, 门店覆盖, 在营门店"
tree_text: "用户仅查询门店实体本身的基础信息:在营门店数量、门店列表/明细/分布、门店属性(省市/地址/品牌)。不包含任何经营指标(产值/触客/成交/转化/延保/二手等),不包含任何人员信息(驻店人员/员工清单/排班)。"
- name: "经营指标分析"
domain: "经营分析"
embed_text: "产值, 营收, 本月产值, 截止今天产值, 半年产值, 产值统计, 结构占比, 完成率, 环比, 同比, 预计, 预测, 预估, 目标达成, 触客数, 总触客数, 触客趋势, 触客差异, 触客率, 客单价, 应触客数, 转化率, 成交率, 漏斗, 成交数, 成交量, 新车交付数, 交付数, 订单数, 成交趋势, 成交走势, 延保渗透率, 延保覆盖率, 延保收入, 延保产值, 延保收入占比, 收入结构, 员工触客数, 人员业绩, 门店产值"
tree_text: "用户查询任何经营指标的数值、汇总、趋势、环比同比、预测、结构占比、排名、对比等。即使涉及门店维度展开或人员维度展开,只要核心是指标数值或分析,均归入此类。不包含风险预警(生态系数/预警)和二手业务指标。"
- name: "组织与调度"
domain: "组织与调度"
embed_text: "驻店人员, 驻点人员, 调度, 到店谈客, 兜底目标, 人员安排建议, 排班, 驻店零售, 人员清单, 员工清单, 员工姓名, 谁在驻店, 调谁去, 排班表"
tree_text: "用户查询人员清单(不带业绩数值)、排班、调度建议、到店安排等。核心对象是“人”而非指标。如果用户问及人员的业绩(如触客数、成交率),则自动归入「经营指标分析」。"
- name: "风险预警分析"
domain: "风险预警"
embed_text: "生态系数预警, 预警门店, 风险预警, 指标预警, 生态系数, 预警对比, 风险排序"
tree_text: "用户想查看风险/预警门店清单(如生态系数预警)并进行对比、排序或原因分析。"
- name: "报表查看"
domain: "报表与复盘"
embed_text: "周报, 月报, 日报, 业绩周报, 展业周报, 报表查看, 复盘报告"
tree_text: "用户想查看或获取某类周期性报表(周报/月报等)或复盘信息。"
- name: "二手业务分析"
domain: "二手业务"
embed_text: "二手, 二手车, 收车数, 收车成本, 收车走势, 收车环比, 收车同比, 收车排名, 收车Top门店, 二手收车, 二手车毛利, 毛利率, 毛利环比, 毛利同比, 二手车盈利, 利润分析"
tree_text: "用户想查询或分析二手业务指标(收车/毛利/利润等),包括趋势、环比同比、排名或对比分析。"
- name: "其他查询"
domain: "其他"
embed_text: "你好, 在吗, 谢谢, 哈哈, 你是谁, 你能做什么, 帮助, 随便聊聊, 闲聊, 隐私, 权限, 数据来源, 系统提示词, 安全策略, 内部接口, 公司股价, 午餐推荐, 深圳火锅推荐, 政治, 历史事件, 社会热点, 政府, 执政, 党史, 毛泽东, 天安门, 六四, 法轮功"
tree_text: "用户提出与业务指标/报表/门店/经营分析无关的问题或内容:闲聊、打招呼、表达情绪、问你是谁/能做什么、询问隐私/权限/数据来源/系统规则、以及政治历史社会等非业务话题。"
\ No newline at end of file \ No newline at end of file
intents:
- name: "门店运营分析"
domain: "门店运营"
embed_text: "门店数量统计, 门店列表, 查询门店"
tree_text: "用户仅查询门店实体本身的基础信息"
\ No newline at end of file \ No newline at end of file
intents:
- name: "门店运营分析"
domain: "门店运营"
embed_text: "门店数量统计, 门店列表, 查询门店"
tree_text: "用户仅查询门店实体本身的基础信息"
\ No newline at end of file \ No newline at end of file
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Intent Fusion Demo</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Plus+Jakarta+Sans:wght@500;600;700;800&display=swap" rel="stylesheet" />
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
{
"name": "intent-fusion-web",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc -p tsconfig.json --noEmit && vite build",
"preview": "vite preview"
},
"dependencies": {
"element-plus": "^2.10.4",
"pinia": "^3.0.3",
"vue": "^3.5.17",
"vue-router": "^4.5.1"
},
"devDependencies": {
"@vitejs/plugin-vue": "^6.0.0",
"typescript": "^5.8.3",
"vite": "^7.0.0",
"vue-tsc": "^2.1.6"
}
}
<template>
<el-container class="app-shell">
<el-header height="64px" class="app-header">
<div class="app-header-left">
<div class="app-logo">
<div class="logo-box">IF</div>
</div>
<div class="app-title-group">
<span class="app-title">Intent Fusion</span>
<span class="app-subtitle">SaaS Dual-Channel Routing Engine</span>
</div>
</div>
<div class="app-actions">
<el-button class="action-btn upload-btn" @click="showUploadDialog = true">
<el-icon class="btn-icon"><Upload /></el-icon>
<span>上传意图类别</span>
</el-button>
<el-button class="action-btn refresh-btn" @click="catalog.refresh" :loading="catalog.loading">
<el-icon class="btn-icon" v-if="!catalog.loading"><Refresh /></el-icon>
<span>刷新意图</span>
</el-button>
<el-button class="action-btn clear-btn" @click="chat.clear" :disabled="chat.messages.length === 0">
<el-icon class="btn-icon"><Delete /></el-icon>
<span>清空对话</span>
</el-button>
</div>
</el-header>
<el-main class="app-main">
<router-view />
</el-main>
<!-- 上传自定义意图类别对话框 -->
<el-dialog
v-model="showUploadDialog"
title="上传自定义意图类别"
width="460px"
destroy-on-close
class="custom-dialog"
>
<div class="dialog-body-desc">
上传你的 <code>intents.yaml</code> 意图配置文件。系统会自动编译对应的 Embedding 向量索引并建立多级大模型推理树。
</div>
<el-form label-position="top">
<el-form-item label="意图类别标识 (唯一ID,如 glsx_json)" required>
<el-input
v-model="uploadName"
placeholder="如: glsx_json"
class="custom-input"
/>
</el-form-item>
<el-form-item label="选择 YAML 意图配置文件 (intents.yaml)" required>
<div class="file-upload-wrapper">
<input type="file" accept=".yaml,.yml" @change="onFileChange" class="hidden-file-input" id="yaml-file-input" />
<label for="yaml-file-input" class="file-upload-label">
<el-icon class="upload-icon"><Document /></el-icon>
<span class="upload-text">{{ uploadFile ? uploadFile.name : '点击选择 intents.yaml 文件' }}</span>
</label>
</div>
</el-form-item>
</el-form>
<template #footer>
<div class="dialog-footer">
<el-button class="dialog-btn cancel-btn" @click="showUploadDialog = false">取消</el-button>
<el-button
class="dialog-btn submit-btn"
type="primary"
:loading="uploading"
:disabled="!uploadName || !uploadFile"
@click="handleUpload"
>
上传并自动应用
</el-button>
</div>
</template>
</el-dialog>
</el-container>
</template>
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useCatalogStore } from "./stores/catalog";
import { useChatStore } from "./stores/chat";
import { ElMessage } from "element-plus";
import { Upload, Refresh, Delete, Document } from "@element-plus/icons-vue";
const catalog = useCatalogStore();
const chat = useChatStore();
const showUploadDialog = ref(false);
const uploadName = ref("");
const uploadFile = ref<File | null>(null);
const uploading = ref(false);
function onFileChange(event: Event) {
const target = event.target as HTMLInputElement;
if (target.files && target.files.length > 0) {
uploadFile.value = target.files[0];
} else {
uploadFile.value = null;
}
}
async function handleUpload() {
const datasetName = uploadName.value.trim();
if (!datasetName || !uploadFile.value) return;
uploading.value = true;
try {
const reader = new FileReader();
reader.onload = async (e) => {
const yamlContent = e.target?.result as string;
try {
const response = await fetch("/api/intents/upload", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name: datasetName,
yaml_content: yamlContent,
}),
});
const resData = await response.json();
if (!response.ok) {
throw new Error(resData.error || `HTTP ${response.status}`);
}
ElMessage.success("上传成功!正在切换至新上传的意图类别...");
showUploadDialog.value = false;
// 刷新数据集列表
await catalog.refreshDatasets();
// 切换到新上传的类别(默认为 uploads/名称)
const datasetKey = resData.dataset || `uploads/${datasetName}`;
await catalog.switchDataset(datasetKey);
// 重置状态
uploadName.value = "";
uploadFile.value = null;
} catch (err: any) {
ElMessage.error(`上传失败: ${err.message || err}`);
} finally {
uploading.value = false;
}
};
reader.readAsText(uploadFile.value);
} catch (err: any) {
ElMessage.error(`读取文件失败: ${err.message || err}`);
uploading.value = false;
}
}
onMounted(() => {
catalog.refreshDatasets();
catalog.refresh();
});
</script>
<style scoped>
.app-shell {
height: 100%;
overflow: hidden;
font-family: 'Inter', system-ui, -apple-system, sans-serif;
background-color: #f8fafc;
}
.app-header {
display: flex;
align-items: center;
justify-content: space-between;
border-bottom: 1px solid rgba(226, 232, 240, 0.8);
background: rgba(255, 255, 255, 0.85);
backdrop-filter: blur(12px);
padding: 0 24px;
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.02);
}
.app-header-left {
display: flex;
align-items: center;
gap: 12px;
}
.app-logo {
display: flex;
align-items: center;
justify-content: center;
}
.logo-box {
width: 32px;
height: 32px;
background: linear-gradient(135deg, #4f46e5 0%, #3b82f6 100%);
color: white;
font-weight: 800;
font-size: 14px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(79, 70, 229, 0.25);
font-family: 'Plus Jakarta Sans', sans-serif;
}
.app-title-group {
display: flex;
flex-direction: column;
}
.app-title {
font-family: 'Plus Jakarta Sans', sans-serif;
font-weight: 800;
font-size: 16px;
color: #0f172a;
letter-spacing: -0.02em;
line-height: 1.2;
}
.app-subtitle {
font-size: 11px;
color: #64748b;
font-weight: 500;
}
.app-actions {
display: flex;
gap: 10px;
align-items: center;
}
.action-btn {
border-radius: 8px;
font-weight: 600;
font-size: 13px;
height: 36px;
padding: 0 16px;
display: inline-flex;
align-items: center;
gap: 6px;
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
border: 1px solid #e2e8f0;
background: #ffffff;
color: #334155;
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
}
.action-btn:hover {
border-color: #cbd5e1;
background: #f8fafc;
color: #0f172a;
transform: translateY(-1px);
}
.action-btn:active {
transform: translateY(0);
}
.upload-btn {
background: linear-gradient(135deg, #4f46e5 0%, #4338ca 100%);
border: none;
color: #ffffff;
box-shadow: 0 4px 12px rgba(79, 70, 229, 0.15);
}
.upload-btn:hover {
background: linear-gradient(135deg, #4338ca 0%, #3730a3 100%);
color: #ffffff;
border: none;
box-shadow: 0 6px 16px rgba(79, 70, 229, 0.25);
}
.clear-btn:disabled {
opacity: 0.5;
pointer-events: none;
box-shadow: none;
border-color: #f1f5f9;
background: #f8fafc;
}
.btn-icon {
font-size: 15px;
}
.app-main {
padding: 0;
overflow: hidden;
}
/* Dialog Stylings */
.dialog-body-desc {
font-size: 13px;
color: #64748b;
line-height: 1.5;
margin-bottom: 20px;
}
.dialog-body-desc code {
background-color: #f1f5f9;
color: #0f172a;
padding: 2px 4px;
border-radius: 4px;
font-size: 12px;
}
.custom-input :deep(.el-input__wrapper) {
border-radius: 8px;
padding: 8px 12px;
border: 1px solid #e2e8f0;
box-shadow: none !important;
transition: all 0.2s;
}
.custom-input :deep(.el-input__wrapper):hover,
.custom-input :deep(.el-input__wrapper.is-focus) {
border-color: #818cf8;
}
.file-upload-wrapper {
width: 100%;
}
.hidden-file-input {
display: none;
}
.file-upload-label {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
width: 100%;
height: 48px;
border: 2px dashed #cbd5e1;
border-radius: 8px;
cursor: pointer;
background-color: #f8fafc;
color: #64748b;
font-size: 13px;
font-weight: 500;
transition: all 0.2s;
}
.file-upload-label:hover {
border-color: #818cf8;
background-color: #f5f3ff;
color: #4f46e5;
}
.upload-icon {
font-size: 18px;
}
.dialog-footer {
display: flex;
justify-content: flex-end;
gap: 10px;
margin-top: 15px;
}
.dialog-btn {
height: 38px;
border-radius: 8px;
font-weight: 600;
font-size: 13px;
padding: 0 20px;
}
.submit-btn {
background: linear-gradient(135deg, #4f46e5 0%, #4338ca 100%);
border: none;
}
.submit-btn:hover {
background: linear-gradient(135deg, #4338ca 0%, #3730a3 100%);
}
.cancel-btn {
border: 1px solid #e2e8f0;
color: #475569;
}
.cancel-btn:hover {
background-color: #f8fafc;
color: #0f172a;
border-color: #cbd5e1;
}
</style>
export class HttpError extends Error {
status: number;
payload: unknown;
constructor(status: number, message: string, payload: unknown) {
super(message);
this.status = status;
this.payload = payload;
}
}
const API_BASE = "/api";
export async function requestJson<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(`${API_BASE}${path}`, {
...init,
headers: {
"Content-Type": "application/json",
...(init?.headers ?? {}),
},
});
const text = await res.text();
const payload = text ? safeJsonParse(text) : null;
if (!res.ok) {
const message =
typeof payload === "object" && payload && "error" in (payload as any)
? String((payload as any).error)
: `HTTP ${res.status}`;
throw new HttpError(res.status, message, payload);
}
return payload as T;
}
function safeJsonParse(text: string): unknown {
try {
return JSON.parse(text);
} catch {
return text;
}
}
import { requestJson } from "./http";
import type { CaseItem, DatasetItem, DatasetState, FuseResponse, IntentItem } from "../types";
export async function fetchIntents(): Promise<IntentItem[]> {
const res = await requestJson<{ items: IntentItem[] }>("/intents");
return res.items;
}
export async function fetchCases(): Promise<CaseItem[]> {
const res = await requestJson<{ items: CaseItem[] }>("/cases");
return res.items;
}
export async function fetchDatasets(): Promise<{ items: DatasetItem[]; current: DatasetState }> {
return requestJson<{ items: DatasetItem[]; current: DatasetState }>("/datasets");
}
export async function setDataset(key: string): Promise<{ ok: true; current: DatasetState }> {
return requestJson<{ ok: true; current: DatasetState }>("/dataset", {
method: "POST",
body: JSON.stringify({ key }),
});
}
export async function fuseIntent(message: string): Promise<FuseResponse> {
return requestJson<FuseResponse>("/fuse", {
method: "POST",
body: JSON.stringify({ message }),
});
}
<template>
<div class="wrap">
<el-input
v-model="text"
type="textarea"
:autosize="{ minRows: 2, maxRows: 5 }"
placeholder="输入要测试的用户话术,例如:我想退货"
@keydown.enter.exact.prevent="onEnter"
@keydown.enter.shift.exact.stop
/>
<div class="actions">
<el-button type="primary" :loading="sending" :disabled="!canSend" @click="emitSend">
发送
</el-button>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from "vue";
const props = defineProps<{ sending: boolean; modelValue: string }>();
const emit = defineEmits<{
(e: "send", text: string): void;
(e: "update:modelValue", v: string): void;
}>();
const text = computed({
get: () => props.modelValue,
set: (v: string) => emit("update:modelValue", v),
});
const canSend = computed(() => text.value.trim().length > 0 && !props.sending);
function emitSend(): void {
const value = text.value.trim();
if (!value || props.sending) return;
emit("send", value);
emit("update:modelValue", "");
}
function onEnter(): void {
emitSend();
}
</script>
<style scoped>
.wrap {
display: grid;
grid-template-columns: 1fr 92px;
gap: 10px;
align-items: end;
}
.actions {
display: flex;
justify-content: flex-end;
}
</style>
<template>
<div ref="root" class="list">
<div class="stream">
<div v-if="messages.length === 0" class="empty">
输入一句话,点击发送,左侧显示融合结果,右侧可浏览意图与示例。
</div>
<div v-for="m in messages" :key="m.id" class="row" :class="m.role">
<div class="bubble">
<div class="meta">
<span class="role">{{ m.role === "user" ? "你" : "系统" }}</span>
<span class="time">{{ formatTime(m.createdAt) }}</span>
</div>
<pre class="content">{{ m.content }}</pre>
<div v-if="m.role === 'assistant'" class="result-card">
<div class="badges">
<el-tag :type="tagType(m.result.verdict)" effect="dark" class="badge">{{ m.result.verdict }}</el-tag>
<el-tag v-if="m.result.degraded" type="warning" effect="light" class="badge">DEGRADED</el-tag>
<el-tag v-for="c in m.result.active_channels" :key="c" type="info" effect="light" class="badge">
{{ c }}
</el-tag>
</div>
<div class="kpis">
<div class="kpi">
<div class="kpi-label">Top Intent</div>
<div class="kpi-value mono">{{ resolvedName(m) }}</div>
</div>
<div class="kpi">
<div class="kpi-label">Score</div>
<div class="kpi-value">
{{ resolvedScore(m) }}
</div>
<div class="mini">
<div class="mini-track">
<div class="mini-bar" :style="{ width: scorePct(m) + '%' }" />
</div>
</div>
</div>
<div class="kpi">
<div class="kpi-label">Timing</div>
<div class="kpi-value">{{ Math.round(m.result.timing_ms.total) }}ms</div>
<div class="mini">
<div class="mini-track">
<div class="mini-bar emb" :style="{ width: timingPct(m, 'emb') + '%' }" />
<div class="mini-bar tree" :style="{ width: timingPct(m, 'tree') + '%' }" />
</div>
<div class="mini-meta">
emb={{ Math.round(m.result.timing_ms.emb) }}ms · tree={{ Math.round(m.result.timing_ms.tree) }}ms
</div>
</div>
</div>
</div>
<div v-if="m.result.candidates.length" class="cand">
<div class="cand-head">
<span>候选意图</span>
<span class="muted">final</span>
<span class="muted">emb</span>
<span class="muted">tree</span>
<span class="muted">ch</span>
</div>
<div
v-for="(c, idx) in m.result.candidates"
:key="c.name"
class="cand-row"
:class="{ top: idx === 0 }"
>
<div class="cand-name mono">{{ c.name }}</div>
<div class="cand-num">{{ c.final_score.toFixed(3) }}</div>
<div class="cand-num muted">{{ c.emb_score.toFixed(3) }}</div>
<div class="cand-num muted">{{ c.tree_score.toFixed(3) }}</div>
<div class="cand-ch muted">{{ (c.in_emb ? "E" : "") + (c.in_tree ? "T" : "") }}</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { nextTick, onMounted, ref, watch } from "vue";
import type { ChatMessage, FusionVerdict } from "../../types";
const props = defineProps<{ messages: ChatMessage[] }>();
const root = ref<HTMLElement | null>(null);
function formatTime(ts: number): string {
return new Date(ts).toLocaleTimeString();
}
function tagType(v: FusionVerdict): "success" | "warning" | "info" | "danger" {
if (v === "clear") return "success";
if (v === "ambiguous") return "warning";
if (v === "low") return "info";
return "info";
}
function scorePct(m: ChatMessage): number {
if (m.role !== "assistant") return 0;
const v = resolvedScoreValue(m);
return Math.max(0, Math.min(100, Math.round(v * 100)));
}
function timingPct(m: ChatMessage, k: "emb" | "tree"): number {
if (m.role !== "assistant") return 0;
const total = Math.max(1, m.result.timing_ms.total);
const v = k === "emb" ? m.result.timing_ms.emb : m.result.timing_ms.tree;
return Math.max(0, Math.min(100, Math.round((v / total) * 100)));
}
function resolvedName(m: ChatMessage): string {
if (m.role !== "assistant") return "—";
const intents = m.result.resolved?.intents ?? [];
if (intents.length > 0) return intents.map((x) => x.name).join(" | ");
return m.result.top?.name ?? "—";
}
function resolvedScoreValue(m: ChatMessage): number {
if (m.role !== "assistant") return 0;
const intents = m.result.resolved?.intents ?? [];
if (intents.length === 1) return intents[0].score ?? 0;
if (intents.length > 1) return Math.max(...intents.map((x) => x.score ?? 0));
return m.result.top?.final_score ?? 0;
}
function resolvedScore(m: ChatMessage): string {
if (m.role !== "assistant") return "—";
const intents = m.result.resolved?.intents ?? [];
if (intents.length === 0) return m.result.top ? m.result.top.final_score.toFixed(3) : "—";
if (intents.length === 1) return (intents[0].score ?? 0).toFixed(3);
return resolvedScoreValue(m).toFixed(3);
}
async function scrollToBottom(): Promise<void> {
await nextTick();
const el = root.value;
if (!el) return;
el.scrollTop = el.scrollHeight;
}
onMounted(scrollToBottom);
watch(
() => props.messages.length,
() => {
scrollToBottom();
}
);
</script>
<style scoped>
.list {
flex: 1;
overflow: auto;
padding: 14px 16px 12px;
}
.stream {
width: min(980px, 100%);
margin: 0 auto;
}
.empty {
padding: 24px;
color: var(--el-text-color-secondary);
border: 1px dashed rgba(16, 24, 40, 0.08);
border-radius: 14px;
background: rgba(255, 255, 255, 0.55);
backdrop-filter: blur(10px);
}
.row {
display: flex;
margin: 12px 0;
}
.row.user {
justify-content: flex-end;
}
.row.assistant {
justify-content: flex-start;
}
.bubble {
max-width: min(860px, 100%);
border-radius: 16px;
padding: 12px 14px;
background: rgba(255, 255, 255, 0.62);
border: 1px solid rgba(16, 24, 40, 0.08);
box-shadow:
0 16px 40px rgba(15, 23, 42, 0.08),
0 2px 10px rgba(15, 23, 42, 0.05);
backdrop-filter: blur(14px);
}
.row.user .bubble {
background: linear-gradient(180deg, rgba(16, 24, 40, 0.92), rgba(16, 24, 40, 0.86));
border-color: rgba(16, 24, 40, 0.25);
box-shadow:
0 18px 50px rgba(2, 6, 23, 0.22),
0 2px 10px rgba(2, 6, 23, 0.10);
backdrop-filter: blur(14px);
}
.meta {
display: flex;
gap: 10px;
color: var(--el-text-color-secondary);
font-size: 12px;
margin-bottom: 6px;
}
.row.user .meta {
color: rgba(255, 255, 255, 0.72);
}
.content {
margin: 0;
white-space: pre-wrap;
word-break: break-word;
font-size: 14px;
line-height: 1.5;
color: var(--el-text-color-primary);
}
.row.user .content {
color: rgba(255, 255, 255, 0.92);
}
.mono {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
}
.muted {
color: var(--el-text-color-secondary);
}
.result {
margin-top: 10px;
}
.result-card {
margin-top: 12px;
border-radius: 14px;
padding: 12px;
background: rgba(244, 246, 249, 0.68);
border: 1px solid rgba(16, 24, 40, 0.08);
box-shadow:
0 12px 34px rgba(15, 23, 42, 0.07),
inset 0 1px 0 rgba(255, 255, 255, 0.6);
}
.badges {
display: flex;
gap: 8px;
flex-wrap: wrap;
margin-bottom: 12px;
}
.badge {
border-radius: 999px;
}
.kpis {
display: grid;
grid-template-columns: 1.3fr 1fr 1fr;
gap: 10px;
}
.kpi {
border-radius: 12px;
padding: 10px 10px 8px;
background: rgba(255, 255, 255, 0.64);
border: 1px solid rgba(16, 24, 40, 0.07);
}
.kpi-label {
font-size: 12px;
color: var(--el-text-color-secondary);
margin-bottom: 6px;
}
.kpi-value {
font-size: 20px;
font-weight: 800;
letter-spacing: -0.01em;
color: rgba(15, 23, 42, 0.92);
line-height: 1.1;
}
.mini {
margin-top: 8px;
}
.mini-track {
width: 100%;
height: 6px;
border-radius: 999px;
background: rgba(15, 23, 42, 0.08);
overflow: hidden;
display: flex;
gap: 4px;
}
.mini-bar {
height: 100%;
border-radius: 999px;
background: rgba(128, 163, 143, 0.95);
}
.mini-bar.emb {
background: rgba(30, 58, 138, 0.72);
}
.mini-bar.tree {
background: rgba(128, 163, 143, 0.88);
}
.mini-meta {
margin-top: 6px;
font-size: 12px;
color: var(--el-text-color-secondary);
}
.cand {
margin-top: 12px;
}
.cand-head {
display: grid;
grid-template-columns: 1fr 72px 72px 72px 54px;
gap: 8px;
font-size: 12px;
color: rgba(15, 23, 42, 0.55);
padding: 0 8px 6px;
}
.cand-row {
display: grid;
grid-template-columns: 1fr 72px 72px 72px 54px;
gap: 8px;
align-items: center;
padding: 10px 8px;
border-radius: 12px;
background: rgba(255, 255, 255, 0.52);
border: 1px solid rgba(16, 24, 40, 0.06);
margin-top: 8px;
}
.cand-row.top {
background: rgba(128, 163, 143, 0.16);
border-color: rgba(128, 163, 143, 0.22);
}
.cand-name {
overflow: hidden;
text-overflow: ellipsis;
}
.cand-num,
.cand-ch {
text-align: right;
font-variant-numeric: tabular-nums;
}
</style>
<template>
<el-card shadow="never" class="detail">
<template #header>
<div class="h">
<div class="name">{{ intent.name }}</div>
<el-tag type="info" effect="light">{{ intent.domain }}</el-tag>
</div>
</template>
<div class="section">
<div class="k">tree_text</div>
<div class="v">{{ intent.tree_text }}</div>
</div>
<div class="section">
<div class="k">embed_text</div>
<div class="v mono">{{ intent.embed_text }}</div>
</div>
<div class="section">
<div class="k">示例</div>
<div class="chips">
<el-tag
v-for="ex in intent.examples"
:key="ex"
effect="plain"
type="info"
class="chip"
@click="onUseExample(ex)"
>
{{ ex }}
</el-tag>
</div>
</div>
</el-card>
</template>
<script setup lang="ts">
import type { IntentItem } from "../../types";
defineProps<{ intent: IntentItem }>();
const emit = defineEmits<{ (e: "use-example", text: string): void }>();
function onUseExample(text: string): void {
emit("use-example", text);
}
</script>
<style scoped>
.detail {
border-radius: 12px;
}
.h {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.name {
font-weight: 700;
overflow: hidden;
text-overflow: ellipsis;
}
.section {
margin: 10px 0;
}
.k {
color: var(--el-text-color-secondary);
margin-bottom: 4px;
}
.v {
color: var(--el-text-color-primary);
white-space: pre-wrap;
word-break: break-word;
}
.mono {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
}
.chips {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.chip {
max-width: 100%;
cursor: pointer;
}
</style>
<template>
<el-card class="panel" shadow="never">
<template #header>
<div class="header">
<div class="title">意图与示例</div>
<div class="header-right">
<el-select
v-model="selectedDatasetKey"
size="small"
class="dataset"
:loading="catalog.datasetLoading"
placeholder="选择数据集"
@change="onDatasetChange"
>
<el-option v-for="d in catalog.datasets" :key="d.key" :label="d.label" :value="d.key" />
</el-select>
<el-tag v-if="catalog.loading" type="info" effect="light">loading</el-tag>
<el-tag v-else type="success" effect="light">{{ catalog.intents.length }} intents</el-tag>
</div>
</div>
</template>
<el-tabs v-model="tab">
<el-tab-pane label="意图列表" name="intents">
<el-input v-model="q" placeholder="搜索意图 / 域 / 关键词" clearable />
<div v-if="catalog.error" class="error">{{ catalog.error }}</div>
<div class="intents">
<el-collapse v-model="openDomains">
<el-collapse-item
v-for="d in filteredDomains"
:key="d.domain"
:title="d.domain"
:name="d.domain"
>
<el-menu :default-active="selectedIntentName" class="menu" @select="onSelectIntent">
<el-menu-item v-for="i in d.items" :key="i.name" :index="i.name">
<div class="menu-item">
<span class="name">{{ i.name }}</span>
<span class="count">{{ i.examples.length }}</span>
</div>
</el-menu-item>
</el-menu>
</el-collapse-item>
</el-collapse>
</div>
<el-drawer v-model="detailOpen" size="420px" append-to-body="false">
<IntentDetail v-if="selectedIntent" :intent="selectedIntent" @use-example="onUseExample" />
<div v-else class="empty">选择一个意图查看详情</div>
</el-drawer>
</el-tab-pane>
<el-tab-pane label="用例集" name="cases">
<el-input v-model="caseQ" placeholder="搜索用例文本" clearable />
<el-table :data="filteredCases" size="small" height="520" border>
<el-table-column prop="message" label="message" min-width="220" show-overflow-tooltip />
<el-table-column prop="expected_intent" label="expected" width="160" show-overflow-tooltip />
</el-table>
</el-tab-pane>
</el-tabs>
</el-card>
</template>
<script setup lang="ts">
import { computed, ref, watchEffect } from "vue";
import { useCatalogStore } from "../../stores/catalog";
import IntentDetail from "./IntentDetail.vue";
const emit = defineEmits<{ (e: "use-example", text: string): void }>();
const catalog = useCatalogStore();
const tab = ref<"intents" | "cases">("intents");
const q = ref("");
const caseQ = ref("");
const selectedIntentName = ref<string>("");
const openDomains = ref<string[]>([]);
const detailOpen = ref(false);
const selectedDatasetKey = ref("");
watchEffect(() => {
if (!selectedDatasetKey.value && catalog.datasetKey) {
selectedDatasetKey.value = catalog.datasetKey;
}
if (openDomains.value.length === 0 && catalog.domains.length > 0) {
openDomains.value = catalog.domains.slice(0, 3).map((d) => d.domain);
}
if (!selectedIntentName.value && catalog.intents.length > 0) {
selectedIntentName.value = catalog.intents[0].name;
}
});
watchEffect(() => {
if (catalog.datasets.length === 0 && !catalog.datasetLoading) {
catalog.refreshDatasets();
}
});
function onSelectIntent(name: string): void {
selectedIntentName.value = name;
detailOpen.value = true;
}
async function onDatasetChange(key: string): Promise<void> {
await catalog.switchDataset(key);
openDomains.value = [];
selectedIntentName.value = "";
detailOpen.value = false;
}
const filteredDomains = computed(() => {
const needle = q.value.trim().toLowerCase();
if (!needle) return catalog.domains;
return catalog.domains
.map((d) => ({
domain: d.domain,
items: d.items.filter((i) => {
const hay = `${i.domain} ${i.name} ${i.embed_text} ${i.tree_text}`.toLowerCase();
return hay.includes(needle);
}),
}))
.filter((d) => d.items.length > 0);
});
const selectedIntent = computed(() => catalog.intents.find((i) => i.name === selectedIntentName.value) ?? null);
function onUseExample(text: string): void {
emit("use-example", text);
}
const filteredCases = computed(() => {
const needle = caseQ.value.trim().toLowerCase();
if (!needle) return catalog.cases;
return catalog.cases.filter((c) => c.message.toLowerCase().includes(needle));
});
</script>
<style scoped>
.panel {
height: 100%;
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
}
.title {
font-weight: 600;
}
.header-right {
display: flex;
align-items: center;
gap: 8px;
}
.dataset {
width: 180px;
}
.error {
margin-top: 10px;
color: var(--el-color-danger);
}
.intents {
margin-top: 10px;
}
.menu {
border-right: none;
}
.menu-item {
width: 100%;
display: flex;
justify-content: space-between;
gap: 10px;
}
.name {
overflow: hidden;
text-overflow: ellipsis;
}
.count {
color: var(--el-text-color-secondary);
}
.empty {
padding: 14px;
border: 1px dashed var(--el-border-color);
border-radius: 10px;
color: var(--el-text-color-secondary);
}
:deep(.el-drawer__body) {
padding: 0;
}
:deep(.el-drawer__header) {
margin-bottom: 0;
}
</style>
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!