Official Python SDK for PRSM (Protocol for Recursive Scientific Modeling)
Project description
PRSM Python SDK
Official Python client for the Protocol for Recursive Scientific Modeling (PRSM).
Installation
pip install prsm-python-sdk
Quick Start
import asyncio
from prsm_sdk import PRSMClient
async def main():
# Initialize client
client = PRSMClient(api_key="your_api_key_here")
# Simple AI query
response = await client.query("Explain quantum computing in simple terms")
print(response.content)
# Check token balance
balance = await client.ftns.get_balance()
print(f"FTNS Balance: {balance.available_balance}")
# Search for models
models = await client.marketplace.search_models("gpt")
print(f"Found {len(models)} models")
# Clean up
await client.close()
# Run the example
asyncio.run(main())
Features
- 🤖 AI Query Interface - Simple access to PRSM's distributed AI network
- 💰 FTNS Token Management - Built-in token balance and cost tracking
- 🔒 Authentication - Secure API key and JWT token handling
- 📊 Model Marketplace - Browse and use community-contributed models
- 🛡️ Safety Integration - Built-in safety monitoring and circuit breakers
- 📈 Performance Monitoring - Request tracking and optimization
- 🌐 P2P Network Access - Direct access to distributed computing resources
- 🔧 Tool Integration - MCP tool protocol support for enhanced capabilities
Advanced Usage
Streaming Responses
async def stream_example():
client = PRSMClient(api_key="your_api_key")
print("AI Response: ", end="")
async for chunk in client.stream("Write a short story about AI"):
print(chunk.content, end="", flush=True)
print() # New line at end
await client.close()
Cost Estimation
async def cost_example():
client = PRSMClient(api_key="your_api_key")
# Estimate cost before running
cost = await client.estimate_cost("Complex scientific query about protein folding")
print(f"Estimated cost: {cost} FTNS")
# Check if we have enough balance
balance = await client.ftns.get_balance()
if balance.available_balance >= cost:
response = await client.query("Complex scientific query about protein folding")
print(response.content)
else:
print("Insufficient FTNS balance")
await client.close()
Model Marketplace
async def marketplace_example():
client = PRSMClient(api_key="your_api_key")
# Search for specific models
science_models = await client.marketplace.search_models(
query="scientific research",
min_performance=0.8,
max_cost=0.001
)
# Use a specific model
if science_models:
model = science_models[0]
response = await client.query(
"Explain CRISPR gene editing",
model_id=model.id
)
print(f"Response from {model.name}: {response.content}")
await client.close()
Tool Execution (MCP)
async def tools_example():
client = PRSMClient(api_key="your_api_key")
# List available tools
tools = await client.tools.list_available()
print(f"Available tools: {[tool.name for tool in tools]}")
# Execute a tool
if "web_search" in [tool.name for tool in tools]:
result = await client.tools.execute(
tool_name="web_search",
parameters={"query": "latest AI research papers"}
)
print(f"Search results: {result.result}")
await client.close()
Error Handling
from prsm_sdk import (
PRSMClient,
InsufficientFundsError,
SafetyViolationError,
AuthenticationError
)
async def error_handling_example():
try:
client = PRSMClient(api_key="invalid_key")
response = await client.query("Hello world")
except AuthenticationError:
print("Invalid API key")
except InsufficientFundsError as e:
print(f"Not enough FTNS: need {e.details['required']}, have {e.details['available']}")
except SafetyViolationError as e:
print(f"Content safety violation: {e.message}")
finally:
await client.close()
Configuration
Environment Variables
export PRSM_API_KEY="your_api_key_here"
export PRSM_BASE_URL="https://api.prsm.ai/v1" # Optional
Custom Configuration
client = PRSMClient(
api_key="your_key",
base_url="https://custom-api.prsm.ai/v1",
websocket_url="wss://custom-ws.prsm.ai/v1",
timeout=120, # 2 minutes
max_retries=5
)
API Reference
PRSMClient
The main client class for interacting with PRSM.
Methods
query(prompt, **kwargs)- Execute AI querystream(prompt, **kwargs)- Stream AI responseestimate_cost(prompt, **kwargs)- Estimate query costget_safety_status()- Get safety monitoring statuslist_available_models()- List available modelshealth_check()- Check API healthclose()- Close client connections
FTNSManager
Manage FTNS token balance and transactions.
Methods
get_balance()- Get current token balanceget_transaction_history(limit=50)- Get recent transactionstransfer(to_address, amount)- Transfer tokens
ModelMarketplace
Browse and interact with the model marketplace.
Methods
search_models(query, **filters)- Search for modelsget_model_info(model_id)- Get detailed model informationlist_categories()- List model categories
ToolExecutor
Execute MCP tools and manage tool interactions.
Methods
list_available()- List available toolsexecute(tool_name, parameters)- Execute a toolget_tool_info(tool_name)- Get tool specifications
Development
Setting up Development Environment
# Clone the repository
git clone https://github.com/PRSM-AI/PRSM.git
cd PRSM/sdks/python
# Install in development mode
pip install -e ".[dev]"
# Run tests
pytest
# Run type checking
mypy prsm_sdk
# Format code
black prsm_sdk
isort prsm_sdk
Running Tests
# Run unit tests (no server needed)
pytest tests/test_client.py tests/test_models.py
# Run all tests
pytest
# Run with coverage
pytest --cov=prsm_sdk --cov-report=html
# Run specific test file
pytest tests/test_client.py
Running Integration Tests
Integration tests require a live PRSM server to be running:
# Start a PRSM node
prsm node start &
# Set your API key and run integration tests
PRSM_TEST_API_KEY=your_key pytest tests/test_integration.py -v
# Or with a custom server URL
PRSM_TEST_URL=http://localhost:8000 PRSM_TEST_API_KEY=your_key pytest tests/test_integration.py -v
Integration tests will be skipped automatically if no server is available.
Examples
See the examples directory for more comprehensive examples:
Contributing
We welcome contributions! Please see our Contributing Guide for details.
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
- 📚 Documentation: docs.prsm.ai/python-sdk
- 🐛 Issues: GitHub Issues
- 💬 Community: Discord
- 📧 Email: dev@prsm.ai
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 prsm_python_sdk-0.2.0.tar.gz.
File metadata
- Download URL: prsm_python_sdk-0.2.0.tar.gz
- Upload date:
- Size: 33.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
fedb5096df55a09b62f13b0c4a1fcd928d73f02e5f46740dd30aa48aae9e6735
|
|
| MD5 |
3b68a3d7c4b13976d16084abd59361cf
|
|
| BLAKE2b-256 |
cab8561f75648ce002102046ba045afc16bb924afddebb0477dfb8ccd46e211b
|
File details
Details for the file prsm_python_sdk-0.2.0-py3-none-any.whl.
File metadata
- Download URL: prsm_python_sdk-0.2.0-py3-none-any.whl
- Upload date:
- Size: 34.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b38467d4b17bec1e2ee94e3612458a436c9de0874db1271cabf98e4b75726cdb
|
|
| MD5 |
96ef18c87779e5fc3395499c5639fec9
|
|
| BLAKE2b-256 |
a69573d3a9af3b55c6d47de55e827152f429f98d8fc608969702f612971b15ed
|