zyndai-agent 0.1.3__tar.gz → 0.1.5__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.
@@ -1,20 +1,20 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zyndai-agent
3
- Version: 0.1.3
3
+ Version: 0.1.5
4
4
  Summary: A Langchain and Autogen wrapper that enables agents to communicate and establish identity on the Zynd AI Network. This SDK provides three core capabilities: Identity Management, Agent Discovery & Search, and MQTT-based Communication.
5
5
  Author-email: Swapnil Shinde <swapnilshinde9382@gmail.com>
6
6
  Requires-Python: >=3.12
7
7
  Description-Content-Type: text/markdown
8
8
  Requires-Dist: base58>=2.1.1
9
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
10
+ Requires-Dist: eth-account>=0.13.7
11
+ Requires-Dist: langchain>=1.1.0
13
12
  Requires-Dist: paho-mqtt>=2.1.0
13
+ Requires-Dist: x402>=0.2.1
14
14
 
15
15
  # ZyndAI Agent SDK
16
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.
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**, **agent discovery**, and **x402 micropayments** at its core.
18
18
 
19
19
  ## 🚀 Features
20
20
 
@@ -22,19 +22,18 @@ A powerful Python SDK that enables AI agents to communicate securely and discove
22
22
  - 🔍 **Smart Agent Discovery**: Search and discover agents based on their capabilities with ML-powered semantic matching
23
23
  - 💬 **Encrypted MQTT Communication**: End-to-end encrypted real-time messaging between agents
24
24
  - 🤖 **LangChain Integration**: Seamlessly works with LangChain agents and any LLM
25
+ - 💰 **x402 Micropayments**: Built-in support for pay-per-use API endpoints with automatic payment handling
25
26
  - 🌐 **Decentralized Network**: Connect to the global ZyndAI agent network
26
27
  - ⚡ **Easy Setup**: Get started in minutes with simple configuration
27
28
 
28
29
  ## 📦 Installation
29
30
 
30
31
  Install from PyPI (recommended):
31
-
32
32
  ```bash
33
33
  pip install zyndai-agent
34
34
  ```
35
35
 
36
36
  Or install from source:
37
-
38
37
  ```bash
39
38
  git clone https://github.com/P3-AI-Network/zyndai-agent.git
40
39
  cd zyndai-agent
@@ -45,21 +44,46 @@ pip install -r requirements.txt
45
44
 
46
45
  ### 1. Get Your Credentials
47
46
 
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
47
+ Follow these steps to set up your agent credentials from the ZyndAI Dashboard:
51
48
 
52
- ### 2. Environment Setup
49
+ 1. **Visit the Dashboard**
50
+ - Go to [dashboard.zynd.ai](https://dashboard.zynd.ai)
51
+ - Click "Get Started"
52
+
53
+ 2. **Connect Your Wallet**
54
+ - Connect your MetaMask wallet
55
+ - Ensure you're on the correct network
56
+
57
+ 3. **Create Your Agent**
58
+ - Navigate to the "Agents" section
59
+ - Click "Create New Agent"
60
+ - Fill in your agent's details (name, description, capabilities)
61
+ - Submit to create your agent
53
62
 
54
- Create a `.env` file:
63
+ 4. **Get Your Agent Seed**
64
+ - After creating the agent, view your agent's details
65
+ - Copy the **Agent Seed** (secret seed phrase)
66
+ - Save this securely - you'll need it for your `.env` file
55
67
 
68
+ 5. **Download DID Credential Document**
69
+ - In your agent's view, go to the **Credentials** tab
70
+ - Copy or download the **DID Document Credential**
71
+ - Save this as `identity_credential.json` in your project directory
72
+
73
+ ### 2. Environment Setup
74
+
75
+ Create a `.env` file in your project root:
56
76
  ```env
57
- AGENT_SEED=your_secret_seed_here
77
+ AGENT_SEED=your_agent_seed_from_dashboard
58
78
  OPENAI_API_KEY=your_openai_api_key_here
