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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
//! Utilities for interacting with all prediction endpoints.
//!
//! This includes the following:
//! - [Create Prediction](https://replicate.com/docs/reference/http#predictions.create)
//! - [Get Prediction](https://replicate.com/docs/reference/http#predictions.get)
//! - [List Predictions](https://replicate.com/docs/reference/http#predictions.list)
//! - [Cancel Prediction](https://replicate.com/docs/reference/http#predictions.cancel)
//!

use crate::config::ReplicateConfig;

use anyhow::anyhow;
use bytes::Bytes;
use eventsource_stream::{EventStream, Eventsource};
use futures_lite::StreamExt;
use serde_json::Value;

use crate::models::ModelClient;
use crate::{api_key, base_url};

/// Status of a retrieved or created prediction
#[derive(serde::Serialize, serde::Deserialize, Debug, Eq, PartialEq, Clone)]
#[serde(rename_all = "lowercase")]
pub enum PredictionStatus {
    /// The prediction is starting up. If this status lasts longer than a few seconds, then it's
    /// typically because a new worker is being started to run the prediction.
    Starting,
    /// The `predict()` method of the model is currently running.
    Processing,
    /// The prediction completed successfully.
    Succeeded,
    /// The prediction was canceled by its creator.
    Failed,
    /// The prediction was canceled by its creator.
    Canceled,
}

/// Provided urls to either cancel or retrieve updated details for the specific prediction.
#[derive(serde::Deserialize, Debug)]
pub struct PredictionUrls {
    /// Url endpoint to cancel the specific prediction
    pub cancel: String,
    /// Url endpoint to retrieve the specific prediction
    pub get: String,
    /// Url endpoint to receive streamed output
    pub stream: Option<String>,
}

/// Details for a specific prediction
#[derive(serde::Deserialize, Debug)]
pub struct Prediction {
    /// Id of the prediction
    pub id: String,
    /// Model used during the prediction
    pub model: String,
    /// Specific version used during prediction
    pub version: String,
    /// The inputs provided for the specific prediction
    pub input: Value,
    /// The current status of the prediction
    pub status: PredictionStatus,
    /// The created time for the prediction
    pub created_at: String,
    /// Urls to either retrieve or cancel details for this prediction
    pub urls: PredictionUrls,
    /// The output of the prediction if completed
    pub output: Option<Value>,
}

/// Paginated list of available predictions
#[derive(serde::Deserialize, Debug)]
pub struct Predictions {
    /// Identify for status in pagination
    pub next: Option<String>,
    /// Identify for status of pagination
    pub previous: Option<String>,
    /// List of predictions
    pub results: Vec<Prediction>,
}

impl Prediction {
    /// Leverage the get url provided, to refresh struct attributes
    pub async fn reload(&mut self) -> anyhow::Result<()> {
        let api_key = api_key()?;
        let endpoint = self.urls.get.clone();
        let client = reqwest::Client::new();
        let response = client
            .get(endpoint)
            .header("Authorization", format!("Token {api_key}"))
            .send()
            .await?;

        let data = response.text().await?;
        let prediction: Prediction = serde_json::from_str(data.as_str())?;
        *self = prediction;
        anyhow::Ok(())
    }

    /// Get the status for the current prediction
    pub async fn get_status(&mut self) -> PredictionStatus {
        self.status.clone()
    }

    /// Get the stream from a prediction
    pub async fn get_stream(
        &mut self,
    ) -> anyhow::Result<EventStream<impl futures_lite::stream::Stream<Item = reqwest::Result<Bytes>>>>
    {
        if let Some(stream_url) = self.urls.stream.clone() {
            let api_key = api_key()?;
            let client = reqwest::Client::new();
            let stream = client
                .get(stream_url)
                .header("Authorization", format!("Token {api_key}"))
                .header("Accept", "text/event-stream")
                .send()
                .await?
                .bytes_stream()
                .eventsource();

            return anyhow::Ok(stream);
        } else {
            return Err(anyhow!("prediction has no stream url available"));
        }
    }
}

/// A client for interacting with 'predictions' endpoint
#[derive(Debug)]
pub struct PredictionClient {
    config: ReplicateConfig,
}

#[derive(serde::Serialize)]
struct PredictionInput {
    version: String,
    input: serde_json::Value,
    stream: bool,
}

impl PredictionClient {
    /// Create a new `PredictionClient` based upon a `ReplicateConfig` object
    pub fn from(config: ReplicateConfig) -> Self {
        PredictionClient { config }
    }
    /// Create a new prediction
    pub async fn create(
        &self,
        owner: &str,
        name: &str,
        input: serde_json::Value,
        stream: bool,
    ) -> anyhow::Result<Prediction> {
        let api_key = api_key()?;
        let base_url = base_url();

        let model_client = ModelClient::from(self.config.clone());
        let version = model_client.get_latest_version(owner, name).await?.id;

        let endpoint = format!("{base_url}/predictions");
        let input = PredictionInput {
            version,
            input,
            stream,
        };
        let body = serde_json::to_string(&input)?;
        let client = reqwest::Client::new();
        let response = client
            .post(endpoint)
            .header("Authorization", format!("Token {api_key}"))
            .body(body)
            .send()
            .await?;

        let data = response.text().await?;
        let prediction: Prediction = serde_json::from_str(&data)?;

        anyhow::Ok(prediction)
    }

