AI Chat SDK Platform - Client Libraries

This guide provides detailed information about the client libraries available for the AI Chat SDK Platform.

Available SDKs

JavaScript/TypeScript SDK

The JavaScript/TypeScript SDK provides a convenient way to integrate the AI Chat SDK Platform into web applications, Node.js servers, and other JavaScript environments.

Installation

npm install zeebee-ai-client

Or using Yarn:

yarn add zeebee-ai-client

Initialization

import { ZeebeeAI } from 'zeebee-ai-client';

// Initialize the client
const client = new ZeebeeClient({
  apiKey: 'YOUR_API_KEY',
  userId: 'user123',
  baseUrl: 'https://api.zeebee.ai/v1'  // Optional - defaults to production API
});

Basic Chat

// Send a message and get a response
async function sendMessage() {
  const response = await client.chat({
    message: 'Hello, how can you help me?',
    model: 'gpt-4o',
    conversation_id: 'existing_conversation_id'  // Optional
  });
  
  console.log(response.message);
  console.log(`Conversation ID: ${response.conversation_id}`);
  console.log(`Message ID: ${response.message_id}`);
}

Conversation Management

// Get a list of conversations
const conversations = await client.getConversations({
  limit: 10,
  offset: 0
});

// Get messages from a conversation
const messages = await client.getConversationMessages({
  conversation_id: 'conv_12345',
  limit: 50,
  offset: 0
});

// Delete a conversation
await client.deleteConversation({
  conversation_id: 'conv_12345'
});

WebSocket Connection

// Connect to the WebSocket server
await client.connectWebSocket();

// Set up event listeners
client.on('message', (message) => {
  console.log(`Received message: ${message.content}`);
});

client.on('error', (error) => {
  console.error(`WebSocket error: ${error.message}`);
});

// Send a message via WebSocket
client.sendWebSocketMessage({
  type: 'text',
  message: 'Hello, how can you help me?',
  model: 'gpt-4o'
});

// Close the WebSocket connection when done
client.disconnectWebSocket();

Voice Chat

// Connect to the voice chat
await client.connectVoiceChat({
  onTranscript: (transcript) => {
    console.log(`Transcript: ${transcript.text}`);
  },
  onResponse: (response) => {
    console.log(`AI: ${response.message}`);
  },
  onAudioResponse: (audio) => {
    // Play the audio response
    const audioBlob = new Blob([audio.data], { type: 'audio/mp3' });
    const audioUrl = URL.createObjectURL(audioBlob);
    const audioElement = new Audio(audioUrl);
    audioElement.play();
  },
  onError: (error) => {
    console.error(`Error: ${error.message}`);
  }
});

// Send audio data
function sendAudio(audioData) {
  client.sendAudioMessage({
    data: audioData,
    model: 'gpt-4o',
    tts_provider: 'openai',
    tts_voice: 'alloy',
    stt_provider: 'openai',
    language_code: 'en'
  });
}

// Get available TTS voices
const voiceConfig = await client.getWebSocketConfig();
console.log('Available voices:', voiceConfig.tts.voices);

// Disconnect when done
client.disconnectVoiceChat();

Semantic Search

// Search conversations
const searchResults = await client.searchConversations({
  query: 'renewable energy',
  limit: 10
});

// Search messages
const messageResults = await client.searchMessages({
  query: 'solar panel efficiency',
  conversation_id: 'conv_12345',  // Optional - limit to a specific conversation
  limit: 10
});

Using Templates

// Use a template for the conversation
const response = await client.chat({
  message: 'What are the symptoms of the flu?',
  model: 'gpt-4o',
  template: 'healthcare_assistant',
  template_variables: {
    specialty: 'General Practice',
    medical_disclaimer: true
  }
});

Feedback

// Submit feedback
await client.submitFeedback({
  conversation_id: 'conv_12345',
  message_id: 'msg_67890',
  feedback_type: 'thumbs_up',
  feedback_value: 1,
  comment: 'Very helpful response!'
});

// Analyze feedback
const analysis = await client.analyzeFeedback({
  conversation_id: 'conv_12345'
});

Error Handling

