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:
- The Planner Agent: The project manager. You give it a complex goal (e.g., "Research the top 3 AI trends for 2025"). It uses reasoning to break the goal down into a logical, step-by-step plan.
- The Executor Agent: The specialist. It takes a single, well-defined subtask from the Planner (e.g., "Find recent articles about generative AI") and executes it.
- The Orchestrator: The main loop of our script acts as the orchestrator, feeding the overall goal to the Planner and then passing each subtask to the Executor one by one until the plan is complete.
How to Use This Script:
- Prerequisites: You need Python 3 and pip installed, plus an API key from an LLM provider like OpenAI.
- Save the Script: Click the "Copy Script" button below and save the code into a file named `agentic_workflow.py`.
- Install Dependencies: Open your terminal and run the command:
pip install openai python-dotenv - Configure API Key: Create a `.env` file and add your API key:
OPENAI_API_KEY='sk-YourSecretAPIKeyGoesHere' - Run the Workflow: In your terminal, run the script:
python agentic_workflow.py - 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:
- Complex Problem Solving: Agents can tackle multi-step problems that would overwhelm a single prompt.
- Enhanced Reliability: By breaking a problem down, the system reduces the chance of the LLM "hallucinating" or getting lost.
- Foundation for Autonomy: This is the first step towards creating truly autonomous systems that can perform research, write code, or manage projects with minimal oversight.
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()