    /// Get details for an existing prediction
    pub async fn get(&self, id: String) -> anyhow::Result<Prediction> {
        let api_key = self.config.get_api_key()?;
        let base_url = self.config.get_base_url();

        let endpoint = format!("{base_url}/predictions/{id}");
        let client = reqwest::Client::new();
        let response = client
            .get(endpoint)
            .header("Authorization", format!("Token {api_key}"))
            .send()
            .await?;

        let data = response.text().await?;
        let prediction: Prediction = serde_json::from_str(&data)?;

        anyhow::Ok(prediction)
    }

    /// List all existing predictions for the current user
    pub async fn list(&self) -> anyhow::Result<Predictions> {
        let api_key = self.config.get_api_key()?;
        let base_url = self.config.get_base_url();

        let endpoint = format!("{base_url}/predictions");
        let client = reqwest::Client::new();
        let response = client
            .get(endpoint)
            .header("Authorization", format!("Token {api_key}"))
            .send()
            .await?;

        let data = response.text().await?;
        let predictions: Predictions = serde_json::from_str(&data)?;

        anyhow::Ok(predictions)
    }

    /// Cancel an existing prediction
    pub async fn cancel(&self, id: String) -> anyhow::Result<Prediction> {
        let api_key = self.config.get_api_key()?;
        let base_url = self.config.get_base_url();
        let endpoint = format!("{base_url}/predictions/{id}/cancel");
        let client = reqwest::Client::new();
        let response = client
            .post(endpoint)
            .header("Authorization", format!("Token {api_key}"))
            .send()
            .await?;

        let data = response.text().await?;
        let prediction: Prediction = serde_json::from_str(&data)?;

        anyhow::Ok(prediction)
    }
}

#[cfg(test)]
mod tests {
    use httpmock::prelude::*;
    use serde_json::json;

    use super::*;

    #[tokio::test]
    async fn test_get() {
        let server = MockServer::start();

        let prediction_mock = server.mock(|when, then| {
            when.method(GET).path("/predictions/1234");
            then.status(200).json_body_obj(&json!(
                {
                    "id": "1234",
                    "model": "replicate/hello-world",
                    "version": "5c7d5dc6dd8bf75c1acaa8565735e7986bc5b66206b55cca93cb72c9bf15ccaa",
                    "input": {
                        "text": "Alice"
                    },
                    "logs": "",
                    "error": null,
                    "status": "starting",
                    "created_at": "2023-09-08T16:19:34.765994657Z",
                    "urls": {
                        "cancel": "https://api.replicate.com/v1/predictions/1234/cancel",
                        "get": "https://api.replicate.com/v1/predictions/1234"
                    }
                }
            ));
        });

        let client = ReplicateConfig::test(server.base_url()).unwrap();

        let prediction_client = PredictionClient::from(client);
        prediction_client.get("1234".to_string()).await.unwrap();

        prediction_mock.assert();
    }

