Basic Chat Example
Python
Beginner
Learn how to implement simple text-based chat functionality with conversation history management.
Basic Chat Example
This example demonstrates the core chat functionality of the ZeebeeAI SDK, showing how to create a simple text-based chat application.
Installation
# Install via pip
pip install zeebee-ai-client
# Or directly from the repository
pip install git+https://github.com/zeebeeai/zeebee-python-sdk.git
Basic Chat Example
from zeebee_ai_client import ZeebeeClient
import os
# Initialize the client with your API key
api_key = os.environ.get("ZEEBEE_API_KEY")
client = ZeebeeClient(api_key=api_key)
# Send a simple message
response = client.chat(
message="Hello, who are you?",
model="gpt-4o"
)
# Print the response
print(f"AI: {response['message']}")
# Continue the conversation
conversation_id = response.get("conversation_id")
follow_up = client.chat(
message="What can you help me with?",
conversation_id=conversation_id,
model="gpt-4o"
)
print(f"AI: {follow_up['message']}")
Interactive Chat Application
def interactive_chat():
"""Run an interactive chat session in the console."""
print("ZeebeeAI Chat Demo")
print("Type 'exit' or 'quit' to end the conversation")
print("=" * 50)
# Select a model
available_models = [
"gpt-4o",
"claude-3-5-sonnet-20241022",
"gpt-3.5-turbo",
"grok-2-1212"
]
print("\nAvailable models:")
for i, model in enumerate(available_models, 1):
print(f"{i}. {model}")
choice = input("\nSelect a model (1-4): ")
try:
model = available_models[int(choice) - 1]
except (ValueError, IndexError):
model = "gpt-4o" # Default
print(f"\nUsing model: {model}")
print("=" * 50)
conversation_id = None
while True:
# Get user input
user_input = input("\nYou: ")
# Check for exit command
if user_input.lower() in ["exit", "quit"]:
print("Goodbye!")
break
try:
# Send to API
response = client.chat(
message=user_input,
model=model,
conversation_id=conversation_id
)
# Update conversation ID
conversation_id = response.get("conversation_id")
# Display response
print(f"\nAI: {response['message']}")
# Display token usage if available
if "usage" in response:
usage = response["usage"]
print(f"\n[Token usage: {usage.get('total_tokens', 0)} total, "
f"{usage.get('prompt_tokens', 0)} prompt, "
f"{usage.get('completion_tokens', 0)} completion]")
except Exception as e:
print(f"\nError: {e}")
if __name__ == "__main__":
interactive_chat()
Conversation Management
# List conversations
conversations = client.list_conversations(limit=5)
for conv in conversations.get("conversations", []):
print(f"ID: {conv['id']}, Title: {conv['title']}")
# Get a specific conversation
conversation = client.get_conversation("conversation_id_here")
messages = conversation.get("messages", [])
for msg in messages:
print(f"{msg['role']}: {msg['content']}")
# Delete a conversation
client.delete_conversation("conversation_id_here")
Error Handling
def send_message_with_error_handling(message, model="gpt-4o", conversation_id=None):
"""Send a message with proper error handling."""
try:
response = client.chat(
message=message,
model=model,
conversation_id=conversation_id
)
return response
except ConnectionError as e:
print(f"Connection error: {e}")
print("Please check your internet connection and try again.")
return None
except TimeoutError as e:
print(f"Request timed out: {e}")
print("The server took too long to respond. Please try again later.")
return None
except Exception as e:
print(f"An error occurred: {e}")
# Check for common error patterns
error_str = str(e).lower()
if "api key" in error_str:
print("API key error. Please check that your API key is valid.")
elif "rate limit" in error_str:
print("Rate limit exceeded. Please wait before making more requests.")
elif "model" in error_str:
print("Model error. The requested model may not be available.")
else:
print("Unknown error. Please try again or contact support.")
return None
Full Example
Download the complete example application from the button above to see basic chat functionality in action with an interactive console interface.