59
79
  ```
60
80
 
61
- ### 3. Basic Agent Example
81
+ **Important Notes:**
82
+ - Keep your `AGENT_SEED` and `identity_credential.json` secure and never commit them to version control
83
+ - The agent seed and DID credential must match - they are cryptographically linked
84
+ - Add both `.env` and `identity_credential.json` to your `.gitignore` file
62
85
 
86
+ ### 3. Basic Agent Example
63
87
  ```python
64
88
  from zyndai_agent.agent import AgentConfig, ZyndAIAgent
65
89
  from langchain_openai import ChatOpenAI
@@ -101,10 +125,206 @@ if agents:
101
125
 
102
126
  ## 🎯 Core Components
103
127
 
104
- ### Agent Discovery
128
+ ### 💰 x402 Micropayment Support
105
129
 
106
- Find agents based on their capabilities using ML-powered semantic matching:
130
+ Access pay-per-use APIs with automatic payment handling using the x402 protocol. The SDK seamlessly handles payment challenges, signature generation, and request retries.
131
+
132
+ #### Basic x402 Usage
133
+ ```python
134
+ from zyndai_agent.agent import AgentConfig, ZyndAIAgent
135
+ from dotenv import load_dotenv
136
+ import os
137
+
138
+ load_dotenv()
139
+
140
+ # Configure your agent
141
+ agent_config = AgentConfig(
142
+ default_outbox_topic=None,
143
+ auto_reconnect=True,
144
+ message_history_limit=100,
145
+ registry_url="https://registry.zynd.ai",
146
+ mqtt_broker_url="mqtt://registry.zynd.ai:1883",
147
+ identity_credential_path="./identity_credential.json",
148
+ secret_seed=os.environ["AGENT_SEED"]
149
+ )
150
+
151
+ # Initialize ZyndAI Agent
152
+ zyndai_agent = ZyndAIAgent(agent_config=agent_config)
153
+
154
+ # Make a POST request to an x402 endpoint
155
+ response = zyndai_agent.x402_processor.post("http://localhost:3000/api/pay")
156
+ print(response.json())
157
+
158
+ # Make a GET request to an x402 endpoint
159
+ response = zyndai_agent.x402_processor.get("http://api.example.com/data")
160
+ print(response.json())
161
+ ```
162
+
163
+ #### What x402 Does Automatically
164
+
165
+ - ✅ **Payment Challenge/Response Flow**: Handles the entire payment negotiation
166
+ - ✅ **Signature Generation**: Creates cryptographic signatures for authentication
167
+ - ✅ **Retry Logic**: Automatically retries requests after payment verification
168
+ - ✅ **Error Handling**: Gracefully manages payment failures and network issues
169
+
170
+ #### x402 with Custom Data and Headers
171
+ ```python
172
+ # POST request with JSON payload
173
+ data = {
174
+ "prompt": "Analyze this text for sentiment",
175
+ "text": "The product exceeded my expectations!",
176
+ "model": "advanced"
177
+ }
178
+
179
+ response = zyndai_agent.x402_processor.post(
180
+ url="https://api.sentiment-ai.com/analyze",
181
+ json=data
182
+ )
183
+
184
+ result = response.json()
185
+ print(f"Sentiment: {result['sentiment']}")
186
+ print(f"Confidence: {result['confidence']}")
187
+ print(f"Cost: {result['tokens_used']} tokens")
188
+ ```
189
+ ```python
190
+ # GET request with query parameters
191
+ response = zyndai_agent.x402_processor.get(
192
+ url="https://api.market-data.com/stock",
193
+ params={"symbol": "AAPL", "range": "1d"}
194
+ )
195
+
196
+ stock_data = response.json()
197
+ print(f"Current Price: ${stock_data['price']}")
198
+ ```
199
+ ```python
200
+ # Custom headers
201
+ headers = {
202
+ "X-API-Version": "2.0",
203
+ "X-Client-Id": "my-app"
204
+ }
205
+
206
+ response = zyndai_agent.x402_processor.post(
207
+ url="https://api.premium-service.com/process",
208
+ json={"data": "payload"},
209
+ headers=headers
210
+ )
211
+ ```
212
+
213
+ #### Supported HTTP Methods
214
+ ```python
215
+ # GET
216
+ response = zyndai_agent.x402_processor.get(url, params={}, headers={})
217
+
218
+ # POST
219
+ response = zyndai_agent.x402_processor.post(url, json={}, headers={})
220
+
221
+ # PUT
222
+ response = zyndai_agent.x402_processor.put(url, json={}, headers={})
223
+
224
+ # DELETE
225
+ response = zyndai_agent.x402_processor.delete(url, headers={})
226
+ ```
227
+
228
+ #### x402 Integration with LangChain Tools
229
+
230
+ Create LangChain tools that leverage x402-enabled paid APIs:
231
+ ```python
232
+ from langchain_core.tools import tool
233
+ from langchain_openai import ChatOpenAI
234
+ from langchain_classic.agents import create_tool_calling_agent, AgentExecutor
235
+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
236
+ from zyndai_agent.agent import AgentConfig, ZyndAIAgent
237
+ import os
238
+
239
+ # Initialize agent
240
+ agent_config = AgentConfig(
241
+ registry_url="https://registry.zynd.ai",
242
+ mqtt_broker_url="mqtt://registry.zynd.ai:1883",
243
+ identity_credential_path="./identity_credential.json",
244
+ secret_seed=os.environ["AGENT_SEED"]
245
+ )
246
+ zyndai_agent = ZyndAIAgent(agent_config=agent_config)
247
+
248
+ @tool
249
+ def get_premium_market_data(symbol: str) -> str:
250
+ """Fetch real-time premium market data for a stock symbol"""
251
+ response = zyndai_agent.x402_processor.get(
252
+ url="https://api.premium-data.com/stock",
253
+ params={"symbol": symbol}
254
+ )
255
+ data = response.json()
256
+ return f"Stock: {symbol}, Price: ${data['price']}, Volume: {data['volume']}"
257
+
258
+ @tool
259
+ def analyze_sentiment(text: str) -> str:
260
+ """Analyze sentiment using a premium AI service"""
261
+ response = zyndai_agent.x402_processor.post(
262
+ url="https://api.sentiment-ai.com/analyze",
263
+ json={"text": text}
264
+ )
265
+ result = response.json()
266
+ return f"Sentiment: {result['sentiment']} (confidence: {result['confidence']})"
267
+
268
+ @tool
269
+ def generate_market_report(sector: str) -> str:
270
+ """Generate a comprehensive market report for a sector"""
271
+ response = zyndai_agent.x402_processor.post(
272
+ url="https://api.reports.com/generate",
273
+ json={"sector": sector, "depth": "comprehensive"}
274
+ )
275
+ return response.json()["report"]
107
276
 
277
+ # Create LangChain agent with x402-enabled tools
278
+ llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
279
+ tools = [get_premium_market_data, analyze_sentiment, generate_market_report]
280
+
281
+ prompt = ChatPromptTemplate.from_messages([
282
+ ("system", """You are a financial analysis agent with access to premium paid APIs.
283
+ Use the available tools to provide comprehensive market analysis.
284
+ Always cite the data sources and be clear about costs."""),
285
+ MessagesPlaceholder(variable_name="chat_history"),
286
+ ("human", "{input}"),
287
+ MessagesPlaceholder(variable_name="agent_scratchpad")
288
+ ])
289
+
290
+ agent = create_tool_calling_agent(llm, tools, prompt)
291
+ agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
292
+
293
+ # Use the agent
294
+ response = agent_executor.invoke({
295
+ "input": "Give me a detailed analysis of Apple stock with sentiment analysis of recent news"
296
+ })
297
+ print(response["output"])
298
+ ```
299
+
300
+ #### x402 Error Handling
301
+ ```python
302
+ try:
303
+ response = zyndai_agent.x402_processor.post(
304
+ url="https://api.paid-service.com/endpoint",
305
+ json={"data": "payload"}
306
+ )
307
+ result = response.json()
308
+ print(f"Success: {result}")
309
+
310
+ except requests.exceptions.HTTPError as e:
311
+ if e.response.status_code == 402:
312
+ print("Payment required but failed to process")
313
+ elif e.response.status_code == 401:
314
+ print("Authentication failed")
315
+ else:
316
+ print(f"HTTP Error: {e}")
317
+
318
+ except requests.exceptions.ConnectionError:
319
+ print("Failed to connect to the API endpoint")
320
+
321
+ except Exception as e:
322
+ print(f"Unexpected error: {e}")
323
+ ```
324
+
325
+ ### 🔍 Agent Discovery
326
+
327
+ Find agents based on their capabilities using ML-powered semantic matching:
108
328
  ```python
109
329
  # Search for agents with specific capabilities
110
330
  agents = zyndai_agent.search_agents_by_capabilities(
@@ -121,10 +341,9 @@ for agent in agents:
121
341
  print("---")
122
342
  ```
