parent
20d7ee580f
commit
5bae455600
@ -1,16 +1,15 @@
|
|||||||
import orjson
|
import orjson
|
||||||
from dotenv import load_dotenv
|
|
||||||
|
|
||||||
from swarms.structs.auto_swarm_builder import AutoSwarmBuilder
|
from swarms import AutoSwarmBuilder
|
||||||
|
|
||||||
load_dotenv()
|
|
||||||
|
|
||||||
swarm = AutoSwarmBuilder(
|
swarm = AutoSwarmBuilder(
|
||||||
name="My Swarm",
|
name="My Swarm",
|
||||||
description="My Swarm Description",
|
description="My Swarm Description",
|
||||||
verbose=True,
|
verbose=True,
|
||||||
max_loops=1,
|
max_loops=1,
|
||||||
return_agents=True,
|
execution_type="return-agents",
|
||||||
|
model_name="gpt-4.1",
|
||||||
)
|
)
|
||||||
|
|
||||||
result = swarm.run(
|
result = swarm.run(
|
@ -1,68 +0,0 @@
|
|||||||
import json
|
|
||||||
import asyncio
|
|
||||||
|
|
||||||
from swarms.structs.aop import AOPCluster
|
|
||||||
from swarms.tools.mcp_client_tools import execute_tool_call_simple
|
|
||||||
|
|
||||||
|
|
||||||
async def discover_agents_example():
|
|
||||||
"""Example of how to call the discover_agents tool."""
|
|
||||||
|
|
||||||
# Create AOP cluster connection
|
|
||||||
aop_cluster = AOPCluster(
|
|
||||||
urls=["http://localhost:5932/mcp"],
|
|
||||||
transport="streamable-http",
|
|
||||||
)
|
|
||||||
|
|
||||||
# Check if discover_agents tool is available
|
|
||||||
discover_tool = aop_cluster.find_tool_by_server_name(
|
|
||||||
"discover_agents"
|
|
||||||
)
|
|
||||||
if discover_tool:
|
|
||||||
try:
|
|
||||||
# Create the tool call request
|
|
||||||
tool_call_request = {
|
|
||||||
"type": "function",
|
|
||||||
"function": {
|
|
||||||
"name": "discover_agents",
|
|
||||||
"arguments": json.dumps(
|
|
||||||
{}
|
|
||||||
), # No specific agent name = get all
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
# Execute the tool call
|
|
||||||
result = await execute_tool_call_simple(
|
|
||||||
response=tool_call_request,
|
|
||||||
server_path="http://localhost:5932/mcp",
|
|
||||||
output_type="dict",
|
|
||||||
verbose=False,
|
|
||||||
)
|
|
||||||
|
|
||||||
print(json.dumps(result, indent=2))
|
|
||||||
|
|
||||||
# Parse the result
|
|
||||||
if isinstance(result, list) and len(result) > 0:
|
|
||||||
discovery_data = result[0]
|
|
||||||
if discovery_data.get("success"):
|
|
||||||
agents = discovery_data.get("agents", [])
|
|
||||||
return agents
|
|
||||||
else:
|
|
||||||
return None
|
|
||||||
else:
|
|
||||||
return None
|
|
||||||
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
else:
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
"""Main function to run the discovery example."""
|
|
||||||
# Run the async function
|
|
||||||
return asyncio.run(discover_agents_example())
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
@ -0,0 +1,47 @@
|
|||||||
|
import json
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
from swarms.structs.aop import AOPCluster
|
||||||
|
from swarms.tools.mcp_client_tools import execute_tool_call_simple
|
||||||
|
|
||||||
|
|
||||||
|
async def discover_agents_example():
|
||||||
|
"""
|
||||||
|
Discover all agents using the AOPCluster and print the result.
|
||||||
|
"""
|
||||||
|
aop_cluster = AOPCluster(
|
||||||
|
urls=["http://localhost:5932/mcp"],
|
||||||
|
transport="streamable-http",
|
||||||
|
)
|
||||||
|
tool = aop_cluster.find_tool_by_server_name("discover_agents")
|
||||||
|
if not tool:
|
||||||
|
print("discover_agents tool not found.")
|
||||||
|
return None
|
||||||
|
|
||||||
|
tool_call_request = {
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": "discover_agents",
|
||||||
|
"arguments": "{}",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
result = await execute_tool_call_simple(
|
||||||
|
response=tool_call_request,
|
||||||
|
server_path="http://localhost:5932/mcp",
|
||||||
|
output_type="dict",
|
||||||
|
verbose=False,
|
||||||
|
)
|
||||||
|
print(json.dumps(result, indent=2))
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""
|
||||||
|
Run the discover_agents_example coroutine.
|
||||||
|
"""
|
||||||
|
asyncio.run(discover_agents_example())
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
@ -0,0 +1,149 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Example demonstrating the AOP queue system for agent execution.
|
||||||
|
|
||||||
|
This example shows how to use the new queue-based execution system
|
||||||
|
in the AOP framework for improved performance and reliability.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import time
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.aop import AOP
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""Demonstrate AOP queue functionality."""
|
||||||
|
|
||||||
|
# Create some sample agents
|
||||||
|
agent1 = Agent(
|
||||||
|
agent_name="Research Agent",
|
||||||
|
agent_description="Specialized in research tasks",
|
||||||
|
model_name="gpt-4",
|
||||||
|
max_loops=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
agent2 = Agent(
|
||||||
|
agent_name="Writing Agent",
|
||||||
|
agent_description="Specialized in writing tasks",
|
||||||
|
model_name="gpt-4",
|
||||||
|
max_loops=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create AOP with queue enabled
|
||||||
|
aop = AOP(
|
||||||
|
server_name="Queue Demo Cluster",
|
||||||
|
description="A demonstration of queue-based agent execution",
|
||||||
|
queue_enabled=True,
|
||||||
|
max_workers_per_agent=2, # 2 workers per agent
|
||||||
|
max_queue_size_per_agent=100, # Max 100 tasks per queue
|
||||||
|
processing_timeout=60, # 60 second timeout
|
||||||
|
retry_delay=2.0, # 2 second delay between retries
|
||||||
|
verbose=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Add agents to the cluster
|
||||||
|
print("Adding agents to cluster...")
|
||||||
|
aop.add_agent(agent1, tool_name="researcher")
|
||||||
|
aop.add_agent(agent2, tool_name="writer")
|
||||||
|
|
||||||
|
# Get initial queue stats
|
||||||
|
print("\nInitial queue stats:")
|
||||||
|
stats = aop.get_queue_stats()
|
||||||
|
print(f"Stats: {stats}")
|
||||||
|
|
||||||
|
# Add some tasks to the queues
|
||||||
|
print("\nAdding tasks to queues...")
|
||||||
|
|
||||||
|
# Add high priority research task
|
||||||
|
research_task_id = aop.task_queues["researcher"].add_task(
|
||||||
|
task="Research the latest developments in quantum computing",
|
||||||
|
priority=10, # High priority
|
||||||
|
max_retries=2,
|
||||||
|
)
|
||||||
|
print(f"Added research task: {research_task_id}")
|
||||||
|
|
||||||
|
# Add medium priority writing task
|
||||||
|
writing_task_id = aop.task_queues["writer"].add_task(
|
||||||
|
task="Write a summary of AI trends in 2024",
|
||||||
|
priority=5, # Medium priority
|
||||||
|
max_retries=3,
|
||||||
|
)
|
||||||
|
print(f"Added writing task: {writing_task_id}")
|
||||||
|
|
||||||
|
# Add multiple low priority tasks
|
||||||
|
for i in range(3):
|
||||||
|
task_id = aop.task_queues["researcher"].add_task(
|
||||||
|
task=f"Research task {i+1}: Analyze market trends",
|
||||||
|
priority=1, # Low priority
|
||||||
|
max_retries=1,
|
||||||
|
)
|
||||||
|
print(f"Added research task {i+1}: {task_id}")
|
||||||
|
|
||||||
|
# Get updated queue stats
|
||||||
|
print("\nUpdated queue stats:")
|
||||||
|
stats = aop.get_queue_stats()
|
||||||
|
print(f"Stats: {stats}")
|
||||||
|
|
||||||
|
# Monitor task progress
|
||||||
|
print("\nMonitoring task progress...")
|
||||||
|
for _ in range(10): # Monitor for 10 iterations
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
# Check research task status
|
||||||
|
research_status = aop.get_task_status(
|
||||||
|
"researcher", research_task_id
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
f"Research task status: {research_status['task']['status'] if research_status['success'] else 'Error'}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Check writing task status
|
||||||
|
writing_status = aop.get_task_status(
|
||||||
|
"writer", writing_task_id
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
f"Writing task status: {writing_status['task']['status'] if writing_status['success'] else 'Error'}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Get current queue stats
|
||||||
|
current_stats = aop.get_queue_stats()
|
||||||
|
if current_stats["success"]:
|
||||||
|
for agent_name, agent_stats in current_stats[
|
||||||
|
"stats"
|
||||||
|
].items():
|
||||||
|
print(
|
||||||
|
f"{agent_name}: {agent_stats['pending_tasks']} pending, {agent_stats['processing_tasks']} processing, {agent_stats['completed_tasks']} completed"
|
||||||
|
)
|
||||||
|
|
||||||
|
print("---")
|
||||||
|
|
||||||
|
# Demonstrate queue management
|
||||||
|
print("\nDemonstrating queue management...")
|
||||||
|
|
||||||
|
# Pause the research agent queue
|
||||||
|
print("Pausing research agent queue...")
|
||||||
|
aop.pause_agent_queue("researcher")
|
||||||
|
|
||||||
|
# Get queue status
|
||||||
|
research_queue_status = aop.task_queues["researcher"].get_status()
|
||||||
|
print(f"Research queue status: {research_queue_status.value}")
|
||||||
|
|
||||||
|
# Resume the research agent queue
|
||||||
|
print("Resuming research agent queue...")
|
||||||
|
aop.resume_agent_queue("researcher")
|
||||||
|
|
||||||
|
# Clear all queues
|
||||||
|
print("Clearing all queues...")
|
||||||
|
cleared = aop.clear_all_queues()
|
||||||
|
print(f"Cleared tasks: {cleared}")
|
||||||
|
|
||||||
|
# Final stats
|
||||||
|
print("\nFinal queue stats:")
|
||||||
|
final_stats = aop.get_queue_stats()
|
||||||
|
print(f"Final stats: {final_stats}")
|
||||||
|
|
||||||
|
print("\nQueue demonstration completed!")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
@ -0,0 +1,88 @@
|
|||||||
|
import json
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
from swarms.structs.aop import AOPCluster
|
||||||
|
from swarms.tools.mcp_client_tools import execute_tool_call_simple
|
||||||
|
from mcp import ClientSession
|
||||||
|
from mcp.client.streamable_http import streamablehttp_client
|
||||||
|
|
||||||
|
|
||||||
|
async def discover_agents_example():
|
||||||
|
"""
|
||||||
|
Discover all agents using the AOPCluster and print the result.
|
||||||
|
"""
|
||||||
|
aop_cluster = AOPCluster(
|
||||||
|
urls=["http://localhost:5932/mcp"],
|
||||||
|
transport="streamable-http",
|
||||||
|
)
|
||||||
|
tool = aop_cluster.find_tool_by_server_name("discover_agents")
|
||||||
|
if not tool:
|
||||||
|
print("discover_agents tool not found.")
|
||||||
|
return None
|
||||||
|
|
||||||
|
tool_call_request = {
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": "discover_agents",
|
||||||
|
"arguments": "{}",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
result = await execute_tool_call_simple(
|
||||||
|
response=tool_call_request,
|
||||||
|
server_path="http://localhost:5932/mcp",
|
||||||
|
output_type="dict",
|
||||||
|
verbose=False,
|
||||||
|
)
|
||||||
|
print(json.dumps(result, indent=2))
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
async def raw_mcp_discover_agents_example():
|
||||||
|
"""
|
||||||
|
Call the MCP server directly using the raw MCP client to execute the
|
||||||
|
built-in "discover_agents" tool and print the JSON result.
|
||||||
|
|
||||||
|
This demonstrates how to:
|
||||||
|
- Initialize an MCP client over streamable HTTP
|
||||||
|
- List available tools (optional)
|
||||||
|
- Call a specific tool by name with arguments
|
||||||
|
"""
|
||||||
|
url = "http://localhost:5932/mcp"
|
||||||
|
|
||||||
|
# Open a raw MCP client connection
|
||||||
|
async with streamablehttp_client(url, timeout=10) as ctx:
|
||||||
|
if len(ctx) == 2:
|
||||||
|
read, write = ctx
|
||||||
|
else:
|
||||||
|
read, write, *_ = ctx
|
||||||
|
|
||||||
|
async with ClientSession(read, write) as session:
|
||||||
|
# Initialize the MCP session and optionally inspect tools
|
||||||
|
await session.initialize()
|
||||||
|
|
||||||
|
# Optional: list tools (uncomment to print)
|
||||||
|
# tools = await session.list_tools()
|
||||||
|
# print(json.dumps(tools.model_dump(), indent=2))
|
||||||
|
|
||||||
|
# Call the built-in discovery tool with empty arguments
|
||||||
|
result = await session.call_tool(
|
||||||
|
name="discover_agents",
|
||||||
|
arguments={},
|
||||||
|
)
|
||||||
|
|
||||||
|
# Convert to dict for pretty printing
|
||||||
|
print(json.dumps(result.model_dump(), indent=2))
|
||||||
|
return result.model_dump()
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""
|
||||||
|
Run the helper-based and raw MCP client discovery examples.
|
||||||
|
"""
|
||||||
|
asyncio.run(discover_agents_example())
|
||||||
|
asyncio.run(raw_mcp_discover_agents_example())
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
@ -0,0 +1,107 @@
|
|||||||
|
import json
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
from mcp import ClientSession
|
||||||
|
from mcp.client.streamable_http import streamablehttp_client
|
||||||
|
|
||||||
|
|
||||||
|
async def call_agent_tool_raw(
|
||||||
|
url: str,
|
||||||
|
tool_name: str,
|
||||||
|
task: str,
|
||||||
|
img: str | None = None,
|
||||||
|
imgs: list[str] | None = None,
|
||||||
|
correct_answer: str | None = None,
|
||||||
|
) -> dict:
|
||||||
|
"""
|
||||||
|
Call a specific agent tool on an MCP server using the raw MCP client.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
url: MCP server URL (e.g., "http://localhost:5932/mcp").
|
||||||
|
tool_name: Name of the tool/agent to invoke.
|
||||||
|
task: Task prompt to execute.
|
||||||
|
img: Optional single image path/URL.
|
||||||
|
imgs: Optional list of image paths/URLs.
|
||||||
|
correct_answer: Optional expected answer for validation.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A dict containing the tool's JSON response.
|
||||||
|
"""
|
||||||
|
# Open a raw MCP client connection over streamable HTTP
|
||||||
|
async with streamablehttp_client(url, timeout=30) as ctx:
|
||||||
|
if len(ctx) == 2:
|
||||||
|
read, write = ctx
|
||||||
|
else:
|
||||||
|
read, write, *_ = ctx
|
||||||
|
|
||||||
|
async with ClientSession(read, write) as session:
|
||||||
|
# Initialize the MCP session
|
||||||
|
await session.initialize()
|
||||||
|
|
||||||
|
# Prepare arguments in the canonical AOP tool format
|
||||||
|
arguments: dict = {"task": task}
|
||||||
|
if img is not None:
|
||||||
|
arguments["img"] = img
|
||||||
|
if imgs is not None:
|
||||||
|
arguments["imgs"] = imgs
|
||||||
|
if correct_answer is not None:
|
||||||
|
arguments["correct_answer"] = correct_answer
|
||||||
|
|
||||||
|
# Invoke the tool by name
|
||||||
|
result = await session.call_tool(
|
||||||
|
name=tool_name, arguments=arguments
|
||||||
|
)
|
||||||
|
|
||||||
|
# Convert to dict for return/printing
|
||||||
|
return result.model_dump()
|
||||||
|
|
||||||
|
|
||||||
|
async def list_available_tools(url: str) -> dict:
|
||||||
|
"""
|
||||||
|
List tools from an MCP server using the raw client.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
url: MCP server URL (e.g., "http://localhost:5932/mcp").
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A dict representation of the tools listing.
|
||||||
|
"""
|
||||||
|
async with streamablehttp_client(url, timeout=30) as ctx:
|
||||||
|
if len(ctx) == 2:
|
||||||
|
read, write = ctx
|
||||||
|
else:
|
||||||
|
read, write, *_ = ctx
|
||||||
|
|
||||||
|
async with ClientSession(read, write) as session:
|
||||||
|
await session.initialize()
|
||||||
|
tools = await session.list_tools()
|
||||||
|
return tools.model_dump()
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
"""
|
||||||
|
Demonstration entrypoint: list tools, then call a specified tool with a task.
|
||||||
|
"""
|
||||||
|
url = "http://localhost:5932/mcp"
|
||||||
|
tool_name = "Research-Agent" # Change to your agent tool name
|
||||||
|
task = "Summarize the latest advances in agent orchestration protocols."
|
||||||
|
|
||||||
|
# List tools
|
||||||
|
tools_info = asyncio.run(list_available_tools(url))
|
||||||
|
print("Available tools:")
|
||||||
|
print(json.dumps(tools_info, indent=2))
|
||||||
|
|
||||||
|
# Call the tool
|
||||||
|
print(f"\nCalling tool '{tool_name}' with task...\n")
|
||||||
|
result = asyncio.run(
|
||||||
|
call_agent_tool_raw(
|
||||||
|
url=url,
|
||||||
|
tool_name=tool_name,
|
||||||
|
task=task,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
print(json.dumps(result, indent=2))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
File diff suppressed because it is too large
Load Diff
Loading…
Reference in new issue