Skip to main content

Python SDK for the Payman AI Platform

Project description

Payman SDK Python

This SDK provides a simple way to interact with the Payman AI Platform's API using client credentials authentication. The SDK automatically handles token management, including fetching and refreshing access tokens.

Installation

Prerequisites

  • Python 3.8 or higher
  • Poetry for dependency management

Setup

# Install Poetry (if not already installed)
curl -sSL https://install.python-poetry.org | python3 -

# Clone the repository
git clone https://github.com/payman-ai/payman-sdk-python.git
cd payman-sdk-python

# Install dependencies
poetry install

# Activate virtual environment
poetry shell

Environment Setup

Before running the SDK or tests, you need to set up your environment variables. Create a .env file in the root directory with the following variables:

PAYMAN_CLIENT_ID=your-client-id
PAYMAN_CLIENT_SECRET=your-client-secret

These credentials are required for both running the SDK and executing tests.

Development

Project Structure

payman-sdk-python/
├── payman_sdk/          # Main package directory
│   ├── __init__.py     # Package initialization
│   ├── client.py       # Main client implementation
│   ├── types.py        # Type definitions
│   └── utils.py        # Utility functions
├── tests/              # Test suite
│   ├── __init__.py
│   ├── conftest.py
│   ├── test_client.py
│   ├── test_types.py
│   └── test_utils.py
├── pyproject.toml      # Poetry configuration
├── poetry.lock         # Locked dependencies
├── pytest.ini         # Pytest configuration
├── CHANGELOG.md       # Version history
└── README.md          # This file

Development Workflow

  1. Setup Development Environment
# Install all dependencies including development tools
poetry install

# Activate virtual environment
poetry shell
  1. Running Tests
# Run all tests with coverage
poetry run pytest

# Run specific test file
poetry run pytest tests/test_client.py -v

# Run tests with coverage report
poetry run pytest --cov=payman_sdk --cov-report=html
  1. Code Quality
# Format code
poetry run black .
poetry run isort .

# Type checking
poetry run mypy .

# Run all quality checks
poetry run black . && poetry run isort . && poetry run mypy .
  1. Building and Publishing
# Build the package
poetry build

# Publish to PyPI (requires authentication)
poetry publish

Usage

Initialization

The SDK provides three ways to initialize the client:

  1. Using client credentials (recommended for server-side applications):
from payman_sdk import PaymanClient

payman = PaymanClient.with_credentials({
    'client_id': 'your-client-id',
    'client_secret': 'your-client-secret',
})
  1. Using an authorization code (for OAuth flow):
payman = PaymanClient.with_auth_code({
    'client_id': 'your-client-id',
    'environment': 'TEST'
}, 'your-auth-code')
  1. Using an access token (when you already have a token):
payman = PaymanClient.with_token(
    'your-client-id',
    {
        'access_token': 'your-access-token',
        'expires_in': 3600  # token expiry in seconds
    },
)

Making Requests

  1. Get a formatted response (recommended for most use cases):
response = payman.ask("What's the weather?")
print(response)
  1. Get a raw response (when you need the full JSON-RPC response):
raw_response = payman.ask("What's the weather?", raw=True)
print(raw_response)
  1. Streaming request with formatted responses:
payman.ask("What's the weather?", {
    'on_message': lambda response: print(f"Formatted response: {response}")
})
  1. Streaming request with raw responses:
payman.ask("What's the weather?", {
    'on_message': lambda response: print(f"Raw response: {response}")
}, raw=True)
  1. Start a new session with metadata:
response = payman.ask("Hello!", {
    'new_session': True,
    'metadata': {'source': 'web-app'}
})

Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature-name
  3. Make your changes
  4. Run tests: poetry run pytest
  5. Format code: poetry run black . && poetry run isort .
  6. Check types: poetry run mypy .
  7. Commit your changes: git commit -am 'Add feature'
  8. Push to the branch: git push origin feature-name
  9. Submit a pull request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Testing

The SDK uses pytest for testing. To run the tests:

  1. Make sure you have set up your .env file with the required credentials
  2. Install dependencies:
pip install -e ".[dev]"
  1. Run the tests:
pytest

The test suite will verify the SDK's functionality, including authentication, API interactions, and response handling.

API Reference

PaymanClient

