Skip to content

Latest commit

 

History

History
1184 lines (938 loc) · 32.3 KB

File metadata and controls

1184 lines (938 loc) · 32.3 KB

Build AI Agents That Do Anything

**Vibe Code Your AI Agent** - Lua is built for AI-assisted development. Use Cursor, Windsurf, GitHub Copilot, or any AI coding IDE to build, test, and deploy agents fast.

Connect Your AI IDE to Lua Docs

Get instant access to Lua documentation directly in your coding environment via MCP (Model Context Protocol).

**One-click install** - Click to add Lua docs to Cursor Add `https://docs.heylua.ai/mcp` to your MCP servers Add this to your MCP configuration:
{
  "mcpServers": {
    "lua-docs": {
      "url": "https://docs.heylua.ai/mcp"
    }
  }
}

MCP Server URL: https://docs.heylua.ai/mcp

Works with: Cursor, VS Code, Claude, Windsurf, and any MCP-compatible tool.

**Complete workflow for AI IDEs** - Authentication, testing strategies, sandbox vs production, common gotchas, and the full build-test-deploy cycle optimized for Cursor, Windsurf, and GitHub Copilot.

What is Lua?

Lua is a developer platform for building AI agents that integrate with your entire business.

Write TypeScript functions that connect to any API - your CRM, payment processor, inventory system, or any third-party service - and Lua transforms them into conversational AI capabilities. Your customers chat naturally ("Where's my order?" or "Book me a table"), and your AI agent takes real actions by calling the functions you wrote.

**Built for AI IDEs** - Cursor, Windsurf, GitHub Copilot
All commands are non-interactive. Let AI write your agent.
**Your Backend** - CRM, ERP, databases
**External Services** - Stripe, Shopify, SendGrid
Full type safety with Zod validation
Live reload, testing, instant deployment

Two Powerful Products

**Build AI agents with custom capabilities using TypeScript**
The development framework for creating AI skills that connect to your APIs.

### What You Get
- TypeScript framework for building tools
- Live reload development environment
- Optional Platform APIs (Products, Baskets, Orders, Vector Search, Templates)
- 30+ working examples
- One-command deployment

### Quick Start

<CodeGroup>

```bash npm
npm install -g lua-cli
lua auth configure
lua init
lua chat
```

```bash yarn
yarn global add lua-cli
lua auth configure
lua init
lua chat
```

```bash pnpm
pnpm add -g lua-cli
lua auth configure
lua init
lua chat
```

</CodeGroup>

<Card title="Explore Lua CLI" icon="terminal" href="/getting-started/quick-start">
  Build your first AI agent in 5 minutes
</Card>
**Embeddable AI chat widget for your website**
Add your AI agent to any website with a single script tag.

### What You Get
- One-line integration (CDN or NPM)
- Fully customizable styling
- Voice chat capabilities
- Mobile-responsive
- Event tracking
- Works with any framework

### Quick Start
```html
<script src="https://lua-ai-global.github.io/lua-pop/lua-pop.umd.js"></script>
<script>
  window.LuaPop.init({
    agentId: "your-agent-id",
    position: "bottom-right"
  });
</script>
```

<Card title="Explore LuaPop Widget" icon="comments" href="/chat-widget/introduction">
  Add AI chat to your website in 2 minutes
</Card>

How It Works

