Tagmaster Python Client Documentation

Complete API reference and examples for the official Tagmaster Python client library. Learn how to integrate AI-powered text and image classification into your applications with comprehensive documentation, code examples, and best practices.

🔗 View on PyPI

Quick Start Guide

Get up and running with Tagmaster Python client in minutes. This guide will walk you through installation, basic setup, and your first classification request.

📦
Install Package
Install via pip package manager
pip install tagmaster-python
📦
SDK Features
Key features and capabilities of the Tagmaster Python client
🔑 API Key Authentication
📁 Project Management (CRUD)
🏷️ Category Management
🤖 AI Text & Image Classification
📊 Analytics & History
📁 CSV Import/Export
🔧 Error Handling & Validation
💻 Basic Usage Example
Start with text classification in just a few lines of code
from tagmaster import TagmasterClassificationClient

# Initialize the client with your API key
client = TagmasterClassificationClient(api_key="your-api-key-here")

# Classify text content
result = client.classify_text("Customer login issue")

# Process and display results
if result.get('success'):
    top_match = result['classifications'][0]
    print(f"Top match: {top_match['categoryName']}")
    print(f"Confidence: {top_match['confidence']:.1f}%")
    print(f"Reasoning: {top_match['aiReasoning']}")
else:
    print(f"Classification failed: {result.get('error')}")

💡 Pro Tip

Make sure to replace "your-api-key-here" with your actual Tagmaster API key from the dashboard. You can get your API key by signing up and navigating to the API Keys section.

Installation Guide

Learn how to install the Tagmaster Python client library and set up your development environment for optimal performance.

From PyPI (Recommended)
Install the latest stable version from Python Package Index
pip install tagmaster-python

This command will install the latest stable version of the Tagmaster Python client along with all required dependencies.

System Requirements
Dependencies and system requirements for optimal performance
Python 3.7+Required Python version for compatibility
requestsHTTP library for API communication
Internet ConnectionRequired for API access and updates
Verification
Verify your installation was successful
# Verify installation
import tagmaster
print(f"Tagmaster version: {tagmaster.__version__}")

# Test basic functionality
client = tagmaster.TagmasterClassificationClient(api_key="test")
print("Installation successful!")

Authentication

Learn how to authenticate your API requests and manage your API key.

API Key Authentication
All API requests require a valid API key from your project.

1. Get Your API Key

Access your project's API key from the Tagmaster dashboard.

2. Initialize Client

from tagmaster import TagmasterClassificationClient

# Initialize with your API key
client = TagmasterClassificationClient(api_key="your-api-key-here")

# Optional: Custom base URL
client = TagmasterClassificationClient(
    api_key="your-api-key-here",
    base_url="https://api.tagmaster.com"
)

3. Update API Key

# Update API key after initialization
client.set_api_key("new-api-key-here")

# Update base URL
client.set_base_url("https://new-api-url.com")

Project Management

Learn how to create, manage, and organize your classification projects. Projects help you organize categories and keep your classification system structured.

Get Projects

Retrieve All Projects
Get a list of all projects associated with your API key
# Get all projects for your account
projects = client.get_projects()

# Display project information
for project in projects:
    print(f"Project Name: {project['name']}")
    print(f"Project UUID: {project['uuid']}")
    print(f"Description: {project.get('description', 'No description')}")
    print(f"Created: {project['createdAt']}")
    print("---")

print(f"Total projects: {len(projects)}")

✅ Best Practice

Always check if the response contains projects before processing. The API returns an empty list if no projects exist.

Create Project

Create New Project
Create a new project to organize your classification categories
# Create a new project
project = client.create_project(
    name="Customer Support System",
    description="AI-powered customer support ticket classification system"
)

# Verify creation
if project.get('uuid'):
    print(f"✅ Project created successfully!")
    print(f"Name: {project['name']}")
    print(f"UUID: {project['uuid']}")
    print(f"Description: {project['description']}")
else:
    print(f"❌ Project creation failed: {project.get('error')}")

⚠️ Important

Project names must be unique within your account. Use descriptive names that clearly identify the purpose of your classification system.

Update Project

Update Existing Project
Modify project name or description
# Update project
updated_project = client.update_project(
    project_uuid="your-project-uuid",
    name="Updated Project Name",  # Optional
    description="Updated description"  # Optional
)

print(f"Updated project: {updated_project['name']}")

Delete Project

Delete Project
Remove a project and all its categories
# Delete project
success = client.delete_project("your-project-uuid")

if success:
    print("Project deleted successfully")
else:
    print("Failed to delete project")

Category Management

Learn how to create, manage, and organize your classification categories. Categories help you define the scope of your AI model's understanding.

Get Categories

Get Project Categories
Retrieve all categories for a specific project
# Get categories for a project
categories = client.get_categories("your-project-uuid")

