Official Python SDK for the Henotace AI API
Project description
Henotace AI Python SDK
Official Python SDK for the Henotace AI API - your gateway to AI-powered tutoring and educational assistance.
โจ Features
- ๐ Easy Integration: Simple, intuitive API for Python applications
- ๐ Session Management: Built-in support for managing student sessions and chat history
- ๐พ Flexible Storage: Pluggable storage connectors (in-memory, file, database, etc.)
- โก Async Support: Full async/await support for modern Python applications
- ๐ก๏ธ Error Handling: Comprehensive error handling with custom exceptions
- ๐ Rate Limiting: Built-in retry logic and rate limit handling
- ๐ฏ Context Management: Support for persistent context, personas, and user profiles
- ๐ฆ Modular Architecture: Clean, maintainable code structure matching Node.js SDK
- ๐ง Professional Logging: Configurable logging with multiple levels
- ๐๏ธ History Compression: Automatic chat history summarization for long conversations
- ๐๏ธ Smart Verbosity: Auto-detects and adjusts response length based on user requests
- ๐ Dynamic Response Lengths: Brief, normal, detailed, and comprehensive response modes
- ๐ Classwork Generation: Generate practice questions based on conversation history
- ๐ Educational Focus: Specialized for tutoring and educational applications
- ๐ Secure Authentication: Bearer token authentication with proper error handling
- ๐จ Advanced Personalization: Comprehensive AI tutor personalization with learning pattern analysis
- ๐ง Learning Analysis: Automatic detection of learning levels, styles, and student patterns
- ๐ญ Branding Support: Custom branding and white-label options for enterprise users
- ๐ Multi-language: Support for multiple languages including Nigerian languages (Yoruba, Hausa, Igbo, Pidgin)
- ๐ค Personality Types: Choose from friendly, professional, encouraging, strict, or humorous personalities
- ๐ Teaching Styles: Socratic, Direct Instruction, Problem-Based, or Collaborative learning approaches
- ๐ฏ Interest Integration: Personalize learning based on student interests and preferences
- ๐ Progress Tracking: Automatic tracking of student strengths, struggles, and learning patterns
๐ฆ Installation
pip install henotace-ai-sdk
Or install from source:
git clone https://github.com/Davidoshin/henotace-python-sdk.git
cd henotace-python-sdk
pip install -e .
Development Installation
For development with additional tools:
pip install -e .[dev]
This includes:
pytest- Testing frameworkpytest-asyncio- Async testing supportblack- Code formattingflake8- Lintingmypy- Type checking
๐ Quick Start
Basic Usage (Programmatic)
import asyncio
from henotace_ai import HenotaceAI, create_tutor, SessionSubject, InMemoryConnector
async def main():
# Initialize the SDK with storage
sdk = HenotaceAI(
api_key="your_api_key_here",
storage=InMemoryConnector() # Optional: for session persistence
)
# Check API status
if sdk.get_status_ok():
print("โ
API is available")
else:
print("โ API is not available")
return
# Create a tutor with subject information
tutor = await create_tutor(
sdk=sdk,
student_id="student_123",
tutor_name="Math Tutor",
subject=SessionSubject(
id="math",
name="Mathematics",
topic="Algebra"
)
)
# Send a message
response = await tutor.send("Can you help me solve 2x + 5 = 13?")
print(f"AI Response: {response}")
# Continue the conversation
response = await tutor.send("What's the first step?")
print(f"AI Response: {response}")
# Run the example
asyncio.run(main())
๐จ Advanced Personalization Features
The Henotace AI Python SDK includes comprehensive personalization capabilities that automatically analyze learning patterns and adapt to individual student needs.
๐ง Learning Pattern Analysis
The AI automatically analyzes conversation history to detect:
- Learning Level: Beginner, Intermediate, or Advanced
- Learning Style: Inquisitive, Example-driven, or Practice-oriented
- Student Struggles: Areas where the student needs extra support
- Student Strengths: Topics where the student excels
- Key Concepts: Important topics discussed in the conversation
- Learning Patterns: How the student prefers to learn
๐ Multi-Language Support
Support for multiple languages including Nigerian languages:
import asyncio
from henotace_ai import HenotaceAI, InMemoryConnector
async def multi_language_example():
sdk = HenotaceAI(
api_key="your_api_key_here",
storage=InMemoryConnector()
)
# Supported languages
languages = [
{"code": "en", "name": "English", "question": "What is gravity?"},
{"code": "pidgin", "name": "Nigerian Pidgin", "question": "Wetin be gravity?"},
{"code": "yo-NG", "name": "Yoruba", "question": "Kรญ ni gravity?"},
{"code": "ha-NG", "name": "Hausa", "question": "Menene gravity?"},
{"code": "ig-NG", "name": "Igbo", "question": "Gแปnแป bแปฅ gravity?"}
]
for lang in languages:
print(f"\n๐ฃ๏ธ Testing {lang['name']} ({lang['code']}):")
response = await sdk.chat_completion(
history=[],
input_text=lang["question"],
subject="physics",
topic="mechanics",
language=lang["code"],
personality="friendly",
teaching_style="direct"
)
print(f"โ
{lang['name']} response: {response['ai_response'][:150]}...")
# Run the example
asyncio.run(multi_language_example())
๐ค Personality Types
Choose from different tutor personalities:
import asyncio
from henotace_ai import HenotaceAI, InMemoryConnector
async def personality_example():
sdk = HenotaceAI(api_key="your_api_key_here")
personalities = [
"friendly", # Approachable and supportive
"encouraging", # Warm, supportive, celebrates small wins
"strict", # Precise, direct, focused on accuracy
"humorous", # Uses appropriate humor to make learning engaging
"professional" # Formal, professional tone while being helpful
]
for personality in personalities:
print(f"\n๐งโ๐ซ Testing {personality} personality:")
response = await sdk.chat_completion(
history=[],
input_text="I find math difficult",
subject="mathematics",
topic="algebra",
personality=personality,
teaching_style="socratic",
author_name="Math Tutor"
)
print(f"โ
{personality} response: {response['ai_response'][:150]}...")
asyncio.run(personality_example())
๐ Teaching Styles
Select the teaching approach that works best:
import asyncio
from henotace_ai import HenotaceAI, InMemoryConnector
async def teaching_style_example():
sdk = HenotaceAI(api_key="your_api_key_here")
teaching_styles = [
"socratic", # Asks thought-provoking questions to guide discovery
"direct", # Provides clear explanations and step-by-step instructions
"problem_based", # Focuses on problem-solving and practical applications
"collaborative" # Works together with the student, building on their ideas
]
for style in teaching_styles:
print(f"\n๐ Testing {style} teaching style:")
response = await sdk.chat_completion(
history=[],
input_text="Explain quadratic equations",
subject="mathematics",
topic="algebra",
personality="friendly",
teaching_style=style,
author_name="Algebra Expert"
)
print(f"โ
{style} response: {response['ai_response'][:150]}...")
asyncio.run(teaching_style_example())
๐ฏ Interest Integration
Personalize learning based on student interests:
import asyncio
from henotace_ai import HenotaceAI, InMemoryConnector
async def interest_integration_example():
sdk = HenotaceAI(api_key="your_api_key_here")
# The AI automatically uses student interests for personalization
response = await sdk.chat_completion(
history=[
{"role": "user", "content": "I love football and music"},
{"role": "assistant", "content": "Great! Let me use football examples to explain math concepts..."}
],
input_text="Explain physics concepts",
subject="physics",
topic="mechanics",
interests=["football", "sports", "music"], # Student interests for personalization
personality="encouraging",
teaching_style="problem_based"
)
print(f"AI Response: {response['ai_response']}")
# The AI will automatically use football/sports examples for physics concepts
asyncio.run(interest_integration_example())
๐ Complete Personalization Example
import asyncio
from henotace_ai import HenotaceAI, InMemoryConnector
async def complete_personalization_example():
sdk = HenotaceAI(api_key="your_api_key_here")
# Simulate a conversation that shows learning patterns
conversation_history = [
{"role": "user", "content": "I love football and find math difficult"},
{"role": "assistant", "content": "I understand! Let me use football examples to explain math concepts..."},
{"role": "user", "content": "Can you show me how to calculate angles?"},
{"role": "assistant", "content": "Great question! In football, when a player kicks the ball..."},
{"role": "user", "content": "I still don't understand trigonometry"}
]
print("๐ Simulating learning conversation...")
response = await sdk.chat_completion(
history=conversation_history,
input_text="Can you explain sine and cosine using football?",
subject="mathematics",
topic="trigonometry",
author_name="Coach Math",
language="en",
personality="encouraging",
teaching_style="problem_based",
interests=["football", "sports", "gaming"],
branding={
"name": "Sports Math Tutor",
"primaryColor": "#FF6B35",
"secondaryColor": "#F7931E"
}
)
print("โ
Advanced personalization response:")
print(response['ai_response'])
# The AI will automatically:
# 1. Detect the student struggles with math
# 2. Use football/sports examples for trigonometry
# 3. Apply encouraging personality
# 4. Use problem-based teaching approach
# 5. Reference previous conversation about angles
asyncio.run(complete_personalization_example())
Enhanced Customization
import asyncio
from henotace_ai import HenotaceAI, InMemoryConnector
async def enhanced_example():
sdk = HenotaceAI(
api_key="your_api_key_here",
storage=InMemoryConnector()
)
# Enhanced chat completion with customization
response = await sdk.chat_completion(
history=[
{"role": "user", "content": "What is photosynthesis?"},
{"role": "assistant", "content": "Photosynthesis is the process..."}
],
input_text="Can you explain it in simpler terms?",
subject="biology",
topic="plant_biology",
author_name="Dr. Smith",
language="en",
personality="friendly",
teaching_style="socratic",
branding={
"name": "Bio Tutor",
"primaryColor": "#3B82F6",
"secondaryColor": "#1E40AF"
}
)
print(f"AI Response: {response['ai_response']}")
# Run the example
asyncio.run(enhanced_example())
Tutor with Advanced Personalization
import asyncio
from henotace_ai import HenotaceAI, create_tutor, SessionSubject, InMemoryConnector
async def tutor_advanced_personalization_example():
sdk = HenotaceAI(
api_key="your_api_key_here",
storage=InMemoryConnector()
)
# Create a tutor with enhanced customization
tutor = await create_tutor(
sdk=sdk,
student_id="student_123",
tutor_name="Biology Expert",
subject=SessionSubject(
id="biology",
name="Biology",
topic="cell_structure"
)
)
# Set tutor context and persona
tutor.set_context([
"Student loves sports and music",
"Prefers visual examples and analogies"
])
tutor.set_persona("You are an encouraging biology tutor who uses sports analogies")
tutor.set_user_profile({
"name": "Alex",
"interests": ["football", "music", "art"],
"learning_style": "visual"
})
# Send message with full personalization parameters
response = await tutor.send(
"Explain cell division",
author_name="Dr. Johnson",
language="en",
personality="encouraging",
teaching_style="direct",
interests=["sports", "music", "art"], # Student interests for personalization
branding={
"name": "Cell Biology Tutor",
"primaryColor": "#10B981",
"secondaryColor": "#047857"
}
)
print(f"Tutor Response: {response}")
# Run the example
asyncio.run(tutor_advanced_personalization_example())
Multi-Language Tutor Example
import asyncio
from henotace_ai import HenotaceAI, create_tutor, SessionSubject, InMemoryConnector
async def multi_language_tutor_example():
sdk = HenotaceAI(api_key="your_api_key_here")
# Create tutors for different languages
tutors = [
{
"name": "English Math Tutor",
"language": "en",
"question": "What is 2 + 2?"
},
{
"name": "Pidgin Math Tutor",
"language": "pidgin",
"question": "Wetin be 2 + 2?"
},
{
"name": "Yoruba Math Tutor",
"language": "yo-NG",
"question": "Kรญ ni 2 + 2?"
}
]
for tutor_info in tutors:
print(f"\n๐ฃ๏ธ Testing {tutor_info['name']}:")
tutor = await create_tutor(
sdk=sdk,
student_id="student_123",
tutor_name=tutor_info["name"],
subject=SessionSubject(id="math", name="Mathematics", topic="arithmetic")
)
response = await tutor.send(
tutor_info["question"],
language=tutor_info["language"],
personality="friendly",
teaching_style="direct"
)
print(f"โ
{tutor_info['name']} response: {response[:150]}...")
asyncio.run(multi_language_tutor_example())
๐ฅ๏ธ CLI Usage
Install editable and expose CLI:
pip install -e .[dev]
Then run:
export HENOTACE_API_KEY=your_key
henotace "Explain Pythagoras theorem"
Interactive REPL:
henotace
Advanced options:
henotace --student-id stu1 --tutor-name math --persona "You are a patient math tutor" "Solve x+2=5"
Available CLI options:
--api-key- Your Henotace API key--student-id- Student identifier--tutor-name- Name for the AI tutor--persona- Custom tutor personality--context- Additional context lines
๐ฏ Advanced Usage with Context and Persona
import asyncio
from henotace_ai import HenotaceAI, create_tutor, SessionSubject, InMemoryConnector
async def advanced_example():
# Initialize SDK with custom configuration
sdk = HenotaceAI(
api_key="your_api_key_here",
storage=InMemoryConnector(),
default_persona="You are a helpful and patient tutor.",
default_preset="tutor_default"
)
# Create a specialized tutor
tutor = await create_tutor(
sdk=sdk,
student_id="student_456",
tutor_name="Physics Tutor",
subject=SessionSubject(
id="physics",
name="Physics",
topic="Mechanics"
),
grade_level="high_school",
language="en"
)
# Set persona and context
tutor.set_persona("You are an enthusiastic physics tutor who loves to use real-world examples and analogies to explain complex concepts.")
tutor.set_context([
"The student is in 11th grade and is learning about Newton's laws.",
"They prefer visual explanations and step-by-step problem solving."
])
# Set user profile
tutor.set_user_profile({
"name": "Alex",
"grade": "11th",
"learning_style": "visual",
"difficulty_level": "intermediate"
})
# Configure history compression
tutor.set_compression(
max_turns=10, # Keep last 10 messages
max_summary_chars=800, # Limit summary length
checkpoint_every=5 # Compress every 5 messages
)
# Start tutoring session
response = await tutor.send(
"I'm confused about Newton's second law. Can you explain it?",
context="We just covered Newton's first law in the previous lesson."
)
print(f"Tutor: {response}")
# Check chat history
history = tutor.history()
print(f"Chat history has {len(history)} messages")
asyncio.run(advanced_example())
๐ Automatic Progress Tracking
The AI automatically tracks and adapts to student learning patterns:
import asyncio
from henotace_ai import HenotaceAI, create_tutor, SessionSubject
async def progress_tracking_example():
sdk = HenotaceAI(api_key="your_api_key_here")
# Create a tutor
tutor = await create_tutor(
sdk=sdk,
student_id="student_123",
tutor_name="Math Tutor",
subject=SessionSubject(id="math", name="Mathematics", topic="algebra")
)
# Simulate a learning conversation
messages = [
"I find algebra difficult",
"Can you explain it using football examples?",
"What about quadratic equations?",
"I still don't understand the quadratic formula"
]
for message in messages:
print(f"\n๐ค Student: {message}")
response = await tutor.send(message)
print(f"๐ค Tutor: {response[:200]}...")
# The AI automatically:
# - Detects learning struggles and strengths
# - Adapts teaching style based on responses
# - Uses interests (football) for examples
# - Tracks progress and adjusts complexity
# - Maintains conversation context
# Get chat history to see the learning journey
history = tutor.history()
print(f"\n๐ Learning session completed with {len(history)} messages")
asyncio.run(progress_tracking_example())
๐๏ธ Smart Verbosity System
The SDK automatically detects and adjusts response length based on user requests:
import asyncio
from henotace_ai import HenotaceAI, create_tutor
async def verbosity_example():
sdk = HenotaceAI(api_key="your_api_key_here")
tutor = await create_tutor(sdk=sdk, student_id="student_123")
# Auto-detects verbosity from user input
brief_response = await tutor.send("Briefly explain photosynthesis")
# Returns: Short, concise explanation (1-2 sentences)
normal_response = await tutor.send("What is gravity?")
# Returns: Standard explanation (2-4 sentences)
detailed_response = await tutor.send("Can you give me a detailed explanation of thermodynamics?")
# Returns: Expanded explanation (4-8 sentences)
comprehensive_response = await tutor.send("I need a comprehensive guide to quantum physics")
# Returns: Full guide (8+ sentences with examples and context)
print(f"Brief: {len(brief_response)} chars")
print(f"Normal: {len(normal_response)} chars")
print(f"Detailed: {len(detailed_response)} chars")
print(f"Comprehensive: {len(comprehensive_response)} chars")
asyncio.run(verbosity_example())
Verbosity Levels:
- Brief (1-2 sentences): Keywords like "briefly", "short", "quick", "simple"
- Normal (2-4 sentences): Default level for regular questions
- Detailed (4-8 sentences): Keywords like "detailed", "more information", "elaborate"
- Comprehensive (8+ sentences): Keywords like "comprehensive", "everything", "step by step"
๐ Classwork Generation
Generate practice questions based on conversation history for any subject:
import asyncio
from henotace_ai import HenotaceAI, create_tutor, SessionSubject
async def classwork_example():
sdk = HenotaceAI(api_key="your_api_key_here")
# Create a tutor and have a conversation
tutor = await create_tutor(
sdk=sdk,
student_id="student_123",
tutor_name="Math Tutor",
subject=SessionSubject(id="math", name="Mathematics", topic="Algebra")
)
# Simulate a tutoring session
await tutor.send("I need help with linear equations")
await tutor.send("How do I solve 2x + 5 = 13?")
await tutor.send("What about equations with fractions?")
# Generate classwork based on the conversation
classwork = await tutor.generate_classwork(
question_count=5,
difficulty='medium'
)
print(f"Generated {len(classwork['questions'])} questions:")
for i, question in enumerate(classwork['questions'], 1):
print(f"{i}. {question['question']}")
if question.get('options'):
for j, option in enumerate(question['options'], 1):
print(f" {chr(64+j)}. {option}")
if question.get('correct_answer'):
print(f" Answer: {question['correct_answer']}")
asyncio.run(classwork_example())
Direct SDK Usage:
from henotace_ai import HenotaceAI
# Initialize SDK
sdk = HenotaceAI(api_key="your_api_key_here")
# Conversation history
history = [
{'role': 'user', 'content': 'Explain photosynthesis'},
{'role': 'assistant', 'content': 'Photosynthesis is the process by which plants convert light energy into chemical energy...'},
{'role': 'user', 'content': 'What are the main components needed?'},
{'role': 'assistant', 'content': 'The main components are sunlight, carbon dioxide, water, and chlorophyll...'}
]
# Generate classwork
classwork = sdk.generate_classwork(
history=history,
subject="biology",
topic="photosynthesis",
question_count=4,
difficulty="medium"
)
print(f"Generated {len(classwork['questions'])} questions about photosynthesis")
Classwork Features:
- Multiple Difficulty Levels: Easy, medium, hard
- Context-Aware: Questions based on actual conversation content
- Flexible Question Types: Multiple choice, short answer, essay questions
- Subject-Specific: Tailored to the subject and topic discussed
- Configurable Count: Generate 1-10+ questions as needed
๐พ Custom Storage Connector
import asyncio
import json
from henotace_ai import HenotaceAI, create_tutor, StorageConnector, SessionStudent, SessionTutor, SessionChat
class FileStorageConnector(StorageConnector):
"""Example custom storage connector that saves to JSON files"""
def __init__(self, file_path="sessions.json"):
self.file_path = file_path
self.data = {"students": []}
self._load()
def _load(self):
try:
with open(self.file_path, 'r') as f:
self.data = json.load(f)
except FileNotFoundError:
self.data = {"students": []}
def _save(self):
with open(self.file_path, 'w') as f:
json.dump(self.data, f, indent=2)
def list_students(self):
return [SessionStudent(**s) for s in self.data.get("students", [])]
def upsert_student(self, student):
students = self.data.get("students", [])
# Find and update or add student
for i, s in enumerate(students):
if s["id"] == student.id:
students[i] = student.__dict__
break
else:
students.append(student.__dict__)
self.data["students"] = students
self._save()
# Implement other required methods...
async def custom_storage_example():
sdk = HenotaceAI(api_key="your_api_key_here")
# Use custom storage
storage = FileStorageConnector("my_sessions.json")
tutor = await create_tutor(
sdk=sdk,
student_id="student_789",
storage=storage
)
response = await tutor.send("Hello, I need help with chemistry!")
print(f"Response: {response}")
asyncio.run(custom_storage_example())
๐๏ธ Architecture
The SDK follows a clean, modular architecture that matches the Node.js SDK:
src/henotace_ai/
โโโ __init__.py # Main package exports
โโโ index.py # HenotaceAI main class
โโโ tutor.py # Tutor class and create_tutor factory
โโโ types.py # All data classes and type definitions
โโโ logger.py # Logging utilities (ConsoleLogger, NoOpLogger)
โโโ connectors/
โโโ __init__.py # Connector exports
โโโ inmemory.py # InMemoryConnector implementation
Key Components
HenotaceAI- Main SDK client for API interactionsTutor- Lightweight session manager for chat conversationsStorageConnector- Abstract interface for storage implementationsSessionSubject- Subject information (id, name, topic)SessionChat- Individual chat messages with timestampsLogger- Configurable logging system
๐ API Reference
HenotaceAI
Main client for interacting with the Henotace AI API.
Constructor
HenotaceAI(
api_key: str,
base_url: str = "https://api.djtconcept.ng",
timeout: int = 30,
retries: int = 3,
storage: Optional[StorageConnector] = None,
default_persona: Optional[str] = None,
default_preset: str = "tutor_default",
default_user_profile: Optional[Dict[str, Any]] = None,
default_metadata: Optional[Dict[str, Any]] = None,
logging: Optional[Dict[str, Any]] = None
)
Methods
get_status()- Check API status (returns full response)get_status_ok()- Quick status check (returns bool)complete_chat(history, input_text, preset, subject, topic, verbosity)- Send chat completion requestgenerate_classwork(history, subject, topic, question_count, difficulty)- Generate practice questionsset_base_url(url)- Set custom base URLget_config()- Get current configurationget_logger()- Get logger instance
Tutor
Lightweight tutor instance for managing chat sessions.
Constructor
Tutor(
sdk: HenotaceAI,
student_id: str,
tutor_id: str,
storage: Optional[StorageConnector] = None
)
Methods
send(message, context, preset)- Send message to tutorgenerate_classwork(question_count, difficulty)- Generate practice questions from conversationset_context(context)- Set persistent contextset_persona(persona)- Set tutor personaset_user_profile(profile)- Set user profileset_metadata(metadata)- Set metadataset_compression(**options)- Configure history compressionhistory()- Get chat historycompress_history()- Manually compress old chat historyids- Get student and tutor IDs (property)
StorageConnector
Abstract base class for storage implementations.
Required Methods
list_students()- List all studentsupsert_student(student)- Create or update studentdelete_student(student_id)- Delete studentlist_tutors(student_id)- List tutors for studentupsert_tutor(student_id, tutor)- Create or update tutordelete_tutor(student_id, tutor_id)- Delete tutorlist_chats(student_id, tutor_id)- List chat messagesappend_chat(student_id, tutor_id, chat)- Add chat messagereplace_chats(student_id, tutor_id, chats)- Replace all chats
Built-in Implementations
InMemoryConnector- In-memory storage for testing and development
๐ Supported Languages
The Python SDK supports multiple languages including Nigerian languages:
| Language Code | Language Name | Description |
|---|---|---|
en |
English | Default language |
pidgin |
Nigerian Pidgin | Nigerian Pidgin English |
yo-NG |
Yoruba | Yoruba with Nigerian cultural context |
ha-NG |
Hausa | Hausa with Nigerian cultural context |
ig-NG |
Igbo | Igbo with Nigerian cultural context |
๐ค Personalization Parameters
Personality Types
friendly(default): Approachable and supportiveencouraging: Warm, supportive, celebrates small winsstrict: Precise, direct, focused on accuracyhumorous: Uses appropriate humor to make learning engagingprofessional: Formal, professional tone while being helpful
Teaching Styles
socratic(default): Asks thought-provoking questions to guide discoverydirect: Provides clear explanations and step-by-step instructionsproblem_based: Focuses on problem-solving and practical applicationscollaborative: Works together with the student, building on their ideas
Interest Integration
The SDK automatically uses student interests for personalization when provided:
- Sports and games
- Music and arts
- Technology and programming
- Science and nature
- Any custom interests
โ๏ธ Configuration
Environment Variables
export HENOTACE_API_KEY="your_api_key_here"
export HENOTACE_BASE_URL="https://api.djtconcept.ng" # Optional
SDK Configuration
from henotace_ai import HenotaceAI, InMemoryConnector, LogLevel
sdk = HenotaceAI(
api_key="your_api_key",
base_url="https://api.djtconcept.ng", # Optional
timeout=30, # Request timeout in seconds
retries=3, # Number of retries for failed requests
storage=InMemoryConnector(), # Optional storage connector
default_persona="You are a helpful tutor.",
default_preset="tutor_default",
default_user_profile={"grade": "high_school"},
logging={
"enabled": True,
"level": LogLevel.INFO,
"logger": None # Use default console logger
}
)
Logging Configuration
from henotace_ai import HenotaceAI, LogLevel, ConsoleLogger, NoOpLogger
# Custom logger
custom_logger = ConsoleLogger(LogLevel.DEBUG)
sdk = HenotaceAI(
api_key="your_key",
logging={
"enabled": True,
"level": LogLevel.DEBUG,
"logger": custom_logger
}
)
# Disable logging
sdk = HenotaceAI(
api_key="your_key",
logging={"enabled": False}
)
๐ก๏ธ Error Handling
The SDK provides custom exceptions for different error types:
from henotace_ai import HenotaceError, HenotaceAPIError, HenotaceNetworkError
try:
response = await tutor.send("Hello!")
except HenotaceAPIError as e:
print(f"API Error: {e}")
except HenotaceNetworkError as e:
print(f"Network Error: {e}")
except HenotaceError as e:
print(f"General Error: {e}")
Exception Types
HenotaceError- Base exception for all SDK errorsHenotaceAPIError- API-specific errors (401, 429, 4xx, 5xx)HenotaceNetworkError- Network connectivity issues
Retry Logic
The SDK automatically handles:
- Rate Limiting - Automatic retry with exponential backoff
- Server Errors - Retry on 5xx errors with configurable attempts
- Network Issues - Retry on connection failures
๐ Examples
Check the examples/ directory for comprehensive examples:
basic_usage.py- Basic SDK usage and setupadvanced_features.py- Context, personas, user profiles, and history compressionclasswork_generation.py- Complete classwork generation examples and interactive demodemo_server.py- Flask web demo with interactive UItemplates/index.html- Web interface for testing
Running Examples
# Basic usage example
python examples/basic_usage.py
# Advanced features demo
python examples/advanced_features.py
# Classwork generation demo
python examples/classwork_generation.py
# Interactive classwork demo
python examples/classwork_generation.py --interactive
# Web demo server
python examples/demo_server.py
# Then visit http://localhost:5000
๐งช Testing
Run the test suite:
# Install development dependencies
pip install -e .[dev]
# Run tests
pytest tests/
# Run with coverage
pytest --cov=src/henotace_ai tests/
# Run integration tests (requires API key)
export HENOTACE_API_KEY=your_api_key_here
python test_classwork_integration.py
๐ Web Demo
The SDK includes a complete web demo:
# Start the demo server
python examples/demo_server.py
# Open your browser to http://localhost:5000
Features:
- โจ Real-time AI chat interface
- ๐ฏ Session management
- ๐ API key configuration
- ๐ Multiple subjects and grade levels
- ๐ฑ Responsive design
๐ค Contributing
We welcome contributions! Please see our Contributing Guide for details.
Development Setup
# Clone the repository
git clone https://github.com/Davidoshin/henotace-python-sdk.git
cd henotace-python-sdk
# Install in development mode
pip install -e .[dev]
# Run tests
pytest
# Format code
black src/ tests/
# Lint code
flake8 src/ tests/
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Support
- ๐ Documentation: https://docs.henotace.ai/python-sdk
- ๐ Issues: https://github.com/Davidoshin/henotace-python-sdk/issues
- ๐ง Email: support@henotace.ai
- ๐ฌ Discord: Join our community
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file henotace_ai_sdk-1.2.1.tar.gz.
File metadata
- Download URL: henotace_ai_sdk-1.2.1.tar.gz
- Upload date:
- Size: 51.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6c62a1b17c827041386ba2bc32429512e9aad90372d7eaf9bcf55605c1185cfc
|
|
| MD5 |
106ddcf34fa4e724d4a8d492725cc73e
|
|
| BLAKE2b-256 |
98942eb7536fbe7613f0b6ea427ace5aead838fa50b4b48ec1012dd06ba40dab
|
File details
Details for the file henotace_ai_sdk-1.2.1-py3-none-any.whl.
File metadata
- Download URL: henotace_ai_sdk-1.2.1-py3-none-any.whl
- Upload date:
- Size: 24.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ea39ed1615c584ccb3fee0eeee5954df963c17f4f74110aed0a98a4381df9d60
|
|
| MD5 |
d6e5eb4cc37029e1a5eb8575b52ee0ef
|
|
| BLAKE2b-256 |
e4df351e982e840c879fb4e1de94c37a37d2502f077d7b805d90ddeda30dd814
|