Create tools that integrate with your APIs
```typescript
class OrderLookupTool implements LuaTool {
  async execute(input: { orderId: string }) {
    // Call YOUR API
    const response = await fetch(`https://your-api.com/orders/${input.orderId}`);
    return await response.json();
  }
}
```
Group related tools together
```typescript
const customerService = new LuaSkill({
  name: "customer-service",
  tools: [new OrderLookupTool(), new CreateTicketTool()]
});
```
**New in v3.0.0** - Use LuaAgent to configure everything
```typescript
export const agent = new LuaAgent({
  name: "support-assistant",
  persona: "You are a helpful customer support agent...",
  skills: [customerService]
});
```
Chat with your agent to test everything works
```bash
lua chat
```

Select sandbox mode to test with your local skills
Push to production with one command
```bash
lua push && lua deploy
```
Your users interact naturally, AI calls your tools
**User**: "What's the status of order #12345?"

**AI**: *Calls OrderLookupTool with your API* → "Your order shipped yesterday and will arrive tomorrow!"
**Testing Individual Tools**: Need to test a specific tool with exact inputs? Use `lua test` to test tools one at a time. For most development, `lua chat` is faster for testing complete workflows.

v3.0.0: Beyond Skills and Tools

The v3.0.0 release adds powerful new capabilities beyond basic skills and tools:

**Unified Configuration** - Configure your entire agent in one place
Combines persona, skills, webhooks, jobs, and processors
**HTTP Endpoints** - Receive events from external services
Stripe payments, Shopify orders, GitHub deployments, etc.
**Scheduled Tasks** - Automate recurring operations
Daily reports, cleanup jobs, monitoring with cron patterns
**Dynamic Scheduling** - Create jobs from tools at runtime
User reminders, follow-ups, deferred work
**Message Filtering** - Process messages before your agent
Spam detection, profanity filters, routing, validation
**Response Formatting** - Enhance responses after generation
Disclaimers, branding, translation, formatting

Complete v3.0.0 Example

import { 
  LuaAgent, 
  LuaSkill, 
  LuaWebhook, 
  LuaJob,
  PreProcessor,
  PostProcessor 
} from 'lua-cli';

// Skills
import { customerServiceSkill } from './skills/customer-service';
import { productSkill } from './skills/products';

// Webhooks
const paymentWebhook = new LuaWebhook({
  name: 'stripe-payment',
  execute: async (event) => {
    if (event.type === 'payment.succeeded') {
      // Handle payment confirmation
      await notifyCustomer(event.data);
    }
  }
});

// Scheduled Jobs
const dailyReportJob = new LuaJob({
  name: 'daily-report',
  schedule: { type: 'cron', pattern: '0 9 * * *' },
  execute: async (job) => {
    const user = await job.user();
    await user.send([{ type: 'text', text: 'Daily report ready!' }]);
  }
});

// Message Processing
const profanityFilter = new PreProcessor({
  name: 'profanity-filter',
  execute: async (message, user) => {
    if (containsProfanity(message.content)) {
      return { block: true, response: "Please keep it respectful." };
    }
    return { block: false };
  }
});

const addDisclaimer = new PostProcessor({
  name: 'add-disclaimer',
  execute: async (user, message, response, channel) => {
    return {
      modifiedResponse: response + "\n\n_AI-generated content for informational purposes._"
    };
  }
});

// Complete Agent Configuration
export const agent = new LuaAgent({
  name: "enterprise-assistant",
  
  persona: `You are a professional enterprise assistant.
  
Your role:
- Help with customer inquiries
- Process orders and payments
- Provide product information

Communication:
- Professional and efficient
- Clear and accurate
- Proactive and helpful`,

  
  skills: [customerServiceSkill, productSkill],
  webhooks: [paymentWebhook],
  jobs: [dailyReportJob],
  preProcessors: [profanityFilter],
  postProcessors: [addDisclaimer]
});

Learn more about v3.0.0:

Complete Flexibility: Choose Your Integration Approach

One of Lua's core strengths is flexibility. You can integrate with your existing systems, use our optional Platform APIs, or mix both approaches. Here's how each approach works:

### 100% Custom Integration
Connect directly to your existing backend, databases, and third-party services. This gives you complete control over your business logic, data, and infrastructure.

```typescript
import { LuaTool, env } from 'lua-cli';
import { z } from 'zod';

// Connect to YOUR systems
class YourCustomTool implements LuaTool {
  name = "your_custom_action";
  description = "Performs actions specific to your business";
  inputSchema = z.object({ param: z.string() });
  
