Code Examples

Real-world examples to help you integrate Meebly AI into your applications.

React Chat Widget

Build a streaming chat interface with React:

tsx
import { useState } from 'react';

export function ChatWidget({ apiKey, agentId, environmentId }) {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);

  const sendMessage = async (content) => {
    setIsLoading(true);
    setMessages(prev => [...prev, { role: 'user', content }]);

    try {
      const response = await fetch('https://api.meebly.ai/v1/chat', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-API-Key': apiKey
        },
        body: JSON.stringify({
          agentId,
          environmentId,
          messages: [{ content }]
        })
      });

      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let assistantMessage = '';

      while (true) {
        const { value, done } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value);
        const lines = chunk.split('\n');

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const data = JSON.parse(line.substring(6));
            
            if (data.type === 'chunk') {
              assistantMessage += data.data;
              setMessages(prev => {
                const newMessages = [...prev];
                const lastIndex = newMessages.length - 1;
                
                if (newMessages[lastIndex]?.role === 'assistant') {
                  newMessages[lastIndex].content = assistantMessage;
                } else {
                  newMessages.push({ 
                    role: 'assistant', 
                    content: assistantMessage 
                  });
                }
                
                return newMessages;
              });
            }
          }
        }
      }
    } catch (error) {
      console.error('Chat error:', error);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="chat-widget">
      <div className="messages">
        {messages.map((msg, index) => (
          <div key={index} className={`message ${msg.role}`}>
            {msg.content}
          </div>
        ))}
      </div>
      
      <form onSubmit={(e) => {
        e.preventDefault();
        if (input.trim()) {
          sendMessage(input);
          setInput('');
        }
      }}>
        <input
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Type your message..."
          disabled={isLoading}
        />
        <button type="submit" disabled={isLoading}>
          Send
        </button>
      </form>
    </div>
  );
}

Node.js Client

Create a reusable client for functional agents:

javascript
const axios = require('axios');

class MeeblyClient {
  constructor(apiKey, environmentId) {
    this.apiKey = apiKey;
    this.environmentId = environmentId;
    this.baseURL = 'https://api.meebly.ai/v1';
  }

  async executeAgent(agentId, userContext, inputParameters = {}) {
    try {
      const response = await axios.post(
        `${this.baseURL}/execute`,
        {
          agentId,
          environmentId: this.environmentId,
          userContext,
          inputParameters
        },
        {
          headers: {
            'X-API-Key': this.apiKey
          }
        }
      );

      return response.data;
    } catch (error) {
      throw new Error(`Agent execution failed: ${error.message}`);
    }
  }

  async createAgent(config) {
    try {
      const response = await axios.post(
        `${this.baseURL}/agent`,
        {
          ...config,
          environmentId: this.environmentId
        },
        {
          headers: {
            'Authorization': `Bearer ${this.apiKey}`
          }
        }
      );

      return response.data;
    } catch (error) {
      throw new Error(`Agent creation failed: ${error.message}`);
    }
  }

  async listAgents() {
    try {
      const response = await axios.get(
        `${this.baseURL}/agent`,
        {
          params: { environmentId: this.environmentId },
          headers: {
            'Authorization': `Bearer ${this.apiKey}`
          }
        }
      );

      return response.data;
    } catch (error) {
      throw new Error(`Failed to list agents: ${error.message}`);
    }
  }
}

// Usage
const client = new MeeblyClient('YOUR_API_KEY', 'env_xyz789');

// Execute agent
const result = await client.executeAgent(
  'agent_abc123',
  'Process customer order',
  {
    customerEmail: 'customer@example.com',
    items: [{ productId: 'prod_123', quantity: 2 }]
  }
);

console.log('Result:', result.data);

Python Example

python
import requests
import json

class MeeblyClient:
    def __init__(self, api_key, environment_id):
        self.api_key = api_key
        self.environment_id = environment_id
        self.base_url = 'https://api.meebly.ai/v1'
    
    def execute_agent(self, agent_id, user_context, input_parameters=None):
        url = f'{self.base_url}/execute'
        headers = {'X-API-Key': self.api_key}

        payload = {
            'agentId': agent_id,
            'environmentId': self.environment_id,
            'userContext': user_context,
            'inputParameters': input_parameters or {}
        }

        response = requests.post(url, json=payload, headers=headers)
        response.raise_for_status()

        return response.json()
    
    def create_agent(self, config):
        url = f'{self.base_url}/agent'
        headers = {'Authorization': f'Bearer {self.api_key}'}
        
        payload = {
            **config,
            'environmentId': self.environment_id
        }
        
        response = requests.post(url, json=payload, headers=headers)
        response.raise_for_status()
        
        return response.json()

# Usage
client = MeeblyClient('YOUR_API_KEY', 'env_xyz789')

# Execute agent
result = client.execute_agent(
    'agent_abc123',
    'Generate sales report',
    {
        'startDate': '2024-01-01',
        'endDate': '2024-03-31',
        'region': 'US'
    }
)

print(f"Report: {result['data']}")

cURL Examples

Create an Agent

bash
curl -X POST https://api.meebly.ai/v1/agent \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Support Bot",
    "description": "Customer support assistant",
    "environmentId": "env_xyz789",
    "agentType": "conversational",
    "systemInstructions": "You are a helpful support agent."
  }'

Start a Chat

bash
curl -X POST "https://api.meebly.ai/v1/chat" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "X-Backend-Token: YOUR_BACKEND_TOKEN" \
  -d '{
    "agentId": "agent_abc123",
    "environmentId": "env_xyz789",
    "messages": [
      { "content": "Hello! How can you help me?" }
    ],
    "customerId": "user-123",
    "threadId": "conversation-abc",
    "screenState": {
      "route": "/dashboard",
      "routeName": "Dashboard",
      "timestamp": "2025-01-15T12:00:00Z"
    }
  }'

Execute Functional Agent

bash
curl -X POST "https://api.meebly.ai/v1/execute" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "X-Backend-Token: YOUR_BACKEND_TOKEN" \
  -d '{
    "agentId": "agent_abc123",
    "environmentId": "env_xyz789",
    "userContext": "Analyze the sales data and generate a report",
    "inputParameters": {
      "dateRange": "last-30-days",
      "includeMetrics": ["revenue", "conversion", "customers"]
    },
    "customerId": "user-123"
  }'
Last updated: March 2026Report an issue