Code Examples

    Ready-to-use examples and tutorials

    Code Samples
    Tutorials
    Best Practices

    Email Assistant Agent

    javascript
    Beginner

    Create an AI agent that can draft, send, and manage emails

    Communication
    javascript
    import { FantomuClient } from '@fantomu/sdk';
    
    const client = new FantomuClient({
      apiKey: process.env.FANTOMU_API_KEY
    });
    
    // Create email assistant agent
    const emailAgent = await client.agents.create({
      name: 'Email Assistant',
      description: 'AI agent for email management and drafting',
      capabilities: [
        'email_drafting',
        'email_scheduling', 
        'email_analysis',
        'contact_management'
      ]
    });
    
    // Draft a professional email
    const emailDraft = await emailAgent.execute({
      task: 'Draft a professional follow-up email',
      context: {
        recipient: 'client@example.com',
        subject: 'Project Update - Q1 Review',
        tone: 'professional',
        previousEmails: 2,
        meetingDate: '2024-01-15'
      }
    });
    
    console.log('Email Draft:', emailDraft.result);
    
    // Schedule email for later
    await emailAgent.execute({
      task: 'Schedule this email to be sent tomorrow at 9 AM',
      context: {
        emailContent: emailDraft.result,
        sendTime: '2024-01-16T09:00:00Z'
      }
    });

    Data Analysis Agent

    python
    Intermediate

    Build an agent that can analyze data and generate insights

    Analytics
    python
    from fantomu import FantomuClient
    import pandas as pd
    import json
    
    client = FantomuClient(api_key="your-api-key")
    
    # Create data analysis agent
    analysis_agent = client.agents.create(
        name="Data Analysis Assistant",
        description="AI agent for data analysis and insights generation",
        capabilities=[
            "data_analysis",
            "statistical_analysis", 
            "visualization_recommendations",
            "insight_generation"
        ]
    )
    
    # Load your dataset
    df = pd.read_csv('sales_data.csv')
    
    # Analyze the data
    analysis_result = analysis_agent.execute(
        task="Analyze this sales data and provide key insights",
        context={
            "data_summary": {
                "rows": len(df),
                "columns": list(df.columns),
                "date_range": f"{df['date'].min()} to {df['date'].max()}"
            },
            "sample_data": df.head().to_dict(),
            "analysis_type": "sales_performance"
        }
    )
    
    print("Analysis Results:")
    print(analysis_result.result)
    
    # Generate visualization recommendations
    viz_recommendations = analysis_agent.execute(
        task="Recommend the best visualizations for this data",
        context={
            "data_columns": list(df.columns),
            "analysis_insights": analysis_result.result
        }
    )
    
    print("\nVisualization Recommendations:")
    print(viz_recommendations.result)

    Customer Support Bot

    javascript
    Intermediate

    Create an intelligent customer support agent

    Support
    javascript
    import { FantomuClient } from '@fantomu/sdk';
    
    const client = new FantomuClient({
      apiKey: process.env.FANTOMU_API_KEY
    });
    
    // Create customer support agent
    const supportAgent = await client.agents.create({
      name: 'Customer Support Bot',
      description: 'AI agent for handling customer inquiries and support tickets',
      capabilities: [
        'ticket_classification',
        'response_generation',
        'escalation_detection',
        'knowledge_base_search'
      ]
    });
    
    // Handle incoming support ticket
    async function handleSupportTicket(ticket) {
      // Classify the ticket
      const classification = await supportAgent.execute({
        task: 'Classify this support ticket by priority and category',
        context: {
          ticketId: ticket.id,
          subject: ticket.subject,
          description: ticket.description,
          customerTier: ticket.customerTier
        }
      });
    
      console.log('Ticket Classification:', classification.result);
    
      // Generate response based on classification
      const response = await supportAgent.execute({
        task: 'Generate an appropriate response for this support ticket',
        context: {
          ticketClassification: classification.result,
          ticketDetails: ticket,
          knowledgeBase: await getKnowledgeBase(),
          escalationThreshold: 'high_priority'
        }
      });
    
      // Check if escalation is needed
      const escalationCheck = await supportAgent.execute({
        task: 'Determine if this ticket needs human escalation',
        context: {
          ticketClassification: classification.result,
          response: response.result,
          customerSatisfaction: ticket.customerSatisfaction
        }
      });
    
      return {
        ticketId: ticket.id,
        classification: classification.result,
        response: response.result,
        needsEscalation: escalationCheck.result.needsEscalation
      };
    }
    
    // Example usage
    const ticket = {
      id: 'TICKET-12345',
      subject: 'Unable to access my account',
      description: 'I keep getting an error when trying to log in...',
      customerTier: 'premium'
    };
    
    const result = await handleSupportTicket(ticket);
    console.log('Support Ticket Result:', result);

    Content Generation Pipeline

    python
    Advanced

    Build a multi-agent system for content creation

    Content
    python
    from fantomu import FantomuClient
    import asyncio
    
    client = FantomuClient(api_key="your-api-key")
    
    # Create specialized agents
    research_agent = client.agents.create(
        name="Research Agent",
        description="Agent specialized in research and fact-checking",
        capabilities=["web_research", "fact_checking", "source_verification"]
    )
    
    writer_agent = client.agents.create(
        name="Content Writer",
        description="Agent specialized in content writing and editing",
        capabilities=["content_writing", "editing", "seo_optimization"]
    )
    
    editor_agent = client.agents.create(
        name="Editor Agent", 
        description="Agent specialized in proofreading and quality control",
        capabilities=["proofreading", "grammar_check", "style_consistency"]
    )
    
    async def create_content_pipeline(topic, requirements):
        """Multi-agent content creation pipeline"""
        
        # Step 1: Research
        research_result = await research_agent.execute(
            task="Research comprehensive information about this topic",
            context={
                "topic": topic,
                "requirements": requirements,
                "sources_needed": 5,
                "fact_check_required": True
            }
        )
        
        print("Research completed:", research_result.result)
        
        # Step 2: Content Writing
        content_result = await writer_agent.execute(
            task="Write high-quality content based on the research",
            context={
                "topic": topic,
                "research_data": research_result.result,
                "requirements": requirements,
                "target_audience": requirements.get("audience", "general"),
                "content_type": requirements.get("type", "article")
            }
        )
        
        print("Content written:", content_result.result)
        
        # Step 3: Editing and Quality Control
        edit_result = await editor_agent.execute(
            task="Edit and improve the content for quality and consistency",
            context={
                "original_content": content_result.result,
                "research_sources": research_result.result,
                "style_guide": requirements.get("style_guide", "professional"),
                "word_count_target": requirements.get("word_count", 1000)
            }
        )
        
        print("Content edited:", edit_result.result)
        
        return {
            "research": research_result.result,
            "draft": content_result.result,
            "final": edit_result.result
        }
    
    # Example usage
    topic = "The Future of AI in Healthcare"
    requirements = {
        "type": "blog_post",
        "audience": "healthcare_professionals",
        "word_count": 1500,
        "style_guide": "professional"
    }
    
    result = await create_content_pipeline(topic, requirements)
    print("Content Pipeline Complete!")

    Ready to Build Your Own?

    Start with these examples and customize them for your specific use case