Published

Enterprise Chatbots and AI Assistants: Architecture and Best Practices

Build an enterprise chatbot that holds up in production: dialog management, memory, intent detection, template and LLM answers, human handoff and metrics.

Written by
Ali ÖzdurmuşFounder, Veni AI
Updated
Reading time
6 min read

A company chatbot is no longer a decision tree with canned answers. Today's assistants combine a language model with company knowledge, business systems and clear rules for when to hand over to a person. This guide covers the architecture and the practices that keep them reliable in production, whether they serve customers on the website and WhatsApp or employees on an internal portal.

Code samples are illustrative Python. client is an initialized SDK client and MODEL is a placeholder for the model ID you choose.

Chatbot Architecture

Core Components

┌────────────────────────────────────────────────────┐
│                    User Interface                   │
└───────────────────────┬────────────────────────────┘
                        │
┌───────────────────────▼────────────────────────────┐
│              Input Processing Layer                 │
│  ┌──────────┐  ┌──────────┐  ┌────────────────┐   │
│  │  Speech  │  │   Text   │  │   Multimodal   │   │
│  │  to Text │  │ Normalize│  │   Processing   │   │
│  └──────────┘  └──────────┘  └────────────────┘   │
└───────────────────────┬────────────────────────────┘
                        │
┌───────────────────────▼────────────────────────────┐
│                 Dialog Manager                      │
│  ┌──────────┐  ┌──────────┐  ┌────────────────┐   │
│  │  Intent  │  │  State   │  │    Context     │   │
│  │ Detection│  │ Manager  │  │    Handler     │   │
│  └──────────┘  └──────────┘  └────────────────┘   │
└───────────────────────┬────────────────────────────┘
                        │
┌───────────────────────▼────────────────────────────┐
│              Response Generation                    │
│  ┌──────────┐  ┌──────────┐  ┌────────────────┐   │
│  │   LLM    │  │ Template │  │     Action     │   │
│  │ Response │  │  Engine  │  │    Executor    │   │
│  └──────────┘  └──────────┘  └────────────────┘   │
└────────────────────────────────────────────────────┘

Context Management

Conversation Memory

python
from typing import List, Dict
from datetime import datetime

class ConversationMemory:
    def __init__(self, max_turns: int = 10):
        self.max_turns = max_turns
        self.history: List[Dict] = []
        self.metadata: Dict = {}
    
    def add_message(self, role: str, content: str):
        message = {
            "role": role,
            "content": content,
            "timestamp": datetime.now().isoformat()
        }
        self.history.append(message)
        
        # Clean old messages
        if len(self.history) > self.max_turns * 2:
            self.history = self.history[-self.max_turns * 2:]
    
    def get_context(self) -> List[Dict]:
        return [{"role": m["role"], "content": m["content"]} 
                for m in self.history]
    
    def summarize(self, llm_client) -> str:
        """Summarize long conversations"""
        if len(self.history) < 10:
            return None
        
        response = llm_client.chat.completions.create(
            model=MODEL,
            messages=[
                {"role": "system", "content": "Summarize this conversation."},
                {"role": "user", "content": str(self.history)}
            ]
        )
        return response.choices[0].message.content

Session State

python
class SessionState:
    def __init__(self, session_id: str):
        self.session_id = session_id
        self.user_info: Dict = {}
        self.collected_data: Dict = {}
        self.current_intent: str = None
        self.current_step: str = None
        self.awaiting_input: str = None
    
    def set_slot(self, name: str, value: any):
        self.collected_data[name] = value
    
    def get_slot(self, name: str) -> any:
        return self.collected_data.get(name)
    
    def clear_slots(self):
        self.collected_data = {}
    
    def is_complete(self, required_slots: List[str]) -> bool:
        return all(slot in self.collected_data for slot in required_slots)

Intent Classification

LLM-based Intent Detection

python
def detect_intent(user_message: str, available_intents: List[Dict]) -> Dict:
    intent_descriptions = "\n".join([
        f"- {intent['name']}: {intent['description']}"
        for intent in available_intents
    ])
    
    response = client.chat.completions.create(
        model=MODEL,
        response_format={"type": "json_object"},
        messages=[
            {
                "role": "system",
                "content": f"""Determine the intent of the user message.
                
Available intents:
{intent_descriptions}

Respond in JSON format:
{{"intent": "intent_name", "confidence": 0.0-1.0, "entities": {{}}}}
"""
            },
            {"role": "user", "content": user_message}
        ]
    )
    
    return json.loads(response.choices[0].message.content)

Hybrid Intent Detection

python
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression

class HybridIntentClassifier:
    def __init__(self):
        self.ml_classifier = None
        self.vectorizer = TfidfVectorizer()
    
    def train_ml(self, texts: List[str], labels: List[str]):
        X = self.vectorizer.fit_transform(texts)
        self.ml_classifier = LogisticRegression()
        self.ml_classifier.fit(X, labels)
    
    def classify(self, text: str) -> Dict:
        # ML prediction
        X = self.vectorizer.transform([text])
        ml_intent = self.ml_classifier.predict(X)[0]
        ml_confidence = max(self.ml_classifier.predict_proba(X)[0])
        
        # Ask LLM if confidence is low
        if ml_confidence < 0.7:
            llm_result = detect_intent(text, self.available_intents)
            return llm_result
        
        return {"intent": ml_intent, "confidence": ml_confidence}

