summaryrefslogtreecommitdiffstats
path: root/src/client/localai.rs
blob: 084603b733d2bddb1d9dba81e4220ebf26327d47 (plain) (blame)
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
use super::openai::{openai_send_message, openai_send_message_streaming};
use super::{set_proxy, Client, ClientConfig, ModelInfo};

use crate::config::SharedConfig;
use crate::repl::ReplyStreamHandler;

use anyhow::{anyhow, Context, Result};
use async_trait::async_trait;
use inquire::{Confirm, Text};
use reqwest::{Client as ReqwestClient, RequestBuilder};
use serde::Deserialize;
use serde_json::json;
use std::env;
use std::time::Duration;

#[derive(Debug)]
pub struct LocalAIClient {
    global_config: SharedConfig,
    local_config: LocalAIConfig,
    model_info: ModelInfo,
}

#[derive(Debug, Clone, Deserialize)]
pub struct LocalAIConfig {
    pub url: String,
    pub api_key: Option<String>,
    pub models: Vec<LocalAIModel>,
    pub proxy: Option<String>,
    /// Set a timeout in seconds for connect to server
    pub connect_timeout: Option<u64>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct LocalAIModel {
    name: String,
    max_tokens: usize,
}

#[async_trait]
impl Client for LocalAIClient {
    fn get_config(&self) -> &SharedConfig {
        &self.global_config
    }

    async fn send_message_inner(&self, content: &str) -> Result<String> {
        let builder = self.request_builder(content, false)?;
        openai_send_message(builder).await
    }

    async fn send_message_streaming_inner(
        &self,
        content: &str,
        handler: &mut ReplyStreamHandler,
    ) -> Result<()> {
        let builder = self.request_builder(content, true)?;
        openai_send_message_streaming(builder, handler).await
    }
}

impl LocalAIClient {
    pub fn init(global_config: SharedConfig) -> Option<Box<dyn Client>> {
        let model_info = global_config.read().model_info.clone();
        if model_info.client != LocalAIClient::name() {
            return None;
        }
        let local_config = {
            if let ClientConfig::LocalAI(c) = &global_config.read().clients[model_info.index] {
                c.clone()
            } else {
                return None;
            }
        };
        Some(Box::new(Self {
            global_config,
            local_config,
            model_info,
        }))
    }

    pub fn name() -> &'static str {
        "localai"
    }

    pub fn list_models(local_config: &LocalAIConfig, index: usize) -> Vec<ModelInfo> {
        local_config
            .models
            .iter()
            .map(|v| ModelInfo::new(Self::name(), &v.name, v.max_tokens, index))
            .collect()
    }

    pub fn create_config() -> Result<String> {
        let mut client_config = format!("clients:\n  - type: {}\n", Self::name());

        let url = Text::new("URL:")
            .prompt()
            .map_err(|_| anyhow!("An error happened when asking for url, try again later."))?;

        client_config.push_str(&format!("    url: {url}\n"));

        let ans = Confirm::new("Use auth?")
            .with_default(false)
            .prompt()
            .map_err(|_| anyhow!("Not finish questionnaire, try again later."))?;

        if ans {
            let api_key = Text::new("API key:").prompt().map_err(|_| {
                anyhow!("An error happened when asking for api key, try again later.")
            })?;

            client_config.push_str(&format!("    api_key: {api_key}\n"));
        }

        let model_name = Text::new("Model Name:").prompt().map_err(|_| {
            anyhow!("An error happened when asking for model name, try again later.")
        })?;

        let max_tokens = Text::new("Max tokens:").prompt().map_err(|_| {
            anyhow!("An error happened when asking for max tokens, try again later.")
        })?;

        let ans = Confirm::new("Use proxy?")
            .with_default(false)
            .prompt()
            .map_err(|_| anyhow!("Not finish questionnaire, try again later."))?;

        if ans {
            let proxy = Text::new("Set proxy:").prompt().map_err(|_| {
                anyhow!("An error happened when asking for proxy, try again later.")
            })?;
            client_config.push_str(&format!("    proxy: {proxy}\n"));
        }

        client_config.push_str(&format!(
            "    models:\n      - name: {model_name}\n        max_tokens: {max_tokens}\n"
        ));

        Ok(client_config)
    }

    fn request_builder(&self, content: &str, stream: bool) -> Result<RequestBuilder> {
        let messages = self.global_config.read().build_messages(content)?;

        let mut body = json!({
            "model": self.model_info.name,
            "messages": messages,
        });

        if let Some(v) = self.global_config.read().get_temperature() {
            body.as_object_mut()
                .and_then(|m| m.insert("temperature".into(), json!(v)));
        }

        if stream {
            body.as_object_mut()
                .and_then(|m| m.insert("stream".into(), json!(true)));
        }

        let client = {
            let mut builder = ReqwestClient::builder();
            builder = set_proxy(builder, &self.local_config.proxy)?;
            let timeout = Duration::from_secs(self.local_config.connect_timeout.unwrap_or(10));
            builder
                .connect_timeout(timeout)
                .build()
                .with_context(|| "Failed to build client")?
        };

        let mut builder = client.post(&self.local_config.url);
        if let Some(api_key) = &self.local_config.api_key {
            builder = builder.bearer_auth(api_key);
        } else if let Ok(api_key) = env::var("LOCALAI_API_KEY") {
            builder = builder.bearer_auth(api_key);
        }
        builder = builder.json(&body);

        Ok(builder)
    }
}