Manuscript Offprint

arXiv:2610.07851

RA-MoWE: Workflow-Affinity Embeddings for Query Clustering and Agentic Workflow Generation

Qi Cheng, Shengyu Chen, Wei Cheng, Yiqun Xie, Haoyu Wang, Haifeng Chen, Xiaowei Jia

Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.

Qi Cheng

Rutgers University

New Brunswick, NJ

q.cheng@rutgers.edu

Shengyu Chen

University of Pittsburgh

Pittsburgh, PA

shc160@pitt.edu

Wei Cheng

NEC Labs America

Princeton, NJ

weicheng@nec-labs.com

Yiqun Xie

University of Maryland

College Park, MD

xie@umd.edu

Haoyu Wang

NEC Labs America

Princeton, NJ

haoyu@nec-labs.com

Haifeng Chen

NEC Labs America

Princeton, NJ

haifeng@nec-labs.com

Xiaowei Jia

Rutgers University

New Brunswick, NJ

xj159@cs.rutgers.edu

ABSTRACT

Agentic workflows enable large language models (LLMs) to solve complex tasks by coordinating reasoning, tool use, and verification. However, a workflow optimized for an entire task collection can overlook differences in the reasoning strategies that individual queries need, while searching for a new workflow for every query repeats costly optimization. To address this tradeoff, we introduce RA-MoWE, a framework that uses workflow-affinity embeddings to cluster queries and guide the generation of reusable expert workflows. Each embedding records how well a fixed set of reference workflows solves a query, revealing similarities in which reasoning strategies are effective. RA-MoWE uses each cluster's queries and average embedding to initialize and refine a specialized workflow through execution feedback. An embedding encoder predicts these embeddings from query text, allowing new queries to select a generated expert without first executing the reference workflows. On a 300-query test set drawn from four benchmarks spanning mathematics, science, and programming, RA-MoWE improves average task score by 4.04 percentage points over selecting among the reference workflows, while using 27.7% fewer language-model calls at inference.

1 INTRODUCTION

Agentic workflows organize large language model (LLM) calls into procedures for reasoning, revising answers, and using tools, extending their capabilities on complex tasks (Yao et al., 2023b; Madaan et al., 2023). 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 (Hu et al., 2025; Zhang et al., 2025b).

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 (Hu et al., 2025; Zhang et al., 2025b; Shang et al., 2025). 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 (Gao et al., 2025), learn to generate a workflow for each query. These methods need

(a) Affinity profiles of query clusters

Cluster (total queries)

C0 (301).04-.03-.03.00.07.00.05.03-.07.01-.03-.05
C1 (83).13.08.03.13-.25.03-.01-.19-.17.11.05.06
C2 (42)-.11.24.67-.42.14.19-.23-.78-.49.16.27.36
C3 (48).29-.33-.44.40-.30-.02-.19.49.45.30-.34-.32
C4 (82)-.15.09-.05-.03.31.05.10.22-.46-.19.08.03
C5 (44)-.16-.18-.11-.11-.23-.19-.15.07.60-.19-.18-.17

(b) Generated workflows

SeedStored expert
RefineRefine
CoTCoT
Ens.(3)Ens.(3)
Ens.(3)*Plan + Ens.(4)
RefineRefine
Ens.(3)*Ens.(3)

Ens.(n): n CoT samples with answer selection. * Runnable fallback.

Figure 1: Different workflow preferences motivate specialized experts. (a) Average embeddings for six GPT-4o-mini training-query clusters show distinct responses to reference workflows. C2 favors sampling and answer selection (CoT-SC), whereas C4 favors self-refinement. (b) RA-MoWE uses these preferences to choose initial workflows. Values are standardized scores centered within each row; outlines mark row maxima, and parentheses give full cluster sizes. Refine revises a chain-of-thought (CoT) answer; Ens.(n) selects among n sampled CoT answers; Plan adds decomposition. Asterisks mark runnable substitutes for unavailable workflows. Measurement details are in Appendix C.4.

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 integrate this idea into RA-MoWE, a framework that uses the workflow-affinity embeddings to guide the generation of reusable expert workflows. Offline, we execute the reference workflows on training queries, compute their embeddings, and partition them into clusters. Clustering these embeddings groups queries with similar measured responses, giving expert construction both a focused set of examples and evidence about potentially useful reasoning strategies. For each cluster, we introduce an embedding-guided search mechanism, which uses the cluster prototype to choose an executable starting workflow and constrain the candidate operations. It then proposes refinements informed by execution feedback and probe outcomes on remaining failures, retaining edits that improve the cluster's validation score. The resulting expert is stored for reuse. Figure 1 connects the measured cluster affinities to the workflows produced by this process.

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.

