converge-provider 3.7.3

LLM provider implementations for Converge
Documentation
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
// Copyright 2024-2026 Reflective Labs
// SPDX-License-Identifier: MIT

//! Provider selection via bipartite matching.
//!
//! Reads a [`ProviderRequest`] from context, matches required capabilities
//! against the registered backend pool using Hopcroft-Karp, and proposes a
//! [`ProviderAssignment`] to [`ContextKey::Strategies`].

use std::sync::Arc;

use async_trait::async_trait;
use converge_optimization::graph::matching::bipartite_matching;
use converge_pack::{AgentEffect, Context, ContextKey, ProposedFact, Suggestor};
use converge_provider_api::{
    Backend, BackendRequirements, CapabilityAssignment, ProviderAssignment, ProviderRequest,
};

// ── Suggestor ─────────────────────────────────────────────────────────────────

const REQUEST_PREFIX: &str = "provider-request:";
const ASSIGNMENT_PREFIX: &str = "provider-assignment:";
const MALFORMED_PREFIX: &str = "provider-request-error:";

/// Routes required capabilities to available backends via bipartite matching.
///
/// # Construction
///
/// ```rust,ignore
/// let backends: Vec<Arc<dyn Backend>> = vec![
///     Arc::new(AnthropicBackend::from_env()),
///     Arc::new(KongBackend::from_env()),
/// ];
///
/// engine.register_suggestor(ProviderSelectionSuggestor::new(backends));
/// ```
pub struct ProviderSelectionSuggestor {
    backends: Vec<Arc<dyn Backend>>,
}

impl ProviderSelectionSuggestor {
    pub fn new(backends: Vec<Arc<dyn Backend>>) -> Self {
        Self { backends }
    }
}

#[async_trait]
impl Suggestor for ProviderSelectionSuggestor {
    fn name(&self) -> &str {
        "ProviderSelectionSuggestor"
    }

    fn dependencies(&self) -> &[ContextKey] {
        &[ContextKey::Seeds]
    }

    fn accepts(&self, ctx: &dyn Context) -> bool {
        ctx.get(ContextKey::Seeds).iter().any(|f| {
            f.id.starts_with(REQUEST_PREFIX)
                && match serde_json::from_str::<ProviderRequest>(&f.content) {
                    Ok(_) => !assignment_exists(ctx, request_id(&f.id)),
                    Err(_) => !malformed_diagnostic_exists(ctx, &f.id),
                }
        })
    }

    async fn execute(&self, ctx: &dyn Context) -> AgentEffect {
        let mut proposals = Vec::new();

        for fact in ctx
            .get(ContextKey::Seeds)
            .iter()
            .filter(|f| f.id.starts_with(REQUEST_PREFIX))
        {
            match serde_json::from_str::<ProviderRequest>(&fact.content) {
                Ok(req) => {
                    if assignment_exists(ctx, request_id(&fact.id)) {
                        continue;
                    }

                    let assignment = route(&req, &self.backends);
                    proposals.push(
                        ProposedFact::new(
                            ContextKey::Strategies,
                            format!("{}{}", ASSIGNMENT_PREFIX, assignment.request_id),
                            serde_json::to_string(&assignment).unwrap_or_default(),
                            self.name(),
                        )
                        .with_confidence(assignment.coverage_ratio),
                    );
                }
                Err(error) => {
                    if malformed_diagnostic_exists(ctx, &fact.id) {
                        continue;
                    }

                    let diagnostic = serde_json::json!({
                        "request_fact_id": fact.id,
                        "message": "malformed provider request ignored",
                        "error": error.to_string(),
                    });
                    proposals.push(
                        ProposedFact::new(
                            ContextKey::Diagnostic,
                            malformed_diagnostic_id(&fact.id),
                            diagnostic.to_string(),
                            self.name(),
                        )
                        .with_confidence(1.0),
                    );
                }
            }
        }

        if proposals.is_empty() {
            AgentEffect::empty()
        } else {
            AgentEffect::with_proposals(proposals)
        }
    }
}

// ── Matching logic ────────────────────────────────────────────────────────────

fn route(req: &ProviderRequest, backends: &[Arc<dyn Backend>]) -> ProviderAssignment {
    if let Some(requirements) = &req.backend_requirements {
        return route_backend_requirements(req, requirements, backends);
    }

    // Left = required capability slots (index = position in req.required_capabilities).
    // Right = backends (index = position in `backends`).
    // Edge: backends[j].has_capability(req.required_capabilities[i]).
    let edges: Vec<(usize, usize)> = req
        .required_capabilities
        .iter()
        .enumerate()
        .flat_map(|(i, cap)| {
            let cap = cap.clone();
            backends
                .iter()
                .enumerate()
                .filter(move |(_, b)| b.has_capability(cap.clone()))
                .map(move |(j, _)| (i, j))
        })
        .collect();

    let matching = bipartite_matching(req.required_capabilities.len(), backends.len(), &edges)
        .unwrap_or_default();

    let mut covered = vec![false; req.required_capabilities.len()];
    let mut assignments = Vec::with_capacity(matching.size);

    for (cap_idx, backend_idx) in &matching.pairs {
        assignments.push(CapabilityAssignment {
            capability: req.required_capabilities[*cap_idx].clone(),
            backend_name: backends[*backend_idx].name().to_string(),
        });
        covered[*cap_idx] = true;
    }

    let unmatched = req
        .required_capabilities
        .iter()
        .enumerate()
        .filter(|(i, _)| !covered[*i])
        .map(|(_, c)| c.clone())
        .collect::<Vec<_>>();

    let coverage_ratio = if req.required_capabilities.is_empty() {
        1.0
    } else {
        matching.size as f64 / req.required_capabilities.len() as f64
    };

    ProviderAssignment {
        request_id: req.id.clone(),
        assignments,
        unmatched,
        coverage_ratio,
    }
}

