factory.rs 14.3 KB
Newer Older
1
2
// Factory and pool for creating model-specific tool parsers with pooling support.

3
4
5
6
7
use std::{
    collections::HashMap,
    sync::{Arc, RwLock},
};

8
9
use tokio::sync::Mutex;

10
11
12
13
14
15
use crate::tool_parser::{
    parsers::{
        DeepSeekParser, Glm4MoeParser, GptOssHarmonyParser, GptOssParser, JsonParser, KimiK2Parser,
        LlamaParser, MistralParser, PassthroughParser, PythonicParser, QwenParser, Step3Parser,
    },
    traits::ToolParser,
16
17
18
};

/// Type alias for pooled parser instances.
19
pub type PooledParser = Arc<Mutex<Box<dyn ToolParser>>>;
20
21
22
23
24
25

/// Type alias for parser creator functions.
type ParserCreator = Arc<dyn Fn() -> Box<dyn ToolParser> + Send + Sync>;

/// Registry for model-specific tool parsers with pooling support.
#[derive(Clone)]
26
pub struct ParserRegistry {
27
28
29
    /// Creator functions for parsers (used when pool is empty)
    creators: Arc<RwLock<HashMap<String, ParserCreator>>>,
    /// Pooled parser instances for reuse
30
    pool: Arc<RwLock<HashMap<String, PooledParser>>>,
31
32
33
34
35
36
    /// Model pattern to parser name mappings
    model_mapping: Arc<RwLock<HashMap<String, String>>>,
    /// Default parser name
    default_parser: Arc<RwLock<String>>,
}

37
impl ParserRegistry {
38
39
40
41
42
43
    /// Create a new empty registry.
    pub fn new() -> Self {
        Self {
            creators: Arc::new(RwLock::new(HashMap::new())),
            pool: Arc::new(RwLock::new(HashMap::new())),
            model_mapping: Arc::new(RwLock::new(HashMap::new())),
44
            default_parser: Arc::new(RwLock::new("passthrough".to_string())),
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
        }
    }

    /// Register a parser creator for a given parser type.
    pub fn register_parser<F>(&self, name: &str, creator: F)
    where
        F: Fn() -> Box<dyn ToolParser> + Send + Sync + 'static,
    {
        let mut creators = self.creators.write().unwrap();
        creators.insert(name.to_string(), Arc::new(creator));
    }

    /// Map a model name/pattern to a parser
    pub fn map_model(&self, model: impl Into<String>, parser: impl Into<String>) {
        let mut mapping = self.model_mapping.write().unwrap();
        mapping.insert(model.into(), parser.into());
    }

    /// Get a pooled parser by exact name.
    /// Returns a shared parser instance from the pool, creating one if needed.
65
    pub fn get_pooled_parser(&self, name: &str) -> Option<PooledParser> {
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
        // First check if we have a pooled instance
        {
            let pool = self.pool.read().unwrap();
            if let Some(parser) = pool.get(name) {
                return Some(Arc::clone(parser));
            }
        }

        // If not in pool, create one and add to pool
        let creators = self.creators.read().unwrap();
        if let Some(creator) = creators.get(name) {
            let parser = Arc::new(Mutex::new(creator()));

            // Add to pool for future use
            let mut pool = self.pool.write().unwrap();
            pool.insert(name.to_string(), Arc::clone(&parser));

            Some(parser)
        } else {
            None
        }
    }

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
    /// Check if a parser with the given name is registered.
    pub fn has_parser(&self, name: &str) -> bool {
        let creators = self.creators.read().unwrap();
        creators.contains_key(name)
    }

    /// Create a fresh (non-pooled) parser instance by exact name.
    /// Returns a new parser instance for each call - useful for streaming where state isolation is needed.
    pub fn create_parser(&self, name: &str) -> Option<Box<dyn ToolParser>> {
        let creators = self.creators.read().unwrap();
        creators.get(name).map(|creator| creator())
    }

    /// Check if a parser can be created for a specific model without actually creating it.
    /// Returns true if a parser is available (registered) for this model.
    pub fn has_parser_for_model(&self, model: &str) -> bool {
        // Try exact match first
        {
            let mapping = self.model_mapping.read().unwrap();
            if let Some(parser_name) = mapping.get(model) {
                let creators = self.creators.read().unwrap();
                if creators.contains_key(parser_name) {
                    return true;
                }
            }
        }

        // Try prefix matching
        let model_mapping = self.model_mapping.read().unwrap();
        let best_match = model_mapping
            .iter()
            .filter(|(pattern, _)| {
                pattern.ends_with('*') && model.starts_with(&pattern[..pattern.len() - 1])
            })
            .max_by_key(|(pattern, _)| pattern.len());

        if let Some((_, parser_name)) = best_match {
            let creators = self.creators.read().unwrap();
            if creators.contains_key(parser_name) {
                return true;
            }
        }

132
133
134
        // Return false if no specific parser found for this model
        // (get_pooled will still fall back to default parser)
        false
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
    }

