Automate API Calls

Note that the first code is made by 4o and the iterations are made by 4o mini.
mail@pastecode.io avatar
unknown
plain_text
6 months ago
2.3 kB
697
No Index
import openai
import os
import time

# Replace 'your-api-key' with your actual OpenAI API key
client = openai.OpenAI(api_key='OPENAI KEY')

def call_openai_api(model, prompt):
    try:
        response = client.chat.completions.create(
            model=model,
            messages=[{"role": "user", "content": prompt}]
        )
        return response.choices[0].message.content
    except Exception as e:
        print(f"Error calling OpenAI API: {e}")
        return None

def save_code_to_file(code, iteration):
    filename = f"{iteration}.html"
    with open(filename, 'w', encoding='utf-8') as file:
        file.write(code)
    print(f"Saved code to {filename}")

def main():
    iteration = 1
    
    # Initial prompt for GPT-4o
    initial_prompt = """Create a well-commented HTML, CSS, and JavaScript code for a particle simulator web application, similar to Sandbox or Powder Game with sand particles, wall, water, stone particles, etc. The particles never dissapear, and they interact with each other. You can use a grid if it makes it easier for you. Include all code in a single file. The simulator should have basic functionality for creating and interacting with particles, and these should have physics like the game Sandbox. Only reply with the code, beginning with <!DOCTYPE html> and nothing else."""

    code = call_openai_api("gpt-4o", initial_prompt)
    if code:
        save_code_to_file(code, iteration)
    
    while True:
        iteration += 1
        
        # Prompt for GPT-4o mini to improve the code
        improve_prompt = f"""Improve the following HTML/CSS/JavaScript code for a game particle simulator. Fix any bugs or errors you detect, optimize the code, and add new functionality or features. Here's the current code:

{code}

Only reply with the improved code, beginning with <!DOCTYPE html> and nothing else."""

        improved_code = call_openai_api("gpt-4o-mini", improve_prompt)
        if improved_code:
            save_code_to_file(improved_code, iteration)
            code = improved_code
        
        # Wait for X seconds before the next iteration to avoid hitting API rate limits
        time.sleep(30)

if __name__ == "__main__":
    main()