traiy_core 0.0.13

An utility to serve AI suggestions according to user-provided guidelines and (optionally) context
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
//! # Command Line Interface (CLI) module
//!
//! This module defines the command-line interface for an application that generates
//! and enhances content based on user-provided inputs, guidelines, and context.
//! It uses the `clap` crate for argument parsing and supports different LLM providers
//! like Google and OpenAI for content generation.
//!
//! The module includes functionalities for:
//! - Reading input, guidelines, and context files.
//! - Generating recommendations based on specified criteria.
//! - Validating file paths and LLM provider/model compatibility.
//!
//! ## Usage
//!
//! The application can be used to generate content recommendations or enhance existing content
//! by specifying the appropriate subcommands and arguments.
//!
//! ## Subcommands
//!
//! - `recommend`: Generates recommendations based on input, guidelines, and context files.
//! - `enhance`: Enhances existing content (functionality not yet implemented).

use anyhow::{Result, anyhow};
use clap::Parser;
use clap::Subcommand;
use log::{debug, error};
use std::fs;
use std::path::PathBuf;

use crate::config::CompatibilityConfig;
use crate::enums::FileType;
use crate::enums::LlmModel;
use crate::enums::LlmProvider;
use crate::utils;

/// Application Configuration
///
/// Application for generating and enhancing content.
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
pub struct Cli {
    #[command(subcommand)]
    pub action: Action,
}

#[derive(Subcommand, Debug, Clone)]
pub enum Action {
    /// Generates recommendations based on input.
    Recommend {
        /// Input Files Options
        /// The path to the input file that needs processing.
        #[arg(short, long, help = "Path to the input file")]
        input_csv: PathBuf,

        /// The path to the guidelines file containing points/instructions.
        #[arg(short, long, help = "Path to the guidelines file")]
        guidelines_csv: PathBuf,

        /// Context to consider from recommendations
        #[arg(short, long, help = "Path to the context file")]
        context_csv: Option<PathBuf>,

        /// Recommend Options
        /// The approximate number of recommendations to generate
        #[arg(short, long, help = "Number of recommendations")]
        num_recommendations: Option<u32>,

        /// Llm Options
        // Backend LLM provider
        #[arg(short, long, value_enum, help = "LLM Provider", default_value_t = LlmProvider::Google)]
        llm_provider: LlmProvider,

        /// Llm models available per provider
        #[arg(short, long, help = "LLM Provider Model", default_value_t = LlmModel::GeminiFlash2)]
        model: LlmModel,

        /// Max tokens for output
        #[arg(long, help = "Max tokens for output")]
        max_tokens: Option<u32>,

        /// Temperature
        #[arg(long, help = "Temperature")]
        temperature: Option<f32>,
    },
    /// Enhances existing content (functionality not yet implemented).
    Enhance {
        /// Path to the content file to enhance.
        #[arg(short, long, help = "Path to the input file")]
        input_csv: PathBuf,
    },
}

impl Cli {
    /// Checks if a file exists at the given path and returns a Result.
    ///
    /// Logs an error and returns an `anyhow::Error` if the file does not exist
    /// or if there's an error checking its existence.
    ///
    /// # Arguments
    ///
    /// * `path` - The path to the file to check.
    /// * `file_type` - A descriptive string for the type of file being checked (used in error messages).
    ///
    /// # Returns
    ///
    /// * `Result<()>` - Ok if the file exists, otherwise an error.
    fn check_file_exists(&self, path: &PathBuf, file_type: &str) -> Result<()> {
        fs::metadata(path).map_err(|e| {
            error!("Error checking {} existence: {}", file_type, e);
            anyhow!("The specified {} file does not exist.", file_type)
        })?;
        Ok(())
    }

    /// Validates that the input file and guidelines file exist at the given paths.
    ///
    /// This function checks if the files specified by `input_csv` and guidelines_csv` exist.
    /// If a context file path is provided, it also validates its existence.
    ///
    /// * `Result<()>` - Returns `Ok` if all files exist.
    ///   Returns an `Err` if any of the following conditions are met:
    ///     - The input file does not exist.
    ///     - The guidelines file does not exist.
    ///     - The context file is provided but does not exist.
    ///     - There is an error checking the existence of any file.
    pub fn validate_file_paths_exist(&self) -> Result<()> {
        debug!("Arguments received {:#?}", &self);
        debug!("Validating file paths.");
        match &self.action {
            Action::Recommend {
                input_csv,
                guidelines_csv,
                context_csv,
                ..
            } => {
                self.check_file_exists(input_csv, "Input file")?;
                self.check_file_exists(guidelines_csv, "Guidelines file")?;
                if let Some(context_path) = context_csv {
                    self.check_file_exists(context_path, "Context file")?;
                }
            }
            Action::Enhance { .. } => {
                unimplemented!(" ==> In progress of implementation <== ")
            }
        }
        Ok(())
    }

    /// Gets the `PathBuf` associated with a specific `FileType`.
    ///
    /// Returns a reference to the stored path for `Input` or `Guidelines`.
    /// For `Context`, it returns a reference if the path is provided, otherwise
    /// it returns an error indicating the context file was not specified.
    ///
    /// # Arguments
    ///
    /// * `file_type` - The type of file whose path is requested.
    ///
    /// # Returns
    ///
    /// * `Result<&PathBuf>` - A reference to the file path, or an error if the
    ///   context file was requested but not provided.
    fn get_path_for_file_type(&self, file_type: FileType) -> Result<&PathBuf> {
        match &self.action {
            Action::Recommend {
                input_csv,
                guidelines_csv,
                context_csv,
                ..
            } => match file_type {
                FileType::Input => Ok(input_csv),
                FileType::Guidelines => Ok(guidelines_csv),
                FileType::Context => Ok(context_csv.as_ref().unwrap()),
            },
            Action::Enhance { .. } => {
                unimplemented!(" ==> In progress of implementation <== ")
            }
        }
    }

    // /// Reads the content of a CSV file based on the FileType.
    // ///
    // /// Opens the file, reads its content into a String, and returns the result.
    // ///
    // /// # Arguments
    // ///
    // /// * `file_type` - The type of file to read (Input, Guidelines, or Context).
    // ///
    // /// # Returns
    // ///
    // /// * `Result<String>` - The content of the file as a String, or an error if reading fails.
    // pub fn read_csv(&self, file_type: FileType) -> Result<String> {
    //     debug!("Reading {:?} file.", file_type);
    //     let path = self.get_path_for_file_type(file_type)?;
    //     let content = fs::read_to_string(path)?;
    //     Ok(content)
    // }

    pub fn read_file(&self, file_type: FileType) -> Result<String> {
        debug!("Reading {:?} file.", file_type);
        let path = self.get_path_for_file_type(file_type)?;
        let content = utils::read_csv(path)?;
        Ok(content)
    }

