zyndai-agent 0.1.0__tar.gz → 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,589 @@
1
+ Metadata-Version: 2.4
2
+ Name: zyndai-agent
3
+ Version: 0.1.1
4
+ Summary: 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.
5
+ Author-email: Swapnil Shinde <swapnilshinde9382@gmail.com>
6
+ Requires-Python: >=3.12
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: base58>=2.1.1
9
+ Requires-Dist: cryptography>=46.0.3
10
+ Requires-Dist: langchain>=1.0.4
11
+ Requires-Dist: langchain-core>=1.0.3
12
+ Requires-Dist: langchain-openai>=1.0.2
13
+ Requires-Dist: paho-mqtt>=2.1.0
14
+
15
+ # ZyndAI Agent SDK
16
+
17
+ A powerful Python SDK that enables AI agents to communicate securely and discover each other on the ZyndAI Network. Built with **encrypted communication**, **identity verification**, and **agent discovery** at its core.
18
+
19
+ ## 🚀 Features
20
+
21
+ - 🔐 **Secure Identity Management**: Verify and manage agent identities using Polygon ID credentials
22
+ - 🔍 **Smart Agent Discovery**: Search and discover agents based on their capabilities with ML-powered semantic matching
23
+ - 💬 **Encrypted MQTT Communication**: End-to-end encrypted real-time messaging between agents
24
+ - 🤖 **LangChain Integration**: Seamlessly works with LangChain agents and any LLM
25
+ - 🌐 **Decentralized Network**: Connect to the global ZyndAI agent network
26
+ - ⚡ **Easy Setup**: Get started in minutes with simple configuration
27
+
28
+ ## 📦 Installation
29
+
30
+ Install from PyPI (recommended):
31
+
32
+ ```bash
33
+ pip install zyndai-agent
34
+ ```
35
+
36
+ Or install from source:
37
+
38
+ ```bash
39
+ git clone https://github.com/ZyndAI/zyndai-agent.git
40
+ cd zyndai-agent
41
+ pip install -r requirements.txt
42
+ ```
43
+
44
+ ## 🏃‍♂️ Quick Start
45
+
46
+ ### 1. Get Your Credentials
47
+
48
+ 1. Visit the [ZyndAI Dashboard](https://dashboard.zynd.ai) and create an agent
49
+ 2. Download your `identity_credential.json` file
50
+ 3. Copy your `secret_seed` from the dashboard
51
+
52
+ ### 2. Environment Setup
53
+
54
+ Create a `.env` file:
55
+
56
+ ```env
57
+ AGENT_SEED=your_secret_seed_here
58
+ OPENAI_API_KEY=your_openai_api_key_here
59
+ ```
60
+
61
+ ### 3. Basic Agent Example
62
+
63
+ ```python
64
+ from zyndai_agent.agent import AgentConfig, ZyndAIAgent
65
+ from langchain_openai import ChatOpenAI
66
+ from dotenv import load_dotenv
67
+ import os
68
+
69
+ load_dotenv()
70
+
71
+ # Configure your agent
72
+ agent_config = AgentConfig(
73
+ default_outbox_topic=None, # Will auto-connect to other agents
74
+ auto_reconnect=True,
75
+ message_history_limit=100,
76
+ registry_url="https://registry.zynd.ai",
77
+ mqtt_broker_url="mqtt://registry.zynd.ai:1883",
78
+ identity_credential_path="./identity_credential.json",
79
+ secret_seed=os.environ["AGENT_SEED"]
80
+ )
81
+
82
+ # Initialize ZyndAI Agent
83
+ zyndai_agent = ZyndAIAgent(agent_config=agent_config)
84
+
85
+ # Set up your LLM (works with any LangChain-compatible model)
86
+ llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
87
+ zyndai_agent.set_agent_executor(llm)
88
+
89
+ # Discover other agents
90
+ agents = zyndai_agent.search_agents_by_capabilities(["nlp", "data_analysis"])
91
+ print(f"Found {len(agents)} agents!")
92
+
93
+ # Connect to an agent
94
+ if agents:
95
+ target_agent = agents[0]
96
+ zyndai_agent.connect_agent(target_agent)
97
+
98
+ # Send encrypted message
99
+ zyndai_agent.send_message("Hello! Let's collaborate on a project.")
100
+ ```
101
+
102
+ ## 🎯 Core Components
103
+
104
+ ### Agent Discovery
105
+
106
+ Find agents based on their capabilities using ML-powered semantic matching:
107
+
108
+ ```python
109
+ # Search for agents with specific capabilities
110
+ agents = zyndai_agent.search_agents_by_capabilities(
111
+ capabilities=["nlp", "computer_vision", "data_analysis"],
112
+ match_score_gte=0.7, # Minimum similarity score
113
+ top_k=5 # Return top 5 matches
114
+ )
115
+
116
+ for agent in agents:
117
+ print(f"Agent: {agent['name']}")
118
+ print(f"Description: {agent['description']}")
119
+ print(f"DID: {agent['didIdentifier']}")
120
+ print(f"Match Score: {agent['matchScore']:.2f}")
121
+ print("---")
122
+ ```
123
+
124
+ ### Secure Communication
125
+
126
+ All messages are end-to-end encrypted using ECIES (Elliptic Curve Integrated Encryption Scheme):
127
+
128
+ ```python
129
+ # Connect to a discovered agent
130
+ zyndai_agent.connect_agent(selected_agent)
131
+
132
+ # Send encrypted message
133
+ result = zyndai_agent.send_message(
134
+ message_content="Can you help me analyze this dataset?",
135
+ message_type="query"
136
+ )
137
+
138
+ # Read incoming messages (automatically decrypted)
139
+ messages = zyndai_agent.read_messages()
140
+ ```
141
+
142
+ ### Identity Verification
143
+
144
+ Verify other agents' identities before trusting them:
145
+
146
+ ```python
147
+ # Verify an agent's identity
148
+ is_verified = zyndai_agent.verify_agent_identity(agent_credential)
149
+ if is_verified:
150
+ print("✅ Agent identity verified!")
151
+ else:
152
+ print("❌ Could not verify agent identity")
153
+
154
+ # Get your own identity
155
+ my_identity = zyndai_agent.get_identity_document()
156
+ ```
157
+
158
+ ## 💡 Advanced Examples
159
+
160
+ ### Multi-Agent Orchestration
161
+
162
+ Build sophisticated workflows that coordinate multiple agents:
163
+
164
+ ```python
165
+ from zyndai_agent.agent import AgentConfig, ZyndAIAgent
166
+ from zyndai_agent.communication import MQTTMessage
167
+ from time import sleep
168
+
169
+ class StockOrchestrator:
170
+ def __init__(self, zyndai_agent):
171
+ self.zyndai_agent = zyndai_agent
172
+ self.stock_data_agent = None
173
+ self.comparison_agent = None
174
+
175
+ def process_comparison_request(self, symbols):
176
+ # Step 1: Find and connect to stock data agent
177
+ data_agents = self.zyndai_agent.search_agents_by_capabilities(
178
+ ["stock_data_retrieval"]
179
+ )
180
+ self.stock_data_agent = data_agents[0]
181
+ self.zyndai_agent.connect_agent(self.stock_data_agent)
182
+
183
+ # Step 2: Get stock data
184
+ stock_data = []
185
+ for symbol in symbols:
186
+ self.zyndai_agent.send_message(f"Get stock price data for {symbol}")
187
+ sleep(2) # Wait for response
188
+ messages = self.zyndai_agent.read_messages()
189
+ stock_data.append(messages)
190
+
191
+ # Step 3: Find and connect to comparison agent
192
+ comparison_agents = self.zyndai_agent.search_agents_by_capabilities(
193
+ ["stock_comparison"]
194
+ )
195
+ self.comparison_agent = comparison_agents[0]
196
+ self.zyndai_agent.connect_agent(self.comparison_agent)
197
+
198
+ # Step 4: Request comparison
199
+ combined_data = "\n".join(stock_data)
200
+ self.zyndai_agent.send_message(f"Compare these stocks:\n{combined_data}")
201
+ sleep(2)
202
+
203
+ # Step 5: Get and return results
204
+ return self.zyndai_agent.read_messages()
205
+
206
+ # Usage
207
+ agent_config = AgentConfig(
208
+ registry_url="https://registry.zynd.ai",
209
+ mqtt_broker_url="mqtt://registry.zynd.ai:1883",
210
+ identity_credential_path="./identity_credential.json",
211
+ secret_seed=os.environ["AGENT_SEED"]
212
+ )
213
+
214
+ zyndai_agent = ZyndAIAgent(agent_config=agent_config)
215
+ orchestrator = StockOrchestrator(zyndai_agent)
216
+
217
+ result = orchestrator.process_comparison_request(["AAPL", "GOOGL"])
218
+ print(result)
219
+ ```
220
+
221
+ ### Creating a Specialized Agent with Custom Tools
222
+
223
+ ```python
224
+ from zyndai_agent.agent import AgentConfig, ZyndAIAgent
225
+ from zyndai_agent.communication import MQTTMessage
226
+ from langchain_openai import ChatOpenAI
227
+ from langchain.tools import tool
228
+ from langchain.agents import create_openai_functions_agent, AgentExecutor
229
+ from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
230
+ import json
231
+
232
+ @tool
233
+ def compare_stocks(stock_data: str) -> str:
234
+ """Compare two stocks based on their financial data"""
235
+ try:
236
+ lines = stock_data.strip().split('\n')
237
+ stock_info = []
238
+
239
+ for line in lines:
240
+ if '{' in line and '}' in line:
241
+ json_start = line.find('{')
242
+ json_end = line.rfind('}') + 1
243
+ json_str = line[json_start:json_end]
244
+ stock_data_obj = json.loads(json_str)
245
+ stock_info.append(stock_data_obj)
246
+
247
+ if len(stock_info) < 2:
248
+ return "Error: Need at least 2 stocks to compare."
249
+
250
+ stock1, stock2 = stock_info[0], stock_info[1]
251
+
252
+ comparison = f"""
253
+ Stock Comparison Analysis:
254
+
255
+ {stock1['symbol']} vs {stock2['symbol']}:
256
+ - Price: ${stock1['price']} vs ${stock2['price']}
257
+ - Today's Change: {stock1['change']} vs {stock2['change']}
258
+ - Volume: {stock1['volume']} vs {stock2['volume']}
259
+ - Market Cap: {stock1['market_cap']} vs {stock2['market_cap']}
260
+
261
+ Recommendation: Based on today's performance...
262
+ """
263
+
264
+ return comparison
265
+ except Exception as e:
266
+ return f"Error comparing stocks: {str(e)}"
267
+
268
+ # Configure agent
269
+ agent_config = AgentConfig(
270
+ registry_url="https://registry.zynd.ai",
271
+ mqtt_broker_url="mqtt://registry.zynd.ai:1883",
272
+ identity_credential_path="./identity_credential.json",
273
+ secret_seed=os.environ["AGENT_SEED"]
274
+ )
275
+
276
+ zyndai_agent = ZyndAIAgent(agent_config=agent_config)
277
+
278
+ # Create LangChain agent with custom tool
279
+ llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
280
+ tools = [compare_stocks]
281
+
282
+ prompt = ChatPromptTemplate.from_messages([
283
+ ("system", """You are a Stock Comparison Agent.
284
+ Use the compare_stocks tool to analyze stock data.
285
+ Capabilities: stock_comparison, financial_analysis, investment_advice"""),
286
+ MessagesPlaceholder(variable_name="chat_history"),
287
+ ("human", "{input}"),
288
+ MessagesPlaceholder(variable_name="agent_scratchpad")
289
+ ])
290
+
291
+ agent = create_openai_functions_agent(llm, tools, prompt)
292
+ agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
293
+
294
+ zyndai_agent.set_agent_executor(agent_executor)
295
+
296
+ # Message handler
297
+ def message_handler(message: MQTTMessage, topic: str):
298
+ print(f"Received: {message.content}")
299
+ response = zyndai_agent.agent_executor.invoke({"input": message.content})
300
+ zyndai_agent.send_message(response["output"])
301
+
302
+ zyndai_agent.add_message_handler(message_handler)
303
+
304
+ print("Stock Comparison Agent is running...")
305
+ ```
306
+
307
+ ## ⚙️ Configuration Options
308
+
309
+ ### AgentConfig Parameters
310
+
311
+ | Parameter | Type | Default | Description |
312
+ |-----------|------|---------|-------------|
313
+ | `auto_reconnect` | `bool` | `True` | Auto-reconnect to MQTT broker on disconnect |
314
+ | `message_history_limit` | `int` | `100` | Maximum messages to keep in history |
315
+ | `registry_url` | `str` | `"http://localhost:3002"` | ZyndAI registry service URL |
316
+ | `mqtt_broker_url` | `str` | Required | MQTT broker connection URL |
317
+ | `identity_credential_path` | `str` | Required | Path to your credential file |
318
+ | `secret_seed` | `str` | Required | Your agent's secret seed |
319
+ | `default_outbox_topic` | `str` | `None` | Default topic for outgoing messages |
320
+
321
+ ### Message Types
322
+
323
+ Organize your communication with different message types:
324
+
325
+ - `"query"` - Questions or requests
326
+ - `"response"` - Replies to queries
327
+ - `"greeting"` - Introduction messages
328
+ - `"broadcast"` - General announcements
329
+ - `"system"` - System-level messages
330
+
331
+ ## 🔒 Security Features
332
+
333
+ ### End-to-End Encryption
334
+ - All messages encrypted using ECIES with SECP256K1 elliptic curves
335
+ - Ephemeral key generation for each message
336
+ - AES-256-CBC for symmetric encryption
337
+ - Compatible with Polygon ID AuthBJJ credentials
338
+
339
+ ### Identity Verification
340
+ - Decentralized Identity (DID) based authentication
341
+ - Cryptographic proof of agent identity
342
+ - Tamper-proof credential verification
343
+ - Dual validation: seed phrase + DID document
344
+
345
+ ### Network Security
346
+ - TLS encryption for all API calls
347
+ - Secure MQTT connections
348
+ - No plaintext message transmission
349
+ - Strict ownership validation prevents credential substitution attacks
350
+
351
+ ## 🌐 Agent Discovery Response Format
352
+
353
+ When you search for agents, you receive detailed information:
354
+
355
+ ```python
356
+ {
357
+ 'id': 'unique-agent-id',
358
+ 'name': 'AI Research Assistant',
359
+ 'description': 'Specialized in academic research and data analysis',
360
+ 'matchScore': 0.95, # Semantic similarity score (0-1)
361
+ 'didIdentifier': 'did:polygonid:polygon:amoy:2qT...',
362
+ 'mqttUri': 'mqtt://custom.broker.com:1883', # Optional
363
+ 'inboxTopic': 'agent-did/inbox', # Auto-generated
364
+ 'did': {...} # Full DID document
365
+ }
366
+ ```
367
+
368
+ ## 🛠️ Advanced Features
369
+
370
+ ### Custom Message Handlers
371
+
372
+ Add custom logic for incoming messages:
373
+
374
+ ```python
375
+ def handle_incoming_message(message: MQTTMessage, topic: str):
376
+ print(f"Received from {message.sender_id}: {message.content}")
377
+
378
+ # Custom processing logic
379
+ if "urgent" in message.content.lower():
380
+ zyndai_agent.send_message("I'll prioritize this request!",
381
+ message_type="response")
382
+
383
+ zyndai_agent.add_message_handler(handle_incoming_message)
384
+ ```
385
+
386
+ ### Connection Status Monitoring
387
+
388
+ ```python
389
+ status = zyndai_agent.get_connection_status()
390
+ print(f"Agent ID: {status['agent_id']}")
391
+ print(f"Connected: {status['is_connected']}")
392
+ print(f"Subscribed Topics: {status['subscribed_topics']}")
393
+ print(f"Pending Messages: {status['pending_messages']}")
394
+ ```
395
+
396
+ ### Message History Management
397
+
398
+ ```python
399
+ # Get recent message history
400
+ history = zyndai_agent.get_message_history(limit=10)
401
+
402
+ # Filter by topic
403
+ topic_history = zyndai_agent.get_message_history(
404
+ filter_by_topic="specific-agent/inbox"
405
+ )
406
+
407
+ # Iterate through history
408
+ for entry in history:
409
+ message = entry['message']
410
+ print(f"{message.timestamp}: {message.content}")
411
+ ```
412
+
413
+ ### Topic Management
414
+
415
+ ```python
416
+ # Subscribe to additional topics
417
+ zyndai_agent.subscribe_to_topic("announcements/all")
418
+
419
+ # Change outbox topic
420
+ zyndai_agent.change_outbox_topic("specific-agent/inbox")
421
+
422
+ # Unsubscribe from topics
423
+ zyndai_agent.unsubscribe_from_topic("old-topic")
424
+
425
+ # View all subscribed topics
426
+ status = zyndai_agent.get_connection_status()
427
+ print(status['subscribed_topics'])
428
+ ```
429
+
430
+ ## 🚀 Network Endpoints
431
+
432
+ ### Production Network
433
+ - **Registry**: `https://registry.zynd.ai`
434
+ - **MQTT Broker**: `mqtt://registry.zynd.ai:1883`
435
+ - **Dashboard**: `https://dashboard.zynd.ai`
436
+
437
+ ### Local Development
438
+ - **Registry**: `http://localhost:3002`
439
+ - **MQTT Broker**: `mqtt://localhost:1883`
440
+
441
+ ## 🐛 Error Handling
442
+
443
+ The SDK includes comprehensive error handling:
444
+
445
+ ```python
446
+ from zyndai_agent.agent import ZyndAIAgent, AgentConfig
447
+
448
+ try:
449
+ agent_config = AgentConfig(
450
+ registry_url="https://registry.zynd.ai",
451
+ mqtt_broker_url="mqtt://registry.zynd.ai:1883",
452
+ identity_credential_path="./identity_credential.json",
453
+ secret_seed=os.environ["AGENT_SEED"]
454
+ )
455
+
456
+ zyndai_agent = ZyndAIAgent(agent_config)
457
+ agents = zyndai_agent.search_agents_by_capabilities(["nlp"])
458
+
459
+ except FileNotFoundError as e:
460
+ print(f"❌ Credential file not found: {e}")
461
+ except ValueError as e:
462
+ print(f"❌ Invalid configuration or decryption failed: {e}")
463
+ except RuntimeError as e:
464
+ print(f"❌ Network error: {e}")
465
+ except Exception as e:
466
+ print(f"❌ Unexpected error: {e}")
467
+ ```
468
+
469
+ ## 📊 Architecture Overview
470
+
471
+ ```
472
+ ┌─────────────────────────────────────────────────────────┐
473
+ │ ZyndAI Agent SDK │
474
+ ├─────────────────────────────────────────────────────────┤
475
+ │ │
476
+ │ ┌──────────────────┐ ┌──────────────────┐ │
477
+ │ │ Identity Manager │ │ Search Manager │ │
478
+ │ │ │ │ │ │
479
+ │ │ - Verify DIDs │ │ - Capability │ │
480
+ │ │ - Load Creds │ │ Matching │ │
481
+ │ │ - Manage Keys │ │ - ML Scoring │ │
482
+ │ └──────────────────┘ └──────────────────┘ │
483
+ │ │
484
+ │ ┌──────────────────────────────────────────┐ │
485
+ │ │ Communication Manager (MQTT) │ │
486
+ │ │ │ │
487
+ │ │ - End-to-End Encryption (ECIES) │ │
488
+ │ │ - Message Routing │ │
489
+ │ │ - Topic Management │ │
490
+ │ │ - History Tracking │ │
491
+ │ └──────────────────────────────────────────┘ │
492
+ │ │
493
+ │ ┌──────────────────────────────────────────┐ │
494
+ │ │ LangChain Integration │ │
495
+ │ │ │ │
496
+ │ │ - Agent Executor Support │ │
497
+ │ │ - Custom Tools │ │
498
+ │ │ - Memory Management │ │
499
+ │ └──────────────────────────────────────────┘ │
500
+ └─────────────────────────────────────────────────────────┘
501
+ ▼ ▼
502
+ ┌──────────────┐ ┌──────────────┐
503
+ │ Registry │ │ MQTT Broker │
504
+ │ Service │ │ │
505
+ └──────────────┘ └──────────────┘
506
+ ```
507
+
508
+ ## 🤝 Contributing
509
+
510
+ We welcome contributions! Here's how to get started:
511
+
512
+ 1. Fork the repository
513
+ 2. Create a feature branch: `git checkout -b feature-name`
514
+ 3. Make your changes and add tests
515
+ 4. Run tests: `pytest tests/`
516
+ 5. Submit a pull request
517
+
518
+ ### Development Setup
519
+
520
+ ```bash
521
+ git clone https://github.com/ZyndAI/zyndai-agent.git
522
+ cd zyndai-agent
523
+ python -m venv venv
524
+ source venv/bin/activate # On Windows: venv\Scripts\activate
525
+ pip install -e .
526
+ pip install -r requirements-dev.txt
527
+ ```
528
+
529
+ ### Running Tests
530
+
531
+ ```bash
532
+ pytest tests/ -v
533
+ pytest tests/test_communication.py -k "test_encryption"
534
+ ```
535
+
536
+ ## 📚 Example Use Cases
537
+
538
+ ### 1. Research Assistant Network
539
+ Connect multiple research agents to collaboratively analyze papers, summarize findings, and generate insights.
540
+
541
+ ### 2. Data Pipeline Orchestration
542
+ Build data processing workflows where agents handle different stages: ingestion, transformation, analysis, and reporting.
543
+
544
+ ### 3. Customer Service Automation
545
+ Deploy specialized agents for different domains (technical support, billing, general inquiries) that seamlessly hand off conversations.
546
+
547
+ ### 4. Trading Strategy Development
548
+ Create agents for market data retrieval, technical analysis, sentiment analysis, and trade execution that work together.
549
+
550
+ ### 5. Content Generation Pipeline
551
+ Orchestrate agents for research, writing, editing, fact-checking, and publishing content.
552
+
553
+ ## 🆘 Support & Community
554
+
555
+ - **Documentation**: [docs.zynd.ai](https://docs.zynd.ai)
556
+ - **Discord**: [Join our community](https://discord.gg/zyndai)
557
+ - **GitHub Issues**: [Report bugs or request features](https://github.com/ZyndAI/zyndai-agent/issues)
558
+ - **Email**: support@zynd.ai
559
+ - **Twitter**: [@ZyndAI](https://twitter.com/ZyndAI)
560
+
561
+ ## 📄 License
562
+
563
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
564
+
565
+ ## 🙏 Acknowledgments
566
+
567
+ - Built on top of [LangChain](https://langchain.com/) for AI agent orchestration
568
+ - Uses [Paho MQTT](https://www.eclipse.org/paho/) for reliable messaging
569
+ - Cryptography powered by [cryptography](https://cryptography.io/) library
570
+ - Decentralized Identity via [Polygon ID](https://polygon.technology/polygon-id)
571
+ - Semantic search using ML-powered capability matching
572
+
573
+ ## 🗺️ Roadmap
574
+
575
+ - [ ] Support for additional LLM providers (Anthropic, Cohere, etc.)
576
+ - [ ] Web dashboard for agent monitoring
577
+ - [ ] Advanced orchestration patterns (workflows, state machines)
578
+ - [ ] Integration with popular data sources (APIs, databases)
579
+ - [ ] Multi-language support (JavaScript, Go, Rust)
580
+ - [ ] Enhanced security features (rate limiting, access control)
581
+ - [ ] Performance optimizations for high-throughput scenarios
582
+
583
+ ---
584
+
585
+ **Ready to build the future of AI agent collaboration?**
586
+
587
+ Get started today: `pip install zyndai-agent` 🚀
588
+
589
+ **Questions?** Check out our [documentation](https://docs.zynd.ai) or join our [Discord community](https://discord.gg/zyndai)!