Python SDK
The ZeebeeAI Python client library provides a simple and powerful way to integrate AI functionality into your Python applications, including multi-model support, agent orchestration, and advanced routing capabilities.
Installation
You can install the ZeebeeAI Python SDK using pip:
pip install zeebee-ai-client
AI Chat
The ZeebeeAI SDK provides a powerful chat interface for
interacting with large language models through the
chat()
method of the ZeebeeClient
class.
Function Signature
chat(message, conversation_id=None, model="gpt-4o",
system_prompt=None, template_name=None, template_variables=None,
stream=False, layout=None, max_tokens=None, temperature=0.7,
top_p=1.0, frequency_penalty=0.0, presence_penalty=0.0,
stop_sequences=None, user_id=None, metadata=None)
Sends a message to the AI and returns a response.
Parameters:
- message str: The user message to send to the AI.
- conversation_id str, optional: ID for continuing a conversation. If not provided, a new conversation will be created.
- model str, default="gpt-4o": The language model to use for generating responses.
- system_prompt str, optional: A system prompt to guide the AI's behavior.
- template_name str, optional: Name of a template to use for formatting the response.
- template_variables dict, optional: Variables to use with the template.
- stream bool, default=False: Whether to stream the response instead of waiting for the complete response.
- layout str, optional: Specific layout for the response.
- max_tokens int, optional: Maximum number of tokens in the response.
- temperature float, default=0.7: Controls randomness in response generation (0-1).
- top_p float, default=1.0: Controls diversity via nucleus sampling (0-1).
- frequency_penalty float, default=0.0: Reduces repetition of token sequences (0-2).
- presence_penalty float, default=0.0: Reduces repetition of topics (0-2).
- stop_sequences list, optional: Sequences that will stop response generation.
- user_id str, optional: User identifier for tracking purposes.
- metadata dict, optional: Additional metadata to include with the request.
Returns:
dict or
Generator: Response object or
stream of response chunks if stream=True
.
Basic Example
Here's a simple example of how to use the SDK for basic chat functionality:
import os
from zeebee_ai_client import ZeebeeClient
# Initialize the client
client = ZeebeeClient(
api_key=os.environ.get("ZEEBEE_API_KEY"), # Replace with your API key
)
# Send a simple message
response = client.chat("Hello, how can you help me today?")
print(response["message"])
# Or create a conversation for multi-turn interactions
conversation = client.create_conversation()
conversation_id = conversation["id"]
response = client.chat("Tell me about quantum computing", conversation_id=conversation_id)
print(response["message"])
# Continue the conversation
follow_up = client.chat("How is that related to cryptography?", conversation_id=conversation_id)
print(follow_up["message"])
Voice Chat
The ZeebeeAI SDK provides WebSocket-based voice chat functionality for real-time audio streaming interactions. This allows your application to send audio recordings and receive responses both as text and audio.
WebSocketVoiceChat Class
WebSocketVoiceChat(api_key, ws_url="wss://zeebee.ai/ws",
user_id=None, debug=False)
Initializes the WebSocket voice chat client.
Parameters:
- api_key str: API key for authentication.
- ws_url str, default="wss://zeebee.ai/ws": WebSocket server URL.
- user_id str, optional: User ID for tracking.
- debug bool, default=False: Enable debug logging.
Methods:
-
create_session(conversation_id=None, model="gpt-4o", stt_provider="openai", tts_provider="openai", language_code="en-US", voice_id=None, on_transcript=None, on_response=None, on_audio=None, on_error=None, on_status=None)
Creates a new voice chat session.
-
close_all_sessions()
Closes all active sessions.
-
get_active_sessions()
Returns all active sessions.
-
get_session_count()
Returns the number of active sessions.
VoiceChatSession Class
VoiceChatSession
Manages a real-time voice chat session over WebSockets.
Methods:
-
connect()
Connects to the WebSocket server.
Returns bool: True if connection established, False otherwise.
-
disconnect()
Disconnects from the WebSocket server.
-
send_audio(audio_data)
Sends audio data to the server.
audio_data Union[bytes, str]: Audio data as bytes, base64-encoded string, or path to audio file.
Returns bool: True if sent successfully, False otherwise.
Callbacks:
- on_transcript: Called when transcript is received.
- on_response: Called when AI response is received.
- on_audio: Called when audio response is received.
- on_error: Called when an error occurs.
- on_status: Called when connection status changes.
Basic Example
Here's a simple example of how to use the voice chat functionality:
import os
import asyncio
import soundfile as sf # pip install soundfile
import sounddevice as sd # pip install sounddevice
from zeebee_ai_client import WebSocketVoiceChat
# Example callback functions with practical implementations
def on_transcript(text):
"""Called when your audio is transcribed to text"""
print(f"\nš¤ You said: {text}")
# You could update UI with transcription here
def on_response(text):
"""Called when AI responds with text"""
print(f"\nš¤ AI response: {text}")
# You could update UI with AI response here
def on_audio(audio_data):
"""Called when AI responds with audio"""
# Save the audio to a file
with open("ai_response.wav", "wb") as f:
f.write(audio_data)
# If you have soundfile/sounddevice installed, play the audio
try:
# Save temporarily and play
with open("temp_response.wav", "wb") as f:
f.write(audio_data)
# Load and play audio
data, samplerate = sf.read("temp_response.wav")
sd.play(data, samplerate)
sd.wait() # Wait until audio is finished playing
print(f"š Playing audio response ({len(audio_data)} bytes)")
except Exception as e:
print(f"Could not play audio: {e}")
print(f"Audio saved to ai_response.wav ({len(audio_data)} bytes)")
def on_error(error_message):
"""Called when an error occurs"""
print(f"\nā Error: {error_message}")
def on_status(status):
"""Called when connection status changes"""
status_symbols = {
"connecting": "š",
"connected": "š¢",
"ready": "ā
",
"processing": "ā³",
"disconnected": "š“",
"reconnecting": "š"
}
symbol = status_symbols.get(status, "ā¹ļø")
print(f"{symbol} Status: {status}")
async def main():
# Initialize the WebSocket voice chat client
voice_chat = WebSocketVoiceChat()
# Create a voice chat session with our callback functions
session = voice_chat.create_session(
model="gpt-4o", # AI model to use
on_transcript=on_transcript,
on_response=on_response,
on_audio=on_audio,
on_error=on_error,
on_status=on_status
)
# Connect to the WebSocket server
connected = await session.connect()
if not connected:
print("Failed to connect to voice chat server")
return
# Send an audio file to the server
audio_file_path = "recording.wav" # Path to your WAV audio file
print(f"\nSending audio file: {audio_file_path}")
success = await session.send_audio(audio_file_path)
if success:
print("Audio sent successfully")
else:
print("Failed to send audio")
# Wait for the interaction to complete (transcription + AI response)
# Adjust this time based on your expected response time
print("Waiting for response...")
await asyncio.sleep(30)
# Disconnect when done
await session.disconnect()
await voice_chat.close_all_sessions()
print("\nSession ended")
# Run the async main function
if __name__ == "__main__":
asyncio.run(main())
soundfile
and sounddevice
libraries to play audio responses. To install these, run:
pip install soundfile sounddevice
If you don't need audio playback, you can simplify the
on_audio
function to just save the file.
Advanced Features
ZeebeeAI SDK offers several advanced features including Agent Orchestration, Autonomous Routing, and Dynamic Layout Engine.
Dynamic Layout Engine
The Dynamic Layout Engine allows applications to intelligently generate appropriate layouts for content based on message complexity, detected intents, and context. This helps create visually rich and contextually appropriate user interfaces for AI responses.
LayoutController Class
LayoutController(client)
Controller for dynamic layout generation operations.
Methods:
-
generate_layout(message, routing_result=None)
Generate a dynamic layout based on message complexity and routing.
Parameters:
- message str: The user message to analyze.
- routing_result Dict[str, Any], optional: Optional routing result to customize the layout based on routing decisions.
Returns:
Dict[str, Any]: Layout configuration including components, theme, and settings.
LayoutType Class
LayoutType
Constants for all supported layout types when requesting or specifying layout preferences.
Constants:
TEXT_HIGHLIGHT
: Simple text layout with highlightsCARD_LIST
: List layout with cardsSTACKED_CARDS
: Stack of cardsCOMPARISON_VIEW
: Split view for comparisonsCODE_DISPLAY
: Layout optimized for code displayDATA_VISUALIZATION
: Layout for charts and graphsSTORY_BLOCK
: Document and story layoutTABLE_LAYOUT
: Dashboard with tabular dataCAROUSEL_GALLERY
: Media gallery with carouselHERO_ALERT
: Timeline with alertsSIMPLE
: Default simple layout
Class Methods:
-
all()
Returns a list of all available layout type values.
Example:
from zeebee_ai_client import ZeebeeClient, LayoutController, LayoutType
import os
# Initialize the SDK
client = ZeebeeClient(api_key=os.environ.get("ZEEBEE_API_KEY"))
# Initialize the layout controller for layout generation
layout = LayoutController(client)
# Generate a dynamic layout for tabular data
table_layout = layout.generate_layout(
message="Create a table comparing Python, JavaScript, and Java programming languages",
routing_result={
"suggested_template": LayoutType.TABLE_LAYOUT,
"content_analysis": {
"contentTypes": ["table", "comparison"],
"complexity": "medium",
"formality": "formal"
}
}
)
print(f"Generated layout template: {table_layout['layout']['template']}")
print(f"Layout type: {table_layout['layout']['type']}")
print(f"Number of components: {len(table_layout['layout']['components'])}")
print(f"Content analysis: {table_layout['layout']['content_analysis']}")
# Accessing specific components in the layout
for component in table_layout['layout']['components']:
print(f"Component type: {component['type']}")
if component['type'] == 'table':
print(f"Table options: {component['options']}")
Agent Orchestration
The Agent Orchestration feature allows you to create, configure, and execute specialized AI agents designed for specific tasks, and connect them into pipelines for multi-step workflows. This enables complex AI applications that require multiple processing steps or different types of expertise.
AgentController Class
AgentController(client)
Controller for creating and managing specialized AI agents.
Methods:
-
create_agent(name, agent_type, configuration, description=None, model_id=None)
Create a new agent with the specified configuration.
Returns Dict[str, Any]: Created agent details including its ID.
-
get_agent(agent_id)
Get details about a specific agent.
Returns Dict[str, Any]: Agent details.
-
update_agent(agent_id, update_data)
Update an existing agent's configuration.
Returns Dict[str, Any]: Updated agent details.
-
delete_agent(agent_id)
Delete an agent.
Returns Dict[str, Any]: Deletion confirmation.
-
execute_agent(agent_id, input_data)
Execute an agent with the provided input data.
Returns Dict[str, Any]: Agent execution result.
-
get_agent_types()
Get all available agent types.
Returns Dict[str, Any]: List of available agent types.
-
get_agents()
Get all agents available to the user.
Returns Dict[str, Any]: List of available agents.
AgentTypes Class
AgentTypes
Constants for available agent types in the Zeebee AI platform.
Constants:
RETRIEVAL
: Agent for retrieving information from knowledge basesSUMMARIZATION
: Agent for summarizing long-form contentREASONING
: Agent for performing logical reasoning and analysisGENERATION
: Agent for generating creative contentWEB
: Agent for interacting with web resourcesSTRUCTURE
: Agent for processing and transforming structured data
Class Methods:
-
all()
Returns a list of all available agent type values.
PipelineController Class
PipelineController(client)
Controller for creating and managing pipelines of connected agents.
Methods:
-
create_pipeline(name, stages=None, description=None, visual_layout=None)
Create a new pipeline of connected agents.
Returns Dict[str, Any]: Created pipeline details including its ID.
-
get_pipeline(pipeline_id)
Get details about a specific pipeline.
Returns Dict[str, Any]: Pipeline details.
-
get_pipelines()
Get all pipelines available to the current user.
Returns Dict[str, Any]: List of available pipelines.
-
update_pipeline(pipeline_id, update_data)
Update an existing pipeline.
Returns Dict[str, Any]: Updated pipeline details.
-
delete_pipeline(pipeline_id)
Delete a pipeline.
Returns Dict[str, Any]: Deletion confirmation.
-
execute_pipeline(pipeline_id, input_data, conversation_id=None)
Execute a pipeline with the provided input data.
Returns Dict[str, Any]: Pipeline execution result.
-
get_pipeline_executions(pipeline_id)
Get all executions of a pipeline.
Returns Dict[str, Any]: List of pipeline executions.
-
get_execution(execution_id)
Get detailed information about a specific pipeline execution.
Returns Dict[str, Any]: Detailed execution information.
-
execute_pipeline_streaming(pipeline_id, input_data, conversation_id=None)
Execute a pipeline and stream the results in real-time.
Yields Dict[str, Any]: Pipeline execution results in real-time.
Example:
from zeebee_ai_client import ZeebeeClient, AgentController, AgentTypes, PipelineController
import os
# Initialize the SDK
client = ZeebeeClient(api_key=os.environ.get("ZEEBEE_API_KEY"))
# Initialize the agents controller
agents = AgentController(client)
# Initialize the pipeline controller
pipelines = PipelineController(client)
# Create a specialized research agent
research_agent = agents.create_agent(
name="Research Agent",
agent_type=AgentTypes.RETRIEVAL,
configuration={
"description": "Retrieves and analyzes research information",
"system_prompt": "You are a specialized research assistant. Provide detailed, accurate information with sources."
},
description="A specialized assistant for research tasks",
model_id="gpt-4o"
)
# Get the agent details
agent_id = research_agent["agent_id"]
agent_details = agents.get_agent(agent_id)
# Update the agent configuration
updated_agent = agents.update_agent(
agent_id,
update_data={
"name": "Advanced Research Agent",
"configuration": {
"system_prompt": "You are an advanced research assistant specializing in scientific literature. Provide comprehensive analysis with peer-reviewed sources."
}
}
)
# Execute the agent directly
result = agents.execute_agent(
agent_id=agent_id,
input_data={"query": "Summarize recent developments in nuclear fusion technology"}
)
# Get all available agent types
agent_types = agents.get_agent_types()
print(f"Available agent types: {agent_types}")
# Create a summarization agent
summarize_agent = agents.create_agent(
name="Summarize Agent",
agent_type=AgentTypes.SUMMARIZATION,
configuration={
"system_prompt": "You are a summarization expert. Create concise, accurate summaries of complex information."
},
description="An agent that summarizes complex information",
model_id="gpt-4o"
)
# Create a pipeline of multiple agents
pipeline = pipelines.create_pipeline(
name="Research and Summarize",
stages=[
{
"agent_id": agent_id,
"name": "Research Stage",
"input_mapping": {"query": "$.input.research_topic"},
"output_mapping": {"research_results": "$.output.result"}
},
{
"agent_id": summarize_agent["agent_id"],
"name": "Summarize Stage",
"input_mapping": {"text": "$.stages.Research Stage.research_results"},
"output_mapping": {"summary": "$.output.result"}
}
],
description="Pipeline that researches a topic and summarizes the findings"
)
# Execute the pipeline
pipeline_id = pipeline["pipeline_id"]
pipeline_result = pipelines.execute_pipeline(
pipeline_id=pipeline_id,
input_data={"research_topic": "Recent breakthroughs in quantum computing"}
)
# Get all pipelines
all_pipelines = pipelines.get_pipelines()
print(f"Number of pipelines: {len(all_pipelines['pipelines'])}")
# Get specific pipeline details
pipeline_details = pipelines.get_pipeline(pipeline_id)
# When done with the agent and pipeline, you can delete them
# agents.delete_agent(agent_id)
# agents.delete_agent(summarize_agent["agent_id"])
# pipelines.delete_pipeline(pipeline_id)
Autonomous Routing
The Autonomous Routing feature intelligently routes user messages to the appropriate agent, pipeline, or language model based on message content analysis. This enables your application to automatically direct user requests to specialized handling components without requiring explicit user selection.
RoutingController Class
RoutingController(client)
Controller for autonomous routing operations.
Methods:
-
route_message(message)
Route a user message to the appropriate agent, pipeline, or model.
Parameters:
- message str: The user message to route.
Returns:
Dict[str, Any]: Routing result with fields:
success
: Whether the request was successfulroute_to
: Target destination (agent, pipeline, or model name)route_type
: Type of destination ("agent", "pipeline", or "model")confidence
: Confidence score (0-1)intent
: Intent informationreasoning
: Reasons behind the routing decisionalternative_routes
: Alternative routing optionsdiagnostic_info
: Additional diagnostics
IntentCategory Class
IntentCategory
Constants for available intent categories in the Zeebee AI routing system.
Constants:
INFORMATION_RETRIEVAL
: Information seeking intentsCONTENT_CREATION
: Content generation intentsCONTENT_SUMMARIZATION
: Content summarization intentsCODE_GENERATION
: Code-related intents for generating codeCODE_EXPLANATION
: Code-related intents for explaining codeDATA_ANALYSIS
: Analysis intents for dataSENTIMENT_ANALYSIS
: Analysis intents for sentimentTRANSLATION
: Specialized intents for translationPERSONAL_ASSISTANCE
: Specialized intents for personal assistanceCUSTOMER_SUPPORT
: Specialized intents for customer supportSYSTEM_INSTRUCTION
: System intentsGENERAL_QUERY
: Fallback intentUNKNOWN
: Unknown intent
Class Methods:
-
all()
Returns a list of all available intent category values.
Example:
from zeebee_ai_client import ZeebeeClient, RoutingController
import os
# Initialize the SDK
client = ZeebeeClient(api_key=os.environ.get("ZEEBEE_API_KEY"))
# Initialize the routing controller
routing = RoutingController(client)
# Route a message to the appropriate agent, pipeline, or model
routing_result = routing.route_message(
message="Can you analyze this data and create a visualization?"
)
print(f"Routing to: {routing_result['route_to']} ({routing_result['route_type']})")
print(f"Confidence: {routing_result['confidence']}")
print(f"Intent information: {routing_result['intent']}")
print(f"Reasoning: {routing_result['reasoning']}")