Skip to main content

car_multi/patterns/
vote.rs

1//! Vote — N agents answer independently, majority wins.
2//!
3//! For factual questions: normalized string matching picks the most common answer.
4//! For open-ended questions: an optional synthesizer picks the best.
5
6use crate::error::MultiError;
7use crate::mailbox::Mailbox;
8use crate::patterns::swarm::{Swarm, SwarmMode};
9use crate::runner::AgentRunner;
10use crate::shared::SharedInfra;
11use crate::types::{AgentOutput, AgentSpec};
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14use std::sync::Arc;
15use tracing::instrument;
16
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct VoteResult {
19    pub task: String,
20    pub votes: Vec<AgentOutput>,
21    pub winner: String,
22    pub agreement_ratio: f64,
23}
24
25pub struct Vote {
26    pub agents: Vec<AgentSpec>,
27    pub synthesizer: Option<AgentSpec>,
28}
29
30impl Vote {
31    pub fn new(agents: Vec<AgentSpec>) -> Self {
32        Self {
33            agents,
34            synthesizer: None,
35        }
36    }
37
38    pub fn with_synthesizer(mut self, spec: AgentSpec) -> Self {
39        self.synthesizer = Some(spec);
40        self
41    }
42
43    #[instrument(name = "multi.vote", skip_all)]
44    pub async fn run(
45        &self,
46        task: &str,
47        runner: &Arc<dyn AgentRunner>,
48        infra: &SharedInfra,
49    ) -> Result<VoteResult, MultiError> {
50        // All agents answer in parallel
51        let swarm = Swarm::new(self.agents.clone(), SwarmMode::Parallel);
52        let swarm_result = swarm.run(task, runner, infra).await?;
53
54        let votes = swarm_result.outputs;
55        let answers: Vec<AgentOutput> = votes.iter().filter(|o| o.succeeded()).cloned().collect();
56
57        if answers.is_empty() {
58            return Ok(VoteResult {
59                task: task.to_string(),
60                votes,
61                winner: String::new(),
62                agreement_ratio: 0.0,
63            });
64        }
65
66        if let Some(synth_spec) = &self.synthesizer {
67            let vote_summary: Vec<String> = answers
68                .iter()
69                .map(|o| format!("- {}: {}", o.name, truncate(&o.answer, 200)))
70                .collect();
71
72            let synth_task = format!(
73                "Task: {}\n\nVotes:\n{}\n\nPick the best answer or synthesize a consensus.",
74                task,
75                vote_summary.join("\n")
76            );
77
78            let mailbox = Mailbox::default();
79            let rt = infra.make_runtime();
80            let winner = runner
81                .run(synth_spec, &synth_task, &rt, &mailbox)
82                .await
83                .map(|o| o.answer)
84                .unwrap_or_else(|_| answers[0].answer.clone());
85
86            return Ok(VoteResult {
87                task: task.to_string(),
88                votes,
89                winner,
90                agreement_ratio: 1.0,
91            });
92        }
93
94        // Simple majority: pick the most common answer (normalized)
95        let mut counter: HashMap<String, usize> = HashMap::new();
96        for a in &answers {
97            let normalized = a.answer.trim().to_lowercase();
98            *counter.entry(normalized).or_insert(0) += 1;
99        }
100
101        let (most_common, count) = counter
102            .iter()
103            .max_by_key(|(_, c)| *c)
104            .map(|(k, c)| (k.clone(), *c))
105            .unwrap_or_default();
106
107        // Find the original (un-normalized) answer
108        let winner = answers
109            .iter()
110            .find(|a| a.answer.trim().to_lowercase() == most_common)
111            .map(|a| a.answer.clone())
112            .unwrap_or_default();
113
114        Ok(VoteResult {
115            task: task.to_string(),
116            votes,
117            winner,
118            agreement_ratio: count as f64 / answers.len() as f64,
119        })
120    }
121}
122
123fn truncate(s: &str, max_len: usize) -> &str {
124    if s.len() <= max_len {
125        return s;
126    }
127    let mut end = max_len;
128    while end > 0 && !s.is_char_boundary(end) {
129        end -= 1;
130    }
131    &s[..end]
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137    use crate::types::{AgentOutput, AgentSpec};
138    use car_engine::Runtime;
139
140    struct FixedRunner;
141
142    #[async_trait::async_trait]
143    impl crate::runner::AgentRunner for FixedRunner {
144        async fn run(
145            &self,
146            spec: &AgentSpec,
147            _task: &str,
148            _runtime: &Runtime,
149            _mailbox: &Mailbox,
150        ) -> Result<AgentOutput, MultiError> {
151            // Agents 0 and 2 agree, agent 1 disagrees
152            let answer = if spec.name.ends_with('1') {
153                "Paris is the capital"
154            } else {
155                "The capital is Paris"
156            };
157            Ok(AgentOutput {
158                name: spec.name.clone(),
159                answer: answer.to_string(),
160                turns: 1,
161                tool_calls: 0,
162                duration_ms: 5.0,
163                error: None,
164                outcome: None,
165                tokens: None,
166            })
167        }
168    }
169
170    #[tokio::test]
171    async fn test_vote_majority() {
172        let agents: Vec<AgentSpec> = (0..3)
173            .map(|i| AgentSpec::new(&format!("voter_{}", i), "Answer the question"))
174            .collect();
175
176        let runner: Arc<dyn crate::runner::AgentRunner> = Arc::new(FixedRunner);
177        let infra = SharedInfra::new();
178
179        let result = Vote::new(agents)
180            .run("What is the capital of France?", &runner, &infra)
181            .await
182            .unwrap();
183
184        assert_eq!(result.votes.len(), 3);
185        // 2/3 agree on "The capital is Paris"
186        assert_eq!(result.winner, "The capital is Paris");
187        assert!((result.agreement_ratio - 2.0 / 3.0).abs() < 0.01);
188    }
189}