Skip to main content
Interface primitives enable agents to communicate through various channels - from chat interfaces to voice calls to custom UI components - providing flexible ways for users to interact with agent capabilities.

Overview

The Interface primitive provides the building blocks for creating rich, interactive user experiences with agents. Whether you’re building a chat application, voice assistant, embedded widget, or custom dashboard, interfaces make agent capabilities accessible through the channels your users prefer. Interfaces are essential for:
  • Multi-Channel Communication: Deploy agents across chat, voice, email, and more
  • Custom UI Components: Build branded agent experiences
  • Real-Time Interaction: Stream responses and provide instant feedback
  • Rich Media: Support images, files, buttons, and interactive elements
  • Accessibility: Ensure agents work across devices and abilities
  • White-Label Solutions: Customize interface to match your brand

Chat Interface

Rich chat experiences with streaming, typing indicators, and media

Voice Interface

Voice-based interactions with speech-to-text and text-to-speech

Widget Embed

Embeddable components for websites and applications

Custom UI

Full control over design and user experience

How Interfaces Work

When you implement an interface:
  1. Channel Selection: Choose communication channel (chat, voice, email, etc.)
  2. UI Components: Configure interactive elements and styling
  3. Message Handling: Process user inputs and route to agents
  4. Response Rendering: Display agent responses with appropriate formatting
  5. State Management: Maintain conversation state and context
  6. Event Handling: React to user actions and system events
Streaming Support: All interfaces support real-time response streaming for immediate user feedback.

Interface Types

Chat Interface

{
  type: "chat",
  features: {
    streaming: true,
    fileUpload: true,
    richMedia: true,
    typing: true
  }
}

Voice Interface

{
  type: "voice",
  features: {
    speechToText: true,
    textToSpeech: true,
    language: "en-US",
    voice: "neural"
  }
}

Email Interface

{
  type: "email",
  features: {
    threading: true,
    attachments: true,
    templates: true
  }
}

Custom Widget

{
  type: "widget",
  features: {
    position: "bottom-right",
    theme: "light",
    branding: true
  }
}

Code Examples

Basic Chat Interface

import { Agentbase } from '@agentbase/sdk';

const agentbase = new Agentbase({
  apiKey: process.env.AGENTBASE_API_KEY
});

// Initialize chat interface
const chat = await agentbase.createInterface({
  type: "chat",
  name: "Customer Support Chat",
  config: {
    greeting: "Hi! How can I help you today?",
    placeholder: "Type your message...",
    streaming: true,
    fileUpload: {
      enabled: true,
      maxSize: 10485760, // 10MB
      allowedTypes: ["image/*", "application/pdf"]
    }
  },
  agent: {
    system: "You are a helpful customer support agent.",
    capabilities: {
      memory: { enabled: true }
    }
  }
});

console.log('Chat interface created:', chat.id);
console.log('Widget URL:', chat.widgetUrl);

Streaming Chat Responses

// Stream agent responses in real-time
const stream = await agentbase.streamMessage({
  interfaceId: chat.id,
  sessionId: session.id,
  message: "Explain quantum computing"
});

// Handle streaming chunks
for await (const chunk of stream) {
  if (chunk.type === "text") {
    console.log(chunk.text); // Display incrementally
  } else if (chunk.type === "function_call") {
    console.log("Calling function:", chunk.function);
  } else if (chunk.type === "complete") {
    console.log("Response complete");
  }
}

Embeddable Chat Widget

// Generate embeddable widget code
const widget = await agentbase.generateWidgetCode({
  interfaceId: chat.id,
  customization: {
    position: "bottom-right",
    theme: {
      primaryColor: "#0066cc",
      fontFamily: "Inter, sans-serif",
      borderRadius: "12px"
    },
    branding: {
      showPoweredBy: false,
      logo: "https://yourcompany.com/logo.png",
      companyName: "Your Company"
    },
    behavior: {
      openByDefault: false,
      showNotifications: true,
      soundEnabled: true
    }
  }
});

console.log('Widget code:', widget.embedCode);
// Add to your website's <head> or before </body>

Voice Interface

// Create voice interface
const voice = await agentbase.createInterface({
  type: "voice",
  name: "Phone Support",
  config: {
    voice: {
      provider: "elevenlabs",
      voiceId: "21m00Tcm4TlvDq8ikWAM", // Rachel voice
      model: "eleven_multilingual_v2",
      stability: 0.5,
      similarityBoost: 0.75
    },
    speech: {
      language: "en-US",
      timeout: 5000, // 5 seconds silence
      interruptible: true
    },
    greeting: "Hello! How can I assist you today?"
  },
  agent: {
    system: "You are a phone support agent. Be concise and clear."
  }
});