try {
  const response = await client.chat({
    message: 'Hello, how can you help me?',
    model: 'gpt-4o'
  });
} catch (error) {
  if (error.status === 401) {
    console.error('Authentication error. Check your API key.');
  } else if (error.status === 429) {
    console.error('Rate limit exceeded. Please try again later.');
  } else {
    console.error(`Error: ${error.message}`);
  }
}

Python SDK

The Python SDK provides a convenient way to integrate the AI Chat SDK Platform into Python applications, scripts, and servers.

Installation

pip install zeebee-ai-client

Initialization

from zeebee_ai_client import ZeebeeAI

# Initialize the client
client = ZeebeeAI(
    api_key="YOUR_API_KEY",
    user_id="user123",
    base_url="https://api.zeebee.ai/v1"  # Optional - defaults to production API
)

Basic Chat

# Send a message and get a response
response = client.chat(
    message="Hello, how can you help me?",
    model="gpt-4o",
    conversation_id="existing_conversation_id"  # Optional
)

print(response.message)
print(f"Conversation ID: {response.conversation_id}")
print(f"Message ID: {response.message_id}")

Conversation Management

# Get a list of conversations
conversations = client.get_conversations(
    limit=10,
    offset=0
)

# Get messages from a conversation
messages = client.get_conversation_messages(
    conversation_id="conv_12345",
    limit=50,
    offset=0
)

# Delete a conversation
client.delete_conversation(
    conversation_id="conv_12345"
)

Async Support

import asyncio
from zeebee_ai_client import AsyncZeebeeAI

async def main():
    client = AsyncZeebeeAI(
        api_key="YOUR_API_KEY",
        user_id="user123"
    )
    
    response = await client.chat(
        message="Hello, how can you help me?",
        model="gpt-4o"
    )
    
    print(response.message)

asyncio.run(main())

WebSocket Client

import asyncio
from zeebee_ai_client import ZeebeeWebSocketClient

async def on_message(message):
    print(f"AI: {message['content']}")

async def on_error(error):
    print(f"Error: {error['message']}")

async def main():
    ws_client = ZeebeeWebSocketClient(
        api_key="YOUR_API_KEY",
        user_id="user123"
    )
    
    await ws_client.connect()
    
    # Set up event handlers
    ws_client.on_message = on_message
    ws_client.on_error = on_error
    
    # Send a message
    await ws_client.send_message(
        message="Hello, how can you help me?",
        model="gpt-4o"
    )
    
    # Keep the connection open for a while
    await asyncio.sleep(10)
    
    # Close the connection
    await ws_client.disconnect()

asyncio.run(main())

Voice Chat

import asyncio
from zeebee_ai_client import ZeebeeVoiceClient

async def on_transcript(transcript):
    print(f"Transcript: {transcript['text']}")

async def on_response(response):
    print(f"AI: {response['message']}")

async def on_audio_response(audio):
    # Save audio to file
    with open("response.mp3", "wb") as f:
        f.write(audio["data"])
    
    # Play audio (requires external library)
    # play_audio("response.mp3")

async def on_error(error):
    print(f"Error: {error['message']}")

async def main():
    voice_client = ZeebeeVoiceClient(
        api_key="YOUR_API_KEY",
        user_id="user123"
    )
    
    # Set up event handlers
    voice_client.on_transcript = on_transcript
    voice_client.on_response = on_response
    voice_client.on_audio_response = on_audio_response
    voice_client.on_error = on_error
    
    await voice_client.connect()
    
    # Send audio data
    with open("audio.wav", "rb") as f:
        audio_data = f.read()
    
    await voice_client.send_audio(
        data=audio_data,
        model="gpt-4o",
        tts_provider="openai",
        tts_voice="alloy",
        stt_provider="openai",
        language_code="en"
    )
    
    # Keep the connection open for a while
    await asyncio.sleep(10)
    
    # Close the connection
    await voice_client.disconnect()

asyncio.run(main())

Semantic Search

# Search conversations
search_results = client.search_conversations(
    query="renewable energy",
    limit=10
)

