Code Examples
Browse our collection of code examples, sample applications, and implementation patterns to help you integrate ZeebeeAI into your projects. Each example demonstrates best practices and common use cases.
Basic Chat Implementation
This example shows how to implement a simple chat interface using ZeebeeAI. You can select your preferred programming language below.
// Import the ZeebeeAI SDK
import { ZeebeeAI } from '@zeebee-ai/sdk';
// Initialize the client with your API key
const zeebee = new ZeebeeAI('YOUR_API_KEY');
async function sendMessage(userMessage) {
try {
// Send the message to ZeebeeAI
const response = await zeebee.chat({
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: userMessage }
],
model: 'gpt-4-turbo'
});
// Return the AI's response
return response.message;
} catch (error) {
console.error('Error:', error);
return 'Sorry, there was an error processing your request.';
}
}
// Example usage
sendMessage('What is artificial intelligence?')
.then(response => console.log(response));
from zeebee_ai import ZeebeeAI
# Initialize the client with your API key
zeebee = ZeebeeAI(api_key="YOUR_API_KEY")
def send_message(user_message):
try:
# Send the message to ZeebeeAI
response = zeebee.chat(
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": user_message}
],
model="gpt-4-turbo"
)
# Return the AI's response
return response.message
except Exception as e:
print(f"Error: {e}")
return "Sorry, there was an error processing your request."
# Example usage
response = send_message("What is artificial intelligence?")
print(response)
import ai.zeebee.ZeebeeAI;
import ai.zeebee.model.ChatRequest;
import ai.zeebee.model.ChatResponse;
import ai.zeebee.model.Message;
import java.util.Arrays;
import java.util.List;
public class SimpleChat {
public static void main(String[] args) {
// Initialize the client with your API key
ZeebeeAI zeebee = new ZeebeeAI("YOUR_API_KEY");
// Create message list
List messages = Arrays.asList(
new Message("system", "You are a helpful assistant."),
new Message("user", "What is artificial intelligence?")
);
try {
// Send the chat request
ChatRequest request = new ChatRequest.Builder()
.messages(messages)
.model("gpt-4-turbo")
.build();
ChatResponse response = zeebee.chat(request);
// Print the response
System.out.println(response.getMessage());
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
using ZeebeeAI;
using ZeebeeAI.Models;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// Initialize the client with your API key
var zeebee = new ZeebeeAIClient("YOUR_API_KEY");
// Create messages
var messages = new List
{
new Message { Role = "system", Content = "You are a helpful assistant." },
new Message { Role = "user", Content = "What is artificial intelligence?" }
};
try
{
// Send chat request
var request = new ChatRequest
{
Messages = messages,
Model = "gpt-4-turbo"
};
var response = await zeebee.ChatAsync(request);
// Print response
Console.WriteLine(response.Message);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
import ZeebeeAI
// Initialize the client with your API key
let zeebee = ZeebeeAI(apiKey: "YOUR_API_KEY")
// Create messages
let messages = [
Message(role: .system, content: "You are a helpful assistant."),
Message(role: .user, content: "What is artificial intelligence?")
]
// Send chat request
zeebee.chat(
messages: messages,
model: "gpt-4-turbo"
) { result in
switch result {
case .success(let response):
print(response.message)
case .failure(let error):
print("Error: \(error.localizedDescription)")
}
}
Streaming Responses
This example demonstrates how to use streaming to display AI responses in real-time as they're generated.
import { ZeebeeAI } from '@zeebee-ai/sdk';
const zeebee = new ZeebeeAI('YOUR_API_KEY');
async function streamChat(userMessage) {
try {
// Create a streaming chat request
const stream = await zeebee.chatStream({
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: userMessage }
],
model: 'gpt-4-turbo'
});
let fullResponse = '';
// Process each chunk as it arrives
for await (const chunk of stream) {
fullResponse += chunk.content || '';
// Update UI with the current response
console.log('Chunk received:', chunk.content);
// In a real application, you would update your UI here
updateUI(fullResponse);
}
return fullResponse;
} catch (error) {
console.error('Error:', error);
return 'Sorry, there was an error processing your request.';
}
}
// Example UI update function (replace with your own implementation)
function updateUI(text) {
document.getElementById('response').textContent = text;
}
from zeebee_ai import ZeebeeAI
zeebee = ZeebeeAI(api_key="YOUR_API_KEY")
def stream_chat(user_message):
try:
# Create a streaming chat request
stream = zeebee.chat_stream(
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": user_message}
],
model="gpt-4-turbo"
)
full_response = ""
# Process each chunk as it arrives
for chunk in stream:
content = chunk.get("content", "")
full_response += content
# In a real application, you would update your UI here
print(content, end="", flush=True)
print() # Print a newline at the end
return full_response
except Exception as e:
print(f"Error: {e}")
return "Sorry, there was an error processing your request."
# Example usage
response = stream_chat("Explain quantum computing in simple terms.")
Sample Applications
Simple Chat Interface
A basic React application demonstrating how to build a chat interface using ZeebeeAI.
View CodeVoice Assistant
A voice-enabled chat application using WebSockets for real-time speech recognition and synthesis.
View CodeDocument Q&A
A Flask application that allows users to ask questions about uploaded documents.
View CodeCode Assistant API
A Spring Boot application that provides a REST API for code generation and explanation.
View CodeCode Snippets
Error Handling
try {
const response = await zeebee.chat({
messages: [{ role: 'user', content: userMessage }],
model: 'gpt-4-turbo'
});
return response.message;
} catch (error) {
// Check error type
if (error.type === 'rate_limit_exceeded') {
return 'You have exceeded your rate limit. Please try again later.';
} else if (error.type === 'authentication_error') {
return 'Authentication failed. Please check your API key.';
} else if (error.type === 'server_error') {
return 'A server error occurred. Please try again later.';
} else {
// Generic error handling
console.error('Unexpected error:', error);
return 'An unexpected error occurred.';
}
}
Custom System Prompts
// Create a specialized assistant with a custom system prompt
const response = await zeebee.chat({
messages: [
{
role: 'system',
content: 'You are a mathematics tutor specialized in calculus. ' +
'Explain concepts clearly and step-by-step. ' +
'When appropriate, provide practice problems.'
},
{ role: 'user', content: 'Can you explain derivatives?' }
],
model: 'gpt-4-turbo'
});
Conversation Management
// Initialize a conversation
const conversation = await zeebee.createConversation({
title: 'Product Support Chat',
metadata: {
product_id: '12345',
user_tier: 'premium'
}
});
// Send a message in the conversation
const response = await zeebee.chat({
conversation_id: conversation.id,
messages: [{ role: 'user', content: 'How do I reset my password?' }],
model: 'gpt-4-turbo'
});
// Later, continue the same conversation
const followUpResponse = await zeebee.chat({
conversation_id: conversation.id,
messages: [{ role: 'user', content: 'Thanks, and how do I change my email?' }],
model: 'gpt-4-turbo'
});
// The API automatically includes previous messages from the conversation