// Handle voice call
const call = await agentbase.initiateVoiceCall({
  interfaceId: voice.id,
  phoneNumber: "+1234567890"
});

Email Interface

// Create email interface
const email = await agentbase.createInterface({
  type: "email",
  name: "Support Email",
  config: {
    email: {
      address: "[email protected]",
      displayName: "Customer Support"
    },
    threading: {
      enabled: true,
      maxThreadLength: 10
    },
    templates: {
      signature: `
        Best regards,
        Customer Support Team
        Your Company
      `,
      footer: "This email was sent by an AI agent"
    },
    attachments: {
      enabled: true,
      maxSize: 25 * 1024 * 1024 // 25MB
    }
  },
  agent: {
    system: `You are an email support agent.

    Guidelines:
    - Professional and courteous tone
    - Comprehensive answers
    - Include relevant links and resources
    - Sign with your signature`
  }
});

// Process incoming email
await agentbase.processEmail({
  interfaceId: email.id,
  from: "[email protected]",
  subject: "Question about billing",
  body: "I have a question about my recent invoice...",
  inReplyTo: "previous_message_id" // For threading
});

Rich Interactive Messages

// Send message with interactive components
await agentbase.sendMessage({
  interfaceId: chat.id,
  sessionId: session.id,
  content: {
    text: "I found these products for you:",
    components: [
      {
        type: "card_carousel",
        cards: [
          {
            title: "Product A",
            description: "High-quality product",
            image: "https://example.com/product-a.jpg",
            price: "$99.99",
            buttons: [
              {
                label: "View Details",
                action: "open_url",
                url: "https://example.com/product-a"
              },
              {
                label: "Add to Cart",
                action: "callback",
                data: { productId: "prod_a", action: "add_cart" }
              }
            ]
          }
        ]
      },
      {
        type: "quick_replies",
        options: [
          { label: "Show more", value: "show_more" },
          { label: "Filter by price", value: "filter_price" },
          { label: "Start over", value: "start_over" }
        ]
      }
    ]
  }
});

Custom React Component

// Build custom chat UI with React
import { useAgentbase } from '@agentbase/react';

function CustomChat() {
  const { messages, sendMessage, isTyping, streamResponse } = useAgentbase({
    interfaceId: "int_123",
    sessionId: session.id
  });

  const handleSend = async (text: string) => {
    await sendMessage(text);
  };

  return (
    <div className="chat-container">
      <div className="messages">
        {messages.map(msg => (
          <Message
            key={msg.id}
            role={msg.role}
            content={msg.content}
            timestamp={msg.timestamp}
          />
        ))}
        {isTyping && <TypingIndicator />}
      </div>

      <ChatInput onSend={handleSend} />
    </div>
  );
}

Multi-Channel Interface

// Deploy agent across multiple channels
const multiChannel = await agentbase.createInterface({
  type: "multi_channel",
  name: "Omnichannel Support",
  channels: [
    {
      type: "chat",
      config: { /* chat config */ }
    },
    {
      type: "voice",
      config: { /* voice config */ }
    },
    {
      type: "email",
      config: { /* email config */ }
    },
    {
      type: "sms",
      config: {
        phoneNumber: "+1234567890",
        provider: "twilio"
      }
    }
  ],
  agent: {
    system: `You are an omnichannel support agent.

    Adapt your communication style to the channel:
    - Chat: Conversational, can use emojis
    - Voice: Clear, concise, spoken language
    - Email: Professional, comprehensive
    - SMS: Very brief, essential info only`
  }
});

Use Cases

1. Customer Support Chat

Build comprehensive support chat:
const supportChat = await agentbase.createInterface({
  type: "chat",
  name: "Customer Support",
  config: {
    greeting: "Hi! I'm here to help. What can I assist you with?",
    quickReplies: [
      "Track my order",
      "Return an item",
      "Technical support",
      "Billing question"
    ],
    fileUpload: {
      enabled: true,
      types: ["image/*", "application/pdf"],
      hint: "Upload screenshots or documents"
    },
    availability: {
      businessHours: {
        monday: { start: "9:00", end: "17:00" },
        tuesday: { start: "9:00", end: "17:00" },
        wednesday: { start: "9:00", end: "17:00" },
        thursday: { start: "9:00", end: "17:00" },
        friday: { start: "9:00", end: "17:00" }
      },
      timezone: "America/New_York",
      offHoursMessage: "We're currently offline. Leave a message and we'll respond when we're back!"
    }
  },
  agent: {
    system: `You are a customer support agent.

    Capabilities:
    - Answer questions about products and services
    - Help track orders and shipments
    - Process returns and refunds
    - Troubleshoot technical issues
    - Escalate to human when needed

    Always be helpful, patient, and professional.`,
    integrations: {
      zendesk: { enabled: true },
      shopify: { enabled: true }
    }
  }
});

