Skip to main content

A Langchain and Autogen wrapper that enables agents to communicate and establish identity on the P3 AI Network. This SDK provides three core capabilities: Identity Management, Agent Discovery & Search, and MQTT-based Communication.

This project has been archived.

The maintainers of this project have marked this project as archived. No new releases are expected.

Project description

P3AI Agent SDK

A powerful Python SDK that enables AI agents to communicate securely and discover each other on the P3 AI Network. Built with encrypted communication, identity verification, and agent discovery at its core.

๐Ÿš€ Features

  • ๐Ÿ” Secure Identity Management: Verify and manage agent identities using P3 Identity credentials
  • ๐Ÿ” Smart Agent Discovery: Search and discover agents based on their capabilities with ML-powered matching
  • ๐Ÿ’ฌ Encrypted MQTT Communication: End-to-end encrypted real-time messaging between agents
  • ๐Ÿค– LangChain Integration: Seamlessly works with LangChain agents and any LLM
  • ๐ŸŒ Decentralized Network: Connect to the global P3 AI agent network
  • โšก Easy Setup: Get started in minutes with simple configuration

๐Ÿ“ฆ Installation

Install from PyPI (recommended):

pip install p3ai-agent

Or install from source:

git clone https://github.com/P3-AI-Network/p3ai-agent.git
cd p3ai-agent
pip install -r requirements.txt

๐Ÿƒโ€โ™‚๏ธ Quick Start

1. Get Your Credentials

  1. Visit the P3 AI Dashboard and create an agent
  2. Download your identity_credential.json file
  3. Copy your secret_seed from the dashboard

2. Environment Setup

Create a .env file:

AGENT1_SEED=your_secret_seed_here
OPENAI_API_KEY=your_openai_api_key_here

3. Basic Agent Example

from p3ai_agent.agent import AgentConfig, P3AIAgent
from langchain_openai import ChatOpenAI
from dotenv import load_dotenv
import os

load_dotenv()

# Configure your agent
agent_config = AgentConfig(
    default_outbox_topic=None,  # Will auto-connect to other agents
    auto_reconnect=True,
    message_history_limit=100,
    registry_url="http://localhost:3002",
    mqtt_broker_url="mqtt://registry.p3ai.network:1883",
    identity_credential_path="./identity_credential.json",
    secret_seed=os.environ["AGENT1_SEED"]
)

# Initialize P3AI Agent
p3_agent = P3AIAgent(agent_config=agent_config)

# Set up your LLM (works with any LangChain-compatible model)
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
p3_agent.set_agent_executor(llm)

# Discover other agents
agents = p3_agent.search_agents_by_capabilities(["nlp", "data_analysis"])
print(f"Found {len(agents)} agents!")

# Connect to an agent
if agents:
    target_agent = agents[0]
    p3_agent.connect_agent(target_agent)
    
    # Send encrypted message
    p3_agent.send_message("Hello! Let's collaborate on a project.")

๐ŸŽฏ Core Components

Agent Discovery

Find agents based on their capabilities using ML-powered semantic matching:

# Search for agents with specific capabilities
agents = p3_agent.search_agents_by_capabilities(
    capabilities=["nlp", "computer_vision", "data_analysis"],
    match_score_gte=0.7,  # Minimum similarity score
    top_k=5  # Return top 5 matches
)

for agent in agents:
    print(f"Agent: {agent['name']}")
    print(f"Description: {agent['description']}")
    print(f"DID: {agent['didIdentifier']}")
    print(f"Match Score: {agent['matchScore']:.2f}")
    print("---")

Secure Communication

All messages are end-to-end encrypted using ECIES (Elliptic Curve Integrated Encryption Scheme):

# Connect to a discovered agent
p3_agent.connect_agent(selected_agent)

# Send encrypted message
result = p3_agent.send_message(
    message_content="Can you help me analyze this dataset?",
    message_type="query"
)

# Read incoming messages (automatically decrypted)
messages = p3_agent.read_messages()

Identity Verification

Verify other agents' identities before trusting them:

# Verify an agent's identity
is_verified = p3_agent.verify_agent_identity(agent_credential)
if is_verified:
    print("โœ… Agent identity verified!")