Static Methods

  • with_credentials(config: PaymanConfig) -> PaymanClient

    • Creates a client using client credentials
    • config: Configuration object containing client_id, client_secret, and optional environment
  • with_auth_code(config: PaymanConfig, auth_code: str) -> PaymanClient

    • Creates a client using an authorization code
    • config: Configuration object containing client_id, client_secret, and optional environment
    • auth_code: Authorization code obtained via OAuth
  • with_token(client_id: str, token_info: Dict[str, Any], environment: Optional[Environment] = 'LIVE') -> PaymanClient

    • Creates a client using an existing access token
    • client_id: Your Payman client ID
    • token_info: Object containing access token and its expiration time
    • environment: Optional environment to use (defaults to "LIVE")

Instance Methods

  • ask(text: str, options: Optional[AskOptions] = None, raw: bool = False) -> Union[FormattedTaskResponse, TaskResponse]

    • Sends a message to the Payman AI Agent
    • text: The message or question to send
    • options: Optional parameters for the request
    • raw: Whether to return raw responses (default: False)
  • get_access_token() -> Optional[Dict[str, Any]]

    • Gets the current access token and its expiration information
    • Returns None if no token is set
  • is_access_token_expired() -> bool

    • Checks if the current access token has expired
    • Returns True if the token has expired or is about to expire within 60 seconds

Types

  • PaymanConfig

    {
        'client_id': str,
        'client_secret': str,
        'environment': Optional[Literal['TEST', 'LIVE', 'INTERNAL']]
    }
    
  • AskOptions

    {
        'on_message': Optional[Callable[[Union[FormattedTaskResponse, TaskResponse]], None]],
        'new_session': Optional[bool],
        'metadata': Optional[Dict[str, Any]],
        'part_metadata': Optional[Dict[str, Any]],
        'message_metadata': Optional[Dict[str, Any]]
    }
    

Response Types

  • FormattedTaskResponse

    {
        'status': Literal['completed', 'failed', 'in_progress'],
        'is_final': bool,
        'artifacts': Optional[List[Dict[str, Any]]],
        'error': Optional[Dict[str, Any]]
    }
    
  • TaskResponse

    {
        'jsonrpc': Literal['2.0'],
        'id': str,
        'result': Optional[Dict[str, Any]],
        'error': Optional[Dict[str, Any]]
    }
    

Events

  • TaskStatusUpdateEvent

    {
        'type': Literal['status_update'],
        'status': Literal['completed', 'failed', 'in_progress'],
        'is_final': bool
    }
    
  • TaskArtifactUpdateEvent

    {
        'type': Literal['artifact_update'],
        'artifacts': List[Dict[str, Any]]
    }
    

Error Handling

The SDK uses the requests library for HTTP requests. All API calls will raise an exception if the request fails. You can catch these exceptions and handle them appropriately:

try:
    response = payman.ask("What's the weather?")
except requests.exceptions.RequestException as e:
    if hasattr(e, 'response'):
        # The request was made and the server responded with a status code
        # that falls out of the range of 2xx
        print(e.response.json())
        print(e.response.status_code)
    else:
        # Something happened in setting up the request that triggered an Error
        print('Error:', str(e)) 

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

paymanai_sdk-1.0.2.tar.gz (11.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

paymanai_sdk-1.0.2-py3-none-any.whl (10.4 kB view details)

Uploaded Python 3

File details

Details for the file paymanai_sdk-1.0.2.tar.gz.

File metadata

  • Download URL: paymanai_sdk-1.0.2.tar.gz
  • Upload date:
  • Size: 11.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.5 CPython/3.9.22 Linux/6.11.0-1014-azure

File hashes

Hashes for paymanai_sdk-1.0.2.tar.gz
Algorithm Hash digest
SHA256 ed29bcc7579c6e398af9a8d0de27e3aa8340ab66a432692afd8bcfb819559ea4
MD5 137039522f3b59b2c415ff7fc9725afc
BLAKE2b-256 3b6e2320639fa52103f321d7c45b97c6c6e7555ffeac2085548c28b2b81b5967

See more details on using hashes here.

File details

Details for the file paymanai_sdk-1.0.2-py3-none-any.whl.

File metadata

  • Download URL: paymanai_sdk-1.0.2-py3-none-any.whl
  • Upload date:
  • Size: 10.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.5 CPython/3.9.22 Linux/6.11.0-1014-azure

File hashes

Hashes for paymanai_sdk-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 ec3d171de362c1f62f6573406c11bc41f218e9ff925042b8b9af8f270efae87e
MD5 65a00fc6152c981b16bc90f27f3ec879
BLAKE2b-256 3a88c0d6691db662ac013619719ced4fb6d2df3add6f66dd2995f9cd2b6c95d3

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page