debajyotidasgupta's picture
MindFlow reproduction bundle
448d6a5 verified
Raw
History Blame Contribute Delete
8.39 kB
"""Thinking operators (Def 4.1 / Appendix B of MindFlow).
Each operator is an atomic, reusable LLM-agent routine O=(P,{Q},{T}) that performs
a distinct cognitive function. Operators consume the current structured idea
y=(title, problem, method, evaluation) (Eq. 2) plus the topic and related works,
and emit a new/refined structured idea.
"""
from __future__ import annotations
import json
from . import llm
# Canonical structured-idea schema (Eq. 2): y = (y_t, y_p, y_m, y_e)
IDEA_KEYS = ["title", "problem", "method", "evaluation"]
_SYS = (
"You are an expert AI research scientist generating rigorous, novel and feasible "
"research ideas. Always answer with a single JSON object with keys "
'"title", "problem", "method", "evaluation". '
'"problem" states the motivation, research gap and a testable hypothesis; '
'"method" gives the core technical approach, key components, assumptions, datasets and metrics; '
'"evaluation" gives baselines, ablations and success criteria. Be concrete and specific.'
)
def _fmt_idea(idea):
if not idea:
return "(none yet)"
return json.dumps({k: idea.get(k, "") for k in IDEA_KEYS}, indent=1)
def _fmt_context(topic, related):
rw = "\n".join(f"- {r}" for r in (related or [])[:6]) or "(none provided)"
return f"RESEARCH TOPIC:\n{topic}\n\nRELATED WORKS (inspiration):\n{rw}"
def _run(prompt, topic, related, idea, model=None, temperature=0.7, seed=None, max_tokens=900):
msgs = [
{"role": "system", "content": _SYS},
{"role": "user", "content": f"{_fmt_context(topic, related)}\n\nCURRENT IDEA:\n{_fmt_idea(idea)}\n\n{prompt}"},
]
obj = llm.chat_json(msgs, model=model, temperature=temperature, seed=seed, max_tokens=max_tokens)
# normalise: keep the 4 keys, fall back to previous idea for missing fields
out = {}
for k in IDEA_KEYS:
v = obj.get(k)
out[k] = v if isinstance(v, str) and v.strip() else (idea.get(k, "") if idea else "")
return out
# ---- operator implementations -------------------------------------------------
def op_generate(topic, related, idea=None, **kw):
p = ("GENERATE: Produce an initial, complete research idea for this topic, grounded in the "
"related works. This is the default proposal.")
return _run(p, topic, related, None, temperature=0.9, **kw)
def op_generate_cot(topic, related, idea=None, **kw):
p = ("GENERATE with chain-of-thought: First think step by step about the gaps, prior work and possible "
"approaches (reason internally), THEN produce a single complete research idea as the JSON object.")
return _run(p, topic, related, None, temperature=0.9, max_tokens=1400, **kw)
def op_divergent(topic, related, idea, **kw):
"""Fallback single-output form (best alternative). The flow executor prefers
op_divergent_expand to branch into a candidate pool."""
p = ("DIVERGENT THINKING: Expand the search space. Propose a markedly different alternative "
"framing for the CURRENT IDEA and return it. Prioritise originality and breadth.")
return _run(p, topic, related, idea, temperature=1.0, **kw)
def op_divergent_expand(topic, related, idea, n=3, model=None, seed=None):
"""Divergent branching: return up to n diverse candidate ideas (one LLM call)."""
schema = ('Respond ONLY with a JSON object {"alternatives": [ {"title","problem","method",'
'"evaluation"}, ... ]} containing %d markedly different, diverse alternatives.' % n)
msgs = [
{"role": "system", "content": _SYS},
{"role": "user", "content": f"{_fmt_context(topic, related)}\n\nCURRENT IDEA:\n{_fmt_idea(idea)}\n\n"
f"DIVERGENT THINKING: Expand the search space by generating {n} markedly different alternative "
f"directions/framings for the current idea (different problems or methods, not minor tweaks). {schema}"}]
obj = llm.chat_json(msgs, model=model, temperature=1.0, seed=seed, max_tokens=1800)
alts = obj.get("alternatives") if isinstance(obj, dict) else None
out = []
for a in (alts or [])[:n]:
if isinstance(a, dict):
out.append({k: (a.get(k) if isinstance(a.get(k), str) else (idea.get(k, "") if idea else "")) for k in IDEA_KEYS})
if not out:
out = [op_divergent(topic, related, idea, model=model, seed=seed)]
return out
def op_convergent(topic, related, idea, **kw):
p = ("CONVERGENT THINKING: Synthesise, rank and select the strongest elements of the CURRENT IDEA "
"into a single coherent, high-quality and well-scoped proposal. Remove redundancy; sharpen the "
"contribution.")
return _run(p, topic, related, idea, temperature=0.4, **kw)
def op_convergent_select(topic, related, candidates, model=None, seed=None):
"""Convergent selection over a candidate pool (Prompt E): pick the single most
novel/promising/feasible idea. Falls back to sharpening if only one candidate."""
candidates = [c for c in candidates if c]
if len(candidates) <= 1:
return op_convergent(topic, related, candidates[0] if candidates else None, model=model, seed=seed)
letters = [chr(ord("A") + i) for i in range(len(candidates))]
listing = "\n\n".join(f"Idea {L}:\n{_fmt_idea(c)}" for L, c in zip(letters, candidates))
msgs = [
{"role": "system", "content": _SYS},
{"role": "user", "content": f"{_fmt_context(topic, related)}\n\nSeveral candidate ideas have been proposed:\n\n{listing}\n\n"
"CONVERGENT THINKING: Carefully evaluate these candidates and select the ONE that is most novel, "
'promising and feasible. Respond ONLY with JSON {"solution_letter":"<letter>", "title","problem",'
'"method","evaluation"} where the four idea fields are the refined, sharpened version of the selected idea.'}]
obj = llm.chat_json(msgs, model=model, temperature=0.3, seed=seed, max_tokens=1300)
L = str(obj.get("solution_letter", "")).strip().upper()[:1]
base = candidates[letters.index(L)] if L in letters else candidates[0]
out = {}
for k in IDEA_KEYS:
v = obj.get(k)
out[k] = v if isinstance(v, str) and v.strip() else base.get(k, "")
return out
def op_critical(topic, related, idea, **kw):
p = ("CRITICAL THINKING: Stress-test the CURRENT IDEA. List its top weaknesses, hidden assumptions and "
"verification risks, then return a REVISED idea with targeted fixes that address them. Improve "
"significance and feasibility.")
return _run(p, topic, related, idea, temperature=0.5, **kw)
def op_analogical(topic, related, idea, **kw):
p = ("ANALOGICAL THINKING: Transfer structure from a related but different problem/field to the CURRENT "
"IDEA, proposing a new formulation or solution route by analogy. Name the source analogy explicitly "
"in the method.")
return _run(p, topic, related, idea, temperature=0.85, **kw)
def op_counterfactual(topic, related, idea, **kw):
p = ("COUNTERFACTUAL THINKING: Perturb a key assumption of the CURRENT IDEA (a 'what-if'), and return the "
"resulting new idea that follows from relaxing/inverting that assumption. Maximise novelty.")
return _run(p, topic, related, idea, temperature=1.0, **kw)
def op_constraint(topic, related, idea, **kw):
p = ("CONSTRAINT-DRIVEN THINKING: Impose explicit real-world constraints (available data, compute/cost "
"budget, and a runnable experiment). Repair the CURRENT IDEA so its method and evaluation are "
"concretely executable under these constraints. Improve feasibility.")
return _run(p, topic, related, idea, temperature=0.4, **kw)
# operator registry (Exit handled by the controller, no LLM call)
OPERATORS = {
"Generate": op_generate,
"Divergent": op_divergent,
"Convergent": op_convergent,
"Critical": op_critical,
"Analogical": op_analogical,
"Counterfactual": op_counterfactual,
"Constraint": op_constraint,
}
# Refinement operators the controller composes after the initial Generate (+ Exit).
REFINE_OPS = ["Divergent", "Convergent", "Critical", "Analogical", "Counterfactual", "Constraint"]
EXIT = "Exit"
ALL_OPS = ["Generate"] + REFINE_OPS + [EXIT]
# approximate per-operator execution cost C(G) in LLM-calls (used in Eq. 11 cost term)
OP_COST = {name: 1.0 for name in OPERATORS}
OP_COST[EXIT] = 0.0