Lesson 22 of 23 · Part 4: Multi-Agent Teams

Code: Writer & Critic Loop

Wally writes, Cora reviews, and they loop until she says APPROVED (or 3 rounds run out).

Last time: In an assembly line, one agent's answer becomes the next agent's task, carried by our code.
Today: Wally writes, Cora reviews, and they loop until APPROVED, with a safety fuse so it ends.
Source Code
1# 2_writer_critic.py
2# Wally writes, Cora reviews. They loop until Cora says APPROVED.
3from openai import OpenAI
4client = OpenAI()
5
6# Same helper as before: one agent = one API call with its own system prompt.
7def run_agent(system_prompt, task):
8    response = client.chat.completions.create(
9        model="gpt-4o-mini",
10        messages=[
11            {"role": "system", "content": system_prompt},
12            {"role": "user", "content": task},
13        ],
14    )
15    return response.choices[0].message.content
16
17# Agent 1: Wally the writer
18writer_prompt = "You are Wally, a writer. Write short, catchy poems and slogans."
19
20# Agent 2: Cora the critic
21critic_prompt = "You are Cora, a critic. Review the draft. If it is great, reply exactly APPROVED. Otherwise give ONE short tip to improve it."
22
23task = "Write a 2-line slogan for a school recycling club"
24
25# Wally writes a first draft
26draft = run_agent(writer_prompt, task)
27print("First draft:\n" + draft)
28
29# At most 3 rounds: a safety fuse, so they can't argue forever
30for round_number in range(1, 4):
31    feedback = run_agent(critic_prompt, draft)
32    print(f"\nRound {round_number} - Cora says: {feedback}")
33
34    if feedback.strip() == "APPROVED":
35        print("Cora approved it!")
36        break
37
38    # Not approved yet: Wally rewrites, using Cora's tip
39    rewrite_task = f"Task: {task}\nYour draft: {draft}\nFeedback: {feedback}\nWrite a better version."
40    draft = run_agent(writer_prompt, rewrite_task)
41    print("Wally's new draft:\n" + draft)
42
43print("\nFinal slogan:\n" + draft)

No output yet...

← Prev
1/0
Next: Boss Agent →