Our contributions are:

  1. Workflow-affinity embeddings that represent queries through measured workflow outcomes and organize training examples for specialist construction.

  2. An embedding encoder that predicts this representation from text, enabling expert selection without online reference-workflow execution.

  3. Embedding-guided expert generation that uses cluster affinities, query examples, and failure feedback to initialize and refine reusable workflows.

Our analysis identifies when measurement and prediction errors preserve useful decisions and when the available workflow operations support transfer from a strong probe to a generated expert.

References (93)

  • FrugalGPT: How to use large language models while reducing cost and improving performance
  • Improving factuality and reasoning in language models through multiagent debate
  • FlowReasoner: Reinforcing query-level meta-agents (opens arXiv in a new tab)
  • Wassily Hoeffding. Probability inequalities for sums of bounded random variables. Journal of the American Statistical Association, 58(301):13–30, 1963. doi: 10.1080/01621459.1963.10500830. (opens the publisher in a new tab)
  • Automated design of agentic systems
  • Editing models with task arithmetic
  • LiveCodeBench: Holistic and contamination free evaluation of large language models for code
  • SWE-bench: Can language models resolve real-world GitHub issues? In International Conference on Learning Representations, 2024
  • Competition-level code generation with AlphaCode
  • Routing manifold alignment improves generalization of mixture-of-experts LLMs
  • Self-Refine: Iterative refinement with self-feedback
  • MTEB: Massive text embedding benchmark (opens the publisher in a new tab)
  • Learning to orchestrate agents in natural language with the conductor
  • RouteLLM: Learning to route LLMs with preference data
  • GPQA: A graduate-level google-proof Q&A benchmark
  • John R. Rice. The algorithm selection problem. In Advances in Computers, volume 15, pp. 65–118. Elsevier, 1976. doi: 10.1016/S0065-2458(08)60520-3. (opens the publisher in a new tab)
  • AgentSquare: Automatic LLM agent search in modular design space
  • Reflexion: Language agents with verbal reinforcement learning
  • Function vectors in large language models
  • Self-consistency improves chain of thought reasoning in language models
  • ScoreFlow: Mastering LLM agent workflows via score-based preference optimization (opens arXiv in a new tab)
  • Chain-of-thought prompting elicits reasoning in large language models
  • Demystifying LLM-based software engineering agents (opens the publisher in a new tab)
  • C-Pack: Packed resources for general chinese embeddings (opens the publisher in a new tab)
  • Tree of thoughts: Deliberate problem solving with large language models
  • ReAct: Synergizing reasoning and acting in language models
  • MasRouter: Learning to route LLMs for multi-agent systems (opens the publisher in a new tab)
  • Learning invariant representations for reinforcement learning without reconstruction
  • Multi-agent architecture search via agentic supernet
  • AFlow: Automating agentic workflow generation
  • Qwen3 Embedding: Advancing Text Embedding and Reranking Through Foundation Models
  • Least-to-most prompting enables complex reasoning in large language models
  • The arguments adapt standard concentration and decision-theoretic tools; they are not claims of new concentration inequalities or a universal sufficiency theorem
  • A protocol specifies the model and endpoint, prompts, available tools, answer extraction, score, execution limits, and failure handling
  • Evaluation queries are fresh
  • A union bound over $K$ coordinates proves the stated $2K \exp(-2S\epsilon^2)$ bound
  • For fixed train-fitted $\Lambda$
  • Taking expectations proves the reward-difference bound
  • Writing $\bar{Z} = \bar{z}(Q)$, both sources of error matter when comparing the measured route with the encoder:
  • Assume finite second moments, fixed affine normalization, and $\bar{Z} = Z + \xi$ with $\mathbb{E}[\xi \mid Q] = 0$
  • The current mapping merges several probe families, omits tool-use and ReAct executors, and adds a chain-of-thought instruction to every guided seed
  • More repeated executions do not eliminate finite-query uncertainty
  • Candidate scores may be dependent across workflows
  • This is the price, relative to per-query probe selection, of requiring one probe decision per population cluster; generated experts may recover or exceed this lost value
  • Empty clusters contribute zero
  • A mapping is an implementation approximation, not an equivalence assertion
  • It does not establish that any term is small
  • Table 2 distinguishes the measured implementations from their generator-side approximations
  • For the CoT-SC probe, the five inner samples occur within each repetition and must not be counted as five independent fingerprint observations
  • It does not inherit the affine-noise decomposition in Equation (18)
  • A fitted standard deviation below $10^{-8}$ is replaced by one, avoiding division by zero; a nonconstant but low-variance coordinate can still receive a large weight
  • Its target is $\bar{z}(q)$
  • Its loss term encourages agreement in the relative pattern of probe responses; the second term penalizes coordinate error in the space used for cluster assignment
  • Long questions can therefore lose relevant content before the trainable head; Proposition 3 does not eliminate that information loss
  • The width and loss weights are fixed capacity and optimization choices; no experiment establishes them as optimal
  • The centroids use the encoder checkpoint's normalization
  • For any vector $v$ in the standardized embedding space, the assignment rule and construction members are
  • A clustering centroid $c_j$ summarizes its full cluster; the generation embedding $\rho_j$ averages the search-validation subset defined below and need not equal $c_j$
  • Optional decomposition adds a short plan to the question
  • With fewer surviving candidates, the actual selection stage can differ; empirical costs use recorded calls
  • Construction uses one execution per candidate, while separate final comparisons use repeated executions
  • This handles many-to-one mappings without letting one low-ranked alias veto a well-supported operator
  • For recognized edit types, the sanitizer resets fields outside that axis
  • Changing a probe subset, normalization, feature backbone, number of clusters, assignment rule, or search optimizer changes an implementation of those objects
  • These labels name concrete repository implementations; they do not imply exact reproduction of every original paper's system
  • The current generator explicitly supplies the training corpus when invoked for test fingerprints
  • Training-priority ties use decreasing mean score across the 600 training queries, with stored probe order as a final deterministic tie rule
  • Each resample draws queries with replacement within their benchmark and preserves the observed benchmark counts
  • Its checkpoint records nested inner-split epoch selection followed by refitting on outer-training rows, selecting 24 epochs
  • Adding tree-of-thought, reflexion, ReAct, and role team increases the number of distinct measured fingerprints from 281 to 329 and effective rank from 2.6698 to 3.0819
  • Historical inference uses query-paired confidence intervals and sign-flip tests with Holm adjustment within the stored comparison families
  • Probe scores average three executions, whereas the searched workflow scores follow their stored evaluation protocol
  • Increasing to four samples yields 0.4107; adding decomposition yields 0.4821
  • A Hungarian bijection fitted solely to their 600 training assignments maps paper labels 0, 1, 2, 3, 4, 5 to expert labels 4, 2, 1, 3, 5, 0, with 517/600 agreements
  • SD is across the three pass means, not a standard error over queries
  • The single-call controls were executed subsequently on the same queries using the guided executor's unmodified single-call implementation
  • average each query across its three executions, then resample queries without benchmark stratification
  • Twelve policy texts form the measured panel; ReAct, reflexion, and tool-use labels are single-turn analogues here
  • The adaptation names in Table 1 specify the evaluated systems
  • The mixed-task bank uses AFlow's workflow search (Zhang et al., 2025b), with Custom and ScEnsemble operators, five optimization rounds after initialization, parent sample size four, one validation execution per query, and the executor itself as optimizer
  • Its meta-model is GPT-4o-mini or Haiku, matching the executor rather than the original GPT-4-class meta-agent
  • It resolves 34/200 instances at USD 0.00227 per instance
  • The higher-budget FrugalGPT configuration selects the identical cascade
  • the training-selected GPT-4o-mini mixed-task probe is tool use, Haiku selects self-consistency, and SWE selects retrieval
  • Twelve-probe $B$ reaches 0.3153, but random partitions also improve and eight-probe $B$ decreases
  • The saved mixed-task ledger covers only the experts actually executed by $A$ or $B$, so alternative routes can be scored only where they select one of those recorded experts
  • Six BGE executions remain failed in the saved artifact and are counted as zero; this row is .2861 on the full denominator rather than a completed-only mean
  • The analysis therefore evaluates the available preview features, not what complete generations could support
  • The observed per-query maximum is 0.4961, although 194 queries give identical scores for all six executions
  • These replace unavailable original-paper model versions, and DeepSeek is omitted
  • The full Haiku probe program (eight/twelve probes, training/test) records 115,330 calls and USD 603.90
  • The seven D comparisons are twelve/eight-probe A/B, BGE, Qwen3, and random
  • 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