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
use std::fmt;

use serde::{Deserialize, Serialize};

use crate::{function_specification::FunctionSpecification, message::Message};

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ChatContext {
    pub model: String,
    pub messages: Vec<Message>,
    pub functions: Vec<FunctionSpecification>,
    pub function_call: Option<String>,
}

impl ChatContext {
    /// Creates a new ChatContext with a model name
    /// as a string. This is an internal function used by other functions.
    pub fn new(model: String) -> ChatContext {
        ChatContext {
            model,
            messages: Vec::new(),
            functions: Vec::new(),
            function_call: None,
        }
    }

    /// Pushes a message in the chat context
    /// as a Message. This is an internal function used by other functions.
    /// It is recommended to use ChatGPT.push_message()
    pub fn push_message(&mut self, message: Message) {
        self.messages.push(message);
    }

    /// Sets the messages in the chat context
    /// as a vector of Message.
    /// This is an internal function used by other functions.
    pub fn set_messages(&mut self, messages: Vec<Message>) {
        self.messages = messages;
    }

    /// Pushes a function in the chat context
    /// as a FunctionSpecification.
    /// This is an internal function used by other functions.
    /// It is recommended to use ChatGPT.push_function()
    pub fn push_function(&mut self, functions: FunctionSpecification) {
        self.functions.push(functions);
    }

    /// Sets the functions in the chat context
    /// as a vector of FunctionSpecification.
    /// This is an internal function used by other functions.
    pub fn set_functions(&mut self, functions: Vec<FunctionSpecification>) {
        self.functions = functions;
    }

    /// Sets the last message sent by the user or the bot
    /// as a string. This is an internal function used by other functions.
    pub fn set_function_call(&mut self, function_call: String) {
        self.function_call = Some(function_call);
    }

    /// Returns the last message sent by the user or the bot
    /// as a string. This is an internal function used by other functions.
    /// It is recommended to use ChatGPT.last_content()
    pub fn last_content(&self) -> Option<String> {
        match self.messages.last() {
            Some(message) => {
                if let Some(c) = message.content.clone() {
                    Some(c)
                } else {
                    None
                }
            }
            None => None,
        }
    }

    /// Returns the last function call in the chat context
    /// as a tuple of the function name and the arguments.
    /// This is an internal function used by other functions.
    /// It is recommended to use ChatGPT.last_function_call()
    pub fn last_function_call(&self) -> Option<(String, String)> {
        match self.messages.last() {
            Some(message) => {
                if let Some(f) = message.function_call.clone() {
                    Some((f.name, f.arguments))
                } else {
                    None
                }
            }
            None => None,
        }
    }
}

// Print valid JSON for ChatContext, no commas if last field
impl fmt::Display for ChatContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{{\"model\":\"{}\"", self.model)?;
        if !self.messages.is_empty() {
            write!(f, ",\"messages\":[")?;
            for (i, message) in self.messages.iter().enumerate() {
                write!(f, "{}", message)?;
                if i < self.messages.len() - 1 {
                    write!(f, ",")?;
                }
            }
            write!(f, "]")?;
        }
        if self.functions.len() > 0 {
            write!(f, ",\"functions\":[")?;
            for (i, function) in self.functions.iter().enumerate() {
                write!(f, "{}", function)?;
                if i < self.functions.len() - 1 {
                    write!(f, ",")?;
                }
            }
            write!(f, "]")?;
        }
        if let Some(function_call) = &self.function_call {
            write!(f, ",\"function_call\":\"{}\"", function_call)?;
        }
        write!(f, "}}")
    }
}
#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use super::*;
    use crate::{
        function_specification::{Parameters, Property},
        message::Message,
    };

    #[test]
    fn test_display_for_chat_context() {
        let mut chat_context = ChatContext::new("test_model".to_string());
        chat_context.push_message(Message {
            role: "role".to_string(),
            content: Some("Hello".to_string()),
            name: None,
            function_call: None,
        });
        chat_context.push_message(Message {
            role: "bot".to_string(),
            content: Some("Hi".to_string()),
            name: None,
            function_call: None,
        });
        assert_eq!(
            chat_context.to_string(),
            "{\"model\":\"test_model\",\"messages\":[{\"role\":\"role\",\"content\":\"Hello\"},{\"role\":\"bot\",\"content\":\"Hi\"}]}"
        );
    }

    #[test]
    fn test_display_chat_context_with_functions() {
        let mut chat_context = ChatContext::new("test_model".to_string());

        // Add a function to the chat context
        let mut properties = HashMap::new();
        properties.insert(
            "location".to_string(),
            Property {
                type_: "string".to_string(),
                description: Some("a dummy string".to_string()),
                enum_: None,
            },
        );
        let function = FunctionSpecification {
            name: "test_function".to_string(),
            description: Some("a dummy function to test the chat context".to_string()),
            parameters: Some(Parameters {
                type_: "object".to_string(),
                properties,
                required: vec!["location".to_string()],
            }),
        };
        chat_context.push_function(function);

        // Add a message to the chat context
        chat_context.push_message(Message {
            role: "test".to_string(),
            content: Some("hi".to_string()),
            name: Some("test_function".to_string()),
            function_call: None, // Lets assume a function has not been called yet
        });

        // Print the chat context, with the model, the messages, the functions, and the function_call
        assert_eq!(
            chat_context.to_string(),
            "{\"model\":\"test_model\",\"messages\":[{\"role\":\"test\",\"content\":\"hi\",\"name\":\"test_function\"}],\"functions\":[{\"name\":\"test_function\",\"description\":\"a dummy function to test the chat context\",\"parameters\":{\"type\":\"object\",\"properties\":{\"location\":{\"type\":\"string\",\"description\":\"a dummy string\"}},\"required\":[\"location\"]}}]}"
        );
    }

    #[test]
    fn test_last_content() {
        let mut chat_context = ChatContext::new("model".to_string());

        // Test with no messages
        assert_eq!(chat_context.last_content(), None);

        // Test with a message with no content
        chat_context.push_message(Message {
            role: "role".to_string(),
            content: None,
            name: None,
            function_call: None,
        });
        assert_eq!(chat_context.last_content(), None);

        // Test with a message with content
        chat_context.push_message(Message {
            role: "role".to_string(),
            content: Some("content".to_string()),
            name: None,
            function_call: None,
        });
        assert_eq!(chat_context.last_content(), Some("content".to_string()));
    }

    #[test]
    fn test_last_function_call() {
        let mut chat_context = ChatContext::new("model".to_string());

        // Test with no messages
        assert_eq!(chat_context.last_content(), None);

        // Test with a message with no function call
        chat_context.push_message(Message {
            role: "role".to_string(),
            content: None,
            name: None,
            function_call: None,
        });
        assert_eq!(chat_context.last_content(), None);

        // Test with a message with function call
        use crate::message::FunctionCall;
        chat_context.push_message(Message {
            role: "role".to_string(),
            content: None,
            name: None,
            function_call: Some(FunctionCall {
                name: "function".to_string(),
                arguments: "arguments".to_string(),
            }),
        });
        assert_eq!(
            chat_context.last_function_call(),
            Some(("function".to_string(), "arguments".to_string()))
        );
    }
}