chatgpt/
converse.rs

1use std::path::Path;
2
3use crate::{
4    client::ChatGPT,
5    types::{ChatMessage, CompletionResponse, Role},
6};
7
8/// Stores a single conversation session, and automatically saves message history
9pub struct Conversation {
10    client: ChatGPT,
11    /// All the messages sent and received, starting with the beginning system message
12    pub history: Vec<ChatMessage>,
13}
14
15impl Conversation {
16    /// Constructs a new conversation from an API client and the introductory message
17    pub fn new(client: ChatGPT, first_message: String) -> Self {
18        Self {
19            client,
20            history: vec![ChatMessage {
21                role: Role::System,
22                content: first_message,
23            }],
24        }
25    }
26
27    /// Constructs a new conversation from a pre-initialized chat history
28    pub fn new_with_history(client: ChatGPT, history: Vec<ChatMessage>) -> Self {
29        Self { client, history }
30    }
31
32    /// Sends the message to the ChatGPT API and returns the completion response.
33    ///
34    /// Execution speed depends on API response times.
35    pub fn send_message<S: Into<String>>(
36        &mut self,
37        message: S,
38    ) -> String {
39        self.history.push(ChatMessage {
40            role: Role::User,
41            content: message.into(),
42        });
43        let resp = self.client.send_history(&self.history);
44        self.history.push(ChatMessage {
45            role: Role::User,
46            content: resp.clone(),
47        });
48        resp
49    }
50}