TuringsSolutions's picture
Update app.py
54e35ae verified
raw
history blame
3.51 kB
import gradio as gr
import os
import json
import numpy as np
import requests
from openai import OpenAI
import ast
def call_gpt3_5(prompt, api_key):
client = OpenAI(api_key=api_key)
try:
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a Python expert capable of constructing and executing a Swarm Neural Network (SNN). Return only the Python code for the SNN."},
{"role": "user", "content": prompt}
]
)
return response.choices[0].message.content
except Exception as e:
return f"Error calling GPT-3.5: {str(e)}"
def execute_snn(api_url, openai_api_key, num_agents, calls_per_agent, special_config):
prompt = f"""
Construct a Swarm Neural Network (SNN) in Python with the following parameters:
- API URL: {api_url}
- Number of Agents: {num_agents}
- Calls per Agent: {calls_per_agent}
- Special Configuration: {special_config if special_config else 'None'}
The SNN should:
1. Initialize the specified number of agents
2. Have each agent make the specified number of API calls
3. Process the data retrieved from the API calls
4. Implement a simple collective behavior mechanism
5. Return a dictionary with the following keys:
- 'data_summary': A summary of the data retrieved
- 'insights': Any patterns or insights derived from the collective behavior
- 'performance': Performance metrics (e.g., execution time, success rate of API calls)
Provide only the Python code to implement this SNN. The code should be fully functional and ready to execute.
"""
snn_code = call_gpt3_5(prompt, openai_api_key)
if not snn_code.startswith("Error"):
try:
# Add necessary imports to the generated code
full_code = f"""
import requests
import time
import numpy as np
{snn_code}
# Execute the SNN
snn = SwarmNeuralNetwork("{api_url}", {num_agents}, {calls_per_agent})
result = snn.execute()
print(result)
"""
# Execute the generated code
exec_globals = {}
exec(full_code, exec_globals)
# Retrieve the result from the executed code
result = exec_globals.get('result', "No result returned from SNN execution.")
return f"Results from the swarm neural network:\n\n{json.dumps(result, indent=2)}"
except Exception as e:
return f"Error executing SNN code: {str(e)}\n\nGenerated code:\n{snn_code}"
else:
return snn_code
# Define the Gradio interface
iface = gr.Interface(
fn=execute_snn,
inputs=[
gr.Textbox(label="API URL for your task"),
gr.Textbox(label="OpenAI API Key", type="password"),
gr.Number(label="Number of Agents", minimum=1, maximum=100, step=1),
gr.Number(label="Calls per Agent", minimum=1, maximum=100, step=1),
gr.Textbox(label="Special Configuration (optional)")
],
outputs="text",
title="Swarm Neural Network Simulator",
description="Enter the parameters for your Swarm Neural Network (SNN) simulation. The SNN will be constructed and executed based on your inputs.",
examples=[
["https://meowfacts.herokuapp.com/", "your-api-key-here", 3, 1, ""],
["https://api.publicapis.org/entries", "your-api-key-here", 5, 2, "category=Animals"]
]
)
# Launch the interface
iface.launch()