File size: 5,101 Bytes
6cbcd8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import os
import requests
import matplotlib.pyplot as plt
import numpy as np
import gradio as gr

# Define Agent and Swarm classes based on fractal geometry
class Agent:
    def __init__(self, id, api_key=None):
        self.id = id
        self.task = None
        self.results = None
        self.api_key = api_key

    def execute_task(self):
        if self.task:
            print(f"Agent {self.id} is making an API call to '{self.task}'")
            headers = {"Authorization": f"Bearer {self.api_key}"} if self.api_key else {}
            response = requests.get(self.task, headers=headers)
            if response.status_code == 200:
                self.results = response.json().get('data')[0]
            else:
                self.results = "Error: Unable to fetch data"
            print(f"Agent {self.id} received: {self.results}")

    def communicate(self, other_agents):
        # Communication could be extended for more complex scenarios
        pass

class Swarm:
    def __init__(self, num_agents, fractal_pattern, api_key=None):
        self.agents = [Agent(i, api_key) for i in range(num_agents)]
        self.fractal_pattern = fractal_pattern
        print(f"Swarm created with {num_agents} agents using the {fractal_pattern} pattern.")

    def assign_tasks(self, tasks):
        # Assign tasks to agents based on fractal pattern
        for i, task in enumerate(tasks):
            self.agents[i % len(self.agents)].task = task
            print(f"Task assigned to Agent {self.agents[i % len(self.agents)].id}: {task}")

    def execute(self):
        for agent in self.agents:
            agent.execute_task()
        for agent in self.agents:
            agent.communicate(self.agents)

    def gather_results(self):
        return [agent.results for agent in self.agents if agent.results]

# Generate tasks for the swarm
def generate_tasks(api_url, num_tasks):
    return [api_url] * num_tasks

# Function to plot points in a pentagonal pattern and mirror them orthogonally
def plot_pentagonal_and_mirrored(results):
    fig, ax = plt.subplots()
    ax.set_aspect('equal')

    # Define pentagon vertices
    angle = 2 * np.pi / 5
    radius = 1
    pentagon_points = np.array([(radius * np.cos(i * angle), radius * np.sin(i * angle)) for i in range(5)])

    # Plot pentagon
    for i in range(5):
        ax.plot([pentagon_points[i][0], pentagon_points[(i + 1) % 5][0]],
                [pentagon_points[i][1], pentagon_points[(i + 1) % 5][1]], 'k-')

    # Define inner points for 9-agent spread
    center = np.array([0, 0])
    points = [
        center,
        (center + pentagon_points[0]) / 2,
        (center + pentagon_points[1]) / 2,
        (center + pentagon_points[2]) / 2,
        (center + pentagon_points[3]) / 2,
        (center + pentagon_points[4]) / 2,
        (pentagon_points[0] + pentagon_points[1]) / 2,
        (pentagon_points[1] + pentagon_points[2]) / 2,
        (pentagon_points[2] + pentagon_points[3]) / 2
    ]

    # Plot points and results, along with their mirrored counterparts
    for i, point in enumerate(points[:len(results)]):
        ax.plot(point[0], point[1], 'bo')
        ax.text(point[0], point[1], results[i], fontsize=9, ha='right')

        # Mirrored points
        mirrored_x = [-point[0], point[0]]
        mirrored_y = [-point[1], point[1]]

        for mx in mirrored_x:
            for my in mirrored_y:
                if (mx, my) != (point[0], point[1]):
                    ax.plot(mx, my, 'ro')
                    ax.text(mx, my, results[i], fontsize=9, ha='right')

    plt.show()

# Function to run the swarm and plot results
def run_swarm(api_url, api_key, num_agents, num_tasks):
    # Create a swarm with a fractal pattern (Pentagonal spread)
    swarm = Swarm(num_agents=num_agents, fractal_pattern="Pentagonal", api_key=api_key)
    tasks = generate_tasks(api_url, num_tasks)
    swarm.assign_tasks(tasks)
    swarm.execute()

    # Gather results
    results = swarm.gather_results()

    # Print all results
    print("\nAll results retrieved by the swarm:")
    for i, result in enumerate(results):
        print(f"Result {i + 1}: {result}")

    # Plot the results in a pentagonal pattern with mirrored points
    if results:
        plot_pentagonal_and_mirrored(results)

    return results

# Gradio interface
def gradio_interface(api_url, api_key, num_agents, num_tasks):
    results = run_swarm(api_url, api_key, num_agents, num_tasks)
    return results

iface = gr.Interface(
    fn=gradio_interface,
    inputs=[
        gr.Textbox(label="API URL", placeholder="Enter the API URL"),
        gr.Textbox(label="API Key (Optional)", placeholder="Enter the API Key"),
        gr.Number(label="Number of Agents", value=9, precision=0),
        gr.Number(label="Number of API Calls", value=9, precision=0)
    ],
    outputs=gr.Textbox(label="Results"),
    title="Swarm API Call and Plotter",
    description="Enter the API URL, API Key (Optional), number of agents, and number of API calls. The results will be plotted in a pentagonal pattern with mirrored points."
)

iface.launch(share=True)