  async execute(input) {
    // YOUR API
    const apiKey = env('YOUR_API_KEY');
    const response = await fetch('https://your-backend.com/api/endpoint', {
      headers: { 'Authorization': `Bearer ${apiKey}` }
    });
    
    // YOUR business logic
    const data = await response.json();
    return processYourData(data);
  }
}
```

**Perfect for:**
- Existing infrastructure and systems
- Custom business requirements
- Enterprise integrations
- Any industry or use case
- Complete control over data and logic

**Real Examples:**
- CRM: Salesforce, HubSpot, your custom CRM
- E-commerce: Shopify, WooCommerce, Magento, your custom store
- ERP: SAP, Oracle, your internal systems
- Payments: Stripe, PayPal, Square, your payment gateway
- Databases: PostgreSQL, MongoDB, MySQL, your data warehouse
### Optional Built-In Helpers
For common e-commerce and data storage needs, we provide ready-to-use APIs. These are completely optional shortcuts.

```typescript
import { Products, Baskets, Orders, Data } from 'lua-cli';

class QuickShopTool implements LuaTool {
  name = "shop_assistant";
  description = "Help users browse and purchase products";
  
  async execute(input: { query: string }) {
    // Platform APIs - no backend needed
    const products = await Products.search(input.query);
    const basket = await Baskets.create({ currency: 'USD' });
    
    // Add items to cart
    await Baskets.addItem(basket.id, {
      id: products[0].id,
      price: products[0].price,
      quantity: 1
    });
    
    return { products, basketId: basket.id };
  }
}
```

**Available Platform APIs:**
- **Products** - E-commerce catalog management
- **Baskets** - Shopping cart functionality
- **Orders** - Order processing and tracking
- **Data** - Vector search and data storage
- **User** - User profile management

**Perfect for:**
- Building e-commerce quickly
- Need vector/semantic search
- Rapid prototyping and MVPs
- Don't have backend infrastructure yet
- Want to focus on AI experience first
### Best of Both Worlds
Most production applications use a hybrid approach: your critical business systems combined with Platform helpers where they add value.

```typescript
import { Data, env } from 'lua-cli';

class HybridSearchTool implements LuaTool {
  name = "comprehensive_search";
  description = "Search across all your data sources";
  
  async execute(input: { query: string }) {
    // 1. YOUR Shopify store for products
    const shopifyProducts = await fetch(
      `https://your-store.myshopify.com/admin/api/2024-01/products.json`,
      { 
        headers: { 
          'X-Shopify-Access-Token': env('SHOPIFY_TOKEN') 
        }
      }
    ).then(r => r.json());
    
    // 2. Platform vector search for FAQs and docs
    const helpArticles = await Data.search('help_articles', input.query, 5);
    
    // 3. YOUR custom database for user history
    const userHistory = await fetch(
      `https://your-api.com/users/${input.userId}/history`,
      {
        headers: { 'Authorization': `Bearer ${env('YOUR_API_KEY')}` }
      }
    ).then(r => r.json());
    
    return {
      products: shopifyProducts.products,
      help: helpArticles.data,
      history: userHistory
    };
  }
}
```

**Perfect for:**
- Most production applications
- Pragmatic, flexible solutions
- Using best tool for each job
- Extending existing systems
- Adding AI-powered search to your stack

**Common Patterns:**
- Your product catalog + Platform vector search
- Your authentication + Platform data storage
- Your payment system + Platform product management
- Your CRM + Platform semantic search

Detailed Integration Examples

Example 1: Pure Custom - CRM Integration

Connect to your existing CRM system (Salesforce, HubSpot, or custom):

import { LuaTool, LuaSkill, env } from 'lua-cli';
import { z } from 'zod';

class GetCustomerTool implements LuaTool {
  name = "get_customer";
  description = "Look up customer in your CRM";
  inputSchema = z.object({ 
    email: z.string().email() 
  });

  async execute(input: { email: string }) {
    // Call YOUR CRM API
    const response = await fetch(
      `https://your-crm.com/api/customers/${input.email}`,
      {
        headers: { 
          'X-API-Key': env('YOUR_CRM_API_KEY'),
          'Content-Type': 'application/json'
        }
      }
    );
    
    if (!response.ok) {
      throw new Error('Customer not found');
    }
    
    return await response.json();
  }
}

class CreateTicketTool implements LuaTool {
  name = "create_ticket";
  description = "Create support ticket in your system";
  inputSchema = z.object({
    customerId: z.string(),
    subject: z.string(),
    description: z.string()
  });

  async execute(input) {
    const response = await fetch('https://your-crm.com/api/tickets', {
      method: 'POST',
      headers: {
        'X-API-Key': env('YOUR_CRM_API_KEY'),
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(input)
    });
    
    return await response.json();
  }
}

const crmSkill = new LuaSkill({
  name: "crm-integration",
  description: "Access our CRM system for customer support",
  tools: [new GetCustomerTool(), new CreateTicketTool()]
});

// Configure agent (v3.0.0)
export const agent = new LuaAgent({
  name: "crm-support-agent",
  persona: "You are a customer support specialist. Help users by looking up their information and creating support tickets when needed.",
  skills: [crmSkill]
});

Example 2: Platform APIs - Quick E-commerce

Build an e-commerce assistant using Platform APIs:

import { LuaAgent, LuaTool, LuaSkill, Products, Baskets } from 'lua-cli';
import { z } from 'zod';

class ShopAssistantTool implements LuaTool {
  name = "add_to_cart";
  description = "Add product to shopping cart";
  inputSchema = z.object({
    productId: z.string(),
    quantity: z.number().min(1)
  });
  
  async execute(input: { productId: string; quantity: number }) {
    // Use Platform APIs
    const product = await Products.getById(input.productId);
    const basket = await Baskets.create({ currency: 'USD' });
    
    await Baskets.addItem(basket.id, {
      id: input.productId,
      price: product.price,
      quantity: input.quantity
    });
    
    return { 
      basketId: basket.id,
      product: product.name,
      quantity: input.quantity,
      total: product.price * input.quantity
    };
  }
}

const shopSkill = new LuaSkill({
  name: "shop-assistant",
  description: "Help users shop and add items to cart",
  tools: [new ShopAssistantTool()]
});

// Configure agent (v3.0.0)
export const agent = new LuaAgent({
  name: "shop-assistant",
  persona: "You are a friendly shopping assistant. Help users find products and add them to their cart.",
  skills: [shopSkill]
});

Example 3: Hybrid - Real Business Solution

Combine your systems with Platform helpers:

import { LuaAgent, LuaSkill, LuaTool, Data, env } from 'lua-cli';
import { z } from 'zod';

class CompleteSearchTool implements LuaTool {
  name = "smart_search";
  description = "Search across all data sources intelligently";
  inputSchema = z.object({
    query: z.string(),
    userId: z.string().optional()
  });
  
  async execute(input: { query: string; userId?: string }) {
    // 1. Search YOUR product API/database
    const yourProducts = await fetch('https://your-api.com/search', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${env('YOUR_API_KEY')}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ query: input.query })
    }).then(r => r.json());
    
    // 2. Use Platform vector search for FAQs and documentation
    const faqResults = await Data.search('faqs', input.query, 5, 0.7);
    
    // 3. If user provided, get their purchase history from YOUR system
    let userHistory = null;
    if (input.userId) {
      userHistory = await fetch(
        `https://your-api.com/users/${input.userId}/purchases`,
        {
          headers: { 'Authorization': `Bearer ${env('YOUR_API_KEY')}` }
        }
      ).then(r => r.json());
    }
    
    // 4. Combine and return all results
    return {
      products: yourProducts,
      faqs: faqResults.map(e => ({ id: e.id, question: e.question, answer: e.answer })),
      userHistory,
      message: `Found ${yourProducts.length} products and ${faqResults.length} help articles`
    };
  }
}

const hybridSkill = new LuaSkill({
  name: "hybrid-search",
  description: "Search across all your systems and our platform",
  tools: [new CompleteSearchTool()]
});

// Configure agent (v3.0.0)
export const agent = new LuaAgent({
  name: "hybrid-assistant",
  persona: "You are a comprehensive search assistant. Help users find information across products, FAQs, and their history.",
  skills: [hybridSkill]
});

Real-World Use Cases

Lua can power AI agents for virtually any industry or use case. Here are some common scenarios:

**Shopping Assistant**
- Product search and recommendations
- Cart management and checkout
- Order tracking and updates
- Customer support and FAQs