    /// Create a fresh (non-pooled) parser instance for a specific model.
    /// Returns a new parser instance for each call - useful for streaming where state isolation is needed.
    pub fn create_for_model(&self, model: &str) -> Option<Box<dyn ToolParser>> {
        // Try exact match first
        {
            let mapping = self.model_mapping.read().unwrap();
            if let Some(parser_name) = mapping.get(model) {
                if let Some(parser) = self.create_parser(parser_name) {
                    return Some(parser);
                }
            }
        }

        // Try prefix matching with more specific patterns first
        let model_mapping = self.model_mapping.read().unwrap();
        let best_match = model_mapping
            .iter()
            .filter(|(pattern, _)| {
                pattern.ends_with('*') && model.starts_with(&pattern[..pattern.len() - 1])
            })
            .max_by_key(|(pattern, _)| pattern.len());

        // Return the best matching parser
        if let Some((_, parser_name)) = best_match {
            if let Some(parser) = self.create_parser(parser_name) {
                return Some(parser);
            }
        }

        // Fall back to default parser
        let default = self.default_parser.read().unwrap().clone();
        self.create_parser(&default)
    }

171
    /// Get parser for a specific model
172
    pub fn get_pooled_for_model(&self, model: &str) -> Option<PooledParser> {
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
        // Try exact match first
        {
            let mapping = self.model_mapping.read().unwrap();
            if let Some(parser_name) = mapping.get(model) {
                if let Some(parser) = self.get_pooled_parser(parser_name) {
                    return Some(parser);
                }
            }
        }

        // Try prefix matching with more specific patterns first
        let model_mapping = self.model_mapping.read().unwrap();
        let best_match = model_mapping
            .iter()
            .filter(|(pattern, _)| {
                pattern.ends_with('*') && model.starts_with(&pattern[..pattern.len() - 1])
            })
            .max_by_key(|(pattern, _)| pattern.len());

        // Return the best matching parser
        if let Some((_, parser_name)) = best_match {
            if let Some(parser) = self.get_pooled_parser(parser_name) {
                return Some(parser);
            }
        }

        // Fall back to default parser
        let default = self.default_parser.read().unwrap().clone();
        self.get_pooled_parser(&default)
    }

    /// Clear the parser pool, forcing new instances to be created.
    pub fn clear_pool(&self) {
        let mut pool = self.pool.write().unwrap();
        pool.clear();
    }

    /// Set the default parser
    pub fn set_default_parser(&self, name: impl Into<String>) {
        let mut default = self.default_parser.write().unwrap();
        *default = name.into();
    }
}

217
impl Default for ParserRegistry {
218
219
220
221
222
223
224
    fn default() -> Self {
        Self::new()
    }
}

/// Factory for creating tool parsers based on model type.
#[derive(Clone)]
225
226
pub struct ParserFactory {
    registry: ParserRegistry,
227
228
}