    #[tokio::test]
    async fn test_create() {
        let server = MockServer::start();

        server.mock(|when, then| {
            when.method(POST).path("/predictions");
            then.status(200).json_body_obj(&json!(
                {
                    "id": "gm3qorzdhgbfurvjtvhg6dckhu",
                    "model": "replicate/hello-world",
                    "version": "5c7d5dc6dd8bf75c1acaa8565735e7986bc5b66206b55cca93cb72c9bf15ccaa",
                    "input": {
                        "text": "Alice"
                    },
                    "logs": "",
                    "error": null,
                    "status": "starting",
                    "created_at": "2023-09-08T16:19:34.765994657Z",
                    "urls": {
                        "cancel": "https://api.replicate.com/v1/predictions/gm3qorzdhgbfurvjtvhg6dckhu/cancel",
                        "get": "https://api.replicate.com/v1/predictions/gm3qorzdhgbfurvjtvhg6dckhu"
                    }
                }
            ));
        });

        server.mock(|when, then| {
            when.method(GET)
                .path("/models/replicate/hello-world/versions");

            then.status(200).json_body_obj(&json!({
                "next": null,
                "previous": null,
                "results": [{
                    "id": "5c7d5dc6dd8bf75c1acaa8565735e7986bc5b66206b55cca93cb72c9bf15ccaa",
                    "created_at": "2022-04-26T19:29:04.418669Z",
                    "cog_version": "0.3.0",
                    "openapi_schema": null
                }]
            }));
        });

        let client = ReplicateConfig::test(server.base_url()).unwrap();

        let prediction_client = PredictionClient::from(client);
        prediction_client
            .create(
                "replicate",
                "hello-world",
                json!({"text": "This is test input"}),
                false,
            )
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn test_list_predictions() {
        let server = MockServer::start();

        server.mock(|when, then| {
            when.method(GET).path("/predictions");
            then.status(200).json_body_obj(&json!(
                { "next": null,
                  "previous": null,
                  "results": [
                    {
                        "id": "gm3qorzdhgbfurvjtvhg6dckhu",
                        "model": "replicate/hello-world",
                        "version": "5c7d5dc6dd8bf75c1acaa8565735e7986bc5b66206b55cca93cb72c9bf15ccaa",
                        "input": {
                            "text": "Alice"
                        },
                        "logs": "",
                        "error": null,
                        "status": "starting",
                        "created_at": "2023-09-08T16:19:34.765994657Z",
                        "urls": {
                            "cancel": "https://api.replicate.com/v1/predictions/gm3qorzdhgbfurvjtvhg6dckhu/cancel",
                            "get": "https://api.replicate.com/v1/predictions/gm3qorzdhgbfurvjtvhg6dckhu"
                        }
                    },
                    {
                        "id": "gm3qorzdhgbfurvjtvhg6dckhu",
                        "model": "replicate/hello-world",
                        "version": "5c7d5dc6dd8bf75c1acaa8565735e7986bc5b66206b55cca93cb72c9bf15ccaa",
                        "input": {
                            "text": "Alice"
                        },
                        "logs": "",
                        "error": null,
                        "status": "starting",
                        "created_at": "2023-09-08T16:19:34.765994657Z",
                        "urls": {
                            "cancel": "https://api.replicate.com/v1/predictions/gm3qorzdhgbfurvjtvhg6dckhu/cancel",
                            "get": "https://api.replicate.com/v1/predictions/gm3qorzdhgbfurvjtvhg6dckhu"
                        }
                    }
                ]}
            ));
        });

        let client = ReplicateConfig::test(server.base_url()).unwrap();

        let prediction_client = PredictionClient::from(client);
        prediction_client.list().await.unwrap();
    }

    #[tokio::test]
    async fn test_create_and_reload() {
        let server = MockServer::start();

        server.mock(|when, then| {
            when.method(POST).path("/predictions");
            then.status(200).json_body_obj(&json!(
                {
                    "id": "gm3qorzdhgbfurvjtvhg6dckhu",
                    "model": "replicate/hello-world",
                    "version": "5c7d5dc6dd8bf75c1acaa8565735e7986bc5b66206b55cca93cb72c9bf15ccaa",
                    "input": {
                        "text": "Alice"
                    },
                    "logs": "",
                    "error": null,
                    "status": "starting",
                    "created_at": "2023-09-08T16:19:34.765994657Z",
                    "urls": {
                        "cancel": "https://api.replicate.com/v1/predictions/gm3qorzdhgbfurvjtvhg6dckhu/cancel",
                        "get": "https://api.replicate.com/v1/predictions/gm3qorzdhgbfurvjtvhg6dckhu"
                    }
                }
            ));
        });

        server.mock(|when, then| {
            when.method(GET)
                .path("/models/replicate/hello-world/versions");

            then.status(200).json_body_obj(&json!({
                "next": null,
                "previous": null,
                "results": [{
                    "id": "5c7d5dc6dd8bf75c1acaa8565735e7986bc5b66206b55cca93cb72c9bf15ccaa",
                    "created_at": "2022-04-26T19:29:04.418669Z",
                    "cog_version": "0.3.0",
                    "openapi_schema": null
                }]
            }));
        });

        let client = ReplicateConfig::test(server.base_url()).unwrap();

        let prediction_client = PredictionClient::from(client);
        let mut prediction = prediction_client
            .create(
                "replicate",
                "hello-world",
                json!({"text": "This is test input"}),
                false,
            )
            .await
            .unwrap();

        prediction.reload().await.unwrap();
    }

    #[tokio::test]
    async fn test_cancel() {
        let server = MockServer::start();

        let prediction_mock = server.mock(|when, then| {
            when.method(POST).path("/predictions/1234/cancel");
            then.status(200).json_body_obj(&json!(
                {
                    "id": "1234",
                    "model": "replicate/hello-world",
                    "version": "5c7d5dc6dd8bf75c1acaa8565735e7986bc5b66206b55cca93cb72c9bf15ccaa",
                    "input": {
                        "text": "Alice"
                    },
                    "logs": "",
                    "error": null,
                    "status": "starting",
                    "created_at": "2023-09-08T16:19:34.765994657Z",
                    "urls": {
                        "cancel": "https://api.replicate.com/v1/predictions/1234/cancel",
                        "get": "https://api.replicate.com/v1/predictions/1234"
                    }
                }
            ));
        });

        let config = ReplicateConfig::test(server.base_url()).unwrap();
        let prediction_client = PredictionClient::from(config);

        prediction_client.cancel("1234".to_string()).await.unwrap();

        prediction_mock.assert();
    }
}