Below is a minimal but reasonably-fast proof-of-concept that uses Monte-Carlo Tree Search (MCTS) to discover an “optimal” prompt chain that drives an LLM to rewrite/optimize a single function.
The objective I picked is raw speed (average run-time on a given test-set), but you can swap the evaluate_patch() routine for any other quality metric you care about.
High-level idea
- Each node in the tree stores the entire LLM conversation up to that point (system + user + assistant messages).
- When we expand a node, we append all messages in the path to form the next prompt for the LLM, which returns a candidate code patch.
- The patch is executed in a sandboxed namespace and benchmarked with
timeit.
- The obtained reward (−mean execution time) is propagated up the tree with standard UCB1.
- After
N iterations we pick the best child of the root (highest visit-count or reward) and return its code.
Code
"""
mcts_code_optimizer.py
Minimal MCTS driver that uses an LLM to iteratively improve a single
Python function for speed. Requires: openai>=1.0.0, tiktoken, psutil
!!! DISCLAIMER !!!
Running untrusted code is dangerous. This PoC isolates execution
in a separate process with resource limits, but you *must* harden
it further for production (docker, firejail, gVisor, …).
"""
from __future__ import annotations
import ast, time, math, os, sys, textwrap, random, multiprocessing as mp
from dataclasses import dataclass, field
from typing import List, Optional
import openai # pip install openai
import tiktoken # pip install tiktoken
import psutil # pip install psutil
# -----------------------------------------------------------------------------
# Config – tweak to your liking
# -----------------------------------------------------------------------------
OPENAI_MODEL = "gpt-4o-mini"
TEMPERATURE = 0.7
ROLL_OUTS = 300 # total MCTS iterations
EXPAND_AFTER_N = 5 # visits before node is eligible for expansion
MAX_CHILDREN = 4 # beam width
MAX_TOKENS_NODE = 4000 # budget for each prompt
TIME_LIMIT_SEC = 0.3 # runtime budget for each benchmark execution
N_BENCH_RUNS = 15 # repetitions in `timeit`
UCB_C = 1.4
SEED = 42
random.seed(SEED)
# -----------------------------------------------------------------------------
# Target baseline code – in practice you’d load this from file(s)
# -----------------------------------------------------------------------------
BASELINE_CODE = '''
def fib(n: int) -> int:
if n < 2:
return n
return fib(n-1) + fib(n-2)
'''
TEST_INPUTS = [5, 10, 20, 25] # synthetic workload
# -----------------------------------------------------------------------------
# Helper: cheap sandbox for timing a single patch
# -----------------------------------------------------------------------------
def _exec_and_time(code_src: str, inputs: List[int]) -> float:
"""
Runs `code_src` in a fresh process. Returns mean exec time (sec) over TEST_INPUTS.
Long-running or crashing code yields `float('inf')`.
"""
def _runner(pipe, code, data):
try:
ns = {}
exec(code, ns)
fn = ns[next(k for k in ns if callable(ns[k]))] # first function
times = []
for x in data:
t0 = time.perf_counter()
fn(x)
times.append(time.perf_counter() - t0)
pipe.send(sum(times) / len(times))
except Exception as e:
pipe.send(float("inf"))
parent, child = mp.Pipe()
p = mp.Process(target=_runner, args=(child, code_src, inputs))
p.start()
p.join(TIME_LIMIT_SEC * len(inputs) + 0.2) # soft wall-time
if p.is_alive():
p.kill(); p.join()
return float("inf")
return parent.recv()
# -----------------------------------------------------------------------------
# MCTS structures
# -----------------------------------------------------------------------------
@dataclass
class Node:
messages: List[dict] # conversation up to now
parent: Optional['Node']
reward_sum: float = 0.0
visits: int = 0
children: List['Node'] = field(default_factory=list)
prior: float = 0.0
def ucb_score(self, total_visits: int) -> float:
if self.visits == 0:
return float("inf")
exploit = self.reward_sum / self.visits
explore = UCB_C * math.sqrt(math.log(total_visits) / self.visits)
return exploit + explore
# -----------------------------------------------------------------------------
# Core MCTS algorithm
# -----------------------------------------------------------------------------
class LlmMCTS:
def __init__(self, system_prompt: str):
self.root = Node(messages=[{"role": "system", "content": system_prompt}],
parent=None)
# ---- Public -------------------------------------------------------------
def search(self, n_iters: int) -> Node:
for _ in range(n_iters):
node = self._select(self.root)
reward = self._simulate(node)
self._backprop(node, reward)
best = max(self.root.children, key=lambda c: c.visits) if self.root.children else self.root
return best
# ---- MCTS steps ---------------------------------------------------------
def _select(self, node: Node) -> Node:
while node.children:
node = max(node.children, key=lambda c: c.ucb_score(node.visits))
return node
def _expand(self, node: Node):
prompt = node.messages
llm_reply = self._call_llm(prompt)
child_messages = prompt + [{"role": "assistant", "content": llm_reply}]
child = Node(messages=child_messages, parent=node)
node.children.append(child)
return child
def _simulate(self, node: Node) -> float:
if node.visits >= EXPAND_AFTER_N and len(node.children) < MAX_CHILDREN:
node = self._expand(node)
# Extract latest assistant message == code patch
code = self._get_code_from_messages(node.messages)
mean_time = _exec_and_time(code, TEST_INPUTS)
reward = -mean_time # smaller time = larger reward
return reward
def _backprop(self, node: Node, reward: float):
while node:
node.visits += 1
node.reward_sum += reward
node = node.parent
# ---- LLM wrappers -------------------------------------------------------
def _call_llm(self, messages: List[dict]) -> str:
# truncate if > token budget
enc = tiktoken.encoding_for_model(OPENAI_MODEL)
while len(enc.encode(self._concat(messages))) > MAX_TOKENS_NODE:
# drop earliest assistant msgs
for i, m in enumerate(messages):
if m['role'] == "assistant":
del messages[i]
break
resp = openai.chat.completions.create(
model=OPENAI_MODEL,
messages=messages + [
{"role": "user",
"content": "Please propose a faster implementation. "
"Return ONLY the replacement function."}
],
temperature=TEMPERATURE,
max_tokens=512,
)
return resp.choices[0].message.content.strip()
# ---- Utils --------------------------------------------------------------
@staticmethod
def _concat(messages: List[dict]) -> str:
return "\n".join(m["role"] + ": " + m["content"] for m in messages)
@staticmethod
def _get_code_from_messages(msgs: List[dict]) -> str:
# last assistant message is assumed to contain code
for m in reversed(msgs):
if m["role"] == "assistant":
return m["content"]
raise ValueError("No assistant message found")
# -----------------------------------------------------------------------------
# Putting it all together
# -----------------------------------------------------------------------------
def main():
system_prompt = textwrap.dedent(f"""
You are an expert Python performance engineer. You will be shown the current
implementation of a target function plus a set of unit-tests.
Your task is to output an improved, drop-in replacement that is FASTER yet
preserves correctness. Output ONLY the new function definition.
Current baseline:
```python
{BASELINE_CODE.strip()}
```
""")
mcts = LlmMCTS(system_prompt)
best_node = mcts.search(ROLL_OUTS)
optimized_code = LlmMCTS._get_code_from_messages(best_node.messages)
baseline_time = _exec_and_time(BASELINE_CODE, TEST_INPUTS)
new_time = _exec_and_time(optimized_code, TEST_INPUTS)
print("=== Best patch discovered ===")
print(optimized_code)
print(f"\nBaseline mean time : {baseline_time:.6f}s")
print(f"Optimized mean time: {new_time:.6f}s")
print(f"Speed-up factor : {baseline_time / new_time if new_time>0 else 'inf'}")
if __name__ == "__main__":
main()
How to use / extend
pip install openai tiktoken psutil
- Set
OPENAI_API_KEY in your environment (or use openai.api_key = ...).
- Replace
BASELINE_CODE with whichever function/class you want to tune.
- Fill
TEST_INPUTS (or even randomized property-based tests) that capture realistic workload.
- Swap
evaluate_patch() (here _exec_and_time) to focus on accuracy, memory, code-quality scores, Pareto fronts, etc.
- Harden execution: Docker,
ulimit, file-system isolation, kill signals, etc.
Why this is “fast”
• Minimal state per node – only the conversation.
• The evaluation is embarrassingly parallel (here single process for simplicity; just toss _exec_and_time to a ProcessPoolExecutor).
• Token-budget trimming avoids quadratic prompt growth.
• UCB1 encourages aggressive pruning of unpromising branches.
Have fun hacking—and stay safe when running arbitrary code!