zino_chatbot/
client.rs

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
use self::ChatbotClient::*;
use super::{ChatbotService, OpenAiChatCompletion};
use toml::Table;
use zino_core::{bail, error::Error, extension::TomlTableExt, Map};

/// Client for supported chatbot services.
#[non_exhaustive]
pub(super) enum ChatbotClient {
    /// OpenAI
    OpenAi(OpenAiChatCompletion),
}

/// A chatbot with the specific service and model.
pub struct Chatbot {
    /// Service
    service: String,
    /// Name
    name: String,
    /// Client
    client: ChatbotClient,
}

impl Chatbot {
    /// Creates a new instance.
    #[inline]
    pub(super) fn new(
        service: impl Into<String>,
        name: impl Into<String>,
        client: ChatbotClient,
    ) -> Self {
        Self {
            service: service.into(),
            name: name.into(),
            client,
        }
    }

    /// Constructs a new instance with the service and configuration,
    /// returning an error if it fails.
    pub fn try_new(service: &str, config: &Table) -> Result<Chatbot, Error> {
        match service {
            "openai" => OpenAiChatCompletion::try_new_chatbot(config),
            _ => {
                bail!("chatbot service `{}` is unsupported", service);
            }
        }
    }

    /// Returns the service.
    #[inline]
    pub fn service(&self) -> &str {
        self.service.as_str()
    }

    /// Returns the name.
    #[inline]
    pub fn name(&self) -> &str {
        self.name.as_str()
    }
}

impl ChatbotService for Chatbot {
    fn try_new_chatbot(config: &Table) -> Result<Chatbot, Error> {
        let service = config.get_str("service").unwrap_or("unkown");
        Self::try_new(service, config)
    }

    fn model(&self) -> &str {
        match &self.client {
            OpenAi(chat_completion) => chat_completion.model(),
        }
    }

    async fn try_send(&self, message: String, options: Option<Map>) -> Result<Vec<String>, Error> {
        match &self.client {
            OpenAi(chat_completion) => chat_completion.try_send(message, options).await,
        }
    }
}