Skip to content

Instantly share code, notes, and snippets.

@ruvnet
Created May 18, 2024 00:27
Show Gist options
  • Select an option

  • Save ruvnet/c0acb81e02cb5c052e1def32e3f8df04 to your computer and use it in GitHub Desktop.

Select an option

Save ruvnet/c0acb81e02cb5c052e1def32e3f8df04 to your computer and use it in GitHub Desktop.
Agent Swarm Tutorial.ipynb
Display the source blob
Display the rendered blob
Raw
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/gist/ruvnet/c0acb81e02cb5c052e1def32e3f8df04/agent-swarm-tutorial.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"source": [
"**Basic SWARM Performing A Basic Function**"
],
"metadata": {
"id": "4yoYditi8cFu"
}
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "piQA_iTB8TOq",
"outputId": "99bff918-5d9f-4fd4-e962-6fc1236071b2"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Agent 3 executed. Result: 2\n",
"Agent 1 executed. Result: 3\n",
"Agent 2 executed. Result: 6\n",
"Final result: 6\n"
]
}
],
"source": [
"import random\n",
"\n",
"class Agent:\n",
" def __init__(self, name, sub_function):\n",
" self.name = name\n",
" self.sub_function = sub_function\n",
"\n",
" def execute(self, input_data):\n",
" return self.sub_function(input_data)\n",
"\n",
"def sub_function1(input_data):\n",
" # Perform sub-function 1 logic\n",
" result = input_data + 1\n",
" return result\n",
"\n",
"def sub_function2(input_data):\n",
" # Perform sub-function 2 logic\n",
" result = input_data * 2\n",
" return result\n",
"\n",
"def sub_function3(input_data):\n",
" # Perform sub-function 3 logic\n",
" result = input_data - 3\n",
" return result\n",
"\n",
"def swarm_function(input_data):\n",
" # Create agents with their respective sub-functions\n",
" agents = [\n",
" Agent(\"Agent 1\", sub_function1),\n",
" Agent(\"Agent 2\", sub_function2),\n",
" Agent(\"Agent 3\", sub_function3)\n",
" ]\n",
"\n",
" # Execute sub-functions in a random order\n",
" random.shuffle(agents)\n",
"\n",
" # Iterate over agents and execute their sub-functions\n",
" for agent in agents:\n",
" input_data = agent.execute(input_data)\n",
" print(f\"{agent.name} executed. Result: {input_data}\")\n",
"\n",
" return input_data\n",
"\n",
"# Example usage\n",
"initial_input = 5\n",
"final_result = swarm_function(initial_input)\n",
"print(f\"Final result: {final_result}\")"
]
},
{
"cell_type": "markdown",
"source": [
"**In this updated version:**\n",
"\n",
"New Sub-Functions: Additional sub-functions (sub_function4 and sub_function5) provide more varied behaviors.\n",
"\n",
"Dynamic Agent Creation: Based on the initial input, the system dynamically adds agents.\n",
"\n",
"Agent Collaboration: Demonstrated by using the results of two agents to calculate a new value, showcasing inter-agent communication and collaboration.\n",
"\n",
"Result Handling: The system stores and prints the results of each agent's execution, allowing for more complex decision-making processes."
],
"metadata": {
"id": "x_9Thmco9L40"
}
},
{
"cell_type": "code",
"source": [
"import random\n",
"\n",
"class Agent:\n",
" def __init__(self, name, sub_function):\n",
" self.name = name\n",
" self.sub_function = sub_function\n",
"\n",
" def execute(self, input_data):\n",
" return self.sub_function(input_data)\n",
"\n",
"def sub_function1(input_data):\n",
" result = input_data + 1\n",
" return result\n",
"\n",
"def sub_function2(input_data):\n",
" result = input_data * 2\n",
" return result\n",
"\n",
"def sub_function3(input_data):\n",
" result = input_data - 3\n",
" return result\n",
"\n",
"def sub_function4(input_data):\n",
" result = input_data ** 2\n",
" return result\n",
"\n",
"def sub_function5(input_data):\n",
" result = input_data / 2\n",
" return result\n",
"\n",
"def create_agents(input_data):\n",
" agents = [\n",
" Agent(\"Agent 1\", sub_function1),\n",
" Agent(\"Agent 2\", sub_function2),\n",
" Agent(\"Agent 3\", sub_function3),\n",
" ]\n",
"\n",
" # Dynamically adding more agents based on input data\n",
" if input_data > 10:\n",
" agents.append(Agent(\"Agent 4\", sub_function4))\n",
" if input_data % 2 == 0:\n",
" agents.append(Agent(\"Agent 5\", sub_function5))\n",
"\n",
" return agents\n",
"\n",
"def swarm_function(input_data):\n",
" agents = create_agents(input_data)\n",
" random.shuffle(agents)\n",
"\n",
" results = {}\n",
" for agent in agents:\n",
" output = agent.execute(input_data)\n",
" results[agent.name] = output\n",
" print(f\"{agent.name} executed. Result: {output}\")\n",
"\n",
" # Example of agents using the output of other agents\n",
" if \"Agent 4\" in results and \"Agent 5\" in results:\n",
" combined_result = results[\"Agent 4\"] + results[\"Agent 5\"]\n",
" print(f\"Combined result of Agent 4 and Agent 5: {combined_result}\")\n",
"\n",
" return results\n",
"\n",
"# Example usage\n",
"initial_input = 5\n",
"final_results = swarm_function(initial_input)\n",
"print(f\"Final results: {final_results}\")\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "eG5TGpF69Bnh",
"outputId": "ac9ae1ab-1f31-4b26-cf29-47d9b69ec8cd"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Agent 1 executed. Result: 6\n",
"Agent 2 executed. Result: 10\n",
"Agent 3 executed. Result: 2\n",
"Final results: {'Agent 1': 6, 'Agent 2': 10, 'Agent 3': 2}\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"In this more complex example, the swarm algorithm operates on a list of input data rather than a single value. The sub-functions perform various mathematical operations on the input data, such as multiplying by 2, raising to the power of 3, calculating sine and cosine values, adding random values, subtracting random integers, taking absolute values, and calculating reciprocals.\n",
"\n",
"The create_agents function has been updated to dynamically create agents based on different conditions of the input data:\n",
"\n",
"If the length of the input data is greater than 5, Agent 5 with sub_function5 is added.\n",
"If any value in the input data is negative, Agent 6 with sub_function6 is added.\n",
"If the sum of the input data is greater than 100, Agent 7 with sub_function7 is added.\n",
"If all values in the input data are non-zero, Agent 8 with sub_function8 is added.\n",
"The swarm_function now checks for additional combinations of agents and performs operations on their outputs:\n",
"\n",
"If both Agent 1 and Agent 2 are present, it combines their outputs by adding corresponding elements using a list comprehension and the zip function.\n",
"If both Agent 3 and Agent 4 are present, it combines their outputs by multiplying corresponding elements.\n",
"The example usage demonstrates running the swarm algorithm with a list of input data from 1 to 10.\n",
"\n",
"When you run this code, you will see the outputs of each agent's execution, as well as any combined results based on the presence of specific agents.\n",
"\n",
"This more complex example showcases how the swarm algorithm can handle a list of input data, perform various mathematical operations, dynamically create agents based on different conditions, and combine the outputs of agents in different ways."
],
"metadata": {
"id": "P6XKMTWE-K1_"
}
},
{
"cell_type": "code",
"source": [
"import random\n",
"import math\n",
"\n",
"class Agent:\n",
" def __init__(self, name, sub_function):\n",
" self.name = name\n",
" self.sub_function = sub_function\n",
"\n",
" def execute(self, input_data):\n",
" return self.sub_function(input_data)\n",
"\n",
"def sub_function1(input_data):\n",
" result = [x * 2 for x in input_data]\n",
" return result\n",
"\n",
"def sub_function2(input_data):\n",
" result = [x ** 3 for x in input_data]\n",
" return result\n",
"\n",
"def sub_function3(input_data):\n",
" result = [math.sin(x) for x in input_data]\n",
" return result\n",
"\n",
"def sub_function4(input_data):\n",
" result = [math.cos(x) for x in input_data]\n",
" return result\n",
"\n",
"def sub_function5(input_data):\n",
" result = [x + random.random() for x in input_data]\n",
" return result\n",
"\n",
"def sub_function6(input_data):\n",
" result = [x - random.randint(1, 10) for x in input_data]\n",
" return result\n",
"\n",
"def sub_function7(input_data):\n",
" result = [abs(x) for x in input_data]\n",
" return result\n",
"\n",
"def sub_function8(input_data):\n",
" result = [1 / (x + 1) for x in input_data]\n",
" return result\n",
"\n",
"def create_agents(input_data):\n",
" agents = [\n",
" Agent(\"Agent 1\", sub_function1),\n",
" Agent(\"Agent 2\", sub_function2),\n",
" Agent(\"Agent 3\", sub_function3),\n",
" Agent(\"Agent 4\", sub_function4),\n",
" ]\n",
"\n",
" if len(input_data) > 5:\n",
" agents.append(Agent(\"Agent 5\", sub_function5))\n",
" if any(x < 0 for x in input_data):\n",
" agents.append(Agent(\"Agent 6\", sub_function6))\n",
" if sum(input_data) > 100:\n",
" agents.append(Agent(\"Agent 7\", sub_function7))\n",
" if all(x != 0 for x in input_data):\n",
" agents.append(Agent(\"Agent 8\", sub_function8))\n",
"\n",
" return agents\n",
"\n",
"def swarm_function(input_data):\n",
" agents = create_agents(input_data)\n",
" random.shuffle(agents)\n",
"\n",
" results = {}\n",
" for agent in agents:\n",
" output = agent.execute(input_data)\n",
" results[agent.name] = output\n",
" print(f\"{agent.name} executed. Result: {output}\")\n",
"\n",
" if \"Agent 1\" in results and \"Agent 2\" in results:\n",
" combined_result = [x + y for x, y in zip(results[\"Agent 1\"], results[\"Agent 2\"])]\n",
" print(f\"Combined result of Agent 1 and Agent 2: {combined_result}\")\n",
"\n",
" if \"Agent 3\" in results and \"Agent 4\" in results:\n",
" combined_result = [x * y for x, y in zip(results[\"Agent 3\"], results[\"Agent 4\"])]\n",
" print(f\"Combined result of Agent 3 and Agent 4: {combined_result}\")\n",
"\n",
" return results\n",
"\n",
"# Example usage\n",
"initial_input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n",
"final_results = swarm_function(initial_input)\n",
"print(f\"Final results: {final_results}\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "OkiUzfln-CKh",
"outputId": "480e3be8-48aa-4f59-a12b-560c1639994d"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Agent 4 executed. Result: [0.5403023058681398, -0.4161468365471424, -0.9899924966004454, -0.6536436208636119, 0.28366218546322625, 0.960170286650366, 0.7539022543433046, -0.14550003380861354, -0.9111302618846769, -0.8390715290764524]\n",
"Agent 5 executed. Result: [1.1793177990751216, 2.9324304808428234, 3.9386136624435686, 4.176268658934219, 5.252785987177877, 6.198079991832379, 7.192136036872432, 8.479237481424645, 9.346714501019168, 10.013595150544282]\n",
"Agent 3 executed. Result: [0.8414709848078965, 0.9092974268256817, 0.1411200080598672, -0.7568024953079282, -0.9589242746631385, -0.27941549819892586, 0.6569865987187891, 0.9893582466233818, 0.4121184852417566, -0.5440211108893698]\n",
"Agent 8 executed. Result: [0.5, 0.3333333333333333, 0.25, 0.2, 0.16666666666666666, 0.14285714285714285, 0.125, 0.1111111111111111, 0.1, 0.09090909090909091]\n",
"Agent 1 executed. Result: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]\n",
"Agent 2 executed. Result: [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]\n",
"Combined result of Agent 1 and Agent 2: [3, 12, 33, 72, 135, 228, 357, 528, 747, 1020]\n",
"Combined result of Agent 3 and Agent 4: [0.4546487134128409, -0.37840124765396416, -0.13970774909946293, 0.4946791233116909, -0.2720105554446849, -0.26828645900021747, 0.4953036778474351, -0.14395165833253265, -0.375493623385838, 0.4564726253638138]\n",
"Final results: {'Agent 4': [0.5403023058681398, -0.4161468365471424, -0.9899924966004454, -0.6536436208636119, 0.28366218546322625, 0.960170286650366, 0.7539022543433046, -0.14550003380861354, -0.9111302618846769, -0.8390715290764524], 'Agent 5': [1.1793177990751216, 2.9324304808428234, 3.9386136624435686, 4.176268658934219, 5.252785987177877, 6.198079991832379, 7.192136036872432, 8.479237481424645, 9.346714501019168, 10.013595150544282], 'Agent 3': [0.8414709848078965, 0.9092974268256817, 0.1411200080598672, -0.7568024953079282, -0.9589242746631385, -0.27941549819892586, 0.6569865987187891, 0.9893582466233818, 0.4121184852417566, -0.5440211108893698], 'Agent 8': [0.5, 0.3333333333333333, 0.25, 0.2, 0.16666666666666666, 0.14285714285714285, 0.125, 0.1111111111111111, 0.1, 0.09090909090909091], 'Agent 1': [2, 4, 6, 8, 10, 12, 14, 16, 18, 20], 'Agent 2': [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]}\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"In this modified code:\n",
"\n",
"We import the requests library to make HTTP requests to the API.\n",
"The sub-functions (sub_function1, sub_function2, sub_function3) now make API calls to different endpoints of the JSONPlaceholder service:\n",
"sub_function1 fetches a todo item by ID.\n",
"sub_function2 fetches a user by ID.\n",
"sub_function3 fetches a post by ID.\n",
"The create_agents function creates three agents, each associated with one of the sub-functions.\n",
"In the swarm_function, the agents execute their respective sub-functions by making API calls with the provided input_data as the ID.\n",
"The results of each agent's API call are stored in the results dictionary.\n",
"If all the API calls are successful (i.e., all values in the results dictionary are non-empty), the code combines the results into a single dictionary called combined_result, which contains the todo, user, and post information.\n",
"The swarm_function returns the results dictionary containing the individual agent results.\n",
"The example usage demonstrates running the swarm algorithm with an input ID of 1. The agents will make API calls to fetch the corresponding todo item, user, and post with ID 1 from the JSONPlaceholder service.\n",
"\n",
"When you run this code, you will see the output of each agent's API call, as well as the combined result if all the API calls are successful."
],
"metadata": {
"id": "07i60QrAEA02"
}
},
{
"cell_type": "code",
"source": [
"!pip install requests"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "WCIVZIHPC-1o",
"outputId": "6402ab07-fd2f-4e88-c70e-d7607f54eea2"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Requirement already satisfied: requests in /usr/local/lib/python3.10/dist-packages (2.31.0)\n",
"Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests) (3.3.2)\n",
"Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests) (3.7)\n",
"Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests) (2.0.7)\n",
"Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests) (2024.2.2)\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"import random\n",
"import requests\n",
"\n",
"class Agent:\n",
" def __init__(self, name, sub_function):\n",
" self.name = name\n",
" self.sub_function = sub_function\n",
"\n",
" def execute(self, input_data):\n",
" return self.sub_function(input_data)\n",
"\n",
"def sub_function1(input_data):\n",
" url = f\"https://jsonplaceholder.typicode.com/todos/{input_data}\"\n",
" response = requests.get(url)\n",
" if response.status_code == 200:\n",
" return response.json()\n",
" else:\n",
" return None\n",
"\n",
"def sub_function2(input_data):\n",
" url = f\"https://jsonplaceholder.typicode.com/users/{input_data}\"\n",
" response = requests.get(url)\n",
" if response.status_code == 200:\n",
" return response.json()\n",
" else:\n",
" return None\n",
"\n",
"def sub_function3(input_data):\n",
" url = f\"https://jsonplaceholder.typicode.com/posts/{input_data}\"\n",
" response = requests.get(url)\n",
" if response.status_code == 200:\n",
" return response.json()\n",
" else:\n",
" return None\n",
"\n",
"def create_agents():\n",
" agents = [\n",
" Agent(\"Agent 1\", sub_function1),\n",
" Agent(\"Agent 2\", sub_function2),\n",
" Agent(\"Agent 3\", sub_function3),\n",
" ]\n",
" return agents\n",
"\n",
"def swarm_function(input_data):\n",
" agents = create_agents()\n",
" random.shuffle(agents)\n",
"\n",
" results = {}\n",
" for agent in agents:\n",
" output = agent.execute(input_data)\n",
" results[agent.name] = output\n",
" print(f\"{agent.name} executed. Result: {output}\")\n",
"\n",
" if all(results.values()):\n",
" combined_result = {\n",
" \"todo\": results[\"Agent 1\"],\n",
" \"user\": results[\"Agent 2\"],\n",
" \"post\": results[\"Agent 3\"]\n",
" }\n",
" print(f\"Combined result: {combined_result}\")\n",
"\n",
" return results\n",
"\n",
"# Example usage\n",
"input_id = 1\n",
"final_results = swarm_function(input_id)\n",
"print(f\"Final results: {final_results}\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "SOgnVwCBDhmQ",
"outputId": "b60ea6cd-a93f-455c-ea60-217f00dab557"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Agent 2 executed. Result: {'id': 1, 'name': 'Leanne Graham', 'username': 'Bret', 'email': 'Sincere@april.biz', 'address': {'street': 'Kulas Light', 'suite': 'Apt. 556', 'city': 'Gwenborough', 'zipcode': '92998-3874', 'geo': {'lat': '-37.3159', 'lng': '81.1496'}}, 'phone': '1-770-736-8031 x56442', 'website': 'hildegard.org', 'company': {'name': 'Romaguera-Crona', 'catchPhrase': 'Multi-layered client-server neural-net', 'bs': 'harness real-time e-markets'}}\n",
"Agent 1 executed. Result: {'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}\n",
"Agent 3 executed. Result: {'userId': 1, 'id': 1, 'title': 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit', 'body': 'quia et suscipit\\nsuscipit recusandae consequuntur expedita et cum\\nreprehenderit molestiae ut ut quas totam\\nnostrum rerum est autem sunt rem eveniet architecto'}\n",
"Combined result: {'todo': {'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}, 'user': {'id': 1, 'name': 'Leanne Graham', 'username': 'Bret', 'email': 'Sincere@april.biz', 'address': {'street': 'Kulas Light', 'suite': 'Apt. 556', 'city': 'Gwenborough', 'zipcode': '92998-3874', 'geo': {'lat': '-37.3159', 'lng': '81.1496'}}, 'phone': '1-770-736-8031 x56442', 'website': 'hildegard.org', 'company': {'name': 'Romaguera-Crona', 'catchPhrase': 'Multi-layered client-server neural-net', 'bs': 'harness real-time e-markets'}}, 'post': {'userId': 1, 'id': 1, 'title': 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit', 'body': 'quia et suscipit\\nsuscipit recusandae consequuntur expedita et cum\\nreprehenderit molestiae ut ut quas totam\\nnostrum rerum est autem sunt rem eveniet architecto'}}\n",
"Final results: {'Agent 2': {'id': 1, 'name': 'Leanne Graham', 'username': 'Bret', 'email': 'Sincere@april.biz', 'address': {'street': 'Kulas Light', 'suite': 'Apt. 556', 'city': 'Gwenborough', 'zipcode': '92998-3874', 'geo': {'lat': '-37.3159', 'lng': '81.1496'}}, 'phone': '1-770-736-8031 x56442', 'website': 'hildegard.org', 'company': {'name': 'Romaguera-Crona', 'catchPhrase': 'Multi-layered client-server neural-net', 'bs': 'harness real-time e-markets'}}, 'Agent 1': {'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}, 'Agent 3': {'userId': 1, 'id': 1, 'title': 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit', 'body': 'quia et suscipit\\nsuscipit recusandae consequuntur expedita et cum\\nreprehenderit molestiae ut ut quas totam\\nnostrum rerum est autem sunt rem eveniet architecto'}}\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"**Putting It All Together: Introducing API SWARM**"
],
"metadata": {
"id": "KS3zz_U-bUrx"
}
},
{
"cell_type": "code",
"source": [
"import random\n",
"import requests\n",
"import concurrent.futures\n",
"import logging\n",
"import json\n",
"\n",
"logging.basicConfig(level=logging.INFO)\n",
"\n",
"class Agent:\n",
" def __init__(self, name, endpoint, method, base_url, **kwargs):\n",
" self.name = name\n",
" self.endpoint = endpoint\n",
" self.method = method\n",
" self.base_url = base_url\n",
" self.kwargs = kwargs\n",
"\n",
" def execute(self, input_data):\n",
" url = f\"{self.base_url}{self.endpoint}/{input_data}\"\n",
" try:\n",
" response = requests.request(self.method, url, **self.kwargs)\n",
" response.raise_for_status()\n",
" return response.json()\n",
" except requests.exceptions.RequestException as e:\n",
" logging.error(f\"Error in {self.name}: {e}\")\n",
" return None\n",
"\n",
"def create_agents(base_url, endpoints, **kwargs):\n",
" agents = []\n",
" for i, endpoint in enumerate(endpoints, start=1):\n",
" agents.append(Agent(f\"GET Agent {i}\", endpoint, 'GET', base_url, **kwargs))\n",
" agents.append(Agent(f\"PUT Agent {i}\", endpoint, 'PUT', base_url, **kwargs))\n",
" return agents\n",
"\n",
"def swarm_function(base_url, endpoints, input_data, **kwargs):\n",
" agents = create_agents(base_url, endpoints, **kwargs)\n",
" random.shuffle(agents)\n",
" results = {}\n",
"\n",
" with concurrent.futures.ThreadPoolExecutor() as executor:\n",
" futures = {executor.submit(agent.execute, input_data): agent for agent in agents}\n",
" for future in concurrent.futures.as_completed(futures):\n",
" agent = futures[future]\n",
" try:\n",
" output = future.result()\n",
" results[agent.name] = output\n",
" logging.info(f\"{agent.name} executed. Result: {output}\")\n",
" except Exception as e:\n",
" logging.error(f\"Error in {agent.name}: {e}\")\n",
"\n",
" return results\n",
"\n",
"# Example usage - Using the JSONPlaceholder API\n",
"base_url = \"https://jsonplaceholder.typicode.com\"\n",
"endpoints = [\"/todos\", \"/users\", \"/posts\"]\n",
"input_id = 1\n",
"kwargs = {'timeout': 5}\n",
"\n",
"final_results = swarm_function(base_url, endpoints, input_id, **kwargs)\n",
"\n",
"print(\"Final Results:\")\n",
"for agent_name, result in final_results.items():\n",
" print(f\"\\nAgent: {agent_name}\")\n",
" print(json.dumps(result, indent=2))\n",
"\n",
"logging.info(f\"Final results: {final_results}\")"
],
"metadata": {
"id": "r0VgeNhPbT8a",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "372adf96-0e11-4947-c5ed-5f92d50e4bd1"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Final Results:\n",
"\n",
"Agent: GET Agent 3\n",
"{\n",
" \"userId\": 1,\n",
" \"id\": 1,\n",
" \"title\": \"sunt aut facere repellat provident occaecati excepturi optio reprehenderit\",\n",
" \"body\": \"quia et suscipit\\nsuscipit recusandae consequuntur expedita et cum\\nreprehenderit molestiae ut ut quas totam\\nnostrum rerum est autem sunt rem eveniet architecto\"\n",
"}\n",
"\n",
"Agent: GET Agent 1\n",
"{\n",
" \"userId\": 1,\n",
" \"id\": 1,\n",
" \"title\": \"delectus aut autem\",\n",
" \"completed\": false\n",
"}\n",
"\n",
"Agent: GET Agent 2\n",
"{\n",
" \"id\": 1,\n",
" \"name\": \"Leanne Graham\",\n",
" \"username\": \"Bret\",\n",
" \"email\": \"Sincere@april.biz\",\n",
" \"address\": {\n",
" \"street\": \"Kulas Light\",\n",
" \"suite\": \"Apt. 556\",\n",
" \"city\": \"Gwenborough\",\n",
" \"zipcode\": \"92998-3874\",\n",
" \"geo\": {\n",
" \"lat\": \"-37.3159\",\n",
" \"lng\": \"81.1496\"\n",
" }\n",
" },\n",
" \"phone\": \"1-770-736-8031 x56442\",\n",
" \"website\": \"hildegard.org\",\n",
" \"company\": {\n",
" \"name\": \"Romaguera-Crona\",\n",
" \"catchPhrase\": \"Multi-layered client-server neural-net\",\n",
" \"bs\": \"harness real-time e-markets\"\n",
" }\n",
"}\n",
"\n",
"Agent: PUT Agent 1\n",
"{\n",
" \"id\": 1\n",
"}\n",
"\n",
"Agent: PUT Agent 3\n",
"{\n",
" \"id\": 1\n",
"}\n",
"\n",
"Agent: PUT Agent 2\n",
"{\n",
" \"id\": 1\n",
"}\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"**LLM Swarm Base Function:**"
],
"metadata": {
"id": "de8OqLqO240A"
}
},
{
"cell_type": "code",
"source": [
"def llm_request_swarm(base_url, endpoints, input_data, **kwargs):\n",
" # Update the base URL if provided by the LLM\n",
" if 'update_base_url' in kwargs:\n",
" base_url = kwargs['update_base_url']\n",
" del kwargs['update_base_url']\n",
"\n",
" # Make a request to the SWARM algorithm\n",
" results = swarm_function(base_url, endpoints, input_data, **kwargs)\n",
"\n",
" return results"
],
"metadata": {
"id": "FBK-ZkQO2bYs"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"**No URL Update**"
],
"metadata": {
"id": "HZTU3Nrd3IIi"
}
},
{
"cell_type": "code",
"source": [
"base_url = \"https://jsonplaceholder.typicode.com\"\n",
"endpoints = [\"/todos\", \"/users\", \"/posts\"]\n",
"input_id = 1\n",
"kwargs = {'timeout': 5}\n",
"\n",
"results = llm_request_swarm(base_url, endpoints, input_id, **kwargs)"
],
"metadata": {
"id": "g5_2x50A3S8m"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"**With URL Update**"
],
"metadata": {
"id": "MWlsMKOT3cmS"
}
},
{
"cell_type": "code",
"source": [
"base_url = \"https://jsonplaceholder.typicode.com\"\n",
"endpoints = [\"/todos\", \"/users\", \"/posts\"]\n",
"input_id = 1\n",
"kwargs = {'timeout': 5, 'update_base_url': \"https://new-api.example.com\"}\n",
"\n",
"results = llm_request_swarm(base_url, endpoints, input_id, **kwargs)"
],
"metadata": {
"id": "fVkTeVzZ3ebN"
},
"execution_count": null,
"outputs": []
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment