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
use std::{sync::Arc, time::Duration};

use futures::{Future, FutureExt as _};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::json;
use tracing::{debug, info, warn};
use url::Url;

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Choice {
    text: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Choices {
    choices: Vec<Choice>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Completion {
    content: String,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
enum LlmResponse {
    OpenAI(Choices),
    LlamaCpp(Completion),
}

pub struct Generator {
    endpoint: Url,
    model: String,
    client: Arc<Client>,
}

impl Generator {
    pub fn new(endpoint: Url, model: Option<String>) -> Self {
        Generator {
            endpoint,
            model: model.unwrap_or_else(|| "HF://mlc-ai/gemma-2b-it-q4f16_1-MLC".to_string()),
            client: Arc::new(Client::new()),
        }
    }

    async fn try_gen(
        endpoint: Url,
        client: Arc<Client>,
        model: String,
        prompt: String,
        max_tokens: Option<usize>,
        stop: Option<Vec<String>>,
    ) -> Result<String, bool> {
        let mut stop = stop.unwrap_or_default();
        stop.push("<eos>".to_string());
        let payload = json!({
            "max_tokens": max_tokens.unwrap_or(128),
            "n_predict": max_tokens.unwrap_or(128),
            "model": model,
            "prompt": prompt,
            "stream": false,
            "stop": stop,
        });

        let res = client
            .post(endpoint)
            .json(&payload)
            .send()
            .await
            .map_err(|err| {
                if err.is_connect() {
                    debug!("got connect error, better retry");
                    return true;
                }
                false
            })?;

        if res.status() == 503 {
            debug!("got 503 error, better retry");
            return Err(true);
        }
        if !res.status().is_success() {
            return Err(false);
        }

        // Assume all error happening here is unrecoverable
        res.text().await.map_err(|_| false)
    }

    async fn retry<R: Future<Output = Result<String, bool>>, F: Fn() -> R>(
        func: F,
    ) -> anyhow::Result<String> {
        let mut cnt = 30;
        loop {
            let r1 = func().await;
            match r1 {
                Ok(resp) => return Ok(resp),
                Err(err) => {
                    if err {
                        info!("Retryable error, retry in 1000ms");
                        let _ = tokio::time::sleep(Duration::from_millis(1000)).await;
                    } else {
                        warn!(err = format!("{:?}", err), "unknown error querying daemon");
                        anyhow::bail!(err)
                    }
                }
            };
            cnt -= 1;
            if cnt == 0 {
                anyhow::bail!("timed out");
            }
        }
    }

    pub fn generate(
        &self,
        prompt: String,
    ) -> impl Future<Output = anyhow::Result<String>> + Send + 'static {
        let endpoint = self.endpoint.clone();
        let client = self.client.clone();
        let model = self.model.clone();
        Self::retry(move || {
            Self::try_gen(
                endpoint.clone(),
                client.clone(),
                model.clone(),
                prompt.clone(),
                None,
                None,
            )
        })
        .map(|json| match serde_json::from_str(&json?)? {
            LlmResponse::OpenAI(choices) => Ok(choices.choices.first().unwrap().text.clone()),
            LlmResponse::LlamaCpp(completion) => Ok(completion.content),
        })
    }
}