Code Examples

Code Examples & Best Practices

Production-ready code samples, integration patterns, and best practices. Copy, customize, and deploy with confidence.

Browse by Category

Organized examples from beginner to advanced

Getting Started

Create Your First Agent

Basic agent setup with knowledge source and web deployment

TypeScriptBeginner5 min

Upload Knowledge Sources

Add documents, PDFs, and web pages to your agent

PythonBeginner10 min

Multi-Channel Deployment

Deploy same agent to website, WhatsApp, and Instagram

TypeScriptIntermediate15 min

Integrations

Lead Qualification Workflow

Automatically qualify and format leads for export

PythonIntermediate20 min

Calendar Integration

Sync appointments with Google Calendar and Calendly

TypeScriptIntermediate25 min

Email Automation

Trigger email sequences based on conversation outcomes

PythonAdvanced30 min

Advanced Workflows

Multi-Step Booking Flow

Complete hotel reservation workflow with payment

TypeScriptAdvanced45 min

Hierarchical RAG Setup

Multi-location knowledge bases for franchise businesses

PythonAdvanced40 min

Custom Webhook Handlers

Build real-time event processors with signature verification

GoAdvanced35 min

Sample Code

Copy and paste these examples into your project

Run Prompt with Variables

TypeScriptPrompts
import { HyperleapClient } from '@hyperleapai/sdk';

const client = new HyperleapClient({
  apiKey: process.env.HYPERLEAP_API_KEY
});

// Run a prompt with dynamic replacements
const result = await client.runPrompt({
  promptId: 'prompt_email_writer',
  promptVersionId: 'version_latest',
  replacements: {
    tone: 'professional',
    topic: 'quarterly performance review',
    audience: 'executive team'
  }
});

console.log('Generated email:', result.message);

// Collect feedback on the result
await client.setPromptRunScore(result.promptRunId, {
  score: 5,
  feedback: 'Clear and concise',
  labels: ['accurate', 'professional']
});

RAG with Document Upload

PythonKnowledge
from hyperleap import Hyperleap
import os

client = Hyperleap(api_key=os.environ["HYPERLEAP_API_KEY"])

# Upload a PDF knowledge source
with open("product_catalog.pdf", "rb") as f:
    source = client.sources.create(
        file=f,
        name="Product Catalog 2025",
        description="Complete product documentation",
        metadata={
            "version": "2.0",
            "department": "sales",
            "last_updated": "2025-01-15"
        }
    )

print(f"Source ID: {source.id}")
print(f"Processing status: {source.status}")
print(f"Chunks created: {source.chunk_count}")

# Wait for processing
while source.status == "processing":
    time.sleep(2)
    source = client.sources.get(source.id)

# Attach to agent
agent = client.agents.update(
    agent_id="agent_abc123",
    sources=[source.id, "doc_existing_faq"]
)

print("Knowledge source attached successfully!")

Persona Conversation

TypeScriptPersonas
import { HyperleapClient } from '@hyperleapai/sdk';

const client = new HyperleapClient({
  apiKey: process.env.HYPERLEAP_API_KEY
});

async function chatWithPersona() {
  // Create a persona conversation
  const conversation = await client.createPersonaConversation({
    personaId: 'persona_support_agent',
    personaVersionId: 'version_v1',
    replacements: {
      company_name: 'Acme Inc',
      support_tier: 'premium'
    }
  });

  console.log('Conversation started:', conversation.id);

  // Send a message
  const response = await client.continueConversation(conversation.id, {
    message: 'I need help resetting my password'
  });

  console.log('AI Response:', response.message);

  // Continue the conversation with context
  const followUp = await client.continueConversation(conversation.id, {
    message: 'What email should I use?'
  });

  console.log('Follow-up:', followUp.message);

  // Score the conversation quality
  await client.setConversationScore(conversation.id, {
    score: 5,
    feedback: 'Very helpful and clear',
    labels: ['helpful', 'professional']
  });
}

chatWithPersona();

Lead Qualification Workflow

