Advanced App Development

Master advanced Fiberwise app development with complete enterprise examples, including external API integration, AI-powered workflows, and human-in-the-loop processes.

Real-World Advanced App Examples

Learn advanced Fiberwise app development through two comprehensive examples that demonstrate enterprise-grade features including AI automation, complex workflows, and sophisticated user interfaces.

πŸ“„ Smart Document Processor

Upload documents, extract data with AI, and manage approval workflows

  • Drag-and-drop file uploads
  • AI-powered text extraction and classification
  • Dynamic forms based on document types
  • Multi-stage approval workflows
  • Real-time processing status

🎫 Customer Support Portal

Complete ticketing system with AI assistance and agent dashboards

  • External API integration for ticket creation
  • AI sentiment analysis and auto-responses
  • Human-in-the-loop approval processes
  • Real-time agent collaboration
  • Advanced reporting and analytics

Advanced Platform Features Demonstrated:

  • Complex Data Models: Related entities with user isolation and validation
  • AI Agent Integration: Multiple agents working together in processing pipelines
  • Advanced UI Patterns: Dynamic components, real-time updates, and responsive design
  • External Integration: REST APIs, webhooks, and third-party service connections
  • Workflow Orchestration: Multi-step processes with conditional logic and human intervention
  • Enterprise Security: User isolation, audit trails, and role-based access control

Document Processing Application

A complete AI-powered document processing system with file uploads, intelligent data extraction, and approval workflows.

Document Processing Flow

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  User Uploads   │────│  File Storage   │────│  AI Analysis    β”‚
β”‚   Document      β”‚    β”‚  (Fiberwise)    β”‚    β”‚   (LLM Agent)   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚                       β”‚                       β”‚
         β–Ό                       β–Ό                       β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Status: uploaded│────│Status: processing│───│Status: completedβ”‚
β”‚   (Dashboard)   β”‚    β”‚   (Real-time)   β”‚    β”‚  (With Results) β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚                       β”‚                       β”‚
         β–Ό                       β–Ό                       β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  User Reviews   │────│  AI Extracted   │────│   Final Data    β”‚
β”‚   on Dashboard  β”‚    β”‚   Structured    β”‚    β”‚   Stored in     β”‚
β”‚                 β”‚    β”‚      Data       β”‚    β”‚     Model       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Process Breakdown:

  1. Upload: User drags and drops documents into the web interface
  2. Storage: Files are securely stored with automatic metadata generation
  3. AI Analysis: LLM agents extract structured data and classify document types
  4. Real-time Updates: WebSocket connections keep the dashboard synchronized
  5. Review & Approval: Human users can review and modify AI-extracted data
  6. Final Storage: Approved data is committed to the database model

Complete App Manifest

# app_manifest.yaml - Advanced Document Processor
app:
  name: Document Processor
  app_slug: doc-processor
  version: 1.0.0
  description: AI-powered document processing with real-time status
  entryPoint: index.js
  icon: fas fa-file-alt
  category: productivity

  models:
    - name: Document
      model_slug: documents
      user_isolation: enforced
      fields:
        - name: ID
          field_column: id
          type: uuid
          is_primary_key: true
        - name: Filename
          field_column: filename
          type: string
          required: true
        - name: Status
          field_column: status
          type: string
          default: "uploaded"
          validations:
            enum: ["uploaded", "processing", "completed", "failed"]
        - name: Document Type
          field_column: doc_type
          type: string
          description: "AI-determined document category"
        - name: Extracted Data
          field_column: extracted_data
          type: json
          description: "AI-extracted structured data"
        - name: Processing Notes
          field_column: notes
          type: text
        - name: Confidence Score
          field_column: confidence
          type: decimal
        - name: Created At
          field_column: created_at
          type: timestamp
          default: CURRENT_TIMESTAMP
          is_system_field: true

  routes:
    - path: /
      component: document-dashboard
      title: Dashboard
      icon: fas fa-tachometer-alt
    - path: /upload
      component: document-upload
      title: Upload
      icon: fas fa-cloud-upload-alt
    - path: /documents/:id
      component: document-detail
      title: Document Details
      icon: fas fa-file-alt

agents:
  - name: documentAnalyzer
    description: Analyze and extract data from documents
    agent_type_id: llm
    version: 1.0.0
    input_schema:
      type: object
      properties:
        filename:
          type: string
        content_preview:
          type: string
    output_schema:
      type: object
      properties:
        document_type:
          type: string
          enum: ["invoice", "contract", "receipt", "form", "other"]
        confidence:
          type: number
        extracted_fields:
          type: object
        summary:
          type: string

functions:
  - name: processDocument
    description: Process uploaded document with AI analysis
    version: 1.0.0
    input_schema:
      type: object
      properties:
        document_id:
          type: string
    output_schema:
      type: object
      properties:
        success:
          type: boolean
        processing_id:
          type: string
        estimated_completion:
          type: string

pipelines:
  - id: document_processing_pipeline
    name: Document Processing Pipeline
    description: Complete document analysis and data extraction workflow
    trigger:
      type: data_change
      model: documents
      conditions:
        - field: status
          operator: equals
          value: "uploaded"
    
    steps:
      - id: analyze_document
        name: AI Document Analysis
        type: agent_activation
        agent_id: documentAnalyzer
        input_mapping:
          filename: "${trigger.data.filename}"
          content_preview: "${trigger.data.content_preview}"
        
      - id: update_results
        name: Update Document with Results
        type: data_update
        model: documents
        item_id: "${trigger.item_id}"
        data:
          doc_type: "${steps.analyze_document.output.document_type}"
          confidence: "${steps.analyze_document.output.confidence}"
          extracted_data: "${steps.analyze_document.output.extracted_fields}"
          status: "completed"
          notes: "${steps.analyze_document.output.summary}"

Key Features Demonstrated

πŸ“ File Upload & Management

Drag-and-drop interface with progress tracking and real-time status updates

🧠 AI Document Analysis

Intelligent document classification and structured data extraction using LLM agents

⚑ Pipeline Automation

Automated processing workflows triggered by data changes with conditional logic

πŸ“Š Real-time Dashboard

Live processing status with WebSocket updates and comprehensive metrics

Enterprise Customer Support System

A complete enterprise support system with external API integration, AI processing, and human workflow management.

Support System Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   External API  │────│  Fiberwise API  │────│   Support App   β”‚
β”‚  (Python SDK)   β”‚    β”‚   (REST/WS)     β”‚    β”‚  (Dashboard)    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚                       β”‚                       β”‚
         β–Ό                       β–Ό                       β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Support Tickets │────│   AI Agents     │────│ Human Agents    β”‚
β”‚   (Model Data)  β”‚    β”‚ (Classification)β”‚    β”‚  (Dashboard)    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚                       β”‚                       β”‚
         β–Ό                       β–Ό                       β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Pipelines     │────│   Workflows     │────│  Notifications  β”‚
β”‚  (Automation)   β”‚    β”‚ (Human Steps)   β”‚    β”‚   (Real-time)   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

🎫 Support Ticket Management

Dynamic data models for tickets, responses, and escalations with automatic user attribution and role-based access.

πŸ€– AI Processing Pipeline

Automated ticket classification, sentiment analysis, and response generation using multiple specialized LLM agents.

πŸ‘₯ Human Workflow Integration

Approval processes, escalation management, and agent collaboration tools with real-time updates.

πŸ”Œ External API Integration

REST endpoints for ticket creation, Python SDK integration, and webhook notifications for external systems.

Complete Support System Manifest

