File size: 8,388 Bytes
448d6a5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 | """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
|