229
impl ParserFactory {
230
231
    /// Create a new factory with default parsers registered.
    pub fn new() -> Self {
232
        let registry = ParserRegistry::new();
233
234

        // Register default parsers
235
        registry.register_parser("passthrough", || Box::new(PassthroughParser::new()));
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
        registry.register_parser("json", || Box::new(JsonParser::new()));
        registry.register_parser("mistral", || Box::new(MistralParser::new()));
        registry.register_parser("qwen", || Box::new(QwenParser::new()));
        registry.register_parser("pythonic", || Box::new(PythonicParser::new()));
        registry.register_parser("llama", || Box::new(LlamaParser::new()));
        registry.register_parser("deepseek", || Box::new(DeepSeekParser::new()));
        registry.register_parser("glm4_moe", || Box::new(Glm4MoeParser::new()));
        registry.register_parser("step3", || Box::new(Step3Parser::new()));
        registry.register_parser("kimik2", || Box::new(KimiK2Parser::new()));

        // Register GPT-OSS parsers
        registry.register_parser("gpt_oss_legacy", || Box::new(GptOssParser::new()));
        registry.register_parser("gpt_oss_harmony", || Box::new(GptOssHarmonyParser::new()));

        // Choose which GPT-OSS variant to use as default
        if use_harmony_gpt_oss() {
            registry.register_parser("gpt_oss", || Box::new(GptOssHarmonyParser::new()));
        } else {
            registry.register_parser("gpt_oss", || Box::new(GptOssParser::new()));
        }

        // Register default model mappings
        Self::register_default_mappings(&registry);

        Self { registry }
    }

263
    fn register_default_mappings(registry: &ParserRegistry) {
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
        // OpenAI models
        registry.map_model("gpt-4*", "json");
        registry.map_model("gpt-3.5*", "json");
        registry.map_model("gpt-4o*", "json");

        // Anthropic models
        registry.map_model("claude-*", "json");

        // Mistral models
        registry.map_model("mistral-*", "mistral");
        registry.map_model("mixtral-*", "mistral");

        // Qwen models
        registry.map_model("qwen*", "qwen");
        registry.map_model("Qwen*", "qwen");

        // Llama models
        registry.map_model("llama-4*", "pythonic");
        registry.map_model("meta-llama-4*", "pythonic");
        registry.map_model("llama-3.2*", "llama");
        registry.map_model("meta-llama-3.2*", "llama");
        registry.map_model("llama-*", "json");
        registry.map_model("meta-llama-*", "json");

        // DeepSeek models
        registry.map_model("deepseek-v3*", "deepseek");
        registry.map_model("deepseek-ai/DeepSeek-V3*", "deepseek");
        registry.map_model("deepseek-*", "pythonic");

        // GLM models
        registry.map_model("glm-4.5*", "glm4_moe");
        registry.map_model("glm-4.6*", "glm4_moe");
        registry.map_model("glm-*", "json");

        // Step3 models
        registry.map_model("step3*", "step3");
        registry.map_model("Step-3*", "step3");

        // Kimi models
        registry.map_model("kimi-k2*", "kimik2");
        registry.map_model("Kimi-K2*", "kimik2");
        registry.map_model("moonshot*/Kimi-K2*", "kimik2");

        // GPT-OSS models
        registry.map_model("gpt-oss*", "gpt_oss");
        registry.map_model("t4-*", "gpt_oss");

        // Other models
        registry.map_model("gemini-*", "json");
        registry.map_model("palm-*", "json");
        registry.map_model("gemma-*", "json");
    }

    /// Get a pooled parser for the given model ID.
    /// Returns a shared instance that can be used concurrently.
319
    /// Falls back to passthrough parser if model is not recognized.
320
    pub fn get_pooled(&self, model_id: &str) -> PooledParser {
321
322
323
        self.registry
            .get_pooled_for_model(model_id)
            .unwrap_or_else(|| {
324
                // Fallback to passthrough parser (no-op, returns text unchanged)
325
                self.registry
326
327
                    .get_pooled_parser("passthrough")
                    .expect("Passthrough parser should always be registered")
328
329
330
331
            })
    }

    /// Get the internal registry for custom registration.
332
    pub fn registry(&self) -> &ParserRegistry {
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
        &self.registry
    }

    /// Clear the parser pool.
    pub fn clear_pool(&self) {
        self.registry.clear_pool();
    }

    /// Get a non-pooled parser for the given model ID (creates a fresh instance each time).
    /// This is useful for benchmarks and testing where you want independent parser instances.
    pub fn get_parser(&self, model_id: &str) -> Option<Arc<dyn ToolParser>> {
        // Determine which parser type to use
        let parser_type = {
            let mapping = self.registry.model_mapping.read().unwrap();

            // Try exact match first
            if let Some(parser_name) = mapping.get(model_id) {
                parser_name.clone()
            } else {
                // Try prefix matching
                let best_match = mapping
                    .iter()
                    .filter(|(pattern, _)| {
                        pattern.ends_with('*')
                            && model_id.starts_with(&pattern[..pattern.len() - 1])
                    })
                    .max_by_key(|(pattern, _)| pattern.len());

                if let Some((_, parser_name)) = best_match {
                    parser_name.clone()
                } else {
                    // Fall back to default
                    self.registry.default_parser.read().unwrap().clone()
                }
            }
        };

        let creators = self.registry.creators.read().unwrap();
        creators.get(&parser_type).map(|creator| {
            // Call the creator to get a Box<dyn ToolParser>, then convert to Arc
            let boxed_parser = creator();
            Arc::from(boxed_parser)
        })
    }

    /// List all registered parsers (for compatibility with old API).
    pub fn list_parsers(&self) -> Vec<String> {
        self.registry
            .creators
            .read()
            .unwrap()
            .keys()
            .cloned()
            .collect()
    }
}

390
impl Default for ParserFactory {
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
    fn default() -> Self {
        Self::new()
    }
}

fn use_harmony_gpt_oss() -> bool {
    std::env::var("ROUTER_USE_HARMONY_GPT_OSS")
        .ok()
        .map(|value| {
            let normalized = value.trim();
            matches!(
                normalized,
                "1" | "true" | "TRUE" | "True" | "yes" | "YES" | "Yes" | "on" | "ON" | "On"
            )
        })
        .unwrap_or(false)
}