# app_manifest.yaml - Enterprise Support System
app:
  name: Customer Support Portal
  app_slug: support-portal
  version: 2.0.0
  description: Enterprise customer support system with AI automation and human workflows
  entryPoint: index.js
  icon: fas fa-headset
  category: customer_service

  models:
    - name: Support Ticket
      model_slug: support_tickets
      user_isolation: enforced
      fields:
        - name: ID
          field_column: id
          type: uuid
          is_primary_key: true
        - name: Customer Email
          field_column: customer_email
          type: string
          required: true
          validations:
            format: email
        - name: Subject
          field_column: subject
          type: string
          required: true
          validations:
            max_length: 200
        - name: Description
          field_column: description
          type: text
          required: true
        - name: Status
          field_column: status
          type: string
          default: "new"
          validations:
            enum: ["new", "processing", "waiting_review", "resolved", "closed"]
        - name: Priority
          field_column: priority
          type: string
          default: "medium"
          validations:
            enum: ["low", "medium", "high", "urgent"]
        - name: Category
          field_column: category
          type: string
          validations:
            enum: ["technical", "billing", "general", "urgent", "feature_request"]
        - name: AI Response
          field_column: ai_response
          type: text
          description: "Generated AI response"
        - name: Human Response
          field_column: human_response
          type: text
          description: "Final approved response"
        - name: Sentiment Score
          field_column: sentiment_score
          type: decimal
          description: "Customer sentiment analysis result"
        - name: Confidence Score
          field_column: confidence_score
          type: decimal
          description: "AI classification confidence"
        - name: Escalation Required
          field_column: escalation_required
          type: boolean
          default: false
        - name: Assigned Agent
          field_column: assigned_agent
          type: string
          description: "Human agent assigned to ticket"
        - name: Resolution Time
          field_column: resolution_time
          type: timestamp
          description: "When ticket was resolved"
        - name: Customer Satisfaction
          field_column: satisfaction_rating
          type: integer
          validations:
            min: 1
            max: 5
        - name: Created At
          field_column: created_at
          type: timestamp
          default: CURRENT_TIMESTAMP
          is_system_field: true

  routes:
    - path: /
      component: support-dashboard
      title: Support Dashboard
      icon: fas fa-tachometer-alt
    - path: /tickets
      component: ticket-list
      title: All Tickets
      icon: fas fa-list
    - path: /tickets/:id
      component: ticket-detail
      title: Ticket Details
      icon: fas fa-ticket-alt
    - path: /analytics
      component: support-analytics
      title: Analytics
      icon: fas fa-chart-bar

agents:
  - name: ticketClassifier
    description: Classify and prioritize support tickets
    agent_type_id: llm
    version: 1.0.0
    input_schema:
      type: object
      properties:
        subject:
          type: string
        description:
          type: string
        customer_email:
          type: string
    output_schema:
      type: object
      properties:
        category:
          type: string
          enum: ["technical", "billing", "general", "urgent", "feature_request"]
        priority:
          type: string
          enum: ["low", "medium", "high", "urgent"]
        confidence:
          type: number
        reasoning:
          type: string

  - name: sentimentAnalyzer
    description: Analyze customer sentiment and urgency
    agent_type_id: llm
    version: 1.0.0
    input_schema:
      type: object
      properties:
        ticket_content:
          type: string
    output_schema:
      type: object
      properties:
        sentiment:
          type: string
          enum: ["positive", "neutral", "negative", "frustrated", "angry"]
        urgency_indicators:
          type: array
        satisfaction_risk:
          type: string
          enum: ["low", "medium", "high", "critical"]

  - name: responseGenerator
    description: Generate AI responses for support tickets
    agent_type_id: llm
    version: 1.0.0
    input_schema:
      type: object
      properties:
        ticket:
          type: object
        classification:
          type: object
        company_context:
          type: object
    output_schema:
      type: object
      properties:
        response_text:
          type: string
        requires_human_review:
          type: boolean
        suggested_actions:
          type: array
        escalation_needed:
          type: boolean

functions:
  - name: createTicketFromAPI
    description: Create support ticket from external API call
    version: 1.0.0
    input_schema:
      type: object
      properties:
        customer_email:
          type: string
        subject:
          type: string
        description:
          type: string
        source:
          type: string
    output_schema:
      type: object
      properties:
        success:
          type: boolean
        ticket_id:
          type: string
        processing_started:
          type: boolean

pipelines:
  - id: new_ticket_processing
    name: New Ticket AI Processing
    description: Complete AI processing workflow for new support tickets
    trigger:
      type: data_change
      model: support_tickets
      conditions:
        - field: status
          operator: equals
          value: "new"
    
    steps:
      - id: classify_ticket
        name: Classify and Prioritize
        type: agent_activation
        agent_id: ticketClassifier
        input_mapping:
          subject: "${trigger.data.subject}"
          description: "${trigger.data.description}"
          customer_email: "${trigger.data.customer_email}"
        
      - id: analyze_sentiment
        name: Sentiment Analysis
        type: agent_activation
        agent_id: sentimentAnalyzer
        input_mapping:
          ticket_content: "${trigger.data.subject} ${trigger.data.description}"
        
      - id: generate_response
        name: Generate AI Response
        type: agent_activation
        agent_id: responseGenerator
        input_mapping:
          ticket: "${trigger}"
          classification: "${steps.classify_ticket.output}"
          company_context: {}
        
      - id: update_ticket_ai_data
        name: Update Ticket with AI Results
        type: data_update
        model: support_tickets
        item_id: "${trigger.item_id}"
        data:
          category: "${steps.classify_ticket.output.category}"
          priority: "${steps.classify_ticket.output.priority}"
          confidence_score: "${steps.classify_ticket.output.confidence}"
          sentiment_score: "${steps.analyze_sentiment.output.sentiment}"
          ai_response: "${steps.generate_response.output.response_text}"
          escalation_required: "${steps.generate_response.output.escalation_needed}"
          status: "${steps.generate_response.output.requires_human_review ? 'waiting_review' : 'processing'}"

# Human-in-the-Loop Workflows
workflows:
  - id: response_approval_workflow
    name: AI Response Review & Approval
    description: Human review process for AI-generated responses
    trigger:
      type: data_change
      model: support_tickets
      conditions:
        - field: status
          operator: equals
          value: "waiting_review"
    
    steps:
      - id: assign_to_agent
        name: Assign to Human Agent
        type: human_task
        assignee_type: role
        assignee_value: "support_agent"
        task_data:
          title: "Review AI Response for Ticket"
          description: "Please review the AI-generated response and approve or modify as needed"
          ticket_id: "${trigger.item_id}"
          ai_response: "${trigger.data.ai_response}"
          customer_email: "${trigger.data.customer_email}"
          priority: "${trigger.data.priority}"
        
        actions:
          - id: approve_response
            label: "Approve & Send"
            type: data_update
            model: support_tickets
            item_id: "${trigger.item_id}"
            data:
              human_response: "${trigger.data.ai_response}"
              status: "resolved"
              assigned_agent: "${action.user_id}"
              resolution_time: "${now()}"
            
          - id: modify_response
            label: "Modify Response"
            type: form_input
            fields:
              - name: modified_response
                type: textarea
                label: "Modified Response"
                default: "${trigger.data.ai_response}"
                required: true
            
            on_submit:
              type: data_update
              model: support_tickets
              item_id: "${trigger.item_id}"
              data:
                human_response: "${action.form.modified_response}"
                status: "resolved"
                assigned_agent: "${action.user_id}"
                resolution_time: "${now()}"
          
          - id: escalate_ticket
            label: "Escalate to Senior"
            type: data_update
            model: support_tickets
            item_id: "${trigger.item_id}"
            data:
              status: "escalated"
              escalation_required: true
              assigned_agent: "${action.user_id}"

Advanced Features Demonstrated

πŸ”Œ External API Integration

REST endpoints for ticket creation with Python SDK authentication and webhook support

πŸ€– Multi-Agent AI Pipeline

Coordinated AI agents for classification, sentiment analysis, and response generation

πŸ‘₯ Human-in-the-Loop Workflows

Approval processes, escalation management, and agent collaboration with role-based assignment

πŸ“Š Advanced Analytics

Real-time metrics, sentiment tracking, and performance analytics with customer satisfaction scoring

Python Agent Implementations

Here are the actual Python implementation files for the LLM agents defined in the manifest. These provide proper prompts and business logic for automated support ticket processing:

