Below is a minimal but fast MCTS implementation whose nodes are complete LLM outputs (prompts).
Each time we descend the tree we concatenate the entire chain of ancestor prompts into the context that is sent to the LLM for expansion.
The reward is the speed-up (wall-time ratio) of the refactored code versus the original baseline, measured with timeit.
The code is self-contained; drop it in a file (e.g. mcts_prompt_optimizer.py) and run.
It assumes you have an OpenAI key in the environment variable OPENAI_API_KEY.
"""
Fast MCTS to evolve an LLM prompt that rewrites a Python function for speed.
Nodes = complete LLM outputs (prompts).
Tree descent concatenates the whole prompt chain.
Reward = speed-up of the refactored code vs. the original baseline.
"""
import ast
import inspect
import textwrap
import timeit
import openai
import random
import math
from typing import List, Tuple, Dict, Any
openai.api_key = open("key.txt").read().strip()
# ------------------------------------------------------------------
# 1. USER CONFIGURATION
# ------------------------------------------------------------------
TARGET_FUNCTION = """
def slow_fib(n: int) -> int:
if n < 2:
return n
return slow_fib(n-1) + slow_fib(n-2)
"""
N_MCTS_ITER = 20
N_ROLLOUTS_PER_LEAF = 3
C_PUCT = 1.0
MAX_TOKENS = 512
TEMPERATURE = 0.3
# ------------------------------------------------------------------
# 2. UTILITIES
# ------------------------------------------------------------------
def extract_code_block(text: str) -> str:
"""Pull the first fenced Python block from an LLM reply."""
lines = text.splitlines()
in_fence = False
buf = []
for ln in lines:
if ln.strip().startswith("```"):
if in_fence:
break
in_fence = True
continue
if in_fence:
buf.append(ln)
code = "\n".join(buf).strip()
if not code:
# Fallback: assume the whole reply is code
code = text.strip()
return code
def safe_exec(code: str, globals_dict: Dict[str, Any]) -> Any:
"""Exec code and return the last defined function."""
tree = ast.parse(code)
last_func = None
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
last_func = node.name
if not last_func:
raise ValueError("No function found in generated code")
exec(code, globals_dict)
return globals_dict[last_func]
def speed_reward(original_src: str, new_src: str, arg: Tuple[Any, ...] = (20,)) -> float:
"""Return speed-up ratio (old_time / new_time)."""
globals_old, globals_new = {}, {}
try:
old_fn = safe_exec(original_src, globals_old)
new_fn = safe_exec(new_src, globals_new)
except Exception as e:
return 0.0 # Invalid code → worst reward
try:
t_old = timeit.timeit(lambda: old_fn(*arg), number=5)
t_new = timeit.timeit(lambda: new_fn(*arg), number=5)
except Exception:
return 0.0
if t_new <= 0:
return 0.0
return t_old / t_new
# ------------------------------------------------------------------
# 3. MCTS CORE
# ------------------------------------------------------------------
class Node:
def __init__(self, prompt_chain: List[str], parent=None):
self.prompt_chain = prompt_chain # list[str] – full history
self.parent = parent
self.children: List[Node] = []
self.N = 0 # visits
self.W = 0.0 # total reward
self.Q = 0.0 # mean reward
def uct(self, c_puct: float) -> float:
if self.N == 0:
return float("inf")
return self.Q + c_puct * math.sqrt(math.log(self.parent.N) / self.N)
def best_child(self, c_puct: float) -> "Node":
return max(self.children, key=lambda c: c.uct(c_puct))
def expand(self, llm_outputs: List[str]) -> None:
for out in llm_outputs:
self.children.append(Node(self.prompt_chain + [out], parent=self))
def is_leaf(self) -> bool:
return len(self.children) == 0
def backprop(self, reward: float) -> None:
self.N += 1
self.W += reward
self.Q = self.W / self.N
if self.parent:
self.parent.backprop(reward)
# ------------------------------------------------------------------
# 4. LLM HELPERS
# ------------------------------------------------------------------
SYSTEM_PROMPT = (
"You are a world-class Python performance engineer. "
"Return ONLY the refactored Python code inside a single fenced block ```python ... ```. "
"Do NOT include explanations or usage examples."
)
def llm_generate(prompt_chain: List[str]) -> List[str]:
"""Return k LLM completions given the prompt chain."""
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
# Concatenate the entire chain into one big prompt
full_prompt = "\n\n".join(prompt_chain)
messages.append({"role": "user", "content": full_prompt})
try:
resp = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages,
max_tokens=MAX_TOKENS,
temperature=TEMPERATURE,
n=3, # 3 parallel completions
stop=["```\n```"], # crude stop to avoid double fences
)
return [choice["message"]["content"] for choice in resp["choices"]]
except Exception as e:
print("LLM error:", e)
return []
# ------------------------------------------------------------------
# 5. MCTS LOOP
# ------------------------------------------------------------------
def mcts_optimize(
original_code: str,
n_iter: int = N_MCTS_ITER,
k_rollouts: int = N_ROLLOUTS_PER_LEAF,
) -> str:
root_prompt = (
f"Below is a Python function. Refactor it for maximum speed while keeping the same semantics.\n\n"
f"```python\n{original_code.strip()}\n```"
)
root = Node([root_prompt])
for _ in range(n_iter):
node = root
# 1. SELECT
while not node.is_leaf():
node = node.best_child(C_PUCT)
# 2. EXPAND
llm_outputs = llm_generate(node.prompt_chain)
if not llm_outputs:
continue # skip failed LLM call
node.expand(llm_outputs)
# 3. ROLLOUT (simulate from each new child)
for child in node.children:
reward = 0.0
for _ in range(k_rollouts):
code = extract_code_block(child.prompt_chain[-1])
reward += speed_reward(original_code, code)
reward /= k_rollouts
child.backprop(reward)
# Return the best code found so far
best_node = max(root.children, key=lambda c: c.Q, default=root)
if best_node is root:
return original_code
best_code = extract_code_block(best_node.prompt_chain[-1])
return best_code
# ------------------------------------------------------------------
# 6. DEMO
# ------------------------------------------------------------------
if __name__ == "__main__":
print("Original code:\n", TARGET_FUNCTION)
optimized = mcts_optimize(TARGET_FUNCTION)
print("\nOptimized code:\n", optimized)
How it works
- Node = list of prompts (
prompt_chain).
When we descend, the LLM sees the entire chain concatenated, so each child is a refinement of its ancestors.
- Expansion asks the LLM for 3 completions at once (
n=3) to keep the tree wide but cheap.
- Rollout runs the generated code 3× with
timeit, averages the speed-up, and back-propagates.
- After
N_MCTS_ITER iterations the best child (highest Q) is returned.
Tuning knobs
N_MCTS_ITER, N_ROLLOUTS_PER_LEAF, C_PUCT, MAX_TOKENS, TEMPERATURE.
- Change
speed_reward to optimize for accuracy (unit-test pass rate), quality (cyclomatic complexity), etc.