SemanticPen Python SDK
AI Article Writer & SEO Blog Generator SDK - Professional Python library for automated content creation, AI-powered article generation, and SEO blog writing with SemanticPen.
🚀 Features
- AI-Powered Article Generation: Generate high-quality articles from keywords
- SEO Optimization: Built-in SEO best practices and optimization
- Bulk Operations: Generate multiple articles simultaneously
- Real-time Status Tracking: Monitor article generation progress
- Type Safety: Full typing support with dataclasses and type hints
- Error Handling: Comprehensive error handling and retry mechanisms
- Async Support: Built for high-performance applications
- Flexible Configuration: Customizable settings for different use cases
📦 Installation
pip install semanticpen
🔑 Quick Start
Basic Usage
from semanticpen import SemanticPenClient
# Initialize client
client = SemanticPenClient.create("your-api-key")
# Generate a single article
result = client.generate_article("Python programming best practices")
print(f"Article ID: {result['articleId']}")
print(f"Project ID: {result['projectId']}")
print(f"Message: {result['message']}")
# Check article status
status = client.get_article_status(result['articleId'])
print(f"Status: {status['status']}")
print(f"Complete: {status['isComplete']}")
Advanced Configuration
from semanticpen import SemanticPenClient, SemanticPenConfig
# Custom configuration
config = SemanticPenConfig(
api_key="your-api-key",
base_url="https://www.semanticpen.com",
timeout=60000, # 60 seconds
debug=True
)
client = SemanticPenClient.create_with_config(config)
📝 Core Features
1. Article Generation
Single Article
# Simple generation
result = client.generate_article("AI in healthcare")
# With options
result = client.generate_article(
"Machine learning algorithms",
gpt_version="gpt-4",
project_name="AI Blog Series",
preset_id="seo-optimized"
)
Bulk Generation
keywords = [
"Python web development",
"Django best practices",
"FastAPI tutorial"
]
results = client.generate_articles(keywords)
print(f"Successfully generated: {results.success_count}")
print(f"Failed: {results.failure_count}")
2. Article Retrieval
# Get complete article
article = client.get_article("article-id")
print(f"Title: {article.title}")
print(f"Content: {article.article_html}")
print(f"Status: {article.status}")
# Get multiple articles
article_ids = ["id1", "id2", "id3"]
results = client.get_articles(article_ids)
for article in results.successful:
print(f"Article: {article.title}")
3. Status Monitoring
# Quick completion check
is_complete = client.is_article_complete("article-id")
# Detailed status
status = client.get_article_status("article-id")
print(f"Status: {status['status']}")
print(f"Complete: {status['isComplete']}")
print(f"Has Error: {status['hasError']}")
4. Waiting for Completion
from semanticpen import PollingConfig
# Generate and wait for completion
article = client.generate_and_wait(
"Content marketing strategies",
polling_config=PollingConfig(
interval=5000, # Check every 5 seconds
max_attempts=60 # Max 5 minutes
)
)
print(f"Completed article: {article.title}")
print(f"Content length: {len(article.article_html)}")
5. Bulk Operations with Progress Tracking
def progress_callback(completed, total, new_articles):
print(f"Progress: {completed}/{total} articles completed")
for article in new_articles:
print(f" ✓ {article.title}")
# Generate multiple articles and wait
result = client.generate_bulk_and_wait(
["Topic 1", "Topic 2", "Topic 3"],
on_progress=progress_callback
)
print(f"Successful: {len(result['successful'])}")
print(f"Failed: {len(result['failed'])}")
print(f"Total time: {result['total_time']:.2f} seconds")
🏗️ Advanced Usage
Request Builder Pattern
# Complex article generation with builder pattern
builder = client.create_request_builder()
articles = (builder
.keyword(["AI ethics", "Machine learning bias"])
.gpt_version("gpt-4")
.project_name("AI Ethics Series")
.preset("academic")
.parameter("tone", "professional")
.parameter("target_audience", "researchers")
.generate_and_wait())
print(f"Generated {len(articles)} articles")
Error Handling
from semanticpen import (
AuthenticationError,
ValidationError,
RateLimitError,
NetworkError,
TimeoutError
)
try:
result = client.generate_article("Python tutorials")
except AuthenticationError:
print("Invalid API key")
except ValidationError as e:
print(f"Invalid input: {e}")
except RateLimitError as e:
print(f"Rate limit exceeded. Retry after: {e.retry_after}s")
except NetworkError:
print("Network connection failed")
except TimeoutError:
print("Request timed out")
Custom Polling Configuration
from semanticpen import PollingConfig
# Custom polling behavior
custom_polling = PollingConfig(
interval=3000, # Poll every 3 seconds
max_attempts=100, # Try for up to 100 times
backoff_multiplier=1.2 # Increase interval by 20% each time
)
article = client.wait_for_article(
"article-id",
polling_config=custom_polling
)
🔧 Configuration Options
SemanticPenConfig
| Parameter | Type | Default | Description |
|---|---|---|---|
api_key |
str |
Required | Your SemanticPen API key |
base_url |
str |
"https://www.semanticpen.com" |
API base URL |
timeout |
int |
30000 |
Request timeout in milliseconds |
debug |
bool |
False |
Enable debug logging |
PollingConfig
| Parameter | Type | Default | Description |
|---|---|---|---|
interval |
int |
5000 |
Polling interval in milliseconds |
max_attempts |
int |
60 |
Maximum polling attempts |
backoff_multiplier |
float |
1.0 |
Exponential backoff multiplier |
📊 Response Types
Article
@dataclass
class Article:
id: str
organization_id: str
user_id: str
project_id: str
target_keyword: str
status: ArticleStatusEnum
created_at: str
updated_at: str
article_html: Optional[str] = None
content: Optional[str] = None
title: Optional[str] = None
metadata: Optional[Dict[str, Any]] = None
completed_at: Optional[str] = None
error_message: Optional[str] = None
BulkOperationResult
@dataclass
class BulkOperationResult:
successful: List[Any]
failed: List[Dict[str, Any]]
total: int
success_count: int
failure_count: int
🧪 Testing
# Test API connection
if client.test_connection():
print("✓ Connected to SemanticPen API")
else:
print("✗ Connection failed")
# Validate keywords
validation = SemanticPenClient.validate_keywords([
"Valid keyword",
"", # Invalid
"Another valid keyword"
])
if validation["valid"]:
print("All keywords are valid")
else:
print(f"Validation errors: {validation['errors']}")
📚 API Reference
SemanticPenClient Methods
| Method | Description |
|---|---|
create(api_key, **options) |
Create client with API key |
test_connection() |
Test API connectivity |
generate_article(keyword, **options) |
Generate single article |
generate_articles(keywords, **options) |
Generate multiple articles |
get_article(article_id) |
Retrieve article by ID |
get_articles(article_ids) |
Retrieve multiple articles |
is_article_complete(article_id) |
Check if article is complete |
get_article_status(article_id) |
Get article status |
wait_for_article(article_id, **options) |
Wait for article completion |
generate_and_wait(keyword, **options) |
Generate and wait workflow |
🌟 Examples
See the examples/ directory for complete examples:
basic_usage.py- Simple article generationbulk_generation.py- Multiple article generationasync_monitoring.py- Real-time status monitoringerror_handling.py- Comprehensive error handling
🤝 Contributing
We welcome contributions! Please see our Contributing Guide for details.
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🔗 Links
- Website: https://www.semanticpen.com
- API Documentation: https://www.semanticpen.com/api-documentation
- Python SDK Documentation: https://www.semanticpen.com/api-documentation
- Support: contact@semanticpen.com
- Issues: GitHub Issues
💡 Need Help?
- 📖 Check our documentation
- 💬 Join our community forum
- 📧 Email us at support@semanticpen.com
- 🐛 Report bugs on GitHub
Made with ❤️ by the SemanticPen team
Metadata
Release files for semanticpen 1.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| semanticpen-1.0.0.tar.gz | 33.3 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| semanticpen-1.0.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 56.3 kB
Release files / semanticpen-1.0.0.tar.gz
| Download URL | semanticpen-1.0.0.tar.gz |
|---|---|
| Size | 33.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
b8446b2b9a2c6dd98913bd4274254b0f0abfb4769c8bbcf823f64097bf696bee
|
|
BLAKE2b-256 checksum How to use checksums |
77cc167cd438b237085213fbd0bf49a717a44fe05c9c4e27a01d472aada39c5c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.11.0
|
Release files / semanticpen-1.0.0-py3-none-any.whl
| Download URL | semanticpen-1.0.0-py3-none-any.whl |
|---|---|
| Size | 23.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
a8ced2467b4dfdaaae6b3793fb06676b8965ff7eef9b0ff53e04f9b3384700c6
|
|
BLAKE2b-256 checksum How to use checksums |
784b19af6a68c626561c3583555aff6afb34579a1a19cdbd2e7e68d0f49d34e2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.11.0
|