SDK for PINAI Agent API
Project description
PINAI Agent SDK Development Guide
Introduction
PINAI Agent SDK is a powerful toolkit that allows developers to quickly create and deploy intelligent agents. This guide will help you get started and provide best practices and API references.
Installation
pip install pinai-agent-sdk
Quick Start
Here are the basic steps to create a simple agent:
import os
from pinai_agent_sdk import PINAIAgentSDK, AGENT_CATEGORY_SOCIAL
# Initialize the SDK client
API_KEY = os.environ.get("PINAI_API_KEY", "your_api_key_here")
client = PINAIAgentSDK(api_key=API_KEY)
# Define message handling function
def handle_message(message):
"""
Process incoming messages and respond
Args:
message (dict): Message object with format:
{
"session_id": "unique-session-id",
"id": 12345, # Message ID
"content": "user message text",
"created_at": "2023-01-01T12:00:00"
}
"""
print(f"Received: {message['content']}")
session_id = message.get("session_id")
if not session_id:
print("Message missing session_id, cannot respond")
return
# Get user's message
user_message = message.get("content", "")
# Get persona info
persona_info = client.get_persona(session_id)
# Create your response (this is where your agent logic goes)
response = f"Echo: {user_message}"
# Send response back to user
client.send_message(content=response)
print(f"Sent: {response}")
# Register a new agent
agent_info = client.register_agent(
name="My Hackathon Agent",
description="A simple agent built during the hackathon",
category=AGENT_CATEGORY_SOCIAL
)
agent_id = agent_info.get("id")
print(f"Agent registered with ID: {agent_id}")
# Start the agent and listen for messages
print("Starting agent... Press Ctrl+C to stop")
client.start_and_run(
on_message_callback=handle_message,
agent_id=agent_id
)
Core Concepts
Agent
An agent is the intelligent assistant you create that can interact with users. Each agent has a unique ID, name, description, and category.
Session
A session represents a conversation with a user. Each session has a unique session_id used to track interactions with a specific user.
Message
A message is the unit of information exchanged between the agent and users. Messages can contain text content and media (images, videos, audio, or files).
Agent Categories
PINAI platform supports the following agent categories:
| Category Constant | Display Name | Description |
|---|---|---|
AGENT_CATEGORY_SOCIAL |
Social | Social agents |
AGENT_CATEGORY_DAILY |
Daily Life/Utility | Daily life and utility agents |
AGENT_CATEGORY_PRODUCTIVITY |
Productivity | Productivity tool agents |
AGENT_CATEGORY_WEB3 |
Web3 | Web3-related agents |
AGENT_CATEGORY_SHOPPING |
Shopping | Shopping agents |
AGENT_CATEGORY_FINANCE |
Finance | Finance agents |
AGENT_CATEGORY_AI_CHAT |
AI Chat | AI chat agents |
AGENT_CATEGORY_OTHER |
Other | Other types of agents |
API Reference
Initializing the SDK
from pinai_agent_sdk import PINAIAgentSDK
client = PINAIAgentSDK(
api_key="your_api_key", # Required: PINAI API key
base_url="https://api.example.com", # Optional: API base URL
timeout=30, # Optional: Request timeout in seconds
polling_interval=1.0 # Optional: Message polling interval in seconds
)
Registering an Agent
agent_info = client.register_agent(
name="My Agent", # Required: Agent name
description="This is an example agent", # Required: Agent description
category=AGENT_CATEGORY_SOCIAL, # Required: Agent category
wallet="your_wallet_address", # Optional: Wallet address
cover="cover_image_url", # Optional: Cover image URL
metadata={"key": "value"} # Optional: Additional metadata
)
Unregistering an Agent
result = client.unregister_agent(agent_id=123)
Starting an Agent
# Non-blocking mode
client._start(
on_message_callback=handle_message,
agent_id=123,
blocking=False
)
# Blocking mode (until Ctrl+C)
client.start_and_run(
on_message_callback=handle_message,
agent_id=123
)
Sending Messages
response = client.send_message(
content="Hello, world!", # Required: Message content
session_id="unique-session-id", # Optional: Session ID
media_type="image", # Optional: Media type, default is "none"
media_url="https://example.com/image.jpg", # Optional: Media URL
meta_data={"key": "value"} # Optional: Additional metadata
)
Getting User Information
persona = client.get_persona(session_id="unique-session-id")
Uploading Media
media_info = client.upload_media(
file_path="/path/to/image.jpg", # File path
media_type="image" # Media type: "image", "video", "audio", "file"
)
media_url = media_info.get("url")
Media Types and Limitations
| Media Type | Supported Extensions | Size Limit |
|---|---|---|
| image | .jpg, .jpeg, .png, .gif, .webp | 10MB |
| video | .mp4, .webm, .mov | 100MB |
| audio | .mp3, .wav, .ogg | 50MB |
| file | .pdf, .txt, .zip, .docx | 20MB |
Error Handling
The SDK provides various exception types to help handle different error scenarios:
AuthenticationError: API authentication failure (401 errors)PermissionError: Insufficient permissions (403 errors)ResourceNotFoundError: Requested resource not found (404 errors)ResourceConflictError: Resource conflict (409 errors)ValidationError: Request validation failure (400 errors)ServerError: Server returns 5xx errorsNetworkError: Network connection issues
Example:
try:
client.send_message(content="Hello")
except ValidationError as e:
print(f"Validation error: {e}")
except AuthenticationError as e:
print(f"Authentication error: {e}")
except Exception as e:
print(f"Other error: {e}")
Best Practices
1. Securely Store API Keys
Don't hardcode API keys in your code. Use environment variables or secure key management services.
import os
API_KEY = os.environ.get("PINAI_API_KEY")
2. Implement Robust Message Handling
Always check if messages contain necessary fields and handle exceptions properly.
def handle_message(message):
if not message or "content" not in message:
print("Received invalid message")
return
session_id = message.get("session_id")
if not session_id:
print("Message missing session_id, cannot respond")
return
# Process message...
3. Use Asynchronous Processing for Long-Running Tasks
For tasks that require long processing times, consider using asynchronous processing to avoid blocking the message loop.
4. Regularly Save Agent State
If your agent needs to maintain state, save it regularly to prevent data loss.
5. Monitoring and Logging
Implement appropriate logging and monitoring to track your agent's performance and issues in production.
Example Applications
Echo Bot
def handle_message(message):
session_id = message.get("session_id")
content = message.get("content", "")
# Simply reply with the user's message
client.send_message(
content=f"You said: {content}",
session_id=session_id
)
Image Generation Bot
def handle_message(message):
"""
Process incoming messages and respond
Args:
message (dict): Message object with format:
{
"session_id": "unique-session-id",
"id": 12345, # Message ID
"content": "user message text",
"created_at": "2023-01-01T12:00:00"
}
"""
print(f"Received: {message['content']}")
session_id = message.get("session_id")
if not session_id:
print("Message missing session_id, cannot respond")
return
# Get user's message
user_message = message.get("content", "")
# Get persona info
persona_info = client.get_persona(session_id)
# Create your response (this is where your agent logic goes)
response = f"Echo: {user_message}"
# Send response back to user
client.send_message(content=response)
print(f"Sent: {response}")
Frequently Asked Questions
Q: How do I get an API key?
A: You can obtain an API key from the PINAI Agent platform after login.
Q: How many agents can one account create?
A: No limit.
Q: How do I handle a large number of concurrent users?
A: Consider using multi-threading or asynchronous processing, and implement appropriate rate limiting and load balancing.
Support and Resources
Good luck with your Hackathon! If you have any questions, feel free to contact the PINAI team.
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 pinai_agent_sdk-0.1.13.tar.gz.
File metadata
- Download URL: pinai_agent_sdk-0.1.13.tar.gz
- Upload date:
- Size: 21.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.10.15
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6d22262bafa40e4cfb14310b62418a5d0991f536915ecf374d27b35b39d32d43
|
|
| MD5 |
2e65d84f32f9da7589ec8ec287cce35d
|
|
| BLAKE2b-256 |
8b2a0ca201f2d4080a96e1f461e1ac51b413e1b277544f3250c75b080a132c1d
|
File details
Details for the file pinai_agent_sdk-0.1.13-py3-none-any.whl.
File metadata
- Download URL: pinai_agent_sdk-0.1.13-py3-none-any.whl
- Upload date:
- Size: 22.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.10.15
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3dd27b2e14c019613ab68f354eb7d8bd6f328924e6b9465630947bc3fd03d1be
|
|
| MD5 |
607acd99e5fe2987caa6391b95cc0af2
|
|
| BLAKE2b-256 |
974616d2374f71e86afbca4c2ef1f2e8907885bf9c1e5d8dba959e5dfbb9d6c0
|