Complete Agent Implementations Include:

  • Response Generator: 400+ lines with intelligent prompt engineering and fallback responses
  • Ticket Classifier: 350+ lines with rule-based + LLM hybrid classification
  • Sentiment Analyzer: 300+ lines with multi-layered sentiment detection
  • Production Features: Error handling, confidence scoring, escalation logic

πŸ€– Response Generator Agent

File: agents/response_generator.py

  • Context-aware response generation with customer history
  • Company policy integration and template-based responses
  • Human review logic based on confidence thresholds
  • Escalation detection and suggested follow-up actions
  • LLM integration with intelligent fallback mechanisms

🏷️ Ticket Classifier Agent

File: agents/ticket_classifier.py

  • Rule-based + LLM hybrid classification approach
  • Category detection (technical, billing, urgent, feature_request)
  • Priority scoring with customer tier considerations
  • Confidence metrics and escalation recommendations
  • Estimated resolution time calculation

πŸ“Š Sentiment Analyzer Agent

File: agents/sentiment_analyzer.py

  • Multi-layered sentiment analysis (positive, neutral, negative, frustrated, angry)
  • Urgency indicator extraction with pattern recognition
  • Customer satisfaction risk assessment
  • Emotional intensity scoring and escalation risk evaluation
  • Actionable recommendations for support teams

Key Implementation Features

Example: Response Generator Core Logic

# Core response generation with context
async def run(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
    """Generate contextual support response with AI and business logic"""
    
    # Extract ticket and classification data
    ticket = input_data.get('ticket', {})
    classification = input_data.get('classification', {})
    
    # Get customer context for personalization
    customer_context = await self._get_customer_context(customer_email)
    
    # Build comprehensive prompt with company policies
    response_prompt = self._build_response_prompt(
        ticket_data, classification, customer_context, company_context
    )
    
    # Generate response using LLM with fallback
    llm_response = await self._generate_llm_response(response_prompt)
    
    # Determine human review requirements
    requires_review = self._requires_human_review(
        category, priority, sentiment, confidence, processed_response
    )
    
    return {
        "response_text": processed_response,
        "requires_human_review": requires_review,
        "suggested_actions": suggested_actions,
        "escalation_needed": escalation_needed,
        "confidence_score": confidence
    }

Example: Intelligent Classification Logic

# Hybrid classification approach
def _combine_classifications(self, rule_based: Dict, llm_based: Dict, 
                           customer_context: Dict) -> Dict[str, Any]:
    """Combine rule-based and LLM results intelligently"""
    
    # Start with rule-based baseline
    final_category = rule_based['category']
    final_confidence = rule_based['confidence']
    
    # Override with LLM if higher confidence
    if llm_based.get('confidence', 0) > final_confidence:
        final_category = llm_based.get('category', final_category)
        final_confidence = llm_based.get('confidence', final_confidence)
    
    # Premium customer tier adjustments
    if customer_context.get('tier') == 'premium':
        if final_priority == 'low':
            final_priority = 'medium'
        final_confidence = min(final_confidence + 0.1, 1.0)
    
    return final_classification

Example: Sentiment Analysis with Risk Assessment

# Advanced sentiment analysis
def _assess_satisfaction_risk(self, sentiment_data: Dict, 
                            urgency_indicators: List, escalation_risk: str) -> str:
    """Assess customer satisfaction risk level"""
    
    risk_factors = 0
    
    # Sentiment-based risk factors
    if sentiment_data['sentiment'] in ['negative', 'frustrated', 'angry']:
        risk_factors += 2
    
    # Urgency indicators increase risk
    if urgency_indicators:
        risk_factors += len(urgency_indicators)
    
    # Escalation indicators
    if escalation_risk == 'high':
        risk_factors += 3
    
    # Return risk assessment
    if risk_factors >= 5:
        return 'critical'
    elif risk_factors >= 3:
        return 'high'
    elif risk_factors >= 1:
        return 'medium'
    else:
        return 'low'

Production Implementation Notes

Key Production Features:

  • Error Handling: Comprehensive try-catch blocks with graceful degradation
  • Logging: Structured logging for monitoring and debugging
  • Confidence Scoring: All decisions include confidence metrics
  • Fallback Mechanisms: Template-based responses when LLM fails
  • Customer Context: Integration with customer history and preferences
  • Business Logic: Company policy integration and compliance
  • Scalability: Async/await patterns for high-throughput processing
  • Security: Input validation and secure API integrations

External API Integration

Python SDK Integration with API Keys

Here's how external systems can create support tickets using the Fiberwise Python SDK with proper API key authentication:

# external_support_integration.py
"""
External system integration for creating support tickets
via Fiberwise API using proper authentication
"""

import asyncio
from fiberwise import FiberwiseClient
from typing import Dict, Any, Optional

class SupportTicketIntegration:
    """
    Integration class for creating support tickets from external systems
    """
    
    def __init__(self, api_key: str, app_slug: str, base_url: str = "https://api.fiberwise.ai"):
        """
        Initialize with API credentials
        
        Args:
            api_key: Your Fiberwise API key
            app_slug: The support portal app slug
            base_url: Fiberwise API base URL
        """
        self.client = FiberwiseClient(
            api_key=api_key,
            base_url=base_url
        )
        self.app_slug = app_slug

    async def create_support_ticket(self, 
                                  customer_email: str,
                                  subject: str, 
                                  description: str,
                                  source: str = "external_api",
                                  metadata: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """
        Create a new support ticket that will be processed by AI agents
        
        Args:
            customer_email: Customer's email address
            subject: Ticket subject line
            description: Detailed description of the issue
            source: Source system identifier
            metadata: Additional metadata for the ticket
            
        Returns:
            Created ticket data with processing status
        """
        try:
            # Create the support ticket using Fiberwise data API
            ticket_data = {
                "customer_email": customer_email,
                "subject": subject,
                "description": description,
                "status": "new",  # Will trigger AI processing pipeline
                "source": source,
                "metadata": metadata or {}
            }
            
            # Call the createTicketFromAPI function
            result = await self.client.functions.invoke(
                app_slug=self.app_slug,
                function_name="createTicketFromAPI",
                input_data=ticket_data
            )
            
            if result.get('success'):
                ticket_id = result.get('ticket_id')
                
                # Wait briefly for AI processing to start
                await asyncio.sleep(1)
                
                # Get the updated ticket with AI analysis
                ticket = await self.client.data.get_item(
                    app_slug=self.app_slug,
                    model_slug="support_tickets",
                    item_id=ticket_id
                )
                
                return {
                    "success": True,
                    "ticket_id": ticket_id,
                    "ticket_data": ticket,
                    "ai_processing_started": result.get('processing_started', False),
                    "classification": {
                        "category": ticket.get('data', {}).get('category'),
                        "priority": ticket.get('data', {}).get('priority'),
                        "confidence": ticket.get('data', {}).get('confidence_score')
                    }
                }
            else:
                return {
                    "success": False,
                    "error": result.get('error', 'Unknown error creating ticket')
                }
                
        except Exception as e:
            return {
                "success": False,
                "error": f"Integration error: {str(e)}"
            }

    async def get_ticket_status(self, ticket_id: str) -> Dict[str, Any]:
        """
        Get current status and AI analysis results for a ticket
        
        Args:
            ticket_id: The ticket ID to check
            
        Returns:
            Current ticket status and AI results
        """
        try:
            ticket = await self.client.data.get_item(
                app_slug=self.app_slug,
                model_slug="support_tickets", 
                item_id=ticket_id
            )
            
            ticket_data = ticket.get('data', {})
            
            return {
                "success": True,
                "ticket_id": ticket_id,
                "status": ticket_data.get('status'),
                "priority": ticket_data.get('priority'),
                "category": ticket_data.get('category'),
                "ai_response": ticket_data.get('ai_response'),
                "human_response": ticket_data.get('human_response'),
                "escalation_required": ticket_data.get('escalation_required'),
                "assigned_agent": ticket_data.get('assigned_agent'),
                "sentiment_score": ticket_data.get('sentiment_score'),
                "confidence_score": ticket_data.get('confidence_score'),
                "resolution_time": ticket_data.get('resolution_time'),
                "satisfaction_rating": ticket_data.get('satisfaction_rating')
            }
            
        except Exception as e:
            return {
                "success": False,
                "error": f"Error retrieving ticket: {str(e)}"
            }

    async def bulk_create_tickets(self, tickets: list) -> Dict[str, Any]:
        """
        Create multiple support tickets efficiently
        
        Args:
            tickets: List of ticket dictionaries with customer_email, subject, description
            
        Returns:
            Bulk creation results with success/failure counts
        """
        results = []
        successful = 0
        failed = 0
        
        # Process tickets concurrently for efficiency
        tasks = []
        for ticket in tickets:
            task = self.create_support_ticket(
                customer_email=ticket['customer_email'],
                subject=ticket['subject'],
                description=ticket['description'],
                source=ticket.get('source', 'bulk_import'),
                metadata=ticket.get('metadata')
            )
            tasks.append(task)
        
        # Execute all tasks concurrently
        results = await asyncio.gather(*tasks, return_exceptions=True)
        
        # Count successes and failures
        for result in results:
            if isinstance(result, dict) and result.get('success'):
                successful += 1
            else:
                failed += 1
        
        return {
            "total_processed": len(tickets),
            "successful": successful,
            "failed": failed,
            "results": results
        }

# Example usage
async def main():
    """Example integration usage"""
    
    # Initialize with your API credentials
    integration = SupportTicketIntegration(
        api_key="your_api_key_here",
        app_slug="support-portal"
    )
    
    # Create a single support ticket
    result = await integration.create_support_ticket(
        customer_email="[email protected]",
        subject="Login Issues After Update",
        description="I cannot log into my account after the latest app update. Getting 'invalid credentials' error even with correct password.",
        source="mobile_app",
        metadata={"app_version": "2.1.3", "device": "iOS"}
    )
    
    if result['success']:
        print(f"Ticket created: {result['ticket_id']}")
        print(f"AI Classification: {result['classification']}")
        
        # Check status after some processing time
        await asyncio.sleep(5)
        
        status = await integration.get_ticket_status(result['ticket_id'])
        print(f"Current status: {status['status']}")
        print(f"AI Response: {status['ai_response']}")
    else:
        print(f"Failed to create ticket: {result['error']}")

if __name__ == "__main__":
    asyncio.run(main())

Advanced Development Patterns

πŸ—οΈ Architecture Patterns

  • Multi-tenant data isolation
  • Event-driven pipeline orchestration
  • Microservice-style agent composition
  • Real-time WebSocket integration

πŸ€– AI Integration Patterns

  • Multi-agent coordination
  • Confidence-based decision making
  • Human-in-the-loop workflows
  • Fallback and error handling

πŸ”„ Workflow Patterns

  • Conditional pipeline execution
  • Approval and review processes
  • Escalation management
  • Automated notifications

πŸ’Ό Enterprise Patterns

  • API-first integration
  • Audit trails and compliance
  • Performance monitoring
  • Scalable architecture design

Next Steps

πŸš€ Deploy Your App

Ready to deploy? Learn about production deployment strategies and best practices.

Deployment Guide

πŸ“š Learn More Concepts

Dive deeper into specific Fiberwise concepts and advanced features.

All Concepts

πŸ”§ API Reference

Explore the complete API documentation for advanced integrations.

API Docs

πŸ’‘ Get Help

Join our community or get support for your advanced app development.

Get Support

Ready to Build Advanced Apps?

These examples demonstrate the full power of the Fiberwise platform for enterprise applications. You now have:

  • Complete working manifests for complex applications
  • Production-ready Python agent implementations
  • Advanced UI patterns and real-time features
  • External API integration examples
  • Human workflow and approval processes

Use these as starting points for your own advanced applications, or mix and match patterns to create something entirely new!

🎫 Support Ticket Management

Dynamic data models for tickets, responses, and escalations with automatic user attribution and role-based access.

πŸ€– AI Processing Pipeline

Automatic ticket classification, sentiment analysis, response generation, and priority routing using multiple AI agents.

πŸ‘₯ Human Workflow Integration

Agent dashboard for review, approval, escalation, and manual intervention with real-time collaboration.

πŸ”— External API Integration

Secure REST API endpoints for ticket creation from external systems using Fiberwise API keys.

Complete App Manifest

# Advanced Customer Support System Manifest
app:
  name: Customer Support Portal
  app_slug: customer-support-portal
  version: 1.0.0
  description: Enterprise customer support system with AI automation and human workflows
  entryPoint: index.js
  icon: fas fa-headset
  category: productivity
  publisher: Enterprise Solutions
  
  # Data Models with Advanced Security
  models:
    - name: Support Ticket
      model_slug: support_tickets
      description: Customer support requests with AI processing
      user_isolation: enforced  # βœ… Complete user isolation - IMPLEMENTED
      fields:
        - name: Ticket ID
          field_column: ticket_id
          type: uuid
          is_primary_key: true
        - name: Customer Email
          field_column: customer_email
          type: string
          required: true
          validations:
            pattern: "^[^@]+@[^@]+\\.[^@]+$"
        - name: Subject
          field_column: subject
          type: string
          required: true
          validations:
            max_length: 200
        - name: Description
          field_column: description
          type: text
          required: true
        - name: Priority
          field_column: priority
          type: string
          default: "medium"
          validations:
            enum: ["low", "medium", "high", "urgent"]
        - name: Status
          field_column: status
          type: string
          default: "open"
          validations:
            enum: ["open", "in_progress", "waiting_customer", "resolved", "closed"]
        - name: Category
          field_column: category
          type: string
          description: "AI-determined category"
        - name: Sentiment
          field_column: sentiment
          type: string
          description: "AI-analyzed customer sentiment"
        - name: AI Analysis
          field_column: ai_analysis
          type: json
          description: "Complete AI processing results"
        - name: Assigned Agent
          field_column: assigned_agent_id
          type: integer
          description: "ID of assigned support agent"
        - name: Created At
          field_column: created_at
          type: timestamp
          default: CURRENT_TIMESTAMP
          is_system_field: true  # System timestamp field
        - name: Updated At
          field_column: updated_at
          type: timestamp
          default: CURRENT_TIMESTAMP
          is_system_field: true  # System timestamp field

    - name: Ticket Response
      model_slug: ticket_responses
      user_isolation: enforced  # βœ… Automatic user data isolation
      fields:
        - name: Response ID
          field_column: response_id
          type: uuid
          is_primary_key: true
        - name: Ticket Reference
          field_column: ticket_id
          type: uuid
          required: true
          relatedModelSlug: support_tickets
        - name: Response Text
          field_column: response_text
          type: text
          required: true
        - name: Response Type
          field_column: response_type
          type: string
          required: true
          validations:
            enum: ["ai_generated", "human_written", "template", "escalation"]
        - name: Approved By Agent
          field_column: approved_by_agent_id
          type: integer
          description: "Agent who approved this response"
        - name: Sent Status
          field_column: sent_status
          type: string
          default: "draft"
          validations:
            enum: ["draft", "approved", "sent", "failed"]
        - name: Created At
          field_column: created_at
          type: timestamp
          default: CURRENT_TIMESTAMP
          is_system_field: true  # System timestamp field

    - name: Agent Activity
      model_slug: agent_activities
      user_isolation: enforced  # βœ… Automatic user data isolation
      fields:
        - name: Activity ID
          field_column: activity_id
          type: uuid
          is_primary_key: true
        - name: Agent ID
          field_column: agent_id
          type: integer
          required: true
          description: "Platform user ID of the agent"
        - name: Ticket Reference
          field_column: ticket_id
          type: uuid
          relatedModelSlug: support_tickets
        - name: Action Type
          field_column: action_type
          type: string
          required: true
          validations:
            enum: ["viewed", "assigned", "responded", "escalated", "closed", "reopened"]
        - name: Notes
          field_column: notes
          type: text
          description: "Agent's notes about the action"
        - name: Created At
          field_column: created_at
          type: timestamp
          default: CURRENT_TIMESTAMP
          is_system_field: true  # System timestamp field

  # App Routes for Different User Roles
  routes:
    - path: /
      component: support-dashboard
      title: Support Dashboard
      icon: fas fa-tachometer-alt
    - path: /tickets
      component: ticket-list
      title: All Tickets
      icon: fas fa-list
    - path: /tickets/:ticket_id
      component: ticket-detail
      title: Ticket Details
      icon: fas fa-ticket-alt
    - path: /analytics
      component: support-analytics
      title: Analytics
      icon: fas fa-chart-bar
    - path: /settings
      component: support-settings
      title: Settings
      icon: fas fa-cog
      isOverlay: true

# AI Agents for Automated Processing
agents:
  - name: ticketClassifier
    description: Automatically categorize and prioritize support tickets
    agent_type_id: llm
    version: 1.0.0
    input_schema:
      type: object
      properties:
        subject:
          type: string
          description: Ticket subject line
        description:
          type: string
          description: Ticket description
        customer_email:
          type: string
          description: Customer email for context
    output_schema:
      type: object
      properties:
        category:
          type: string
          enum: ["technical", "billing", "general", "urgent", "feature_request"]
        priority:
          type: string
          enum: ["low", "medium", "high", "urgent"]
        confidence:
          type: number
          description: Classification confidence score
        reasoning:
          type: string
          description: Explanation of classification decision

  - name: sentimentAnalyzer
    description: Analyze customer sentiment and emotional tone
    agent_type_id: llm
    version: 1.0.0
    input_schema:
      type: object
      properties:
        ticket_content:
          type: string
          description: Combined subject and description
    output_schema:
      type: object
      properties:
        sentiment:
          type: string
          enum: ["positive", "neutral", "negative", "frustrated", "angry"]
        urgency_indicators:
          type: array
          items:
            type: string
          description: List of phrases indicating urgency
        customer_satisfaction_risk:
          type: string
          enum: ["low", "medium", "high", "critical"]

  - name: responseGenerator
    description: Generate draft responses for support tickets
    agent_type_id: llm
    version: 1.0.0
    input_schema:
      type: object
      properties:
        ticket:
          type: object
          description: Complete ticket data
        classification:
          type: object
          description: AI classification results
        company_context:
          type: object
          description: Company policies and knowledge base
    output_schema:
      type: object
      properties:
        response_text:
          type: string
          description: Generated response draft
        requires_human_review:
          type: boolean
          description: Whether response needs human approval
        suggested_actions:
          type: array
          items:
            type: string
          description: Recommended follow-up actions
        escalation_needed:
          type: boolean
          description: Whether ticket should be escalated

# Custom Functions for Business Logic
functions:
  - name: ticketNotifier
    description: Send notifications for ticket updates
    version: 1.0.0
    input_schema:
      type: object
      properties:
        ticket_id:
          type: string
        notification_type:
          type: string
          enum: ["new_ticket", "assignment", "response", "escalation", "resolution"]
        recipient_type:
          type: string
          enum: ["customer", "agent", "manager"]
        context:
          type: object
    implementation: |-
      async def run(input_data):
          ticket_id = input_data.get('ticket_id')
          notification_type = input_data.get('notification_type')
          recipient_type = input_data.get('recipient_type')
          
          # Implementation would integrate with email/SMS services
          # This is a simplified example
          
          notifications_sent = []
          
          if recipient_type == "customer":
              # Send customer notification
              notifications_sent.append({
                  "type": "email",
                  "status": "sent",
                  "recipient": "[email protected]"
              })
          
          if recipient_type == "agent" or recipient_type == "manager":
              # Send internal notifications
              notifications_sent.append({
                  "type": "internal_notification",
                  "status": "sent",
                  "recipient": "internal_team"
              })
          
          return {
              "success": True,
              "notifications_sent": notifications_sent,
              "ticket_id": ticket_id
          }

  - name: escalationHandler
    description: Handle ticket escalations and routing
    version: 1.0.0
    input_schema:
      type: object
      properties:
        ticket_id:
          type: string
        escalation_reason:
          type: string
        current_agent_id:
          type: integer
    implementation: |-
      async def run(input_data):
          ticket_id = input_data.get('ticket_id')
          escalation_reason = input_data.get('escalation_reason')
          current_agent_id = input_data.get('current_agent_id')
          
          # Logic to determine appropriate escalation target
          escalation_target = None
          
          if "billing" in escalation_reason.lower():
              escalation_target = "billing_team"
          elif "technical" in escalation_reason.lower():
              escalation_target = "technical_team"
          else:
              escalation_target = "supervisor"
          
          return {
              "success": True,
              "ticket_id": ticket_id,
              "escalated_to": escalation_target,
              "escalation_timestamp": "now",
              "previous_agent": current_agent_id
          }

# Automated Processing Pipelines
pipelines:
  - id: new_ticket_processor
    name: New Ticket Processing Pipeline
    description: Complete AI processing workflow for new support tickets
    trigger:
      type: data_event
      config:
        model: support_tickets
        event: create
    nodes:
      # Parallel AI Analysis
      - id: classify_ticket
        type: agent_executor
        config:
          agent_id: ticketClassifier
        input_mapping:
          subject: "$trigger.data.subject"
          description: "$trigger.data.description"
          customer_email: "$trigger.data.customer_email"
      
      - id: analyze_sentiment
        type: agent_executor
        config:
          agent_id: sentimentAnalyzer
        input_mapping:
          ticket_content: "$trigger.data.subject + ' ' + $trigger.data.description"
      
      # Update ticket with AI analysis
      - id: update_ticket_analysis
        type: function_executor
        config:
          function_id: updateTicketWithAnalysis
        input_mapping:
          ticket_id: "$trigger.data.ticket_id"
          classification: "$nodes.classify_ticket.output"
          sentiment: "$nodes.analyze_sentiment.output"
      
      # Generate initial response
      - id: generate_response
        type: agent_executor
        config:
          agent_id: responseGenerator
        input_mapping:
          ticket: "$trigger.data"
          classification: "$nodes.classify_ticket.output"
          company_context: "$system.company_knowledge"
      
      # Conditional routing based on priority
      - id: priority_router
        type: conditional_router
        condition: "$nodes.classify_ticket.output.priority == 'urgent' || $nodes.analyze_sentiment.output.customer_satisfaction_risk == 'critical'"
        config:
          high_priority_handler: urgent_ticket_handler
          normal_handler: standard_ticket_handler
      
      # Notifications
      - id: notify_customer
        type: function_executor
        config:
          function_id: ticketNotifier
        input_mapping:
          ticket_id: "$trigger.data.ticket_id"
          notification_type: "new_ticket"
          recipient_type: "customer"
      
      - id: notify_agents
        type: function_executor
        config:
          function_id: ticketNotifier
        input_mapping:
          ticket_id: "$trigger.data.ticket_id"
          notification_type: "new_ticket"
          recipient_type: "agent"
    
    # Define execution flow
    edges:
      # Parallel processing
      - source: classify_ticket
        target: update_ticket_analysis
      - source: analyze_sentiment
        target: update_ticket_analysis
      
      # Sequential processing
      - source: update_ticket_analysis
        target: generate_response
      - source: generate_response
        target: priority_router
      - source: priority_router
        target: notify_customer
      - source: priority_router
        target: notify_agents

# Human-in-the-Loop Workflows
workflows:
  - id: response_approval_workflow
    name: AI Response Review and Approval
    description: Human agent review of AI-generated responses
    trigger:
      type: pipeline_completion
      config:
        pipeline_id: new_ticket_processor
        condition: "$output.generate_response.requires_human_review == true"
    
    steps:
      - id: assign_to_agent
        type: assignment_step
        config:
          assignment_logic: "round_robin"  # or "workload_based", "skill_based"
          agent_pool: "support_agents"
          timeout: 300  # 5 minutes
      
      - id: agent_review
        type: human_task
        config:
          task_type: "response_review"
          ui_component: "response-review-widget"
          allowed_actions: ["approve", "modify", "escalate", "reject"]
          timeout: 1800  # 30 minutes
          data:
            original_ticket: "$trigger.ticket"
            generated_response: "$trigger.pipeline_output.generate_response.response_text"
            ai_analysis: "$trigger.pipeline_output"
      
      - id: handle_agent_decision
        type: conditional_router
        condition: "$steps.agent_review.action"
        config:
          approve_handler: send_approved_response
          modify_handler: send_modified_response
          escalate_handler: escalate_to_supervisor
          reject_handler: regenerate_response
      
      - id: send_response
        type: function_executor
        config:
          function_id: sendCustomerResponse
        input_mapping:
          ticket_id: "$trigger.ticket.ticket_id"
          response_text: "$steps.agent_review.final_response"
          agent_id: "$steps.assign_to_agent.assigned_agent_id"
      
      - id: log_activity
        type: function_executor
        config:
          function_id: logAgentActivity
        input_mapping:
          agent_id: "$steps.assign_to_agent.assigned_agent_id"
          ticket_id: "$trigger.ticket.ticket_id"
          action_type: "responded"
          notes: "$steps.agent_review.agent_notes"

External API Integration

Python SDK Integration with API Keys

Here's how external systems can create support tickets using the Fiberwise Python SDK with proper API key authentication:

# external_support_integration.py
"""
External system integration for creating support tickets
via Fiberwise API using proper authentication
"""

import os
import asyncio
from datetime import datetime
from typing import Dict, Any, Optional
import logging

# Import Fiberwise Python SDK
from fiberwise_sdk import FiberwiseClient

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class SupportTicketIntegration:
    """
    Integration class for creating support tickets from external systems
    """
    
    def __init__(self, api_key: str, base_url: str = None):
        """
        Initialize the support integration client
        
        Args:
            api_key: Fiberwise API key for authentication
            base_url: Optional custom base URL for the Fiberwise instance
        """
        self.client = FiberwiseClient(
            api_key=api_key,
            base_url=base_url or os.getenv('FIBERWISE_BASE_URL', 'https://api.fiberwise.ai')
        )
        self.app_id = "customer-support-portal"  # App slug from manifest
    
    async def create_support_ticket(
        self,
        customer_email: str,
        subject: str,
        description: str,
        priority: str = "medium",
        additional_data: Optional[Dict[str, Any]] = None
    ) -> Dict[str, Any]:
        """
        Create a new support ticket
        
        Args:
            customer_email: Customer's email address
            subject: Ticket subject line
            description: Detailed description of the issue
            priority: Ticket priority (low, medium, high, urgent)
            additional_data: Optional additional context data
        
        Returns:
            Created ticket data with ID and processing status
        """
        try:
            # Prepare ticket data
            ticket_data = {
                "customer_email": customer_email,
                "subject": subject,
                "description": description,
                "priority": priority,
                "status": "open",
                # Additional context can be included
                **(additional_data or {})
            }
            
            # Create the ticket using Fiberwise SDK
            logger.info(f"Creating support ticket for {customer_email}: {subject}")
            
            # Create item in the support_tickets model
            ticket = await self.client.data.create_item(
                app_id=self.app_id,
                model_slug="support_tickets",
                data=ticket_data
            )
            
            logger.info(f"Support ticket created successfully: {ticket['item_id']}")
            
            # The ticket creation will automatically trigger the processing pipeline
            # defined in the app manifest (new_ticket_processor)
            
            return {
                "success": True,
                "ticket_id": ticket["item_id"],
                "status": "created",
                "processing_started": True,
                "customer_email": customer_email,
                "created_at": ticket["created_at"],
                "message": "Support ticket created and AI processing initiated"
            }
            
        except Exception as e:
            logger.error(f"Failed to create support ticket: {str(e)}")
            return {
                "success": False,
                "error": str(e),
                "customer_email": customer_email
            }
    
    async def get_ticket_status(self, ticket_id: str) -> Dict[str, Any]:
        """
        Get current status of a support ticket
        
        Args:
            ticket_id: ID of the ticket to check
        
        Returns:
            Current ticket status and details
        """
        try:
            ticket = await self.client.data.get_item(
                app_id=self.app_id,
                model_slug="support_tickets",
                item_id=ticket_id
            )
            
            return {
                "success": True,
                "ticket_id": ticket_id,
                "status": ticket["data"]["status"],
                "priority": ticket["data"]["priority"],
                "category": ticket["data"].get("category"),
                "assigned_agent_id": ticket["data"].get("assigned_agent_id"),
                "last_updated": ticket["updated_at"]
            }
            
        except Exception as e:
            logger.error(f"Failed to get ticket status: {str(e)}")
            return {
                "success": False,
                "error": str(e),
                "ticket_id": ticket_id
            }
    
    async def add_customer_response(
        self,
        ticket_id: str,
        response_text: str,
        customer_email: str
    ) -> Dict[str, Any]:
        """
        Add a customer response to an existing ticket
        
        Args:
            ticket_id: ID of the existing ticket
            response_text: Customer's response/additional information
            customer_email: Customer's email for verification
        
        Returns:
            Response creation status
        """
        try:
            # Create a customer response
            response = await self.client.data.create_item(
                app_id=self.app_id,
                model_slug="ticket_responses",
                data={
                    "ticket_id": ticket_id,
                    "response_text": response_text,
                    "response_type": "customer_response",
                    "sent_status": "received"
                }
            )
            
            # Update ticket status to indicate customer response
            await self.client.data.update_item(
                app_id=self.app_id,
                model_slug="support_tickets",
                item_id=ticket_id,
                data={
                    "status": "waiting_agent",
                    "updated_at": datetime.utcnow().isoformat()
                }
            )
            
            logger.info(f"Customer response added to ticket {ticket_id}")
            
            return {
                "success": True,
                "response_id": response["item_id"],
                "ticket_id": ticket_id,
                "message": "Customer response added successfully"
            }
            
        except Exception as e:
            logger.error(f"Failed to add customer response: {str(e)}")
            return {
                "success": False,
                "error": str(e),
                "ticket_id": ticket_id
            }

# Example usage and integration patterns
async def main():
    """
    Example usage of the support ticket integration
    """
    
    # Initialize with API key (should be stored securely)
    api_key = os.getenv('FIBERWISE_API_KEY')
    if not api_key:
        logger.error("FIBERWISE_API_KEY environment variable not set")
        return
    
    support_integration = SupportTicketIntegration(api_key=api_key)
    
    # Example 1: Create a new support ticket
    ticket_result = await support_integration.create_support_ticket(
        customer_email="[email protected]",
        subject="Unable to access dashboard",
        description="""
        I'm having trouble logging into my dashboard. When I enter my 
        credentials, the page just refreshes and doesn't log me in. 
        This has been happening since yesterday.
        
        Browser: Chrome 118
        OS: Windows 11
        Account: premium_user
        """,
        priority="high",
        additional_data={
            "browser": "Chrome 118",
            "os": "Windows 11",
            "account_type": "premium_user",
            "error_first_seen": "2025-01-13"
        }
    )
    
    if ticket_result["success"]:
        ticket_id = ticket_result["ticket_id"]
        logger.info(f"Ticket created: {ticket_id}")
        
        # Example 2: Check ticket status after AI processing
        await asyncio.sleep(5)  # Wait for AI processing
        status_result = await support_integration.get_ticket_status(ticket_id)
        logger.info(f"Ticket status: {status_result}")
        
        # Example 3: Add customer follow-up
        followup_result = await support_integration.add_customer_response(
            ticket_id=ticket_id,
            response_text="I tried clearing my browser cache as suggested, but the issue persists.",
            customer_email="[email protected]"
        )
        logger.info(f"Follow-up added: {followup_result}")
    
    else:
        logger.error(f"Failed to create ticket: {ticket_result['error']}")

# Integration with web frameworks (Flask/FastAPI example)
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI(title="Support Ticket API Integration")

class TicketRequest(BaseModel):
    customer_email: str
    subject: str
    description: str
    priority: str = "medium"
    additional_data: Optional[Dict[str, Any]] = None

@app.post("/api/support/tickets")
async def create_ticket_endpoint(ticket_request: TicketRequest):
    """
    REST API endpoint for creating support tickets
    """
    api_key = os.getenv('FIBERWISE_API_KEY')
    support_integration = SupportTicketIntegration(api_key=api_key)
    
    result = await support_integration.create_support_ticket(
        customer_email=ticket_request.customer_email,
        subject=ticket_request.subject,
        description=ticket_request.description,
        priority=ticket_request.priority,
        additional_data=ticket_request.additional_data
    )
    
    if not result["success"]:
        raise HTTPException(status_code=500, detail=result["error"])
    
    return result

if __name__ == "__main__":
    # Run the example
    asyncio.run(main())

API Key Management Best Practices

πŸ” Secure API Key Storage

# Environment-based configuration
import os
from fiberwise_sdk import FiberwiseClient

# Production: Use environment variables
api_key = os.getenv('FIBERWISE_API_KEY')
base_url = os.getenv('FIBERWISE_BASE_URL', 'https://api.fiberwise.ai')

# Development: Use .env files with python-dotenv
from dotenv import load_dotenv
load_dotenv()

# Initialize client with proper error handling
try:
    client = FiberwiseClient(
        api_key=api_key,
        base_url=base_url,
        timeout=30,
        retry_attempts=3
    )
except ValueError as e:
    logger.error(f"Invalid API configuration: {e}")
    raise

πŸ”„ API Key Rotation

# API key rotation handling
class RotatingAPIKeyClient:
    def __init__(self, primary_key: str, backup_key: str = None):
        self.primary_key = primary_key
        self.backup_key = backup_key
        self.current_client = FiberwiseClient(api_key=primary_key)
    
    async def make_request(self, operation, **kwargs):
        try:
            return await operation(**kwargs)
        except AuthenticationError:
            if self.backup_key:
                logger.warning("Primary key failed, trying backup")
                self.current_client = FiberwiseClient(api_key=self.backup_key)
                return await operation(**kwargs)
            raise

Support Agent Dashboard

Real-time Agent Interface

The support dashboard provides agents with a comprehensive interface for managing tickets, reviewing AI suggestions, and collaborating with customers:

// support-dashboard.js - Advanced agent dashboard component
import htmlTemplate from './support-dashboard.html?raw';
import cssStyles from './support-dashboard.css?inline';
import { FIBER } from './index.js';

export class SupportDashboard extends HTMLElement {
    constructor() {
        super();
        this.attachShadow({ mode: 'open' });
        
        // Dashboard state
        this.currentAgent = null;
        this.activeTickets = [];
        this.selectedTicket = null;
        this.realtimeConnected = false;
        this.workflowTasks = [];
        
        // Performance tracking
        this.dashboardMetrics = {
            ticketsProcessed: 0,
            averageResponseTime: 0,
            customerSatisfaction: 0
        };
    }

    async connectedCallback() {
        // Initialize dashboard
        console.log('[SupportDashboard] Initializing agent dashboard');
        
        // Get current agent information
        await this.loadAgentProfile();
        
        // Connect to real-time updates
        await this.connectRealtime();
        
        // Load initial data
        await this.loadDashboardData();
        
        // Setup workflow task polling
        await this.initializeWorkflowHandling();
        
        // Render dashboard
        this.render();
        
        // Setup event handlers
        this.setupEventHandlers();
    }

    async loadAgentProfile() {
        try {
            // Get current user profile and role
            this.currentAgent = await FIBER.auth.getCurrentUser();
            
            // Load agent-specific settings and preferences
            const agentSettings = await FIBER.data.listItems('agent_settings', {
                filters: {
                    agent_id: this.currentAgent.id
                }
            });
            
            if (agentSettings.items.length > 0) {
                this.agentSettings = agentSettings.items[0].data;
            }
            
            console.log('[SupportDashboard] Agent profile loaded:', this.currentAgent.username);
            
        } catch (error) {
            console.error('[SupportDashboard] Failed to load agent profile:', error);
        }
    }

    async loadDashboardData() {
        try {
            // Load assigned tickets
            const assignedTickets = await FIBER.data.listItems('support_tickets', {
                filters: {
                    assigned_agent_id: this.currentAgent.id,
                    status: ['open', 'in_progress', 'waiting_customer']
                },
                sort: [{ field: 'created_at', order: 'desc' }],
                limit: 20
            });
            
            this.activeTickets = assignedTickets.items;
            
            // Load pending workflow tasks
            await this.loadPendingWorkflowTasks();
            
            // Load performance metrics
            await this.loadAgentMetrics();
            
            console.log(`[SupportDashboard] Loaded ${this.activeTickets.length} active tickets`);
            
        } catch (error) {
            console.error('[SupportDashboard] Failed to load dashboard data:', error);
        }
    }

    async loadPendingWorkflowTasks() {
        try {
            // Get tasks assigned to this agent from active workflows
            const pendingTasks = await FIBER.workflows.getAssignedTasks({
                agent_id: this.currentAgent.id,
                status: 'pending'
            });
            
            this.workflowTasks = pendingTasks.tasks;
            
            console.log(`[SupportDashboard] Found ${this.workflowTasks.length} pending workflow tasks`);
            
        } catch (error) {
            console.error('[SupportDashboard] Failed to load workflow tasks:', error);
            this.workflowTasks = []; // Fallback to empty array
        }
    }

    async connectRealtime() {
        try {
            await FIBER.realtime.connect();
            this.realtimeConnected = true;
            
            // Subscribe to ticket updates
            FIBER.realtime.subscribe('ticket_updates', (update) => {
                this.handleTicketUpdate(update);
            });
            
            // Subscribe to workflow task assignments
            FIBER.realtime.subscribe('workflow_tasks', (task) => {
                this.handleWorkflowTask(task);
            });
            
            // Subscribe to AI processing completions
            FIBER.realtime.subscribe('ai_processing', (result) => {
                this.handleAIProcessingComplete(result);
            });
            
            console.log('[SupportDashboard] Real-time connection established');
            
        } catch (error) {
            console.error('[SupportDashboard] Real-time connection failed:', error);
            this.realtimeConnected = false;
        }
    }

    async initializeWorkflowHandling() {
        // Set up periodic check for new workflow tasks
        setInterval(async () => {
            await this.loadPendingWorkflowTasks();
            this.updateWorkflowTasksUI();
        }, 30000); // Check every 30 seconds
    }

    handleTicketUpdate(update) {
        console.log('[SupportDashboard] Ticket update received:', update);
        
        const ticketId = update.ticket_id;
        const ticketIndex = this.activeTickets.findIndex(t => t.item_id === ticketId);
        
        if (ticketIndex !== -1) {
            // Update existing ticket
            this.activeTickets[ticketIndex] = { ...this.activeTickets[ticketIndex], ...update.data };
            this.updateTicketInUI(ticketId, this.activeTickets[ticketIndex]);
        } else if (update.data.assigned_agent_id === this.currentAgent.id) {
            // New ticket assigned to this agent
            this.activeTickets.unshift(update.data);
            this.addTicketToUI(update.data);
            this.showNotification('New ticket assigned', update.data.subject);
        }
    }

    handleWorkflowTask(task) {
        console.log('[SupportDashboard] Workflow task received:', task);
        
        if (task.assigned_agent_id === this.currentAgent.id) {
            this.workflowTasks.push(task);
            this.addWorkflowTaskToUI(task);
            this.showNotification('New workflow task', task.task_description);
        }
    }

    handleAIProcessingComplete(result) {
        console.log('[SupportDashboard] AI processing complete:', result);
        
        // Update ticket with AI suggestions
        const ticketId = result.ticket_id;
        const ticket = this.activeTickets.find(t => t.item_id === ticketId);
        
        if (ticket) {
            ticket.ai_analysis = result.analysis;
            ticket.ai_suggested_response = result.suggested_response;
            this.updateTicketInUI(ticketId, ticket);
            
            // Highlight tickets with new AI suggestions
            this.highlightAISuggestion(ticketId);
        }
    }

    async handleWorkflowTaskAction(taskId, action, data = {}) {
        try {
            console.log(`[SupportDashboard] Handling workflow task ${taskId} with action: ${action}`);
            
            // Execute the workflow task action
            const result = await FIBER.workflows.executeTaskAction({
                task_id: taskId,
                action: action,
                agent_id: this.currentAgent.id,
                data: data
            });
            
            if (result.success) {
                // Remove completed task from UI
                this.workflowTasks = this.workflowTasks.filter(t => t.id !== taskId);
                this.removeWorkflowTaskFromUI(taskId);
                
                this.showNotification('Task completed', `${action} action executed successfully`);
            } else {
                this.showError('Task failed', result.error);
            }
            
        } catch (error) {
            console.error(`[SupportDashboard] Failed to handle workflow task ${taskId}:`, error);
            this.showError('Task execution failed', error.message);
        }
    }

    async approveAIResponse(ticketId, responseText, modifications = null) {
        try {
            const finalResponse = modifications || responseText;
            
            // Create approved response
            const response = await FIBER.data.createItem('ticket_responses', {
                ticket_id: ticketId,
                response_text: finalResponse,
                response_type: modifications ? 'human_modified' : 'ai_approved',
                approved_by_agent_id: this.currentAgent.id,
                sent_status: 'approved'
            });
            
            // Update ticket status
            await FIBER.data.updateItem('support_tickets', ticketId, {
                status: 'waiting_customer',
                updated_at: new Date().toISOString()
            });
            
            // Send response to customer (would integrate with email service)
            await this.sendCustomerResponse(ticketId, finalResponse);
            
            // Log agent activity
            await this.logAgentActivity(ticketId, 'responded', modifications ? 'Modified and approved AI response' : 'Approved AI response');
            
            this.showNotification('Response sent', 'Customer has been notified');
            
        } catch (error) {
            console.error('[SupportDashboard] Failed to approve response:', error);
            this.showError('Failed to send response', error.message);
        }
    }

    async escalateTicket(ticketId, escalationReason, escalationNotes) {
        try {
            // Execute escalation function
            const escalationResult = await FIBER.functions.execute('escalationHandler', {
                ticket_id: ticketId,
                escalation_reason: escalationReason,
                current_agent_id: this.currentAgent.id,
                notes: escalationNotes
            });
            
            if (escalationResult.success) {
                // Update ticket status
                await FIBER.data.updateItem('support_tickets', ticketId, {
                    status: 'escalated',
                    assigned_agent_id: null, // Remove from current agent
                    escalation_reason: escalationReason,
                    escalated_by: this.currentAgent.id,
                    escalated_at: new Date().toISOString()
                });
                
                // Remove from active tickets
                this.activeTickets = this.activeTickets.filter(t => t.item_id !== ticketId);
                this.removeTicketFromUI(ticketId);
                
                // Log activity
                await this.logAgentActivity(ticketId, 'escalated', escalationNotes);
                
                this.showNotification('Ticket escalated', `Escalated to ${escalationResult.escalated_to}`);
            }
            
        } catch (error) {
            console.error('[SupportDashboard] Failed to escalate ticket:', error);
            this.showError('Escalation failed', error.message);
        }
    }

    render() {
        // Render dashboard with real-time data
        this.shadowRoot.innerHTML = `
            
            

Support Dashboard

${this.currentAgent?.username || 'Loading...'} ${this.realtimeConnected ? '🟒 Online' : 'πŸ”΄ Offline'}
${this.activeTickets.length} Active Tickets
${this.workflowTasks.length} Pending Tasks

Pending Workflow Tasks

${this.renderWorkflowTasks()}

Active Tickets

${this.renderActiveTickets()}
${this.selectedTicket ? this.renderTicketDetail(this.selectedTicket) : '

Select a ticket to view details

'}
`; this.bindEventHandlers(); } renderWorkflowTasks() { if (this.workflowTasks.length === 0) { return '

No pending workflow tasks

'; } return this.workflowTasks.map(task => `

${task.task_type}

${task.priority}

${task.task_description}

${task.ticket_context ? `
Ticket: ${task.ticket_context.subject}
` : ''}
${this.renderTaskActions(task)}
`).join(''); } renderTaskActions(task) { switch (task.task_type) { case 'response_review': return ` `; case 'escalation_approval': return ` `; default: return ` `; } } renderActiveTickets() { if (this.activeTickets.length === 0) { return '

No active tickets

'; } return this.activeTickets.map(ticket => `

${ticket.data.subject}

${ticket.data.priority} ${ticket.data.status} ${ticket.ai_suggested_response ? 'AI Ready' : ''}
${ticket.data.customer_email} ${this.formatDate(ticket.created_at)}
${ticket.data.category ? `
${ticket.data.category}
` : ''}
`).join(''); } // Additional helper methods... setupEventHandlers() { // Event handlers for dashboard interactions } selectTicket(ticketId) { this.selectedTicket = this.activeTickets.find(t => t.item_id === ticketId); this.updateTicketDetailPanel(); } formatDate(dateString) { return new Date(dateString).toLocaleDateString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }); } showNotification(title, message) { // Implementation for showing notifications console.log(`[Notification] ${title}: ${message}`); } showError(title, message) { // Implementation for showing errors console.error(`[Error] ${title}: ${message}`); } } // Register the dashboard component customElements.define('support-dashboard', SupportDashboard);

Deployment & Scaling Considerations

πŸš€ Production Deployment

  • Load Balancing: Multiple app instances for high availability
  • Database Optimization: Proper indexing for user-scoped queries
  • Caching Strategy: Redis for session management and real-time data
  • Monitoring: Application performance and AI processing metrics

πŸ“ˆ Scaling Patterns

  • Horizontal Scaling: Multiple agent dashboard instances
  • AI Processing: Distributed agent activation handling
  • Workflow Management: Queue-based task distribution
  • Data Partitioning: User-based data sharding when RLS is implemented

Performance Optimizations

# Advanced app configuration for production
app:
  name: Customer Support Portal
  performance:
    caching:
      enabled: true
      strategy: "redis"
      ttl: 300  # 5 minutes
    
    database:
      connection_pool_size: 20
      query_timeout: 30
      enable_query_caching: true
    
    realtime:
      max_connections_per_user: 5
      heartbeat_interval: 30
      reconnection_attempts: 3
    
    ai_processing:
      concurrent_activations: 10
      activation_timeout: 120
      retry_attempts: 3
    
    workflows:
      task_processing_threads: 5
      task_timeout: 1800  # 30 minutes
      escalation_timeout: 3600  # 1 hour

Advanced Development Best Practices

πŸ” Security Best Practices

  • API Key Rotation: Regular rotation with fallback mechanisms
  • Input Validation: Comprehensive validation at all entry points
  • User Context: Always verify user permissions for data access
  • Audit Logging: Complete activity trails for compliance

⚑ Performance Best Practices

  • Efficient Queries: Use indexes and limit result sets
  • Batch Operations: Group multiple operations when possible
  • Async Processing: Non-blocking operations for UI responsiveness
  • Resource Cleanup: Proper cleanup of connections and listeners

πŸ”„ Reliability Best Practices

  • Error Handling: Graceful degradation with user feedback
  • Retry Logic: Exponential backoff for failed operations
  • Circuit Breakers: Prevent cascade failures
  • Health Checks: Monitor system health and dependencies

πŸ‘₯ User Experience Best Practices

  • Real-time Feedback: Immediate response to user actions
  • Progressive Loading: Load critical data first
  • Offline Support: Handle network connectivity issues
  • Accessibility: WCAG compliance for all users

Next Steps & Advanced Topics

πŸ”§ Customize This Example

Adapt this customer support system for your specific needs:

  • Modify data models for your business requirements
  • Customize AI agents for your domain knowledge
  • Integrate with your existing customer systems
  • Add custom workflow steps and approval processes

πŸ“š Learn More

Explore additional Fiberwise platform capabilities: