Python SDK for fetching LaikaTest prompt templates via API
Project description
LaikaTest Python Client
Official Python SDK for fetching and managing LaikaTest prompt templates via API.
Features
- 🚀 Simple API - Clean, intuitive interface for fetching prompts
- 💾 Built-in Caching - TTL-based caching with automatic cleanup
- 🔒 Secure - HTTPS enforcement with localhost exception for testing
- 🎯 Type Hints - Full type annotations for better IDE support
- 🐍 Pythonic - Follows Python best practices and conventions
- 📦 Zero Dependencies - Uses only Python standard library
- ⚡ Flexible - Supports both dict and kwargs for parameters
- 🔄 Variable Injection - Template variable replacement with
{{variable}}syntax
Installation
# From source
pip install -e .
# From PyPI (when published)
pip install laikatest-client
Quick Start
from laikatest_client import LaikaTest
# Initialize the client
client = LaikaTest('your-api-key')
# Fetch a prompt
prompt = client.get_prompt('my-prompt')
# Get content
content = prompt.get_content()
print(content)
# Compile with variables (Pythonic kwargs!)
compiled = prompt.compile(name='John', role='developer')
print(compiled.get_content())
# Clean up when done
client.destroy()
Usage Examples
Basic Usage
from laikatest_client import LaikaTest
client = LaikaTest(
'your-api-key',
base_url='https://api.laikatest.com', # optional
timeout=10000, # milliseconds (optional)
cache_enabled=True, # optional
cache_ttl=1800000 # 30 minutes in ms (optional)
)
# Fetch latest version
prompt = client.get_prompt('welcome-message')
# Get prompt details
print(f"Type: {prompt.get_type()}") # 'text' or 'chat'
print(f"Content: {prompt.get_content()}")
Version Management
# Fetch specific version
prompt_v10 = client.get_prompt('my-prompt', version_id='v10')
prompt_v5 = client.get_prompt('my-prompt', version_id='5') # 'v' prefix optional
Variable Injection
The SDK supports {{variable}} syntax for template variables.
Using kwargs (Recommended - Pythonic!):
prompt = client.get_prompt('greeting')
compiled = prompt.compile(
name='Alice',
role='Engineer',
company='TechCorp'
)
Using dictionary:
variables = {
'name': 'Alice',
'role': 'Engineer',
'company': 'TechCorp'
}
compiled = prompt.compile(variables)
Combining both (kwargs override dict values):
base_vars = {'name': 'Alice', 'role': 'Engineer'}
compiled = prompt.compile(base_vars, role='Senior Engineer', team='Backend')
# Result: name='Alice', role='Senior Engineer', team='Backend'
Text vs Chat Prompts
Text Prompt:
prompt = client.get_prompt('simple-text')
print(prompt.get_type()) # 'text'
content = prompt.get_content() # Returns string
Chat Prompt:
prompt = client.get_prompt('conversation')
print(prompt.get_type()) # 'chat'
messages = prompt.get_content() # Returns list of message objects
# Compile with variables
compiled = prompt.compile(user_name='John', topic='Python')
Cache Control
# Use cached version (default)
prompt1 = client.get_prompt('my-prompt')
# Force fresh fetch, bypass cache
prompt2 = client.get_prompt('my-prompt', bypass_cache=True)
# Disable cache entirely
client_no_cache = LaikaTest('api-key', cache_enabled=False)
Error Handling
from laikatest_client import (
LaikaTest,
ValidationError,
AuthenticationError,
NetworkError,
LaikaServiceError
)
try:
client = LaikaTest('api-key')
prompt = client.get_prompt('my-prompt')
except ValidationError as e:
print(f"Invalid input: {e}")
except AuthenticationError as e:
print(f"Auth failed: {e}")
except NetworkError as e:
print(f"Network issue: {e}")
print(f"Original error: {e.original_error}")
except LaikaServiceError as e:
print(f"API error: {e}")
print(f"Status code: {e.status_code}")
print(f"Response: {e.response}")
API Reference
LaikaTest
Main client class for interacting with LaikaTest API.
Constructor:
LaikaTest(api_key: str, **options)
Parameters:
api_key(str, required): Your LaikaTest API keybase_url(str, optional): API base URL (default: 'https://api.laikatest.com')timeout(int, optional): Request timeout in milliseconds (default: 10000)cache_enabled(bool, optional): Enable caching (default: True)cache_ttl(int, optional): Cache TTL in milliseconds (default: 1800000 / 30 min)
Methods:
get_prompt(prompt_name: str, **options) -> Prompt
Fetch a prompt by name.
Parameters:
prompt_name(str, required): Name of the promptversion_id(str, optional): Specific version to fetchbypass_cache(bool, optional): Skip cache lookup (default: False)
Returns: Prompt instance
destroy() -> None
Cleanup resources and stop cache cleanup thread.
Prompt
Wrapper class for prompt content with compilation support.
Methods:
get_content() -> Union[str, List]
Returns the prompt content (string for text, list for chat).
get_type() -> str
Returns prompt type: 'text' or 'chat'.
compile(variables: dict = None, **kwargs) -> Prompt
Compile prompt with variable injection.
Parameters:
variables(dict, optional): Dictionary of variables to inject**kwargs: Variables as keyword arguments (merged with dict)
Returns: New Prompt instance with variables injected
Exception Classes
ValidationError: Invalid input parametersAuthenticationError: Authentication failed (401)NetworkError: Network connectivity issues- Properties:
original_error
- Properties:
LaikaServiceError: API/service errors (4xx, 5xx)- Properties:
status_code,response
- Properties:
Architecture
The SDK is organized into focused modules:
laikatest_client/
├── __init__.py # Main client and exports
└── lib/
├── cache.py # TTL-based caching
├── errors.py # Exception classes
├── http.py # HTTP request utilities
├── prompt.py # Prompt wrapper class
├── prompt_utils.py # Prompt fetching logic
├── validation.py # Input validation
└── variables.py # Variable injection
Development
Running Tests
python test_example.py
Building Distribution
python setup.py sdist bdist_wheel
Installing in Development Mode
pip install -e .
Comparison with JavaScript Client
This Python SDK maintains 100% logic parity with the JavaScript client while adding Python-specific enhancements:
| Feature | JavaScript | Python |
|---|---|---|
| Core Logic | ✅ | ✅ Identical |
| Caching | ✅ | ✅ Identical (threading) |
| Error Handling | ✅ | ✅ Identical hierarchy |
| Variable Injection | ✅ | ✅ Identical algorithm |
| API | options = {} |
**options (Pythonic) |
| Variable Passing | Dict only | Dict + kwargs ✨ |
| Type Safety | TypeScript .d.ts |
Type hints ✨ |
| Dependencies | 0 (Node stdlib) | 0 (Python stdlib) ✨ |
See CODE_COMPARISON.md for detailed comparison.
Requirements
- Python 3.7 or higher
- No external dependencies (uses standard library only)
License
MIT License - see LICENSE file for details.
Support
- Issues: GitHub Issues
- Documentation: API Docs
Contributing
Contributions are welcome! Please ensure:
- Code follows PEP 8 style guidelines
- All functions have type hints and docstrings
- Logic remains consistent with JavaScript client
- Tests pass
Changelog
v1.0.1 (2024)
- Initial release
- Feature parity with JavaScript client v1.0.1
- Added kwargs support for Pythonic API
- Full type hint coverage
- Zero external dependencies
Project details
Release history Release notifications | RSS feed
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 laikatest_client-1.0.0.tar.gz.
File metadata
- Download URL: laikatest_client-1.0.0.tar.gz
- Upload date:
- Size: 13.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0c0b06cf1670771595f31ca6ccb03329de0d52e861ee5a608d5393393eefa817
|
|
| MD5 |
ebe993c50978b8083ef467d27970d316
|
|
| BLAKE2b-256 |
2b8efbc1883f3a6e8ecb3db20ecbf7cda411864c8ad278886f07033d85a448ff
|
File details
Details for the file laikatest_client-1.0.0-py3-none-any.whl.
File metadata
- Download URL: laikatest_client-1.0.0-py3-none-any.whl
- Upload date:
- Size: 13.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0d6c5d4e64b1dec9c514c05fb9d577e398580c3db14f0fbed1bd446f949060ff
|
|
| MD5 |
a323dd7d03837a6c3b317698f61bc1de
|
|
| BLAKE2b-256 |
5e4f8886de3e4e26a5697534769143ba979837987b398155ff43c131ef4ba429
|