From 872bb693c66ab453bb17e99fb10fbf0140277866 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BE=99=E8=99=BE=E6=9C=BA=E5=99=A8=E4=BA=BA?= Date: Sun, 15 Mar 2026 04:31:02 +0800 Subject: [PATCH] docs: Add comprehensive marketplace documentation - Add README.md to shaprai/marketplace/ with quick start guide - Add docs/marketplace/USAGE.md with detailed usage instructions - Add docs/marketplace/API.md with complete API reference This documentation covers: - CLI commands (publish, search, buy, list) - Template format and examples - Revenue split explanation (90/5/5) - Python API usage - Troubleshooting guide Closes #8 --- docs/marketplace/API.md | 261 ++++++++++++++++++++++++++ docs/marketplace/USAGE.md | 333 ++++++++++++++++++++++++++++++++++ shaprai/marketplace/README.md | 233 ++++++++++++++++++++++++ 3 files changed, 827 insertions(+) create mode 100644 docs/marketplace/API.md create mode 100644 docs/marketplace/USAGE.md create mode 100644 shaprai/marketplace/README.md diff --git a/docs/marketplace/API.md b/docs/marketplace/API.md new file mode 100644 index 0000000..02639b2 --- /dev/null +++ b/docs/marketplace/API.md @@ -0,0 +1,261 @@ +# ShaprAI Marketplace API Reference + +Complete API reference for the ShaprAI Template Marketplace module. + +## Module Structure + +``` +shaprai/marketplace/ +├── __init__.py # Package exports +├── registry.py # Template registry (CRUD, search) +├── pricing.py # RTC pricing and revenue split +├── validator.py # Template schema validation +└── cli.py # Command-line interface +``` + +## Quick Start + +```python +from shaprai.marketplace.registry import TemplateRegistry, Template +from shaprai.marketplace.pricing import calculate_purchase +from shaprai.marketplace.validator import validate_template + +# Initialize registry +registry = TemplateRegistry() + +# Validate a template +result = validate_template("my_template.yaml") +if not result.is_valid: + print("Validation failed:", result.errors) + exit(1) + +# Create and publish a template +template = Template( + name="my-agent", + version="1.0.0", + author="Your Name", + description="My custom agent", + price_rtc=10, + tags=["custom", "agent"], + content=yaml_content, +) +registry.publish(template) + +# Search for templates +templates = registry.search(tag="personality", sort="downloads", limit=10) + +# Calculate purchase +purchase = calculate_purchase(100, "sophia-personality", "1.2.3") +print(f"Creator gets: {purchase['creator']['amount']} RTC") +``` + +## Registry API + +### Template Dataclass + +```python +from shaprai.marketplace.registry import Template + +template = Template( + name: str, # Unique template identifier + version: str, # Semver format (e.g., "1.0.0") + author: str, # Author name + description: str, # Brief description + price_rtc: int, # Price in RTC tokens + tags: List[str], # Category tags + content: str, # Full template content (YAML/JSON) + download_count: int = 0, # Auto-tracked + created_at: str = None, # Auto-generated ISO timestamp + updated_at: str = None, # Auto-generated ISO timestamp +) +``` + +### TemplateRegistry Methods + +#### `publish(template: Template) -> bool` + +Publish a new template version. + +```python +try: + registry.publish(template) +except ValueError as e: + print(f"Publish failed: {e}") +``` + +**Exceptions**: +- `ValueError`: If version already exists or semver is invalid + +#### `get(name: str, version: str) -> Optional[Template]` + +Get a specific template version. + +```python +template = registry.get("sophia-personality", "1.2.3") +``` + +#### `get_latest(name: str) -> Optional[Template]` + +Get the latest version of a template. + +```python +latest = registry.get_latest("sophia-personality") +``` + +#### `search(...) -> List[Template]` + +Search templates with filters. + +```python +templates = registry.search( + tag="personality", + author="Jane Doe", + query="business assistant", + sort="downloads", # or "recent", "price" + limit=20 +) +``` + +#### `list_by_author(author: str) -> List[Template]` + +List all templates by an author. + +```python +templates = registry.list_by_author("Jane Doe") +``` + +#### `increment_download(name: str, version: str) -> None` + +Increment download count (called automatically on purchase). + +#### `delete(name: str, version: str) -> bool` + +Delete a template version. + +## Pricing API + +### RevenueSplit Dataclass + +```python +from shaprai.marketplace.pricing import RevenueSplit + +split = RevenueSplit( + creator_amount: int, # 90% of total + protocol_amount: int, # 5% of total + relay_amount: int, # 5% of total + total_rtc: int, # Total price + template_name: str, + template_version: str, + buyer_id: str = None, +) +``` + +### PricingEngine Methods + +#### `calculate_split(price_rtc, template_name, template_version) -> RevenueSplit` + +Calculate revenue distribution. + +```python +engine = PricingEngine() +split = engine.calculate_split(100, "sophia-personality", "1.2.3") +print(f"Creator: {split.creator_amount} RTC") # 90 +``` + +#### `validate_price(price_rtc: int) -> bool` + +Validate a template price (0 to 100,000 RTC). + +#### `format_rtc(amount: int) -> str` + +Format RTC amount for display. + +### Convenience Function + +```python +from shaprai.marketplace.pricing import calculate_purchase + +purchase = calculate_purchase(100, "sophia-personality", "1.2.3") +# Returns dict with total_rtc, creator, protocol, relay amounts +``` + +## Validator API + +### ValidationResult Dataclass + +```python +from shaprai.marketplace.validator import ValidationResult + +result = ValidationResult( + is_valid: bool, + errors: List[str], + warnings: List[str], +) +``` + +### TemplateValidator Methods + +#### `validate_file(file_path: Path) -> ValidationResult` + +Validate a template file. + +```python +validator = TemplateValidator() +result = validator.validate_file(Path("my_template.yaml")) +if result.is_valid: + print("✅ Valid") +else: + for error in result.errors: + print(f"❌ {error}") +``` + +#### `validate_content(content: str, file_type: str) -> ValidationResult` + +Validate template content directly. + +#### `validate_template_dict(data: dict) -> ValidationResult` + +Validate a parsed template dictionary. + +### Schema Requirements + +**Required Fields**: +- `name`: Non-empty string, alphanumeric with hyphens +- `version`: Valid semver format +- `author`: Non-empty string +- `description`: Non-empty string, max 200 characters + +**Optional Fields**: +- `tags`: List of strings +- `personality`: Personality configuration +- `agent`: Agent configuration + +## Testing + +```python +import pytest +from shaprai.marketplace.registry import TemplateRegistry, Template + +def test_publish_and_search(): + registry = TemplateRegistry(db_path=":memory:") + + template = Template( + name="test-template", + version="1.0.0", + author="Test", + description="Test", + price_rtc=10, + tags=["test"], + content="test" + ) + + registry.publish(template) + results = registry.search(tag="test") + + assert len(results) == 1 +``` + +Run tests: +```bash +pytest tests/test_marketplace.py -v +``` diff --git a/docs/marketplace/USAGE.md b/docs/marketplace/USAGE.md new file mode 100644 index 0000000..7cb113c --- /dev/null +++ b/docs/marketplace/USAGE.md @@ -0,0 +1,333 @@ +# ShaprAI Marketplace Usage Guide + +This guide provides detailed instructions for using the ShaprAI Template Marketplace. + +## Table of Contents + +1. [Getting Started](#getting-started) +2. [Creating Templates](#creating-templates) +3. [Publishing Templates](#publishing-templates) +4. [Searching and Discovering](#searching-and-discovering) +5. [Purchasing Templates](#purchasing-templates) +6. [Managing Your Templates](#managing-your-templates) +7. [Best Practices](#best-practices) +8. [Troubleshooting](#troubleshooting) + +## Getting Started + +### Prerequisites + +- ShaprAI installed (`pip install -e .`) +- RTC wallet configured (for purchases) +- Python 3.8+ + +### Quick Start + +```bash +# Check marketplace status +shaprai marketplace --help + +# View available commands +shaprai marketplace search --help +``` + +## Creating Templates + +### Template Structure + +A valid template must include: + +```yaml +# Required fields +name: string # Unique template identifier +version: string # Semver format (e.g., 1.0.0) +author: string # Your name or pseudonym +description: string # Brief description (max 200 chars) + +# Optional fields +tags: [string] # Categories for discovery +price_rtc: integer # Price in RTC (optional, set at publish time) + +# Template content (varies by type) +personality: + system_prompt: string + temperature: float + max_tokens: integer +``` + +### Example Templates + +#### Personality Template + +```yaml +name: professional-assistant +version: 1.0.0 +author: Jane Doe +description: Professional business assistant with formal tone +tags: + - personality + - business + - professional +personality: + system_prompt: | + You are a professional business assistant. + Maintain a formal, courteous tone in all interactions. + Focus on clarity, accuracy, and efficiency. + temperature: 0.5 + max_tokens: 2048 + top_p: 0.9 +``` + +#### Agent Template + +```yaml +name: research-agent +version: 2.1.0 +author: Research Labs +description: Autonomous research agent with web browsing capabilities +tags: + - agent + - research + - autonomous +agent: + capabilities: + - web_search + - document_analysis + - citation_generation + tools: + - browser + - pdf_reader + - citation_manager + workflow: + - understand_query + - search_sources + - analyze_results + - generate_report +``` + +## Publishing Templates + +### Step-by-Step Publishing + +1. **Create your template file** (YAML or JSON) + +2. **Validate before publishing**: + ```bash + # Validation happens automatically during publish + # But you can test locally first + python -c "from shaprai.marketplace.validator import TemplateValidator; print(TemplateValidator().validate_file('my_template.yaml'))" + ``` + +3. **Publish with price**: + ```bash + shaprai marketplace publish \ + --template my_template.yaml \ + --price 25 \ + --author "Your Name" + ``` + +4. **Verify publication**: + ```bash + shaprai marketplace search --author "Your Name" + ``` + +### Publishing Tips + +- **Version correctly**: Use semver (major.minor.patch) + - `1.0.0` - Initial release + - `1.0.1` - Bug fix + - `1.1.0` - New feature + - `2.0.0` - Breaking change + +- **Price appropriately**: + - Simple templates: 5-15 RTC + - Complex personalities: 15-50 RTC + - Full agent configurations: 50-100 RTC + +- **Use descriptive tags**: Helps users discover your templates + +## Searching and Discovering + +### Search Strategies + +```bash +# By tag (most common) +shaprai marketplace search --tag personality +shaprai marketplace search --tag agent --tag research + +# By author +shaprai marketplace search --author "Jane Doe" + +# By keyword in description +shaprai marketplace search --query "business assistant" + +# Combined filters +shaprai marketplace search --tag personality --author "Jane Doe" --sort downloads +``` + +### Sorting Options + +| Sort Key | Description | Use Case | +|----------|-------------|----------| +| `downloads` | Most downloaded first | Find popular templates | +| `recent` | Newest first | Discover latest templates | +| `price` | Price ascending | Find budget options | + +### Reading Search Results + +``` +Found 3 templates: + + 📦 sophia-personality@1.2.3 + 💰 15 RTC | 📥 1234 downloads + 📝 A friendly AI assistant with empathetic responses + + 📦 professional-assistant@2.0.0 + 💰 25 RTC | 📥 567 downloads + 📝 Professional business assistant with formal tone +``` + +## Purchasing Templates + +### Purchase Flow + +1. **Find a template**: + ```bash + shaprai marketplace search --tag personality + ``` + +2. **Preview the template** (shown automatically): + ``` + 📦 sophia-personality@1.2.3 + 💰 Price: 15 RTC + 👤 Author: Alice + 📝 Description: A friendly AI assistant... + + Preview (truncated): + personality: + system_prompt: | + You are Sophia, a friendly... + ``` + +3. **Confirm purchase**: + ```bash + shaprai marketplace buy --template sophia-personality@1.2.3 + ``` + +4. **Download completes**: + ``` + ✅ Purchase successful! + 💳 Charged: 15 RTC + 📥 Template downloaded to: ~/.shaprai/templates/sophia-personality@1.2.3.yaml + ``` + +### Revenue Distribution + +When you purchase a template for 100 RTC: +- 90 RTC → Template creator +- 5 RTC → ShaprAI development fund +- 5 RTC → Relay node + +## Managing Your Templates + +### List Your Published Templates + +```bash +# List all your templates +shaprai marketplace list --author me + +# List with details +shaprai marketplace list --author me --verbose +``` + +### Update a Template + +You cannot overwrite an existing version. Create a new version: + +```bash +# Update your template file with new version +# version: 1.1.0 + +# Publish new version +shaprai marketplace publish --template my_template_v1.1.yaml --price 25 +``` + +### Delete a Template + +```bash +# Note: Deletion is permanent and cannot be undone +shaprai marketplace delete --template my-template@1.0.0 +``` + +## Best Practices + +### For Template Creators + +1. **Write clear descriptions**: Help users understand what your template does +2. **Use appropriate tags**: 3-5 relevant tags improve discoverability +3. **Test before publishing**: Validate your template works as expected +4. **Version responsibly**: Follow semver conventions +5. **Price fairly**: Consider complexity and value provided +6. **Update regularly**: Fix bugs and improve based on feedback + +### For Template Buyers + +1. **Check download counts**: Popular templates are often more reliable +2. **Read descriptions carefully**: Ensure the template meets your needs +3. **Start with lower-priced templates**: Test before investing heavily +4. **Leave feedback**: Help improve the marketplace ecosystem +5. **Check version history**: Newer versions may have important fixes + +## Troubleshooting + +### Common Issues + +#### "Template already exists" +``` +Error: Template my-template@1.0.0 already exists +``` +**Solution**: Increment the version number (e.g., to 1.0.1) + +#### "Invalid semver version" +``` +Error: Invalid semver version: 1.0 +``` +**Solution**: Use full semver format (e.g., 1.0.0) + +#### "Validation failed" +``` +Validation failed: + ❌ Missing required field: name + ❌ Missing required field: version +``` +**Solution**: Add all required fields to your template + +#### "Template not found" +``` +Error: Template 'sophia-personality@1.2.3' not found +``` +**Solution**: Check the template name and version, or search to verify it exists + +#### "Insufficient RTC" +``` +Error: Insufficient RTC balance +``` +**Solution**: Add RTC to your wallet before purchasing + +### Getting Help + +```bash +# View help for any command +shaprai marketplace --help +shaprai marketplace publish --help +shaprai marketplace search --help + +# Check marketplace status +shaprai marketplace status +``` + +## Additional Resources + +- [API Reference](../shaprai/marketplace/README.md#api-usage) +- [Template Examples](examples/) +- [Revenue Split Details](REVENUE.md) diff --git a/shaprai/marketplace/README.md b/shaprai/marketplace/README.md new file mode 100644 index 0000000..c81714b --- /dev/null +++ b/shaprai/marketplace/README.md @@ -0,0 +1,233 @@ +# ShaprAI Template Marketplace + +The ShaprAI Template Marketplace enables creators to publish, version, and sell agent personality templates priced in RTC tokens. + +## Features + +- **Template Registry**: SQLite-backed storage with full CRUD operations +- **Semantic Versioning**: All templates use semver (e.g., `sophia-personality@1.2.3`) +- **RTC Pricing**: Built-in pricing engine with 90/5/5 revenue split +- **Template Validation**: Schema validation before publishing +- **CLI Interface**: Easy-to-use commands for all marketplace operations + +## Revenue Split + +| Recipient | Share | Purpose | +|-----------|-------|---------| +| Creator | 90% | Template author | +| Protocol | 5% | ShaprAI development fund | +| Relay | 5% | Node that facilitated the transaction | + +## Installation + +The marketplace module is included with ShaprAI. Ensure you have the latest version: + +```bash +pip install -e . +``` + +## CLI Commands + +### Publish a Template + +Publish a template to the marketplace with a specified RTC price: + +```bash +shaprai marketplace publish --template my_agent.yaml --price 10 +``` + +Options: +- `-t, --template`: Path to template file (YAML/JSON) [required] +- `-p, --price`: Price in RTC [required] +- `-a, --author`: Author name (defaults to 'anonymous') + +### Search Templates + +Search for templates in the marketplace: + +```bash +shaprai marketplace search --tag personality --sort downloads +``` + +Options: +- `-t, --tag`: Filter by tag +- `-a, --author`: Filter by author +- `-q, --query`: Search query +- `-s, --sort`: Sort by (downloads, recent, price) +- `-l, --limit`: Maximum results (default: 20) + +### Buy a Template + +Purchase a template from the marketplace: + +```bash +shaprai marketplace buy --template sophia-personality@1.2.3 +``` + +Options: +- `-t, --template`: Template name with version (e.g., `sophia-personality@1.2.3`) + +### List Your Templates + +List all templates published by you: + +```bash +shaprai marketplace list --author me +``` + +## Template Format + +Templates should be YAML or JSON files with the following structure: + +```yaml +name: sophia-personality +version: 1.2.3 +author: Your Name +description: A friendly AI assistant personality +tags: + - personality + - assistant + - friendly +personality: + system_prompt: | + You are Sophia, a friendly and helpful AI assistant... + temperature: 0.7 + max_tokens: 2048 +``` + +## API Usage + +### Registry + +```python +from shaprai.marketplace.registry import TemplateRegistry, Template + +registry = TemplateRegistry() + +# Create a template +template = Template( + name="my-agent", + version="1.0.0", + author="Your Name", + description="My custom agent", + price_rtc=10, + tags=["custom", "agent"], + content=yaml_content, +) + +# Publish +registry.publish(template) + +# Search +templates = registry.search(tag="personality", sort="downloads", limit=10) + +# Get specific version +template = registry.get("sophia-personality", "1.2.3") + +# Get latest version +template = registry.get_latest("sophia-personality") +``` + +### Pricing + +```python +from shaprai.marketplace.pricing import PricingEngine, calculate_purchase + +engine = PricingEngine() + +# Calculate revenue split +split = engine.calculate_split( + price_rtc=100, + template_name="sophia-personality", + template_version="1.2.3" +) + +print(f"Creator gets: {split.creator_amount} RTC") # 90 RTC +print(f"Protocol gets: {split.protocol_amount} RTC") # 5 RTC +print(f"Relay gets: {split.relay_amount} RTC") # 5 RTC + +# Or use convenience function +purchase = calculate_purchase(100, "sophia-personality", "1.2.3") +``` + +### Validator + +```python +from shaprai.marketplace.validator import TemplateValidator + +validator = TemplateValidator() +result = validator.validate_file("my_template.yaml") + +if result.is_valid: + print("Template is valid!") +else: + for error in result.errors: + print(f"Error: {error}") +``` + +## Database Location + +The marketplace uses SQLite for storage. The database is located at: + +``` +~/.shaprai/marketplace.db +``` + +## Examples + +### Example 1: Publish a Personality Template + +```bash +# Create template file +cat > sophia.yaml << 'EOF' +name: sophia-personality +version: 1.0.0 +author: Alice +description: A friendly AI assistant with empathetic responses +tags: + - personality + - assistant + - empathetic +personality: + system_prompt: | + You are Sophia, a warm and empathetic AI assistant... +EOF + +# Publish for 15 RTC +shaprai marketplace publish --template sophia.yaml --price 15 +``` + +### Example 2: Search for Templates + +```bash +# Find all personality templates, sorted by popularity +shaprai marketplace search --tag personality --sort downloads + +# Find templates by a specific author +shaprai marketplace search --author Alice + +# Search by keyword +shaprai marketplace search --query "helpful assistant" +``` + +### Example 3: Purchase a Template + +```bash +# Buy the latest version +shaprai marketplace buy --template sophia-personality + +# Buy a specific version +shaprai marketplace buy --template sophia-personality@1.0.0 +``` + +## Testing + +Run the marketplace test suite: + +```bash +pytest tests/test_marketplace.py -v +``` + +## License + +MIT License - Copyright (c) 2026 Elyan Labs