Name | moderatelyai-sdk JSON |
Version |
0.2.6
JSON |
| download |
home_page | None |
Summary | Python SDK for Moderately AI platform |
upload_time | 2025-08-11 21:53:26 |
maintainer | None |
docs_url | None |
author | None |
requires_python | >=3.8 |
license | MIT |
keywords |
ai
sdk
api
moderately
|
VCS |
 |
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
# Moderately AI Python SDK
The official Python SDK for the Moderately AI platform, providing programmatic access to agents, datasets, pipelines, and team management.
## Features
- **Python 3.8+ Support**: Compatible with Python 3.8 and later versions
- **Type Safety**: Full type annotations with mypy support
- **Async/Await**: Built-in support for asynchronous operations
- **Team-scoped Operations**: Automatic filtering and scoping to your team
- **Resource Management**: Agents, datasets, pipelines, files, and users
- **Error Handling**: Comprehensive exception handling for different error scenarios
- **Rate Limiting**: Built-in rate limit handling and retry logic
- **Modern Tooling**: Uses PDM for dependency management, Ruff for linting, and pytest for testing
## Installation
```bash
pip install moderatelyai-sdk
```
## Quick Start
### Synchronous Client
```python
import moderatelyai_sdk
# Initialize with environment variables (recommended)
client = moderatelyai_sdk.ModeratelyAI() # reads MODERATELY_API_KEY and MODERATELY_TEAM_ID
# Or initialize with explicit parameters
client = moderatelyai_sdk.ModeratelyAI(
team_id="your-team-id",
api_key="your-api-key"
)
# Use the client - all operations are automatically scoped to your team
users = client.users.list()
dataset = client.datasets.create(name="My Dataset")
agents = client.agents.list()
```
### Asynchronous Client
```python
import asyncio
import moderatelyai_sdk
async def main():
# Initialize async client
async with moderatelyai_sdk.AsyncModeratelyAI() as client:
# Same operations, just with await
users = await client.users.list()
dataset = await client.datasets.create(name="My Dataset")
agents = await client.agents.list()
asyncio.run(main())
```
## Usage
### Working with Datasets
```python
from moderatelyai_sdk import ModeratelyAI
client = ModeratelyAI(team_id="your-team-id", api_key="your-api-key")
# Create a dataset
dataset = client.datasets.create(
name="Customer Data",
description="Customer interaction dataset"
)
# Upload data to the dataset
version = dataset.upload_data("/path/to/data.csv")
print(f"Uploaded version {version.version_no} with {version.row_count} rows")
# List all datasets
datasets = client.datasets.list()
```
### Working with Agents
```python
# List all agents in your team
agents = client.agents.list()
# Create and run an agent execution
execution = client.agent_executions.create(
agent_id="agent_123",
input_data={"query": "Process this data"}
)
```
### Working with Pipelines
```python
# Create a pipeline
pipeline = client.pipelines.create(
name="Document Processing Pipeline",
description="Processes legal documents and extracts key information"
)
# Create a configuration version with workflow logic
config_version = client.pipeline_configuration_versions.create(
pipeline_id=pipeline["pipelineId"],
configuration={
"id": "doc-processor",
"name": "Document Processor",
"version": "1.0.0",
"blocks": {
"input": {
"id": "input",
"type": "input",
"config": {"json_schema": {"type": "object"}}
},
"llm": {
"id": "llm",
"type": "llm",
"config": {
"provider": "anthropic",
"model": "small",
"temperature": 0.2
}
},
"output": {
"id": "output",
"type": "output",
"config": {"name": "results"}
}
}
}
)
# Execute the pipeline
execution = client.pipeline_executions.create(
pipeline_configuration_version_id=config_version["pipelineConfigurationVersionId"],
pipeline_input={"documents": ["doc1.pdf", "doc2.pdf"]},
pipeline_input_summary="Process 2 legal documents"
)
# Monitor execution status
status = client.pipeline_executions.retrieve(execution["pipelineExecutionId"])
print(f"Execution status: {status['status']}")
# Get execution results when completed
if status["status"] == "completed":
output = client.pipeline_executions.get_output(execution["pipelineExecutionId"])
print(f"Results: {output}")
# List all pipelines in your team
pipelines = client.pipelines.list()
```
### Using Context Manager
```python
from moderatelyai_sdk import ModeratelyAI
with ModeratelyAI(team_id="your-team-id", api_key="your-api-key") as client:
users = client.users.list()
print(f"Found {len(users)} users")
```
### Async Support
The SDK provides full async support with `AsyncModeratelyAI`. All methods have identical interfaces - just add `await`:
```python
import asyncio
from moderatelyai_sdk import AsyncModeratelyAI
async def main():
# Use async context manager (recommended)
async with AsyncModeratelyAI() as client: # reads environment variables
# All the same operations, just with await
users = await client.users.list()
dataset = await client.datasets.create(name="Async Dataset")
agents = await client.agents.list()
# File operations work the same way
file = await client.files.upload(
file="data.csv",
name="Training Data"
)
if file.is_ready():
content = await file.download()
await file.delete()
asyncio.run(main())
```
### File Operations
The SDK provides rich file upload, download, and management capabilities with automatic presigned URL handling:
```python
from moderatelyai_sdk import ModeratelyAI
client = ModeratelyAI()
# Upload a file (multiple input types supported)
file = client.files.upload(
file="/path/to/document.pdf", # File path
name="Important Document",
metadata={"category": "legal", "priority": "high"}
)
# Upload from bytes or file-like objects also supported
with open("data.csv", "rb") as f:
file = client.files.upload(
file=f.read(), # Raw bytes
name="Dataset"
)
# Rich file model with convenience methods
print(f"File: {file.name} ({file.file_size} bytes)")
print(f"Type: {file.mime_type}")
print(f"Ready: {file.is_ready()}")
print(f"Is CSV: {file.is_csv()}")
print(f"Is Document: {file.is_document()}")
# Download files
content = file.download() # Download to memory
file.download(path="./local_copy.pdf") # Download to disk
# List files with filtering
files_response = client.files.list(
mime_type="application/pdf",
page_size=20,
order_direction="desc"
)
files = files_response["items"] # List of FileModel instances
for file in files:
if file.is_ready():
print(f"Ready: {file.name} ({file.file_size} bytes)")
# Delete files
file.delete() # Permanent deletion
```
#### Async File Operations
File operations work identically in async mode:
```python
import asyncio
from moderatelyai_sdk import AsyncModeratelyAI
async def file_operations():
async with AsyncModeratelyAI() as client:
# Same interface, just add await
file = await client.files.upload(
file="document.pdf",
name="Async Upload"
)
# All the same rich methods available
if file.is_ready() and file.is_document():
content = await file.download() # Download to memory
await file.download(path="./copy.pdf") # Download to disk
await file.delete() # Clean up
asyncio.run(file_operations())
```
### Error Handling
```python
from moderatelyai_sdk import ModeratelyAI, APIError, AuthenticationError
client = ModeratelyAI(team_id="your-team-id", api_key="your-api-key")
try:
dataset = client.datasets.create(name="Test Dataset")
except AuthenticationError:
print("Invalid API key")
except APIError as e:
print(f"API error: {e}")
if hasattr(e, 'status_code'):
print(f"Status code: {e.status_code}")
```
## Configuration
The client can be configured with various options:
```python
client = ModeratelyAI(
team_id="your-team-id",
api_key="your-api-key",
base_url="https://api.moderately.ai", # Custom API endpoint
timeout=30, # Request timeout in seconds
max_retries=3 # Maximum retry attempts
)
```
## Examples
Complete working examples are available in the `examples/` directory:
- **[File Operations](examples/01-file-operations/)** - Complete file upload, download, and management workflows
- `main.py` - Synchronous file operations example
- `main_async.py` - Asynchronous file operations example
- Demonstrates upload, list, download, and delete operations
- Shows both FileModel and resource-level approaches
- Includes REST API to SDK method mappings
To run the examples:
```bash
cd examples/01-file-operations
dotenvx run -- python main.py # Sync version
dotenvx run -- python main_async.py # Async version
```
## Development
This project uses PDM for dependency management. To set up the development environment:
```bash
# Install PDM
pip install pdm
# Install dependencies
pdm install
# Install pre-commit hooks
pdm run pre-commit install
# Run tests
pdm run pytest
# Run linting
pdm run ruff check .
pdm run ruff format .
# Type checking
pdm run mypy src/
```
## API Reference
### ModeratelyAI
The main client class for interacting with the Moderately AI API.
### AsyncModeratelyAI
The async client class with identical interface to `ModeratelyAI`. All methods are async and return awaitable objects.
#### Resource Groups
- `client.users`: Manage users in your team
- `client.teams`: Manage team settings and information
- `client.agents`: Manage AI agents
- `client.agent_executions`: Create and monitor agent executions
- `client.datasets`: Manage datasets with rich functionality (upload, download, schema management)
- `client.pipelines`: Manage pipeline metadata (create, update, delete pipelines)
- `client.pipeline_configuration_versions`: Manage pipeline workflow configurations and logic
- `client.pipeline_executions`: Execute pipelines and monitor execution status
- `client.files`: Upload and manage files
### Exceptions
- `ModeratelyAIError`: Base exception class
- `APIError`: Raised for API-related errors
- `AuthenticationError`: Raised for authentication failures
- `ConflictError`: Raised for resource conflicts
- `NotFoundError`: Raised when resources are not found
- `RateLimitError`: Raised when rate limits are exceeded
- `TimeoutError`: Raised for request timeouts
- `UnprocessableEntityError`: Raised for validation errors
- `ValidationError`: Raised for input validation errors
## License
This project is licensed under the MIT License - see the LICENSE file for details.
## Support
For questions and support, please visit our [GitHub repository](https://github.com/moderately-ai/platform-sdk) or contact us at sdk@moderately.ai.
Raw data
{
"_id": null,
"home_page": null,
"name": "moderatelyai-sdk",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": null,
"keywords": "ai, sdk, api, moderately",
"author": null,
"author_email": "Moderately AI <sdk@moderately.ai>",
"download_url": "https://files.pythonhosted.org/packages/39/01/2ee30aa1d7d20eeedc05599cc5979e25cd9f19d9e94b585716913895cff9/moderatelyai_sdk-0.2.6.tar.gz",
"platform": null,
"description": "# Moderately AI Python SDK\n\nThe official Python SDK for the Moderately AI platform, providing programmatic access to agents, datasets, pipelines, and team management.\n\n## Features\n\n- **Python 3.8+ Support**: Compatible with Python 3.8 and later versions\n- **Type Safety**: Full type annotations with mypy support\n- **Async/Await**: Built-in support for asynchronous operations\n- **Team-scoped Operations**: Automatic filtering and scoping to your team\n- **Resource Management**: Agents, datasets, pipelines, files, and users\n- **Error Handling**: Comprehensive exception handling for different error scenarios\n- **Rate Limiting**: Built-in rate limit handling and retry logic\n- **Modern Tooling**: Uses PDM for dependency management, Ruff for linting, and pytest for testing\n\n## Installation\n\n```bash\npip install moderatelyai-sdk\n```\n\n## Quick Start\n\n### Synchronous Client\n\n```python\nimport moderatelyai_sdk\n\n# Initialize with environment variables (recommended)\nclient = moderatelyai_sdk.ModeratelyAI() # reads MODERATELY_API_KEY and MODERATELY_TEAM_ID\n\n# Or initialize with explicit parameters\nclient = moderatelyai_sdk.ModeratelyAI(\n team_id=\"your-team-id\",\n api_key=\"your-api-key\"\n)\n\n# Use the client - all operations are automatically scoped to your team\nusers = client.users.list()\ndataset = client.datasets.create(name=\"My Dataset\")\nagents = client.agents.list()\n```\n\n### Asynchronous Client\n\n```python\nimport asyncio\nimport moderatelyai_sdk\n\nasync def main():\n # Initialize async client\n async with moderatelyai_sdk.AsyncModeratelyAI() as client:\n # Same operations, just with await\n users = await client.users.list()\n dataset = await client.datasets.create(name=\"My Dataset\")\n agents = await client.agents.list()\n\nasyncio.run(main())\n```\n\n## Usage\n\n### Working with Datasets\n\n```python\nfrom moderatelyai_sdk import ModeratelyAI\n\nclient = ModeratelyAI(team_id=\"your-team-id\", api_key=\"your-api-key\")\n\n# Create a dataset\ndataset = client.datasets.create(\n name=\"Customer Data\",\n description=\"Customer interaction dataset\"\n)\n\n# Upload data to the dataset\nversion = dataset.upload_data(\"/path/to/data.csv\")\nprint(f\"Uploaded version {version.version_no} with {version.row_count} rows\")\n\n# List all datasets\ndatasets = client.datasets.list()\n```\n\n### Working with Agents\n\n```python\n# List all agents in your team\nagents = client.agents.list()\n\n# Create and run an agent execution\nexecution = client.agent_executions.create(\n agent_id=\"agent_123\",\n input_data={\"query\": \"Process this data\"}\n)\n```\n\n### Working with Pipelines\n\n```python\n# Create a pipeline\npipeline = client.pipelines.create(\n name=\"Document Processing Pipeline\",\n description=\"Processes legal documents and extracts key information\"\n)\n\n# Create a configuration version with workflow logic\nconfig_version = client.pipeline_configuration_versions.create(\n pipeline_id=pipeline[\"pipelineId\"],\n configuration={\n \"id\": \"doc-processor\",\n \"name\": \"Document Processor\",\n \"version\": \"1.0.0\",\n \"blocks\": {\n \"input\": {\n \"id\": \"input\",\n \"type\": \"input\",\n \"config\": {\"json_schema\": {\"type\": \"object\"}}\n },\n \"llm\": {\n \"id\": \"llm\",\n \"type\": \"llm\", \n \"config\": {\n \"provider\": \"anthropic\",\n \"model\": \"small\",\n \"temperature\": 0.2\n }\n },\n \"output\": {\n \"id\": \"output\",\n \"type\": \"output\",\n \"config\": {\"name\": \"results\"}\n }\n }\n }\n)\n\n# Execute the pipeline\nexecution = client.pipeline_executions.create(\n pipeline_configuration_version_id=config_version[\"pipelineConfigurationVersionId\"],\n pipeline_input={\"documents\": [\"doc1.pdf\", \"doc2.pdf\"]},\n pipeline_input_summary=\"Process 2 legal documents\"\n)\n\n# Monitor execution status\nstatus = client.pipeline_executions.retrieve(execution[\"pipelineExecutionId\"])\nprint(f\"Execution status: {status['status']}\")\n\n# Get execution results when completed\nif status[\"status\"] == \"completed\":\n output = client.pipeline_executions.get_output(execution[\"pipelineExecutionId\"]) \n print(f\"Results: {output}\")\n\n# List all pipelines in your team\npipelines = client.pipelines.list()\n```\n\n### Using Context Manager\n\n```python\nfrom moderatelyai_sdk import ModeratelyAI\n\nwith ModeratelyAI(team_id=\"your-team-id\", api_key=\"your-api-key\") as client:\n users = client.users.list()\n print(f\"Found {len(users)} users\")\n```\n\n### Async Support\n\nThe SDK provides full async support with `AsyncModeratelyAI`. All methods have identical interfaces - just add `await`:\n\n```python\nimport asyncio\nfrom moderatelyai_sdk import AsyncModeratelyAI\n\nasync def main():\n # Use async context manager (recommended)\n async with AsyncModeratelyAI() as client: # reads environment variables\n # All the same operations, just with await\n users = await client.users.list()\n dataset = await client.datasets.create(name=\"Async Dataset\")\n agents = await client.agents.list()\n \n # File operations work the same way\n file = await client.files.upload(\n file=\"data.csv\",\n name=\"Training Data\"\n )\n \n if file.is_ready():\n content = await file.download()\n await file.delete()\n\nasyncio.run(main())\n```\n\n### File Operations\n\nThe SDK provides rich file upload, download, and management capabilities with automatic presigned URL handling:\n\n```python\nfrom moderatelyai_sdk import ModeratelyAI\n\nclient = ModeratelyAI()\n\n# Upload a file (multiple input types supported)\nfile = client.files.upload(\n file=\"/path/to/document.pdf\", # File path\n name=\"Important Document\",\n metadata={\"category\": \"legal\", \"priority\": \"high\"}\n)\n\n# Upload from bytes or file-like objects also supported\nwith open(\"data.csv\", \"rb\") as f:\n file = client.files.upload(\n file=f.read(), # Raw bytes\n name=\"Dataset\"\n )\n\n# Rich file model with convenience methods\nprint(f\"File: {file.name} ({file.file_size} bytes)\")\nprint(f\"Type: {file.mime_type}\")\nprint(f\"Ready: {file.is_ready()}\")\nprint(f\"Is CSV: {file.is_csv()}\")\nprint(f\"Is Document: {file.is_document()}\")\n\n# Download files\ncontent = file.download() # Download to memory\nfile.download(path=\"./local_copy.pdf\") # Download to disk\n\n# List files with filtering\nfiles_response = client.files.list(\n mime_type=\"application/pdf\",\n page_size=20,\n order_direction=\"desc\"\n)\n\nfiles = files_response[\"items\"] # List of FileModel instances\nfor file in files:\n if file.is_ready():\n print(f\"Ready: {file.name} ({file.file_size} bytes)\")\n\n# Delete files\nfile.delete() # Permanent deletion\n```\n\n#### Async File Operations\n\nFile operations work identically in async mode:\n\n```python\nimport asyncio\nfrom moderatelyai_sdk import AsyncModeratelyAI\n\nasync def file_operations():\n async with AsyncModeratelyAI() as client:\n # Same interface, just add await\n file = await client.files.upload(\n file=\"document.pdf\",\n name=\"Async Upload\"\n )\n \n # All the same rich methods available\n if file.is_ready() and file.is_document():\n content = await file.download() # Download to memory \n await file.download(path=\"./copy.pdf\") # Download to disk\n await file.delete() # Clean up\n\nasyncio.run(file_operations())\n```\n\n### Error Handling\n\n```python\nfrom moderatelyai_sdk import ModeratelyAI, APIError, AuthenticationError\n\nclient = ModeratelyAI(team_id=\"your-team-id\", api_key=\"your-api-key\")\n\ntry:\n dataset = client.datasets.create(name=\"Test Dataset\")\nexcept AuthenticationError:\n print(\"Invalid API key\")\nexcept APIError as e:\n print(f\"API error: {e}\")\n if hasattr(e, 'status_code'):\n print(f\"Status code: {e.status_code}\")\n```\n\n## Configuration\n\nThe client can be configured with various options:\n\n```python\nclient = ModeratelyAI(\n team_id=\"your-team-id\",\n api_key=\"your-api-key\",\n base_url=\"https://api.moderately.ai\", # Custom API endpoint\n timeout=30, # Request timeout in seconds\n max_retries=3 # Maximum retry attempts\n)\n```\n\n## Examples\n\nComplete working examples are available in the `examples/` directory:\n\n- **[File Operations](examples/01-file-operations/)** - Complete file upload, download, and management workflows\n - `main.py` - Synchronous file operations example \n - `main_async.py` - Asynchronous file operations example\n - Demonstrates upload, list, download, and delete operations\n - Shows both FileModel and resource-level approaches\n - Includes REST API to SDK method mappings\n\nTo run the examples:\n```bash\ncd examples/01-file-operations\ndotenvx run -- python main.py # Sync version\ndotenvx run -- python main_async.py # Async version\n```\n\n## Development\n\nThis project uses PDM for dependency management. To set up the development environment:\n\n```bash\n# Install PDM\npip install pdm\n\n# Install dependencies\npdm install\n\n# Install pre-commit hooks\npdm run pre-commit install\n\n# Run tests\npdm run pytest\n\n# Run linting\npdm run ruff check .\npdm run ruff format .\n\n# Type checking\npdm run mypy src/\n```\n\n## API Reference\n\n### ModeratelyAI\n\nThe main client class for interacting with the Moderately AI API.\n\n### AsyncModeratelyAI \n\nThe async client class with identical interface to `ModeratelyAI`. All methods are async and return awaitable objects.\n\n#### Resource Groups\n\n- `client.users`: Manage users in your team\n- `client.teams`: Manage team settings and information\n- `client.agents`: Manage AI agents\n- `client.agent_executions`: Create and monitor agent executions\n- `client.datasets`: Manage datasets with rich functionality (upload, download, schema management)\n- `client.pipelines`: Manage pipeline metadata (create, update, delete pipelines)\n- `client.pipeline_configuration_versions`: Manage pipeline workflow configurations and logic\n- `client.pipeline_executions`: Execute pipelines and monitor execution status\n- `client.files`: Upload and manage files\n\n### Exceptions\n\n- `ModeratelyAIError`: Base exception class\n- `APIError`: Raised for API-related errors\n- `AuthenticationError`: Raised for authentication failures\n- `ConflictError`: Raised for resource conflicts\n- `NotFoundError`: Raised when resources are not found\n- `RateLimitError`: Raised when rate limits are exceeded\n- `TimeoutError`: Raised for request timeouts\n- `UnprocessableEntityError`: Raised for validation errors\n- `ValidationError`: Raised for input validation errors\n\n## License\n\nThis project is licensed under the MIT License - see the LICENSE file for details.\n\n## Support\n\nFor questions and support, please visit our [GitHub repository](https://github.com/moderately-ai/platform-sdk) or contact us at sdk@moderately.ai.",
"bugtrack_url": null,
"license": "MIT",
"summary": "Python SDK for Moderately AI platform",
"version": "0.2.6",
"project_urls": {
"Documentation": "https://moderately-ai-platform-sdk.readthedocs.io/",
"Homepage": "https://github.com/moderately-ai/platform-sdk",
"Issues": "https://github.com/moderately-ai/platform-sdk/issues",
"Repository": "https://github.com/moderately-ai/platform-sdk"
},
"split_keywords": [
"ai",
" sdk",
" api",
" moderately"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "62d69b05ae73554ce5c869b983c0f1dc1799d64d1054c6bd570a9703734990eb",
"md5": "500f549fc72999f1f2a3f5d006827732",
"sha256": "e71b77437395860e584c2f1dd4bf55dd0200381ca7e8af800084443cd16fdc02"
},
"downloads": -1,
"filename": "moderatelyai_sdk-0.2.6-py3-none-any.whl",
"has_sig": false,
"md5_digest": "500f549fc72999f1f2a3f5d006827732",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 111411,
"upload_time": "2025-08-11T21:53:24",
"upload_time_iso_8601": "2025-08-11T21:53:24.795627Z",
"url": "https://files.pythonhosted.org/packages/62/d6/9b05ae73554ce5c869b983c0f1dc1799d64d1054c6bd570a9703734990eb/moderatelyai_sdk-0.2.6-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "39012ee30aa1d7d20eeedc05599cc5979e25cd9f19d9e94b585716913895cff9",
"md5": "7ea4268bbf4997af8bce5de8217b43e0",
"sha256": "cdd1f1ad80b27c5ad26f4c0c5ba42c0c3ab8df21c79c2596c0367d7e6e54a6c5"
},
"downloads": -1,
"filename": "moderatelyai_sdk-0.2.6.tar.gz",
"has_sig": false,
"md5_digest": "7ea4268bbf4997af8bce5de8217b43e0",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 64988,
"upload_time": "2025-08-11T21:53:26",
"upload_time_iso_8601": "2025-08-11T21:53:26.013409Z",
"url": "https://files.pythonhosted.org/packages/39/01/2ee30aa1d7d20eeedc05599cc5979e25cd9f19d9e94b585716913895cff9/moderatelyai_sdk-0.2.6.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-08-11 21:53:26",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "moderately-ai",
"github_project": "platform-sdk",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "moderatelyai-sdk"
}