# Search messages
message_results = client.search_messages(
    query="solar panel efficiency",
    conversation_id="conv_12345",  # Optional - limit to a specific conversation
    limit=10
)

Using Templates

# Use a template for the conversation
response = client.chat(
    message="What are the symptoms of the flu?",
    model="gpt-4o",
    template="healthcare_assistant",
    template_variables={
        "specialty": "General Practice",
        "medical_disclaimer": True
    }
)

Feedback

# Submit feedback
client.submit_feedback(
    conversation_id="conv_12345",
    message_id="msg_67890",
    feedback_type="thumbs_up",
    feedback_value=1,
    comment="Very helpful response!"
)

# Analyze feedback
analysis = client.analyze_feedback(
    conversation_id="conv_12345"
)

Error Handling

try:
    response = client.chat(
        message="Hello, how can you help me?",
        model="gpt-4o"
    )
except Exception as e:
    print(f"Error: {str(e)}")

Flutter SDK

The Flutter SDK provides a convenient way to integrate the AI Chat SDK Platform into Flutter applications for iOS, Android, web, and desktop.

Installation

Add the dependency to your pubspec.yaml file:

dependencies:
  zeebee_ai_client: ^1.0.0

Then run:

flutter pub get

Initialization

import 'package:zeebee_ai_client/zeebee_ai_client.dart';

// Initialize the client
final client = ZeebeeAI(
  apiKey: 'YOUR_API_KEY',
  userId: 'user123',
  baseUrl: 'https://api.zeebee.ai/v1'  // Optional - defaults to production API
);

Basic Chat

// Send a message and get a response
Future sendMessage() async {
  try {
    final response = await client.chat(
      message: 'Hello, how can you help me?',
      model: 'gpt-4o',
      conversationId: 'existing_conversation_id'  // Optional
    );
    
    print(response.message);
    print('Conversation ID: ${response.conversationId}');
    print('Message ID: ${response.messageId}');
  } catch (e) {
    print('Error: $e');
  }
}

Conversation Management

// Get a list of conversations
final conversations = await client.getConversations(
  limit: 10,
  offset: 0
);

// Get messages from a conversation
final messages = await client.getConversationMessages(
  conversationId: 'conv_12345',
  limit: 50,
  offset: 0
);

// Delete a conversation
await client.deleteConversation(
  conversationId: 'conv_12345'
);

Voice Chat

// Start voice chat
await client.connectVoiceChat(
  onTranscript: (transcript) {
    print('Transcript: ${transcript.text}');
  },
  onResponse: (response) {
    print('AI: ${response.message}');
  },
  onAudioResponse: (audio) {
    // Play audio
    final player = AudioPlayer();
    player.play(BytesSource(audio.data));
  },
  onError: (error) {
    print('Error: ${error.message}');
  }
);

// Record and send audio
Future recordAndSendAudio() async {
  final recorder = FlutterSoundRecorder();
  await recorder.openRecorder();
  await recorder.startRecorder(toFile: 'temp.wav');
  
  // Record for 5 seconds
  await Future.delayed(Duration(seconds: 5));
  
  final path = await recorder.stopRecorder();
  final audioBytes = await File(path).readAsBytes();
  
  await client.sendAudioMessage(
    data: audioBytes,
    model: 'gpt-4o',
    ttsProvider: 'openai',
    ttsVoice: 'alloy',
    sttProvider: 'openai',
    languageCode: 'en'
  );
  
  await recorder.closeRecorder();
}

// Close the voice chat connection when done
await client.disconnectVoiceChat();

UI Components

The Flutter SDK includes pre-built UI components for common use cases:

import 'package:flutter/material.dart';
import 'package:zeebee_ai_client/zeebee_ai_client.dart';

class ChatScreen extends StatelessWidget {
  final ZeebeeAI client = ZeebeeAI(
    apiKey: 'YOUR_API_KEY',
    userId: 'user123'
  );
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('AI Chat')),
      body: Column(
        children: [
          Expanded(
            child: ZeebeeMessageList(
              client: client,
              conversationId: 'conv_12345',  // Optional
            ),
          ),
          ZeebeeMessageInput(
            client: client,
            conversationId: 'conv_12345',  // Optional
            model: 'gpt-4o',
            onMessageSent: (response) {
              // Handle sent message
            },
          ),
        ],
      ),
    );
  }
}