# Print category details
for category in categories:
    print(f"Name: {category['name']}")
    print(f"Description: {category.get('description', 'No description')}")
    print(f"UUID: {category['uuid']}")
    print("---")

Create Category

Create New Category
Add a new classification category to a project
# Create a new category
category = client.create_category(
    project_uuid="your-project-uuid",
    name="Login Issues",
    description="Problems with user authentication and login"
)

print(f"Created category: {category['name']}")
print(f"Category UUID: {category['uuid']}")

CSV Import/Export

Bulk Category Operations
Import and export categories using CSV files

Export Categories

# Export categories to CSV
csv_file = client.export_categories_csv(
    project_uuid="your-project-uuid",
    output_file_path="categories_export.csv"  # Optional
)

print(f"Categories exported to: {csv_file}")

Import Categories

# Import categories from CSV
result = client.import_categories_csv(
    project_uuid="your-project-uuid",
    csv_file_path="categories_import.csv"
)

print(f"Imported {result.get('imported', 0)} categories")

CSV Format

name,description
Login Issues,Problems with user authentication and login
Password Reset,Password recovery and reset requests
Technical Support,Technical issues and troubleshooting
Billing Questions,Payment and billing inquiries

AI Classification

Harness the power of artificial intelligence to automatically classify text and images. Our advanced AI models provide accurate categorization with detailed reasoning.

Text Classification

Classify Text Content
Analyze and categorize text using advanced AI models
# Classify text content
text_to_classify = "Customer is having trouble logging into their account"

result = client.classify_text(text_to_classify)

