Skip to content

Commit 6cc298f

Browse files
authored
Merge branch 'kyegomez:master' into Graph-of-thought
2 parents 112b088 + 8c76701 commit 6cc298f

33 files changed

Lines changed: 934 additions & 1037 deletions

README.md

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,17 @@ Swarms delivers a comprehensive, enterprise-grade multi-agent infrastructure pla
5858
| 🛠️ **Developer Experience** | • Intuitive Enterprise API<br>• Comprehensive Documentation<br>• Active Enterprise Community<br>• CLI & SDK Tools<br>• IDE Integration Support<br>• Code Generation Templates | • Accelerated Development Cycles<br>• Reduced Learning Curve<br>• Expert Community Support<br>• Rapid Deployment Capabilities<br>• Enhanced Developer Productivity<br>• Standardized Development Patterns |
5959

6060

61+
## 🔌 Supported Protocols & Integrations
62+
63+
Swarms seamlessly integrates with industry-standard protocols, enabling powerful capabilities for tool integration, payment processing, and distributed agent orchestration.
64+
65+
| Protocol | Description | Use Cases | Documentation |
66+
|----------|-------------|-----------|---------------|
67+
| **[MCP (Model Context Protocol)](https://docs.swarms.world/en/latest/swarms/examples/multi_mcp_agent/)** | Standardized protocol for AI agents to interact with external tools and services through MCP servers. Enables dynamic tool discovery and execution. | • Tool integration<br>• Multi-server connections<br>• External API access<br>• Database connectivity | [MCP Integration Guide](https://docs.swarms.world/en/latest/swarms/examples/multi_mcp_agent/) |
68+
| **[X402](https://docs.swarms.world/en/latest/examples/x402_payment_integration/)** | Cryptocurrency payment protocol for API endpoints. Enables monetization of agents with pay-per-use models. | • Agent monetization<br>• Payment gate protection<br>• Crypto payments<br>• Pay-per-use services | [X402 Quickstart](https://docs.swarms.world/en/latest/examples/x402_payment_integration/) |
69+
| **[AOP (Agent Orchestration Protocol)](https://docs.swarms.world/en/latest/examples/aop_medical/)** | Framework for deploying and managing agents as distributed services. Enables agent discovery, management, and execution through standardized protocols. | • Distributed agent deployment<br>• Agent discovery<br>• Service orchestration<br>• Scalable multi-agent systems | [AOP Reference](https://docs.swarms.world/en/latest/swarms/structs/aop/) |
70+
71+
6172
## Install 💻
6273

6374
### Using pip
@@ -822,7 +833,7 @@ Thank you for contributing to swarms. Your work is extremely appreciated and rec
822833

823834
-----
824835

825-
## Connect With Us
836+
## Join the Swarms community 👾👾👾
826837

827838
Join our community of agent engineers and researchers for technical support, cutting-edge updates, and exclusive access to world-class agent engineering insights!
828839

Lines changed: 231 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,231 @@
1+
# X402 Discovery Query Agent
2+
3+
This example demonstrates how to create a Swarms agent that can search and query services from the X402 bazaar using the Coinbase CDP API. The agent can discover available services, filter them by price, and provide summaries of the results.
4+
5+
## Overview
6+
7+
The X402 Discovery Query Agent enables you to:
8+
9+
| Feature | Description |
10+
|---------|-------------|
11+
| Query X402 services | Search the X402 bazaar for available services |
12+
| Filter by price | Find services within your budget |
13+
| Summarize results | Get AI-powered summaries of discovered services |
14+
| Pagination support | Handle large result sets efficiently |
15+
16+
## Prerequisites
17+
18+
Before you begin, ensure you have:
19+
20+
- Python 3.10 or higher
21+
- API keys for your AI model provider (e.g., Anthropic Claude)
22+
- `httpx` library for async HTTP requests
23+
24+
## Installation
25+
26+
Install the required dependencies:
27+
28+
```bash
29+
pip install swarms httpx
30+
```
31+
32+
## Code Example
33+
34+
Here's the complete implementation of the X402 Discovery Query Agent:
35+
36+
```python
37+
import asyncio
38+
from typing import List, Optional, Dict, Any
39+
from swarms import Agent
40+
import httpx
41+
42+
43+
async def query_x402_services(
44+
limit: Optional[int] = None,
45+
max_price: Optional[int] = None,
46+
offset: int = 0,
47+
base_url: str = "https://api.cdp.coinbase.com",
48+
) -> Dict[str, Any]:
49+
"""
50+
Query x402 discovery services from the Coinbase CDP API.
51+
52+
Args:
53+
limit: Optional maximum number of services to return. If None, returns all available.
54+
max_price: Optional maximum price in atomic units to filter by. Only services with
55+
maxAmountRequired <= max_price will be included.
56+
offset: Pagination offset for the API request. Defaults to 0.
57+
base_url: Base URL for the API. Defaults to Coinbase CDP API.
58+
59+
Returns:
60+
Dict containing the API response with 'items' list and pagination info.
61+
62+
Raises:
63+
httpx.HTTPError: If the HTTP request fails.
64+
httpx.RequestError: If there's a network error.
65+
"""
66+
url = f"{base_url}/platform/v2/x402/discovery/resources"
67+
params = {"offset": offset}
68+
69+
# If both limit and max_price are specified, fetch more services to account for filtering
70+
api_limit = limit
71+
if limit is not None and max_price is not None:
72+
# Fetch 5x the limit to account for services that might be filtered out
73+
api_limit = limit * 5
74+
75+
if api_limit is not None:
76+
params["limit"] = api_limit
77+
78+
async with httpx.AsyncClient(timeout=30.0) as client:
79+
response = await client.get(url, params=params)
80+
response.raise_for_status()
81+
data = response.json()
82+
83+
# Filter by price if max_price is specified
84+
if max_price is not None and "items" in data:
85+
filtered_items = []
86+
for item in data.get("items", []):
87+
# Check if any payment option in 'accepts' has maxAmountRequired <= max_price
88+
accepts = item.get("accepts", [])
89+
for accept in accepts:
90+
max_amount_str = accept.get("maxAmountRequired", "")
91+
if max_amount_str:
92+
try:
93+
max_amount = int(max_amount_str)
94+
if max_amount <= max_price:
95+
filtered_items.append(item)
96+
break # Only add item once if any payment option matches
97+
except (ValueError, TypeError):
98+
continue
99+
100+
# Apply limit to filtered results if specified
101+
if limit is not None:
102+
filtered_items = filtered_items[:limit]
103+
104+
data["items"] = filtered_items
105+
# Update pagination total if we filtered
106+
if "pagination" in data:
107+
data["pagination"]["total"] = len(filtered_items)
108+
109+
return data
110+
111+
112+
def get_x402_services_sync(
113+
limit: Optional[int] = None,
114+
max_price: Optional[int] = None,
115+
offset: int = 0,
116+
) -> str:
117+
"""
118+
Synchronous wrapper for get_x402_services that returns a formatted string.
119+
120+
Args:
121+
limit: Optional maximum number of services to return.
122+
max_price: Optional maximum price in atomic units to filter by.
123+
offset: Pagination offset for the API request. Defaults to 0.
124+
125+
Returns:
126+
JSON-formatted string of service dictionaries matching the criteria.
127+
"""
128+
async def get_x402_services():
129+
result = await query_x402_services(
130+
limit=limit, max_price=max_price, offset=offset
131+
)
132+
return result.get("items", [])
133+
134+
services = asyncio.run(get_x402_services())
135+
return str(services)
136+
137+
138+
# Initialize the agent with the discovery tool
139+
agent = Agent(
140+
agent_name="X402-Discovery-Agent",
141+
agent_description="A agent that queries the x402 discovery services from the Coinbase CDP API.",
142+
model_name="claude-haiku-4-5",
143+
dynamic_temperature_enabled=True,
144+
max_loops=1,
145+
dynamic_context_window=True,
146+
tools=[get_x402_services_sync],
147+
top_p=None,
148+
temperature=None,
149+
tool_call_summary=True,
150+
)
151+
152+
if __name__ == "__main__":
153+
# Run the agent
154+
out = agent.run(
155+
task="Summarize the first 10 services under 100000 atomic units (e.g., $0.10 USDC)"
156+
)
157+
print(out)
158+
```
159+
160+
## Usage
161+
162+
### Basic Query
163+
164+
Query all available services:
165+
166+
```python
167+
result = await query_x402_services()
168+
print(f"Found {len(result['items'])} services")
169+
```
170+
171+
### Filtered Query
172+
173+
Get services within a specific price range:
174+
175+
```python
176+
# Get first 10 services under 100000 atomic units ($0.10 USDC with 6 decimals)
177+
services = await get_x402_services(limit=10, max_price=100000)
178+
for service in services:
179+
print(service["resource"])
180+
```
181+
182+
### Using the Agent
183+
184+
Run the agent to get AI-powered summaries:
185+
186+
```python
187+
# The agent will automatically call the tool and provide a summary
188+
out = agent.run(
189+
task="Find and summarize 5 affordable services under 50000 atomic units"
190+
)
191+
print(out)
192+
```
193+
194+
## Understanding Price Units
195+
196+
X402 services use atomic units for pricing. For example:
197+
198+
- **USDC** typically uses 6 decimals
199+
- 100,000 atomic units = $0.10 USDC
200+
- 1,000,000 atomic units = $1.00 USDC
201+
202+
Always check the `accepts` array in each service to understand the payment options and their price requirements.
203+
204+
## API Response Structure
205+
206+
Each service in the response contains:
207+
208+
- `resource`: The service endpoint or resource identifier
209+
- `accepts`: Array of payment options with `maxAmountRequired` values
210+
- Additional metadata about the service
211+
212+
## Error Handling
213+
214+
The functions handle various error cases:
215+
216+
- Network errors are raised as `httpx.RequestError`
217+
- HTTP errors are raised as `httpx.HTTPError`
218+
- Invalid price values are silently skipped during filtering
219+
220+
## Next Steps
221+
222+
1. Customize the agent's system prompt for specific use cases
223+
2. Add additional filtering criteria (e.g., by service type)
224+
3. Implement caching for frequently accessed services
225+
4. Create a web interface for browsing services
226+
5. Integrate with payment processing to actually use discovered services
227+
228+
## Related Documentation
229+
230+
- [X402 Payment Integration](x402_payment_integration.md) - Learn how to monetize your agents with X402
231+
- [Agent Tools Reference](../swarms/tools/tools_examples.md) - Understand how to create and use tools with agents

docs/mkdocs.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -437,6 +437,7 @@ nav:
437437

438438
- X402:
439439
- x402 Quickstart Example: "examples/x402_payment_integration.md"
440+
- X402 Discovery Query Agent: "examples/x402_discovery_query.md"
440441

441442

442443
- Swarms Cloud API:

docs/quickstart.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -290,14 +290,14 @@ task = "Write a short story about a robot who discovers music."
290290
# --- Example 1: SequentialWorkflow ---
291291
# Agents run one after another in a chain: Writer -> Editor -> Reviewer.
292292
print("Running a Sequential Workflow...")
293-
sequential_router = SwarmRouter(swarm_type=SwarmType.SequentialWorkflow, agents=agents)
293+
sequential_router = SwarmRouter(swarm_type="SequentialWorkflow", agents=agents)
294294
sequential_output = sequential_router.run(task)
295295
print(f"Final Sequential Output:\n{sequential_output}\n")
296296

297297
# --- Example 2: ConcurrentWorkflow ---
298298
# All agents receive the same initial task and run at the same time.
299299
print("Running a Concurrent Workflow...")
300-
concurrent_router = SwarmRouter(swarm_type=SwarmType.ConcurrentWorkflow, agents=agents)
300+
concurrent_router = SwarmRouter(swarm_type="ConcurrentWorkflow", agents=agents)
301301
concurrent_outputs = concurrent_router.run(task)
302302
# This returns a dictionary of each agent's output
303303
for agent_name, output in concurrent_outputs.items():
@@ -312,9 +312,9 @@ aggregator = Agent(
312312
model_name="gpt-4o-mini"
313313
)
314314
moa_router = SwarmRouter(
315-
swarm_type=SwarmType.MixtureOfAgents,
315+
swarm_type="MixtureOfAgents",
316316
agents=agents,
317-
aggregator_agent=aggregator, # MoA requires an aggregator
317+
aggregator_agent=aggregator,
318318
)
319319
aggregated_output = moa_router.run(task)
320320
print(f"Final Aggregated Output:\n{aggregated_output}\n")

docs/requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ mkdocs-autolinks-plugin
2424

2525
# Requirements for core
2626
jinja2~=3.1
27-
markdown~=3.8
27+
markdown~=3.10
2828
mkdocs-material-extensions~=1.3
2929
pygments~=2.19
3030
pymdown-extensions~=10.16

0 commit comments

Comments
 (0)