    /// Validates if the selected LLM model is compatible with the chosen LLM provider.
    ///
    /// This function checks the compatibility configuration to ensure that the
    /// specified model is supported by the selected provider. If no model is
    /// specified, the validation is skipped.
    ///
    /// # Arguments
    ///
    /// * `compat` - The compatibility configuration loaded from a file.
    ///
    /// # Returns
    ///
    /// * `Result<()>` - Ok if the model is compatible or no model was specified,
    ///   otherwise an error if the model is incompatible or the
    ///   provider doesn't support compatibility validation.
    pub fn validate_llm_provider_model_compatibility(
        &self,
        compat: &CompatibilityConfig,
    ) -> Result<()> {
        match &self.action {
            Action::Recommend {
                llm_provider,
                model,
                ..
            } => match llm_provider {
                LlmProvider::Google => {
                    compat.google.get(&model.to_string()).ok_or_else(|| {
                        anyhow!(
                            "Model '{:#?}' is not compatible with '{:#?}' provider.",
                            model,
                            llm_provider
                        )
                    })?;
                    Ok(())
                }
                LlmProvider::Openai => {
                    compat.openai.get(&model.to_string()).ok_or_else(|| {
                        anyhow!(
                            "Model '{:#?}' is not compatible with '{:#?}' provider.",
                            model,
                            llm_provider
                        )
                    })?;
                    Ok(())
                }
            },
            Action::Enhance { .. } => {
                unimplemented!(" ==> In progress of implementation <== ")
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::enums::*;
    use anyhow::Result;
    use std::{collections::HashMap, env::temp_dir, fs::File, io::Write};

    #[test]
    fn test_check_file_exists_success() -> Result<()> {
        let temp_dir = temp_dir();
        let file_path = temp_dir.as_path().join("test_file.txt");
        File::create(&file_path)?;

        let cli = Cli {
            action: Action::Recommend {
                input_csv: PathBuf::from("dummy_input.csv"),
                guidelines_csv: PathBuf::from("dummy_guidelines.csv"),
                context_csv: None,
                num_recommendations: None,
                llm_provider: LlmProvider::Google,
                model: LlmModel::GeminiFlash2,
                max_tokens: None,
                temperature: None,
            },
        };
        cli.check_file_exists(&file_path, "Test file")?;
        Ok(())
    }

    #[test]
    fn test_check_file_exists_failure() -> Result<()> {
        let cli = Cli {
            action: Action::Recommend {
                input_csv: PathBuf::from("dummy_input.csv"),
                guidelines_csv: PathBuf::from("dummy_guidelines.csv"),
                context_csv: None,
                num_recommendations: None,
                llm_provider: LlmProvider::Google,
                model: LlmModel::GeminiFlash2,
                max_tokens: None,
                temperature: None,
            },
        };
        let non_existent_path = PathBuf::from("non_existent_file.txt");
        let result = cli.check_file_exists(&non_existent_path, "Test file");
        assert!(result.is_err());
        Ok(())
    }

    #[test]
    fn test_get_path_for_file_type() -> Result<()> {
        let input_path = PathBuf::from("input.csv");
        let guidelines_path = PathBuf::from("guidelines.csv");
        let context_path = PathBuf::from("context.csv");

        let cli = Cli {
            action: Action::Recommend {
                input_csv: input_path.clone(),
                guidelines_csv: guidelines_path.clone(),
                context_csv: Some(context_path.clone()),
                num_recommendations: None,
                llm_provider: LlmProvider::Google,
                model: LlmModel::GeminiFlash2,
                max_tokens: None,
                temperature: None,
            },
        };

        assert_eq!(cli.get_path_for_file_type(FileType::Input)?, &input_path);
        assert_eq!(
            cli.get_path_for_file_type(FileType::Guidelines)?,
            &guidelines_path
        );
        assert_eq!(
            cli.get_path_for_file_type(FileType::Context)?,
            &context_path
        );

        Ok(())
    }

    // #[test]
    // fn test_read_csv_success() -> Result<()> {
    //     let temp_dir = temp_dir();
    //     let file_path = temp_dir.as_path().join("test.csv");
    //     let mut file = File::create(&file_path)?;
    //     let _ = file.write(b"test content");

    //     let cli = Cli {
    //         action: Action::Recommend {
    //             input_csv: file_path.clone(),
    //             guidelines_csv: PathBuf::from("dummy_guidelines.csv"),
    //             context_csv: None,
    //             num_recommendations: None,
    //             llm_provider: LlmProvider::Google,
    //             model: LlmModel::GeminiFlash2,
    //             max_tokens: None,
    //             temperature: None,
    //         },
    //     };

    //     let content = cli.read_csv(FileType::Input)?;
    //     assert_eq!(content.trim(), "test content");
    //     Ok(())
    // }

    #[test]
    fn test_validate_llm_provider_model_compatibility_success() -> Result<()> {
        let compat = CompatibilityConfig {
            google: {
                let mut map = HashMap::new();
                map.insert(
                    "gemini-2.0-flash".to_string(),
                    "gemini-2.0-flash".to_string(),
                );
                map
            },
            openai: {
                let mut map = HashMap::new();
                map.insert(
                    "gpt-4.1-nano-2025-04-14".to_string(),
                    "gpt-4.1-nano-2025-04-14".to_string(),
                );
                map
            },
        };

        let cli = Cli {
            action: Action::Recommend {
                input_csv: PathBuf::from("input.csv"),
                guidelines_csv: PathBuf::from("guidelines.csv"),
                context_csv: None,
                num_recommendations: None,
                llm_provider: LlmProvider::Google,
                model: LlmModel::GeminiFlash2,
                max_tokens: None,
                temperature: None,
            },
        };

        assert!(
            cli.validate_llm_provider_model_compatibility(&compat)
                .is_ok()
        );
        Ok(())
    }

    #[test]
    fn test_validate_llm_provider_model_compatibility_failure() -> Result<()> {
        let compat = CompatibilityConfig {
            google: HashMap::new(),
            openai: HashMap::new(),
        };

        let cli = Cli {
            action: Action::Recommend {
                input_csv: PathBuf::from("input.csv"),
                guidelines_csv: PathBuf::from("guidelines.csv"),
                context_csv: None,
                num_recommendations: None,
                llm_provider: LlmProvider::Google,
                model: LlmModel::GeminiFlash2,
                max_tokens: None,
                temperature: None,
            },
        };

        let result = cli.validate_llm_provider_model_compatibility(&compat);
        assert!(result.is_err());
        Ok(())
    }
}