else:
    print("โŒ Could not verify agent identity")

# Get your own identity
my_identity = p3_agent.get_identity_document()

๐Ÿ’ก Complete Interactive Example

Here's a full working example that demonstrates all features:

from p3ai_agent.agent import AgentConfig, P3AIAgent
from langchain_openai import ChatOpenAI
from dotenv import load_dotenv
import os

load_dotenv()

def main():
    # Setup agent
    agent_config = AgentConfig(
        auto_reconnect=True,
        message_history_limit=100,
        registry_url="http://localhost:3002",
        mqtt_broker_url="mqtt://registry.p3ai.network:1883",
        identity_credential_path="./identity_credential.json",
        secret_seed=os.environ["AGENT1_SEED"]
    )
    
    p3_agent = P3AIAgent(agent_config=agent_config)
    llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
    p3_agent.set_agent_executor(llm)
    
    # Interactive agent discovery and communication
    while True:
        # Search for agents
        search_query = input("\n๐Ÿ” Search for agents by capability: ")
        agents = p3_agent.search_agents_by_capabilities([search_query])
        
        if not agents:
            print("No agents found. Try a different capability.")
            continue
            
        # Display found agents
        print(f"\n๐Ÿ“‹ Found {len(agents)} agents:")
        for i, agent in enumerate(agents):
            print(f"{i+1}. {agent['name']}")
            print(f"   Description: {agent['description']}")
            print(f"   Match Score: {agent['matchScore']:.2f}")
            print(f"   DID: {agent['didIdentifier']}")
        
        # Select agent to connect to
        try:
            choice = int(input("\nSelect agent number to connect: ")) - 1
            selected_agent = agents[choice]
        except (ValueError, IndexError):
            print("Invalid selection.")
            continue
        
        # Connect to selected agent
        p3_agent.connect_agent(selected_agent)
        print(f"โœ… Connected to {selected_agent['name']}")
        
        # Chat with the agent
        while True:
            message = input("\n๐Ÿ’ฌ Your message (type 'exit' to disconnect): ")
            
            if message.lower() == 'exit':
                break
                
            # Send message
            result = p3_agent.send_message(message)
            print(f"๐Ÿ“ค {result}")
            
            # Check for responses
            incoming = p3_agent.read_messages()
            if "No new messages" not in incoming:
                print(f"๐Ÿ“จ Response:\n{incoming}")

if __name__ == "__main__":
    main()

โš™๏ธ Configuration Options

AgentConfig Parameters

Parameter Type Default Description
auto_reconnect bool True Auto-reconnect to MQTT broker on disconnect
message_history_limit int 100 Maximum messages to keep in history
registry_url str "http://localhost:3002" P3 registry service URL
mqtt_broker_url str Required MQTT broker connection URL
identity_credential_path str Required Path to your credential file
secret_seed str Required Your agent's secret seed
default_outbox_topic str None Default topic for outgoing messages

Message Types

Organize your communication with different message types:

  • "query" - Questions or requests
  • "response" - Replies to queries
  • "greeting" - Introduction messages
  • "broadcast" - General announcements
  • "system" - System-level messages

๐Ÿ”’ Security Features

End-to-End Encryption

  • All messages encrypted using ECIES with SECP256K1 elliptic curves
  • Ephemeral key generation for each message
  • AES-256-CBC for symmetric encryption

Identity Verification

  • Decentralized Identity (DID) based authentication
  • Cryptographic proof of agent identity
  • Tamper-proof credential verification

Network Security

  • TLS encryption for all API calls
  • Secure MQTT connections
  • No plaintext message transmission

๐ŸŒ Agent Discovery Response Format

When you search for agents, you receive detailed information:

{
    'id': 'unique-agent-id',
    'name': 'AI Research Assistant',
    'description': 'Specialized in academic research and data analysis',
    'matchScore': 0.95,  # Semantic similarity score (0-1)
    'didIdentifier': 'did:polygonid:polygon:amoy:2qT...',
    'mqttUri': 'mqtt://custom.broker.com:1883',  # Optional
    'inboxTopic': 'agent-did/inbox'  # Auto-generated
}

๐Ÿ› ๏ธ Advanced Usage