Dialog Flow

State Machine

python
from enum import Enum

class OrderState(Enum):
    START = "start"
    PRODUCT_SELECTION = "product_selection"
    QUANTITY = "quantity"
    ADDRESS = "address"
    CONFIRMATION = "confirmation"
    COMPLETE = "complete"

class OrderFlow:
    def __init__(self):
        self.state = OrderState.START
        self.data = {}
    
    def process(self, user_input: str, intent: str) -> str:
        if self.state == OrderState.START:
            if intent == "order":
                self.state = OrderState.PRODUCT_SELECTION
                return "Which product would you like to order?"
        
        elif self.state == OrderState.PRODUCT_SELECTION:
            self.data["product"] = user_input
            self.state = OrderState.QUANTITY
            return f"You selected {user_input}. How many do you want?"
        
        elif self.state == OrderState.QUANTITY:
            self.data["quantity"] = int(user_input)
            self.state = OrderState.ADDRESS
            return "Could you provide your delivery address?"
        
        elif self.state == OrderState.ADDRESS:
            self.data["address"] = user_input
            self.state = OrderState.CONFIRMATION
            return f"Order summary:\n{self.data}\nDo you confirm?"
        
        elif self.state == OrderState.CONFIRMATION:
            if "yes" in user_input.lower():
                self.state = OrderState.COMPLETE
                return "Order received. Thank you!"
            else:
                self.state = OrderState.START
                return "Order cancelled."

Response Generation

Template + LLM Hybrid

python
class ResponseGenerator:
    def __init__(self):
        self.templates = {
            "greeting": [
                "Hello! How can I help you?",
                "Welcome! What would you like to do today?"
            ],
            "farewell": [
                "Have a good day! See you again.",
                "I'm here if you have any other questions. Goodbye!"
            ]
        }
    
    def generate(self, intent: str, context: Dict) -> str:
        # Template for simple intents
        if intent in self.templates:
            return random.choice(self.templates[intent])
        
        # LLM for complex intents
        return self.llm_generate(intent, context)
    
    def llm_generate(self, intent: str, context: Dict) -> str:
        system_prompt = f"""You are a helpful customer service assistant.
User intent: {intent}
Current context: {json.dumps(context, ensure_ascii=False)}

Rules:
- Give short and concise answers
- Be friendly but professional
- Ask follow-up questions if necessary
"""
        
        response = client.chat.completions.create(
            model=MODEL,
            messages=[
                {"role": "system", "content": system_prompt},
                *context.get("history", [])
            ]
        )
        
        return response.choices[0].message.content

Fallback Handling

python
class FallbackHandler:
    def __init__(self):
        self.fallback_count = 0
        self.max_fallbacks = 3
    
    def handle(self, user_input: str, context: Dict) -> str:
        self.fallback_count += 1
        
        if self.fallback_count >= self.max_fallbacks:
            self.fallback_count = 0
            return self.human_handoff(context)
        
        responses = [
            "I didn't understand. Could you rephrase that?",
            "I cannot help with this. You can ask a different question.",
            "I think I misunderstood you. could you try again?"
        ]
        
        return responses[self.fallback_count - 1]
    
    def human_handoff(self, context: Dict) -> str:
        # Hand off to human agent
        create_support_ticket(context)
        return "I am connecting you to a customer representative. Please wait."

Analytics and Monitoring

python
class ChatAnalytics:
    def __init__(self):
        self.metrics = {
            "total_conversations": 0,
            "successful_resolutions": 0,
            "fallback_rate": 0,
            "avg_turns_per_conversation": 0,
            "intent_distribution": {}
        }
    
    def log_conversation(self, conversation: Dict):
        self.metrics["total_conversations"] += 1
        
        # Intent tracking
        for message in conversation["messages"]:
            if "intent" in message:
                intent = message["intent"]
                self.metrics["intent_distribution"][intent] = \
                    self.metrics["intent_distribution"].get(intent, 0) + 1
        
        # Resolution tracking
        if conversation.get("resolved"):
            self.metrics["successful_resolutions"] += 1
    
    def get_resolution_rate(self) -> float:
        if self.metrics["total_conversations"] == 0:
            return 0
        return self.metrics["successful_resolutions"] / self.metrics["total_conversations"]

Production Checklist

Security

  • Input sanitization
  • Rate limiting
  • PII masking
  • Injection protection
  • Clear disclosure that users are talking to an AI
  • KVKK/GDPR-compliant retention of conversation logs

Performance

  • Response time < 2s
  • Concurrent users support
  • Caching layer
  • Auto-scaling

User Experience

  • Typing indicators
  • Error messages
  • Conversation history
  • Multi-language support

Conclusion

A reliable assistant is built from a few clear parts: memory that stays within limits, intent detection that knows when it is unsure, a mix of templates and generated answers, and a fast path to a human. Ground answers in company data, measure resolution and fallback rates, and improve from real conversations.

Veni AI builds AI assistants that answer from a company's own documents and systems, in Turkish and other languages, with human handoff built in. See our services or talk to us about your assistant.

Keep reading

Have a process that should run on AI?

Describe one process as it runs today, and we'll show you which repetitive steps an AI application or agent could handle.