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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
//! Used to connect to the Prediction Guard API.
use std::{env, fmt, sync::Arc, time::Duration};
use crate::built_info;
use crate::{
chat, completion, embedding, factuality,
injection, pii, rerank, toxicity, translate,
tokenize, models, Result
};
use dotenvy;
use eventsource_client::Client as EventClient;
use eventsource_client::SSE;
use launchdarkly_sdk_transport::HyperTransport;
use futures::TryStreamExt;
use log::error;
use reqwest::{
header::{HeaderMap, HeaderValue},
ClientBuilder, Response, StatusCode,
};
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc::Sender;
const USER_AGENT: &str = "Prediction Guard Rust Client";
/// The base error that is returned from the API calls.
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct ApiError {
error: String,
}
impl fmt::Display for ApiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_fmt(format_args!("error {}", self.error))
}
}
impl std::error::Error for ApiError {}
/// Prediction Guard Configuration
pub struct PgEnvironment {
pub key: String,
pub host: String,
}
impl PgEnvironment {
/// Specify Prediction Guard API configuration manually
///
/// ## Arguments:
///
/// * `key` - the Prediction Guard API key
/// * `host` - the Prediction Guard URL
pub fn new(key: String, host: String) -> Self {
Self { key, host }
}
/// Loads Prediction Guard API configuration from either
/// a `.env` file or environment variables. Expects to find
/// the `PREDICTIONGUARD_API_KEY` and `PREDICTIONGUARD_URL` environment variables.
///
/// Returns an error if the environment variables are not found.
pub fn from_env() -> Result<Self> {
let _ = dotenvy::dotenv(); // Ignoring error - it's ok to not have .env files
Ok(Self {
key: env::var("PREDICTIONGUARD_API_KEY")?,
host: env::var("PREDICTIONGUARD_URL")?,
})
}
}
/// Handles the connectivity to the Prediction Guard API. It is safe to be
/// used across threads.
#[derive(Debug, Clone)]
pub struct Client {
inner: Arc<ClientInner>,
}
#[derive(Debug)]
struct ClientInner {
server: String,
http_client: reqwest::Client,
headers: HeaderMap,
api_key: String,
}
impl Client {
/// Creates a new instance of client to be used. Assumes the Prediction Guard keys,
/// PREDICTIONGUARD_API_KEY and PREDICTIONGUARD_URL are set in the environment.
pub fn new() -> Result<Self> {
let pg_env = PgEnvironment::from_env().expect("env keys");
Self::from_environment(pg_env)
}
/// Creates a new instance of client to be used with a particular Prediction Guard environment.
///
/// ## Arguments:
///
/// * `pg_env` - the prediction guard environment to connect to.
pub fn from_environment(pg_env: PgEnvironment) -> Result<Self> {
let user_agent = format!("{} v{}", USER_AGENT, built_info::PKG_VERSION);
let http = ClientBuilder::new()
.connect_timeout(Duration::new(30, 0))
.read_timeout(Duration::new(30, 0))
.timeout(Duration::new(45, 0))
.user_agent(user_agent)
.build()?;
let header_key = match HeaderValue::from_str(&pg_env.key) {
Ok(x) => x,
Err(e) => {
return Err(Box::new(e));
}
};
let mut header_map = HeaderMap::new();
let _ = header_map
.insert("x-api-key", header_key)
.ok_or("invalid api key");
let inner = Arc::new(ClientInner {
server: pg_env.host.to_string(),
http_client: http,
headers: header_map,
api_key: pg_env.key,
});
Ok(Self { inner })
}
/// Calls the health endpoint.
///
/// Returns the text response from the server. A 200 (Ok) status code is expected from
/// Prediction Guard api. Any other status code is considered an error.
pub async fn check_health(&self) -> Result<String> {
let result = self
.inner
.http_client
.get(&self.inner.server)
.headers(self.inner.headers.clone())
.send()
.await?;
if result.status() != StatusCode::OK {
return Err(retrieve_error(result).await);
}
let txt = result.text().await?;
Ok(txt)
}
/// Retrieves the list of models available for a set capability
///
/// ## Arguments:
///
/// * `capability` - The capability of models to sort by.
///
/// Returns a vector of strings with the model names. A 200 (Ok) status code is expected from the Prediction Guard api.
/// Any other status code is considered an error.
pub async fn retrieve_model_list(&self, capability: String) -> Result<Vec<String>> {
let url = format!(
"{}{}/{}",
&self.inner.server,
models::PATH,
capability
);
let result = self
.inner
.http_client
.get(url)
.headers(self.inner.headers.clone())
.send()
.await?;
if result.status() != StatusCode::OK {
return Err(retrieve_error(result).await);
}
let response_body: models::Response = result.json().await?;
let retrieve_models_response: Vec<String> = response_body
.data
.into_iter()
.map(|model| model.id)
.collect();
Ok(retrieve_models_response)
}
/// Calls the embedding endpoint.
///
/// ## Arguments:
///
/// * `req` - An instance of [`embedding::Request`]
///
/// Returns a [`embedding::Response`]. A 200 (Ok) status code is expected from the Prediction Guard api. Any other status code
/// is considered an error.
pub async fn embedding(&self, req: &embedding::Request) -> Result<embedding::Response> {
let url = format!("{}{}", &self.inner.server, embedding::PATH);
let result = self
.inner
.http_client
.post(url)
.headers(self.inner.headers.clone())
.json(req)
.send()
.await?;
if result.status() != StatusCode::OK {
return Err(retrieve_error(result).await);
}
let embed_response = result.json::<embedding::Response>().await?;
Ok(embed_response)
}
/// Calls the generate completion endpoint.
///
/// ## Arguments:
///
/// * `req` - An instance of [`completion::Request`]
///
/// Returns a [`completion::Response`]. A 200 (Ok) status code is expected from the Prediction Guard api. Any other status code
/// is considered an error.
pub async fn generate_completion(
&self,
req: &completion::Request,
) -> Result<completion::Response> {
let url = format!("{}{}", &self.inner.server, completion::PATH);
let result = self
.inner
.http_client
.post(url)
.headers(self.inner.headers.clone())
.json(req)
.send()
.await?;
if result.status() != StatusCode::OK {
return Err(retrieve_error(result).await);
}
let comp_response = result.json::<completion::Response>().await?;
Ok(comp_response)
}
/// Calls the generate chat completion endpoint.
///
/// ## Arguments:
///
/// * `req` - An instance of [`chat::Request::<Message>`]
///
/// Returns an instance of [`chat::Response`]. A 200 (Ok) status code is expected from the Prediction Guard api. Any other status code
/// is considered an error.
pub async fn generate_chat_completion(
&self,
req: &chat::Request<chat::Message>,
) -> Result<chat::Response> {
let url = format!("{}{}", &self.inner.server, chat::PATH);
let result = self
.inner
.http_client
.post(url)
.headers(self.inner.headers.clone())
.json(req)
.send()
.await?;
if result.status() != StatusCode::OK {
return Err(retrieve_error(result).await);
}
let chat_response = result.json::<chat::Response>().await?;
Ok(chat_response)
}
/// Calls the generate chat completion endpoint.
///
/// ## Arguments:
///
/// * `req` - An instance of [`chat::Request::<Message>`]
/// * `event_handler` - Event handler function that is called when a server side event is raised.
///
/// Returns an instance of [`chat::Response`].
///
/// The generated text is returned via events from the server. The event handler function gets called
/// every time the client receives an event response with data. Once the server terminates the events the call returns.
/// The entire [`chat::Response`] response is then returned to the caller.
///
/// A 200 (Ok) status code is expected from the Prediction Guard api. Any other status code
/// is considered an error.
pub async fn generate_chat_completion_events<F>(
&self,
req: &mut chat::Request<chat::Message>,
event_handler: &mut F,
) -> Result<Option<chat::ResponseEvents>>
where
F: FnMut(&String),
{
let url = format!("{}{}", &self.inner.server, chat::PATH);
req.stream = true;
req.output = None;
let body = serde_json::to_string(&req)?;
let user_agent = format!("{} v{}", USER_AGENT, built_info::PKG_VERSION);
let key = format!("Bearer {}", &self.inner.api_key);
let transport = HyperTransport::builder().build_https()?;
let client = eventsource_client::ClientBuilder::for_url(&url)?
.header("User-Agent", user_agent.as_str())?
.header("Authorization", &key)?
.method("POST".to_string())
.body(body)
.build_with_transport(transport);
let mut stream = Box::pin(client.stream());
loop {
match stream.try_next().await {
Ok(Some(event)) => {
match event {
SSE::Connected(_) => continue,
SSE::Comment(_) => continue,
SSE::Event(evt) => {
// Check for [DONE]
if evt.data == "[DONE]" {
return Ok(None);
}
// JSON Response
let resp: chat::ResponseEvents = match serde_json::from_str(&evt.data) {
Ok(v) => v,
Err(e) => {
return Err(Box::from(ApiError {
error: format!("error parsing stream response: {}", e),
}));
}
};
if resp.choices.is_empty() {
// No data to stream or Done
continue;
}
// Finish Reason == Stop That is the final Response.
if resp.choices[0].finish_reason == Some("stop".to_string()) {
return Ok(Some(resp));
}
let msg = resp.choices[0].delta.clone().content;
event_handler(&msg);
}
}
}
Ok(None) => continue,
Err(e) => match e {
eventsource_client::Error::Eof => break,
_ => return Err(stream_error_into_api_err(e).await),
},
}
}
Ok(None)
}
/// Calls the generate chat completion endpoint.
///
/// ## Arguments:
///
/// * `req` - An instance of [`chat::Request::<Message>`]
/// * `sender` - A sender instance for a channel where there is a receiver waiting for a message.
///
/// Returns an instance of [`chat::Response`].
///
/// The generated text is returned via events from the server. The sender gets called
/// every time the client receives an event response with data. Once the server terminates the events the call returns.
/// The receiver should handle the `stop` message which means there are no more messages to receive and exit.
/// The entire [`chat::Response`] response is then returned to the caller.
///
/// A 200 (Ok) status code is expected from the Prediction Guard api. Any other status code
/// is considered an error.
pub async fn generate_chat_completion_events_async(
&self,
req: &mut chat::Request<chat::Message>,
sender: &Sender<String>,
) -> Result<Option<chat::ResponseEvents>> {
let url = format!("{}{}", &self.inner.server, chat::PATH);
req.stream = true;
req.output = None;
let body = serde_json::to_string(&req)?;
let user_agent = format!("{} v{}", USER_AGENT, built_info::PKG_VERSION);
let key = format!("Bearer {}", &self.inner.api_key);
let transport = HyperTransport::builder().build_https()?;
let client = eventsource_client::ClientBuilder::for_url(&url)?
.header("User-Agent", user_agent.as_str())?
.header("Authorization", &key)?
.method("POST".to_string())
.body(body)
.build_with_transport(transport);
let mut stream = Box::pin(client.stream());
loop {
match stream.try_next().await {
Ok(Some(event)) => {
match event {
SSE::Connected(_) => continue,
SSE::Comment(_) => continue,
SSE::Event(evt) => {
// Check for [DONE]
if evt.data.to_lowercase() == "[done]" {
let _ = sender.send("stop".to_string()).await;
return Ok(None);
}
// JSON Response
let resp: chat::ResponseEvents = match serde_json::from_str(&evt.data) {
Ok(v) => v,
Err(e) => {
return Err(Box::from(ApiError {
error: format!("error parsing stream response: {}", e),
}));
}
};
if resp.choices.is_empty() {
// No data to stream or Done
continue;
}
// Finish Reason == Stop That is the final Response.
if resp.choices[0].finish_reason == Some("stop".to_string()) {
let _ = sender.send("stop".to_string()).await;
return Ok(Some(resp));
}
let msg = resp.choices[0].delta.clone().content;
match sender.send(msg).await {
Ok(_) => (),
Err(e) => {
error!("generate_chat_completion_events_async - error sending on channel, {e}");
}
}
}
}
}
Ok(None) => continue,
Err(e) => match e {
eventsource_client::Error::Eof => break,
_ => return Err(stream_error_into_api_err(e).await),
},
}
}
Ok(None)
}
/// Calls the generate chat completion endpoint for chat vision.
///
/// ## Arguments:
///
/// * `req` - An instance of [`chat::Request::<MessageVision>`]
///
/// Returns an instance of [`chat::Response`]. A 200 (Ok) status code is expected from the Prediction Guard api. Any other status code
/// is considered an error.
pub async fn generate_chat_vision(
&self,
req: &chat::Request<chat::MessageVision>,
) -> Result<chat::Response> {
let url = format!("{}{}", &self.inner.server, chat::PATH);
let result = self
.inner
.http_client
.post(url)
.headers(self.inner.headers.clone())
.json(req)
.send()
.await?;
if result.status() != StatusCode::OK {
return Err(retrieve_error(result).await);
}
let chat_response = result.json::<chat::Response>().await?;
Ok(chat_response)
}
/// Calls the rerank endpoint.
///
/// ## Arguments:
///
/// * `req` - An instance of [`rerank::Request`]
///
/// Returns an instance of [`rerank::Response`]. A 200 (Ok) status code is expected from the Prediction Guard api. Any other status code
/// is considered an error.
pub async fn rerank(
&self,
req: &rerank::Request,
) -> Result<rerank::Response> {
let url = format!("{}{}", &self.inner.server, rerank::PATH);
let result = self
.inner
.http_client
.post(url)
.headers(self.inner.headers.clone())
.json(req)
.send()
.await?;
if result.status() != StatusCode::OK {
return Err(retrieve_error(result).await);
}
let rerank_response = result.json::<rerank::Response>().await?;
Ok(rerank_response)
}
/// Calls the factuality check endpoint.
///
/// ## Arguments:
///
/// * `req` - An instance of [`factuality::Request`]
///
/// Returns am instance of [`factuality::Response`]. A 200 (Ok) status code is expected from the Prediction Guard api. Any other status code
/// is considered an error.
pub async fn check_factuality(
&self,
req: &factuality::Request,
) -> Result<factuality::Response> {
let url = format!("{}{}", &self.inner.server, factuality::PATH);
let result = self
.inner
.http_client
.post(url)
.headers(self.inner.headers.clone())
.json(req)
.send()
.await?;
if result.status() != StatusCode::OK {
return Err(retrieve_error(result).await);
}
let fact_response = result.json::<factuality::Response>().await?;
Ok(fact_response)
}
/// Calls the translate endpoint.
///
/// ## Arguments:
///
/// `req` - Instance of [`translate::Request`]
///
/// Returns a [`translate::Response`]. A 200 (Ok) status code is expected from the Prediction Guard api. Any other status code
/// is considered an error.
pub async fn translate(&self, req: &translate::Request) -> Result<translate::Response> {
let url = format!("{}{}", &self.inner.server, translate::PATH);
let result = self
.inner
.http_client
.post(url)
.headers(self.inner.headers.clone())
.json(req)
.send()
.await?;
if result.status() != StatusCode::OK {
return Err(retrieve_error(result).await);
}
let translate_response = result.json::<translate::Response>().await?;
Ok(translate_response)
}
/// Calls the PII endpoint that is used to remove/detect PII information in the request.
///
/// ## Arguments:
///
/// `req` - An instance of [`pii::Request`]
///
/// Returns an instance of [`pii::Response`]. A 200 (Ok) status code is expected from the Prediction Guard api.
/// Any other status code is considered an error.
pub async fn pii(&self, req: &pii::Request) -> Result<pii::Response> {
let url = format!("{}{}", &self.inner.server, pii::PATH);
let result = self
.inner
.http_client
.post(url)
.headers(self.inner.headers.clone())
.json(req)
.send()
.await?;
if result.status() != StatusCode::OK {
return Err(retrieve_error(result).await);
}
let pii_response = result.json::<pii::Response>().await?;
Ok(pii_response)
}
/// Calls the injection check endpoint.
///
/// ## Arguments:
///
/// `req` - Instance of [`injection::Request`]
///
/// Returns an instance of [`injection::Response`]. A 200 (Ok) status code is expected from the Prediction Guard api. Any other status code
/// is considered an error.
pub async fn injection(&self, req: &injection::Request) -> Result<injection::Response> {
let url = format!("{}{}", &self.inner.server, injection::PATH);
let result = self
.inner
.http_client
.post(url)
.headers(self.inner.headers.clone())
.json(req)
.send()
.await?;
if result.status() != StatusCode::OK {
return Err(retrieve_error(result).await);
}
let injection_response = result.json::<injection::Response>().await?;
Ok(injection_response)
}
/// Calls the injection check endpoint.
///
/// ## Arguments:
///
/// `req` - An instance of [`toxicity::Request`]
///
/// Returns an instance of [`toxicity::Response`]. A 200 (Ok) status code is expected from the Prediction Guard api. Any other status code
/// is considered an error.
pub async fn toxicity(&self, req: &toxicity::Request) -> Result<toxicity::Response> {
let url = format!("{}{}", &self.inner.server, toxicity::PATH);
let result = self
.inner
.http_client
.post(url)
.headers(self.inner.headers.clone())
.json(req)
.send()
.await?;
if result.status() != StatusCode::OK {
return Err(retrieve_error(result).await);
}
let toxicity_response = result.json::<toxicity::Response>().await?;
Ok(toxicity_response)
}
/// Calls the tokenize endpoint.
///
/// ## Arguments:
///
/// * `req` - An instance of [`tokenize::Request`]
///
/// Returns an instance of [`tokenize::Response`]. A 200 (Ok) status code is expected from the Prediction Guard api. Any other status code
/// is considered an error.
pub async fn tokenize(
&self,
req: &tokenize::Request,
) -> Result<tokenize::Response> {
let url = format!("{}{}", &self.inner.server, tokenize::PATH);
let result = self
.inner
.http_client
.post(url)
.headers(self.inner.headers.clone())
.json(req)
.send()
.await?;
if result.status() != StatusCode::OK {
return Err(retrieve_error(result).await);
}
let token_response = result.json::<tokenize::Response>().await?;
Ok(token_response)
}
/// Retrieves the list of models available.
///
/// Returns a vector with the model metadata. A 200 (Ok) status code is expected from the Prediction Guard api. Any other status code
/// is considered an error.
pub async fn models(
&self,
req: Option<&models::Request>
) -> Result<models::Response> {
let mut url = format!("{}{}", &self.inner.server, models::PATH);
// If `req` is Some, append it to the URL
if let Some(request) = req {
if let Some(capability) = &request.capability {
url.push('/');
url.push_str(capability);
}
}
let result = self
.inner
.http_client
.get(url)
.headers(self.inner.headers.clone())
.send()
.await?;
if result.status() != StatusCode::OK {
return Err(retrieve_error(result).await);
}
let model_response = result.json::<models::Response>().await?;
Ok(model_response)
}
}
async fn retrieve_error(resp: Response) -> Box<dyn std::error::Error> {
let err = match resp.json::<ApiError>().await {
Ok(x) => x,
Err(e) => return Box::from(format!("error parsing error response, {}", e)),
};
err.into()
}
async fn stream_error_into_api_err(err: eventsource_client::Error) -> Box<dyn std::error::Error> {
let msg = format!("{}", err);
Box::from(ApiError {
error: msg.to_string(),
})
}