Python Script

Create an Autonomous AI Agent Workflow in Python

Welcome to the forefront of AI automation. This guide provides a Python script that demonstrates a powerful concept: Agentic AI. Inspired by frameworks like AutoGPT, this script simulates a multi-agent autonomous workflow where AI "digital coworkers" collaborate to solve complex problems with minimal human intervention.

This is the next evolution beyond simple chatbots. We're building an AI workforce that can plan, reason, and execute tasks, opening up a new frontier of possibilities for automation.

The Core Concepts Explained

Our script uses a simple but powerful multi-agent architecture:

How to Use This Script:

  1. Prerequisites: You need Python 3 and pip installed, plus an API key from an LLM provider like OpenAI.
  2. Save the Script: Click the "Copy Script" button below and save the code into a file named `agentic_workflow.py`.
  3. Install Dependencies: Open your terminal and run the command:
    pip install openai python-dotenv
  4. Configure API Key: Create a `.env` file and add your API key:
    OPENAI_API_KEY='sk-YourSecretAPIKeyGoesHere'
  5. Run the Workflow: In your terminal, run the script:
    python agentic_workflow.py
  6. Define Your Goal: When prompted, enter a complex goal and watch the agents work.

Why is Agentic AI a Game Changer?

This approach moves beyond simple question-and-answer. It unlocks:


import os
from openai import OpenAI
from dotenv import load_dotenv

# --- Configuration ---
load_dotenv()
API_KEY = os.getenv("OPENAI_API_KEY")
if not API_KEY:
    raise ValueError("OpenAI API key not found. Please create a .env file with OPENAI_API_KEY='your_key'")

client = OpenAI(api_key=API_KEY)
MODEL = "gpt-4o"

def run_llm(prompt, system_message):
    try:
        response = client.chat.completions.create(
            model=MODEL,
            messages=[
                {"role": "system", "content": system_message},
                {"role": "user", "content": prompt},
            ],
            temperature=0.5,
        )
        return response.choices[0].message.content
    except Exception as e:
        print(f"An error occurred: {e}")
        return None

def planner_agent(goal):
    system_message = (
        "You are a project planning AI. Break the user's goal into a numbered list of simple, "
        "executable subtasks. Each subtask must be a clear, single action. "
        "Return only the numbered list, with nothing else."
    )
    prompt = f"Create a step-by-step plan for this goal: '{goal}'"
    print("\n\033[94m[Planner Agent]\033[0m Thinking...")
    plan_str = run_llm(prompt, system_message)
    
    if plan_str:
        plan = [task.strip() for task in plan_str.split('\n') if task.strip()]
        plan = [task.split('. ', 1)[1] if '. ' in task else task for task in plan]
        print("\033[94m[Planner Agent]\033[0m I have created a plan:")
        for i, task in enumerate(plan, 1):
            print(f"  {i}. {task}")
        return plan
    return []

def executor_agent(task):
    system_message = (
        "You are an AI executor. Take this task and describe the actions to complete it "
        "and the expected outcome. Be concise."
    )
    prompt = f"Execute this task: '{task}'"
    print(f"\n\033[92m[Executor Agent]\033[0m Now executing: '{task}'")
    execution_result = run_llm(prompt, system_message)
    
    if execution_result:
        print(f"\033[92m[Executor Agent]\033[0m Result: {execution_result}")
    return execution_result

def main():
    print("\n--- Autonomous AI Agent Workflow ---")
    goal = input("Please enter your high-level goal: ")
    task_list = planner_agent(goal)

    if not task_list:
        print("\n\033[91m[Orchestrator]\033[0m The planner failed to create a plan. Exiting.")
        return

    print("\n\033[93m[Orchestrator]\033[0m Starting execution of the plan...")
    for task in task_list:
        executor_agent(task)

    print("\n\033[93m[Orchestrator]\033[0m All tasks completed.")

if __name__ == "__main__":
    main()