Library

Volume 2 · NLP, Computer Vision & Predictive Analytics

Notebook
Sign in

Section 53

Enterprise NLP (Text Summarization, NER, Chatbots/Conversational AI Architecture)

1,338 words · about 6 min

53.1 The Enterprise NLP Stack

At architect level, enterprise NLP is rarely “call an LLM and hope.” It is a pipeline with pre-processing, extraction, normalization, and validation stages, because raw LLM output is probabilistic and enterprise systems (billing, compliance, clinical, financial) need deterministic guardrails around it.

Raw Enterprise Text (notes, tickets, contracts, transcripts)
    │
    ▼
┌─────────────────┐
│ Pre-processing   │ ← Tokenization, sentence splitting, section/segment detection
└────────┬────────┘
         ▼
┌─────────────────┐
│ Domain NER       │ ← Entities: people, orgs, dates, amounts, domain-specific concepts
└────────┬────────┘
         ▼
┌─────────────────┐
│ Negation /       │ ← "No evidence of X" → X = NEGATED
│ Assertion Status │ ← "History of X" → X = HISTORICAL
└────────┬────────┘
         ▼
┌─────────────────┐
│ Relation         │ ← Entity-entity links (e.g., drug↔condition, party↔obligation)
│ Extraction       │
└────────┬────────┘
         ▼
┌─────────────────┐
│ Normalization    │ ← Map free text to controlled vocabularies / codes / IDs
└────────┬────────┘
         ▼
Structured Output (JSON) → Downstream systems (billing, CRM, workflow engine)

53.2 Named Entity Recognition (NER)

Model landscape:

Model Architecture Domain Focus Deployment Notes
spaCy (en_core_web_trf) Transformer General Self-hosted Fast, production-grade, easy to fine-tune
BERT-base fine-tuned (BIO tagging) Encoder Domain-specific Self-hosted Standard approach for custom entity sets
BioBERT / ClinicalBERT Encoder Biomedical/clinical Self-hosted Pretrained on PubMed/MIMIC corpora
Managed cloud NER (AWS Comprehend / Azure Language) Managed General + some verticals API Fast to deploy, less customizable
LLM structured extraction (GPT-4o, Claude) Decoder Any domain via prompt/schema API Flexible, no training data needed, higher per-call cost

Two competing extraction paradigms:

Paradigm A: Fine-tuned NER model (BIO tagging)
  Pros: Cheap at scale, low latency, deterministic, no prompt drift
  Cons: Needs labeled training data (500-5000 examples), retraining for new entity types

Paradigm B: LLM structured extraction (function calling / JSON schema)
  Pros: Zero-shot/few-shot, handles novel entity types instantly, easy to iterate
  Cons: Higher cost per document at scale, latency, possible schema drift/hallucination

Architect’s decision rule: Use LLM extraction to bootstrap and validate the entity schema and to handle low-volume/high-complexity documents. Once entity types stabilize and volume is high, distill into a fine-tuned encoder model (BERT/DistilBERT) for cost and latency at scale. This is a common “LLM-to-distillation” pattern.

Negation and assertion detection is a first-class NER problem — getting it wrong silently corrupts every downstream decision:

# Example: LLM-based structured negation/assertion extraction
response = llm.parse(
    text=document_text,
    schema={
        "findings": [
            {
                "entity": str,
                "status": "present|negated|historical|uncertain|hypothetical",
                "evidence_span": str,
                "confidence": float
            }
        ]
    }
)
# "Patient denies chest pain."       -> chest_pain: NEGATED
# "No evidence of pneumonia."        -> pneumonia: NEGATED
# "History of diabetes."             -> diabetes: HISTORICAL

Rule-based approaches (NegEx-style trigger-phrase matching) remain valuable as a fast, deterministic first pass or as a cross-check against LLM output — disagreement between the two is a strong signal to route to human review.

53.3 Text Summarization Architectures

Approach Method Best For Trade-off
Extractive Select/rank existing sentences Factual fidelity, auditability May miss cross-sentence connections, reads choppy
Abstractive Generate new text (LLM) Readability, coherence, conciseness Hallucination risk
Hybrid Extract salient facts → generate fluent summary from facts only Balance of accuracy and readability More engineering complexity
Structured/Template LLM fills a predefined schema, field by field Consistency, auditability, compliance Less narrative flexibility

Structured summarization is the enterprise default because it constrains the model’s freedom to hallucinate and produces machine-consumable output:

SYSTEM: You are a documentation specialist. Summarize the following
document into the structured format below. Include ONLY information
explicitly present in the source. Mark any field "Not documented" if
not found. Do not infer or assume.

OUTPUT FORMAT (JSON):
{
  "summary_type": "structured",
  "key_topic": "...",
  "context": "...",
  "key_findings": ["...", "..."],
  "entities": [{"type": "...", "value": "...", "status": "..."}],
  "action_items": ["...", "..."],
  "quality": {
    "completeness_score": 0.0,
    "missing_elements": ["..."],
    "extraction_confidence": "high|medium|low"
  }
}

Hallucination controls for summarization:

  1. Constrain to extractive-first (select spans), then abstract only for fluency.
  2. Post-hoc faithfulness check: run a second pass verifying every summary claim traces to a source span (entailment check or NLI model).
  3. Force citation of source sentence/section IDs for every fact.
  4. Reject/flag summaries where faithfulness score < threshold before they reach a human or downstream system.

53.4 Conversational AI / Chatbot Architecture

User Message
    │
    ▼
┌──────────────┐
│ Intent        │ ← Classify: FAQ, transactional, complaint, escalation, etc.
│ Classification│
└──────┬───────┘
       ▼
┌──────────────┐
│ Entity        │ ← Extract slots needed to fulfill intent (dates, IDs, amounts)
│ Extraction    │
└──────┬───────┘
       ▼
┌──────────────┐
│ Dialogue State│ ← Track conversation context, multi-turn memory, missing slots
│ Management    │
└──────┬───────┘
       ▼
┌──────────────┐
│ RAG Retrieval │ ← Pull account/knowledge-base context relevant to the intent
│ (Access-      │   (with row/document-level access control applied)
│  controlled)  │
└──────┬───────┘
       ▼
┌──────────────┐
│ Response      │ ← Generate grounded, on-brand response
│ Generation    │
└──────┬───────┘
       ▼
┌──────────────┐
│ Safety/PII    │ ← Ensure no unauthorized data disclosure, tone check
│ Filter        │
└──────┬───────┘
       ▼
Response + optional Human Handoff trigger

Non-negotiable design constraints for enterprise conversational AI:

  1. Authentication before any personalized data access — no account data flows before identity is verified.
  2. Sensitive data never in URLs or plaintext logs — session-scoped, encrypted at rest and in transit.
  3. Always-available escalation path — “talk to a human” must never dead-end.
  4. Scope discipline — the bot must refuse to answer outside its authorized domain (e.g., no medical/legal/financial advice unless explicitly licensed to give it).
  5. Multi-language support where the user base demands it — translation either at the intent layer or via a multilingual base model.
  6. Full audit trail — every turn logged with model version, prompt version, retrieved sources, and confidence, for compliance and post-incident review.

Architecture patterns for conversational AI:

Pattern Description When to Use
Retrieval-augmented chat RAG over knowledge base for every turn Knowledge Q&A, support bots
Slot-filling task bot Structured dialogue to complete a transaction Booking, forms, structured workflows
Agentic chat LLM plans and calls tools/APIs dynamically Complex multi-step tasks (refunds, troubleshooting)
Hybrid router Classifier routes to the right sub-bot/pattern Enterprise assistants spanning many domains

Interview Q&A — Section 53

Q1: How would you design an NER pipeline for a new domain where you have no labeled training data? A: Start with LLM-based structured extraction (few-shot or zero-shot with a JSON schema) to bootstrap output quickly and validate the entity taxonomy with domain experts. Use this LLM pipeline to auto-label a corpus of real documents (with human spot-checking, ~10-15% sample). Once you have 1,000-5,000 validated labeled examples, fine-tune a smaller encoder model (BERT/DistilBERT with BIO tagging) for production — this cuts cost 10-50x and latency 5-10x versus calling an LLM per document at volume. Keep the LLM pipeline running in shadow mode as an ongoing quality check and to catch new entity types/drift.

Q2: Your summarization system occasionally invents facts not present in the source document. How do you fix this architecturally, not just with prompt tweaks? A: Prompt tweaks alone are unreliable because hallucination is a property of generative decoding, not just instruction-following. Architectural fixes: (1) switch to extract-then-abstract — first select candidate spans/sentences via a retrieval or extractive-summarization step, then only allow the LLM to rephrase within those spans; (2) add a post-generation faithfulness/entailment check (NLI model or LLM-as-judge) that verifies every claim in the summary is entailed by the source, rejecting or flagging summaries that fail; (3) require inline citations to source sentence IDs so failures are traceable and auditable; (4) track hallucination rate as a first-class production metric with an automatic block if it exceeds threshold (see Sections 58/67).

Q3: Design a multi-turn conversational AI architecture that must never leak one user’s data to another. A: Enforce authentication and authorization at the boundary before any retrieval happens — the retrieval layer must apply row/document-level ACLs scoped to the authenticated identity, not rely on the LLM to “know” not to answer. Session state (dialogue memory) is per-session, encrypted, and never shared across sessions or cached globally. Any tool call that touches customer data passes the authenticated identity as a mandatory parameter, and the tool itself enforces the ACL server-side (defense in depth — never trust the prompt to enforce access control). Full audit log per turn: user ID, retrieved document IDs, and response, so any leak can be traced immediately.