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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use futures::AsyncReadExt;
use gpui::BackgroundExecutor;
use gpui::{serde_json, AppContext};
use isahc::http::StatusCode;
use isahc::prelude::Configurable;
use isahc::{AsyncBody, Response};
use lazy_static::lazy_static;
use parking_lot::{Mutex, RwLock};
use parse_duration::parse;
use postage::watch;
use serde::{Deserialize, Serialize};
use std::env;
use std::ops::Add;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tiktoken_rs::{cl100k_base, CoreBPE};
use util::http::{HttpClient, Request};
use util::ResultExt;

use crate::auth::{CredentialProvider, ProviderCredential};
use crate::embedding::{Embedding, EmbeddingProvider};
use crate::models::LanguageModel;
use crate::providers::open_ai::OpenAILanguageModel;

use crate::providers::open_ai::OPENAI_API_URL;

lazy_static! {
    static ref OPENAI_BPE_TOKENIZER: CoreBPE = cl100k_base().unwrap();
}

#[derive(Clone)]
pub struct OpenAIEmbeddingProvider {
    model: OpenAILanguageModel,
    credential: Arc<RwLock<ProviderCredential>>,
    pub client: Arc<dyn HttpClient>,
    pub executor: Arc<BackgroundExecutor>,
    rate_limit_count_rx: watch::Receiver<Option<Instant>>,
    rate_limit_count_tx: Arc<Mutex<watch::Sender<Option<Instant>>>>,
}

#[derive(Serialize)]
struct OpenAIEmbeddingRequest<'a> {
    model: &'static str,
    input: Vec<&'a str>,
}

#[derive(Deserialize)]
struct OpenAIEmbeddingResponse {
    data: Vec<OpenAIEmbedding>,
    usage: OpenAIEmbeddingUsage,
}

#[derive(Debug, Deserialize)]
struct OpenAIEmbedding {
    embedding: Vec<f32>,
    index: usize,
    object: String,
}

#[derive(Deserialize)]
struct OpenAIEmbeddingUsage {
    prompt_tokens: usize,
    total_tokens: usize,
}

impl OpenAIEmbeddingProvider {
    pub fn new(client: Arc<dyn HttpClient>, executor: Arc<BackgroundExecutor>) -> Self {
        let (rate_limit_count_tx, rate_limit_count_rx) = watch::channel_with(None);
        let rate_limit_count_tx = Arc::new(Mutex::new(rate_limit_count_tx));

        let model = OpenAILanguageModel::load("text-embedding-ada-002");
        let credential = Arc::new(RwLock::new(ProviderCredential::NoCredentials));

        OpenAIEmbeddingProvider {
            model,
            credential,
            client,
            executor,
            rate_limit_count_rx,
            rate_limit_count_tx,
        }
    }

    fn get_api_key(&self) -> Result<String> {
        match self.credential.read().clone() {
            ProviderCredential::Credentials { api_key } => Ok(api_key),
            _ => Err(anyhow!("api credentials not provided")),
        }
    }

    fn resolve_rate_limit(&self) {
        let reset_time = *self.rate_limit_count_tx.lock().borrow();

        if let Some(reset_time) = reset_time {
            if Instant::now() >= reset_time {
                *self.rate_limit_count_tx.lock().borrow_mut() = None
            }
        }

        log::trace!(
            "resolving reset time: {:?}",
            *self.rate_limit_count_tx.lock().borrow()
        );
    }

    fn update_reset_time(&self, reset_time: Instant) {
        let original_time = *self.rate_limit_count_tx.lock().borrow();

        let updated_time = if let Some(original_time) = original_time {
            if reset_time < original_time {
                Some(reset_time)
            } else {
                Some(original_time)
            }
        } else {
            Some(reset_time)
        };

        log::trace!("updating rate limit time: {:?}", updated_time);

        *self.rate_limit_count_tx.lock().borrow_mut() = updated_time;
    }
    async fn send_request(
        &self,
        api_key: &str,
        spans: Vec<&str>,
        request_timeout: u64,
    ) -> Result<Response<AsyncBody>> {
        let request = Request::post("https://api.openai.com/v1/embeddings")
            .redirect_policy(isahc::config::RedirectPolicy::Follow)
            .timeout(Duration::from_secs(request_timeout))
            .header("Content-Type", "application/json")
            .header("Authorization", format!("Bearer {}", api_key))
            .body(
                serde_json::to_string(&OpenAIEmbeddingRequest {
                    input: spans.clone(),
                    model: "text-embedding-ada-002",
                })
                .unwrap()
                .into(),
            )?;

        Ok(self.client.send(request).await?)
    }
}

