Workflow automation · Research feature

AI Framework Clusters Queries to Create Efficient, Reusable Workflows

The framework was tested on 300 queries from four domains including math, science, and programming.

Adapted from research by Qi Cheng, Shengyu Chen, Wei Cheng and colleagues.

arXiv preprint revision · 2026-10-06 · Attribution & reuse
In this article
Editorial illustration of linked workflow.

Editor’s introduction

The study evaluates RA-MoWE, a framework that uses workflow-affinity embeddings to group queries by their shared reasoning patterns. It compares performance when queries are assigned to pre-defined reference workflows versus when they are clustered and given specialized workflows derived from those groups. The results show a 4.04 percentage point improvement in average task score and a 27.7% reduction in language model calls. The framework was tested on 300 queries from four domains including math, science, and programming. Evidence supports that workflow affinity enables effective clustering and that embeddings derived from query text guide workflow generation without requiring full execution. The study confirms gains in both mixed-task and software engineering settings, showing that cluster-specific workflows improve performance.

Introduction

Agentic workflows organize large language model (LLM) calls into procedures for reasoning, revising answers, and using tools, extending their capabilities on complex tasks. Their design determines which operations run and how they interact, affecting both solution quality and inference cost: repeated sampling, revision, and decomposition offer different ways to spend computation. Manually choosing a suitable design for a diverse collection of queries is therefore a substantial engineering effort.

Recent methods automate workflow design through search and learned generation. ADAS and AFlow explore code-represented agents using execution feedback, while AgentSquare searches combinations of reusable modules. In these works, the workflow is often optimized over a collection of tasks using a collection-level score and thus can overlook differences in individual query need. In contrast, some approaches, such as FlowReasoner, learn to generate a workflow for each query. These methods need to repeat costly optimization and also have less training samples for each workflow. Addressing such tradeoff requires identifying which queries should share a workflow and what computations each group needs. While a natural solution is to group queries based on their similarity. However, conventional semantic similarity does not necessarily capture whether queries benefit from the same reasoning strategies.

Our key idea is to introduce a workflow-affinity embedding and group queries by how they respond to different reasoning workflows. In particular, the workflow-affinity embedding is a vector whose coordinates estimate a query’s task score under a fixed set of reference workflows, called probes. The resulting vector captures a query’s relative strengths and weaknesses across different reasoning strategies, including which reasoning strategies succeed, partially succeed, or fail. Queries with similar profiles can therefore be grouped together based on their computational needs rather than their semantic similarity.

We then create an embedding encoder, which makes the generated experts accessible from query text alone. While workflow-affinity embeddings can be measured offline by executing the reference workflows, this process is too costly to repeat for every new query. We therefore train the encoder to predict a query’s workflow-affinity embedding directly from its text, using the measured embeddings as supervision. At deployment, the predicted embedding selects a cluster’s expert without executing the reference workflows.

We evaluate RA-MoWE across mathematics, science, programming, and repository repair against six families of adapted search and routing methods. On 300 test queries drawn from four benchmarks in mathematics, science, and programming, RA-MoWE improves average task score by 4.04 percentage points over a system that selects from the reference workflows, while using 27.7% fewer LLM calls at inference. Both systems choose a workflow based on the query text. Further experiments examine whether queries consistently benefit from particular workflows, how clustering affects the quality of generated workflows, and how accurately the encoder assigns new queries to experts.

Workflow-affinity embeddings for query clustering

A useful query group should reflect which reasoning procedures help its members. Questions about the same topic can require different computations, such as comparing several candidate answers or revising an initial solution. We therefore represent a query by its performance under a fixed panel of diverse reference workflows, called probes. These probes apply established strategies such as chain-of-thought, self-consistency, and self-refinement.

Learning the embedding encoder

The prediction need not recover every coordinate exactly to preserve an expert choice. If the prediction error is smaller than the measured embedding’s distance to the nearest cluster boundary, the two embeddings select the same expert. Proposition 3 and Appendix A.3 formalize this condition and its counterpart for expected probe scores. This motivates evaluating the encoder through both prediction error and the resulting expert assignments. Appendix A.6 combines the conditions for measurement, generation, and assignment into an analysis of the complete pipeline.

Empirical evaluation

We test the three links in RA-MoWE: whether workflow responses reveal reusable specialization, whether the encoder preserves useful assignments from text, and whether affinity profiles guide the construction of effective workflows. Each experiment connects an intermediate design choice to downstream utility.

Tasks and evaluation

MixBench-H contains 600 training and 300 test queries spanning AIME, GPQA, CodeContests, and LiveCodeBench. We evaluate GPT-4o-mini and Claude Haiku 4.5 separately. SWE-bench Verified uses a repository-stratified 300/200 split and a fixed Agentless-lite localize–repair pipeline. Mixed-task utility is mean answer correctness or public-test pass fraction; SWE utility is harness resolution. Comparisons within each regime share queries and scoring contracts. The main comparison tests the embedding-to-bank interface using cluster-conditioned AFlow search on mixed tasks and cluster policy selection on SWE. A separate experiment evaluates embedding-guided expert generation. We report paired stratified bootstrap intervals and Holm-adjusted sign-flip tests for the historical routing families; the embedding-guided search contrasts use exploratory, unadjusted query-bootstrap intervals.

