@@ -3,16 +3,20 @@ use serde::{de::DeserializeOwned, Serialize};
3
3
use crate :: error:: { OpenAIError , WrappedError } ;
4
4
5
5
#[ derive( Debug , Default ) ]
6
+ /// Client container for api key, base url and other metadata
7
+ /// required to make API calls.
6
8
pub struct Client {
7
9
api_key : String ,
8
10
api_base : String ,
9
11
org_id : String ,
10
12
//headers: reqwest::header::HeaderMap,
11
13
}
12
14
13
- const API_BASE : & str = "https://api.openai.com/v1" ;
15
+ /// Default v1 API base url
16
+ pub const API_BASE : & str = "https://api.openai.com/v1" ;
14
17
15
18
impl Client {
19
+ /// Create client with default [API_BASE] url and default API key from OPENAI_API_KEY env var
16
20
pub fn new ( ) -> Self {
17
21
Self {
18
22
api_base : API_BASE . to_string ( ) ,
@@ -21,18 +25,20 @@ impl Client {
21
25
}
22
26
}
23
27
24
- pub fn with_api_key ( mut self , api_key : String ) -> Self {
25
- self . api_key = api_key;
28
+ /// To use a different API key different from default OPENAI_API_KEY env var
29
+ pub fn with_api_key < S : Into < String > > ( mut self , api_key : S ) -> Self {
30
+ self . api_key = api_key. into ( ) ;
26
31
self
27
32
}
28
33
29
- pub fn with_org_id ( mut self , org_id : String ) -> Self {
30
- self . org_id = org_id;
34
+ pub fn with_org_id < S : Into < String > > ( mut self , org_id : S ) -> Self {
35
+ self . org_id = org_id. into ( ) ;
31
36
self
32
37
}
33
38
34
- pub fn with_api_base ( mut self , api_base : String ) -> Self {
35
- self . api_base = api_base;
39
+ /// To use a API base url different from default [API_BASE]
40
+ pub fn with_api_base < S : Into < String > > ( mut self , api_base : S ) -> Self {
41
+ self . api_base = api_base. into ( ) ;
36
42
self
37
43
}
38
44
@@ -44,6 +50,7 @@ impl Client {
44
50
& self . api_key
45
51
}
46
52
53
+ /// Deserialize response body from either error object or actual response object
47
54
async fn process_response < O > ( & self , response : reqwest:: Response ) -> Result < O , OpenAIError >
48
55
where
49
56
O : DeserializeOwned ,
@@ -63,6 +70,7 @@ impl Client {
63
70
Ok ( response)
64
71
}
65
72
73
+ /// Make a GET request to {path} and deserialize the response body
66
74
pub ( crate ) async fn get < O > ( & self , path : & str ) -> Result < O , OpenAIError >
67
75
where
68
76
O : DeserializeOwned ,
@@ -76,6 +84,7 @@ impl Client {
76
84
self . process_response ( response) . await
77
85
}
78
86
87
+ /// Make a POST request to {path} and deserialize the response body
79
88
pub ( crate ) async fn post < I , O > ( & self , path : & str , request : I ) -> Result < O , OpenAIError >
80
89
where
81
90
I : Serialize ,
@@ -91,6 +100,7 @@ impl Client {
91
100
self . process_response ( response) . await
92
101
}
93
102
103
+ /// POST a form at {path} and deserialize the response body
94
104
pub ( crate ) async fn post_form < O > (
95
105
& self ,
96
106
path : & str ,
0 commit comments