pipeline-integration.md 6.76 KB

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

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.

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:

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:

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:

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:

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).