Text prediction connects the embedding to deployment

Assignment diagnostics explain why reconstruction metrics alone are insufficient. Measured/predicted cluster agreement is 37.7% for GPT-4o-mini and 12.0% for Haiku, whose predictor assigns 277/300 queries to one cluster. The SWE predictor chooses direct for all 200 instances. The measured-affinity gains therefore establish a useful target, but the current predictors do not consistently preserve its specialist decisions. This connects the empirical challenge to Proposition 3, which assesses prediction error relative to cluster boundaries. Assignment fidelity and expert utility are therefore essential complements to coordinate error.

Embedding-guided search generates effective workflows

We next evaluate embedding-guided search, which uses cluster preferences to initialize and edit executable workflows. This study uses GPT-4o-mini through the official OpenAI endpoint, separately from the preceding NEC-endpoint experiments. Each of six cluster searches evaluates an affinity-derived seed and at most two edits. The resulting bank includes refinement, sampling/selection, and decomposition. Five experts retain their seeds; cluster C3 accepts a larger ensemble followed by decomposition. The search traces show that behavioral initialization supplies most of the final bank, with local edits refining one specialist.

Learning representations for computational decisions

Instance-dependent algorithm selection connects instance features to algorithm performance; decision-relevant representation learning seeks to preserve distinctions that affect action quality. Workflow-affinity embeddings specialize this perspective to query-level outcomes of executable reasoning procedures. They provide an external behavioral representation, whereas function vectors and task arithmetic represent tasks through internal activations and weight differences. General text embeddings remain useful features; our supervision target additionally names the workflow behaviors that clustering and construction should exploit.

Allocating workflow construction effort

Search-based agent design learns executable programs or modular compositions from performance feedback. Learned workflow generators further amortize design through preference optimization or execution-reward training. RA-MoWE organizes construction around a reusable behavioral group. Its cluster determines the examples on which an expert is optimized, while the profile supplies a seed preference and failure-conditioned guidance. This interface accommodates different search backends and makes the grouping representation part of expert construction itself.

Selecting models and orchestrating agents

Preference-trained routing, cost-aware cascades, and joint selection of roles and models adapt computation to a query. Related approaches align internal expert routing with task neighborhoods, learn query-conditioned agentic architectures, or train coordination policies. RA-MoWE connects pre-execution selection to the creation of an external workflow bank through one outcome-coordinate space. Our experiments compare the implemented local adaptations under their disclosed information and resource contracts; the separate model-pool study examines the additional freedom to change backbones.

Discussion and conclusion

Workflow affinity provides a common basis for learning query representations and constructing the workflows that serve them. The experiments show repeatable probe complementarity, gains from measured-affinity specialization in two regimes, and effective compact workflows initialized from cluster profiles. The encoder makes this construction reusable from query text; its assignment fidelity determines how much of the behavioral structure reaches deployment.

Standardization changes both noise and the decision geometry

Small coordinate scales can therefore amplify execution noise. Positive diagonal scaling retains the information in the raw vector, but changes Euclidean neighborhoods and cross-coordinate rankings. Our code substitutes one for nearly zero fitted standard deviations; it does not otherwise cap this amplification. Equation (9) conditions on normalization fitted without the evaluated query. It is not a joint guarantee for a training observation reused to fit its own scale, and it does not cover nonlinear per-query unit normalization.

Encoder and cluster construction

The choice of frozen features is motivated by limited fingerprint supervision and the ability to reuse a cached text representation. The width and loss weights are fixed capacity and optimization choices; no experiment establishes them as optimal. Predicting continuous coordinates instead of cluster labels retains information for alternative partitions and operator profiles, at the cost of learning variations that may be irrelevant to the current expert bank. A direct cluster classifier is therefore an informative ablation.

An expert is a dictionary containing an unordered operator set, an integer sample count between one and five, and an instruction string. Optional decomposition adds a short plan to the question. The interpreter always produces the specified number of CoT candidates; when either persona flag is present, two more candidates are added rather than substituted. If multiple candidates survive and sampling-ensemble or persona selection is enabled, a separate call chooses an answer. An optional revision then checks and rewrites it. All scored answer stages receive the same per-domain answer-format instruction. Empty final outputs and scoring failures receive zero; truncated outputs are retained and scored.

The local validation cap is 60 queries, with at least 20 reserved locally when possible; small clusters use the remaining available validation members. Construction uses one execution per candidate, while separate final comparisons use repeated executions. Search also stops at its configured cost or wall-time guard. These guards bound resource use rather than optimize the same objective as score acceptance. The two-grid-step margin was introduced to avoid accepting small fluctuations; with heterogeneous fractional scores and adaptive proposals, it is not a confidence bound.