2. Sales Assistant

Interactive sales chat:
const salesChat = await agentbase.createInterface({
  type: "chat",
  name: "Sales Assistant",
  config: {
    greeting: "Welcome! Looking for something specific?",
    proactive: {
      enabled: true,
      triggers: [
        {
          condition: "pageViews > 3",
          message: "I noticed you're browsing. Can I help you find something?"
        },
        {
          condition: "cartAbandoned",
          delay: 60000, // 1 minute
          message: "I see you have items in your cart. Any questions before checkout?"
        }
      ]
    }
  },
  agent: {
    system: `You are a sales assistant.

    Goals:
    - Understand customer needs
    - Recommend appropriate products
    - Answer product questions
    - Help with purchasing decisions
    - Guide through checkout

    Use product catalog to make informed recommendations.`,
    dataConnectors: {
      postgres: { enabled: true } // Product catalog
    }
  }
});

3. Voice Assistant

Phone support with voice:
const voiceAssistant = await agentbase.createInterface({
  type: "voice",
  name: "Phone Support",
  config: {
    voice: {
      provider: "elevenlabs",
      voiceId: "professional_voice",
      speed: 1.0,
      pitch: 0
    },
    speech: {
      language: "en-US",
      continuous: true,
      interruptible: true,
      silenceTimeout: 3000
    },
    dtmf: {
      enabled: true, // Touch-tone support
      menu: {
        "1": "Sales",
        "2": "Support",
        "3": "Billing",
        "0": "Operator"
      }
    }
  },
  agent: {
    system: `You are a phone support agent.

    Voice guidelines:
    - Speak clearly and at moderate pace
    - Use simple language
    - Confirm understanding
    - Provide step-by-step instructions
    - Be patient with interruptions

    If you can't help, transfer to appropriate department.`
  }
});

4. Email Automation

Automated email responses:
const emailSupport = await agentbase.createInterface({
  type: "email",
  name: "Email Support",
  config: {
    routing: {
      rules: [
        {
          condition: "subject contains 'urgent' OR subject contains 'down'",
          priority: "high",
          notify: ["[email protected]"]
        },
        {
          condition: "from domain 'enterprise-customer.com'",
          priority: "high",
          assignTo: "enterprise-team"
        }
      ]
    },
    autoReply: {
      enabled: true,
      message: "Thank you for contacting us. We've received your email and will respond within 24 hours."
    },
    categorization: {
      enabled: true,
      categories: ["billing", "technical", "sales", "general"]
    }
  },
  agent: {
    system: `You are an email support agent.

    Process:
    1. Categorize the email
    2. Determine if you can fully resolve it
    3. Provide comprehensive answer
    4. Include relevant links/resources
    5. If escalation needed, create ticket

    Maintain professional email etiquette.`
  }
});

5. In-App Assistant

Contextual help within application:
const inAppAssistant = await agentbase.createInterface({
  type: "chat",
  name: "In-App Assistant",
  config: {
    contextual: {
      enabled: true,
      trackPageView: true,
      trackUserActions: true
    },
    suggestions: {
      enabled: true,
      smartSuggestions: [
        {
          page: "/dashboard",
          suggestions: [
            "How do I create a new project?",
            "Explain my usage metrics",
            "How to invite team members?"
          ]
        },
        {
          page: "/billing",
          suggestions: [
            "How to upgrade my plan?",
            "View payment history",
            "Update payment method"
          ]
        }
      ]
    }
  },
  agent: {
    system: `You are an in-app assistant.

    Context awareness:
    - Current page: {{page}}
    - User role: {{user.role}}
    - Account tier: {{user.tier}}

    Provide contextual help based on where user is in the app.
    Guide them through tasks step-by-step.
    Use in-app terminology and match the UI.`,
    auth: {
      required: true,
      inheritUserContext: true
    }
  }
});

6. WhatsApp Business

WhatsApp integration:
const whatsapp = await agentbase.createInterface({
  type: "whatsapp",
  name: "WhatsApp Business",
  config: {
    phoneNumber: "+1234567890",
    businessProfile: {
      name: "Your Company",
      description: "Customer Support",
      website: "https://yourcompany.com"
    },
    messageTemplates: {
      greeting: "Hello! How can we assist you today?",
      orderStatus: "Your order #{{orderId}} is {{status}}. Track it here: {{trackingUrl}}"
    },
    media: {
      enabled: true,
      supportedTypes: ["image", "document", "video"]
    }
  },
  agent: {
    system: `You are a WhatsApp business agent.

    WhatsApp best practices:
    - Be concise and direct
    - Use appropriate emojis
    - Send media when helpful
    - Quick response expected
    - International audience`
  }
});