**Integrate with:** Shopify, WooCommerce, Magento, your custom store, or Platform APIs
**24/7 AI Support Agent**
- Ticket creation and management
- Knowledge base search
- Order lookups and status updates
- Escalation to human agents

**Integrate with:** Zendesk, Freshdesk, Intercom, your ticketing system
**In-App AI Assistant**
- User onboarding and tutorials
- Feature guidance and help
- Account management
- Usage analytics and insights

**Integrate with:** Your product APIs, analytics platforms, auth systems
**AI-Powered Operations**
- Access ERP, CRM, and databases
- Generate reports and analytics
- Automate workflows
- Data lookups and updates

**Integrate with:** Your internal systems, SAP, Oracle, Salesforce
**Account Management**
- Balance inquiries and transfers
- Transaction history
- Payment processing
- Report generation

**Integrate with:** Your banking APIs, Stripe, Plaid, accounting systems
**Patient Portal Assistant**
- Appointment scheduling
- Prescription lookups
- Doctor directory search
- Health record access

**Integrate with:** Your EMR, appointment systems, patient databases
**Employee Assistant**
- Policy and benefits search
- Leave requests and approvals
- Onboarding support
- Document access

**Integrate with:** BambooHR, Workday, your HR systems
**Shipping & Tracking**
- Multi-carrier tracking
- Shipping quotes and labels
- Delivery status updates
- Route optimization

**Integrate with:** UPS, FedEx, USPS APIs, your logistics system

Why Developers Love Lua

Built for AI-assisted development. All CLI commands are non-interactive, meaning Cursor, Windsurf, GitHub Copilot, and other AI coding tools can execute commands directly. Connect docs via MCP for instant context. Build agents faster with AI helping you code. Build on your own infrastructure. Integrate with any API you choose. Not tied to our Platform APIs - they're completely optional. Your data stays with your systems, your authentication remains yours. Live reload during development means instant feedback. TypeScript autocomplete guides you. Test your agent with `lua chat` immediately. Deploy with one command. Build in minutes what would take days with other platforms. Your code, your logic, your data. Complete control over authentication, business rules, error handling, and integrations. Not limited by platform constraints - if you can code it in TypeScript, you can build it. Version management built-in. Sandbox for testing before production. Environment variables for secrets. One-command deployment. Monitoring and logs. Everything you need for enterprise production use. Actual TypeScript code, not YAML configs or no-code builders. Zod validation for type-safe inputs. Proper testing with `lua test` and `lua chat`. Modern dev workflow you already know. Platform APIs available when you need quick e-commerce or vector search. But they're completely optional - use them or don't, it's your choice. Most developers use a hybrid approach.

Platform Architecture

Understanding how Lua works helps you build better agents:

Skills and Tools

Tools are TypeScript classes that implement LuaTool:

  • Each tool performs one specific action
  • Tools have names, descriptions, and input schemas
  • The AI decides when to call each tool based on context

Skills are bundles of related tools:

  • Group tools that work together
  • Each skill can have multiple tools
  • Skills can be versioned and deployed independently

Development Workflow

# Local development with live reload
lua chat

# Test specific tools with exact inputs
lua test

# Push your code to the cloud
lua push

# Deploy to production
lua deploy

# Or combine push and deploy
lua push && lua deploy

Testing Strategies

Interactive Testing (lua chat):

  • Best for testing complete workflows
  • Chat naturally and see tools called in real-time
  • Choose sandbox mode to test local code before deploying
  • Fast iteration during development

Individual Tool Testing (lua test):

  • Test specific tools with exact inputs
  • Useful for debugging edge cases
  • Validates schemas and error handling
  • Good for automated testing

Security and Best Practices

Environment Variables

Always use environment variables for API keys and secrets:

import { env } from 'lua-cli';

const apiKey = env('YOUR_API_KEY');
const dbPassword = env('DATABASE_PASSWORD');

Set environment variables with:

lua env set YOUR_API_KEY "your-key-here"

Error Handling

Implement proper error handling in your tools:

