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
use std::error::Error;
use std::fmt::{self, Debug};

use async_openai::error::OpenAIError;
use async_openai::types::{
    ChatCompletionTool, ChatCompletionToolArgs, ChatCompletionToolType, FunctionObject,
    FunctionObjectArgs,
};
use async_trait::async_trait;
pub use openai_func_enums_macros::*;
use serde_json::Value;

/// A trait to provide a descriptor for an enumeration.
/// This includes the name of the enum and the count of tokens in its name.
pub trait EnumDescriptor {
    /// Returns the name of the enum and the count of tokens in its name.
    ///
    /// # Returns
    ///
    /// A tuple where the first element is a `String` representing the name of the enum,
    /// and the second element is a `usize` representing the count of tokens in the enum's name.
    fn name_with_token_count() -> (String, usize);
    fn arg_description_with_token_count() -> (String, usize);
}

pub trait SubcommandGPT {
    // fn name_with_token_count() -> (String, usize);
    // fn arg_description_with_token_count() -> (String, usize);
}

/// A trait to provide descriptors for the variants of an enumeration.
/// This includes the names of the variants and the count of tokens in their names.
pub trait VariantDescriptors {
    /// Returns the names of the variants of the enum and the count of tokens in each variant's name.
    ///
    /// # Returns
    ///
    /// A `Vec` of tuples where each tuple's first element is a `String` representing the name of a variant,
    /// and the second element is a `usize` representing the count of tokens in the variant's name.
    fn variant_names_with_token_counts() -> Vec<(String, usize)>;

    /// Returns the name of a variant and the count of tokens in its name.
    ///
    /// # Returns
    ///
    /// A tuple where the first element is a `String` representing the name of the variant,
    /// and the second element is a `usize` representing the count of tokens in the variant's name.
    fn variant_name_with_token_count(&self) -> (String, usize);
}

#[derive(Clone, Debug)]
pub enum ToolCallExecutionStrategy {
    Parallel,
    Async,
    Synchronous,
}

#[derive(Debug)]
pub struct CommandError {
    details: String,
}

impl CommandError {
    pub fn new(msg: &str) -> CommandError {
        CommandError {
            details: msg.to_string(),
        }
    }
}

impl fmt::Display for CommandError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.details)
    }
}

impl Error for CommandError {}

impl From<OpenAIError> for CommandError {
    fn from(error: OpenAIError) -> Self {
        CommandError::new(&format!("OpenAI Error: {}", error))
    }
}

#[async_trait]
pub trait RunCommand: Sync + Send {
    async fn run(
        &self,
        execution_strategy: ToolCallExecutionStrategy,
    ) -> Result<Option<String>, Box<dyn std::error::Error + Send + Sync + 'static>>;
}

/// A trait for responses from function calls.
/// This includes a method to generate a JSON representation of the function.
pub trait FunctionCallResponse {
    /// Returns a JSON representation of the function and the count of tokens in the representation.
    ///
    /// # Returns
    ///
    /// A `Vec` of tuples where each tuple's first element is a `Value` representing a JSON object of the function,
    /// and the second element is a `usize` representing the count of tokens in the function's JSON representation.
    fn get_function_json(&self) -> Vec<(Value, usize)>;
}

/// A macro to parse a function call into a specified type.
/// If the parsing fails, it prints an error message and returns `None`.
///
/// # Arguments
///
/// * `$func_call` - An expression representing the function call to parse.
/// * `$type` - The target type to parse the function call into.
#[macro_export]
macro_rules! parse_function_call {
    ($func_call:expr, $type:ty) => {
        match serde_json::from_str::<$type>($func_call.arguments.as_str()) {
            Ok(response) => Some(response),
            Err(e) => {
                eprintln!("Failed to parse function call: {}", e);
                None
            }
        }
    };
}

/// A function to get the chat completion arguments for a function.
///
/// # Arguments
///
/// * `func` - A function that returns a JSON representation of a function and the count of tokens in the representation.
///
/// # Returns
///
/// * A `Result` which is `Ok` if the function chat completion arguments were successfully obtained, and `Err` otherwise.
///   The `Ok` variant contains a tuple where the first element is a `ChatCompletionFunctions` representing the chat completion arguments for the function,
///   and the second element is a `usize` representing the total count of tokens in the function's JSON representation.
pub fn get_function_chat_completion_args(
    func: impl Fn() -> (Value, usize),
    // ) -> Result<(Vec<ChatCompletionFunctions>, usize), OpenAIError> {
) -> Result<(Vec<FunctionObject>, usize), OpenAIError> {
    let (func_json, total_tokens) = func();

    let mut chat_completion_functions_vec = Vec::new();

    let values = match func_json {
        Value::Object(_) => vec![func_json],
        Value::Array(arr) => arr,
        _ => {
            return Err(OpenAIError::InvalidArgument(String::from(
                "Something went wrong parsing the json",
            )))
        }
    };

    for value in values {
        let parameters = value.get("parameters").cloned();

        let description = value
            .get("description")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let name = value.get("name").unwrap().as_str().unwrap().to_string();
        let chat_completion_args = match description {
            Some(desc) => FunctionObjectArgs::default()
                .name(name)
                .description(desc)
                .parameters(parameters)
                .build()?,
            None => FunctionObjectArgs::default()
                .name(name)
                .parameters(parameters)
                .build()?,
        };
        chat_completion_functions_vec.push(chat_completion_args);
    }

    Ok((chat_completion_functions_vec, total_tokens))
}

/// A function to get the chat completion arguments for a tool.
///
/// # Arguments
///
/// * `tool_func` - A function that returns a JSON representation of a tool and the count of tokens in the representation.
///
/// # Returns
///
/// * A `Result` which is `Ok` if the tool chat completion arguments were successfully obtained, and `Err` otherwise.
///   The `Ok` variant contains a tuple where the first element is a `ChatCompletionTool` representing the chat completion arguments for the tool,
///   and the second element is a `usize` representing the total count of tokens in the tool's JSON representation.
pub fn get_tool_chat_completion_args(
    tool_func: impl Fn() -> (Value, usize),
) -> Result<(Vec<ChatCompletionTool>, usize), OpenAIError> {
    let (tool_json, total_tokens) = tool_func();

    let mut chat_completion_tool_vec = Vec::new();

    let values = match tool_json {
        Value::Object(_) => vec![tool_json],
        Value::Array(arr) => arr,
        _ => {
            return Err(OpenAIError::InvalidArgument(String::from(
                "Something went wrong parsing the json",
            )))
        }
    };

    for value in values {
        let parameters = value.get("parameters").cloned();

        let description = value
            .get("description")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let name = value.get("name").unwrap().as_str().unwrap().to_string();

        let chat_completion_functions_args = match description {
            Some(desc) => FunctionObjectArgs::default()
                .name(name)
                .description(desc)
                .parameters(parameters)
                .build()?,
            None => FunctionObjectArgs::default()
                .name(name)
                .parameters(parameters)
                .build()?,
        };

        let chat_completion_tool = ChatCompletionToolArgs::default()
            .r#type(ChatCompletionToolType::Function)
            .function(chat_completion_functions_args)
            .build()?;

        chat_completion_tool_vec.push(chat_completion_tool);
    }

    Ok((chat_completion_tool_vec, total_tokens))
}