fn route_backend_requirements(
    req: &ProviderRequest,
    requirements: &BackendRequirements,
    backends: &[Arc<dyn Backend>],
) -> ProviderAssignment {
    let required_capabilities = if requirements.required_capabilities.is_empty() {
        req.required_capabilities.clone()
    } else {
        requirements.required_capabilities.clone()
    };

    let matched_backend = backends.iter().find(|backend| {
        backend.kind() == requirements.kind
            && required_capabilities
                .iter()
                .all(|capability| backend.has_capability(capability.clone()))
            && (!requirements.requires_replay || backend.supports_replay())
            && (!requirements.requires_offline || !backend.requires_network())
    });

    if let Some(backend) = matched_backend {
        let assignments = required_capabilities
            .iter()
            .cloned()
            .map(|capability| CapabilityAssignment {
                capability,
                backend_name: backend.name().to_string(),
            })
            .collect::<Vec<_>>();
        return ProviderAssignment {
            request_id: req.id.clone(),
            assignments,
            unmatched: Vec::new(),
            coverage_ratio: 1.0,
        };
    }

    let coverage_ratio = if required_capabilities.is_empty() {
        1.0
    } else {
        0.0
    };
    ProviderAssignment {
        request_id: req.id.clone(),
        assignments: Vec::new(),
        unmatched: required_capabilities,
        coverage_ratio,
    }
}

// ── Helpers ───────────────────────────────────────────────────────────────────

fn request_id(fact_id: &str) -> &str {
    fact_id.trim_start_matches(REQUEST_PREFIX)
}

fn assignment_exists(ctx: &dyn Context, request_id: &str) -> bool {
    let assignment_id = format!("{}{}", ASSIGNMENT_PREFIX, request_id);
    ctx.get(ContextKey::Strategies)
        .iter()
        .any(|f| f.id == assignment_id)
}

fn malformed_diagnostic_id(fact_id: &str) -> String {
    format!("{MALFORMED_PREFIX}{fact_id}")
}