class SafeTool implements LuaTool {
  async execute(input) {
    try {
      const response = await fetch('https://api.example.com/data');
      
      if (!response.ok) {
        throw new Error(`API error: ${response.status}`);
      }
      
      return await response.json();
    } catch (error) {
      // Log error for debugging
      console.error('Tool execution failed:', error);
      
      // Return user-friendly message
      return {
        error: true,
        message: 'Sorry, I encountered an issue. Please try again.'
      };
    }
  }
}

Input Validation

Use Zod schemas for type-safe validation:

import { z } from 'zod';

class ValidatedTool implements LuaTool {
  inputSchema = z.object({
    email: z.string().email(),
    amount: z.number().positive(),
    date: z.string().datetime()
  });
  
  async execute(input) {
    // Input is guaranteed to match schema
    // TypeScript knows the types
  }
}

Feature Highlights

REST, GraphQL, WebSockets - integrate with anything callable from TypeScript Full type safety with autocomplete and IntelliSense Instant feedback during development with auto-recompilation Ready-to-use helpers for e-commerce and vector search Voice interactions built into LuaPop widget Production deployment in seconds

Get Started

**For Cursor, Windsurf, Copilot** - Complete workflow for AI IDEs
Non-interactive commands, testing strategies, deployment

→ Best for vibe coding

<Card title="🛠️ Quick Start Tutorial" icon="code" href="/getting-started/quick-start"

**Lua CLI** - Create AI agents that integrate with your APIs

Install CLI, write TypeScript tools, deploy instantly

→ 5 minute quick start

<Card title="💬 Add Chat Widget" icon="comments" href="/chat-widget/quick-start"

**LuaPop Widget** - Embed AI chat on your website

One script tag, fully customizable, works anywhere

→ 2 minute setup

<Card title="📚 Connect Docs to Your IDE" icon="plug" href="#connect-your-ai-ide-to-lua-docs"

**MCP Server** - Get Lua docs in Cursor, VS Code, Claude

One-click install for instant documentation access

→ Scroll up for setup

Learning Path

Learn how Lua enables AI agents to take real actions through your code
<Card title="Skills and Tools" icon="book" href="/concepts/skills-and-tools" />
Follow a complete tutorial from installation to deployment
<Card title="First Skill Tutorial" icon="graduation-cap" href="/getting-started/first-skill" />
See examples of external APIs, Platform APIs, and hybrid approaches
<Card title="API Integration Guide" icon="plug" href="/concepts/platform-apis" />
Add the chat widget to your website and go live
<Card title="Chat Widget Setup" icon="rocket" href="/chat-widget/installation" />

Popular Resources

Get your first AI agent running in 5 minutes Learn how to integrate with your APIs or use Platform APIs Full documentation for all classes and methods External APIs, Platform APIs, and hybrid approaches Complete command reference and workflows Add AI chat to your website in 2 minutes

Featured Demos

See complete, production-ready implementations:

Complete shopping experience with cart and checkout
**Uses:** Platform APIs (Products, Baskets, Orders)

<Card title="Customer Support" icon="headset" href="/demos/customer-support"

Zendesk integration with AI knowledge base

**Uses:** Zendesk API + Platform Data (vector search)

<Card title="Financial Onboarding" icon="building-columns" href="/demos/financial-onboarding"

KYC verification with document upload

**Uses:** Stripe Identity + Platform Data

<Card title="HR Assistant" icon="user-tie" href="/demos/hr-assistant"

Employee management and policy search

**Uses:** BambooHR + Platform Data

<Card title="Logistics Tracker" icon="truck" href="/demos/logistics-tracker"

Multi-carrier shipping (UPS, FedEx, USPS)

**Uses:** Multiple external APIs

<Card title="View All 11 Demos" icon="layer-group" href="/demos/overview"

Customer-facing and internal agent solutions

**See:** Complete code for all use cases

Enterprise Features

Token-based auth, HTTPS only, secure environment variables, session isolation Auto-scaling infrastructure, CDN delivery, WebSocket optimization GDPR ready, SOC 2 compliant, data residency options, audit logs Technical support, migration assistance, dedicated success team

Need Help?

Chat with other builders and get real-time help Complete guides and tutorials Email our team

<Card title="Ready to Build Your First Agent?" icon="rocket" href="/getting-started/quick-start" horizontal

Complete quick start tutorial with step-by-step instructions →