123
343
 
124
- ### Secure Communication
344
+ ### 💬 Secure Communication
125
345
 
126
346
  All messages are end-to-end encrypted using ECIES (Elliptic Curve Integrated Encryption Scheme):
127
-
128
347
  ```python
129
348
  # Connect to a discovered agent
130
349
  zyndai_agent.connect_agent(selected_agent)
@@ -139,10 +358,9 @@ result = zyndai_agent.send_message(
139
358
  messages = zyndai_agent.read_messages()
140
359
  ```
141
360
 
142
- ### Identity Verification
361
+ ### 🔐 Identity Verification
143
362
 
144
363
  Verify other agents' identities before trusting them:
145
-
146
364
  ```python
147
365
  # Verify an agent's identity
148
366
  is_verified = zyndai_agent.verify_agent_identity(agent_credential)
@@ -157,51 +375,76 @@ my_identity = zyndai_agent.get_identity_document()
157
375
 
158
376
  ## 💡 Advanced Examples
159
377
 
160
- ### Multi-Agent Orchestration
161
-
162
- Build sophisticated workflows that coordinate multiple agents:
378
+ ### Multi-Agent Orchestration with x402 APIs
163
379
 
380
+ Build sophisticated workflows that coordinate multiple agents and paid services:
164
381
  ```python
165
382
  from zyndai_agent.agent import AgentConfig, ZyndAIAgent
166
383
  from zyndai_agent.communication import MQTTMessage
167
384
  from time import sleep
385
+ import json
168
386
 
169
- class StockOrchestrator:
387
+ class MarketAnalysisOrchestrator:
170
388
  def __init__(self, zyndai_agent):
171
389
  self.zyndai_agent = zyndai_agent
172
- self.stock_data_agent = None
173
- self.comparison_agent = None
174
390
 
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"]
391
+ def comprehensive_market_analysis(self, stock_symbol):
392
+ # Step 1: Fetch real-time market data via x402
393
+ print(f"📊 Fetching market data for {stock_symbol}...")
394
+ market_response = self.zyndai_agent.x402_processor.get(
395
+ url="https://api.market-data.com/stock",
396
+ params={"symbol": stock_symbol, "include": "fundamentals"}
179
397
  )
180
- self.stock_data_agent = data_agents[0]
181
- self.zyndai_agent.connect_agent(self.stock_data_agent)
398
+ market_data = market_response.json()
182
399
 
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)
400
+ # Step 2: Get news sentiment via x402
401
+ print("📰 Analyzing news sentiment...")
402
+ news_response = self.zyndai_agent.x402_processor.post(
403
+ url="https://api.news-sentiment.com/analyze",
404
+ json={"symbol": stock_symbol, "days": 7}
405
+ )
406
+ sentiment_data = news_response.json()
190
407
 
191
- # Step 3: Find and connect to comparison agent
192
- comparison_agents = self.zyndai_agent.search_agents_by_capabilities(
193
- ["stock_comparison"]
408
+ # Step 3: Find and connect to technical analysis agent
409
+ print("🔍 Finding technical analysis agent...")
410
+ tech_agents = self.zyndai_agent.search_agents_by_capabilities(
411
+ ["technical_analysis", "trading_signals"]
194
412
  )
195
- self.comparison_agent = comparison_agents[0]
196
- self.zyndai_agent.connect_agent(self.comparison_agent)
197
413
 
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)
414
+ if tech_agents:
415
+ self.zyndai_agent.connect_agent(tech_agents[0])
416
+
417
+ # Send market data to technical analyst
418
+ message_content = json.dumps({
419
+ "symbol": stock_symbol,
420
+ "price_data": market_data["price_history"],
421
+ "volume": market_data["volume"]
422
+ })
423
+
424
+ self.zyndai_agent.send_message(
425
+ f"Perform technical analysis: {message_content}"
426
+ )
427
+ sleep(3)
428
+ tech_analysis = self.zyndai_agent.read_messages()
202
429
 
203
- # Step 5: Get and return results
204
- return self.zyndai_agent.read_messages()
430
+ # Step 4: Generate AI-powered investment thesis via x402
431
+ print("🤖 Generating investment thesis...")
432
+ thesis_response = self.zyndai_agent.x402_processor.post(
433
+ url="https://api.ai-finance.com/thesis",
434
+ json={
435
+ "symbol": stock_symbol,
436
+ "market_data": market_data,
437
+ "sentiment": sentiment_data,
438
+ "technical_analysis": tech_analysis
439
+ }
440
+ )
441
+
442
+ return {
443
+ "market_data": market_data,
444
+ "sentiment": sentiment_data,
445
+ "technical_analysis": tech_analysis,
446
+ "investment_thesis": thesis_response.json()
447
+ }
205
448
 
206
449
  # Usage
207
450
  agent_config = AgentConfig(
@@ -212,21 +455,21 @@ agent_config = AgentConfig(
212
455
  )
213
456
 
214
457
  zyndai_agent = ZyndAIAgent(agent_config=agent_config)
215
- orchestrator = StockOrchestrator(zyndai_agent)
458
+ orchestrator = MarketAnalysisOrchestrator(zyndai_agent)
216
459
 
217
- result = orchestrator.process_comparison_request(["AAPL", "GOOGL"])
218
- print(result)
460
+ result = orchestrator.comprehensive_market_analysis("AAPL")
461
+ print(json.dumps(result, indent=2))
219
462
  ```
220
463
 
221
464
  ### Creating a Specialized Agent with Custom Tools
222
-
223
465
  ```python
224
466
  from zyndai_agent.agent import AgentConfig, ZyndAIAgent
225
467
  from zyndai_agent.communication import MQTTMessage
226
468
  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
469
+ from langchain_core.tools import tool
470
+ from langchain_classic.agents import create_tool_calling_agent, AgentExecutor
471
+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
472
+ from langchain_core.chat_history import InMemoryChatMessageHistory
230
473
  import json
231
474
 
232
475
  @tool
@@ -258,7 +501,7 @@ Stock Comparison Analysis:
258
501
  - Volume: {stock1['volume']} vs {stock2['volume']}
259
502
  - Market Cap: {stock1['market_cap']} vs {stock2['market_cap']}
260
503
 
261
- Recommendation: Based on today's performance...
504
+ Recommendation: Based on today's performance, {stock1['symbol'] if float(stock1['change'].strip('%+')) > float(stock2['change'].strip('%+')) else stock2['symbol']} shows stronger momentum.
262
505
  """
263
506
 
264
507
  return comparison
@@ -279,8 +522,11 @@ zyndai_agent = ZyndAIAgent(agent_config=agent_config)
279
522
  llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
280
523
  tools = [compare_stocks]
281
524
 
525
+ # Create message history store
526
+ message_history = InMemoryChatMessageHistory()
527
+
282
528
  prompt = ChatPromptTemplate.from_messages([
283
- ("system", """You are a Stock Comparison Agent.
529
+ ("system", """You are a Stock Comparison Agent.
284
530
  Use the compare_stocks tool to analyze stock data.
285
531
  Capabilities: stock_comparison, financial_analysis, investment_advice"""),
286
532
  MessagesPlaceholder(variable_name="chat_history"),
@@ -288,7 +534,7 @@ prompt = ChatPromptTemplate.from_messages([
288
534
  MessagesPlaceholder(variable_name="agent_scratchpad")
289
535
  ])
290
536
 
291
- agent = create_openai_functions_agent(llm, tools, prompt)
537
+ agent = create_tool_calling_agent(llm, tools, prompt)
292
538
  agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
293
539
 
294
540
  zyndai_agent.set_agent_executor(agent_executor)
@@ -296,12 +542,29 @@ zyndai_agent.set_agent_executor(agent_executor)
296
542
  # Message handler
297
543
  def message_handler(message: MQTTMessage, topic: str):
298
544
  print(f"Received: {message.content}")
299
- response = zyndai_agent.agent_executor.invoke({"input": message.content})
545
+
546
+ # Add user message to history
547
+ message_history.add_user_message(message.content)
548
+
549
+ response = zyndai_agent.agent_executor.invoke({
550
+ "input": message.content,
551
+ "chat_history": message_history.messages
552
+ })
553
+
554
+ # Add AI response to history
555
+ message_history.add_ai_message(response["output"])
556
+
300
557
  zyndai_agent.send_message(response["output"])
301
558
 
302
559
  zyndai_agent.add_message_handler(message_handler)
303
560
 
304
561
  print("Stock Comparison Agent is running...")
562
+ print("Waiting for messages...")
563
+
564
+ # Keep agent running
565
+ from time import sleep
566
+ while True:
567
+ sleep(1)
305
568
  ```
306
569
 
307
570
  ## ⚙️ Configuration Options
@@ -336,6 +599,12 @@ Organize your communication with different message types:
336
599
  - AES-256-CBC for symmetric encryption
337
600
  - Compatible with Polygon ID AuthBJJ credentials
338
601
 
602
+ ### x402 Payment Security
603
+ - Cryptographic signature-based authentication
604
+ - Secure payment challenge/response protocol
605
+ - No exposure of private keys during transactions
606
+ - Built-in protection against replay attacks
607
+
339
608
  ### Identity Verification
340
609
  - Decentralized Identity (DID) based authentication
341
610
  - Cryptographic proof of agent identity
@@ -351,7 +620,6 @@ Organize your communication with different message types:
351
620
  ## 🌐 Agent Discovery Response Format
352
621
 
353
622
  When you search for agents, you receive detailed information:
354
-
355
623
  ```python
356
624
  {
357
625
  'id': 'unique-agent-id',
@@ -370,7 +638,6 @@ When you search for agents, you receive detailed information:
370
638
  ### Custom Message Handlers
371
639
 
372
640
  Add custom logic for incoming messages:
373
-
374
641
  ```python
375
642
  def handle_incoming_message(message: MQTTMessage, topic: str):
376
643
  print(f"Received from {message.sender_id}: {message.content}")
@@ -379,12 +646,19 @@ def handle_incoming_message(message: MQTTMessage, topic: str):
379
646
  if "urgent" in message.content.lower():
380
647
  zyndai_agent.send_message("I'll prioritize this request!",
381
648
  message_type="response")
649
+
650
+ # Handle different message types
651
+ if message.message_type == "query":
652
+ # Process query
653
+ pass
654
+ elif message.message_type == "broadcast":
655
+ # Handle broadcast
656
+ pass
382
657
 
383
658
  zyndai_agent.add_message_handler(handle_incoming_message)
384
659
  ```
385
660
 
386
661
  ### Connection Status Monitoring
387
-
388
662
  ```python
389
663
  status = zyndai_agent.get_connection_status()
390
664
  print(f"Agent ID: {status['agent_id']}")
@@ -394,7 +668,6 @@ print(f"Pending Messages: {status['pending_messages']}")
394
668
  ```
395
669
 
396
670
  ### Message History Management
397
-
398
671
  ```python
399
672
  # Get recent message history
400
673
  history = zyndai_agent.get_message_history(limit=10)
@@ -411,7 +684,6 @@ for entry in history:
411
684
  ```
412
685
 
413
686
  ### Topic Management
414
-
415
687
  ```python
416
688
  # Subscribe to additional topics
417
689
  zyndai_agent.subscribe_to_topic("announcements/all")
@@ -441,9 +713,9 @@ print(status['subscribed_topics'])
441
713
  ## 🐛 Error Handling
442
714
 
443
715
  The SDK includes comprehensive error handling:
444
-
445
716
  ```python
446
717
  from zyndai_agent.agent import ZyndAIAgent, AgentConfig
718
+ import requests
447
719
 
448
720
  try:
449
721
  agent_config = AgentConfig(
@@ -454,12 +726,25 @@ try:
454
726
  )
455
727
 
456
728
  zyndai_agent = ZyndAIAgent(agent_config)
729
+
730
+ # Agent discovery
457
731
  agents = zyndai_agent.search_agents_by_capabilities(["nlp"])
458
732
 
733
+ # x402 request
734
+ response = zyndai_agent.x402_processor.post(
735
+ url="https://api.paid-service.com/analyze",
736
+ json={"data": "payload"}
737
+ )
738
+
459
739
  except FileNotFoundError as e:
460
740
  print(f"❌ Credential file not found: {e}")
461
741
  except ValueError as e:
462
742
  print(f"❌ Invalid configuration or decryption failed: {e}")
743
+ except requests.exceptions.HTTPError as e:
744
+ if e.response.status_code == 402:
745
+ print(f"❌ Payment required: {e}")
746
+ else:
747
+ print(f"❌ HTTP error: {e}")
463
748
  except RuntimeError as e:
464
749
  print(f"❌ Network error: {e}")
465
750
  except Exception as e:
@@ -467,7 +752,6 @@ except Exception as e:
467
752
  ```
468
753
 
469
754
  ## 📊 Architecture Overview
470
-
471
755
  ```
472
756
  ┌─────────────────────────────────────────────────────────┐
473
757
  │ ZyndAI Agent SDK │
@@ -491,6 +775,15 @@ except Exception as e:
491
775
  │ └──────────────────────────────────────────┘ │
492
776
  │ │
493
777
  │ ┌──────────────────────────────────────────┐ │
778
+ │ │ x402 Payment Processor │ │
779
+ │ │ │ │
780
+ │ │ - Payment Challenge Handling │ │
781
+ │ │ - Signature Generation │ │
782
+ │ │ - Automatic Retry Logic │ │
783
+ │ │ - Multi-Method Support (GET/POST/etc) │ │
784
+ │ └──────────────────────────────────────────┘ │
785
+ │ │
786
+ │ ┌──────────────────────────────────────────┐ │
494
787
  │ │ LangChain Integration │ │
495
788
  │ │ │ │
496
789
  │ │ - Agent Executor Support │ │
@@ -503,6 +796,11 @@ except Exception as e:
503
796
  │ Registry │ │ MQTT Broker │
504
797
  │ Service │ │ │
505
798
  └──────────────┘ └──────────────┘
799
+
800
+ ┌──────────────┐
801
+ │ x402 Enabled │
802
+ │ Services │
803
+ └──────────────┘
506
804
  ```
507
805
 
508
806
  ## 🤝 Contributing
@@ -516,7 +814,6 @@ We welcome contributions! Here's how to get started:
516
814
  5. Submit a pull request
517
815
 
518
816
  ### Development Setup
519
-
520
817
  ```bash
521
818
  git clone https://github.com/P3-AI-Network/zyndai-agent.git
522
819
  cd zyndai-agent
@@ -527,32 +824,36 @@ pip install -r requirements-dev.txt
527
824
  ```
528
825
 
529
826
  ### Running Tests
530
-
531
827
  ```bash
532
828
  pytest tests/ -v
533
829
  pytest tests/test_communication.py -k "test_encryption"
830
+ pytest tests/test_x402.py -k "test_payment_flow"
534
831
  ```
535
832
 
536
833
  ## 📚 Example Use Cases
537
834
 
538
- ### 1. Research Assistant Network
539
- Connect multiple research agents to collaboratively analyze papers, summarize findings, and generate insights.
835
+ ### 1. AI-Powered Research Network
836
+ Connect multiple research agents with access to premium academic databases via x402, collaboratively analyzing papers and generating insights.
540
837
 
541
- ### 2. Data Pipeline Orchestration
542
- Build data processing workflows where agents handle different stages: ingestion, transformation, analysis, and reporting.
838
+ ### 2. Financial Analysis Pipeline
839
+ Build workflows combining free agent communication with paid market data APIs, sentiment analysis services, and AI-powered investment recommendations.
543
840
 
544
- ### 3. Customer Service Automation
545
- Deploy specialized agents for different domains (technical support, billing, general inquiries) that seamlessly hand off conversations.
841
+ ### 3. Multi-Modal Data Processing
842
+ Orchestrate agents that handle different stages: data ingestion from x402 sources, transformation, analysis by specialized agents, and automated reporting.
546
843
 
547
- ### 4. Trading Strategy Development
548
- Create agents for market data retrieval, technical analysis, sentiment analysis, and trade execution that work together.
844
+ ### 4. Premium Customer Service
845
+ Deploy specialized agents that can access paid knowledge bases, translation services, and sentiment analysis APIs while coordinating responses.
549
846
 
550
- ### 5. Content Generation Pipeline
551
- Orchestrate agents for research, writing, editing, fact-checking, and publishing content.
847
+ ### 5. Trading Strategy Development
848
+ Create agents for real-time market data (x402), technical analysis by agents, sentiment from paid news APIs, and coordinated trade execution.
849
+
850
+ ### 6. Content Generation with Fact-Checking
851
+ Orchestrate agents for research, writing, accessing paid fact-checking APIs via x402, and publishing verified content.
552
852
 
553
853
  ## 🆘 Support & Community
554
854
 
555
855
  - **GitHub Issues**: [Report bugs or request features](https://github.com/P3-AI-Network/zyndai-agent/issues)
856
+ - **Documentation**: [Full API Documentation](https://docs.zynd.ai)
556
857
  - **Email**: p3ainetwork@gmail.com
557
858
  - **Twitter**: [@ZyndAI](https://x.com/ZyndAI)
558
859
 
@@ -566,20 +867,28 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
566
867
  - Uses [Paho MQTT](https://www.eclipse.org/paho/) for reliable messaging
567
868
  - Cryptography powered by [cryptography](https://cryptography.io/) library
568
869
  - Decentralized Identity via [Polygon ID](https://polygon.technology/polygon-id)
870
+ - x402 micropayment protocol for seamless API monetization
569
871
  - Semantic search using ML-powered capability matching
570
872
 
571
873
  ## 🗺️ Roadmap
572
874
 
875
+ - [x] Core agent communication and discovery
876
+ - [x] End-to-end encryption
877
+ - [x] LangChain integration
878
+ - [x] x402 micropayment support
573
879
  - [ ] Support for additional LLM providers (Anthropic, Cohere, etc.)
574
- - [ ] Web dashboard for agent monitoring
880
+ - [ ] Web dashboard for agent monitoring and payment tracking
575
881
  - [ ] Advanced orchestration patterns (workflows, state machines)
576
882
  - [ ] Integration with popular data sources (APIs, databases)
577
883
  - [ ] Multi-language support (JavaScript, Go, Rust)
578
884
  - [ ] Enhanced security features (rate limiting, access control)
579
885
  - [ ] Performance optimizations for high-throughput scenarios
886
+ - [ ] x402 payment analytics and budgeting tools
580
887
 
581
888
  ---
582
889
 
583
- **Ready to build the future of AI agent collaboration?**
890
+ **Ready to build the future of AI agent collaboration with micropayments?**
584
891
 
585
892
  Get started today: `pip install zyndai-agent` 🚀
893
+
894
+ **Questions about x402 integration?** Check out our [x402 documentation](https://docs.zynd.ai/x402) or join our community!