# Process and analyze results
if result.get('success'):
    print(f"🎯 Classification Results for: '{text_to_classify}'")
    print("=" * 50)
    
    classifications = result.get('classifications', [])
    
    for i, classification in enumerate(classifications, 1):
        print(f"
{i}. Category: {classification['categoryName']}")
        print(f"   Match Percentage: {classification['matchPercentage']:.1f}%")
        print(f"   Confidence Score: {classification['confidence']:.3f}")
        print(f"   AI Reasoning: {classification['aiReasoning']}")
        print(f"   Category Description: {classification.get('description', 'N/A')}")
    
    print(f"
📊 Summary: {len(classifications)} categories matched")
    print(f"⚡ Response Time: {result.get('responseTime', 'N/A')}ms")
else:
    print(f"❌ Classification failed: {result.get('error')}")
    print(f"Error details: {result.get('details', 'No additional details')}")

Key Features:

  • ✓Multiple category matches with confidence scores
  • ✓AI-generated reasoning for each classification
  • ✓Performance metrics and response time tracking
  • ✓Support for multiple languages and content types

Image Classification

Classify Images
Analyze and categorize images using AI vision
# Classify image from URL
result = client.classify_image("https://example.com/image.jpg")

# Process results
if result.get('success'):
    classifications = result.get('classifications', [])
    
    for classification in classifications:
        print(f"Category: {classification['categoryName']}")
        print(f"Match: {classification['matchPercentage']}%")
        print(f"Confidence: {classification['confidence']}")
        print(f"Reasoning: {classification['aiReasoning']}")
        print("---")
else:
    print(f"Image classification failed: {result.get('error')}")

History & Analytics

Learn how to retrieve and analyze historical classification requests and performance metrics.

Get Classification History

Retrieve Classification History
Get detailed history of all classification requests
# Get classification history with filters
history = client.get_classification_history(
    limit=50,                    # Number of records (max 100)
    offset=0,                    # Number of records to skip
    classification_type='text',  # 'text' or 'image'
    success=True,                # Filter by success status
    start_date='2024-01-01',    # Start date filter
    end_date='2024-12-31'       # End date filter
)

# Process history
requests = history.get('requests', [])
print(f"Retrieved {len(requests)} classification requests")

for req in requests:
    print(f"Type: {req.get('type')}")
    print(f"Success: {req.get('success')}")
    print(f"Created: {req.get('createdAt')}")
    print(f"Response time: {req.get('responseTime')}ms")
    print("---")

Get Statistics

Classification Statistics
Get analytics and performance metrics
# Get classification statistics
stats = client.get_classification_stats(
    start_date='2024-01-01',  # Optional start date
    end_date='2024-12-31'     # Optional end date
)

if stats.get('success'):
    statistics = stats.get('statistics', {})
    print("Classification Statistics:")
    print(f"  Total requests: {statistics.get('totalRequests')}")
    print(f"  Successful: {statistics.get('successfulRequests')}")
    print(f"  Failed: {statistics.get('failedRequests')}")
    print(f"  Average response time: {statistics.get('averageResponseTime')}ms")
    print(f"  Success rate: {statistics.get('successRate', 0):.1f}%")

Practical Examples

Real-world examples and use cases that demonstrate how to implement Tagmaster in your applications. From simple classification to complex workflows.

Complete Workflow Example

End-to-End Classification System
Complete example from project creation to automated classification
from tagmaster import TagmasterClassificationClient
import json
from datetime import datetime

class CustomerSupportClassifier:
    def __init__(self, api_key):
        self.client = TagmasterClassificationClient(api_key=api_key)
        self.project_uuid = None
        self.categories = {}
    
    def setup_project(self):
        """Create project and categories for customer support"""
        # Create project
        project = self.client.create_project(
            name="Customer Support System",
            description="Automated classification of customer support tickets"
        )
        self.project_uuid = project['uuid']
        print(f"✅ Project created: {project['name']}")
        
        # Define categories
        category_definitions = [
            ("Login Issues", "Authentication and login problems"),
            ("Password Reset", "Password recovery and reset requests"),
            ("Billing", "Payment, billing, and subscription questions"),
            ("Technical", "Technical support and troubleshooting"),
            ("Feature Request", "New feature requests and suggestions"),
            ("General", "General inquiries and other questions")
        ]
        
        # Create categories
        for name, description in category_definitions:
            category = self.client.create_category(
                project_uuid=self.project_uuid,
                name=name,
                description=description
            )
            self.categories[name] = category['uuid']
            print(f"✅ Category created: {name}")
    
    def classify_ticket(self, ticket_text):
        """Classify a customer support ticket"""
        result = self.client.classify_text(ticket_text)
        
        if result.get('success'):
            top_match = result['classifications'][0]
            return {
                'category': top_match['categoryName'],
                'confidence': top_match['confidence'],
                'reasoning': top_match['aiReasoning'],
                'timestamp': datetime.now().isoformat()
            }
        else:
            return {'error': result.get('error')}
    
    def process_batch(self, tickets):
        """Process multiple tickets in batch"""
        results = []
        for i, ticket in enumerate(tickets, 1):
            print(f"Processing ticket {i}/{len(tickets)}...")
            result = self.classify_ticket(ticket)
            results.append({
                'ticket_id': i,
                'text': ticket,
                'classification': result
            })
        return results

# Usage example
if __name__ == "__main__":
    classifier = CustomerSupportClassifier(api_key="your-api-key")
    
    # Setup project and categories
    classifier.setup_project()
    
    # Sample tickets
    sample_tickets = [
        "User can't log in to account",
        "Need help resetting password",
        "Payment was charged twice",
        "App is crashing on startup",
        "Can you add dark mode feature?",
        "What are your business hours?"
    ]
    
    # Process tickets
    results = classifier.process_batch(sample_tickets)
    
    # Save results
    with open('classification_results.json', 'w') as f:
        json.dump(results, f, indent=2)
    
    print("
🎉 Classification complete! Results saved to classification_results.json")

🚀 Advanced Features

This example demonstrates object-oriented design, batch processing, error handling, and result persistence. You can extend this pattern for other use cases like content moderation, product categorization, or sentiment analysis.

Response Formats & Data Structures

Understand the structure of API responses and how to handle different data types. Learn about error handling and response validation.

Classification Response Format
Standard response structure for successful classification requests
{
  "success": true,
  "classifications": [
    {
      "categoryName": "Login Issues",
      "matchPercentage": 85.5,
      "confidence": 0.92,
      "aiReasoning": "The text describes a user having trouble logging into their account, which directly relates to login issues.",
      "description": "Problems with user authentication and login",
      "categoryId": 123,
      "categoryUuid": "550e8400-e29b-41d4-a716-446655440001"
    }
  ],
  "projectName": "Customer Support System",
  "totalCategories": 6,
  "provider": "openai",
  "model": "gpt-4",
  "responseTime": 1250,
  "requestId": "req_123456789",
  "timestamp": "2024-01-15T10:30:00.000Z"
}

Response Fields Explained:

Core Fields:
  • success - Boolean indicating success
  • classifications - Array of classification results
  • projectName - Name of the project used
Metadata:
  • responseTime - API response time in milliseconds
  • provider - AI provider used (openai, anthropic, etc.)
  • model - Specific AI model used

Error Handling

Learn how to gracefully handle different types of errors that might occur during API calls.

Comprehensive Error Handling
Handle different types of errors gracefully

Basic Error Handling

try:
    result = client.classify_text("Text to classify")
    print("Success:", result)
except requests.RequestException as e:
    print(f"API Error: {e}")
except ValueError as e:
    print(f"Validation Error: {e}")
except ConnectionError as e:
    print(f"Connection Error: {e}")
except Exception as e:
    print(f"Unexpected Error: {e}")

Common Error Codes

401Invalid or missing API key
403No active subscription
404Resource not found
429Rate limit exceeded
500Internal server error
ConnectionNetwork connectivity issues

Ready to Build Intelligent Classification Systems?

Start using the Tagmaster Python client today to add AI-powered classification capabilities to your applications. From customer support to content moderation, our library makes it easy to implement intelligent categorization.

Need help? Check out our support documentation or contact our team.