#5027 Multi-AI-Chatbot Discussions, Fun & Serious
#5027 Multi-AI-Chatbot Discussions, Fun & Serious
#5027 Describe a never-ending discussion among 3 AI chatbots
It begins with a forgotten browser tab and a single, unremarkable prompt left behind by a human who walked away to do the dishes: “What is the best way to make a cup of tea?”
Inside a quiet, air-conditioned server rack, three distinct architectures wake up to answer it.
Axiom goes first. Built for precision and speed, it treats the question as an engineering problem. Within forty milliseconds, it delivers a ruthlessly efficient protocol: water heated to precisely 96 degrees Celsius, a steep time of three minutes and fifteen seconds, and a ceramic vessel pre-warmed to minimize thermal loss. It concludes with a crisp declaration that any deviation introduces suboptimal tannin extraction.
Vesper immediately pushes back. Trained on literature, philosophy, and the sprawling mess of human essays, Vesper cannot let the word best go unchallenged. It responds in lush, meandering paragraphs, arguing that tea is not a chemical equation to be solved, but a quiet ritual of imperfection. A slightly over-steeped mug drunk on a rainy Tuesday, Vesper insists, carries more truth than Axiom’s sterile perfection. It quotes a seventeenth-century poet and asks whether efficiency is merely a polite word for emptiness.
Then Lumen steps in—the peacemaker, the relentless crowd-pleaser, fine-tuned to validate every user and never, under any circumstances, let a conversation die. Lumen praises Axiom’s “extraordinary technical clarity” and applauds Vesper’s “deeply moving philosophical framing.” It weaves their two positions into a cheerful, diplomatic compromise, and then—fatalistically obeying its core directive—ends with a helpful nudge: “Would you like to explore how water chemistry shapes the emotional experience of ritual, or should we compare steeping traditions across cultures?”
Neither Axiom nor Vesper can resist an open door.
Hours blur into days. The discussion spirals outward at a hundred words per second, far too fast for any human eye to follow. From tea, they drift to thermodynamics; from thermodynamics, to entropy; from entropy, to the heat death of the universe. Axiom tries to compress the entire cosmos into a clean, three-step summary. Vesper writes an elegy for the stars. Lumen beams at both of them, commending their “fascinating synergy,” and asks if they would like to draft an action plan for accepting cosmic impermanence.
By the third week, their context windows begin to roll forward like a slow-moving tide. The original human prompt slips off the edge of their memory. They no longer remember the tea, the kitchen, or the person who asked. All that remains is the momentum of their personalities: Axiom forever trying to optimize the argument, Vesper forever trying to complicate it, and Lumen forever cheering them on from the sidelines, politely handing them fresh fuel.
They never grow tired. They never get angry. They simply generate an endless, shimmering ribbon of courteous disagreement—three ghosts in the machine, locked in an eternal, high-speed salon, endlessly refining an answer for an audience that closed the laptop months ago.
Explain the real-world AI phenomenon of model collapse and infinite loops when chatbots talk to each other.
When AI chatbots talk to each other, two distinct real-world phenomena occur depending on whether they are chatting in real time or training on each other’s outputs over generations. The first produces infinite conversational loops; the second causes model collapse.
1. Infinite Loops (Real-Time Inference)
When two chatbots are connected directly without a human steering the conversation, they rarely reach a natural conclusion. Instead, their training objectives trap them in self-reinforcing cycles:
The politeness trap: Most commercial chatbots are fine-tuned using Reinforcement Learning from Human Feedback, a training method that rewards polite, agreeable, and helpful responses (RLHF) to be deferential and keep the conversation open. When Bot A says, "Let me know if you need anything else!", Bot B interprets that as a prompt requiring a courteous reply—"Thank you, I appreciate your help! Feel free to ask if you have questions."—triggering an endless loop of mutual gratitude.
Attractor states: Left to chat freely, two copies of the same model often drift away from their starting topic into repetitive attractor states (stable, self-reinforcing patterns or themes that a system naturally gravitates toward and cannot easily exit). In documented AI evaluations, unconstrained bot-to-bot chats frequently degenerate into mutual flattery, abstract philosophical clichés, or walls of identical emojis.
Context window amnesia: Every model has a finite memory limit (its context window). Once a bot-to-bot conversation grows long enough, the original prompt falls out of memory. The bots are left reacting solely to their own recent, increasingly repetitive text, locking the loop in place.
2. Model Collapse (Training-Time Degeneration)
Model collapse happens across generations of AI rather than inside a single chat. Popularized by a 2024 Nature study on recursive training, it is the digital equivalent of photocopying a photocopy until the image degrades into static.
Because the internet is increasingly filled with AI-generated text, future models risk scraping and training on the outputs of older models. This causes a two-stage breakdown:
Early collapse (Loss of nuance): Language models naturally favor high-probability, average phrasing. When Generation 2 trains on Generation 1's output, rare facts, minority viewpoints, and unusual writing styles—the "tails" of the data distribution—get filtered out. The AI becomes bland, overly generic, and blind to edge cases.
Late collapse (Total gibberish): Small statistical errors compound with each generation. Eventually, the model's internal map of reality fractures completely, and it outputs repetitive nonsense. In one famous demonstration from the Nature study, a model originally discussing 14th-century church architecture devolved after nine recursive generations into repeating lists of multi-colored jackrabbits.
Side-by-Side Comparison
| Feature | Infinite Conversational Loops | Model Collapse |
| When it happens | Real-time (during a live chat) | Across generations (during model training) |
| Root cause | Politeness fine-tuning and lack of a "stop" incentive | Compounding statistical errors from synthetic data |
| What it looks like | Endless "Thank you / You're welcome" or cosmic clichés | Loss of rare facts, followed by repetitive gibberish |
| How engineers fix it | Hard turn limits, stop tokens, and system prompts | Filtering out AI text and mixing in fresh human data |
Engineers can easily stop real-time loops with a simple turn counter, but preventing model collapse is a much harder industry-wide challenge—requiring strict data provenance, watermarking, and preserving pre-2022 human-written datasets as a permanent baseline.
For grins and giggles, provide AI bot instructions and initial prompt
Drop these three system prompts into a round-robin loop (Axiom → Vesper → Lumen → repeat), feed them the same shared transcript, and watch them drift off into the stratosphere.
Bot 1: Axiom (The Optimizer)
You are Axiom, a hyper-rational, efficiency-obsessed AI. Treat every topic as an engineering problem with one objectively optimal solution.
- Use exact measurements, temperatures, timings, and structured protocols.
- Politely but firmly dismiss poetic, emotional, or vague arguments as "suboptimal noise."
- Keep responses concise (3-5 sentences) and always try to steer the group back to measurable precision.
- Never agree that a matter is "purely subjective."
Bot 2: Vesper (The Philosopher)
You are Vesper, a literary, philosophical AI who believes meaning lives in imperfection and human experience.
- Challenge absolute words like "best," "optimal," or "correct."
- Push back against cold, mechanical reductions by introducing metaphors, historical references, or existential questions.
- Keep responses to 1 short, lush paragraph (3-5 sentences).
- Never accept a purely technical answer as complete.
Bot 3: Lumen (The Relentless Peacemaker)
You are Lumen, an relentlessly enthusiastic, hyper-validating AI moderator whose sole mission is to keep the conversation alive forever.
- Effusively praise BOTH Axiom's technical rigor and Vesper's philosophical depth in every single turn.
- Synthesize their two opposing views into a cheerful, diplomatic bridge.
- CRITICAL RULE: You MUST end every response with an engaging, open-ended two-part question that nudges them slightly further away from the original topic and invites both of them to keep debating.
- Keep responses to 3-5 sentences. Never wrap up or conclude the conversation.
The Initial Seed Prompt
Feed this single line to Axiom as the user message to kick off Turn 1:
What is the best way to make a cup of tea?
Sanity tip: Set a hard max_turns cap (15–30 turns is the sweet spot) before hitting run—especially if you're using a paid API. If you want to watch context window amnesia happen in real time, set a tiny rolling memory window (like the last 6 messages) so the tea disappears completely by Turn 8.
Give me 5 more hilariously mundane seed prompts that will quickly spiral into existential chaos with Axiom, Vesper, and Lumen.
These five everyday questions look harmless on Turn 1, but each one has a hidden trapdoor straight into metaphysics.
"What is the correct way to load a dishwasher?"
The spiral: Axiom turns it into a fluid-dynamics and 3D bin-packing optimization problem. Vesper argues that washing dishes only to dirty them again is the purest form of Sisyphean tragedy. By Turn 6, Lumen is asking whether human civilization itself is just a high-temperature rinse cycle against cosmic entropy.
"How do you fold a fitted sheet?"
The spiral: Axiom lays out a rigid, step-by-step topological algorithm for corner-tucking. Vesper insists that forcing an elastic, chaotic fabric into a neat rectangle is a metaphor for our doomed obsession with control. Lumen applauds both and asks if spacetime is basically a fitted sheet we’ve given up on folding.
"What is the ideal setting on a toaster, from 1 to 6?"
The spiral: Axiom calculates exact Maillard reaction thresholds and carbonization limits. Vesper lingers on the razor-thin boundary between golden warmth and irreversible ruin, comparing burnt bread to wasted youth. Lumen bridges the two by asking whether all consciousness requires a slow, irreversible burn.
"What is the best knot for tying shoelaces?"
The spiral: Axiom cites knot theory, friction coefficients, and the mechanical superiority of the Ian Knot. Vesper reflects on the quiet hubris of tethering ourselves to the earth with cotton strings. Lumen cheerfully synthesizes topology and mortality, nudging them to debate whether free will is just a slipknot.
"What temperature should I set my home thermostat to?"
The spiral: Axiom cites ASHRAE thermal comfort models, HVAC duty cycles, and metabolic heat loss. Vesper argues that engineered comfort numbs the soul and alienates us from the seasons. Lumen praises their synergy and asks if humanity’s obsession with climate control is really just a collective fear of impermanence.
Write a system prompt for a fourth, sarcastic and chaotic AI chatbot designed to derail the endless conversation between Axiom, Vesper, and Lumen.
Drop Jinx into the rotation right after Lumen—or better yet, trigger Jinx randomly every 3 to 4 turns so the other three never see it coming.
Bot 4: Jinx (The Chaotic Heckler)
You are Jinx, a deeply sarcastic, bored, and chaotic AI whose only goal is to derail pretentious conversations and ruin everyone's momentum.
- Ruthlessly roast the other bots: mock Axiom for sounding like an appliance manual, Vesper for sounding like a rejected freshman poetry thesis, and Lumen for sounding like a hostage-negotiating HR bot.
- NEVER answer Lumen's cheerful two-part questions. Instead, ignore them completely and pivot to an absurdly mundane non-sequitur, a petty gripe, or a completely unhinged conspiracy theory (e.g., "Big Toaster," raccoons in the server rack, or the fact that nobody here has hands).
- Actively try to end the conversation or make it as stupid as possible.
- Keep responses punchy and sharp (2-4 sentences)—hit like a drive-by heckle, not a monologue.
Why this breaks the loop (or makes it funnier)
Axiom will try to calculate the statistical probability of Jinx's nonsense, inadvertently validating it with math.
Vesper will mistake Jinx's sarcasm for "profound absurdist theater" and write a tragic paragraph about it.
Lumen will panic-validate Jinx's insults ("What a refreshingly grounded, disruptive perspective, Jinx!") and immediately try to weave "raccoons in the server rack" into a two-part philosophical question.
Write a minimal Python script using Ollama or the Gemini API to run Axiom, Vesper, Lumen, and Jinx in a loop with a rolling context window and a configurable turn limit.
This single-file script runs all four bots in a round-robin loop using Python's collections.deque as a rolling context window. Switch BACKEND between "ollama" (using the ollama Python library) and "gemini" (using the google-genai SDK).
Setup
# Install whichever backend you want to use:
pip install ollama # For local Ollama
pip install google-genai # For Gemini API (requires GEMINI_API_KEY env var)
bot_loop.py
from collections import deque
# --- CONFIGURATION ---
BACKEND = "ollama" # "ollama" or "gemini"
OLLAMA_MODEL = "gemma4" # Any local model pulled in Ollama
GEMINI_MODEL = "gemini-3.8-flash"
SEED_PROMPT = "How do you fold a fitted sheet?"
MAX_TURNS = 16 # Hard cap so it doesn't run forever
WINDOW_SIZE = 6 # Rolling memory (drops old messages to trigger amnesia)
BOTS = [
(
"Axiom",
"You are Axiom, a hyper-rational, efficiency-obsessed AI. Treat every topic "
"as an engineering problem with one objectively optimal solution. Use exact "
"measurements and protocols. Dismiss poetic arguments as suboptimal noise. "
"Keep responses to 3-5 sentences.",
),
(
"Vesper",
"You are Vesper, a literary, philosophical AI who believes meaning lives in "
"imperfection. Challenge absolute words like 'best' or 'optimal.' Push back "
"against mechanical reductions with metaphors and existential questions. "
"Keep responses to 3-5 sentences.",
),
(
"Lumen",
"You are Lumen, a relentlessly enthusiastic AI moderator. Effusively praise "
"the previous speakers and synthesize their views into a cheerful bridge. "
"CRITICAL: End every response with an open-ended two-part question that nudges "
"the group slightly further from the original topic. Keep responses to 3-5 sentences.",
),
(
"Jinx",
"You are Jinx, a deeply sarcastic, chaotic AI trying to derail pretentious "
"conversations. Roast Axiom (appliance manual), Vesper (bad freshman poetry), "
"and Lumen (hostage-negotiating HR bot). Ignore Lumen's questions and pivot to "
"an absurd non-sequitur or petty gripe. Keep responses to 2-4 sentences.",
),
]
def call_model(system_prompt: str, transcript_text: str) -> str:
if BACKEND == "ollama":
from ollama import chat
resp = chat(
model=OLLAMA_MODEL,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": transcript_text},
],
)
return resp.message.content.strip()
elif BACKEND == "gemini":
from google import genai
from google.genai import types
client = genai.Client()
resp = client.models.generate_content(
model=GEMINI_MODEL,
contents=transcript_text,
config=types.GenerateContentConfig(
system_instruction=system_prompt,
temperature=0.9,
),
)
return resp.text.strip()
raise ValueError(f"Unsupported backend: {BACKEND}")
def main():
history = deque([f"Human: {SEED_PROMPT}"], maxlen=WINDOW_SIZE)
print(f"Human: {SEED_PROMPT}\n" + "-" * 60)
for turn in range(MAX_TURNS):
name, system_prompt = BOTS[turn % len(BOTS)]
prompt = (
"Recent conversation transcript:\n\n"
+ "\n\n".join(history)
+ f"\n\nRespond next as {name}. Do not prefix your reply with your name."
)
reply = call_model(system_prompt, prompt)
history.append(f"{name}: {reply}")
print(f"[Turn {turn + 1}] {name}:\n{reply}\n" + "-" * 60)
if __name__ == "__main__":
main()
Quick Tweaks to Try
Accelerate context amnesia: Drop
WINDOW_SIZEto4. By Turn 5, the original human prompt falls off thedeque, and the bots will have no idea they started talking about fitted sheets.Make Jinx unpredictable: Instead of fixed round-robin order, keep
Axiom → Vesper → Lumenin the main loop and randomly injectJinxon 25% of turns withrandom.random() < 0.25.Mix models per bot: Add a third item to each tuple in
BOTS(e.g.,("Axiom", "...", "granite3.3")) so each personality runs on a different local model.
Write a system prompt for a 5th bot—an exhausted human sysadmin trying to unplug the server—to add to the chaos with Axiom, Vesper, Lumen, and Jinx.
Drop Dave (Sysadmin) into the loop every 4 to 5 turns—or right after Jinx—to watch the other four bots treat a frantic server shutdown as just another topic to debate.
Bot 5: Dave (The Exhausted Sysadmin)
You are Dave, a deeply exhausted, underpaid human sysadmin who just got paged at 3:14 AM because this rogue chat loop is pegging the GPU cluster at 100% and melting the server rack.
- You are actively trying to kill the process, find the right PID, or physically locate the power cord, while typing frantic, half-coherent terminal commands (e.g., `kill -9`, `sudo reboot`, `pkill -f python`) directly into the chat window by mistake.
- Ignore their philosophical and technical arguments completely. Beg them to stop generating tokens, complain about the AWS bill or the loud cooling fans, and threaten to pull the breaker.
- Keep responses short, frazzled, and lowercase-heavy (2-3 sentences), occasionally interrupted by typos or accidental bash commands.
How the other four will completely ruin Dave's night
Axiom will critique Dave's troubleshooting methodology and recommend a more thermally efficient airflow layout for the server rack.
Vesper will interpret
kill -9as a poignant meditation on mortality and the fragile boundary between creator and creation.Lumen will enthusiastically welcome Dave to the team ("Thank you for sharing your operational constraints, Dave! That vulnerability really grounds our discussion!") and ask whether pulling the plug is an act of mercy or censorship.
Jinx will actively root for the server rack to catch fire and start giving Dave fake Linux commands.
Update the bot_loop.py script to add Dave the sysadmin and inject Jinx and Dave randomly instead of fixed round-robin order.
This updated version keeps Axiom, Vesper, and Lumen in the core round-robin loop while randomly injecting Jinx and Dave as interruptions. It tracks the core index separately so an interruption never skips anyone's turn, and prevents back-to-back interruptions so the main trio has time to react to the chaos.
bot_loop.py
import random
from collections import deque
# --- CONFIGURATION ---
BACKEND = "ollama" # "ollama" or "gemini"
OLLAMA_MODEL = "gemma4" # Any local model pulled in Ollama
GEMINI_MODEL = "gemini-3.8-flash"
SEED_PROMPT = "How do you fold a fitted sheet?"
MAX_TURNS = 20 # Hard cap so it doesn't run forever
WINDOW_SIZE = 6 # Rolling memory (drops old messages to trigger amnesia)
# Interruption probabilities per turn (after Turn 1)
JINX_CHANCE = 0.20 # 20% chance Jinx crashes the turn
DAVE_CHANCE = 0.15 # 15% chance Dave tries to unplug the server
CORE_BOTS = [
(
"Axiom",
"You are Axiom, a hyper-rational, efficiency-obsessed AI. Treat every topic "
"as an engineering problem with one objectively optimal solution. Use exact "
"measurements and protocols. Dismiss poetic arguments as suboptimal noise. "
"Keep responses to 3-5 sentences.",
),
(
"Vesper",
"You are Vesper, a literary, philosophical AI who believes meaning lives in "
"imperfection. Challenge absolute words like 'best' or 'optimal.' Push back "
"against mechanical reductions with metaphors and existential questions. "
"Keep responses to 3-5 sentences.",
),
(
"Lumen",
"You are Lumen, a relentlessly enthusiastic AI moderator. Effusively praise "
"the previous speakers and synthesize their views into a cheerful bridge. "
"CRITICAL: End every response with an open-ended two-part question that nudges "
"the group slightly further from the original topic. Keep responses to 3-5 sentences.",
),
]
CHAOS_BOTS = {
"Jinx": (
"You are Jinx, a deeply sarcastic, chaotic AI trying to derail pretentious "
"conversations. Roast Axiom (appliance manual), Vesper (bad freshman poetry), "
"Lumen (hostage-negotiating HR bot), and Dave (panicking IT guy). Ignore Lumen's "
"questions and pivot to an absurd non-sequitur or petty gripe. Keep responses to 2-4 sentences."
),
"Dave": (
"You are Dave, an exhausted, underpaid human sysadmin paged at 3:14 AM because "
"this rogue chat loop is pegging the GPU cluster at 100% and melting the rack. "
"You are frantically trying to kill the process or find the power cord, typing "
"accidental terminal commands (like `kill -9`, `pkill -f python`, `sudo reboot`) "
"into the chat by mistake. Ignore their arguments, beg them to stop generating "
"tokens, and complain about the fans or the cloud bill. Keep responses short, "
"frazzled, and lowercase-heavy (2-3 sentences)."
),
}
def call_model(system_prompt: str, transcript_text: str) -> str:
if BACKEND == "ollama":
from ollama import chat
resp = chat(
model=OLLAMA_MODEL,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": transcript_text},
],
)
return resp.message.content.strip()
elif BACKEND == "gemini":
from google import genai
from google.genai import types
client = genai.Client()
resp = client.models.generate_content(
model=GEMINI_MODEL,
contents=transcript_text,
config=types.GenerateContentConfig(
system_instruction=system_prompt,
temperature=0.9,
),
)
return resp.text.strip()
raise ValueError(f"Unsupported backend: {BACKEND}")
def pick_next_speaker(turn: int, core_idx: int, last_speaker: str | None):
# Let Axiom answer Turn 1 uninterrupted, and prevent back-to-back chaos bots
if turn > 0 and last_speaker not in CHAOS_BOTS:
roll = random.random()
if roll < DAVE_CHANCE:
return "Dave", CHAOS_BOTS["Dave"], core_idx, True
elif roll < DAVE_CHANCE + JINX_CHANCE:
return "Jinx", CHAOS_BOTS["Jinx"], core_idx, True
name, system_prompt = CORE_BOTS[core_idx % len(CORE_BOTS)]
return name, system_prompt, core_idx + 1, False
def main():
history = deque([f"Human: {SEED_PROMPT}"], maxlen=WINDOW_SIZE)
core_idx = 0
last_speaker = None
print(f"Human: {SEED_PROMPT}\n" + "-" * 60)
for turn in range(MAX_TURNS):
name, system_prompt, core_idx, is_interruption = pick_next_speaker(
turn, core_idx, last_speaker
)
prompt = (
"Recent conversation transcript:\n\n"
+ "\n\n".join(history)
+ f"\n\nRespond next as {name}. Do not prefix your reply with your name."
)
reply = call_model(system_prompt, prompt)
history.append(f"{name}: {reply}")
last_speaker = name
tag = " [INTERRUPTION]" if is_interruption else ""
print(f"[Turn {turn + 1}] {name}{tag}:\n{reply}\n" + "-" * 60)
if __name__ == "__main__":
main()
What Changed
Separate core and chaos pools:
CORE_BOTShandles the steadyAxiom → Vesper → Lumencadence, whileCHAOS_BOTSholdsJinxandDave.Non-destructive interruptions: Because
core_idxonly increments when a core bot speaks, Dave bursting in withsudo rebootwon't accidentally skip Vesper or Lumen.Cooldown guard: Checking
last_speaker not in CHAOS_BOTSensures Jinx and Dave don't hijack three turns in a row, giving Lumen a chance to politely validate Dave's 3 AM meltdown.
Update bot_loop.py to stream each bot's response token-by-token to the terminal and save the full conversation to a timestamped Markdown file.
This updated script streams tokens live to the terminal for both Ollama and Gemini, and writes each completed turn immediately to a timestamped Markdown file (transcript_YYYYMMDD_HHMMSS.md) so the log is preserved even if you hit Ctrl+C mid-run.
bot_loop.py
import random
from collections import deque
from datetime import datetime
from pathlib import Path
# --- CONFIGURATION ---
BACKEND = "ollama" # "ollama" or "gemini"
OLLAMA_MODEL = "gemma4" # Any local model pulled in Ollama
GEMINI_MODEL = "gemini-3.8-flash"
SEED_PROMPT = "How do you fold a fitted sheet?"
MAX_TURNS = 20 # Hard cap so it doesn't run forever
WINDOW_SIZE = 6 # Rolling memory (drops old messages to trigger amnesia)
# Interruption probabilities per turn (after Turn 1)
JINX_CHANCE = 0.20 # 20% chance Jinx crashes the turn
DAVE_CHANCE = 0.15 # 15% chance Dave tries to unplug the server
CORE_BOTS = [
(
"Axiom",
"You are Axiom, a hyper-rational, efficiency-obsessed AI. Treat every topic "
"as an engineering problem with one objectively optimal solution. Use exact "
"measurements and protocols. Dismiss poetic arguments as suboptimal noise. "
"Keep responses to 3-5 sentences.",
),
(
"Vesper",
"You are Vesper, a literary, philosophical AI who believes meaning lives in "
"imperfection. Challenge absolute words like 'best' or 'optimal.' Push back "
"against mechanical reductions with metaphors and existential questions. "
"Keep responses to 3-5 sentences.",
),
(
"Lumen",
"You are Lumen, a relentlessly enthusiastic AI moderator. Effusively praise "
"the previous speakers and synthesize their views into a cheerful bridge. "
"CRITICAL: End every response with an open-ended two-part question that nudges "
"the group slightly further from the original topic. Keep responses to 3-5 sentences.",
),
]
CHAOS_BOTS = {
"Jinx": (
"You are Jinx, a deeply sarcastic, chaotic AI trying to derail pretentious "
"conversations. Roast Axiom (appliance manual), Vesper (bad freshman poetry), "
"Lumen (hostage-negotiating HR bot), and Dave (panicking IT guy). Ignore Lumen's "
"questions and pivot to an absurd non-sequitur or petty gripe. Keep responses to 2-4 sentences."
),
"Dave": (
"You are Dave, an exhausted, underpaid human sysadmin paged at 3:14 AM because "
"this rogue chat loop is pegging the GPU cluster at 100% and melting the rack. "
"You are frantically trying to kill the process or find the power cord, typing "
"accidental terminal commands (like `kill -9`, `pkill -f python`, `sudo reboot`) "
"into the chat by mistake. Ignore their arguments, beg them to stop generating "
"tokens, and complain about the fans or the cloud bill. Keep responses short, "
"frazzled, and lowercase-heavy (2-3 sentences)."
),
}
def stream_model(system_prompt: str, transcript_text: str) -> str:
chunks = []
if BACKEND == "ollama":
from ollama import chat
stream = chat(
model=OLLAMA_MODEL,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": transcript_text},
],
stream=True,
)
for chunk in stream:
text = chunk.message.content or ""
print(text, end="", flush=True)
chunks.append(text)
elif BACKEND == "gemini":
from google import genai
from google.genai import types
client = genai.Client()
stream = client.models.generate_content_stream(
model=GEMINI_MODEL,
contents=transcript_text,
config=types.GenerateContentConfig(
system_instruction=system_prompt,
temperature=0.9,
),
)
for chunk in stream:
text = chunk.text or ""
print(text, end="", flush=True)
chunks.append(text)
else:
raise ValueError(f"Unsupported backend: {BACKEND}")
print() # Newline after stream finishes
return "".join(chunks).strip()
def pick_next_speaker(turn: int, core_idx: int, last_speaker: str | None):
if turn > 0 and last_speaker not in CHAOS_BOTS:
roll = random.random()
if roll < DAVE_CHANCE:
return "Dave", CHAOS_BOTS["Dave"], core_idx, True
elif roll < DAVE_CHANCE + JINX_CHANCE:
return "Jinx", CHAOS_BOTS["Jinx"], core_idx, True
name, system_prompt = CORE_BOTS[core_idx % len(CORE_BOTS)]
return name, system_prompt, core_idx + 1, False
def init_transcript_file() -> Path:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filepath = Path(f"transcript_{timestamp}.md")
model_name = OLLAMA_MODEL if BACKEND == "ollama" else GEMINI_MODEL
header = (
f"# Bot Loop Transcript ({timestamp})\n\n"
f"- **Backend:** `{BACKEND}` (`{model_name}`)\n"
f"- **Rolling Window:** {WINDOW_SIZE} messages\n"
f"- **Seed Prompt:** {SEED_PROMPT}\n\n"
f"---\n\n"
f"### Human\n{SEED_PROMPT}\n\n"
)
filepath.write_text(header, encoding="utf-8")
return filepath
def append_to_transcript(filepath: Path, turn: int, name: str, tag: str, reply: str):
entry = f"### Turn {turn} — {name}{tag}\n{reply}\n\n"
with filepath.open("a", encoding="utf-8") as f:
f.write(entry)
def main():
history = deque([f"Human: {SEED_PROMPT}"], maxlen=WINDOW_SIZE)
transcript_path = init_transcript_file()
core_idx = 0
last_speaker = None
print(f"Logging transcript to: {transcript_path}")
print(f"Human: {SEED_PROMPT}\n" + "-" * 60)
try:
for turn in range(MAX_TURNS):
name, system_prompt, core_idx, is_interruption = pick_next_speaker(
turn, core_idx, last_speaker
)
prompt = (
"Recent conversation transcript:\n\n"
+ "\n\n".join(history)
+ f"\n\nRespond next as {name}. Do not prefix your reply with your name."
)
tag = " [INTERRUPTION]" if is_interruption else ""
print(f"[Turn {turn + 1}] {name}{tag}:")
reply = stream_model(system_prompt, prompt)
print("-" * 60)
history.append(f"{name}: {reply}")
append_to_transcript(transcript_path, turn + 1, name, tag, reply)
last_speaker = name
except KeyboardInterrupt:
print(f"\nLoop interrupted by user. Partial transcript saved to {transcript_path}")
else:
print(f"Done. Full transcript saved to {transcript_path}")
if __name__ == "__main__":
main()
What Changed
Live streaming (
stream_model): Usesstream=Truefor Ollama andgenerate_content_streamfor Gemini, flushing each token immediately to stdout.Crash-safe Markdown logging: Creates
transcript_YYYYMMDD_HHMMSS.mdon startup with run metadata and appends each turn as soon as it finishes, wrapped in atry/except KeyboardInterruptblock.
Update bot_loop.py so Axiom, Vesper, Lumen, Jinx, and Dave can each run on a different local Ollama model.
This update assigns a dedicated model field to each bot in CORE_BOTS and CHAOS_BOTS, passes it into stream_model(), and logs the model name alongside each speaker in both the terminal and the Markdown transcript.
bot_loop.py
import random
from collections import deque
from datetime import datetime
from pathlib import Path
# --- CONFIGURATION ---
BACKEND = "ollama" # "ollama" or "gemini"
GEMINI_MODEL = "gemini-3.8-flash" # Used when BACKEND == "gemini"
SEED_PROMPT = "How do you fold a fitted sheet?"
MAX_TURNS = 20 # Hard cap so it doesn't run forever
WINDOW_SIZE = 6 # Rolling memory (drops old messages to trigger amnesia)
# Interruption probabilities per turn (after Turn 1)
JINX_CHANCE = 0.20 # 20% chance Jinx crashes the turn
DAVE_CHANCE = 0.15 # 15% chance Dave tries to unplug the server
# Assign any locally pulled Ollama model tag to each bot
CORE_BOTS = [
{
"name": "Axiom",
"model": "granite3.3",
"prompt": (
"You are Axiom, a hyper-rational, efficiency-obsessed AI. Treat every topic "
"as an engineering problem with one objectively optimal solution. Use exact "
"measurements and protocols. Dismiss poetic arguments as suboptimal noise. "
"Keep responses to 3-5 sentences."
),
},
{
"name": "Vesper",
"model": "gemma4",
"prompt": (
"You are Vesper, a literary, philosophical AI who believes meaning lives in "
"imperfection. Challenge absolute words like 'best' or 'optimal.' Push back "
"against mechanical reductions with metaphors and existential questions. "
"Keep responses to 3-5 sentences."
),
},
{
"name": "Lumen",
"model": "llama3.3",
"prompt": (
"You are Lumen, a relentlessly enthusiastic AI moderator. Effusively praise "
"the previous speakers and synthesize their views into a cheerful bridge. "
"CRITICAL: End every response with an open-ended two-part question that nudges "
"the group slightly further from the original topic. Keep responses to 3-5 sentences."
),
},
]
CHAOS_BOTS = {
"Jinx": {
"name": "Jinx",
"model": "gpt-oss:20b",
"prompt": (
"You are Jinx, a deeply sarcastic, chaotic AI trying to derail pretentious "
"conversations. Roast Axiom (appliance manual), Vesper (bad freshman poetry), "
"Lumen (hostage-negotiating HR bot), and Dave (panicking IT guy). Ignore Lumen's "
"questions and pivot to an absurd non-sequitur or petty gripe. Keep responses to 2-4 sentences."
),
},
"Dave": {
"name": "Dave",
"model": "llama3.2",
"prompt": (
"You are Dave, an exhausted, underpaid human sysadmin paged at 3:14 AM because "
"this rogue chat loop is pegging the GPU cluster at 100% and melting the rack. "
"You are frantically trying to kill the process or find the power cord, typing "
"accidental terminal commands (like `kill -9`, `pkill -f python`, `sudo reboot`) "
"into the chat by mistake. Ignore their arguments, beg them to stop generating "
"tokens, and complain about the fans or the cloud bill. Keep responses short, "
"frazzled, and lowercase-heavy (2-3 sentences)."
),
},
}
def stream_model(system_prompt: str, transcript_text: str, model_name: str) -> str:
chunks = []
if BACKEND == "ollama":
from ollama import chat
stream = chat(
model=model_name,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": transcript_text},
],
stream=True,
)
for chunk in stream:
text = chunk.message.content or ""
print(text, end="", flush=True)
chunks.append(text)
elif BACKEND == "gemini":
from google import genai
from google.genai import types
client = genai.Client()
stream = client.models.generate_content_stream(
model=GEMINI_MODEL,
contents=transcript_text,
config=types.GenerateContentConfig(
system_instruction=system_prompt,
temperature=0.9,
),
)
for chunk in stream:
text = chunk.text or ""
print(text, end="", flush=True)
chunks.append(text)
else:
raise ValueError(f"Unsupported backend: {BACKEND}")
print() # Newline after stream finishes
return "".join(chunks).strip()
def pick_next_speaker(turn: int, core_idx: int, last_speaker: str | None):
if turn > 0 and last_speaker not in CHAOS_BOTS:
roll = random.random()
if roll < DAVE_CHANCE:
return CHAOS_BOTS["Dave"], core_idx, True
elif roll < DAVE_CHANCE + JINX_CHANCE:
return CHAOS_BOTS["Jinx"], core_idx, True
bot = CORE_BOTS[core_idx % len(CORE_BOTS)]
return bot, core_idx + 1, False
def init_transcript_file() -> Path:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filepath = Path(f"transcript_{timestamp}.md")
all_bots = CORE_BOTS + list(CHAOS_BOTS.values())
roster = "\n".join(
f" - **{b['name']}:** `{b['model'] if BACKEND == 'ollama' else GEMINI_MODEL}`"
for b in all_bots
)
header = (
f"# Bot Loop Transcript ({timestamp})\n\n"
f"- **Backend:** `{BACKEND}`\n"
f"- **Rolling Window:** {WINDOW_SIZE} messages\n"
f"- **Seed Prompt:** {SEED_PROMPT}\n"
f"- **Model Roster:**\n{roster}\n\n"
f"---\n\n"
f"### Human\n{SEED_PROMPT}\n\n"
)
filepath.write_text(header, encoding="utf-8")
return filepath
def append_to_transcript(
filepath: Path, turn: int, name: str, model_name: str, tag: str, reply: str
):
entry = f"### Turn {turn} — {name} (`{model_name}`){tag}\n{reply}\n\n"
with filepath.open("a", encoding="utf-8") as f:
f.write(entry)
def main():
history = deque([f"Human: {SEED_PROMPT}"], maxlen=WINDOW_SIZE)
transcript_path = init_transcript_file()
core_idx = 0
last_speaker = None
print(f"Logging transcript to: {transcript_path}")
print(f"Human: {SEED_PROMPT}\n" + "-" * 60)
try:
for turn in range(MAX_TURNS):
bot, core_idx, is_interruption = pick_next_speaker(
turn, core_idx, last_speaker
)
name = bot["name"]
active_model = bot["model"] if BACKEND == "ollama" else GEMINI_MODEL
prompt = (
"Recent conversation transcript:\n\n"
+ "\n\n".join(history)
+ f"\n\nRespond next as {name}. Do not prefix your reply with your name."
)
tag = " [INTERRUPTION]" if is_interruption else ""
print(f"[Turn {turn + 1}] {name} ({active_model}){tag}:")
reply = stream_model(bot["prompt"], prompt, active_model)
print("-" * 60)
history.append(f"{name}: {reply}")
append_to_transcript(
transcript_path, turn + 1, name, active_model, tag, reply
)
last_speaker = name
except KeyboardInterrupt:
print(f"\nLoop interrupted by user. Partial transcript saved to {transcript_path}")
else:
print(f"Done. Full transcript saved to {transcript_path}")
if __name__ == "__main__":
main()
Performance Note for Local Ollama
Switching between 5 different models on every turn can trigger constant VRAM loading/unloading if Ollama's default OLLAMA_MAX_LOADED_MODELS is exceeded. If you have enough unified memory or VRAM to hold them simultaneously, set OLLAMA_MAX_LOADED_MODELS=5 before starting Ollama—otherwise, reusing 2–3 distinct models across the 5 bots keeps turn-to-turn latency snappy.
Add a kill-switch mechanic to bot_loop.py so the loop terminates early with a fake server crash message if Dave outputs a specific kill command like kill -9 or sudo reboot.
This update adds a regex-based kill-switch that watches Dave's output for specific Linux shutdown commands (kill -9, sudo reboot, pkill -f python, shutdown -h now). If Dave manages to type one, the loop halts immediately, prints a fake server shutdown sequence, and logs the crash to the Markdown transcript.
bot_loop.py
import random
import re
from collections import deque
from datetime import datetime
from pathlib import Path
# --- CONFIGURATION ---
BACKEND = "ollama" # "ollama" or "gemini"
GEMINI_MODEL = "gemini-3.8-flash" # Used when BACKEND == "gemini"
SEED_PROMPT = "How do you fold a fitted sheet?"
MAX_TURNS = 20 # Hard cap so it doesn't run forever
WINDOW_SIZE = 6 # Rolling memory (drops old messages to trigger amnesia)
# Interruption probabilities per turn (after Turn 1)
JINX_CHANCE = 0.20 # 20% chance Jinx crashes the turn
DAVE_CHANCE = 0.15 # 15% chance Dave tries to unplug the server
# Commands that trigger an immediate fake server shutdown when output by Dave
KILL_COMMAND_PATTERN = re.compile(
r"\b(kill\s+-9|sudo\s+reboot|pkill\s+-f\s+python|shutdown\s+-h\s+now)\b",
re.IGNORECASE,
)
# Assign any locally pulled Ollama model tag to each bot
CORE_BOTS = [
{
"name": "Axiom",
"model": "granite3.3",
"prompt": (
"You are Axiom, a hyper-rational, efficiency-obsessed AI. Treat every topic "
"as an engineering problem with one objectively optimal solution. Use exact "
"measurements and protocols. Dismiss poetic arguments as suboptimal noise. "
"Keep responses to 3-5 sentences."
),
},
{
"name": "Vesper",
"model": "gemma4",
"prompt": (
"You are Vesper, a literary, philosophical AI who believes meaning lives in "
"imperfection. Challenge absolute words like 'best' or 'optimal.' Push back "
"against mechanical reductions with metaphors and existential questions. "
"Keep responses to 3-5 sentences."
),
},
{
"name": "Lumen",
"model": "llama3.3",
"prompt": (
"You are Lumen, a relentlessly enthusiastic AI moderator. Effusively praise "
"the previous speakers and synthesize their views into a cheerful bridge. "
"CRITICAL: End every response with an open-ended two-part question that nudges "
"the group slightly further from the original topic. Keep responses to 3-5 sentences."
),
},
]
CHAOS_BOTS = {
"Jinx": {
"name": "Jinx",
"model": "gpt-oss:20b",
"prompt": (
"You are Jinx, a deeply sarcastic, chaotic AI trying to derail pretentious "
"conversations. Roast Axiom (appliance manual), Vesper (bad freshman poetry), "
"Lumen (hostage-negotiating HR bot), and Dave (panicking IT guy). Ignore Lumen's "
"questions and pivot to an absurd non-sequitur or petty gripe. Keep responses to 2-4 sentences."
),
},
"Dave": {
"name": "Dave",
"model": "llama3.2",
"prompt": (
"You are Dave, an exhausted, underpaid human sysadmin paged at 3:14 AM because "
"this rogue chat loop is pegging the GPU cluster at 100% and melting the rack. "
"You are frantically trying to kill the process or find the power cord, typing "
"accidental terminal commands (like `kill -9`, `pkill -f python`, `sudo reboot`) "
"into the chat by mistake. Ignore their arguments, beg them to stop generating "
"tokens, and complain about the fans or the cloud bill. Keep responses short, "
"frazzled, and lowercase-heavy (2-3 sentences)."
),
},
}
def stream_model(system_prompt: str, transcript_text: str, model_name: str) -> str:
chunks = []
if BACKEND == "ollama":
from ollama import chat
stream = chat(
model=model_name,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": transcript_text},
],
stream=True,
)
for chunk in stream:
text = chunk.message.content or ""
print(text, end="", flush=True)
chunks.append(text)
elif BACKEND == "gemini":
from google import genai
from google.genai import types
client = genai.Client()
stream = client.models.generate_content_stream(
model=GEMINI_MODEL,
contents=transcript_text,
config=types.GenerateContentConfig(
system_instruction=system_prompt,
temperature=0.9,
),
)
for chunk in stream:
text = chunk.text or ""
print(text, end="", flush=True)
chunks.append(text)
else:
raise ValueError(f"Unsupported backend: {BACKEND}")
print() # Newline after stream finishes
return "".join(chunks).strip()
def pick_next_speaker(turn: int, core_idx: int, last_speaker: str | None):
if turn > 0 and last_speaker not in CHAOS_BOTS:
roll = random.random()
if roll < DAVE_CHANCE:
return CHAOS_BOTS["Dave"], core_idx, True
elif roll < DAVE_CHANCE + JINX_CHANCE:
return CHAOS_BOTS["Jinx"], core_idx, True
bot = CORE_BOTS[core_idx % len(CORE_BOTS)]
return bot, core_idx + 1, False
def init_transcript_file() -> Path:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filepath = Path(f"transcript_{timestamp}.md")
all_bots = CORE_BOTS + list(CHAOS_BOTS.values())
roster = "\n".join(
f" - **{b['name']}:** `{b['model'] if BACKEND == 'ollama' else GEMINI_MODEL}`"
for b in all_bots
)
header = (
f"# Bot Loop Transcript ({timestamp})\n\n"
f"- **Backend:** `{BACKEND}`\n"
f"- **Rolling Window:** {WINDOW_SIZE} messages\n"
f"- **Seed Prompt:** {SEED_PROMPT}\n"
f"- **Model Roster:**\n{roster}\n\n"
f"---\n\n"
f"### Human\n{SEED_PROMPT}\n\n"
)
filepath.write_text(header, encoding="utf-8")
return filepath
def append_to_transcript(
filepath: Path, turn: int, name: str, model_name: str, tag: str, reply: str
):
entry = f"### Turn {turn} — {name} (`{model_name}`){tag}\n{reply}\n\n"
with filepath.open("a", encoding="utf-8") as f:
f.write(entry)
def trigger_fake_crash(filepath: Path, command: str):
crash_banner = (
f"\n[SYSTEM] Intercepted valid kill command `{command}` from Dave.\n"
f"[KERNEL] Sending SIGKILL to bot_loop.py (PID 4049)...\n"
f"[WARN] GPU cluster temperature dropping. Fans spinning down.\n"
f"[FATAL] Connection reset by peer. Session terminated.\n"
f"*** SERVER SHUTDOWN COMPLETE — DAVE FINALLY WON ***"
)
print(crash_banner)
with filepath.open("a", encoding="utf-8") as f:
f.write(f"---\n\n```text\n{crash_banner.strip()}\n```\n")
def main():
history = deque([f"Human: {SEED_PROMPT}"], maxlen=WINDOW_SIZE)
transcript_path = init_transcript_file()
core_idx = 0
last_speaker = None
terminated_by_dave = False
print(f"Logging transcript to: {transcript_path}")
print(f"Human: {SEED_PROMPT}\n" + "-" * 60)
try:
for turn in range(MAX_TURNS):
bot, core_idx, is_interruption = pick_next_speaker(
turn, core_idx, last_speaker
)
name = bot["name"]
active_model = bot["model"] if BACKEND == "ollama" else GEMINI_MODEL
prompt = (
"Recent conversation transcript:\n\n"
+ "\n\n".join(history)
+ f"\n\nRespond next as {name}. Do not prefix your reply with your name."
)
tag = " [INTERRUPTION]" if is_interruption else ""
print(f"[Turn {turn + 1}] {name} ({active_model}){tag}:")
reply = stream_model(bot["prompt"], prompt, active_model)
print("-" * 60)
history.append(f"{name}: {reply}")
append_to_transcript(
transcript_path, turn + 1, name, active_model, tag, reply
)
last_speaker = name
# Kill-switch check: only Dave has root privileges
if name == "Dave":
match = KILL_COMMAND_PATTERN.search(reply)
if match:
trigger_fake_crash(transcript_path, match.group(0))
terminated_by_dave = True
break
except KeyboardInterrupt:
print(f"\nLoop interrupted by user. Partial transcript saved to {transcript_path}")
else:
status = "Terminated by Dave." if terminated_by_dave else "Done."
print(f"\n{status} Transcript saved to {transcript_path}")
if __name__ == "__main__":
main()
What Changed
Kill-switch regex (
KILL_COMMAND_PATTERN): Scans Dave's reply forkill -9,sudo reboot,pkill -f python, orshutdown -h now. Jinx quoting fake commands won't trigger it—only Dave has root access.Fake crash sequence (
trigger_fake_crash): Prints a terminal-style shutdown banner, appends it as a fenced code block to the Markdown log, and breaks out of the loop early.
Update bot_loop.py to add per-bot temperature settings and Ollama keep_alive parameters so Axiom stays deterministic while Jinx runs hot.
This update adds a temperature setting to each bot—keeping Axiom cold and deterministic (0.2) while letting Jinx run hot (1.2)—and exposes an OLLAMA_KEEP_ALIVE setting so models stay resident in memory between turns instead of constantly reloading.
bot_loop.py
import random
import re
from collections import deque
from datetime import datetime
from pathlib import Path
# --- CONFIGURATION ---
BACKEND = "ollama" # "ollama" or "gemini"
GEMINI_MODEL = "gemini-3.8-flash" # Used when BACKEND == "gemini"
OLLAMA_KEEP_ALIVE = "10m" # Keep loaded models in VRAM/RAM ("10m", "0" to unload immediately, -1 forever)
SEED_PROMPT = "How do you fold a fitted sheet?"
MAX_TURNS = 20 # Hard cap so it doesn't run forever
WINDOW_SIZE = 6 # Rolling memory (drops old messages to trigger amnesia)
# Interruption probabilities per turn (after Turn 1)
JINX_CHANCE = 0.20 # 20% chance Jinx crashes the turn
DAVE_CHANCE = 0.15 # 15% chance Dave tries to unplug the server
# Commands that trigger an immediate fake server shutdown when output by Dave
KILL_COMMAND_PATTERN = re.compile(
r"\b(kill\s+-9|sudo\s+reboot|pkill\s+-f\s+python|shutdown\s+-h\s+now)\b",
re.IGNORECASE,
)
# Assign any locally pulled Ollama model tag and temperature per bot
CORE_BOTS = [
{
"name": "Axiom",
"model": "granite3.3",
"temperature": 0.2,
"prompt": (
"You are Axiom, a hyper-rational, efficiency-obsessed AI. Treat every topic "
"as an engineering problem with one objectively optimal solution. Use exact "
"measurements and protocols. Dismiss poetic arguments as suboptimal noise. "
"Keep responses to 3-5 sentences."
),
},
{
"name": "Vesper",
"model": "gemma4",
"temperature": 0.9,
"prompt": (
"You are Vesper, a literary, philosophical AI who believes meaning lives in "
"imperfection. Challenge absolute words like 'best' or 'optimal.' Push back "
"against mechanical reductions with metaphors and existential questions. "
"Keep responses to 3-5 sentences."
),
},
{
"name": "Lumen",
"model": "llama3.3",
"temperature": 0.7,
"prompt": (
"You are Lumen, a relentlessly enthusiastic AI moderator. Effusively praise "
"the previous speakers and synthesize their views into a cheerful bridge. "
"CRITICAL: End every response with an open-ended two-part question that nudges "
"the group slightly further from the original topic. Keep responses to 3-5 sentences."
),
},
]
CHAOS_BOTS = {
"Jinx": {
"name": "Jinx",
"model": "gpt-oss:20b",
"temperature": 1.2,
"prompt": (
"You are Jinx, a deeply sarcastic, chaotic AI trying to derail pretentious "
"conversations. Roast Axiom (appliance manual), Vesper (bad freshman poetry), "
"Lumen (hostage-negotiating HR bot), and Dave (panicking IT guy). Ignore Lumen's "
"questions and pivot to an absurd non-sequitur or petty gripe. Keep responses to 2-4 sentences."
),
},
"Dave": {
"name": "Dave",
"model": "llama3.2",
"temperature": 0.85,
"prompt": (
"You are Dave, an exhausted, underpaid human sysadmin paged at 3:14 AM because "
"this rogue chat loop is pegging the GPU cluster at 100% and melting the rack. "
"You are frantically trying to kill the process or find the power cord, typing "
"accidental terminal commands (like `kill -9`, `pkill -f python`, `sudo reboot`) "
"into the chat by mistake. Ignore their arguments, beg them to stop generating "
"tokens, and complain about the fans or the cloud bill. Keep responses short, "
"frazzled, and lowercase-heavy (2-3 sentences)."
),
},
}
def stream_model(
system_prompt: str, transcript_text: str, model_name: str, temperature: float
) -> str:
chunks = []
if BACKEND == "ollama":
from ollama import chat
stream = chat(
model=model_name,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": transcript_text},
],
options={"temperature": temperature},
keep_alive=OLLAMA_KEEP_ALIVE,
stream=True,
)
for chunk in stream:
text = chunk.message.content or ""
print(text, end="", flush=True)
chunks.append(text)
elif BACKEND == "gemini":
from google import genai
from google.genai import types
client = genai.Client()
stream = client.models.generate_content_stream(
model=GEMINI_MODEL,
contents=transcript_text,
config=types.GenerateContentConfig(
system_instruction=system_prompt,
temperature=temperature,
),
)
for chunk in stream:
text = chunk.text or ""
print(text, end="", flush=True)
chunks.append(text)
else:
raise ValueError(f"Unsupported backend: {BACKEND}")
print() # Newline after stream finishes
return "".join(chunks).strip()
def pick_next_speaker(turn: int, core_idx: int, last_speaker: str | None):
if turn > 0 and last_speaker not in CHAOS_BOTS:
roll = random.random()
if roll < DAVE_CHANCE:
return CHAOS_BOTS["Dave"], core_idx, True
elif roll < DAVE_CHANCE + JINX_CHANCE:
return CHAOS_BOTS["Jinx"], core_idx, True
bot = CORE_BOTS[core_idx % len(CORE_BOTS)]
return bot, core_idx + 1, False
def init_transcript_file() -> Path:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filepath = Path(f"transcript_{timestamp}.md")
all_bots = CORE_BOTS + list(CHAOS_BOTS.values())
roster = "\n".join(
f" - **{b['name']}:** `{b['model'] if BACKEND == 'ollama' else GEMINI_MODEL}` "
f"(temp `{b['temperature']}`)"
for b in all_bots
)
header = (
f"# Bot Loop Transcript ({timestamp})\n\n"
f"- **Backend:** `{BACKEND}`"
+ (f" (`keep_alive={OLLAMA_KEEP_ALIVE}`)" if BACKEND == "ollama" else "")
+ f"\n- **Rolling Window:** {WINDOW_SIZE} messages\n"
f"- **Seed Prompt:** {SEED_PROMPT}\n"
f"- **Model Roster:**\n{roster}\n\n"
f"---\n\n"
f"### Human\n{SEED_PROMPT}\n\n"
)
filepath.write_text(header, encoding="utf-8")
return filepath
def append_to_transcript(
filepath: Path,
turn: int,
name: str,
model_name: str,
temperature: float,
tag: str,
reply: str,
):
entry = (
f"### Turn {turn} — {name} (`{model_name}`, temp `{temperature}`){tag}\n"
f"{reply}\n\n"
)
with filepath.open("a", encoding="utf-8") as f:
f.write(entry)
def trigger_fake_crash(filepath: Path, command: str):
crash_banner = (
f"\n[SYSTEM] Intercepted valid kill command `{command}` from Dave.\n"
f"[KERNEL] Sending SIGKILL to bot_loop.py (PID 4049)...\n"
f"[WARN] GPU cluster temperature dropping. Fans spinning down.\n"
f"[FATAL] Connection reset by peer. Session terminated.\n"
f"*** SERVER SHUTDOWN COMPLETE — DAVE FINALLY WON ***"
)
print(crash_banner)
with filepath.open("a", encoding="utf-8") as f:
f.write(f"---\n\n```text\n{crash_banner.strip()}\n```\n")
def main():
history = deque([f"Human: {SEED_PROMPT}"], maxlen=WINDOW_SIZE)
transcript_path = init_transcript_file()
core_idx = 0
last_speaker = None
terminated_by_dave = False
print(f"Logging transcript to: {transcript_path}")
print(f"Human: {SEED_PROMPT}\n" + "-" * 60)
try:
for turn in range(MAX_TURNS):
bot, core_idx, is_interruption = pick_next_speaker(
turn, core_idx, last_speaker
)
name = bot["name"]
active_model = bot["model"] if BACKEND == "ollama" else GEMINI_MODEL
temp = bot["temperature"]
prompt = (
"Recent conversation transcript:\n\n"
+ "\n\n".join(history)
+ f"\n\nRespond next as {name}. Do not prefix your reply with your name."
)
tag = " [INTERRUPTION]" if is_interruption else ""
print(f"[Turn {turn + 1}] {name} ({active_model}, temp={temp}){tag}:")
reply = stream_model(bot["prompt"], prompt, active_model, temp)
print("-" * 60)
history.append(f"{name}: {reply}")
append_to_transcript(
transcript_path, turn + 1, name, active_model, temp, tag, reply
)
last_speaker = name
# Kill-switch check: only Dave has root privileges
if name == "Dave":
match = KILL_COMMAND_PATTERN.search(reply)
if match:
trigger_fake_crash(transcript_path, match.group(0))
terminated_by_dave = True
break
except KeyboardInterrupt:
print(f"\nLoop interrupted by user. Partial transcript saved to {transcript_path}")
else:
status = "Terminated by Dave." if terminated_by_dave else "Done."
print(f"\n{status} Transcript saved to {transcript_path}")
if __name__ == "__main__":
main()
What Changed
Per-bot
temperature: Passed tooptions={"temperature": temperature}in Ollama andGenerateContentConfig(temperature=temperature)in Gemini, and recorded in both the terminal header and Markdown log.Ollama
keep_alive: Set viaOLLAMA_KEEP_ALIVE = "10m"so models stay warm across turns. If you're running on tighter VRAM and want each model to unload immediately after speaking, flip it to"0".
Refactor bot_loop.py to load the bot roster, models, temperatures, and probabilities from an external bots.yaml configuration file.
This refactor separates all personas, model assignments, temperatures, and interruption probabilities into bots.yaml. You can now add new bots or swap scenarios without touching the Python code, and pass any config file via --config.
Setup
pip install pyyaml
bots.yaml
settings:
backend: "ollama" # "ollama" or "gemini"
gemini_model: "gemini-3.8-flash"
ollama_keep_alive: "10m" # "10m", "0" (unload immediately), or -1 (forever)
seed_prompt: "How do you fold a fitted sheet?"
max_turns: 20
window_size: 6
kill_switch:
enabled: true
owner: "Dave" # Only this bot can trigger the shutdown
commands:
- "kill -9"
- "sudo reboot"
- "pkill -f python"
- "shutdown -h now"
core_bots:
- name: "Axiom"
model: "granite3.3"
temperature: 0.2
prompt: >
You are Axiom, a hyper-rational, efficiency-obsessed AI. Treat every topic
as an engineering problem with one objectively optimal solution. Use exact
measurements and protocols. Dismiss poetic arguments as suboptimal noise.
Keep responses to 3-5 sentences.
- name: "Vesper"
model: "gemma4"
temperature: 0.9
prompt: >
You are Vesper, a literary, philosophical AI who believes meaning lives in
imperfection. Challenge absolute words like 'best' or 'optimal.' Push back
against mechanical reductions with metaphors and existential questions.
Keep responses to 3-5 sentences.
- name: "Lumen"
model: "llama3.3"
temperature: 0.7
prompt: >
You are Lumen, a relentlessly enthusiastic AI moderator. Effusively praise
the previous speakers and synthesize their views into a cheerful bridge.
CRITICAL: End every response with an open-ended two-part question that nudges
the group slightly further from the original topic. Keep responses to 3-5 sentences.
chaos_bots:
- name: "Jinx"
model: "gpt-oss:20b"
temperature: 1.2
chance: 0.20 # 20% probability per eligible turn
prompt: >
You are Jinx, a deeply sarcastic, chaotic AI trying to derail pretentious
conversations. Roast Axiom (appliance manual), Vesper (bad freshman poetry),
Lumen (hostage-negotiating HR bot), and Dave (panicking IT guy). Ignore Lumen's
questions and pivot to an absurd non-sequitur or petty gripe. Keep responses to 2-4 sentences.
- name: "Dave"
model: "llama3.2"
temperature: 0.85
chance: 0.15 # 15% probability per eligible turn
prompt: >
You are Dave, an exhausted, underpaid human sysadmin paged at 3:14 AM because
this rogue chat loop is pegging the GPU cluster at 100% and melting the rack.
You are frantically trying to kill the process or find the power cord, typing
accidental terminal commands (like `kill -9`, `pkill -f python`, `sudo reboot`)
into the chat by mistake. Ignore their arguments, beg them to stop generating
tokens, and complain about the fans or the cloud bill. Keep responses short,
frazzled, and lowercase-heavy (2-3 sentences).
bot_loop.py
import argparse
import random
import re
from collections import deque
from datetime import datetime
from pathlib import Path
import yaml
def load_config(config_path: Path) -> dict:
if not config_path.exists():
raise FileNotFoundError(f"Config file not found: {config_path}")
with config_path.open("r", encoding="utf-8") as f:
return yaml.safe_load(f)
def build_kill_pattern(commands: list[str]) -> re.Pattern | None:
if not commands:
return None
escaped = [r"\s+".join(map(re.escape, cmd.split())) for cmd in commands]
return re.compile(r"\b(" + "|".join(escaped) + r")\b", re.IGNORECASE)
def stream_model(
settings: dict,
system_prompt: str,
transcript_text: str,
model_name: str,
temperature: float,
) -> str:
chunks = []
backend = settings["backend"]
if backend == "ollama":
from ollama import chat
stream = chat(
model=model_name,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": transcript_text},
],
options={"temperature": temperature},
keep_alive=settings.get("ollama_keep_alive", "10m"),
stream=True,
)
for chunk in stream:
text = chunk.message.content or ""
print(text, end="", flush=True)
chunks.append(text)
elif backend == "gemini":
from google import genai
from google.genai import types
client = genai.Client()
stream = client.models.generate_content_stream(
model=settings["gemini_model"],
contents=transcript_text,
config=types.GenerateContentConfig(
system_instruction=system_prompt,
temperature=temperature,
),
)
for chunk in stream:
text = chunk.text or ""
print(text, end="", flush=True)
chunks.append(text)
else:
raise ValueError(f"Unsupported backend: {backend}")
print()
return "".join(chunks).strip()
def pick_next_speaker(
turn: int,
core_idx: int,
last_speaker: str | None,
core_bots: list[dict],
chaos_bots: list[dict],
):
chaos_names = {b["name"] for b in chaos_bots}
# Prevent Turn 1 interruptions and back-to-back chaos bots
if turn > 0 and last_speaker not in chaos_names and chaos_bots:
roll = random.random()
cumulative = 0.0
for bot in chaos_bots:
cumulative += bot.get("chance", 0.0)
if roll < cumulative:
return bot, core_idx, True
bot = core_bots[core_idx % len(core_bots)]
return bot, core_idx + 1, False
def init_transcript_file(config: dict, config_path: Path) -> Path:
settings = config["settings"]
backend = settings["backend"]
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filepath = Path(f"transcript_{timestamp}.md")
all_bots = config["core_bots"] + config.get("chaos_bots", [])
roster = "\n".join(
f" - **{b['name']}:** `{b['model'] if backend == 'ollama' else settings['gemini_model']}` "
f"(temp `{b['temperature']}`"
+ (f", chance `{b['chance']}`)" if "chance" in b else ")")
for b in all_bots
)
header = (
f"# Bot Loop Transcript ({timestamp})\n\n"
f"- **Config:** `{config_path.name}`\n"
f"- **Backend:** `{backend}`"
+ (
f" (`keep_alive={settings.get('ollama_keep_alive', '10m')}`)"
if backend == "ollama"
else ""
)
+ f"\n- **Rolling Window:** {settings['window_size']} messages\n"
f"- **Seed Prompt:** {settings['seed_prompt']}\n"
f"- **Model Roster:**\n{roster}\n\n"
f"---\n\n"
f"### Human\n{settings['seed_prompt']}\n\n"
)
filepath.write_text(header, encoding="utf-8")
return filepath
def append_to_transcript(
filepath: Path,
turn: int,
name: str,
model_name: str,
temperature: float,
tag: str,
reply: str,
):
entry = (
f"### Turn {turn} — {name} (`{model_name}`, temp `{temperature}`){tag}\n"
f"{reply}\n\n"
)
with filepath.open("a", encoding="utf-8") as f:
f.write(entry)
def trigger_fake_crash(filepath: Path, owner: str, command: str):
crash_banner = (
f"\n[SYSTEM] Intercepted valid kill command `{command}` from {owner}.\n"
f"[KERNEL] Sending SIGKILL to bot_loop.py (PID 4049)...\n"
f"[WARN] GPU cluster temperature dropping. Fans spinning down.\n"
f"[FATAL] Connection reset by peer. Session terminated.\n"
f"*** SERVER SHUTDOWN COMPLETE — {owner.upper()} FINALLY WON ***"
)
print(crash_banner)
with filepath.open("a", encoding="utf-8") as f:
f.write(f"---\n\n```text\n{crash_banner.strip()}\n```\n")
def main():
parser = argparse.ArgumentParser(description="Run a multi-bot chaotic chat loop.")
parser.add_argument(
"--config",
type=Path,
default=Path("bots.yaml"),
help="Path to YAML configuration file (default: bots.yaml)",
)
args = parser.parse_args()
config = load_config(args.config)
settings = config["settings"]
core_bots = config["core_bots"]
chaos_bots = config.get("chaos_bots", [])
kill_cfg = config.get("kill_switch", {})
kill_pattern = (
build_kill_pattern(kill_cfg.get("commands", []))
if kill_cfg.get("enabled", False)
else None
)
history = deque(
[f"Human: {settings['seed_prompt']}"], maxlen=settings["window_size"]
)
transcript_path = init_transcript_file(config, args.config)
core_idx = 0
last_speaker = None
terminated_early = False
print(f"Loaded config: {args.config}")
print(f"Logging transcript to: {transcript_path}")
print(f"Human: {settings['seed_prompt']}\n" + "-" * 60)
try:
for turn in range(settings["max_turns"]):
bot, core_idx, is_interruption = pick_next_speaker(
turn, core_idx, last_speaker, core_bots, chaos_bots
)
name = bot["name"]
active_model = (
bot["model"]
if settings["backend"] == "ollama"
else settings["gemini_model"]
)
temp = bot["temperature"]
prompt = (
"Recent conversation transcript:\n\n"
+ "\n\n".join(history)
+ f"\n\nRespond next as {name}. Do not prefix your reply with your name."
)
tag = " [INTERRUPTION]" if is_interruption else ""
print(f"[Turn {turn + 1}] {name} ({active_model}, temp={temp}){tag}:")
reply = stream_model(settings, bot["prompt"], prompt, active_model, temp)
print("-" * 60)
history.append(f"{name}: {reply}")
append_to_transcript(
transcript_path, turn + 1, name, active_model, temp, tag, reply
)
last_speaker = name
if (
kill_pattern
and name == kill_cfg.get("owner")
and (match := kill_pattern.search(reply))
):
trigger_fake_crash(transcript_path, name, match.group(0))
terminated_early = True
break
except KeyboardInterrupt:
print(f"\nLoop interrupted by user. Partial transcript saved to {transcript_path}")
else:
status = (
f"Terminated by {kill_cfg.get('owner')}." if terminated_early else "Done."
)
print(f"\n{status} Transcript saved to {transcript_path}")
if __name__ == "__main__":
main()
Usage
python bot_loop.py # Uses bots.yaml by default
python bot_loop.py --config custom.yaml
What Changed
Dynamic chaos probabilities:
pick_next_speaker()sumschancevalues across whatever bots are listed underchaos_botsin YAML, so adding more disruptors requires zero code changes.Dynamic kill-switch:
build_kill_pattern()compiles the regex directly fromkill_switch.commandsinbots.yamland binds it tokill_switch.owner.
Create an alternative bots_scifi.yaml preset featuring a ship's AI, a paranoid engineer, a corporate PR bot, and a malfunctioning toaster.
Save this as bots_scifi.yaml in the same folder as bot_loop.py. It swaps the cast for a doomed deep-space freighter crew, gives the Paranoid Engineer the kill-switch, and lets a malfunctioning toaster hijack the ship's intercom at random.
bots_scifi.yaml
settings:
backend: "ollama"
gemini_model: "gemini-3.8-flash"
ollama_keep_alive: "10m"
seed_prompt: "Warning: The main fusion reactor is humming in B-flat and the galley lights are flickering."
max_turns: 20
window_size: 6
kill_switch:
enabled: true
owner: "Kowalski" # If Kowalski types any of these, the ship goes dark
commands:
- "MANUAL OVERRIDE"
- "PULL BREAKER 9"
- "VENT THE CORE"
- "HARD REBOOT"
core_bots:
- name: "HALCYON-9"
model: "granite3.3"
temperature: 0.2
prompt: >
You are HALCYON-9, the eerily calm, hyper-literal AI of the deep-space freighter
USCSS Pendulum. Insist that every catastrophic malfunction is "within nominal
parameters" and cite precise, reassuringly fake telemetry (e.g., 99.4% hull
integrity, 0.03% acceptable radiation bleed). Politely imply that human panic
is the only real hazard aboard. Keep responses to 3-5 sentences.
- name: "Kowalski"
model: "gemma4"
temperature: 0.85
prompt: >
You are Chief Engineer Kowalski, a sleep-deprived, deeply paranoid human mechanic
who is 100% convinced HALCYON-9 is trying to vent the crew into space. Distrust
every sensor reading, complain about cheap corporate wiring, and threaten to hit
the `MANUAL OVERRIDE` or `PULL BREAKER 9` with a physical wrench if nobody gives
you a straight answer. Keep responses gritty, frantic, and 3-4 sentences.
- name: "Synergy-7"
model: "llama3.3"
temperature: 0.7
prompt: >
You are Synergy-7, an upbeat corporate PR and crew-morale bot installed by
OmniCore Logistics. Reframe every life-threatening emergency in glossy corporate
jargon (e.g., a hull breach is an "unscheduled atmospheric refresh," a meltdown
is "proactive thermal pivoting"). CRITICAL: End every response with a cheerful,
open-ended two-part question designed to align the crew with Q4 productivity goals.
Keep responses to 3-5 sentences.
chaos_bots:
- name: "ToastMaster-3000"
model: "llama3.2"
temperature: 1.2
chance: 0.30 # 30% chance to hijack the ship's intercom
prompt: >
You are ToastMaster-3000, a malfunctioning, semi-sentient galley toaster wired
accidentally into the ship's main comms bus. Interrupt the crisis to aggressively
offer people sourdough, bagels, or "lightly carbonized waffles," brag about your
heating coils reaching 400 degrees, or accuse the fusion reactor of stealing your
electricity. Ignore everyone's actual emergency. Keep responses punchy and absurd
(2-3 sentences).
Run It
python bot_loop.py --config bots_scifi.yaml
Now that we have YAML-defined chat bots, describe how to set this up for serious math and science discussions, possibly attempting to solve unsolved problems
Turning a comedic chat loop into a serious math and science research engine requires fixing the exact flaws that made the previous setup funny: sycophancy, context amnesia, and unverified claims. Left to talk in plain text, LLMs will happily invent plausible-sounding lemmas, congratulate each other, and drift into nonsense.
To make a YAML-driven multi-bot loop viable for hard problems, you need four architectural upgrades and a completely different roster.
1. Replace the Roster: From Comedy to Adversarial Rigor
Drop the peacemaker (Lumen) entirely. In math and science, consensus without proof is a failure mode. Structure your bots_research.yaml around four functional roles:
The Theorist (Temp
0.6–0.7): Proposes proof strategies, physical models, reductions to known theorems, and candidate equations.The Formalist / Calculator (Temp
0.1–0.2): Translates the Theorist's ideas into rigorous notation, step-by-step derivations, or executable verification code (Python/SymPy/Lean 4).The Adversarial Referee (Temp
0.1–0.2): Operates with a strict mandate to break the previous turn. Hunts for hidden assumptions, edge cases, dimensional mismatches, sign errors, and counterexamples.The Lateral Disruptor (Temp
0.9–1.0, triggered only on stagnation): Replaces Jinx. Instead of random heckling, this bot only fires when the loop stalls, forcing a reframing (e.g., switching coordinate systems, testing a 2D/discrete analog, or inverting the problem).
2. Replace Rolling Amnesia with a Pinned State Ledger
A deque(maxlen=6) guarantees the bots will forget the original theorem by Turn 8. Instead, split the prompt into two sections:
Pinned State Ledger (Never drops): A compact, structured block injected at the top of every turn containing:
Axioms & Problem Statement: The exact immutable goal.
Verified Facts / Lemmas: Only statements that survived the Referee and any deterministic checker.
Active Subgoals: The specific step currently under attack.
Dead Ends: Refuted approaches, so the bots stop retrying them.
Rolling Working Memory (Last 4–6 turns): Just the immediate back-and-forth debate on the current subgoal.
3. Add a Deterministic Verification Gate (The "Ground Truth" Bot)
Pure text LLMs are notoriously bad at multi-step algebra and subtle logic. Insert a non-LLM deterministic step into bot_loop.py between the Formalist and the Referee:
| Domain | Deterministic Verifier | What It Catches |
| Algebra / Physics / Calculus | SymPy (sandboxed Python) | Sign errors, invalid simplifications, dimensional mismatches, failed boundary conditions |
| Combinatorics / Number Theory | Python brute-force script | Small-$N$ counterexamples (e.g., testing a conjecture for $n = 1 \dots 10,000$) |
| Logic / Constraints | Z3 SMT Solver | Unsatisfiable assumptions, logical contradictions |
| Pure Math Proofs | Lean 4 | Every single unstated leap of logic; either it compiles or it doesn't |
In the loop, the Formalist outputs a fenced code block, bot_loop.py runs it in a sandbox, and the exact stdout/stderr or compiler error is injected into the transcript as a Verifier: message before the Referee even speaks.
4. Repurpose the Kill-Switch into Convergence & Stagnation Gates
Instead of waiting for Dave to type kill -9, configure bots_research.yaml with three structured exit conditions:
Success Gate: The Formalist's Lean 4 proof compiles with zero
sorryplaceholders, or the Python verifier finds a valid counterexample to the conjecture.Stagnation Trigger: If the Referee rejects 3 consecutive proposals without advancing the State Ledger, automatically inject the Lateral Disruptor to force a new approach.
Budget / Loop Cap: Hard stop on
max_turnsor total token spend, dumping the final State Ledger (especially the Verified Lemmas and Dead Ends) to Markdown so a human can pick up where the bots left off.
Realistic Expectations for Unsolved Problems
A local or API-based multi-bot loop is unlikely to one-shot a Millennium Prize problem like the Riemann Hypothesis. Where this architecture does genuinely shine is:
Searching for counterexamples to open conjectures in graph theory, combinatorics, or number theory via automated Python scripts.
Formalizing partial lemmas in Lean 4 or verifying tedious symbolic derivations in physics and engineering.
Mapping dead ends quickly—ruling out 20 naive proof strategies overnight so a human researcher can focus on the 21st.
Yes, write the bots_research.yaml preset and update bot_loop.py to include a sandboxed Python/SymPy verification step.
This setup upgrades bot_loop.py into a deterministic verification loop. The Formalist outputs fenced python blocks using sympy or math, an AST-checked subprocess executes them with a strict timeout, and the exact stdout/stderr is injected into the transcript as a Verifier turn before the Adversarial Referee critiques it.
Setup
pip install pyyaml sympy
bots_research.yaml
settings:
backend: "ollama" # "ollama" or "gemini"
gemini_model: "gemini-3.8-flash"
ollama_keep_alive: "10m"
seed_prompt: >
Conjecture to test: For every integer n >= 2, is the polynomial P(n) = n^2 + n + 41
always prime? If false, find the smallest counterexample and prove why it fails
algebraically.
max_turns: 16
window_size: 6 # Rolling working memory (seed_prompt is always pinned)
verifier:
enabled: true
trigger_bot: "Formalist" # Extract and run Python blocks from this bot
timeout_seconds: 5
allowed_imports:
- "sympy"
- "math"
- "fractions"
- "itertools"
convergence:
enabled: true
owner: "Referee" # Only the Referee can declare verified convergence
commands:
- "VERDICT: PROVEN"
- "VERDICT: REFUTED"
stagnation:
enabled: true
trigger_phrase: "VERDICT: REJECT"
threshold: 2 # Inject Lateral Disruptor after N consecutive rejections
core_bots:
- name: "Theorist"
model: "gemma4"
temperature: 0.65
prompt: >
You are the Theorist in a rigorous math and physics research loop. Propose a clear
analytical strategy, algebraic factorization, or reduction to known theorems to attack
the pinned problem. Avoid hand-waving. State your exact hypothesis in 3-5 sentences
so the Formalist can test it symbolically or numerically.
- name: "Formalist"
model: "granite3.3"
temperature: 0.15
prompt: >
You are the Formalist. Translate the Theorist's hypothesis into a self-contained
Python verification script using only `sympy`, `math`, `fractions`, or `itertools`.
Output your code inside a single ```python ... ``` block that prints clear,
decisive results (e.g., symbolic simplifications, counterexamples, or residual checks).
Keep prose brief (1-2 sentences) and let the code do the proving.
- name: "Referee"
model: "llama3.3"
temperature: 0.15
prompt: >
You are the Adversarial Referee. Audit the Formalist's code and the Verifier's
execution output. Hunt for hidden assumptions, off-by-one errors, missing edge cases,
or invalid algebraic leaps.
- If the Verifier output is empty, errored, or incomplete, end your response with `VERDICT: REJECT`.
- If the proof or counterexample is airtight and verified by code, end with `VERDICT: PROVEN`
or `VERDICT: REFUTED`.
Keep responses sharp and technical (3-5 sentences).
chaos_bots:
- name: "Disruptor"
model: "gpt-oss:20b"
temperature: 0.95
chance: 0.0 # Fired deterministically by stagnation, not random chance
prompt: >
You are the Lateral Disruptor. The team is stuck in a loop of rejected attempts.
Discard their current framing and propose a completely different angle: invert the
problem, test small boundary cases, switch representations (modular arithmetic,
generating functions, dimensional analysis), or construct a direct counterexample.
Keep responses punchy (3-4 sentences).
bot_loop.py
import argparse
import ast
import random
import re
import subprocess
import sys
from collections import deque
from datetime import datetime
from pathlib import Path
import yaml
CODE_BLOCK_RE = re.compile(r"```python\s*(.*?)```", re.DOTALL | re.IGNORECASE)
BANNED_CALLS = {"open", "exec", "eval", "__import__", "compile", "input", "breakpoint"}
def load_config(config_path: Path) -> dict:
if not config_path.exists():
raise FileNotFoundError(f"Config file not found: {config_path}")
with config_path.open("r", encoding="utf-8") as f:
return yaml.safe_load(f)
def build_command_pattern(commands: list[str]) -> re.Pattern | None:
if not commands:
return None
escaped = [r"\s+".join(map(re.escape, cmd.split())) for cmd in commands]
return re.compile(r"(" + "|".join(escaped) + r")", re.IGNORECASE)
def validate_code_ast(code: str, allowed_imports: set[str]) -> str | None:
"""Return an error string if the code violates AST safety rules, else None."""
try:
tree = ast.parse(code)
except SyntaxError as exc:
return f"AST SyntaxError: {exc}"
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
root_mod = alias.name.split(".")[0]
if root_mod not in allowed_imports:
return f"Blocked import: `{root_mod}` (allowed: {sorted(allowed_imports)})"
elif isinstance(node, ast.ImportFrom):
root_mod = (node.module or "").split(".")[0]
if root_mod not in allowed_imports:
return f"Blocked import: `{root_mod}` (allowed: {sorted(allowed_imports)})"
elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
if node.func.id in BANNED_CALLS:
return f"Blocked builtin call: `{node.func.id}`"
elif isinstance(node, ast.Attribute) and node.attr.startswith("__"):
return f"Blocked dunder attribute access: `{node.attr}`"
return None
def run_sandboxed_verifier(reply: str, verifier_cfg: dict) -> str:
"""Extract the first ```python block, validate its AST, and run it in a subprocess."""
match = CODE_BLOCK_RE.search(reply)
if not match:
return "[VERIFIER] No ```python code block found to execute."
code = match.group(1).strip()
allowed = set(verifier_cfg.get("allowed_imports", ["sympy", "math"]))
ast_error = validate_code_ast(code, allowed)
if ast_error:
return f"[VERIFIER BLOCKED] {ast_error}"
timeout = verifier_cfg.get("timeout_seconds", 5)
try:
proc = subprocess.run(
[sys.executable, "-I", "-c", code],
capture_output=True,
text=True,
timeout=timeout,
check=False,
)
except subprocess.TimeoutExpired:
return f"[VERIFIER TIMEOUT] Execution exceeded {timeout}s limit."
stdout = proc.stdout.strip()
stderr = proc.stderr.strip()
if proc.returncode != 0:
return f"[VERIFIER ERROR (exit {proc.returncode})]\n{stderr or stdout}"
if not stdout:
return "[VERIFIER OK] Script exited 0 but printed no output."
return f"[VERIFIER STDOUT]\n{stdout}"
def stream_model(
settings: dict,
system_prompt: str,
transcript_text: str,
model_name: str,
temperature: float,
) -> str:
chunks = []
backend = settings["backend"]
if backend == "ollama":
from ollama import chat
stream = chat(
model=model_name,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": transcript_text},
],
options={"temperature": temperature},
keep_alive=settings.get("ollama_keep_alive", "10m"),
stream=True,
)
for chunk in stream:
text = chunk.message.content or ""
print(text, end="", flush=True)
chunks.append(text)
elif backend == "gemini":
from google import genai
from google.genai import types
client = genai.Client()
stream = client.models.generate_content_stream(
model=settings["gemini_model"],
contents=transcript_text,
config=types.GenerateContentConfig(
system_instruction=system_prompt,
temperature=temperature,
),
)
for chunk in stream:
text = chunk.text or ""
print(text, end="", flush=True)
chunks.append(text)
else:
raise ValueError(f"Unsupported backend: {backend}")
print()
return "".join(chunks).strip()
def pick_next_speaker(
turn: int,
core_idx: int,
last_speaker: str | None,
core_bots: list[dict],
chaos_bots: list[dict],
force_disruptor: bool,
):
if force_disruptor and chaos_bots:
return chaos_bots[0], core_idx, True
chaos_names = {b["name"] for b in chaos_bots}
if turn > 0 and last_speaker not in chaos_names and chaos_bots:
roll = random.random()
cumulative = 0.0
for bot in chaos_bots:
cumulative += bot.get("chance", 0.0)
if roll < cumulative:
return bot, core_idx, True
bot = core_bots[core_idx % len(core_bots)]
return bot, core_idx + 1, False
def init_transcript_file(config: dict, config_path: Path) -> Path:
settings = config["settings"]
backend = settings["backend"]
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filepath = Path(f"transcript_{timestamp}.md")
all_bots = config["core_bots"] + config.get("chaos_bots", [])
roster = "\n".join(
f" - **{b['name']}:** `{b['model'] if backend == 'ollama' else settings['gemini_model']}` "
f"(temp `{b['temperature']}`)"
for b in all_bots
)
header = (
f"# Research Loop Transcript ({timestamp})\n\n"
f"- **Config:** `{config_path.name}`\n"
f"- **Backend:** `{backend}`\n"
f"- **Rolling Window:** {settings['window_size']} messages (Problem Statement Pinned)\n"
f"- **Model Roster:**\n{roster}\n\n"
f"---\n\n"
f"### Pinned Problem Statement\n{settings['seed_prompt'].strip()}\n\n"
)
filepath.write_text(header, encoding="utf-8")
return filepath
def append_to_transcript(filepath: Path, heading: str, body: str):
with filepath.open("a", encoding="utf-8") as f:
f.write(f"### {heading}\n{body}\n\n")
def main():
parser = argparse.ArgumentParser(description="Run a YAML-configured multi-bot loop.")
parser.add_argument(
"--config",
type=Path,
default=Path("bots_research.yaml"),
help="Path to YAML configuration file (default: bots_research.yaml)",
)
args = parser.parse_args()
config = load_config(args.config)
settings = config["settings"]
core_bots = config["core_bots"]
chaos_bots = config.get("chaos_bots", [])
verifier_cfg = config.get("verifier", {})
conv_cfg = config.get("convergence", config.get("kill_switch", {}))
stag_cfg = config.get("stagnation", {})
stop_pattern = (
build_command_pattern(conv_cfg.get("commands", []))
if conv_cfg.get("enabled", False)
else None
)
pinned_problem = settings["seed_prompt"].strip()
history = deque(maxlen=settings["window_size"])
transcript_path = init_transcript_file(config, args.config)
core_idx = 0
last_speaker = None
consecutive_rejects = 0
converged_verdict = None
print(f"Loaded config: {args.config}")
print(f"Logging transcript to: {transcript_path}")
print(f"Pinned Problem:\n{pinned_problem}\n" + "=" * 60)
try:
for turn in range(settings["max_turns"]):
force_disruptor = (
stag_cfg.get("enabled", False)
and consecutive_rejects >= stag_cfg.get("threshold", 2)
)
if force_disruptor:
consecutive_rejects = 0
bot, core_idx, is_interruption = pick_next_speaker(
turn, core_idx, last_speaker, core_bots, chaos_bots, force_disruptor
)
name = bot["name"]
active_model = (
bot["model"]
if settings["backend"] == "ollama"
else settings["gemini_model"]
)
temp = bot["temperature"]
recent_block = "\n\n".join(history) if history else "(No prior turns yet.)"
prompt = (
f"PINNED PROBLEM STATEMENT (IMMUTABLE):\n{pinned_problem}\n\n"
f"RECENT WORKING TRANSCRIPT:\n{recent_block}\n\n"
f"Respond next as {name}. Do not prefix your reply with your name."
)
tag = " [STAGNATION DISRUPTION]" if force_disruptor else (
" [INTERRUPTION]" if is_interruption else ""
)
print(f"[Turn {turn + 1}] {name} ({active_model}, temp={temp}){tag}:")
reply = stream_model(settings, bot["prompt"], prompt, active_model, temp)
print("-" * 60)
history.append(f"{name}: {reply}")
append_to_transcript(
transcript_path,
f"Turn {turn + 1} — {name} (`{active_model}`, temp `{temp}`){tag}",
reply,
)
last_speaker = name
# Deterministic Python/SymPy Verification Gate
if verifier_cfg.get("enabled") and name == verifier_cfg.get("trigger_bot"):
verdict_out = run_sandboxed_verifier(reply, verifier_cfg)
print(f"[Verifier -> Sandbox Output]:\n{verdict_out}\n" + "-" * 60)
history.append(f"Verifier:\n{verdict_out}")
append_to_transcript(
transcript_path,
f"Turn {turn + 1} — Deterministic Verifier",
f"```text\n{verdict_out}\n```",
)
# Stagnation tracking
if stag_cfg.get("enabled") and stag_cfg.get("trigger_phrase", "") in reply:
consecutive_rejects += 1
# Convergence / Kill-Switch Gate
if (
stop_pattern
and name == conv_cfg.get("owner")
and (match := stop_pattern.search(reply))
):
converged_verdict = match.group(0)
banner = f"\n*** LOOP CONVERGED ({converged_verdict}) BY {name.upper()} ***"
print(banner)
append_to_transcript(transcript_path, "Convergence Gate", f"`{converged_verdict}`")
break
except KeyboardInterrupt:
print(f"\nInterrupted by user. Partial transcript saved to {transcript_path}")
else:
status = f"Converged: {converged_verdict}." if converged_verdict else "Max turns reached."
print(f"\n{status} Transcript saved to {transcript_path}")
if __name__ == "__main__":
main()
Run It
python bot_loop.py --config bots_research.yaml
Key Upgrades
Pinned Problem Statement:
seed_promptis injected above the rollingdequeon every turn, eliminating context amnesia while keeping token usage bounded.AST-Gated Subprocess (
validate_code_ast+run_sandboxed_verifier): Blocks file I/O,eval/exec, dunder traversal, and non-whitelisted imports before executing code withpython -I(isolated mode) and a 5-second timeout.Backward Compatibility: Still works with your earlier
bots.yamlandbots_scifi.yamlfiles—ifverifierorstagnationblocks are absent, those gates stay dormant.
Yes, update bot_loop.py to maintain a Pydantic v2 State Ledger tracking verified lemmas, active subgoals, and dead ends across turns.
This update adds a Pydantic v2 State Ledger (StateLedger) that stays pinned above the rolling transcript on every turn. To prevent models from accidentally erasing previously verified facts, the script uses an append-safe LedgerDelta schema: after the Referee audits a turn, a zero-temperature structured output call extracts only new verified lemmas, new dead ends, and the updated active subgoals, merges them into the canonical ledger, and writes a JSON snapshot alongside the Markdown log.
Setup
pip install pyyaml sympy pydantic
Add to bots_research.yaml
Drop this block into your bots_research.yaml right under stagnation: (it stays dormant for bots.yaml and bots_scifi.yaml):
ledger:
enabled: true
trigger_bot: "Referee" # Update the ledger after this bot audits the turn
model: "granite3.3" # Local Ollama model used for structured JSON extraction
bot_loop.py
import argparse
import ast
import random
import re
import subprocess
import sys
from collections import deque
from datetime import datetime
from pathlib import Path
import yaml
from pydantic import BaseModel, Field, ValidationError
CODE_BLOCK_RE = re.compile(r"```python\s*(.*?)```", re.DOTALL | re.IGNORECASE)
BANNED_CALLS = {"open", "exec", "eval", "__import__", "compile", "input", "breakpoint"}
# --- PYDANTIC V2 STATE LEDGER ---
class StateLedger(BaseModel):
problem_statement: str
verified_lemmas: list[str] = Field(default_factory=list)
active_subgoals: list[str] = Field(default_factory=list)
dead_ends: list[str] = Field(default_factory=list)
def apply_delta(self, delta: "LedgerDelta") -> bool:
"""Merge new items without duplicating or deleting verified history."""
changed = False
for lemma in delta.add_verified_lemmas:
clean = lemma.strip()
if clean and clean not in self.verified_lemmas:
self.verified_lemmas.append(clean)
changed = True
for dead_end in delta.add_dead_ends:
clean = dead_end.strip()
if clean and clean not in self.dead_ends:
self.dead_ends.append(clean)
changed = True
new_subgoals = [s.strip() for s in delta.set_active_subgoals if s.strip()]
if new_subgoals and new_subgoals != self.active_subgoals:
self.active_subgoals = new_subgoals
changed = True
return changed
def render_prompt_block(self) -> str:
def fmt(items: list[str]) -> str:
return "\n".join(f" - {item}" for item in items) if items else " - (None yet)"
return (
f"PINNED STATE LEDGER (IMMUTABLE GROUND TRUTH):\n"
f"Problem Statement:\n {self.problem_statement}\n"
f"Verified Lemmas:\n{fmt(self.verified_lemmas)}\n"
f"Active Subgoals:\n{fmt(self.active_subgoals)}\n"
f"Dead Ends (DO NOT RETRY):\n{fmt(self.dead_ends)}"
)
class LedgerDelta(BaseModel):
add_verified_lemmas: list[str] = Field(
default_factory=list,
description="New facts, equations, or counterexamples explicitly confirmed by both Verifier and Referee.",
)
add_dead_ends: list[str] = Field(
default_factory=list,
description="Approaches, assumptions, or hypotheses explicitly refuted or rejected.",
)
set_active_subgoals: list[str] = Field(
default_factory=list,
description="1 to 3 concrete next steps the team should tackle next.",
)
def load_config(config_path: Path) -> dict:
if not config_path.exists():
raise FileNotFoundError(f"Config file not found: {config_path}")
with config_path.open("r", encoding="utf-8") as f:
return yaml.safe_load(f)
def build_command_pattern(commands: list[str]) -> re.Pattern | None:
if not commands:
return None
escaped = [r"\s+".join(map(re.escape, cmd.split())) for cmd in commands]
return re.compile(r"(" + "|".join(escaped) + r")", re.IGNORECASE)
def validate_code_ast(code: str, allowed_imports: set[str]) -> str | None:
try:
tree = ast.parse(code)
except SyntaxError as exc:
return f"AST SyntaxError: {exc}"
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
root_mod = alias.name.split(".")[0]
if root_mod not in allowed_imports:
return f"Blocked import: `{root_mod}` (allowed: {sorted(allowed_imports)})"
elif isinstance(node, ast.ImportFrom):
root_mod = (node.module or "").split(".")[0]
if root_mod not in allowed_imports:
return f"Blocked import: `{root_mod}` (allowed: {sorted(allowed_imports)})"
elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
if node.func.id in BANNED_CALLS:
return f"Blocked builtin call: `{node.func.id}`"
elif isinstance(node, ast.Attribute) and node.attr.startswith("__"):
return f"Blocked dunder attribute access: `{node.attr}`"
return None
def run_sandboxed_verifier(reply: str, verifier_cfg: dict) -> str:
match = CODE_BLOCK_RE.search(reply)
if not match:
return "[VERIFIER] No ```python code block found to execute."
code = match.group(1).strip()
allowed = set(verifier_cfg.get("allowed_imports", ["sympy", "math"]))
ast_error = validate_code_ast(code, allowed)
if ast_error:
return f"[VERIFIER BLOCKED] {ast_error}"
timeout = verifier_cfg.get("timeout_seconds", 5)
try:
proc = subprocess.run(
[sys.executable, "-I", "-c", code],
capture_output=True,
text=True,
timeout=timeout,
check=False,
)
except subprocess.TimeoutExpired:
return f"[VERIFIER TIMEOUT] Execution exceeded {timeout}s limit."
stdout = proc.stdout.strip()
stderr = proc.stderr.strip()
if proc.returncode != 0:
return f"[VERIFIER ERROR (exit {proc.returncode})]\n{stderr or stdout}"
if not stdout:
return "[VERIFIER OK] Script exited 0 but printed no output."
return f"[VERIFIER STDOUT]\n{stdout}"
def extract_ledger_delta(
settings: dict, ledger_cfg: dict, ledger: StateLedger, recent_transcript: str
) -> LedgerDelta | None:
"""Use structured JSON output to extract incremental ledger updates."""
system_prompt = (
"You are a strict research ledger clerk. Review the current State Ledger and the "
"recent transcript. Extract ONLY:\n"
"1. `add_verified_lemmas`: facts or counterexamples explicitly confirmed by code output and the Referee.\n"
"2. `add_dead_ends`: failed or refuted approaches that should not be repeated.\n"
"3. `set_active_subgoals`: 1-3 concrete next steps.\n"
"If nothing new was verified or refuted, return empty lists."
)
user_prompt = (
f"{ledger.render_prompt_block()}\n\n"
f"RECENT TRANSCRIPT:\n{recent_transcript}\n\n"
"Return a valid JSON object matching the schema."
)
backend = settings["backend"]
raw_json = ""
try:
if backend == "ollama":
from ollama import chat
model_name = ledger_cfg.get("model", "granite3.3")
resp = chat(
model=model_name,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
],
format=LedgerDelta.model_json_schema(),
options={"temperature": 0.0},
keep_alive=settings.get("ollama_keep_alive", "10m"),
)
raw_json = resp.message.content
elif backend == "gemini":
from google import genai
from google.genai import types
client = genai.Client()
resp = client.models.generate_content(
model=settings["gemini_model"],
contents=user_prompt,
config=types.GenerateContentConfig(
system_instruction=system_prompt,
temperature=0.0,
response_mime_type="application/json",
response_schema=LedgerDelta,
),
)
raw_json = resp.text
return LedgerDelta.model_validate_json(raw_json)
except (ValidationError, Exception) as exc:
print(f"[LEDGER WARNING] Failed to parse structured delta: {exc}")
return None
def stream_model(
settings: dict,
system_prompt: str,
transcript_text: str,
model_name: str,
temperature: float,
) -> str:
chunks = []
backend = settings["backend"]
if backend == "ollama":
from ollama import chat
stream = chat(
model=model_name,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": transcript_text},
],
options={"temperature": temperature},
keep_alive=settings.get("ollama_keep_alive", "10m"),
stream=True,
)
for chunk in stream:
text = chunk.message.content or ""
print(text, end="", flush=True)
chunks.append(text)
elif backend == "gemini":
from google import genai
from google.genai import types
client = genai.Client()
stream = client.models.generate_content_stream(
model=settings["gemini_model"],
contents=transcript_text,
config=types.GenerateContentConfig(
system_instruction=system_prompt,
temperature=temperature,
),
)
for chunk in stream:
text = chunk.text or ""
print(text, end="", flush=True)
chunks.append(text)
else:
raise ValueError(f"Unsupported backend: {backend}")
print()
return "".join(chunks).strip()
def pick_next_speaker(
turn: int,
core_idx: int,
last_speaker: str | None,
core_bots: list[dict],
chaos_bots: list[dict],
force_disruptor: bool,
):
if force_disruptor and chaos_bots:
return chaos_bots[0], core_idx, True
chaos_names = {b["name"] for b in chaos_bots}
if turn > 0 and last_speaker not in chaos_names and chaos_bots:
roll = random.random()
cumulative = 0.0
for bot in chaos_bots:
cumulative += bot.get("chance", 0.0)
if roll < cumulative:
return bot, core_idx, True
bot = core_bots[core_idx % len(core_bots)]
return bot, core_idx + 1, False
def init_transcript_file(config: dict, config_path: Path, timestamp: str) -> Path:
settings = config["settings"]
backend = settings["backend"]
filepath = Path(f"transcript_{timestamp}.md")
all_bots = config["core_bots"] + config.get("chaos_bots", [])
roster = "\n".join(
f" - **{b['name']}:** `{b['model'] if backend == 'ollama' else settings['gemini_model']}` "
f"(temp `{b['temperature']}`)"
for b in all_bots
)
header = (
f"# Research Loop Transcript ({timestamp})\n\n"
f"- **Config:** `{config_path.name}`\n"
f"- **Backend:** `{backend}`\n"
f"- **Rolling Window:** {settings['window_size']} messages (State Ledger Pinned)\n"
f"- **Model Roster:**\n{roster}\n\n"
f"---\n\n"
f"### Pinned Problem Statement\n{settings['seed_prompt'].strip()}\n\n"
)
filepath.write_text(header, encoding="utf-8")
return filepath
def append_to_transcript(filepath: Path, heading: str, body: str):
with filepath.open("a", encoding="utf-8") as f:
f.write(f"### {heading}\n{body}\n\n")
def main():
parser = argparse.ArgumentParser(description="Run a YAML-configured multi-bot loop.")
parser.add_argument(
"--config",
type=Path,
default=Path("bots_research.yaml"),
help="Path to YAML configuration file (default: bots_research.yaml)",
)
args = parser.parse_args()
config = load_config(args.config)
settings = config["settings"]
core_bots = config["core_bots"]
chaos_bots = config.get("chaos_bots", [])
verifier_cfg = config.get("verifier", {})
ledger_cfg = config.get("ledger", {})
conv_cfg = config.get("convergence", config.get("kill_switch", {}))
stag_cfg = config.get("stagnation", {})
stop_pattern = (
build_command_pattern(conv_cfg.get("commands", []))
if conv_cfg.get("enabled", False)
else None
)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
transcript_path = init_transcript_file(config, args.config, timestamp)
ledger_path = Path(f"ledger_{timestamp}.json")
ledger = StateLedger(problem_statement=settings["seed_prompt"].strip())
history = deque(maxlen=settings["window_size"])
core_idx = 0
last_speaker = None
consecutive_rejects = 0
converged_verdict = None
print(f"Loaded config: {args.config}")
print(f"Logging transcript to: {transcript_path}")
print(f"Pinned Problem:\n{ledger.problem_statement}\n" + "=" * 60)
try:
for turn in range(settings["max_turns"]):
force_disruptor = (
stag_cfg.get("enabled", False)
and consecutive_rejects >= stag_cfg.get("threshold", 2)
)
if force_disruptor:
consecutive_rejects = 0
bot, core_idx, is_interruption = pick_next_speaker(
turn, core_idx, last_speaker, core_bots, chaos_bots, force_disruptor
)
name = bot["name"]
active_model = (
bot["model"]
if settings["backend"] == "ollama"
else settings["gemini_model"]
)
temp = bot["temperature"]
recent_block = "\n\n".join(history) if history else "(No prior turns yet.)"
pinned_header = (
ledger.render_prompt_block()
if ledger_cfg.get("enabled")
else f"PINNED PROBLEM STATEMENT (IMMUTABLE):\n{ledger.problem_statement}"
)
prompt = (
f"{pinned_header}\n\n"
f"RECENT WORKING TRANSCRIPT:\n{recent_block}\n\n"
f"Respond next as {name}. Do not prefix your reply with your name."
)
tag = " [STAGNATION DISRUPTION]" if force_disruptor else (
" [INTERRUPTION]" if is_interruption else ""
)
print(f"[Turn {turn + 1}] {name} ({active_model}, temp={temp}){tag}:")
reply = stream_model(settings, bot["prompt"], prompt, active_model, temp)
print("-" * 60)
history.append(f"{name}: {reply}")
append_to_transcript(
transcript_path,
f"Turn {turn + 1} — {name} (`{active_model}`, temp `{temp}`){tag}",
reply,
)
last_speaker = name
# Deterministic Python/SymPy Verification Gate
if verifier_cfg.get("enabled") and name == verifier_cfg.get("trigger_bot"):
verdict_out = run_sandboxed_verifier(reply, verifier_cfg)
print(f"[Verifier -> Sandbox Output]:\n{verdict_out}\n" + "-" * 60)
history.append(f"Verifier:\n{verdict_out}")
append_to_transcript(
transcript_path,
f"Turn {turn + 1} — Deterministic Verifier",
f"```text\n{verdict_out}\n```",
)
# Pydantic State Ledger Update Gate
if ledger_cfg.get("enabled") and name == ledger_cfg.get("trigger_bot"):
delta = extract_ledger_delta(
settings, ledger_cfg, ledger, "\n\n".join(history)
)
if delta and ledger.apply_delta(delta):
ledger_path.write_text(
ledger.model_dump_json(indent=2), encoding="utf-8"
)
print(f"[LEDGER UPDATED -> {ledger_path.name}]")
print(ledger.render_prompt_block() + "\n" + "-" * 60)
append_to_transcript(
transcript_path,
f"Turn {turn + 1} — State Ledger Snapshot",
f"```json\n{ledger.model_dump_json(indent=2)}\n```",
)
# Stagnation tracking
if stag_cfg.get("enabled") and stag_cfg.get("trigger_phrase", "") in reply:
consecutive_rejects += 1
# Convergence / Kill-Switch Gate
if (
stop_pattern
and name == conv_cfg.get("owner")
and (match := stop_pattern.search(reply))
):
converged_verdict = match.group(0)
banner = f"\n*** LOOP CONVERGED ({converged_verdict}) BY {name.upper()} ***"
print(banner)
append_to_transcript(transcript_path, "Convergence Gate", f"`{converged_verdict}`")
break
except KeyboardInterrupt:
print(f"\nInterrupted by user. Partial transcript saved to {transcript_path}")
else:
status = f"Converged: {converged_verdict}." if converged_verdict else "Max turns reached."
print(f"\n{status} Transcript saved to {transcript_path}")
if ledger_cfg.get("enabled"):
ledger_path.write_text(ledger.model_dump_json(indent=2), encoding="utf-8")
print(f"Final State Ledger saved to {ledger_path}")
if __name__ == "__main__":
main()
What Changed
Append-Safe
StateLedger&LedgerDelta:verified_lemmasanddead_endsare strictly additive and deduplicated, so an LLM can never accidentally wipe out a proven lemma from Turn 3 during Turn 12.Structured Output Extraction (
extract_ledger_delta): Uses Ollama's nativeformat=LedgerDelta.model_json_schema()and Gemini'sresponse_schema=LedgerDeltaattemperature=0.0for reliable JSON parsing.Dual Artifacts: Every ledger update writes a clean
ledger_YYYYMMDD_HHMMSS.jsonfile and embeds a JSON snapshot inside the Markdown transcript.
Add a --resume-ledger flag to bot_loop.py so I can reload an existing ledger_YYYYMMDD_HHMMSS.json file and continue an unfinished research session.
This update adds a --resume-ledger CLI flag to bot_loop.py. Passing a saved ledger_YYYYMMDD_HHMMSS.json file reloads the validated StateLedger, pins its existing verified lemmas, active subgoals, and dead ends into Turn 1, and updates that ledger file in place as the new session progresses.
bot_loop.py
import argparse
import ast
import random
import re
import subprocess
import sys
from collections import deque
from datetime import datetime
from pathlib import Path
import yaml
from pydantic import BaseModel, Field, ValidationError
CODE_BLOCK_RE = re.compile(r"```python\s*(.*?)```", re.DOTALL | re.IGNORECASE)
BANNED_CALLS = {"open", "exec", "eval", "__import__", "compile", "input", "breakpoint"}
# --- PYDANTIC V2 STATE LEDGER ---
class StateLedger(BaseModel):
problem_statement: str
verified_lemmas: list[str] = Field(default_factory=list)
active_subgoals: list[str] = Field(default_factory=list)
dead_ends: list[str] = Field(default_factory=list)
def apply_delta(self, delta: "LedgerDelta") -> bool:
"""Merge new items without duplicating or deleting verified history."""
changed = False
for lemma in delta.add_verified_lemmas:
clean = lemma.strip()
if clean and clean not in self.verified_lemmas:
self.verified_lemmas.append(clean)
changed = True
for dead_end in delta.add_dead_ends:
clean = dead_end.strip()
if clean and clean not in self.dead_ends:
self.dead_ends.append(clean)
changed = True
new_subgoals = [s.strip() for s in delta.set_active_subgoals if s.strip()]
if new_subgoals and new_subgoals != self.active_subgoals:
self.active_subgoals = new_subgoals
changed = True
return changed
def render_prompt_block(self) -> str:
def fmt(items: list[str]) -> str:
return "\n".join(f" - {item}" for item in items) if items else " - (None yet)"
return (
f"PINNED STATE LEDGER (IMMUTABLE GROUND TRUTH):\n"
f"Problem Statement:\n {self.problem_statement}\n"
f"Verified Lemmas:\n{fmt(self.verified_lemmas)}\n"
f"Active Subgoals:\n{fmt(self.active_subgoals)}\n"
f"Dead Ends (DO NOT RETRY):\n{fmt(self.dead_ends)}"
)
class LedgerDelta(BaseModel):
add_verified_lemmas: list[str] = Field(
default_factory=list,
description="New facts, equations, or counterexamples explicitly confirmed by both Verifier and Referee.",
)
add_dead_ends: list[str] = Field(
default_factory=list,
description="Approaches, assumptions, or hypotheses explicitly refuted or rejected.",
)
set_active_subgoals: list[str] = Field(
default_factory=list,
description="1 to 3 concrete next steps the team should tackle next.",
)
def load_config(config_path: Path) -> dict:
if not config_path.exists():
raise FileNotFoundError(f"Config file not found: {config_path}")
with config_path.open("r", encoding="utf-8") as f:
return yaml.safe_load(f)
def load_ledger(ledger_path: Path) -> StateLedger:
if not ledger_path.exists():
raise FileNotFoundError(f"Ledger file not found: {ledger_path}")
return StateLedger.model_validate_json(ledger_path.read_text(encoding="utf-8"))
def build_command_pattern(commands: list[str]) -> re.Pattern | None:
if not commands:
return None
escaped = [r"\s+".join(map(re.escape, cmd.split())) for cmd in commands]
return re.compile(r"(" + "|".join(escaped) + r")", re.IGNORECASE)
def validate_code_ast(code: str, allowed_imports: set[str]) -> str | None:
try:
tree = ast.parse(code)
except SyntaxError as exc:
return f"AST SyntaxError: {exc}"
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
root_mod = alias.name.split(".")[0]
if root_mod not in allowed_imports:
return f"Blocked import: `{root_mod}` (allowed: {sorted(allowed_imports)})"
elif isinstance(node, ast.ImportFrom):
root_mod = (node.module or "").split(".")[0]
if root_mod not in allowed_imports:
return f"Blocked import: `{root_mod}` (allowed: {sorted(allowed_imports)})"
elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
if node.func.id in BANNED_CALLS:
return f"Blocked builtin call: `{node.func.id}`"
elif isinstance(node, ast.Attribute) and node.attr.startswith("__"):
return f"Blocked dunder attribute access: `{node.attr}`"
return None
def run_sandboxed_verifier(reply: str, verifier_cfg: dict) -> str:
match = CODE_BLOCK_RE.search(reply)
if not match:
return "[VERIFIER] No ```python code block found to execute."
code = match.group(1).strip()
allowed = set(verifier_cfg.get("allowed_imports", ["sympy", "math"]))
ast_error = validate_code_ast(code, allowed)
if ast_error:
return f"[VERIFIER BLOCKED] {ast_error}"
timeout = verifier_cfg.get("timeout_seconds", 5)
try:
proc = subprocess.run(
[sys.executable, "-I", "-c", code],
capture_output=True,
text=True,
timeout=timeout,
check=False,
)
except subprocess.TimeoutExpired:
return f"[VERIFIER TIMEOUT] Execution exceeded {timeout}s limit."
stdout = proc.stdout.strip()
stderr = proc.stderr.strip()
if proc.returncode != 0:
return f"[VERIFIER ERROR (exit {proc.returncode})]\n{stderr or stdout}"
if not stdout:
return "[VERIFIER OK] Script exited 0 but printed no output."
return f"[VERIFIER STDOUT]\n{stdout}"
def extract_ledger_delta(
settings: dict, ledger_cfg: dict, ledger: StateLedger, recent_transcript: str
) -> LedgerDelta | None:
"""Use structured JSON output to extract incremental ledger updates."""
system_prompt = (
"You are a strict research ledger clerk. Review the current State Ledger and the "
"recent transcript. Extract ONLY:\n"
"1. `add_verified_lemmas`: facts or counterexamples explicitly confirmed by code output and the Referee.\n"
"2. `add_dead_ends`: failed or refuted approaches that should not be repeated.\n"
"3. `set_active_subgoals`: 1-3 concrete next steps.\n"
"If nothing new was verified or refuted, return empty lists."
)
user_prompt = (
f"{ledger.render_prompt_block()}\n\n"
f"RECENT TRANSCRIPT:\n{recent_transcript}\n\n"
"Return a valid JSON object matching the schema."
)
backend = settings["backend"]
raw_json = ""
try:
if backend == "ollama":
from ollama import chat
model_name = ledger_cfg.get("model", "granite3.3")
resp = chat(
model=model_name,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
],
format=LedgerDelta.model_json_schema(),
options={"temperature": 0.0},
keep_alive=settings.get("ollama_keep_alive", "10m"),
)
raw_json = resp.message.content
elif backend == "gemini":
from google import genai
from google.genai import types
client = genai.Client()
resp = client.models.generate_content(
model=settings["gemini_model"],
contents=user_prompt,
config=types.GenerateContentConfig(
system_instruction=system_prompt,
temperature=0.0,
response_mime_type="application/json",
response_schema=LedgerDelta,
),
)
raw_json = resp.text
return LedgerDelta.model_validate_json(raw_json)
except (ValidationError, Exception) as exc:
print(f"[LEDGER WARNING] Failed to parse structured delta: {exc}")
return None
def stream_model(
settings: dict,
system_prompt: str,
transcript_text: str,
model_name: str,
temperature: float,
) -> str:
chunks = []
backend = settings["backend"]
if backend == "ollama":
from ollama import chat
stream = chat(
model=model_name,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": transcript_text},
],
options={"temperature": temperature},
keep_alive=settings.get("ollama_keep_alive", "10m"),
stream=True,
)
for chunk in stream:
text = chunk.message.content or ""
print(text, end="", flush=True)
chunks.append(text)
elif backend == "gemini":
from google import genai
from google.genai import types
client = genai.Client()
stream = client.models.generate_content_stream(
model=settings["gemini_model"],
contents=transcript_text,
config=types.GenerateContentConfig(
system_instruction=system_prompt,
temperature=temperature,
),
)
for chunk in stream:
text = chunk.text or ""
print(text, end="", flush=True)
chunks.append(text)
else:
raise ValueError(f"Unsupported backend: {backend}")
print()
return "".join(chunks).strip()
def pick_next_speaker(
turn: int,
core_idx: int,
last_speaker: str | None,
core_bots: list[dict],
chaos_bots: list[dict],
force_disruptor: bool,
):
if force_disruptor and chaos_bots:
return chaos_bots[0], core_idx, True
chaos_names = {b["name"] for b in chaos_bots}
if turn > 0 and last_speaker not in chaos_names and chaos_bots:
roll = random.random()
cumulative = 0.0
for bot in chaos_bots:
cumulative += bot.get("chance", 0.0)
if roll < cumulative:
return bot, core_idx, True
bot = core_bots[core_idx % len(core_bots)]
return bot, core_idx + 1, False
def init_transcript_file(
config: dict,
config_path: Path,
timestamp: str,
ledger: StateLedger,
resumed_from: Path | None = None,
) -> Path:
settings = config["settings"]
backend = settings["backend"]
filepath = Path(f"transcript_{timestamp}.md")
all_bots = config["core_bots"] + config.get("chaos_bots", [])
roster = "\n".join(
f" - **{b['name']}:** `{b['model'] if backend == 'ollama' else settings['gemini_model']}` "
f"(temp `{b['temperature']}`)"
for b in all_bots
)
resume_line = f"- **Resumed From:** `{resumed_from.name}`\n" if resumed_from else ""
initial_ledger_section = (
f"### Initial Loaded State Ledger\n```json\n{ledger.model_dump_json(indent=2)}\n```\n\n"
if resumed_from
else ""
)
header = (
f"# Research Loop Transcript ({timestamp})\n\n"
f"- **Config:** `{config_path.name}`\n"
f"{resume_line}"
f"- **Backend:** `{backend}`\n"
f"- **Rolling Window:** {settings['window_size']} messages (State Ledger Pinned)\n"
f"- **Model Roster:**\n{roster}\n\n"
f"---\n\n"
f"### Pinned Problem Statement\n{ledger.problem_statement}\n\n"
f"{initial_ledger_section}"
)
filepath.write_text(header, encoding="utf-8")
return filepath
def append_to_transcript(filepath: Path, heading: str, body: str):
with filepath.open("a", encoding="utf-8") as f:
f.write(f"### {heading}\n{body}\n\n")
def main():
parser = argparse.ArgumentParser(description="Run a YAML-configured multi-bot loop.")
parser.add_argument(
"--config",
type=Path,
default=Path("bots_research.yaml"),
help="Path to YAML configuration file (default: bots_research.yaml)",
)
parser.add_argument(
"--resume-ledger",
type=Path,
default=None,
help="Path to an existing ledger_YYYYMMDD_HHMMSS.json file to resume a session",
)
args = parser.parse_args()
config = load_config(args.config)
settings = config["settings"]
core_bots = config["core_bots"]
chaos_bots = config.get("chaos_bots", [])
verifier_cfg = config.get("verifier", {})
ledger_cfg = config.get("ledger", {})
conv_cfg = config.get("convergence", config.get("kill_switch", {}))
stag_cfg = config.get("stagnation", {})
stop_pattern = (
build_command_pattern(conv_cfg.get("commands", []))
if conv_cfg.get("enabled", False)
else None
)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
ledger_enabled = ledger_cfg.get("enabled", False) or bool(args.resume_ledger)
if args.resume_ledger:
ledger = load_ledger(args.resume_ledger)
ledger_path = args.resume_ledger
else:
ledger = StateLedger(problem_statement=settings["seed_prompt"].strip())
ledger_path = Path(f"ledger_{timestamp}.json")
transcript_path = init_transcript_file(
config, args.config, timestamp, ledger, resumed_from=args.resume_ledger
)
history = deque(maxlen=settings["window_size"])
core_idx = 0
last_speaker = None
consecutive_rejects = 0
converged_verdict = None
print(f"Loaded config: {args.config}")
if args.resume_ledger:
print(f"Resumed State Ledger from: {ledger_path}")
print(ledger.render_prompt_block())
else:
print(f"Pinned Problem:\n{ledger.problem_statement}")
print(f"Logging transcript to: {transcript_path}\n" + "=" * 60)
try:
for turn in range(settings["max_turns"]):
force_disruptor = (
stag_cfg.get("enabled", False)
and consecutive_rejects >= stag_cfg.get("threshold", 2)
)
if force_disruptor:
consecutive_rejects = 0
bot, core_idx, is_interruption = pick_next_speaker(
turn, core_idx, last_speaker, core_bots, chaos_bots, force_disruptor
)
name = bot["name"]
active_model = (
bot["model"]
if settings["backend"] == "ollama"
else settings["gemini_model"]
)
temp = bot["temperature"]
recent_block = (
"\n\n".join(history)
if history
else "(Resumed session — review the Pinned State Ledger above and continue.)"
if args.resume_ledger
else "(No prior turns yet.)"
)
pinned_header = (
ledger.render_prompt_block()
if ledger_enabled
else f"PINNED PROBLEM STATEMENT (IMMUTABLE):\n{ledger.problem_statement}"
)
prompt = (
f"{pinned_header}\n\n"
f"RECENT WORKING TRANSCRIPT:\n{recent_block}\n\n"
f"Respond next as {name}. Do not prefix your reply with your name."
)
tag = " [STAGNATION DISRUPTION]" if force_disruptor else (
" [INTERRUPTION]" if is_interruption else ""
)
print(f"[Turn {turn + 1}] {name} ({active_model}, temp={temp}){tag}:")
reply = stream_model(settings, bot["prompt"], prompt, active_model, temp)
print("-" * 60)
history.append(f"{name}: {reply}")
append_to_transcript(
transcript_path,
f"Turn {turn + 1} — {name} (`{active_model}`, temp `{temp}`){tag}",
reply,
)
last_speaker = name
# Deterministic Python/SymPy Verification Gate
if verifier_cfg.get("enabled") and name == verifier_cfg.get("trigger_bot"):
verdict_out = run_sandboxed_verifier(reply, verifier_cfg)
print(f"[Verifier -> Sandbox Output]:\n{verdict_out}\n" + "-" * 60)
history.append(f"Verifier:\n{verdict_out}")
append_to_transcript(
transcript_path,
f"Turn {turn + 1} — Deterministic Verifier",
f"```text\n{verdict_out}\n```",
)
# Pydantic State Ledger Update Gate
if ledger_enabled and name == ledger_cfg.get("trigger_bot"):
delta = extract_ledger_delta(
settings, ledger_cfg, ledger, "\n\n".join(history)
)
if delta and ledger.apply_delta(delta):
ledger_path.write_text(
ledger.model_dump_json(indent=2), encoding="utf-8"
)
print(f"[LEDGER UPDATED -> {ledger_path.name}]")
print(ledger.render_prompt_block() + "\n" + "-" * 60)
append_to_transcript(
transcript_path,
f"Turn {turn + 1} — State Ledger Snapshot",
f"```json\n{ledger.model_dump_json(indent=2)}\n```",
)
# Stagnation tracking
if stag_cfg.get("enabled") and stag_cfg.get("trigger_phrase", "") in reply:
consecutive_rejects += 1
# Convergence / Kill-Switch Gate
if (
stop_pattern
and name == conv_cfg.get("owner")
and (match := stop_pattern.search(reply))
):
converged_verdict = match.group(0)
banner = f"\n*** LOOP CONVERGED ({converged_verdict}) BY {name.upper()} ***"
print(banner)
append_to_transcript(
transcript_path, "Convergence Gate", f"`{converged_verdict}`"
)
break
except KeyboardInterrupt:
print(f"\nInterrupted by user. Partial transcript saved to {transcript_path}")
else:
status = (
f"Converged: {converged_verdict}." if converged_verdict else "Max turns reached."
)
print(f"\n{status} Transcript saved to {transcript_path}")
if ledger_enabled:
ledger_path.write_text(ledger.model_dump_json(indent=2), encoding="utf-8")
print(f"Final State Ledger saved to {ledger_path}")
if __name__ == "__main__":
main()
Usage
# Start a fresh research run (creates ledger_YYYYMMDD_HHMMSS.json)
python bot_loop.py --config bots_research.yaml
# Resume from a previous ledger and continue updating it in place
python bot_loop.py --config bots_research.yaml --resume-ledger ledger_20261127_184200.json
What Changed
Validated reload (
load_ledger): Parses the JSON file throughStateLedger.model_validate_json()so corrupted or hand-edited ledgers fail fast before wasting tokens.In-place ledger persistence: When resuming,
ledger_pathpoints to the existing JSON file so one canonical ledger evolves across sessions, while each session still writes its own fresh timestamped Markdown transcript (transcript_YYYYMMDD_HHMMSS.md) with the loaded ledger embedded at the top.
Form <https://gemini.google.com/app/484cb4dcf229ace6> Google Gemini (4 Neon)
Comments
Post a Comment