# 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
```bash
pip install henotace-ai-sdk
```
Or install from source:
```bash
git clone https://github.com/Davidoshin/henotace-python-sdk.git
cd henotace-python-sdk
pip install -e .
```
### Development Installation
For development with additional tools:
```bash
pip install -e .[dev]
```
This includes:
- `pytest` - Testing framework
- `pytest-asyncio` - Async testing support
- `black` - Code formatting
- `flake8` - Linting
- `mypy` - Type checking
## ๐ Quick Start
### Basic Usage (Programmatic)
```python
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:
```python
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:
```python
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:
```python
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:
```python
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
```python
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
```python
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
```python
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
```python
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:
```bash
pip install -e .[dev]
```
Then run:
```bash
export HENOTACE_API_KEY=your_key
henotace "Explain Pythagoras theorem"
```
Interactive REPL:
```bash
henotace
```
Advanced options:
```bash
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
```python
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:
```python
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:
```python
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:
```python
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:**
```python
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
```python
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 interactions
- **`Tutor`** - Lightweight session manager for chat conversations
- **`StorageConnector`** - Abstract interface for storage implementations
- **`SessionSubject`** - Subject information (id, name, topic)
- **`SessionChat`** - Individual chat messages with timestamps
- **`Logger`** - Configurable logging system
## ๐ API Reference
### HenotaceAI
Main client for interacting with the Henotace AI API.
#### Constructor
```python
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 request
- `generate_classwork(history, subject, topic, question_count, difficulty)` - Generate practice questions
- `set_base_url(url)` - Set custom base URL
- `get_config()` - Get current configuration
- `get_logger()` - Get logger instance
### Tutor
Lightweight tutor instance for managing chat sessions.
#### Constructor
```python
Tutor(
sdk: HenotaceAI,
student_id: str,
tutor_id: str,
storage: Optional[StorageConnector] = None
)
```
#### Methods
- `send(message, context, preset)` - Send message to tutor
- `generate_classwork(question_count, difficulty)` - Generate practice questions from conversation
- `set_context(context)` - Set persistent context
- `set_persona(persona)` - Set tutor persona
- `set_user_profile(profile)` - Set user profile
- `set_metadata(metadata)` - Set metadata
- `set_compression(**options)` - Configure history compression
- `history()` - Get chat history
- `compress_history()` - Manually compress old chat history
- `ids` - Get student and tutor IDs (property)
### StorageConnector
Abstract base class for storage implementations.
#### Required Methods
- `list_students()` - List all students
- `upsert_student(student)` - Create or update student
- `delete_student(student_id)` - Delete student
- `list_tutors(student_id)` - List tutors for student
- `upsert_tutor(student_id, tutor)` - Create or update tutor
- `delete_tutor(student_id, tutor_id)` - Delete tutor
- `list_chats(student_id, tutor_id)` - List chat messages
- `append_chat(student_id, tutor_id, chat)` - Add chat message
- `replace_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 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
### Teaching Styles
- **`socratic`** (default): 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
### 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
```bash
export HENOTACE_API_KEY="your_api_key_here"
export HENOTACE_BASE_URL="https://api.djtconcept.ng" # Optional
```
### SDK Configuration
```python
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
```python
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:
```python
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 errors
- **`HenotaceAPIError`** - 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 setup
- **`advanced_features.py`** - Context, personas, user profiles, and history compression
- **`classwork_generation.py`** - Complete classwork generation examples and interactive demo
- **`demo_server.py`** - Flask web demo with interactive UI
- **`templates/index.html`** - Web interface for testing
### Running Examples
```bash
# 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:
```bash
# 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:
```bash
# 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](CONTRIBUTING.md) for details.
### Development Setup
```bash
# 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](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](https://discord.gg/henotace)
Raw data
{
"_id": null,
"home_page": "https://github.com/Davidoshin/henotace-python-sdk",
"name": "henotace-ai-sdk",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.7",
"maintainer_email": null,
"keywords": "ai, tutor, education, api, sdk",
"author": "Henotace AI Team",
"author_email": "support@henotace.ai",
"download_url": "https://files.pythonhosted.org/packages/98/94/2eb7536fbe7613f0b6ea427ace5aead838fa50b4b48ec1012dd06ba40dab/henotace_ai_sdk-1.2.1.tar.gz",
"platform": null,
"description": "# Henotace AI Python SDK\n\nOfficial Python SDK for the Henotace AI API - your gateway to AI-powered tutoring and educational assistance.\n\n## \u2728 Features\n\n- **\ud83d\ude80 Easy Integration**: Simple, intuitive API for Python applications\n- **\ud83d\udcda Session Management**: Built-in support for managing student sessions and chat history\n- **\ud83d\udcbe Flexible Storage**: Pluggable storage connectors (in-memory, file, database, etc.)\n- **\u26a1 Async Support**: Full async/await support for modern Python applications\n- **\ud83d\udee1\ufe0f Error Handling**: Comprehensive error handling with custom exceptions\n- **\ud83d\udd04 Rate Limiting**: Built-in retry logic and rate limit handling\n- **\ud83c\udfaf Context Management**: Support for persistent context, personas, and user profiles\n- **\ud83d\udce6 Modular Architecture**: Clean, maintainable code structure matching Node.js SDK\n- **\ud83d\udd27 Professional Logging**: Configurable logging with multiple levels\n- **\ud83d\udddc\ufe0f History Compression**: Automatic chat history summarization for long conversations\n- **\ud83c\udf9b\ufe0f Smart Verbosity**: Auto-detects and adjusts response length based on user requests\n- **\ud83d\udccf Dynamic Response Lengths**: Brief, normal, detailed, and comprehensive response modes\n- **\ud83d\udcdd Classwork Generation**: Generate practice questions based on conversation history\n- **\ud83c\udf93 Educational Focus**: Specialized for tutoring and educational applications\n- **\ud83d\udd10 Secure Authentication**: Bearer token authentication with proper error handling\n- **\ud83c\udfa8 Advanced Personalization**: Comprehensive AI tutor personalization with learning pattern analysis\n- **\ud83e\udde0 Learning Analysis**: Automatic detection of learning levels, styles, and student patterns\n- **\ud83c\udfad Branding Support**: Custom branding and white-label options for enterprise users\n- **\ud83c\udf0d Multi-language**: Support for multiple languages including Nigerian languages (Yoruba, Hausa, Igbo, Pidgin)\n- **\ud83d\udc64 Personality Types**: Choose from friendly, professional, encouraging, strict, or humorous personalities\n- **\ud83d\udcd6 Teaching Styles**: Socratic, Direct Instruction, Problem-Based, or Collaborative learning approaches\n- **\ud83c\udfaf Interest Integration**: Personalize learning based on student interests and preferences\n- **\ud83d\udcca Progress Tracking**: Automatic tracking of student strengths, struggles, and learning patterns\n\n## \ud83d\udce6 Installation\n\n```bash\npip install henotace-ai-sdk\n```\n\nOr install from source:\n\n```bash\ngit clone https://github.com/Davidoshin/henotace-python-sdk.git\ncd henotace-python-sdk\npip install -e .\n```\n\n### Development Installation\n\nFor development with additional tools:\n\n```bash\npip install -e .[dev]\n```\n\nThis includes:\n- `pytest` - Testing framework\n- `pytest-asyncio` - Async testing support\n- `black` - Code formatting\n- `flake8` - Linting\n- `mypy` - Type checking\n\n## \ud83d\ude80 Quick Start\n\n### Basic Usage (Programmatic)\n\n```python\nimport asyncio\nfrom henotace_ai import HenotaceAI, create_tutor, SessionSubject, InMemoryConnector\n\nasync def main():\n # Initialize the SDK with storage\n sdk = HenotaceAI(\n api_key=\"your_api_key_here\",\n storage=InMemoryConnector() # Optional: for session persistence\n )\n \n # Check API status\n if sdk.get_status_ok():\n print(\"\u2705 API is available\")\n else:\n print(\"\u274c API is not available\")\n return\n \n # Create a tutor with subject information\n tutor = await create_tutor(\n sdk=sdk,\n student_id=\"student_123\",\n tutor_name=\"Math Tutor\",\n subject=SessionSubject(\n id=\"math\",\n name=\"Mathematics\", \n topic=\"Algebra\"\n )\n )\n \n # Send a message\n response = await tutor.send(\"Can you help me solve 2x + 5 = 13?\")\n print(f\"AI Response: {response}\")\n \n # Continue the conversation\n response = await tutor.send(\"What's the first step?\")\n print(f\"AI Response: {response}\")\n\n# Run the example\nasyncio.run(main())\n```\n\n### \ud83c\udfa8 Advanced Personalization Features\n\nThe Henotace AI Python SDK includes comprehensive personalization capabilities that automatically analyze learning patterns and adapt to individual student needs.\n\n#### \ud83e\udde0 Learning Pattern Analysis\n\nThe AI automatically analyzes conversation history to detect:\n- **Learning Level**: Beginner, Intermediate, or Advanced\n- **Learning Style**: Inquisitive, Example-driven, or Practice-oriented\n- **Student Struggles**: Areas where the student needs extra support\n- **Student Strengths**: Topics where the student excels\n- **Key Concepts**: Important topics discussed in the conversation\n- **Learning Patterns**: How the student prefers to learn\n\n#### \ud83c\udf0d Multi-Language Support\n\nSupport for multiple languages including Nigerian languages:\n\n```python\nimport asyncio\nfrom henotace_ai import HenotaceAI, InMemoryConnector\n\nasync def multi_language_example():\n sdk = HenotaceAI(\n api_key=\"your_api_key_here\",\n storage=InMemoryConnector()\n )\n \n # Supported languages\n languages = [\n {\"code\": \"en\", \"name\": \"English\", \"question\": \"What is gravity?\"},\n {\"code\": \"pidgin\", \"name\": \"Nigerian Pidgin\", \"question\": \"Wetin be gravity?\"},\n {\"code\": \"yo-NG\", \"name\": \"Yoruba\", \"question\": \"K\u00ed ni gravity?\"},\n {\"code\": \"ha-NG\", \"name\": \"Hausa\", \"question\": \"Menene gravity?\"},\n {\"code\": \"ig-NG\", \"name\": \"Igbo\", \"question\": \"G\u1ecbn\u1ecb b\u1ee5 gravity?\"}\n ]\n \n for lang in languages:\n print(f\"\\n\ud83d\udde3\ufe0f Testing {lang['name']} ({lang['code']}):\")\n \n response = await sdk.chat_completion(\n history=[],\n input_text=lang[\"question\"],\n subject=\"physics\",\n topic=\"mechanics\",\n language=lang[\"code\"],\n personality=\"friendly\",\n teaching_style=\"direct\"\n )\n \n print(f\"\u2705 {lang['name']} response: {response['ai_response'][:150]}...\")\n\n# Run the example\nasyncio.run(multi_language_example())\n```\n\n#### \ud83d\udc64 Personality Types\n\nChoose from different tutor personalities:\n\n```python\nimport asyncio\nfrom henotace_ai import HenotaceAI, InMemoryConnector\n\nasync def personality_example():\n sdk = HenotaceAI(api_key=\"your_api_key_here\")\n \n personalities = [\n \"friendly\", # Approachable and supportive\n \"encouraging\", # Warm, supportive, celebrates small wins\n \"strict\", # Precise, direct, focused on accuracy\n \"humorous\", # Uses appropriate humor to make learning engaging\n \"professional\" # Formal, professional tone while being helpful\n ]\n \n for personality in personalities:\n print(f\"\\n\ud83e\uddd1\u200d\ud83c\udfeb Testing {personality} personality:\")\n \n response = await sdk.chat_completion(\n history=[],\n input_text=\"I find math difficult\",\n subject=\"mathematics\",\n topic=\"algebra\",\n personality=personality,\n teaching_style=\"socratic\",\n author_name=\"Math Tutor\"\n )\n \n print(f\"\u2705 {personality} response: {response['ai_response'][:150]}...\")\n\nasyncio.run(personality_example())\n```\n\n#### \ud83d\udcd6 Teaching Styles\n\nSelect the teaching approach that works best:\n\n```python\nimport asyncio\nfrom henotace_ai import HenotaceAI, InMemoryConnector\n\nasync def teaching_style_example():\n sdk = HenotaceAI(api_key=\"your_api_key_here\")\n \n teaching_styles = [\n \"socratic\", # Asks thought-provoking questions to guide discovery\n \"direct\", # Provides clear explanations and step-by-step instructions\n \"problem_based\", # Focuses on problem-solving and practical applications\n \"collaborative\" # Works together with the student, building on their ideas\n ]\n \n for style in teaching_styles:\n print(f\"\\n\ud83d\udcda Testing {style} teaching style:\")\n \n response = await sdk.chat_completion(\n history=[],\n input_text=\"Explain quadratic equations\",\n subject=\"mathematics\",\n topic=\"algebra\",\n personality=\"friendly\",\n teaching_style=style,\n author_name=\"Algebra Expert\"\n )\n \n print(f\"\u2705 {style} response: {response['ai_response'][:150]}...\")\n\nasyncio.run(teaching_style_example())\n```\n\n#### \ud83c\udfaf Interest Integration\n\nPersonalize learning based on student interests:\n\n```python\nimport asyncio\nfrom henotace_ai import HenotaceAI, InMemoryConnector\n\nasync def interest_integration_example():\n sdk = HenotaceAI(api_key=\"your_api_key_here\")\n \n # The AI automatically uses student interests for personalization\n response = await sdk.chat_completion(\n history=[\n {\"role\": \"user\", \"content\": \"I love football and music\"},\n {\"role\": \"assistant\", \"content\": \"Great! Let me use football examples to explain math concepts...\"}\n ],\n input_text=\"Explain physics concepts\",\n subject=\"physics\",\n topic=\"mechanics\",\n interests=[\"football\", \"sports\", \"music\"], # Student interests for personalization\n personality=\"encouraging\",\n teaching_style=\"problem_based\"\n )\n \n print(f\"AI Response: {response['ai_response']}\")\n # The AI will automatically use football/sports examples for physics concepts\n\nasyncio.run(interest_integration_example())\n```\n\n#### \ud83d\udcca Complete Personalization Example\n\n```python\nimport asyncio\nfrom henotace_ai import HenotaceAI, InMemoryConnector\n\nasync def complete_personalization_example():\n sdk = HenotaceAI(api_key=\"your_api_key_here\")\n \n # Simulate a conversation that shows learning patterns\n conversation_history = [\n {\"role\": \"user\", \"content\": \"I love football and find math difficult\"},\n {\"role\": \"assistant\", \"content\": \"I understand! Let me use football examples to explain math concepts...\"},\n {\"role\": \"user\", \"content\": \"Can you show me how to calculate angles?\"},\n {\"role\": \"assistant\", \"content\": \"Great question! In football, when a player kicks the ball...\"},\n {\"role\": \"user\", \"content\": \"I still don't understand trigonometry\"}\n ]\n \n print(\"\ud83d\udcda Simulating learning conversation...\")\n \n response = await sdk.chat_completion(\n history=conversation_history,\n input_text=\"Can you explain sine and cosine using football?\",\n subject=\"mathematics\",\n topic=\"trigonometry\",\n author_name=\"Coach Math\",\n language=\"en\",\n personality=\"encouraging\",\n teaching_style=\"problem_based\",\n interests=[\"football\", \"sports\", \"gaming\"],\n branding={\n \"name\": \"Sports Math Tutor\",\n \"primaryColor\": \"#FF6B35\",\n \"secondaryColor\": \"#F7931E\"\n }\n )\n \n print(\"\u2705 Advanced personalization response:\")\n print(response['ai_response'])\n \n # The AI will automatically:\n # 1. Detect the student struggles with math\n # 2. Use football/sports examples for trigonometry\n # 3. Apply encouraging personality\n # 4. Use problem-based teaching approach\n # 5. Reference previous conversation about angles\n\nasyncio.run(complete_personalization_example())\n```\n\n### Enhanced Customization\n\n```python\nimport asyncio\nfrom henotace_ai import HenotaceAI, InMemoryConnector\n\nasync def enhanced_example():\n sdk = HenotaceAI(\n api_key=\"your_api_key_here\",\n storage=InMemoryConnector()\n )\n \n # Enhanced chat completion with customization\n response = await sdk.chat_completion(\n history=[\n {\"role\": \"user\", \"content\": \"What is photosynthesis?\"},\n {\"role\": \"assistant\", \"content\": \"Photosynthesis is the process...\"}\n ],\n input_text=\"Can you explain it in simpler terms?\",\n subject=\"biology\",\n topic=\"plant_biology\",\n author_name=\"Dr. Smith\",\n language=\"en\",\n personality=\"friendly\",\n teaching_style=\"socratic\",\n branding={\n \"name\": \"Bio Tutor\",\n \"primaryColor\": \"#3B82F6\",\n \"secondaryColor\": \"#1E40AF\"\n }\n )\n \n print(f\"AI Response: {response['ai_response']}\")\n\n# Run the example\nasyncio.run(enhanced_example())\n```\n\n### Tutor with Advanced Personalization\n\n```python\nimport asyncio\nfrom henotace_ai import HenotaceAI, create_tutor, SessionSubject, InMemoryConnector\n\nasync def tutor_advanced_personalization_example():\n sdk = HenotaceAI(\n api_key=\"your_api_key_here\",\n storage=InMemoryConnector()\n )\n \n # Create a tutor with enhanced customization\n tutor = await create_tutor(\n sdk=sdk,\n student_id=\"student_123\",\n tutor_name=\"Biology Expert\",\n subject=SessionSubject(\n id=\"biology\",\n name=\"Biology\",\n topic=\"cell_structure\"\n )\n )\n \n # Set tutor context and persona\n tutor.set_context([\n \"Student loves sports and music\",\n \"Prefers visual examples and analogies\"\n ])\n tutor.set_persona(\"You are an encouraging biology tutor who uses sports analogies\")\n tutor.set_user_profile({\n \"name\": \"Alex\",\n \"interests\": [\"football\", \"music\", \"art\"],\n \"learning_style\": \"visual\"\n })\n \n # Send message with full personalization parameters\n response = await tutor.send(\n \"Explain cell division\",\n author_name=\"Dr. Johnson\",\n language=\"en\",\n personality=\"encouraging\",\n teaching_style=\"direct\",\n interests=[\"sports\", \"music\", \"art\"], # Student interests for personalization\n branding={\n \"name\": \"Cell Biology Tutor\",\n \"primaryColor\": \"#10B981\",\n \"secondaryColor\": \"#047857\"\n }\n )\n \n print(f\"Tutor Response: {response}\")\n\n# Run the example\nasyncio.run(tutor_advanced_personalization_example())\n```\n\n### Multi-Language Tutor Example\n\n```python\nimport asyncio\nfrom henotace_ai import HenotaceAI, create_tutor, SessionSubject, InMemoryConnector\n\nasync def multi_language_tutor_example():\n sdk = HenotaceAI(api_key=\"your_api_key_here\")\n \n # Create tutors for different languages\n tutors = [\n {\n \"name\": \"English Math Tutor\",\n \"language\": \"en\",\n \"question\": \"What is 2 + 2?\"\n },\n {\n \"name\": \"Pidgin Math Tutor\", \n \"language\": \"pidgin\",\n \"question\": \"Wetin be 2 + 2?\"\n },\n {\n \"name\": \"Yoruba Math Tutor\",\n \"language\": \"yo-NG\", \n \"question\": \"K\u00ed ni 2 + 2?\"\n }\n ]\n \n for tutor_info in tutors:\n print(f\"\\n\ud83d\udde3\ufe0f Testing {tutor_info['name']}:\")\n \n tutor = await create_tutor(\n sdk=sdk,\n student_id=\"student_123\",\n tutor_name=tutor_info[\"name\"],\n subject=SessionSubject(id=\"math\", name=\"Mathematics\", topic=\"arithmetic\")\n )\n \n response = await tutor.send(\n tutor_info[\"question\"],\n language=tutor_info[\"language\"],\n personality=\"friendly\",\n teaching_style=\"direct\"\n )\n \n print(f\"\u2705 {tutor_info['name']} response: {response[:150]}...\")\n\nasyncio.run(multi_language_tutor_example())\n```\n\n### \ud83d\udda5\ufe0f CLI Usage\n\nInstall editable and expose CLI:\n\n```bash\npip install -e .[dev]\n```\n\nThen run:\n\n```bash\nexport HENOTACE_API_KEY=your_key\nhenotace \"Explain Pythagoras theorem\"\n```\n\nInteractive REPL:\n\n```bash\nhenotace\n```\n\nAdvanced options:\n\n```bash\nhenotace --student-id stu1 --tutor-name math --persona \"You are a patient math tutor\" \"Solve x+2=5\"\n```\n\nAvailable CLI options:\n- `--api-key` - Your Henotace API key\n- `--student-id` - Student identifier\n- `--tutor-name` - Name for the AI tutor\n- `--persona` - Custom tutor personality\n- `--context` - Additional context lines\n\n### \ud83c\udfaf Advanced Usage with Context and Persona\n\n```python\nimport asyncio\nfrom henotace_ai import HenotaceAI, create_tutor, SessionSubject, InMemoryConnector\n\nasync def advanced_example():\n # Initialize SDK with custom configuration\n sdk = HenotaceAI(\n api_key=\"your_api_key_here\",\n storage=InMemoryConnector(),\n default_persona=\"You are a helpful and patient tutor.\",\n default_preset=\"tutor_default\"\n )\n \n # Create a specialized tutor\n tutor = await create_tutor(\n sdk=sdk,\n student_id=\"student_456\",\n tutor_name=\"Physics Tutor\",\n subject=SessionSubject(\n id=\"physics\",\n name=\"Physics\",\n topic=\"Mechanics\"\n ),\n grade_level=\"high_school\",\n language=\"en\"\n )\n \n # Set persona and context\n tutor.set_persona(\"You are an enthusiastic physics tutor who loves to use real-world examples and analogies to explain complex concepts.\")\n tutor.set_context([\n \"The student is in 11th grade and is learning about Newton's laws.\",\n \"They prefer visual explanations and step-by-step problem solving.\"\n ])\n \n # Set user profile\n tutor.set_user_profile({\n \"name\": \"Alex\",\n \"grade\": \"11th\",\n \"learning_style\": \"visual\",\n \"difficulty_level\": \"intermediate\"\n })\n \n # Configure history compression\n tutor.set_compression(\n max_turns=10, # Keep last 10 messages\n max_summary_chars=800, # Limit summary length\n checkpoint_every=5 # Compress every 5 messages\n )\n \n # Start tutoring session\n response = await tutor.send(\n \"I'm confused about Newton's second law. Can you explain it?\",\n context=\"We just covered Newton's first law in the previous lesson.\"\n )\n print(f\"Tutor: {response}\")\n \n # Check chat history\n history = tutor.history()\n print(f\"Chat history has {len(history)} messages\")\n\nasyncio.run(advanced_example())\n```\n\n### \ud83d\udcca Automatic Progress Tracking\n\nThe AI automatically tracks and adapts to student learning patterns:\n\n```python\nimport asyncio\nfrom henotace_ai import HenotaceAI, create_tutor, SessionSubject\n\nasync def progress_tracking_example():\n sdk = HenotaceAI(api_key=\"your_api_key_here\")\n \n # Create a tutor\n tutor = await create_tutor(\n sdk=sdk,\n student_id=\"student_123\",\n tutor_name=\"Math Tutor\",\n subject=SessionSubject(id=\"math\", name=\"Mathematics\", topic=\"algebra\")\n )\n \n # Simulate a learning conversation\n messages = [\n \"I find algebra difficult\",\n \"Can you explain it using football examples?\",\n \"What about quadratic equations?\",\n \"I still don't understand the quadratic formula\"\n ]\n \n for message in messages:\n print(f\"\\n\ud83d\udc64 Student: {message}\")\n response = await tutor.send(message)\n print(f\"\ud83e\udd16 Tutor: {response[:200]}...\")\n \n # The AI automatically:\n # - Detects learning struggles and strengths\n # - Adapts teaching style based on responses\n # - Uses interests (football) for examples\n # - Tracks progress and adjusts complexity\n # - Maintains conversation context\n \n # Get chat history to see the learning journey\n history = tutor.history()\n print(f\"\\n\ud83d\udcc8 Learning session completed with {len(history)} messages\")\n\nasyncio.run(progress_tracking_example())\n```\n\n### \ud83c\udf9b\ufe0f Smart Verbosity System\n\nThe SDK automatically detects and adjusts response length based on user requests:\n\n```python\nimport asyncio\nfrom henotace_ai import HenotaceAI, create_tutor\n\nasync def verbosity_example():\n sdk = HenotaceAI(api_key=\"your_api_key_here\")\n tutor = await create_tutor(sdk=sdk, student_id=\"student_123\")\n \n # Auto-detects verbosity from user input\n brief_response = await tutor.send(\"Briefly explain photosynthesis\")\n # Returns: Short, concise explanation (1-2 sentences)\n \n normal_response = await tutor.send(\"What is gravity?\")\n # Returns: Standard explanation (2-4 sentences)\n \n detailed_response = await tutor.send(\"Can you give me a detailed explanation of thermodynamics?\")\n # Returns: Expanded explanation (4-8 sentences)\n \n comprehensive_response = await tutor.send(\"I need a comprehensive guide to quantum physics\")\n # Returns: Full guide (8+ sentences with examples and context)\n \n print(f\"Brief: {len(brief_response)} chars\")\n print(f\"Normal: {len(normal_response)} chars\") \n print(f\"Detailed: {len(detailed_response)} chars\")\n print(f\"Comprehensive: {len(comprehensive_response)} chars\")\n\nasyncio.run(verbosity_example())\n```\n\n**Verbosity Levels:**\n- **Brief** (1-2 sentences): Keywords like \"briefly\", \"short\", \"quick\", \"simple\"\n- **Normal** (2-4 sentences): Default level for regular questions\n- **Detailed** (4-8 sentences): Keywords like \"detailed\", \"more information\", \"elaborate\"\n- **Comprehensive** (8+ sentences): Keywords like \"comprehensive\", \"everything\", \"step by step\"\n\n### \ud83d\udcdd Classwork Generation\n\nGenerate practice questions based on conversation history for any subject:\n\n```python\nimport asyncio\nfrom henotace_ai import HenotaceAI, create_tutor, SessionSubject\n\nasync def classwork_example():\n sdk = HenotaceAI(api_key=\"your_api_key_here\")\n \n # Create a tutor and have a conversation\n tutor = await create_tutor(\n sdk=sdk,\n student_id=\"student_123\",\n tutor_name=\"Math Tutor\",\n subject=SessionSubject(id=\"math\", name=\"Mathematics\", topic=\"Algebra\")\n )\n \n # Simulate a tutoring session\n await tutor.send(\"I need help with linear equations\")\n await tutor.send(\"How do I solve 2x + 5 = 13?\")\n await tutor.send(\"What about equations with fractions?\")\n \n # Generate classwork based on the conversation\n classwork = await tutor.generate_classwork(\n question_count=5,\n difficulty='medium'\n )\n \n print(f\"Generated {len(classwork['questions'])} questions:\")\n for i, question in enumerate(classwork['questions'], 1):\n print(f\"{i}. {question['question']}\")\n if question.get('options'):\n for j, option in enumerate(question['options'], 1):\n print(f\" {chr(64+j)}. {option}\")\n if question.get('correct_answer'):\n print(f\" Answer: {question['correct_answer']}\")\n\nasyncio.run(classwork_example())\n```\n\n**Direct SDK Usage:**\n\n```python\nfrom henotace_ai import HenotaceAI\n\n# Initialize SDK\nsdk = HenotaceAI(api_key=\"your_api_key_here\")\n\n# Conversation history\nhistory = [\n {'role': 'user', 'content': 'Explain photosynthesis'},\n {'role': 'assistant', 'content': 'Photosynthesis is the process by which plants convert light energy into chemical energy...'},\n {'role': 'user', 'content': 'What are the main components needed?'},\n {'role': 'assistant', 'content': 'The main components are sunlight, carbon dioxide, water, and chlorophyll...'}\n]\n\n# Generate classwork\nclasswork = sdk.generate_classwork(\n history=history,\n subject=\"biology\",\n topic=\"photosynthesis\",\n question_count=4,\n difficulty=\"medium\"\n)\n\nprint(f\"Generated {len(classwork['questions'])} questions about photosynthesis\")\n```\n\n**Classwork Features:**\n- **Multiple Difficulty Levels**: Easy, medium, hard\n- **Context-Aware**: Questions based on actual conversation content\n- **Flexible Question Types**: Multiple choice, short answer, essay questions\n- **Subject-Specific**: Tailored to the subject and topic discussed\n- **Configurable Count**: Generate 1-10+ questions as needed\n\n### \ud83d\udcbe Custom Storage Connector\n\n```python\nimport asyncio\nimport json\nfrom henotace_ai import HenotaceAI, create_tutor, StorageConnector, SessionStudent, SessionTutor, SessionChat\n\nclass FileStorageConnector(StorageConnector):\n \"\"\"Example custom storage connector that saves to JSON files\"\"\"\n \n def __init__(self, file_path=\"sessions.json\"):\n self.file_path = file_path\n self.data = {\"students\": []}\n self._load()\n \n def _load(self):\n try:\n with open(self.file_path, 'r') as f:\n self.data = json.load(f)\n except FileNotFoundError:\n self.data = {\"students\": []}\n \n def _save(self):\n with open(self.file_path, 'w') as f:\n json.dump(self.data, f, indent=2)\n \n def list_students(self):\n return [SessionStudent(**s) for s in self.data.get(\"students\", [])]\n \n def upsert_student(self, student):\n students = self.data.get(\"students\", [])\n # Find and update or add student\n for i, s in enumerate(students):\n if s[\"id\"] == student.id:\n students[i] = student.__dict__\n break\n else:\n students.append(student.__dict__)\n self.data[\"students\"] = students\n self._save()\n \n # Implement other required methods...\n\nasync def custom_storage_example():\n sdk = HenotaceAI(api_key=\"your_api_key_here\")\n \n # Use custom storage\n storage = FileStorageConnector(\"my_sessions.json\")\n \n tutor = await create_tutor(\n sdk=sdk,\n student_id=\"student_789\",\n storage=storage\n )\n \n response = await tutor.send(\"Hello, I need help with chemistry!\")\n print(f\"Response: {response}\")\n\nasyncio.run(custom_storage_example())\n```\n\n## \ud83c\udfd7\ufe0f Architecture\n\nThe SDK follows a clean, modular architecture that matches the Node.js SDK:\n\n```\nsrc/henotace_ai/\n\u251c\u2500\u2500 __init__.py # Main package exports\n\u251c\u2500\u2500 index.py # HenotaceAI main class\n\u251c\u2500\u2500 tutor.py # Tutor class and create_tutor factory\n\u251c\u2500\u2500 types.py # All data classes and type definitions\n\u251c\u2500\u2500 logger.py # Logging utilities (ConsoleLogger, NoOpLogger)\n\u2514\u2500\u2500 connectors/\n \u251c\u2500\u2500 __init__.py # Connector exports\n \u2514\u2500\u2500 inmemory.py # InMemoryConnector implementation\n```\n\n### Key Components\n\n- **`HenotaceAI`** - Main SDK client for API interactions\n- **`Tutor`** - Lightweight session manager for chat conversations\n- **`StorageConnector`** - Abstract interface for storage implementations\n- **`SessionSubject`** - Subject information (id, name, topic)\n- **`SessionChat`** - Individual chat messages with timestamps\n- **`Logger`** - Configurable logging system\n\n## \ud83d\udcda API Reference\n\n### HenotaceAI\n\nMain client for interacting with the Henotace AI API.\n\n#### Constructor\n\n```python\nHenotaceAI(\n api_key: str,\n base_url: str = \"https://api.djtconcept.ng\",\n timeout: int = 30,\n retries: int = 3,\n storage: Optional[StorageConnector] = None,\n default_persona: Optional[str] = None,\n default_preset: str = \"tutor_default\",\n default_user_profile: Optional[Dict[str, Any]] = None,\n default_metadata: Optional[Dict[str, Any]] = None,\n logging: Optional[Dict[str, Any]] = None\n)\n```\n\n#### Methods\n\n- `get_status()` - Check API status (returns full response)\n- `get_status_ok()` - Quick status check (returns bool)\n- `complete_chat(history, input_text, preset, subject, topic, verbosity)` - Send chat completion request\n- `generate_classwork(history, subject, topic, question_count, difficulty)` - Generate practice questions\n- `set_base_url(url)` - Set custom base URL\n- `get_config()` - Get current configuration\n- `get_logger()` - Get logger instance\n\n### Tutor\n\nLightweight tutor instance for managing chat sessions.\n\n#### Constructor\n\n```python\nTutor(\n sdk: HenotaceAI,\n student_id: str,\n tutor_id: str,\n storage: Optional[StorageConnector] = None\n)\n```\n\n#### Methods\n\n- `send(message, context, preset)` - Send message to tutor\n- `generate_classwork(question_count, difficulty)` - Generate practice questions from conversation\n- `set_context(context)` - Set persistent context\n- `set_persona(persona)` - Set tutor persona\n- `set_user_profile(profile)` - Set user profile\n- `set_metadata(metadata)` - Set metadata\n- `set_compression(**options)` - Configure history compression\n- `history()` - Get chat history\n- `compress_history()` - Manually compress old chat history\n- `ids` - Get student and tutor IDs (property)\n\n### StorageConnector\n\nAbstract base class for storage implementations.\n\n#### Required Methods\n\n- `list_students()` - List all students\n- `upsert_student(student)` - Create or update student\n- `delete_student(student_id)` - Delete student\n- `list_tutors(student_id)` - List tutors for student\n- `upsert_tutor(student_id, tutor)` - Create or update tutor\n- `delete_tutor(student_id, tutor_id)` - Delete tutor\n- `list_chats(student_id, tutor_id)` - List chat messages\n- `append_chat(student_id, tutor_id, chat)` - Add chat message\n- `replace_chats(student_id, tutor_id, chats)` - Replace all chats\n\n#### Built-in Implementations\n\n- `InMemoryConnector` - In-memory storage for testing and development\n\n## \ud83c\udf0d Supported Languages\n\nThe Python SDK supports multiple languages including Nigerian languages:\n\n| Language Code | Language Name | Description |\n|---------------|---------------|-------------|\n| `en` | English | Default language |\n| `pidgin` | Nigerian Pidgin | Nigerian Pidgin English |\n| `yo-NG` | Yoruba | Yoruba with Nigerian cultural context |\n| `ha-NG` | Hausa | Hausa with Nigerian cultural context |\n| `ig-NG` | Igbo | Igbo with Nigerian cultural context |\n\n## \ud83d\udc64 Personalization Parameters\n\n### Personality Types\n- **`friendly`** (default): Approachable and supportive\n- **`encouraging`**: Warm, supportive, celebrates small wins\n- **`strict`**: Precise, direct, focused on accuracy\n- **`humorous`**: Uses appropriate humor to make learning engaging\n- **`professional`**: Formal, professional tone while being helpful\n\n### Teaching Styles\n- **`socratic`** (default): Asks thought-provoking questions to guide discovery\n- **`direct`**: Provides clear explanations and step-by-step instructions\n- **`problem_based`**: Focuses on problem-solving and practical applications\n- **`collaborative`**: Works together with the student, building on their ideas\n\n### Interest Integration\nThe SDK automatically uses student interests for personalization when provided:\n- Sports and games\n- Music and arts\n- Technology and programming\n- Science and nature\n- Any custom interests\n\n## \u2699\ufe0f Configuration\n\n### Environment Variables\n\n```bash\nexport HENOTACE_API_KEY=\"your_api_key_here\"\nexport HENOTACE_BASE_URL=\"https://api.djtconcept.ng\" # Optional\n```\n\n### SDK Configuration\n\n```python\nfrom henotace_ai import HenotaceAI, InMemoryConnector, LogLevel\n\nsdk = HenotaceAI(\n api_key=\"your_api_key\",\n base_url=\"https://api.djtconcept.ng\", # Optional\n timeout=30, # Request timeout in seconds\n retries=3, # Number of retries for failed requests\n storage=InMemoryConnector(), # Optional storage connector\n default_persona=\"You are a helpful tutor.\",\n default_preset=\"tutor_default\",\n default_user_profile={\"grade\": \"high_school\"},\n logging={\n \"enabled\": True,\n \"level\": LogLevel.INFO,\n \"logger\": None # Use default console logger\n }\n)\n```\n\n### Logging Configuration\n\n```python\nfrom henotace_ai import HenotaceAI, LogLevel, ConsoleLogger, NoOpLogger\n\n# Custom logger\ncustom_logger = ConsoleLogger(LogLevel.DEBUG)\n\nsdk = HenotaceAI(\n api_key=\"your_key\",\n logging={\n \"enabled\": True,\n \"level\": LogLevel.DEBUG,\n \"logger\": custom_logger\n }\n)\n\n# Disable logging\nsdk = HenotaceAI(\n api_key=\"your_key\",\n logging={\"enabled\": False}\n)\n```\n\n## \ud83d\udee1\ufe0f Error Handling\n\nThe SDK provides custom exceptions for different error types:\n\n```python\nfrom henotace_ai import HenotaceError, HenotaceAPIError, HenotaceNetworkError\n\ntry:\n response = await tutor.send(\"Hello!\")\nexcept HenotaceAPIError as e:\n print(f\"API Error: {e}\")\nexcept HenotaceNetworkError as e:\n print(f\"Network Error: {e}\")\nexcept HenotaceError as e:\n print(f\"General Error: {e}\")\n```\n\n### Exception Types\n\n- **`HenotaceError`** - Base exception for all SDK errors\n- **`HenotaceAPIError`** - API-specific errors (401, 429, 4xx, 5xx)\n- **`HenotaceNetworkError`** - Network connectivity issues\n\n### Retry Logic\n\nThe SDK automatically handles:\n- **Rate Limiting** - Automatic retry with exponential backoff\n- **Server Errors** - Retry on 5xx errors with configurable attempts\n- **Network Issues** - Retry on connection failures\n\n## \ud83d\udcd6 Examples\n\nCheck the `examples/` directory for comprehensive examples:\n\n- **`basic_usage.py`** - Basic SDK usage and setup\n- **`advanced_features.py`** - Context, personas, user profiles, and history compression\n- **`classwork_generation.py`** - Complete classwork generation examples and interactive demo\n- **`demo_server.py`** - Flask web demo with interactive UI\n- **`templates/index.html`** - Web interface for testing\n\n### Running Examples\n\n```bash\n# Basic usage example\npython examples/basic_usage.py\n\n# Advanced features demo\npython examples/advanced_features.py\n\n# Classwork generation demo\npython examples/classwork_generation.py\n\n# Interactive classwork demo\npython examples/classwork_generation.py --interactive\n\n# Web demo server\npython examples/demo_server.py\n# Then visit http://localhost:5000\n```\n\n## \ud83e\uddea Testing\n\nRun the test suite:\n\n```bash\n# Install development dependencies\npip install -e .[dev]\n\n# Run tests\npytest tests/\n\n# Run with coverage\npytest --cov=src/henotace_ai tests/\n\n# Run integration tests (requires API key)\nexport HENOTACE_API_KEY=your_api_key_here\npython test_classwork_integration.py\n```\n\n## \ud83d\ude80 Web Demo\n\nThe SDK includes a complete web demo:\n\n```bash\n# Start the demo server\npython examples/demo_server.py\n\n# Open your browser to http://localhost:5000\n```\n\nFeatures:\n- \u2728 Real-time AI chat interface\n- \ud83c\udfaf Session management\n- \ud83d\udd11 API key configuration\n- \ud83d\udcda Multiple subjects and grade levels\n- \ud83d\udcf1 Responsive design\n\n## \ud83e\udd1d Contributing\n\nWe welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.\n\n### Development Setup\n\n```bash\n# Clone the repository\ngit clone https://github.com/Davidoshin/henotace-python-sdk.git\ncd henotace-python-sdk\n\n# Install in development mode\npip install -e .[dev]\n\n# Run tests\npytest\n\n# Format code\nblack src/ tests/\n\n# Lint code\nflake8 src/ tests/\n```\n\n## \ud83d\udcc4 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## \ud83c\udd98 Support\n\n- \ud83d\udcda **Documentation**: https://docs.henotace.ai/python-sdk\n- \ud83d\udc1b **Issues**: https://github.com/Davidoshin/henotace-python-sdk/issues\n- \ud83d\udce7 **Email**: support@henotace.ai\n- \ud83d\udcac **Discord**: [Join our community](https://discord.gg/henotace)\n",
"bugtrack_url": null,
"license": null,
"summary": "Official Python SDK for the Henotace AI API",
"version": "1.2.1",
"project_urls": {
"Bug Reports": "https://github.com/Davidoshin/henotace-python-sdk/issues",
"Documentation": "https://docs.henotace.ai/python-sdk",
"Homepage": "https://github.com/Davidoshin/henotace-python-sdk",
"Source": "https://github.com/Davidoshin/henotace-python-sdk"
},
"split_keywords": [
"ai",
" tutor",
" education",
" api",
" sdk"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "e4df351e982e840c879fb4e1de94c37a37d2502f077d7b805d90ddeda30dd814",
"md5": "d6e5eb4cc37029e1a5eb8575b52ee0ef",
"sha256": "ea39ed1615c584ccb3fee0eeee5954df963c17f4f74110aed0a98a4381df9d60"
},
"downloads": -1,
"filename": "henotace_ai_sdk-1.2.1-py3-none-any.whl",
"has_sig": false,
"md5_digest": "d6e5eb4cc37029e1a5eb8575b52ee0ef",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.7",
"size": 24730,
"upload_time": "2025-10-28T01:14:43",
"upload_time_iso_8601": "2025-10-28T01:14:43.838698Z",
"url": "https://files.pythonhosted.org/packages/e4/df/351e982e840c879fb4e1de94c37a37d2502f077d7b805d90ddeda30dd814/henotace_ai_sdk-1.2.1-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "98942eb7536fbe7613f0b6ea427ace5aead838fa50b4b48ec1012dd06ba40dab",
"md5": "106ddcf34fa4e724d4a8d492725cc73e",
"sha256": "6c62a1b17c827041386ba2bc32429512e9aad90372d7eaf9bcf55605c1185cfc"
},
"downloads": -1,
"filename": "henotace_ai_sdk-1.2.1.tar.gz",
"has_sig": false,
"md5_digest": "106ddcf34fa4e724d4a8d492725cc73e",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.7",
"size": 51369,
"upload_time": "2025-10-28T01:14:45",
"upload_time_iso_8601": "2025-10-28T01:14:45.819070Z",
"url": "https://files.pythonhosted.org/packages/98/94/2eb7536fbe7613f0b6ea427ace5aead838fa50b4b48ec1012dd06ba40dab/henotace_ai_sdk-1.2.1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-10-28 01:14:45",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "Davidoshin",
"github_project": "henotace-python-sdk",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"requirements": [
{
"name": "requests",
"specs": [
[
">=",
"2.25.0"
]
]
},
{
"name": "dataclasses",
"specs": []
}
],
"lcname": "henotace-ai-sdk"
}