Code Examples

Ready-to-use code examples for common integration patterns with Core and Business APIs.

Basic Agent Creation

Create a simple customer support agent with knowledge.

Basic Agent Creation Example
import { RodgerClient } from '@rodger-ai/sdk';

const client = new RodgerClient({
  apiKey: process.env.RODGER_API_KEY,
  apiUrl: 'https://api.rodger.ai'
});

async function createSupportAgent() {
  // Create the agent
  const agent = await client.createPersona({
    name: 'Customer Support Agent',
    instructions: `You are a helpful customer support agent for Acme Corp.
      - Always be polite and professional
      - Provide accurate information from the knowledge base
      - If you don't know something, ask the customer to contact human support`,
    traits: ['helpful', 'professional', 'patient'],
    guardrails: ['no_personal_info', 'stay_on_topic'],
    model: 'gpt-4'
  });

  // Add knowledge sources
  await client.addKnowledge(agent.id, {
    type: 'url',
    source: 'https://help.acmecorp.com',
    metadata: { title: 'Help Documentation' }
  });

  await client.addKnowledge(agent.id, {
    type: 'text',
    source: `Common Issues:
      - Password reset: Users can reset passwords via the forgot password link
      - Account locked: Contact support for account unlock requests
      - Billing issues: Check the billing section in account settings`,
    metadata: { title: 'Common Issues Guide' }
  });

  return agent;
}

// Usage
const agent = await createSupportAgent();
console.log('Agent created:', agent.id);

Simple Chat Interface

Build a basic chat interface with session management.

Chat Interface Implementation
async function handleChat(agentId: string, userId: string, message: string) {
  try {
    const response = await client.query(agentId, {
      message: message,
      sessionId: `user-${userId}`, // Maintain conversation context
      stream: false // Set to true for streaming responses
    });

    return {
      success: true,
      message: response.message,
      sessionId: response.sessionId
    };
  } catch (error) {
    console.error('Chat error:', error);
    return {
      success: false,
      error: 'Failed to get response from agent'
    };
  }
}

// Usage in a chat application
const result = await handleChat(
  'agent-123',
  'user-456', 
  'How do I reset my password?'
);

if (result.success) {
  console.log('Agent response:', result.message);
} else {
  console.error('Error:', result.error);
}

Team Management

Set up teams with availability and routing using Business API.

Team Management Example
async function setupCustomerSupportTeam() {
  // Create a team using Business API
  const team = await client.createTeam({
    name: 'Customer Support Team',
    description: 'Handles all customer inquiries',
    members: [
      { email: 'alice@company.com', role: 'agent' },
      { email: 'bob@company.com', role: 'supervisor' }
    ]
  });

  // Set team availability
  await client.updateTeamAvailability(team.id, {
    timezone: 'America/New_York',
    schedule: {
      monday: { start: '09:00', end: '17:00' },
      tuesday: { start: '09:00', end: '17:00' },
      wednesday: { start: '09:00', end: '17:00' },
      thursday: { start: '09:00', end: '17:00' },
      friday: { start: '09:00', end: '17:00' }
    }
  });

  // Configure routing rules
  await client.updateTeamRouting(team.id, {
    strategy: 'round_robin',
    fallback_agent_id: 'ai-agent-123', // AI agent handles off-hours
    max_queue_size: 10
  });

  return team;
}

Analytics Integration

Track performance and run A/B tests with Business API.

Analytics & A/B Testing Example
async function runPerformanceAnalysis() {
  // Get overall analytics
  const analytics = await client.getAnalytics({
    timeframe: '7d',
    metrics: ['conversations', 'satisfaction', 'response_time'],
    groupBy: 'agent'
  });

  // Create A/B test
  const abTest = await client.createABTest({
    name: 'Formal vs Casual Tone',
    description: 'Test which tone performs better',
    agents: {
      variant_a: 'formal-agent-id',
      variant_b: 'casual-agent-id'
    },
    traffic_split: 50, // 50/50 split
    success_metric: 'satisfaction_score'
  });

  // Start the test
  await client.startABTest(abTest.id);

  // Check results after sufficient data
  setTimeout(async () => {
    const results = await client.getABTestResults(abTest.id);
    if (results.statistical_significance >= 0.95) {
      console.log('Test completed with significance:', results);
      
      // Stop test and implement winner
      await client.stopABTest(abTest.id);
    }
  }, 24 * 60 * 60 * 1000); // Check after 24 hours

  return { analytics, abTest };
}

Error Handling

Proper error handling patterns for production applications.

Error Handling Example
import { RodgerError } from '@rodger-ai/sdk';

async function robustQuery(agentId: string, message: string) {
  try {
    const response = await client.query(agentId, { message });
    return { success: true, data: response };
  } catch (error) {
    if (error instanceof RodgerError) {
      switch (error.code) {
        case 'RATE_LIMIT_EXCEEDED':
          return { success: false, error: 'Too many requests, please try again later' };
        case 'AGENT_NOT_FOUND':
          return { success: false, error: 'Agent not found or not accessible' };
        case 'INSUFFICIENT_QUOTA':
          return { success: false, error: 'API quota exceeded, please upgrade your plan' };
        default:
          return { success: false, error: error.message };
      }
    }
    return { success: false, error: 'Unexpected error occurred' };
  }
}