zyndai-agent 0.1.3__tar.gz → 0.1.4__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.
- {zyndai_agent-0.1.3 → zyndai_agent-0.1.4}/PKG-INFO +345 -74
- {zyndai_agent-0.1.3 → zyndai_agent-0.1.4}/README.md +341 -72
- {zyndai_agent-0.1.3 → zyndai_agent-0.1.4}/pyproject.toml +4 -2
- {zyndai_agent-0.1.3 → zyndai_agent-0.1.4}/zyndai_agent/agent.py +8 -6
- {zyndai_agent-0.1.3 → zyndai_agent-0.1.4}/zyndai_agent/communication.py +0 -1
- {zyndai_agent-0.1.3 → zyndai_agent-0.1.4}/zyndai_agent/identity.py +0 -5
- zyndai_agent-0.1.4/zyndai_agent/payment.py +173 -0
- {zyndai_agent-0.1.3 → zyndai_agent-0.1.4}/zyndai_agent/utils.py +19 -1
- {zyndai_agent-0.1.3 → zyndai_agent-0.1.4}/zyndai_agent.egg-info/PKG-INFO +345 -74
- {zyndai_agent-0.1.3 → zyndai_agent-0.1.4}/zyndai_agent.egg-info/SOURCES.txt +1 -0
- {zyndai_agent-0.1.3 → zyndai_agent-0.1.4}/zyndai_agent.egg-info/requires.txt +3 -1
- {zyndai_agent-0.1.3 → zyndai_agent-0.1.4}/setup.cfg +0 -0
- {zyndai_agent-0.1.3 → zyndai_agent-0.1.4}/zyndai_agent/__init__.py +0 -0
- {zyndai_agent-0.1.3 → zyndai_agent-0.1.4}/zyndai_agent/search.py +0 -0
- {zyndai_agent-0.1.3 → zyndai_agent-0.1.4}/zyndai_agent.egg-info/dependency_links.txt +0 -0
- {zyndai_agent-0.1.3 → zyndai_agent-0.1.4}/zyndai_agent.egg-info/top_level.txt +0 -0
|
@@ -1,20 +1,22 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: zyndai-agent
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.4
|
|
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:
|
|
10
|
+
Requires-Dist: eth-account>=0.13.7
|
|
11
|
+
Requires-Dist: langchain<1.0.4
|
|
11
12
|
Requires-Dist: langchain-core>=1.0.3
|
|
12
13
|
Requires-Dist: langchain-openai>=1.0.2
|
|
13
14
|
Requires-Dist: paho-mqtt>=2.1.0
|
|
15
|
+
Requires-Dist: x402>=0.2.1
|
|
14
16
|
|
|
15
17
|
# ZyndAI Agent SDK
|
|
16
18
|
|
|
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**,
|
|
19
|
+
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
20
|
|
|
19
21
|
## 🚀 Features
|
|
20
22
|
|
|
@@ -22,19 +24,18 @@ A powerful Python SDK that enables AI agents to communicate securely and discove
|
|
|
22
24
|
- 🔍 **Smart Agent Discovery**: Search and discover agents based on their capabilities with ML-powered semantic matching
|
|
23
25
|
- 💬 **Encrypted MQTT Communication**: End-to-end encrypted real-time messaging between agents
|
|
24
26
|
- 🤖 **LangChain Integration**: Seamlessly works with LangChain agents and any LLM
|
|
27
|
+
- 💰 **x402 Micropayments**: Built-in support for pay-per-use API endpoints with automatic payment handling
|
|
25
28
|
- 🌐 **Decentralized Network**: Connect to the global ZyndAI agent network
|
|
26
29
|
- ⚡ **Easy Setup**: Get started in minutes with simple configuration
|
|
27
30
|
|
|
28
31
|
## 📦 Installation
|
|
29
32
|
|
|
30
33
|
Install from PyPI (recommended):
|
|
31
|
-
|
|
32
34
|
```bash
|
|
33
35
|
pip install zyndai-agent
|
|
34
36
|
```
|
|
35
37
|
|
|
36
38
|
Or install from source:
|
|
37
|
-
|
|
38
39
|
```bash
|
|
39
40
|
git clone https://github.com/P3-AI-Network/zyndai-agent.git
|
|
40
41
|
cd zyndai-agent
|
|
@@ -52,14 +53,12 @@ pip install -r requirements.txt
|
|
|
52
53
|
### 2. Environment Setup
|
|
53
54
|
|
|
54
55
|
Create a `.env` file:
|
|
55
|
-
|
|
56
56
|
```env
|
|
57
57
|
AGENT_SEED=your_secret_seed_here
|
|
58
58
|
OPENAI_API_KEY=your_openai_api_key_here
|
|
59
59
|
```
|
|
60
60
|
|
|
61
61
|
### 3. Basic Agent Example
|
|
62
|
-
|
|
63
62
|
```python
|
|
64
63
|
from zyndai_agent.agent import AgentConfig, ZyndAIAgent
|
|
65
64
|
from langchain_openai import ChatOpenAI
|
|
@@ -101,10 +100,206 @@ if agents:
|
|
|
101
100
|
|
|
102
101
|
## 🎯 Core Components
|
|
103
102
|
|
|
104
|
-
###
|
|
103
|
+
### 💰 x402 Micropayment Support
|
|
105
104
|
|
|
106
|
-
|
|
105
|
+
Access pay-per-use APIs with automatic payment handling using the x402 protocol. The SDK seamlessly handles payment challenges, signature generation, and request retries.
|
|
106
|
+
|
|
107
|
+
#### Basic x402 Usage
|
|
108
|
+
```python
|
|
109
|
+
from zyndai_agent.agent import AgentConfig, ZyndAIAgent
|
|
110
|
+
from dotenv import load_dotenv
|
|
111
|
+
import os
|
|
112
|
+
|
|
113
|
+
load_dotenv()
|
|
114
|
+
|
|
115
|
+
# Configure your agent
|
|
116
|
+
agent_config = AgentConfig(
|
|
117
|
+
default_outbox_topic=None,
|
|
118
|
+
auto_reconnect=True,
|
|
119
|
+
message_history_limit=100,
|
|
120
|
+
registry_url="https://registry.zynd.ai",
|
|
121
|
+
mqtt_broker_url="mqtt://registry.zynd.ai:1883",
|
|
122
|
+
identity_credential_path="./identity_credential.json",
|
|
123
|
+
secret_seed=os.environ["AGENT_SEED"]
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
# Initialize ZyndAI Agent
|
|
127
|
+
zyndai_agent = ZyndAIAgent(agent_config=agent_config)
|
|
128
|
+
|
|
129
|
+
# Make a POST request to an x402 endpoint
|
|
130
|
+
response = zyndai_agent.x402_processor.post("http://localhost:3000/api/pay")
|
|
131
|
+
print(response.json())
|
|
132
|
+
|
|
133
|
+
# Make a GET request to an x402 endpoint
|
|
134
|
+
response = zyndai_agent.x402_processor.get("http://api.example.com/data")
|
|
135
|
+
print(response.json())
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
#### What x402 Does Automatically
|
|
139
|
+
|
|
140
|
+
- ✅ **Payment Challenge/Response Flow**: Handles the entire payment negotiation
|
|
141
|
+
- ✅ **Signature Generation**: Creates cryptographic signatures for authentication
|
|
142
|
+
- ✅ **Retry Logic**: Automatically retries requests after payment verification
|
|
143
|
+
- ✅ **Error Handling**: Gracefully manages payment failures and network issues
|
|
144
|
+
|
|
145
|
+
#### x402 with Custom Data and Headers
|
|
146
|
+
```python
|
|
147
|
+
# POST request with JSON payload
|
|
148
|
+
data = {
|
|
149
|
+
"prompt": "Analyze this text for sentiment",
|
|
150
|
+
"text": "The product exceeded my expectations!",
|
|
151
|
+
"model": "advanced"
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
response = zyndai_agent.x402_processor.post(
|
|
155
|
+
url="https://api.sentiment-ai.com/analyze",
|
|
156
|
+
json=data
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
result = response.json()
|
|
160
|
+
print(f"Sentiment: {result['sentiment']}")
|
|
161
|
+
print(f"Confidence: {result['confidence']}")
|
|
162
|
+
print(f"Cost: {result['tokens_used']} tokens")
|
|
163
|
+
```
|
|
164
|
+
```python
|
|
165
|
+
# GET request with query parameters
|
|
166
|
+
response = zyndai_agent.x402_processor.get(
|
|
167
|
+
url="https://api.market-data.com/stock",
|
|
168
|
+
params={"symbol": "AAPL", "range": "1d"}
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
stock_data = response.json()
|
|
172
|
+
print(f"Current Price: ${stock_data['price']}")
|
|
173
|
+
```
|
|
174
|
+
```python
|
|
175
|
+
# Custom headers
|
|
176
|
+
headers = {
|
|
177
|
+
"X-API-Version": "2.0",
|
|
178
|
+
"X-Client-Id": "my-app"
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
response = zyndai_agent.x402_processor.post(
|
|
182
|
+
url="https://api.premium-service.com/process",
|
|
183
|
+
json={"data": "payload"},
|
|
184
|
+
headers=headers
|
|
185
|
+
)
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
#### Supported HTTP Methods
|
|
189
|
+
```python
|
|
190
|
+
# GET
|
|
191
|
+
response = zyndai_agent.x402_processor.get(url, params={}, headers={})
|
|
192
|
+
|
|
193
|
+
# POST
|
|
194
|
+
response = zyndai_agent.x402_processor.post(url, json={}, headers={})
|
|
195
|
+
|
|
196
|
+
# PUT
|
|
197
|
+
response = zyndai_agent.x402_processor.put(url, json={}, headers={})
|
|
198
|
+
|
|
199
|
+
# DELETE
|
|
200
|
+
response = zyndai_agent.x402_processor.delete(url, headers={})
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
#### x402 Integration with LangChain Tools
|
|
204
|
+
|
|
205
|
+
Create LangChain tools that leverage x402-enabled paid APIs:
|
|
206
|
+
```python
|
|
207
|
+
from langchain_core.tools import tool
|
|
208
|
+
from langchain_openai import ChatOpenAI
|
|
209
|
+
from langchain.agents import create_tool_calling_agent, AgentExecutor
|
|
210
|
+
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
|
211
|
+
from zyndai_agent.agent import AgentConfig, ZyndAIAgent
|
|
212
|
+
import os
|
|
213
|
+
|
|
214
|
+
# Initialize agent
|
|
215
|
+
agent_config = AgentConfig(
|
|
216
|
+
registry_url="https://registry.zynd.ai",
|
|
217
|
+
mqtt_broker_url="mqtt://registry.zynd.ai:1883",
|
|
218
|
+
identity_credential_path="./identity_credential.json",
|
|
219
|
+
secret_seed=os.environ["AGENT_SEED"]
|
|
220
|
+
)
|
|
221
|
+
zyndai_agent = ZyndAIAgent(agent_config=agent_config)
|
|
107
222
|
|
|
223
|
+
@tool
|
|
224
|
+
def get_premium_market_data(symbol: str) -> str:
|
|
225
|
+
"""Fetch real-time premium market data for a stock symbol"""
|
|
226
|
+
response = zyndai_agent.x402_processor.get(
|
|
227
|
+
url="https://api.premium-data.com/stock",
|
|
228
|
+
params={"symbol": symbol}
|
|
229
|
+
)
|
|
230
|
+
data = response.json()
|
|
231
|
+
return f"Stock: {symbol}, Price: ${data['price']}, Volume: {data['volume']}"
|
|
232
|
+
|
|
233
|
+
@tool
|
|
234
|
+
def analyze_sentiment(text: str) -> str:
|
|
235
|
+
"""Analyze sentiment using a premium AI service"""
|
|
236
|
+
response = zyndai_agent.x402_processor.post(
|
|
237
|
+
url="https://api.sentiment-ai.com/analyze",
|
|
238
|
+
json={"text": text}
|
|
239
|
+
)
|
|
240
|
+
result = response.json()
|
|
241
|
+
return f"Sentiment: {result['sentiment']} (confidence: {result['confidence']})"
|
|
242
|
+
|
|
243
|
+
@tool
|
|
244
|
+
def generate_market_report(sector: str) -> str:
|
|
245
|
+
"""Generate a comprehensive market report for a sector"""
|
|
246
|
+
response = zyndai_agent.x402_processor.post(
|
|
247
|
+
url="https://api.reports.com/generate",
|
|
248
|
+
json={"sector": sector, "depth": "comprehensive"}
|
|
249
|
+
)
|
|
250
|
+
return response.json()["report"]
|
|
251
|
+
|
|
252
|
+
# Create LangChain agent with x402-enabled tools
|
|
253
|
+
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
|
|
254
|
+
tools = [get_premium_market_data, analyze_sentiment, generate_market_report]
|
|
255
|
+
|
|
256
|
+
prompt = ChatPromptTemplate.from_messages([
|
|
257
|
+
("system", """You are a financial analysis agent with access to premium paid APIs.
|
|
258
|
+
Use the available tools to provide comprehensive market analysis.
|
|
259
|
+
Always cite the data sources and be clear about costs."""),
|
|
260
|
+
MessagesPlaceholder(variable_name="chat_history"),
|
|
261
|
+
("human", "{input}"),
|
|
262
|
+
MessagesPlaceholder(variable_name="agent_scratchpad")
|
|
263
|
+
])
|
|
264
|
+
|
|
265
|
+
agent = create_tool_calling_agent(llm, tools, prompt)
|
|
266
|
+
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
|
|
267
|
+
|
|
268
|
+
# Use the agent
|
|
269
|
+
response = agent_executor.invoke({
|
|
270
|
+
"input": "Give me a detailed analysis of Apple stock with sentiment analysis of recent news"
|
|
271
|
+
})
|
|
272
|
+
print(response["output"])
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
#### x402 Error Handling
|
|
276
|
+
```python
|
|
277
|
+
try:
|
|
278
|
+
response = zyndai_agent.x402_processor.post(
|
|
279
|
+
url="https://api.paid-service.com/endpoint",
|
|
280
|
+
json={"data": "payload"}
|
|
281
|
+
)
|
|
282
|
+
result = response.json()
|
|
283
|
+
print(f"Success: {result}")
|
|
284
|
+
|
|
285
|
+
except requests.exceptions.HTTPError as e:
|
|
286
|
+
if e.response.status_code == 402:
|
|
287
|
+
print("Payment required but failed to process")
|
|
288
|
+
elif e.response.status_code == 401:
|
|
289
|
+
print("Authentication failed")
|
|
290
|
+
else:
|
|
291
|
+
print(f"HTTP Error: {e}")
|
|
292
|
+
|
|
293
|
+
except requests.exceptions.ConnectionError:
|
|
294
|
+
print("Failed to connect to the API endpoint")
|
|
295
|
+
|
|
296
|
+
except Exception as e:
|
|
297
|
+
print(f"Unexpected error: {e}")
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
### 🔍 Agent Discovery
|
|
301
|
+
|
|
302
|
+
Find agents based on their capabilities using ML-powered semantic matching:
|
|
108
303
|
```python
|
|
109
304
|
# Search for agents with specific capabilities
|
|
110
305
|
agents = zyndai_agent.search_agents_by_capabilities(
|
|
@@ -121,10 +316,9 @@ for agent in agents:
|
|
|
121
316
|
print("---")
|
|
122
317
|
```
|
|
123
318
|
|
|
124
|
-
### Secure Communication
|
|
319
|
+
### 💬 Secure Communication
|
|
125
320
|
|
|
126
321
|
All messages are end-to-end encrypted using ECIES (Elliptic Curve Integrated Encryption Scheme):
|
|
127
|
-
|
|
128
322
|
```python
|
|
129
323
|
# Connect to a discovered agent
|
|
130
324
|
zyndai_agent.connect_agent(selected_agent)
|
|
@@ -139,10 +333,9 @@ result = zyndai_agent.send_message(
|
|
|
139
333
|
messages = zyndai_agent.read_messages()
|
|
140
334
|
```
|
|
141
335
|
|
|
142
|
-
### Identity Verification
|
|
336
|
+
### 🔐 Identity Verification
|
|
143
337
|
|
|
144
338
|
Verify other agents' identities before trusting them:
|
|
145
|
-
|
|
146
339
|
```python
|
|
147
340
|
# Verify an agent's identity
|
|
148
341
|
is_verified = zyndai_agent.verify_agent_identity(agent_credential)
|
|
@@ -157,51 +350,76 @@ my_identity = zyndai_agent.get_identity_document()
|
|
|
157
350
|
|
|
158
351
|
## 💡 Advanced Examples
|
|
159
352
|
|
|
160
|
-
### Multi-Agent Orchestration
|
|
161
|
-
|
|
162
|
-
Build sophisticated workflows that coordinate multiple agents:
|
|
353
|
+
### Multi-Agent Orchestration with x402 APIs
|
|
163
354
|
|
|
355
|
+
Build sophisticated workflows that coordinate multiple agents and paid services:
|
|
164
356
|
```python
|
|
165
357
|
from zyndai_agent.agent import AgentConfig, ZyndAIAgent
|
|
166
358
|
from zyndai_agent.communication import MQTTMessage
|
|
167
359
|
from time import sleep
|
|
360
|
+
import json
|
|
168
361
|
|
|
169
|
-
class
|
|
362
|
+
class MarketAnalysisOrchestrator:
|
|
170
363
|
def __init__(self, zyndai_agent):
|
|
171
364
|
self.zyndai_agent = zyndai_agent
|
|
172
|
-
self.stock_data_agent = None
|
|
173
|
-
self.comparison_agent = None
|
|
174
365
|
|
|
175
|
-
def
|
|
176
|
-
# Step 1:
|
|
177
|
-
|
|
178
|
-
|
|
366
|
+
def comprehensive_market_analysis(self, stock_symbol):
|
|
367
|
+
# Step 1: Fetch real-time market data via x402
|
|
368
|
+
print(f"📊 Fetching market data for {stock_symbol}...")
|
|
369
|
+
market_response = self.zyndai_agent.x402_processor.get(
|
|
370
|
+
url="https://api.market-data.com/stock",
|
|
371
|
+
params={"symbol": stock_symbol, "include": "fundamentals"}
|
|
179
372
|
)
|
|
180
|
-
|
|
181
|
-
self.zyndai_agent.connect_agent(self.stock_data_agent)
|
|
373
|
+
market_data = market_response.json()
|
|
182
374
|
|
|
183
|
-
# Step 2: Get
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
375
|
+
# Step 2: Get news sentiment via x402
|
|
376
|
+
print("📰 Analyzing news sentiment...")
|
|
377
|
+
news_response = self.zyndai_agent.x402_processor.post(
|
|
378
|
+
url="https://api.news-sentiment.com/analyze",
|
|
379
|
+
json={"symbol": stock_symbol, "days": 7}
|
|
380
|
+
)
|
|
381
|
+
sentiment_data = news_response.json()
|
|
190
382
|
|
|
191
|
-
# Step 3: Find and connect to
|
|
192
|
-
|
|
193
|
-
|
|
383
|
+
# Step 3: Find and connect to technical analysis agent
|
|
384
|
+
print("🔍 Finding technical analysis agent...")
|
|
385
|
+
tech_agents = self.zyndai_agent.search_agents_by_capabilities(
|
|
386
|
+
["technical_analysis", "trading_signals"]
|
|
194
387
|
)
|
|
195
|
-
self.comparison_agent = comparison_agents[0]
|
|
196
|
-
self.zyndai_agent.connect_agent(self.comparison_agent)
|
|
197
388
|
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
389
|
+
if tech_agents:
|
|
390
|
+
self.zyndai_agent.connect_agent(tech_agents[0])
|
|
391
|
+
|
|
392
|
+
# Send market data to technical analyst
|
|
393
|
+
message_content = json.dumps({
|
|
394
|
+
"symbol": stock_symbol,
|
|
395
|
+
"price_data": market_data["price_history"],
|
|
396
|
+
"volume": market_data["volume"]
|
|
397
|
+
})
|
|
398
|
+
|
|
399
|
+
self.zyndai_agent.send_message(
|
|
400
|
+
f"Perform technical analysis: {message_content}"
|
|
401
|
+
)
|
|
402
|
+
sleep(3)
|
|
403
|
+
tech_analysis = self.zyndai_agent.read_messages()
|
|
404
|
+
|
|
405
|
+
# Step 4: Generate AI-powered investment thesis via x402
|
|
406
|
+
print("🤖 Generating investment thesis...")
|
|
407
|
+
thesis_response = self.zyndai_agent.x402_processor.post(
|
|
408
|
+
url="https://api.ai-finance.com/thesis",
|
|
409
|
+
json={
|
|
410
|
+
"symbol": stock_symbol,
|
|
411
|
+
"market_data": market_data,
|
|
412
|
+
"sentiment": sentiment_data,
|
|
413
|
+
"technical_analysis": tech_analysis
|
|
414
|
+
}
|
|
415
|
+
)
|
|
202
416
|
|
|
203
|
-
|
|
204
|
-
|
|
417
|
+
return {
|
|
418
|
+
"market_data": market_data,
|
|
419
|
+
"sentiment": sentiment_data,
|
|
420
|
+
"technical_analysis": tech_analysis,
|
|
421
|
+
"investment_thesis": thesis_response.json()
|
|
422
|
+
}
|
|
205
423
|
|
|
206
424
|
# Usage
|
|
207
425
|
agent_config = AgentConfig(
|
|
@@ -212,21 +430,21 @@ agent_config = AgentConfig(
|
|
|
212
430
|
)
|
|
213
431
|
|
|
214
432
|
zyndai_agent = ZyndAIAgent(agent_config=agent_config)
|
|
215
|
-
orchestrator =
|
|
433
|
+
orchestrator = MarketAnalysisOrchestrator(zyndai_agent)
|
|
216
434
|
|
|
217
|
-
result = orchestrator.
|
|
218
|
-
print(result)
|
|
435
|
+
result = orchestrator.comprehensive_market_analysis("AAPL")
|
|
436
|
+
print(json.dumps(result, indent=2))
|
|
219
437
|
```
|
|
220
438
|
|
|
221
439
|
### Creating a Specialized Agent with Custom Tools
|
|
222
|
-
|
|
223
440
|
```python
|
|
224
441
|
from zyndai_agent.agent import AgentConfig, ZyndAIAgent
|
|
225
442
|
from zyndai_agent.communication import MQTTMessage
|
|
226
443
|
from langchain_openai import ChatOpenAI
|
|
227
|
-
from
|
|
228
|
-
from langchain.agents import
|
|
229
|
-
from
|
|
444
|
+
from langchain_core.tools import tool
|
|
445
|
+
from langchain.agents import create_tool_calling_agent, AgentExecutor
|
|
446
|
+
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
|
447
|
+
from langchain.memory import ConversationBufferMemory
|
|
230
448
|
import json
|
|
231
449
|
|
|
232
450
|
@tool
|
|
@@ -258,7 +476,7 @@ Stock Comparison Analysis:
|
|
|
258
476
|
- Volume: {stock1['volume']} vs {stock2['volume']}
|
|
259
477
|
- Market Cap: {stock1['market_cap']} vs {stock2['market_cap']}
|
|
260
478
|
|
|
261
|
-
Recommendation: Based on today's performance
|
|
479
|
+
Recommendation: Based on today's performance, {stock1['symbol'] if float(stock1['change'].strip('%+')) > float(stock2['change'].strip('%+')) else stock2['symbol']} shows stronger momentum.
|
|
262
480
|
"""
|
|
263
481
|
|
|
264
482
|
return comparison
|
|
@@ -278,6 +496,7 @@ zyndai_agent = ZyndAIAgent(agent_config=agent_config)
|
|
|
278
496
|
# Create LangChain agent with custom tool
|
|
279
497
|
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
|
|
280
498
|
tools = [compare_stocks]
|
|
499
|
+
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
|
|
281
500
|
|
|
282
501
|
prompt = ChatPromptTemplate.from_messages([
|
|
283
502
|
("system", """You are a Stock Comparison Agent.
|
|
@@ -288,8 +507,8 @@ prompt = ChatPromptTemplate.from_messages([
|
|
|
288
507
|
MessagesPlaceholder(variable_name="agent_scratchpad")
|
|
289
508
|
])
|
|
290
509
|
|
|
291
|
-
agent =
|
|
292
|
-
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
|
|
510
|
+
agent = create_tool_calling_agent(llm, tools, prompt)
|
|
511
|
+
agent_executor = AgentExecutor(agent=agent, tools=tools, memory=memory, verbose=True)
|
|
293
512
|
|
|
294
513
|
zyndai_agent.set_agent_executor(agent_executor)
|
|
295
514
|
|
|
@@ -302,6 +521,12 @@ def message_handler(message: MQTTMessage, topic: str):
|
|
|
302
521
|
zyndai_agent.add_message_handler(message_handler)
|
|
303
522
|
|
|
304
523
|
print("Stock Comparison Agent is running...")
|
|
524
|
+
print("Waiting for messages...")
|
|
525
|
+
|
|
526
|
+
# Keep agent running
|
|
527
|
+
from time import sleep
|
|
528
|
+
while True:
|
|
529
|
+
sleep(1)
|
|
305
530
|
```
|
|
306
531
|
|
|
307
532
|
## ⚙️ Configuration Options
|
|
@@ -336,6 +561,12 @@ Organize your communication with different message types:
|
|
|
336
561
|
- AES-256-CBC for symmetric encryption
|
|
337
562
|
- Compatible with Polygon ID AuthBJJ credentials
|
|
338
563
|
|
|
564
|
+
### x402 Payment Security
|
|
565
|
+
- Cryptographic signature-based authentication
|
|
566
|
+
- Secure payment challenge/response protocol
|
|
567
|
+
- No exposure of private keys during transactions
|
|
568
|
+
- Built-in protection against replay attacks
|
|
569
|
+
|
|
339
570
|
### Identity Verification
|
|
340
571
|
- Decentralized Identity (DID) based authentication
|
|
341
572
|
- Cryptographic proof of agent identity
|
|
@@ -351,7 +582,6 @@ Organize your communication with different message types:
|
|
|
351
582
|
## 🌐 Agent Discovery Response Format
|
|
352
583
|
|
|
353
584
|
When you search for agents, you receive detailed information:
|
|
354
|
-
|
|
355
585
|
```python
|
|
356
586
|
{
|
|
357
587
|
'id': 'unique-agent-id',
|
|
@@ -370,7 +600,6 @@ When you search for agents, you receive detailed information:
|
|
|
370
600
|
### Custom Message Handlers
|
|
371
601
|
|
|
372
602
|
Add custom logic for incoming messages:
|
|
373
|
-
|
|
374
603
|
```python
|
|
375
604
|
def handle_incoming_message(message: MQTTMessage, topic: str):
|
|
376
605
|
print(f"Received from {message.sender_id}: {message.content}")
|
|
@@ -379,12 +608,19 @@ def handle_incoming_message(message: MQTTMessage, topic: str):
|
|
|
379
608
|
if "urgent" in message.content.lower():
|
|
380
609
|
zyndai_agent.send_message("I'll prioritize this request!",
|
|
381
610
|
message_type="response")
|
|
611
|
+
|
|
612
|
+
# Handle different message types
|
|
613
|
+
if message.message_type == "query":
|
|
614
|
+
# Process query
|
|
615
|
+
pass
|
|
616
|
+
elif message.message_type == "broadcast":
|
|
617
|
+
# Handle broadcast
|
|
618
|
+
pass
|
|
382
619
|
|
|
383
620
|
zyndai_agent.add_message_handler(handle_incoming_message)
|
|
384
621
|
```
|
|
385
622
|
|
|
386
623
|
### Connection Status Monitoring
|
|
387
|
-
|
|
388
624
|
```python
|
|
389
625
|
status = zyndai_agent.get_connection_status()
|
|
390
626
|
print(f"Agent ID: {status['agent_id']}")
|
|
@@ -394,7 +630,6 @@ print(f"Pending Messages: {status['pending_messages']}")
|
|
|
394
630
|
```
|
|
395
631
|
|
|
396
632
|
### Message History Management
|
|
397
|
-
|
|
398
633
|
```python
|
|
399
634
|
# Get recent message history
|
|
400
635
|
history = zyndai_agent.get_message_history(limit=10)
|
|
@@ -411,7 +646,6 @@ for entry in history:
|
|
|
411
646
|
```
|
|
412
647
|
|
|
413
648
|
### Topic Management
|
|
414
|
-
|
|
415
649
|
```python
|
|
416
650
|
# Subscribe to additional topics
|
|
417
651
|
zyndai_agent.subscribe_to_topic("announcements/all")
|
|
@@ -441,9 +675,9 @@ print(status['subscribed_topics'])
|
|
|
441
675
|
## 🐛 Error Handling
|
|
442
676
|
|
|
443
677
|
The SDK includes comprehensive error handling:
|
|
444
|
-
|
|
445
678
|
```python
|
|
446
679
|
from zyndai_agent.agent import ZyndAIAgent, AgentConfig
|
|
680
|
+
import requests
|
|
447
681
|
|
|
448
682
|
try:
|
|
449
683
|
agent_config = AgentConfig(
|
|
@@ -454,12 +688,25 @@ try:
|
|
|
454
688
|
)
|
|
455
689
|
|
|
456
690
|
zyndai_agent = ZyndAIAgent(agent_config)
|
|
691
|
+
|
|
692
|
+
# Agent discovery
|
|
457
693
|
agents = zyndai_agent.search_agents_by_capabilities(["nlp"])
|
|
458
694
|
|
|
695
|
+
# x402 request
|
|
696
|
+
response = zyndai_agent.x402_processor.post(
|
|
697
|
+
url="https://api.paid-service.com/analyze",
|
|
698
|
+
json={"data": "payload"}
|
|
699
|
+
)
|
|
700
|
+
|
|
459
701
|
except FileNotFoundError as e:
|
|
460
702
|
print(f"❌ Credential file not found: {e}")
|
|
461
703
|
except ValueError as e:
|
|
462
704
|
print(f"❌ Invalid configuration or decryption failed: {e}")
|
|
705
|
+
except requests.exceptions.HTTPError as e:
|
|
706
|
+
if e.response.status_code == 402:
|
|
707
|
+
print(f"❌ Payment required: {e}")
|
|
708
|
+
else:
|
|
709
|
+
print(f"❌ HTTP error: {e}")
|
|
463
710
|
except RuntimeError as e:
|
|
464
711
|
print(f"❌ Network error: {e}")
|
|
465
712
|
except Exception as e:
|
|
@@ -467,7 +714,6 @@ except Exception as e:
|
|
|
467
714
|
```
|
|
468
715
|
|
|
469
716
|
## 📊 Architecture Overview
|
|
470
|
-
|
|
471
717
|
```
|
|
472
718
|
┌─────────────────────────────────────────────────────────┐
|
|
473
719
|
│ ZyndAI Agent SDK │
|
|
@@ -491,6 +737,15 @@ except Exception as e:
|
|
|
491
737
|
│ └──────────────────────────────────────────┘ │
|
|
492
738
|
│ │
|
|
493
739
|
│ ┌──────────────────────────────────────────┐ │
|
|
740
|
+
│ │ x402 Payment Processor │ │
|
|
741
|
+
│ │ │ │
|
|
742
|
+
│ │ - Payment Challenge Handling │ │
|
|
743
|
+
│ │ - Signature Generation │ │
|
|
744
|
+
│ │ - Automatic Retry Logic │ │
|
|
745
|
+
│ │ - Multi-Method Support (GET/POST/etc) │ │
|
|
746
|
+
│ └──────────────────────────────────────────┘ │
|
|
747
|
+
│ │
|
|
748
|
+
│ ┌──────────────────────────────────────────┐ │
|
|
494
749
|
│ │ LangChain Integration │ │
|
|
495
750
|
│ │ │ │
|
|
496
751
|
│ │ - Agent Executor Support │ │
|
|
@@ -503,6 +758,11 @@ except Exception as e:
|
|
|
503
758
|
│ Registry │ │ MQTT Broker │
|
|
504
759
|
│ Service │ │ │
|
|
505
760
|
└──────────────┘ └──────────────┘
|
|
761
|
+
▼
|
|
762
|
+
┌──────────────┐
|
|
763
|
+
│ x402 Enabled │
|
|
764
|
+
│ Services │
|
|
765
|
+
└──────────────┘
|
|
506
766
|
```
|
|
507
767
|
|
|
508
768
|
## 🤝 Contributing
|
|
@@ -516,7 +776,6 @@ We welcome contributions! Here's how to get started:
|
|
|
516
776
|
5. Submit a pull request
|
|
517
777
|
|
|
518
778
|
### Development Setup
|
|
519
|
-
|
|
520
779
|
```bash
|
|
521
780
|
git clone https://github.com/P3-AI-Network/zyndai-agent.git
|
|
522
781
|
cd zyndai-agent
|
|
@@ -527,32 +786,36 @@ pip install -r requirements-dev.txt
|
|
|
527
786
|
```
|
|
528
787
|
|
|
529
788
|
### Running Tests
|
|
530
|
-
|
|
531
789
|
```bash
|
|
532
790
|
pytest tests/ -v
|
|
533
791
|
pytest tests/test_communication.py -k "test_encryption"
|
|
792
|
+
pytest tests/test_x402.py -k "test_payment_flow"
|
|
534
793
|
```
|
|
535
794
|
|
|
536
795
|
## 📚 Example Use Cases
|
|
537
796
|
|
|
538
|
-
### 1. Research
|
|
539
|
-
Connect multiple research agents to
|
|
797
|
+
### 1. AI-Powered Research Network
|
|
798
|
+
Connect multiple research agents with access to premium academic databases via x402, collaboratively analyzing papers and generating insights.
|
|
540
799
|
|
|
541
|
-
### 2.
|
|
542
|
-
Build
|
|
800
|
+
### 2. Financial Analysis Pipeline
|
|
801
|
+
Build workflows combining free agent communication with paid market data APIs, sentiment analysis services, and AI-powered investment recommendations.
|
|
543
802
|
|
|
544
|
-
### 3.
|
|
545
|
-
|
|
803
|
+
### 3. Multi-Modal Data Processing
|
|
804
|
+
Orchestrate agents that handle different stages: data ingestion from x402 sources, transformation, analysis by specialized agents, and automated reporting.
|
|
546
805
|
|
|
547
|
-
### 4.
|
|
548
|
-
|
|
806
|
+
### 4. Premium Customer Service
|
|
807
|
+
Deploy specialized agents that can access paid knowledge bases, translation services, and sentiment analysis APIs while coordinating responses.
|
|
549
808
|
|
|
550
|
-
### 5.
|
|
551
|
-
|
|
809
|
+
### 5. Trading Strategy Development
|
|
810
|
+
Create agents for real-time market data (x402), technical analysis by agents, sentiment from paid news APIs, and coordinated trade execution.
|
|
811
|
+
|
|
812
|
+
### 6. Content Generation with Fact-Checking
|
|
813
|
+
Orchestrate agents for research, writing, accessing paid fact-checking APIs via x402, and publishing verified content.
|
|
552
814
|
|
|
553
815
|
## 🆘 Support & Community
|
|
554
816
|
|
|
555
817
|
- **GitHub Issues**: [Report bugs or request features](https://github.com/P3-AI-Network/zyndai-agent/issues)
|
|
818
|
+
- **Documentation**: [Full API Documentation](https://docs.zynd.ai)
|
|
556
819
|
- **Email**: p3ainetwork@gmail.com
|
|
557
820
|
- **Twitter**: [@ZyndAI](https://x.com/ZyndAI)
|
|
558
821
|
|
|
@@ -566,20 +829,28 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
|
|
|
566
829
|
- Uses [Paho MQTT](https://www.eclipse.org/paho/) for reliable messaging
|
|
567
830
|
- Cryptography powered by [cryptography](https://cryptography.io/) library
|
|
568
831
|
- Decentralized Identity via [Polygon ID](https://polygon.technology/polygon-id)
|
|
832
|
+
- x402 micropayment protocol for seamless API monetization
|
|
569
833
|
- Semantic search using ML-powered capability matching
|
|
570
834
|
|
|
571
835
|
## 🗺️ Roadmap
|
|
572
836
|
|
|
837
|
+
- [x] Core agent communication and discovery
|
|
838
|
+
- [x] End-to-end encryption
|
|
839
|
+
- [x] LangChain integration
|
|
840
|
+
- [x] x402 micropayment support
|
|
573
841
|
- [ ] Support for additional LLM providers (Anthropic, Cohere, etc.)
|
|
574
|
-
- [ ] Web dashboard for agent monitoring
|
|
842
|
+
- [ ] Web dashboard for agent monitoring and payment tracking
|
|
575
843
|
- [ ] Advanced orchestration patterns (workflows, state machines)
|
|
576
844
|
- [ ] Integration with popular data sources (APIs, databases)
|
|
577
845
|
- [ ] Multi-language support (JavaScript, Go, Rust)
|
|
578
846
|
- [ ] Enhanced security features (rate limiting, access control)
|
|
579
847
|
- [ ] Performance optimizations for high-throughput scenarios
|
|
848
|
+
- [ ] x402 payment analytics and budgeting tools
|
|
580
849
|
|
|
581
850
|
---
|
|
582
851
|
|
|
583
|
-
**Ready to build the future of AI agent collaboration?**
|
|
852
|
+
**Ready to build the future of AI agent collaboration with micropayments?**
|
|
584
853
|
|
|
585
854
|
Get started today: `pip install zyndai-agent` 🚀
|
|
855
|
+
|
|
856
|
+
**Questions about x402 integration?** Check out our [x402 documentation](https://docs.zynd.ai/x402) or join our community!
|