The bottom-three restriction ranks within the cluster, excludes an operator only when all mapped probes are low-ranked, and exempts the single operator mapped from the selected seed probe. This handles many-to-one mappings without letting one low-ranked alias veto a well-supported operator. The implementation also has a nonempty-set fallback. The prior reduces available search choices; standalone outcomes do not identify all beneficial interactions, so its exclusion loss may be positive. The three-round budget was a limited construction allocation, not evidence of search convergence.

The optimizer is asked to edit one axis: sample count, addition to the operator set, removal from it, or instruction. For recognized edit types, the sanitizer resets fields outside that axis. An addition/removal request may still change several flags on its axis. Unknown edit types are logged and do not receive the same axis constraint, although vocabulary and prior filtering still apply. No unrestricted program synthesis or Monte Carlo tree search occurs in this interpreter.

Why the design choices remain ablations

The central objects are the outcome coordinates, their text approximation, and their use in construction. Changing a probe subset, normalization, feature backbone, number of clusters, assignment rule, or search optimizer changes an implementation of those objects. The corresponding intervention should hold the remaining executor, score contract, split, and resource allocation fixed. Behavioral versus semantic or random construction needs the same operator language and proposal budget; seed-only versus searched experts needs the same assignments. Measured A versus text B changes information access, so it diagnoses amortization rather than supplying a deployable competitor. These controls follow directly from the quantity each proposition characterizes.

The design also separates construction cost from serving cost. Probing and expert generation are offline investments; a text-only assignment incurs local encoder computation and the chosen expert’s calls. An amortization advantage requires both a stated quality target and lower per-query serving cost than the comparator. Since guided B uses more calls than single-call CoT without an established quality improvement, this experiment does not justify a break-even claim against CoT.

Data, scores, and information access

AIME is scored by the existing mathematical answer checker. GPQA extracts the option following the last Answer: marker, falling back to a letter match if that marker is absent. Every scored September arm receives the appropriate answer-format instruction. For coding, the scorer extracts Python code, executes at most 12 available public stdin/stdout tests with a ten-second limit per test, normalizes output whitespace, and returns the fraction passed. Unsupported functional or interactive tests are skipped. Missing runnable tests score zero. Public-test success need not imply correctness on hidden tests, and the aggregate metric weights each query equally rather than each benchmark equally. The implementation’s scoring and loading files are included in the provenance manifest.

Historical probe measurements and cross-repeat analysis

The twelve mixed-task probe coordinates, in stored order, are direct, CoT, CoT self-consistency, tree-of-thought, self-refinement, reflexion, retrieval, ReAct, tool use, debate, role team, and decomposition. These labels name concrete repository implementations; they do not imply exact reproduction of every original paper’s system. Both historical model panels have 21,600 unique training cells and 10,800 unique test cells: 600/300 queries, twelve probes, and three repeats. The offline audit verified completeness of every query–probe–repeat tensor and used the recorded scores without rerunning models.

The retrieval probe uses same-benchmark TF–IDF demonstrations with available reference answers and excludes the current query. The current generator explicitly supplies the training corpus when invoked for test fingerprints. The saved sample ledgers retain answer previews rather than complete prompts or retrieved identifiers, so they do not independently certify the retrieval membership of every historical call. The September routed-probe arm selects no retrieval probe. For future releases, complete retrieval provenance should accompany the scorer and model revision, since conditioning on another evaluation query’s label would change the information contract.

Encoder and representation ablations

The expanded-panel study fits an MLP on frozen BGE features, using a 510/90 outer training/validation partition stratified by benchmark. Its checkpoint records nested inner-split epoch selection followed by refitting on outer-training rows, selecting 24 epochs. Normalization statistics are fit on the permitted training partition. The reported MSE averages over coordinates; converting it to the expected squared Euclidean error used in the analysis requires multiplication by the number of coordinates. The study’s 90-query validation metrics should not be confused with performance on the separate 300-query routing test set. Text truncation in the frozen backbone is a further information boundary: relevant information outside its retained input cannot be recovered by the MLP.

Guided construction, splits, and executable semantics

Seed profiles use search-validation members rather than local holdout members. However, the optimizer’s marginal-value table computes its ALL column over all cluster members, including the local holdout. Furthermore, candidate proposals and acceptance reuse the same search-validation outcomes. Consequently neither the local holdout nor adaptively reused validation establishes the independent-selection assumptions of the conditional analysis. Only C1/C2 have stored local-holdout executions; we do not use them as independent confirmation. The outer 300 test queries do not participate in these searches.

Reproducibility and outstanding attribution

The accompanying evidence manifests record source paths, SHA-256 hashes, query memberships, per-query cross-repeat scores, recomputed means, and statistical conventions. The original evidence audit and expanded baseline audit perform no API calls and leave experimental artifacts unchanged; the latter additionally checks all reported adapted-search means against their saved per-query records and records corrected failure denominators. Historical panel size, semantic/random partitions, and decoder/executor controls are reported as ablations. A matched full guided-versus-unguided construction experiment, independent final candidate selection, capability-complete probe-to-operator mapping, and held-out margin-stratified encoder analysis are not present in the saved evidence. We therefore report no numerical outcomes for these missing interventions and do not infer their success from the conditional bounds.