Best Practices

User Experience

{
  streaming: true, // Show responses as they're generated
  typing: {
    enabled: true,
    showAfter: 500 // Show typing indicator after 500ms
  },
  acknowledgment: {
    enabled: true,
    message: "Got it, let me help with that..."
  }
}
{
  errorHandling: {
    userFriendly: true,
    fallback: "I'm having trouble processing that. Could you rephrase?",
    retryEnabled: true,
    escalation: {
      afterAttempts: 3,
      message: "Let me connect you with a human agent.",
      action: "create_ticket"
    }
  }
}
{
  responsive: true,
  mobile: {
    optimized: true,
    inputType: "text", // Optimize keyboard
    compact Mode: true,
    touchFriendly: true
  }
}
{
  accessibility: {
    screenReader: true,
    keyboardNavigation: true,
    highContrast: true,
    focusIndicators: true,
    ariaLabels: true
  }
}

Performance

Optimize Loading: Lazy load interface components and cache static assets for faster performance.
// Stream responses for instant feedback
{
  streaming: {
    enabled: true,
    chunkSize: 50, // Characters per chunk
    minChunkDelay: 20 // Minimum ms between chunks
  }
}
{
  lazyLoad: {
    enabled: true,
    loadOnScroll: true,
    preloadMessages: 20
  }
}
{
  caching: {
    staticAssets: true,
    conversationHistory: {
      enabled: true,
      ttl: 3600 // 1 hour
    }
  }
}

Security

Sanitize User Input: Always sanitize and validate user inputs to prevent XSS and injection attacks.
{
  validation: {
    maxLength: 4000,
    sanitizeHtml: true,
    blockScripts: true,
    rateLimiting: {
      maxMessagesPerMinute: 10
    }
  }
}
{
  auth: {
    required: true,
    method: "jwt",
    enforceSessionValid ity: true
  }
}
{
  contentModeration: {
    enabled: true,
    blockProfanity: true,
    blockPII: true,
    customFilters: ["credit-card", "ssn"]
  }
}

Integration with Other Primitives

With Memory

Maintain conversation context:
const interface = await agentbase.createInterface({
  type: "chat",
  agent: {
    capabilities: {
      memory: {
        enabled: true,
        namespace: "user_{{userId}}"
      }
    }
  }
});

// Agent remembers previous conversations
Learn more: Memory Primitive

With Skills

Apply specialized skills:
const interface = await agentbase.createInterface({
  type: "chat",
  agent: {
    skills: ["customer_support", "product_knowledge"]
  }
});
Learn more: Skills Primitive

With Authentication

Secure interfaces:
const interface = await agentbase.createInterface({
  type: "chat",
  auth: {
    required: true,
    method: "jwt"
  },
  agent: {
    auth: {
      inheritUserContext: true
    }
  }
});
Learn more: Authentication Primitive

Performance Considerations

Response Times

  • Text Chat: < 100ms to first token
  • Voice: < 200ms to speech start
  • Email: < 1s for simple responses
  • Streaming: 20-50 tokens/second

Scalability

  • Concurrent Users: Thousands per interface
  • Message Throughput: Millions per day
  • Global Distribution: CDN-cached widgets

Troubleshooting

Problem: Chat widget doesn’t appearSolutions:
  • Check widget script is loaded
  • Verify interfaceId is correct
  • Check for JavaScript console errors
  • Ensure no CSP blocking
  • Verify domain is whitelisted
// Debug widget loading
window.agentbaseDebug = true;
Problem: User messages fail to sendSolutions:
  • Check network connectivity
  • Verify session is active
  • Check rate limits
  • Review authentication
  • Inspect browser console
// Handle send errors
try {
  await sendMessage(text);
} catch (error) {
  console.error('Send failed:', error);
  showUserFriendlyError();
}
Problem: Responses not streaming smoothlySolutions:
  • Check network connection quality
  • Verify streaming is enabled
  • Reduce chunk size
  • Check for proxy/firewall issues
  • Use WebSocket instead of SSE
{
  streaming: {
    enabled: true,
    transport: "websocket", // Instead of SSE
    fallback: "polling"
  }
}

Additional Resources

API Reference

Complete interface API docs

UI Components

Pre-built UI component library

Design Guide

Interface design best practices
Pro Tip: Start with the pre-built chat widget for quick deployment, then customize the UI as your needs evolve. The widget provides a production-ready experience out of the box.