fn malformed_diagnostic_exists(ctx: &dyn Context, fact_id: &str) -> bool {
    let diagnostic_id = malformed_diagnostic_id(fact_id);
    ctx.get(ContextKey::Diagnostic)
        .iter()
        .any(|fact| fact.id == diagnostic_id)
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use converge_core::{ContextState, Engine};
    use converge_provider_api::{BackendKind, Capability};

    struct MockBackend {
        name: &'static str,
        kind: BackendKind,
        capabilities: Vec<Capability>,
        supports_replay: bool,
        requires_network: bool,
    }

    impl Backend for MockBackend {
        fn name(&self) -> &str {
            self.name
        }
        fn kind(&self) -> BackendKind {
            self.kind.clone()
        }
        fn capabilities(&self) -> Vec<Capability> {
            self.capabilities.clone()
        }
        fn supports_replay(&self) -> bool {
            self.supports_replay
        }
        fn requires_network(&self) -> bool {
            self.requires_network
        }
    }

    fn backend(name: &'static str, caps: &[Capability]) -> Arc<dyn Backend> {
        backend_with(name, BackendKind::Llm, caps, false, true)
    }

    fn backend_with(
        name: &'static str,
        kind: BackendKind,
        caps: &[Capability],
        supports_replay: bool,
        requires_network: bool,
    ) -> Arc<dyn Backend> {
        Arc::new(MockBackend {
            name,
            kind,
            capabilities: caps.to_vec(),
            supports_replay,
            requires_network,
        })
    }

    fn request(id: &str, caps: &[Capability]) -> ProviderRequest {
        ProviderRequest {
            id: id.to_string(),
            required_capabilities: caps.to_vec(),
            backend_requirements: None,
        }
    }

    #[test]
    fn full_coverage_when_all_capabilities_available() {
        let pool = vec![
            backend("anthropic", &[Capability::Reasoning]),
            backend("kong", &[Capability::AccessControl]),
            backend("elastic", &[Capability::FullTextSearch]),
        ];
        let req = request(
            "req-1",
            &[
                Capability::Reasoning,
                Capability::AccessControl,
                Capability::FullTextSearch,
            ],
        );

        let assignment = route(&req, &pool);

        assert_eq!(assignment.assignments.len(), 3);
        assert!(assignment.unmatched.is_empty());
        assert!((assignment.coverage_ratio - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn partial_coverage_when_capability_missing() {
        let pool = vec![backend("anthropic", &[Capability::Reasoning])];
        let req = request("req-2", &[Capability::Reasoning, Capability::AccessControl]);

        let assignment = route(&req, &pool);

        assert_eq!(assignment.assignments.len(), 1);
        assert_eq!(assignment.unmatched, vec![Capability::AccessControl]);
        assert!((assignment.coverage_ratio - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn no_double_booking_with_two_same_capability_slots() {
        let pool = vec![
            backend("anthropic", &[Capability::Reasoning]),
            backend("openai", &[Capability::Reasoning]),
        ];
        let req = request("req-3", &[Capability::Reasoning, Capability::Reasoning]);

        let assignment = route(&req, &pool);

        assert_eq!(assignment.assignments.len(), 2);
        let names: Vec<_> = assignment
            .assignments
            .iter()
            .map(|a| &a.backend_name)
            .collect();
        let unique: std::collections::HashSet<_> = names.iter().collect();
        assert_eq!(unique.len(), 2);
    }

    #[test]
    fn multi_capability_backend_can_only_fill_one_slot() {
        // One backend that has both capabilities but should only fill one slot.
        let pool = vec![backend(
            "all-in-one",
            &[Capability::Reasoning, Capability::AccessControl],
        )];
        let req = request("req-4", &[Capability::Reasoning, Capability::AccessControl]);

        let assignment = route(&req, &pool);

        // Only one slot filled — backend can't be double-booked.
        assert_eq!(assignment.assignments.len(), 1);
        assert_eq!(assignment.unmatched.len(), 1);
    }

    #[test]
    fn empty_pool_yields_zero_coverage() {
        let req = request("req-5", &[Capability::Reasoning]);
        let assignment = route(&req, &[]);
        assert_eq!(assignment.coverage_ratio, 0.0);
        assert_eq!(assignment.unmatched, vec![Capability::Reasoning]);
    }

    #[test]
    fn empty_request_yields_full_coverage() {
        let pool = vec![backend("anthropic", &[Capability::Reasoning])];
        let req = request("req-6", &[]);
        let assignment = route(&req, &pool);
        assert!((assignment.coverage_ratio - 1.0).abs() < f64::EPSILON);
        assert!(assignment.assignments.is_empty());
    }

    #[test]
    fn backend_requirements_select_one_backend_satisfying_role_constraints() {
        let pool = vec![
            backend("remote-llm", &[Capability::AccessControl]),
            backend_with(
                "local-policy",
                BackendKind::Policy,
                &[Capability::AccessControl],
                true,
                false,
            ),
        ];
        let req = ProviderRequest {
            id: "policy-role".to_string(),
            required_capabilities: vec![],
            backend_requirements: Some(
                BackendRequirements::access_policy()
                    .with_replay()
                    .with_offline(),
            ),
        };

        let assignment = route(&req, &pool);

        assert_eq!(assignment.assignments.len(), 1);
        assert_eq!(assignment.assignments[0].backend_name, "local-policy");
        assert!(assignment.unmatched.is_empty());
        assert!((assignment.coverage_ratio - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn repeated_routing_is_deterministic_for_equal_candidates() {
        let pool = vec![
            backend("reasoner-a", &[Capability::Reasoning]),
            backend("reasoner-b", &[Capability::Reasoning]),
            backend("policy-a", &[Capability::AccessControl]),
        ];
        let req = request(
            "req-7",
            &[
                Capability::Reasoning,
                Capability::Reasoning,
                Capability::AccessControl,
            ],
        );

        let first = route(&req, &pool);
        let second = route(&req, &pool);

        assert_eq!(first.assignments, second.assignments);
        assert_eq!(first.unmatched, second.unmatched);
        assert_eq!(first.coverage_ratio, second.coverage_ratio);
    }

    #[tokio::test]
    async fn malformed_request_emits_diagnostic_once() {
        let mut engine = Engine::new();
        engine.register_suggestor(ProviderSelectionSuggestor::new(vec![backend(
            "anthropic",
            &[Capability::Reasoning],
        )]));

        let mut ctx = ContextState::new();
        ctx.add_input(ContextKey::Seeds, "provider-request:broken", "{")
            .expect("seed should stage");

        let first = engine.run(ctx).await.expect("run should converge");
        let diagnostics = first.context.get(ContextKey::Diagnostic);
        assert_eq!(diagnostics.len(), 1);
        assert_eq!(
            diagnostics[0].id,
            "provider-request-error:provider-request:broken"
        );
        assert!(!first.context.has(ContextKey::Strategies));

        let mut rerun_engine = Engine::new();
        rerun_engine.register_suggestor(ProviderSelectionSuggestor::new(vec![backend(
            "anthropic",
            &[Capability::Reasoning],
        )]));
        let second = rerun_engine
            .run(first.context.clone())
            .await
            .expect("rerun should converge");
        assert_eq!(second.context.get(ContextKey::Diagnostic).len(), 1);
    }
}