impl CredentialProvider for OpenAIEmbeddingProvider {
    fn has_credentials(&self) -> bool {
        match *self.credential.read() {
            ProviderCredential::Credentials { .. } => true,
            _ => false,
        }
    }
    fn retrieve_credentials(&self, cx: &mut AppContext) -> ProviderCredential {
        let existing_credential = self.credential.read().clone();

        let retrieved_credential = match existing_credential {
            ProviderCredential::Credentials { .. } => existing_credential.clone(),
            _ => {
                if let Some(api_key) = env::var("OPENAI_API_KEY").log_err() {
                    ProviderCredential::Credentials { api_key }
                } else if let Some(Some((_, api_key))) =
                    cx.read_credentials(OPENAI_API_URL).log_err()
                {
                    if let Some(api_key) = String::from_utf8(api_key).log_err() {
                        ProviderCredential::Credentials { api_key }
                    } else {
                        ProviderCredential::NoCredentials
                    }
                } else {
                    ProviderCredential::NoCredentials
                }
            }
        };

        *self.credential.write() = retrieved_credential.clone();
        retrieved_credential
    }

    fn save_credentials(&self, cx: &mut AppContext, credential: ProviderCredential) {
        *self.credential.write() = credential.clone();
        match credential {
            ProviderCredential::Credentials { api_key } => {
                cx.write_credentials(OPENAI_API_URL, "Bearer", api_key.as_bytes())
                    .log_err();
            }
            _ => {}
        }
    }

    fn delete_credentials(&self, cx: &mut AppContext) {
        cx.delete_credentials(OPENAI_API_URL).log_err();
        *self.credential.write() = ProviderCredential::NoCredentials;
    }
}

#[async_trait]
impl EmbeddingProvider for OpenAIEmbeddingProvider {
    fn base_model(&self) -> Box<dyn LanguageModel> {
        let model: Box<dyn LanguageModel> = Box::new(self.model.clone());
        model
    }

    fn max_tokens_per_batch(&self) -> usize {
        50000
    }

    fn rate_limit_expiration(&self) -> Option<Instant> {
        *self.rate_limit_count_rx.borrow()
    }

    async fn embed_batch(&self, spans: Vec<String>) -> Result<Vec<Embedding>> {
        const BACKOFF_SECONDS: [usize; 4] = [3, 5, 15, 45];
        const MAX_RETRIES: usize = 4;

        let api_key = self.get_api_key()?;

        let mut request_number = 0;
        let mut rate_limiting = false;
        let mut request_timeout: u64 = 15;
        let mut response: Response<AsyncBody>;
        while request_number < MAX_RETRIES {
            response = self
                .send_request(
                    &api_key,
                    spans.iter().map(|x| &**x).collect(),
                    request_timeout,
                )
                .await?;

            request_number += 1;

            match response.status() {
                StatusCode::REQUEST_TIMEOUT => {
                    request_timeout += 5;
                }
                StatusCode::OK => {
                    let mut body = String::new();
                    response.body_mut().read_to_string(&mut body).await?;
                    let response: OpenAIEmbeddingResponse = serde_json::from_str(&body)?;

                    log::trace!(
                        "openai embedding completed. tokens: {:?}",
                        response.usage.total_tokens
                    );

                    // If we complete a request successfully that was previously rate_limited
                    // resolve the rate limit
                    if rate_limiting {
                        self.resolve_rate_limit()
                    }

                    return Ok(response
                        .data
                        .into_iter()
                        .map(|embedding| Embedding::from(embedding.embedding))
                        .collect());
                }
                StatusCode::TOO_MANY_REQUESTS => {
                    rate_limiting = true;
                    let mut body = String::new();
                    response.body_mut().read_to_string(&mut body).await?;

                    let delay_duration = {
                        let delay = Duration::from_secs(BACKOFF_SECONDS[request_number - 1] as u64);
                        if let Some(time_to_reset) =
                            response.headers().get("x-ratelimit-reset-tokens")
                        {
                            if let Ok(time_str) = time_to_reset.to_str() {
                                parse(time_str).unwrap_or(delay)
                            } else {
                                delay
                            }
                        } else {
                            delay
                        }
                    };

                    // If we've previously rate limited, increment the duration but not the count
                    let reset_time = Instant::now().add(delay_duration);
                    self.update_reset_time(reset_time);

                    log::trace!(
                        "openai rate limiting: waiting {:?} until lifted",
                        &delay_duration
                    );

                    self.executor.timer(delay_duration).await;
                }
                _ => {
                    let mut body = String::new();
                    response.body_mut().read_to_string(&mut body).await?;
                    return Err(anyhow!(
                        "open ai bad request: {:?} {:?}",
                        &response.status(),
                        body
                    ));
                }
            }
        }
        Err(anyhow!("openai max retries"))
    }
}