Voice Chat UI

import 'package:flutter/material.dart';
import 'package:zeebee_ai_client/zeebee_ai_client.dart';

class VoiceChatScreen extends StatelessWidget {
  final ZeebeeAI client = ZeebeeAI(
    apiKey: 'YOUR_API_KEY',
    userId: 'user123'
  );
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Voice Chat')),
      body: Column(
        children: [
          Expanded(
            child: ZeebeeMessageList(
              client: client,
            ),
          ),
          ZeebeeVoiceInput(
            client: client,
            model: 'gpt-4o',
            ttsProvider: 'openai',
            ttsVoice: 'alloy',
            sttProvider: 'openai',
            languageCode: 'en',
            onRecordingChanged: (isRecording) {
              // Handle recording state changes
            },
          ),
        ],
      ),
    );
  }
}

Semantic Search

// Search conversations
final searchResults = await client.searchConversations(
  query: 'renewable energy',
  limit: 10
);

// Search messages
final messageResults = await client.searchMessages(
  query: 'solar panel efficiency',
  conversationId: 'conv_12345',  // Optional - limit to a specific conversation
  limit: 10
);

Using Templates

// Use a template for the conversation
final response = await client.chat(
  message: 'What are the symptoms of the flu?',
  model: 'gpt-4o',
  template: 'healthcare_assistant',
  templateVariables: {
    'specialty': 'General Practice',
    'medical_disclaimer': true
  }
);

Feedback

// Submit feedback
await client.submitFeedback(
  conversationId: 'conv_12345',
  messageId: 'msg_67890',
  feedbackType: 'thumbs_up',
  feedbackValue: 1,
  comment: 'Very helpful response!'
);

// Analyze feedback
final analysis = await client.analyzeFeedback(
  conversationId: 'conv_12345'
);

Common Patterns

Chat With History

All SDKs automatically maintain conversation history by using the conversation ID returned from the initial message. Simply pass this ID in subsequent requests to continue the conversation.

Error Handling

All SDKs provide structured error handling. Errors include status codes and detailed messages to help you diagnose issues.

Real-time Updates

For real-time applications, use the WebSocket connections provided by the SDKs rather than making separate HTTP requests for each message.

Voice Integration

For the best voice chat experience:

  1. Use a high-quality microphone
  2. Process audio in chunks rather than waiting for complete recordings
  3. Handle background noise with client-side filtering if possible
  4. Provide visual feedback during recording and processing

Best Practices

Security

  • Never expose your API key in client-side code
  • For web applications, create a server-side proxy to make API calls
  • Implement proper authentication and authorization in your application
  • Use HTTPS for all communications
  • Regularly rotate API keys for enhanced security

Rate Limiting

  • Implement proper backoff and retry logic for rate-limited requests
  • Cache frequently accessed data to reduce API usage
  • Batch requests when possible to minimize API calls

User Experience

  • Provide clear feedback when waiting for AI responses
  • Implement typing indicators for chat interfaces
  • Allow users to cancel requests that take too long
  • Save conversation state locally to handle network interruptions

Error Handling

  • Implement proper error handling for all API calls
  • Display user-friendly error messages
  • Log detailed error information for debugging
  • Implement automatic retry for transient errors

Troubleshooting

Common Issues

  • Authentication Errors (401)
    • Check that your API key is valid and properly formatted
    • Ensure your subscription is active
    • Verify that your API key has the necessary permissions
  • Rate Limiting (429)
    • Implement exponential backoff and retry logic
    • Consider upgrading your plan for higher rate limits
    • Optimize your code to reduce unnecessary API calls
  • WebSocket Connection Issues
    • Check your network connection and firewall settings
    • Ensure your WebSocket implementation supports the required protocols
    • Implement proper reconnection logic with backoff
  • Voice Chat Problems
    • Ensure proper microphone permissions are granted
    • Check audio format compatibility
    • Verify that audio data is properly encoded

Getting Help

If you encounter issues not covered in this documentation, please contact our support team: