Commit 89675fd6 by Liyuan

Initial commit: HybridIntentResolutionFramework - Multi-signal intent fusion lib…

…rary with calibration, routing, and tree-based parsing.

Made-with: Cursor
0 parents
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10", "3.11", "3.12"]
steps:
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -e ".[dev]"
- name: Run tests
run: pytest tests/ -v
__pycache__/
*.py[cod]
*$py.class
*.egg-info/
dist/
build/
*.egg
.eggs/
.pytest_cache/
.mypy_cache/
.ruff_cache/
htmlcov/
.coverage
*.csv
calibration_results.csv
.env
.venv/
venv/
env/
.idea/
.vscode/
*.swp
*.swo
*~
*.DS_Store
Thumbs.db
# 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
MIT License
Copyright (c) 2024-present intent-fusion contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# 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
# intent-fusion
[English](README.md) | [中文](#intent-fusion)
**经过生产验证的双通道意图识别:Embedding 召回 + LLM 意图树推理。**
一个 Python 库,并行运行两个互补的意图分类通道——快速 embedding 相似度匹配和 LLM 层级推理——然后将两路结果融合为带分数的三态判决。来自真实 SaaS 系统的生产验证,不是实验室原型。
## 生产数据
在生产环境零售管理 SaaS 上评估 —— 57 个意图、7 个业务域、140 条标注路由用例。
**单模型基线**(3 个 LLM,104 条用例):
| 模型 | 准确率 | 平均延迟 |
|------|--------|---------|
| 模型 A(快速) | 80.8% | 2.2s |
| 模型 B(均衡) | 82.7% | 6.0s |
| 模型 C(强力) | 86.5% | 15.1s |
单模型没有一个突破 87%。**双通道融合**基于最快模型(140 条用例,扩展回归):
| 指标 | 最佳单模型 | 双通道融合 |
|------|-----------|-----------|
| **整体准确率** | 86.5% (90/104) | **97.1% (136/140)** |
| 分析报表域 | 47–87% | 100% |
| 剩余失败 | 14–20 条 | 4 条(全部是上下文指代词) |
剩余 4 条失败全部包含「那个」「这个」等指代词,需要多轮对话上下文才能正确理解——这是对话管理层的职责,不是意图识别层的问题。
→ [完整评估报告与跨模型失败分析](benchmarks/README.md)
## 为什么需要双通道?
| 用户说 | 纯 Embedding | 纯 LLM | 融合 |
|--------|-------------|--------|------|
| "取消订单" | cancel_order | cancel_order | cancel_order |
| "我不想要了" | ??? | cancel_order | cancel_order |
| "今天店里怎么样" | query_revenue(错) | daily_report | daily_report |
| "什么卖得最好" | query_product(错) | hot_selling | hot_selling |
- **Embedding** 速度快,关键词匹配好,但在间接表达上失败
- **LLM 意图树推理** 擅长语义推理,但更慢且可能幻觉出不存在的意图名
- **融合** 结合两者:embedding 扩大召回面,tree 推理提供精确度
## 架构
```
用户消息
│
├──────────────────┬──────────────────┐
│ │ │
┌───▼──────┐ ┌──────▼───────┐ │
│ Embedding │ │ 意图树推理 │ 并行执行
│ 通道 │ │ 通道 │ │
│ (5-15ms) │ │ (LLM 调用) │ │
└───┬──────┘ └──────┬───────┘ │
│ │ │
└────────┬─────────┘──────────────────┘
│
┌──────▼──────┐
│ 融合评分 │ final = α·emb + (1-α)·tree
└──────┬──────┘
│
┌──────▼──────┐
│ 三态判决 │ CLEAR / AMBIGUOUS / LOW
└─────────────┘
```
## 快速开始
```bash
pip install intent-fusion
```
```python
from intent_fusion import IntentRouter, IntentEntry, FusionVerdict
# 定义意图,每个通道使用独立的文本描述
entries = [
IntentEntry(
name="query_order_status",
domain="订单管理",
embed_text="查订单, 物流状态, 我的包裹到哪了, 快递查询",
tree_text="用户想知道订单当前状态、物流进度或预计送达时间",
),
IntentEntry(
name="cancel_order",
domain="订单管理",
embed_text="取消订单, 不想要了, 退订, 取消购买",
tree_text="用户想取消一个已下的订单",
),
# ... 更多意图
]
# 创建路由器(embedding 模型只加载一次)
router = IntentRouter(entries)
# 任何有 async chat() 方法的 LLM 都可以
result = await router.fuse("我不想要了", 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) # 展示备选
case FusionVerdict.LOW:
fallback_to_free_chat()
```
## 核心概念
### IntentEntry:一个意图,两段文本
每个意图拥有为各通道独立优化的描述:
```python
IntentEntry(
name="hot_selling",
domain="报表分析",
embed_text="热销排行, 卖得最好, 畅销商品, 什么卖得多, 爆款",
tree_text="用户想看商品销量排行。区分:查营业额→query_revenue;查商品详情→query_product",
)
```
- **`embed_text`**:关键词密集,同义词丰富。喂给 embedding 模型的是用户实际会说的话。
- **`tree_text`**:描述性强,含消歧提示。告诉 LLM 这个意图是什么,*以及不是什么*。
### LLMProvider 协议
任何有 async `chat()` 方法的对象都可以:
```python
class YourLLM:
async def chat(self, messages: list[dict[str, str]], **kwargs) -> str:
# 调用 OpenAI、DeepSeek、通义千问、Ollama 或任意 Provider
...
```
`examples/` 中包含了一个 OpenAI 兼容的适配器。
### 三态判决
| 判决 | 含义 | 建议动作 |
|------|------|---------|
| `CLEAR` | Top 候选明显领先 | 直接路由执行 |
| `AMBIGUOUS` | Top-2 得分接近 | 执行 Top,附带备选建议 |
| `LOW` | 没有置信匹配 | 降级到闲聊 / 引导搜索 |
### 单通道降级
如果 LLM 不可用,embedding 通道仍然工作(反之亦然):
```python
result = await router.fuse(message, llm)
if result.degraded:
print(f"当前运行在 {result.active_channels} 通道")
```
## 参数标定
为你的意图集找到最优的 `alpha` 和 `delta`:
```bash
python -m intent_fusion.calibration \
--cases your_cases.yaml \
--intents your_intents.yaml
# 输出: Best alpha=0.10, delta=0.10 → accuracy=0.971 (101/104)
```
详见 [docs/calibration.md](docs/calibration.md)。
## 基准测试
包含两个数据集:
| 数据集 | 意图数 | 用例数 | 来源 |
|--------|--------|--------|------|
| `ecommerce/` | 10 | 20 | 合成数据 |
| `petstore/` | 15 | 52 | 生产环境(脱敏) |
```bash
export OPENAI_API_KEY=sk-...
python benchmarks/petstore/run_benchmark.py
```
详见 [benchmarks/README.md](benchmarks/README.md)。
## 文档
- [架构设计](docs/architecture.md) — 双通道原理、融合公式、三态判决逻辑
- [管道集成指南](docs/pipeline-integration.md) — 如何集成到生产系统中
- [标定指南](docs/calibration.md) — 为你的数据找到最优参数
## API 参考
### 类 API(推荐)
```python
router = IntentRouter(entries, model_name="BAAI/bge-small-en-v1.5")
router.build_index() # 可选:启动时预热
result = await router.fuse(message, llm, alpha=0.10, delta=0.10)
```
### 函数 API(便捷)
```python
from intent_fusion import fuse_intent, build_index, invalidate_cache
build_index(entries) # 可选预热
result = await fuse_intent(message, entries, llm)
invalidate_cache() # 更新意图后调用
```
## 许可证
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"
"""Run the e-commerce benchmark.
Usage:
export OPENAI_API_KEY=sk-...
python benchmarks/ecommerce/run_benchmark.py
"""
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="E-commerce 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
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
mark = "OK" if is_correct else "FAIL"
print(f" [{mark}] {case.message:<45} expected={case.expected_intent:<25} got={predicted}")
accuracy = correct / len(cases) if cases else 0
print(f"\nResult: {correct}/{len(cases)} ({accuracy:.1%})")
if __name__ == "__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())
# 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).
File mode changed
# 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 ""
"""intent-fusion: Dual-channel intent recognition via Embedding + LLM Tree Reasoning.
Two ways to use:
# 1. Function API (simple, module-level singleton)
from intent_fusion import fuse_intent, FusionResult, FusionVerdict
result = await fuse_intent("where is my order", entries, llm)
# 2. Class API (multi-instance, explicit lifecycle)
from intent_fusion import IntentRouter
router = IntentRouter(entries)
result = await router.fuse("where is my order", llm)
"""
from intent_fusion.fusion import build_index, fuse_intent, invalidate_cache
from intent_fusion.router import IntentRouter
from intent_fusion.tree import LLMProvider
from intent_fusion.types import (
FusedCandidate,
FusionResult,
FusionVerdict,
IntentEntry,
)
__all__ = [
"IntentRouter",
"LLMProvider",
"build_index",
"fuse_intent",
"invalidate_cache",
"FusedCandidate",
"FusionResult",
"FusionVerdict",
"IntentEntry",
]
__version__ = "0.1.0"
"""Offline calibration tool for alpha and delta parameters.
Runs a grid search over (alpha, delta) pairs on a labeled dataset to find
the combination that maximizes routing accuracy.
Usage:
python -m intent_fusion.calibration \\
--cases examples/ecommerce/cases.yaml \\
--intents examples/ecommerce/intents.yaml
Output:
Best alpha=0.10, delta=0.10 -> accuracy=0.923 (96/104 correct)
Full grid saved to calibration_results.csv
"""
from __future__ import annotations
import asyncio
import csv
import itertools
import logging
from dataclasses import dataclass
from pathlib import Path
from typing import Any
logger = logging.getLogger(__name__)
@dataclass
class CalibrationCase:
"""A single labeled test case."""
message: str
expected_intent: str
note: str = ""
@dataclass
class GridPoint:
alpha: float
delta: float
accuracy: float
correct: int
total: int
ambiguous_count: int
low_count: int
def load_cases_from_yaml(path: str | Path) -> list[CalibrationCase]:
"""Load labeled cases from a YAML file.
Expected format::
cases:
- message: "where is my order"
expected: "query_order_status"
- message: "I want to return this"
expected: "initiate_return"
note: "return flow entry point"
"""
import yaml
with open(path, encoding="utf-8") as f:
data = yaml.safe_load(f)
return [
CalibrationCase(
message=c["message"],
expected_intent=c["expected"],
note=c.get("note", ""),
)
for c in data.get("cases", [])
]
def load_intents_from_yaml(path: str | Path) -> list[Any]:
"""Load IntentEntry objects from a YAML file.
Expected format::
intents:
- name: query_order_status
domain: Order Management
embed_text: "track order, shipping status"
tree_text: "user wants to know where their order is"
"""
import yaml
from intent_fusion.types import IntentEntry
with open(path, encoding="utf-8") as f:
data = yaml.safe_load(f)
return [
IntentEntry(
name=item["name"],
domain=item["domain"],
embed_text=item["embed_text"],
tree_text=item.get("tree_text", ""),
)
for item in data.get("intents", [])
]
async def run_grid_search(
cases: list[CalibrationCase],
entries: list[Any],
llm: Any,
*,
alpha_values: list[float] | None = None,
delta_values: list[float] | None = None,
output_csv: str | Path | None = None,
) -> GridPoint:
"""Run grid search over (alpha, delta) and return the best configuration.
Args:
cases: Labeled test cases.
entries: IntentEntry list (same as used in production).
llm: LLM provider.
alpha_values: Alpha candidates to try. Default: [0.0, 0.05, 0.1, 0.2, 0.3, 0.5].
delta_values: Delta candidates to try. Default: [0.05, 0.10, 0.15, 0.20, 0.25].
output_csv: Optional path to save full grid results.
Returns:
GridPoint with the best (alpha, delta) combination.
"""
if alpha_values is None:
alpha_values = [0.0, 0.05, 0.10, 0.20, 0.30, 0.50]
if delta_values is None:
delta_values = [0.05, 0.10, 0.15, 0.20, 0.25]
from intent_fusion.router import IntentRouter
from intent_fusion.types import FusionVerdict
results: list[GridPoint] = []
for alpha, delta in itertools.product(alpha_values, delta_values):
router = IntentRouter(entries)
correct = 0
ambiguous_count = 0
low_count = 0
tasks = [
router.fuse(c.message, llm, alpha=alpha, delta=delta)
for c in cases
]
fusion_results = await asyncio.gather(*tasks)
for case, result in zip(cases, fusion_results):
if result.verdict == FusionVerdict.LOW:
low_count += 1
if case.expected_intent in ("free_chat", "guide_search", "orchestrate"):
correct += 1
elif result.verdict == FusionVerdict.AMBIGUOUS:
ambiguous_count += 1
if result.top and result.top.name == case.expected_intent:
correct += 1
else:
if result.top and result.top.name == case.expected_intent:
correct += 1
accuracy = correct / len(cases) if cases else 0.0
point = GridPoint(
alpha=alpha, delta=delta,
accuracy=accuracy, correct=correct, total=len(cases),
ambiguous_count=ambiguous_count, low_count=low_count,
)
results.append(point)
logger.info(
"calibration: alpha=%.2f delta=%.2f accuracy=%.3f (%d/%d) "
"ambiguous=%d low=%d",
alpha, delta, accuracy, correct, len(cases),
ambiguous_count, low_count,
)
best = max(results, key=lambda p: (p.accuracy, -p.ambiguous_count))
if output_csv:
_save_csv(results, output_csv)
logger.info("calibration: grid saved to %s", output_csv)
print(
f"\nBest: alpha={best.alpha:.2f}, delta={best.delta:.2f} "
f"-> accuracy={best.accuracy:.3f} ({best.correct}/{best.total})"
)
return best
def _save_csv(results: list[GridPoint], path: str | Path) -> None:
with open(path, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(
f,
fieldnames=["alpha", "delta", "accuracy", "correct", "total",
"ambiguous_count", "low_count"],
)
writer.writeheader()
for r in results:
writer.writerow({
"alpha": r.alpha, "delta": r.delta,
"accuracy": r.accuracy, "correct": r.correct, "total": r.total,
"ambiguous_count": r.ambiguous_count, "low_count": r.low_count,
})
# ── CLI entry point ──
def main() -> None:
import argparse
logging.basicConfig(level=logging.INFO, format="%(message)s")
parser = argparse.ArgumentParser(description="Calibrate intent-fusion alpha/delta")
parser.add_argument("--cases", required=True, help="Path to labeled cases YAML")
parser.add_argument("--intents", required=True, help="Path to intents YAML")
parser.add_argument("--output", default="calibration_results.csv")
parser.add_argument("--model", default=None, help="LLM model name override")
args = parser.parse_args()
entries = load_intents_from_yaml(args.intents)
cases = load_cases_from_yaml(args.cases)
from examples.ecommerce.llm_adapter import OpenAIAdapter
llm = OpenAIAdapter(model=args.model)
asyncio.run(run_grid_search(cases, entries, llm, output_csv=args.output))
if __name__ == "__main__":
main()
"""Function-style API for dual-channel intent fusion.
This module provides ``fuse_intent()`` and ``build_index()`` as convenient
top-level functions. They delegate to a module-level :class:`IntentRouter`
singleton so that simple use-cases need no explicit router construction.
For multi-instance scenarios (different intent sets in one process), use
:class:`intent_fusion.IntentRouter` directly.
"""
from __future__ import annotations
import logging
from typing import Any
from intent_fusion.router import ALPHA, DELTA, IntentRouter
from intent_fusion.tree import LLMProvider
from intent_fusion.types import FusionResult, FusionVerdict, IntentEntry
logger = logging.getLogger(__name__)
_default_router: IntentRouter | None = None
def build_index(entries: list[IntentEntry], *, model_name: str | None = None) -> None:
"""Pre-build the embedding index from intent entries.
Call this once at startup to avoid cold-start latency on the first request.
Safe to call multiple times — rebuilds the index each time (use for hot reload).
Args:
entries: The same list of IntentEntry objects you pass to fuse_intent().
model_name: Override the default sentence-transformer model name.
"""
global _default_router
kwargs: dict[str, Any] = {}
if model_name:
kwargs["model_name"] = model_name
_default_router = IntentRouter(entries, **kwargs)
_default_router.build_index()
def invalidate_cache() -> None:
"""Clear the default router (e.g. after updating intents)."""
global _default_router
_default_router = None
async def fuse_intent(
message: str,
entries: list[IntentEntry],
llm: LLMProvider,
*,
alpha: float = ALPHA,
delta: float = DELTA,
) -> FusionResult:
"""Dual-channel intent fusion (convenience function).
Runs embedding recall and LLM tree reasoning in parallel, merges candidates,
and returns a three-state verdict.
Delegates to a module-level :class:`IntentRouter`. For multi-instance use,
construct an ``IntentRouter`` directly.
Args:
message: User input string.
entries: List of IntentEntry objects defining your intent space.
llm: LLM provider implementing the LLMProvider protocol.
alpha: Embedding channel weight in [0, 1]. Default 0.10 (tree-dominant).
Increase if your embed_text descriptions are highly distinctive.
delta: Score gap threshold for CLEAR vs AMBIGUOUS. Default 0.10.
Increase for stricter routing (fewer CLEAR, more AMBIGUOUS).
Returns:
FusionResult with verdict, top candidate, runner-up, and timing info.
Example::
result = await fuse_intent("where is my order", entries, llm)
if result.verdict == FusionVerdict.CLEAR:
handle(result.top.name)
"""
global _default_router
if _default_router is None:
_default_router = IntentRouter(entries)
return await _default_router.fuse(message, llm, alpha=alpha, delta=delta)
"""IntentRouter — class-based dual-channel intent fusion.
Encapsulates embedding index and tree text cache as instance state,
enabling multiple routers with different intent sets in the same process.
Implements single-channel degradation: if one channel fails, the other
still produces a result (with degraded=True in FusionResult).
Architecture:
Layer 1 — Embedding Recall: fast cosine similarity, top-k candidates
Layer 2 — Intent Tree: LLM hierarchical reasoning, top-3 with scores
Layer 3 — Merge & Score: union of candidates, final_score = alpha * emb + (1-alpha) * tree
Layer 4 — Three-state Decide: CLEAR / AMBIGUOUS / LOW
"""
from __future__ import annotations
import asyncio
import logging
import time
from typing import Any
import numpy as np
from intent_fusion.tree import LLMProvider, build_intent_tree_text, reason_intent_tree
from intent_fusion.types import (
FusedCandidate,
FusionResult,
FusionVerdict,
IntentEntry,
)
logger = logging.getLogger(__name__)
ALPHA: float = 0.10
DELTA: float = 0.10
LOW_SCORE_THRESHOLD: float = 0.20
EMBEDDING_TOP_K: int = 5
DEFAULT_MODEL: str = "BAAI/bge-small-en-v1.5"
class IntentRouter:
"""Dual-channel intent router with embedding recall and LLM tree reasoning.
Args:
entries: List of IntentEntry objects defining your intent space.
model_name: Sentence-transformer model for embedding channel.
Default: "BAAI/bge-small-en-v1.5".
Example::
router = IntentRouter(entries)
result = await router.fuse("where is my order", llm)
if result.verdict == FusionVerdict.CLEAR:
handle(result.top.name)
"""
def __init__(
self,
entries: list[IntentEntry],
*,
model_name: str = DEFAULT_MODEL,
) -> None:
self._entries = entries
self._model_name = model_name
self._model: Any = None
self._index: list[tuple[str, np.ndarray]] = []
self._tree_text: str = build_intent_tree_text(entries)
def build_index(self) -> None:
"""Pre-build the embedding index.
Call once at startup to avoid cold-start latency on the first request.
Called automatically on the first ``fuse()`` if not called explicitly.
"""
model = self._get_model()
if model is None:
return
index = []
for entry in self._entries:
text = f"{entry.name}: {entry.embed_text}"
vec = model.encode([text], normalize_embeddings=True)[0]
index.append((entry.name, vec))
self._index = index
logger.info("IntentRouter: index built (%d entries)", len(index))
def _get_model(self) -> Any:
if self._model is None:
try:
from sentence_transformers import SentenceTransformer
self._model = SentenceTransformer(self._model_name)
logger.info("IntentRouter: loaded %s", self._model_name)
except Exception as e:
logger.warning("IntentRouter: failed to load embedding model: %s", e)
return self._model
def _embedding_channel(self, message: str) -> list[tuple[str, float]]:
"""Return top-k candidates by cosine similarity."""
model = self._get_model()
if model is None:
return []
if not self._index:
self.build_index()
if not self._index:
return []
user_vec = model.encode([message], normalize_embeddings=True)[0]
scores = [(name, float(np.dot(user_vec, vec))) for name, vec in self._index]
scores.sort(key=lambda x: x[1], reverse=True)
return scores[:EMBEDDING_TOP_K]
async def fuse(
self,
message: str,
llm: LLMProvider,
*,
alpha: float = ALPHA,
delta: float = DELTA,
) -> FusionResult:
"""Run dual-channel intent fusion with single-channel degradation.
Runs embedding recall and LLM tree reasoning in parallel. If one
channel fails, the other still produces a result (degraded=True).
Args:
message: User input string.
llm: LLM provider implementing the LLMProvider protocol.
alpha: Embedding channel weight in [0, 1]. Default 0.10 (tree-dominant).
delta: Score gap threshold for CLEAR vs AMBIGUOUS. Default 0.10.
Returns:
FusionResult with verdict, top candidate, runner-up, and timing info.
"""
t0 = time.time()
async def _run_emb() -> tuple[list[tuple[str, float]], float]:
t = time.time()
result = await asyncio.to_thread(self._embedding_channel, message)
return result, (time.time() - t) * 1000
async def _run_tree() -> tuple[list[tuple[str, float]], float]:
t = time.time()
candidates = await reason_intent_tree(
message, self._entries, llm, tree_text=self._tree_text,
)
result = [(c.skill, c.score) for c in candidates]
return result, (time.time() - t) * 1000
results = await asyncio.gather(
_run_emb(), _run_tree(), return_exceptions=True,
)
emb_result, tree_result = results
emb_ok = not isinstance(emb_result, BaseException)
tree_ok = not isinstance(tree_result, BaseException)
emb_top: list[tuple[str, float]] = []
tree_top: list[tuple[str, float]] = []
emb_ms = 0.0
tree_ms = 0.0
if emb_ok:
emb_top, emb_ms = emb_result # type: ignore[misc]
else:
logger.warning("IntentRouter: embedding channel failed: %s", emb_result)
if tree_ok:
tree_top, tree_ms = tree_result # type: ignore[misc]
else:
logger.warning("IntentRouter: tree channel failed: %s", tree_result)
if not emb_ok and not tree_ok:
logger.error("IntentRouter: both channels failed")
return FusionResult(
verdict=FusionVerdict.LOW,
total_ms=(time.time() - t0) * 1000,
degraded=True,
active_channels=[],
)
effective_alpha = alpha
active_channels: list[str] = []
degraded = False
if emb_ok and tree_ok:
active_channels = ["embedding", "tree"]
elif emb_ok:
effective_alpha = 1.0
active_channels = ["embedding"]
degraded = True
else:
effective_alpha = 0.0
active_channels = ["tree"]
degraded = True
candidates = merge_and_score(emb_top, tree_top, effective_alpha)
result = decide(candidates, delta)
result.emb_ms = emb_ms
result.tree_ms = tree_ms
result.total_ms = (time.time() - t0) * 1000
result.degraded = degraded
result.active_channels = active_channels
if result.top:
logger.info(
"IntentRouter: verdict=%s top=%s(%.3f) runner=%s(%.3f) "
"channels=%s emb=%.0fms tree=%.0fms total=%.0fms",
result.verdict.value,
result.top.name, result.top.final_score,
result.runner_up.name if result.runner_up else "-",
result.runner_up.final_score if result.runner_up else 0.0,
active_channels, emb_ms, tree_ms, result.total_ms,
)
return result
# ── Stateless helpers (also used by calibration) ──
def merge_and_score(
emb_top: list[tuple[str, float]],
tree_top: list[tuple[str, float]],
alpha: float,
) -> list[FusedCandidate]:
"""Union both channel candidates and compute fused score.
Formula:
both channels: alpha * emb_score + (1 - alpha) * tree_score
embedding only: alpha * emb_score
tree only: (1 - alpha) * tree_score
Candidates appearing in both channels naturally score higher,
rewarding cross-channel agreement without any special bonus term.
"""
cands: dict[str, FusedCandidate] = {}
for name, score in emb_top:
cands[name] = FusedCandidate(
name=name, final_score=0.0,
emb_score=score, tree_score=0.0,
in_emb=True, in_tree=False,
)
for name, score in tree_top:
if name in cands:
cands[name].tree_score = score
cands[name].in_tree = True
else:
cands[name] = FusedCandidate(
name=name, final_score=0.0,
emb_score=0.0, tree_score=score,
in_emb=False, in_tree=True,
)
for c in cands.values():
c.final_score = alpha * c.emb_score + (1 - alpha) * c.tree_score
return sorted(cands.values(), key=lambda x: x.final_score, reverse=True)
def decide(candidates: list[FusedCandidate], delta: float) -> FusionResult:
"""Produce a three-state verdict.
CLEAR: top score >= LOW_SCORE_THRESHOLD and gap to runner-up >= delta
AMBIGUOUS: top score >= LOW_SCORE_THRESHOLD but gap < delta (two plausible intents)
LOW: top score < LOW_SCORE_THRESHOLD (no confident match)
Recommended downstream handling:
CLEAR -> route directly to top.name
AMBIGUOUS -> execute top.name, surface runner_up as a suggestion
LOW -> fall back to free chat or search
"""
if not candidates:
return FusionResult(verdict=FusionVerdict.LOW)
top = candidates[0]
if top.final_score < LOW_SCORE_THRESHOLD:
return FusionResult(verdict=FusionVerdict.LOW, top=top, candidates=candidates)
if len(candidates) < 2:
return FusionResult(verdict=FusionVerdict.CLEAR, top=top, candidates=candidates)
runner_up = candidates[1]
gap = top.final_score - runner_up.final_score
verdict = FusionVerdict.CLEAR if gap >= delta else FusionVerdict.AMBIGUOUS
return FusionResult(
verdict=verdict,
top=top,
runner_up=runner_up,
candidates=candidates,
)
"""Intent tree reasoning channel — LLM-based hierarchical intent classification.
PageIndex-style: builds a domain-grouped intent tree from IntentEntry definitions,
then uses a single LLM call with chain-of-thought reasoning to select top candidates.
Complements the embedding channel:
- Embedding excels at surface/lexical similarity ("refund" → process_refund)
- Intent tree excels at semantic inference ("where's my stuff" → query_order_status)
"""
from __future__ import annotations
import json
import logging
import re
from typing import Any, Protocol, runtime_checkable
from intent_fusion.types import IntentEntry, TreeCandidate
logger = logging.getLogger(__name__)
# ── LLM Provider Protocol ──
@runtime_checkable
class LLMProvider(Protocol):
"""Minimal interface required by the tree reasoning channel.
Any object with a `chat(messages)` method works — OpenAI, Anthropic,
local Ollama, or a mock for testing.
"""
async def chat(self, messages: list[dict[str, str]], **kwargs: Any) -> str:
"""Send messages and return the assistant's reply as a string."""
...
# ── Build Intent Tree Text ──
def build_intent_tree_text(entries: list[IntentEntry]) -> str:
"""Build a domain-grouped intent tree prompt from IntentEntry definitions.
Output format:
── Order Management ──
query_order_status: user asks where their order is, shipping status, ETA
cancel_order: user wants to cancel an order they placed
...
"""
domain_map: dict[str, list[str]] = {}
for entry in entries:
line = f" {entry.name}: {entry.tree_text}"
domain_map.setdefault(entry.domain, []).append(line)
parts: list[str] = []
for domain, lines in domain_map.items():
parts.append(f"── {domain} ──")
parts.extend(lines)
parts.append("")
# Built-in fallback targets (always present)
parts.append("── Special (non-intent) ──")
parts.append(" free_chat: greetings, small talk, questions unrelated to the system")
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)
# ── 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"""
# ── Parse LLM Response ──
def parse_tree_response(text: str) -> list[TreeCandidate]:
"""Parse LLM response into TreeCandidate list.
Handles:
1. <think>...</think> + JSON
2. Plain JSON
3. JSON embedded in prose
"""
# Strip <think> block if present
think_end = text.rfind("</think>")
if think_end >= 0:
json_part = text[think_end + len("</think>"):].strip()
else:
json_part = text.strip()
for candidate_text in (json_part, text):
# Try direct parse
try:
data = json.loads(candidate_text)
return _extract_candidates(data)
except json.JSONDecodeError:
pass
# Try regex extraction
match = re.search(r'\{[\s\S]*"top"[\s\S]*\}', candidate_text)
if match:
try:
data = json.loads(match.group())
return _extract_candidates(data)
except json.JSONDecodeError:
pass
logger.warning("intent_tree: failed to parse LLM response: %s", text[:200])
return []
def _extract_candidates(data: dict) -> list[TreeCandidate]:
candidates = []
for item in data.get("top", []):
if isinstance(item, dict) and "skill" in item:
score = max(0.0, min(1.0, float(item.get("score", 0.5))))
candidates.append(TreeCandidate(
skill=item["skill"],
score=score,
reason=item.get("reason", ""),
))
return candidates
# ── LLM Call ──
async def reason_intent_tree(
message: str,
entries: list[IntentEntry],
llm: LLMProvider,
*,
tree_text: str | None = None,
temperature: float = 0.1,
max_tokens: int = 800,
) -> list[TreeCandidate]:
"""Run intent tree reasoning via a single LLM call.
Args:
message: User input.
entries: Intent definitions (used to build tree_text if not provided).
llm: Any object implementing LLMProvider (openai client, wrapper, mock).
tree_text: Pre-built tree text (pass to avoid rebuilding on every call).
temperature: Lower = more deterministic routing.
max_tokens: Keep low — we only need a short JSON response.
Returns:
Up to 3 TreeCandidate objects sorted by score descending.
"""
if tree_text is None:
tree_text = build_intent_tree_text(entries)
prompt = INTENT_TREE_PROMPT.format(tree_text=tree_text, message=message)
messages = [{"role": "user", "content": prompt}]
response = await llm.chat(messages, temperature=temperature, max_tokens=max_tokens)
return parse_tree_response(response)
"""Core data types for intent-fusion."""
from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Any
@dataclass
class IntentEntry:
"""Defines a single intent for indexing.
Attributes:
name: Unique intent identifier (e.g. "query_order_status").
domain: Grouping label for the intent tree (e.g. "Order Management").
embed_text: Text used for embedding similarity — optimized for lexical/surface matching.
tree_text: Text used in the LLM intent tree — optimized for semantic reasoning.
If omitted, falls back to embed_text.
"""
name: str
domain: str
embed_text: str
tree_text: str = ""
def __post_init__(self):
if not self.tree_text:
self.tree_text = self.embed_text
@dataclass
class TreeCandidate:
"""A candidate returned by the LLM tree reasoning channel."""
skill: str
score: float
reason: str = ""
@dataclass
class FusedCandidate:
"""A candidate after merging both channels."""
name: str
final_score: float
emb_score: float = 0.0
tree_score: float = 0.0
in_emb: bool = False
in_tree: bool = False
class FusionVerdict(str, Enum):
CLEAR = "clear" # Top candidate is clearly dominant — route directly.
AMBIGUOUS = "ambiguous" # Top-2 are close — surface both to user or pick top.
LOW = "low" # No confident match — fall back to free chat / search.
@dataclass
class FusionResult:
"""The final output of dual-channel fusion."""
verdict: FusionVerdict
top: FusedCandidate | None = None
runner_up: FusedCandidate | None = None
candidates: list[FusedCandidate] = field(default_factory=list)
emb_ms: float = 0.0
tree_ms: float = 0.0
total_ms: float = 0.0
degraded: bool = False
active_channels: list[str] = field(default_factory=lambda: ["embedding", "tree"])
[build-system]
requires = ["setuptools>=68", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "intent-fusion"
version = "0.1.0"
description = "Production-validated dual-channel intent routing: Embedding Recall + LLM Tree Reasoning"
readme = "README.md"
license = { text = "MIT" }
requires-python = ">=3.10"
keywords = ["intent-recognition", "nlp", "llm", "routing", "chatbot", "embedding", "intent-fusion"]
classifiers = [
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
"Topic :: Software Development :: Libraries :: Python Modules",
"Typing :: Typed",
]
dependencies = [
"numpy>=1.24",
"sentence-transformers>=2.7",
"pyyaml>=6.0",
]
[project.optional-dependencies]
openai = ["openai>=1.0"]
dev = [
"pytest>=8.0",
"pytest-asyncio>=0.23",
"openai>=1.0",
]
[project.urls]
Homepage = "https://github.com/YOUR_USERNAME/intent-fusion"
Documentation = "https://github.com/YOUR_USERNAME/intent-fusion/tree/main/docs"
Issues = "https://github.com/YOUR_USERNAME/intent-fusion/issues"
Changelog = "https://github.com/YOUR_USERNAME/intent-fusion/blob/main/CHANGELOG.md"
[tool.setuptools.packages.find]
include = ["intent_fusion*"]
[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = ["tests"]
"""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"
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!