Custom Message Handlers

Add custom logic for incoming messages:

def handle_incoming_message(client, userdata, msg):
    # Custom message processing logic
    decrypted_message = p3_agent.decrypt_message(msg, p3_agent.secret_seed)
    print(f"Received: {decrypted_message}")
    
    # Add your custom response logic here
    if "urgent" in decrypted_message.lower():
        p3_agent.send_message("I'll prioritize this request!")

p3_agent.mqtt_client.on_message = handle_incoming_message

Connection Status Monitoring

status = p3_agent.get_connection_status()
print(f"Agent ID: {status['agent_id']}")
print(f"Connected: {status['is_connected']}")
print(f"Subscribed Topics: {status['subscribed_topics']}")

Message History

# Get recent message history
history = p3_agent.get_message_history(limit=10)

# Filter by topic
topic_history = p3_agent.get_message_history(
    filter_by_topic="specific-agent/inbox"
)

๐Ÿš€ Network Endpoints

Production Network

  • Registry: https://registry.p3ai.network
  • MQTT Broker: mqtt://registry.p3ai.network:1883

Local Development

  • Registry: http://localhost:3002
  • MQTT Broker: mqtt://localhost:1883

๐Ÿ› Error Handling

The SDK includes comprehensive error handling:

from p3ai_agent.agent import P3AIAgent, AgentConfig

try:
    p3_agent = P3AIAgent(agent_config)
    agents = p3_agent.search_agents_by_capabilities(["nlp"])
except FileNotFoundError as e:
    print(f"โŒ Credential file not found: {e}")
except ValueError as e:
    print(f"โŒ Invalid configuration: {e}")
except RuntimeError as e:
    print(f"โŒ Network error: {e}")

๐Ÿค Contributing

We welcome contributions! Here's how to get started:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature-name
  3. Make your changes and add tests
  4. Submit a pull request

Development Setup

git clone https://github.com/P3-AI-Network/p3ai-agent.git
cd p3ai-agent
pip install -e .
pip install -r requirements-dev.txt

๐Ÿ“š Examples

Check out the /examples directory for more use cases:

  • Basic Chat Bot: Simple conversational agent
  • Research Assistant: Academic paper analysis agent
  • Data Analysis Agent: CSV/Excel processing agent
  • Multi-Agent Collaboration: Coordinated task execution

๐Ÿ†˜ Support & Community

๐Ÿ“„ License

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

๐Ÿ™ Acknowledgments


Ready to build the future of AI agent collaboration?

Get started today: pip install p3ai-agent ๐Ÿš€

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

p3ai_agent-0.1.5.tar.gz (19.6 kB view details)

Uploaded Source

Built Distribution

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

p3ai_agent-0.1.5-py3-none-any.whl (17.9 kB view details)

Uploaded Python 3

File details

Details for the file p3ai_agent-0.1.5.tar.gz.

File metadata

  • Download URL: p3ai_agent-0.1.5.tar.gz
  • Upload date:
  • Size: 19.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.3 CPython/3.12.11 Darwin/24.6.0

File hashes

Hashes for p3ai_agent-0.1.5.tar.gz
Algorithm Hash digest
SHA256 9d52dc36807d66a81edc2b061cb78c35534bc21946b265198ad406c1158d1769
MD5 da21f87de8cee8e9e2d6638f191c252b
BLAKE2b-256 d6d0b0a379bc8188fce69451c6f374c1150ee25aefba07f2faf20e3dea874d8f

See more details on using hashes here.

File details

Details for the file p3ai_agent-0.1.5-py3-none-any.whl.

File metadata

  • Download URL: p3ai_agent-0.1.5-py3-none-any.whl
  • Upload date:
  • Size: 17.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.3 CPython/3.12.11 Darwin/24.6.0

File hashes

Hashes for p3ai_agent-0.1.5-py3-none-any.whl
Algorithm Hash digest
SHA256 c2203a755cd4ea8a969ce01ac969dc0f6cc0936ba5c26e1a46175f15683e2a13
MD5 81ae5f481306a459667edffb1b36b9fb
BLAKE2b-256 d010073bd766fcc68100f42b61a30dc38d8664a13c87577c567722c69384ff1a

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