PythonWorkflows
from hyperleap import Hyperleap
import os

client = Hyperleap(api_key=os.environ["HYPERLEAP_API_KEY"])

# Set up automation workflow
workflow = client.workflows.create(
    name="Lead Capture & Scoring",
    trigger="conversation.lead_captured",
    actions=[
        {
            "type": "data.process_lead",
            "config": {
                "format": "json",
                "validate_phone": True
            },
            "field_mapping": {
                "firstname": "{{lead.first_name}}",
                "lastname": "{{lead.last_name}}",
                "email": "{{lead.email}}",
                "phone": "{{lead.phone}}",
                "lead_source": "Hyperleap Chatbot",
                "lead_score": "{{lead.qualification_score}}",
                "notes": "{{conversation.summary}}"
            }
        },
        {
            "type": "notification.email",
            "to": "sales-team@company.com",
            "subject": "Hot Lead: {{lead.name}} (Score: {{lead.qualification_score}})",
            "template": "new_lead_notification",
            "conditions": {
                "if": "{{lead.qualification_score}} > 70"
            }
        }
    ]
)

print(f"Workflow created: {workflow.id}")

Streaming Prompt Response

TypeScriptPrompts
import { HyperleapClient } from '@hyperleapai/sdk';

const client = new HyperleapClient({
  apiKey: process.env.HYPERLEAP_API_KEY
});

async function streamPrompt() {
  // Stream a long-form prompt response
  await client.runPromptSSE(
    {
      promptId: 'prompt_article_writer',
      promptVersionId: 'version_002',
      replacements: {
        topic: 'The Future of AI in Healthcare',
        word_count: '500',
        style: 'informative and accessible'
      }
    },
    (event) => {
      if (event.type === 'chunk') {
        // Display content in real-time
        process.stdout.write(event.content);
      } else if (event.type === 'done') {
        console.log('\n✓ Article complete!');
      } else if (event.type === 'error') {
        console.error('Error:', event.error);
      }
    }
  );
}

streamPrompt();

Streaming Persona Conversation

TypeScriptPersonas
import { HyperleapClient } from '@hyperleapai/sdk';

const client = new HyperleapClient({
  apiKey: process.env.HYPERLEAP_API_KEY
});

async function streamConversation() {
  // Create persona conversation
  const conversation = await client.createPersonaConversation({
    personaId: 'persona_creative_writer',
    personaVersionId: 'version_001',
    replacements: {
      genre: 'science fiction',
      style: 'descriptive and immersive'
    }
  });

  console.log('Conversation ID:', conversation.id);

  // Stream the persona's response
  await client.continueConversationSSE(
    conversation.id,
    {
      message: 'Write the opening paragraph about first contact with aliens'
    },
    (event) => {
      if (event.type === 'chunk') {
        process.stdout.write(event.content);
      } else if (event.type === 'done') {
        console.log('\n✓ Response complete!');
      }
    }
  );

  // Score the message quality
  await client.setMessageScore({
    conversationId: conversation.id,
    messageId: event.messageId,
    score: 5,
    feedback: 'Very creative and engaging'
  });
}

streamConversation();

Best Practices

Production-ready guidelines for building reliable applications

Error Handling

  • Always wrap API calls in try-catch blocks
  • Implement exponential backoff for retries
  • Log errors with context for debugging
  • Provide user-friendly error messages
  • Monitor error rates in production

Security

  • Never expose API keys in client-side code
  • Use environment variables for secrets
  • Rotate API keys every 90 days
  • Verify webhook signatures
  • Implement rate limiting on your endpoints

Performance

  • Cache agent responses when appropriate
  • Use pagination for large data sets
  • Implement connection pooling
  • Monitor API response times
  • Batch operations where possible

Testing

  • Test with multiple user scenarios
  • Validate webhook payloads
  • Use staging environment before production
  • Monitor conversation quality metrics
  • A/B test different prompts

Need Implementation Help?

Our solutions engineers can help you build custom integrations and workflows.