-
Notifications
You must be signed in to change notification settings - Fork 430
/
Copy pathEndpointBase.cs
469 lines (415 loc) · 20.8 KB
/
EndpointBase.cs
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
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.Authentication;
using System.Text;
using System.Threading.Tasks;
namespace OpenAI_API
{
/// <summary>
/// A base object for any OpenAI API endpoint, encompassing common functionality
/// </summary>
public abstract class EndpointBase
{
private const string UserAgent = "okgodoit/dotnet_openai_api";
/// <summary>
/// The internal reference to the API, mostly used for authentication
/// </summary>
protected readonly OpenAIAPI _Api;
/// <summary>
/// Constructor of the api endpoint base, to be called from the contructor of any devived classes. Rather than instantiating any endpoint yourself, access it through an instance of <see cref="OpenAIAPI"/>.
/// </summary>
/// <param name="api"></param>
protected EndpointBase(OpenAIAPI api)
{
this._Api = api;
}
/// <summary>
/// The name of the endpoint, which is the final path segment in the API URL. Must be overriden in a derived class.
/// </summary>
protected abstract string Endpoint { get; }
/// <summary>
/// Gets the URL of the endpoint, based on the base OpenAI API URL followed by the endpoint name. For example "https://api.openai.com/v1/completions"
/// </summary>
protected string Url
{
get
{
return string.Format(_Api.ApiUrlFormat, _Api.ApiVersion, Endpoint);
}
}
/// <summary>
/// Gets an HTTPClient with the appropriate authorization and other headers set
/// </summary>
/// <returns>The fully initialized HttpClient</returns>
/// <exception cref="AuthenticationException">Thrown if there is no valid authentication. Please refer to <see href="https://github.com/OkGoDoIt/OpenAI-API-dotnet#authentication"/> for details.</exception>
protected HttpClient GetClient()
{
if (_Api.Auth?.ApiKey is null)
{
throw new AuthenticationException("You must provide API authentication. Please refer to https://github.com/OkGoDoIt/OpenAI-API-dotnet#authentication for details.");
}
HttpClient client;
var clientFactory = _Api.HttpClientFactory;
if (clientFactory != null)
{
client = clientFactory.CreateClient();
}
else
{
client = new HttpClient();
}
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _Api.Auth.ApiKey);
// Further authentication-header used for Azure openAI service
client.DefaultRequestHeaders.Add("api-key", _Api.Auth.ApiKey);
client.DefaultRequestHeaders.Add("User-Agent", UserAgent);
if (!string.IsNullOrEmpty(_Api.Auth.OpenAIOrganization)) client.DefaultRequestHeaders.Add("OpenAI-Organization", _Api.Auth.OpenAIOrganization);
return client;
}
/// <summary>
/// Formats a human-readable error message relating to calling the API and parsing the response
/// </summary>
/// <param name="resultAsString">The full content returned in the http response</param>
/// <param name="response">The http response object itself</param>
/// <param name="name">The name of the endpoint being used</param>
/// <param name="description">Additional details about the endpoint of this request (optional)</param>
/// <returns>A human-readable string error message.</returns>
protected string GetErrorMessage(string resultAsString, HttpResponseMessage response, string name, string description = "")
{
return $"Error at {name} ({description}) with HTTP status code: {response.StatusCode}. Content: {resultAsString ?? "<no content>"}";
}
/// <summary>
/// Sends an HTTP request and returns the response. Does not do any parsing, but does do error handling.
/// </summary>
/// <param name="url">(optional) If provided, overrides the url endpoint for this request. If omitted, then <see cref="Url"/> will be used.</param>
/// <param name="verb">(optional) The HTTP verb to use, for example "<see cref="HttpMethod.Get"/>". If omitted, then "GET" is assumed.</param>
/// <param name="postData">(optional) A json-serializable object to include in the request body.</param>
/// <param name="streaming">(optional) If true, streams the response. Otherwise waits for the entire response before returning.</param>
/// <returns>The HttpResponseMessage of the response, which is confirmed to be successful.</returns>
/// <exception cref="HttpRequestException">Throws an exception if a non-success HTTP response was returned</exception>
private async Task<HttpResponseMessage> HttpRequestRaw(string url = null, HttpMethod verb = null, object postData = null, bool streaming = false)
{
if (string.IsNullOrEmpty(url))
url = this.Url;
if (verb == null)
verb = HttpMethod.Get;
using var client = GetClient();
HttpResponseMessage response = null;
string resultAsString = null;
HttpRequestMessage req = new HttpRequestMessage(verb, url);
if (postData != null)
{
if (postData is HttpContent)
{
req.Content = postData as HttpContent;
}
else
{
string jsonContent = JsonConvert.SerializeObject(postData, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
var stringContent = new StringContent(jsonContent, UnicodeEncoding.UTF8, "application/json");
req.Content = stringContent;
}
}
response = await client.SendAsync(req, streaming ? HttpCompletionOption.ResponseHeadersRead : HttpCompletionOption.ResponseContentRead);
if (response.IsSuccessStatusCode)
{
return response;
}
else
{
try
{
resultAsString = await response.Content.ReadAsStringAsync();
}
catch (Exception readError)
{
resultAsString = "Additionally, the following error was thrown when attemping to read the response content: " + readError.ToString();
}
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
throw new AuthenticationException("OpenAI rejected your authorization, most likely due to an invalid API Key. Try checking your API Key and see https://github.com/OkGoDoIt/OpenAI-API-dotnet#authentication for guidance. Full API response follows: " + resultAsString);
}
else if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError)
{
throw new HttpRequestException("OpenAI had an internal server error, which can happen occasionally. Please retry your request. " + GetErrorMessage(resultAsString, response, Endpoint, url));
}
else
{
var errorToThrow = new HttpRequestException(GetErrorMessage(resultAsString, response, Endpoint, url));
var parsedError = JsonConvert.DeserializeObject<ApiErrorResponse>(resultAsString);
try
{
errorToThrow.Data.Add("message", parsedError.Error.Message);
errorToThrow.Data.Add("type", parsedError.Error.ErrorType);
errorToThrow.Data.Add("param", parsedError.Error.Parameter);
errorToThrow.Data.Add("code", parsedError.Error.ErrorCode);
}
catch (Exception parsingError)
{
throw new HttpRequestException(errorToThrow.Message, parsingError);
}
throw errorToThrow;
}
}
}
/// <summary>
/// Sends an HTTP Get request and return the string content of the response without parsing, and does error handling.
/// </summary>
/// <param name="url">(optional) If provided, overrides the url endpoint for this request. If omitted, then <see cref="Url"/> will be used.</param>
/// <param name="verb">(optional) The HTTP verb to use, for example "<see cref="HttpMethod.Get"/>". If omitted, then "GET" is assumed.</param>
/// <param name="postData">(optional) A json-serializable object to include in the request body.</param>
/// <returns>The text string of the response, which is confirmed to be successful.</returns>
/// <exception cref="HttpRequestException">Throws an exception if a non-success HTTP response was returned</exception>
internal async Task<string> HttpGetContent(string url = null, HttpMethod verb = null, object postData = null)
{
var response = await HttpRequestRaw(url, verb, postData);
return await response.Content.ReadAsStringAsync();
}
/// <summary>
/// Sends an HTTP request and return the raw content stream of the response without parsing, and does error handling.
/// </summary>
/// <param name="url">(optional) If provided, overrides the url endpoint for this request. If omitted, then <see cref="Url"/> will be used.</param>
/// <param name="verb">(optional) The HTTP verb to use, for example "<see cref="HttpMethod.Get"/>". If omitted, then "GET" is assumed.</param>
/// <param name="postData">(optional) A json-serializable object to include in the request body.</param>
/// <returns>The response content stream, which is confirmed to be successful.</returns>
/// <exception cref="HttpRequestException">Throws an exception if a non-success HTTP response was returned</exception>
internal async Task<Stream> HttpRequest(string url = null, HttpMethod verb = null, object postData = null)
{
var response = await HttpRequestRaw(url, verb, postData);
return await response.Content.ReadAsStreamAsync();
}
/// <summary>
/// Sends an HTTP Request and does initial parsing
/// </summary>
/// <typeparam name="T">The <see cref="ApiResultBase"/>-derived class for the result</typeparam>
/// <param name="url">(optional) If provided, overrides the url endpoint for this request. If omitted, then <see cref="Url"/> will be used.</param>
/// <param name="verb">(optional) The HTTP verb to use, for example "<see cref="HttpMethod.Get"/>". If omitted, then "GET" is assumed.</param>
/// <param name="postData">(optional) A json-serializable object to include in the request body.</param>
/// <returns>An awaitable Task with the parsed result of type <typeparamref name="T"/></returns>
/// <exception cref="HttpRequestException">Throws an exception if a non-success HTTP response was returned or if the result couldn't be parsed.</exception>
private async Task<T> HttpRequest<T>(string url = null, HttpMethod verb = null, object postData = null) where T : ApiResultBase
{
var response = await HttpRequestRaw(url, verb, postData);
string resultAsString = await response.Content.ReadAsStringAsync();
var res = JsonConvert.DeserializeObject<T>(resultAsString);
try
{
res.Organization = response.Headers.GetValues("Openai-Organization").FirstOrDefault();
res.RequestId = response.Headers.GetValues("X-Request-ID").FirstOrDefault();
res.ProcessingTime = TimeSpan.FromMilliseconds(int.Parse(response.Headers.GetValues("Openai-Processing-Ms").First()));
res.OpenaiVersion = response.Headers.GetValues("Openai-Version").FirstOrDefault();
if (string.IsNullOrEmpty(res.Model))
res.Model = response.Headers.GetValues("Openai-Model").FirstOrDefault();
}
catch (Exception e)
{
Debug.Print($"Issue parsing metadata of OpenAi Response. Url: {url}, Error: {e.ToString()}, Response: {resultAsString}. This is probably ignorable.");
}
return res;
}
/*
/// <summary>
/// Sends an HTTP Request, supporting a streaming response
/// </summary>
/// <typeparam name="T">The <see cref="ApiResultBase"/>-derived class for the result</typeparam>
/// <param name="url">(optional) If provided, overrides the url endpoint for this request. If omitted, then <see cref="Url"/> will be used.</param>
/// <param name="verb">(optional) The HTTP verb to use, for example "<see cref="HttpMethod.Get"/>". If omitted, then "GET" is assumed.</param>
/// <param name="postData">(optional) A json-serializable object to include in the request body.</param>
/// <returns>An awaitable Task with the parsed result of type <typeparamref name="T"/></returns>
/// <exception cref="HttpRequestException">Throws an exception if a non-success HTTP response was returned or if the result couldn't be parsed.</exception>
private async Task<T> StreamingHttpRequest<T>(string url = null, HttpMethod verb = null, object postData = null) where T : ApiResultBase
{
var response = await HttpRequestRaw(url, verb, postData);
string resultAsString = await response.Content.ReadAsStringAsync();
var res = JsonConvert.DeserializeObject<T>(resultAsString);
try
{
res.Organization = response.Headers.GetValues("Openai-Organization").FirstOrDefault();
res.RequestId = response.Headers.GetValues("X-Request-ID").FirstOrDefault();
res.ProcessingTime = TimeSpan.FromMilliseconds(int.Parse(response.Headers.GetValues("Openai-Processing-Ms").First()));
res.OpenaiVersion = response.Headers.GetValues("Openai-Version").FirstOrDefault();
if (string.IsNullOrEmpty(res.Model))
res.Model = response.Headers.GetValues("Openai-Model").FirstOrDefault();
}
catch (Exception e)
{
Debug.Print($"Issue parsing metadata of OpenAi Response. Url: {url}, Error: {e.ToString()}, Response: {resultAsString}. This is probably ignorable.");
}
return res;
}
*/
/// <summary>
/// Sends an HTTP Get request and does initial parsing
/// </summary>
/// <typeparam name="T">The <see cref="ApiResultBase"/>-derived class for the result</typeparam>
/// <param name="url">(optional) If provided, overrides the url endpoint for this request. If omitted, then <see cref="Url"/> will be used.</param>
/// <returns>An awaitable Task with the parsed result of type <typeparamref name="T"/></returns>
/// <exception cref="HttpRequestException">Throws an exception if a non-success HTTP response was returned or if the result couldn't be parsed.</exception>
internal async Task<T> HttpGet<T>(string url = null) where T : ApiResultBase
{
return await HttpRequest<T>(url, HttpMethod.Get);
}
/// <summary>
/// Sends an HTTP Post request and does initial parsing
/// </summary>
/// <typeparam name="T">The <see cref="ApiResultBase"/>-derived class for the result</typeparam>
/// <param name="url">(optional) If provided, overrides the url endpoint for this request. If omitted, then <see cref="Url"/> will be used.</param>
/// <param name="postData">(optional) A json-serializable object to include in the request body.</param>
/// <returns>An awaitable Task with the parsed result of type <typeparamref name="T"/></returns>
/// <exception cref="HttpRequestException">Throws an exception if a non-success HTTP response was returned or if the result couldn't be parsed.</exception>
internal async Task<T> HttpPost<T>(string url = null, object postData = null) where T : ApiResultBase
{
return await HttpRequest<T>(url, HttpMethod.Post, postData);
}
/// <summary>
/// Sends an HTTP Delete request and does initial parsing
/// </summary>
/// <typeparam name="T">The <see cref="ApiResultBase"/>-derived class for the result</typeparam>
/// <param name="url">(optional) If provided, overrides the url endpoint for this request. If omitted, then <see cref="Url"/> will be used.</param>
/// <param name="postData">(optional) A json-serializable object to include in the request body.</param>
/// <returns>An awaitable Task with the parsed result of type <typeparamref name="T"/></returns>
/// <exception cref="HttpRequestException">Throws an exception if a non-success HTTP response was returned or if the result couldn't be parsed.</exception>
internal async Task<T> HttpDelete<T>(string url = null, object postData = null) where T : ApiResultBase
{
return await HttpRequest<T>(url, HttpMethod.Delete, postData);
}
/// <summary>
/// Sends an HTTP Put request and does initial parsing
/// </summary>
/// <typeparam name="T">The <see cref="ApiResultBase"/>-derived class for the result</typeparam>
/// <param name="url">(optional) If provided, overrides the url endpoint for this request. If omitted, then <see cref="Url"/> will be used.</param>
/// <param name="postData">(optional) A json-serializable object to include in the request body.</param>
/// <returns>An awaitable Task with the parsed result of type <typeparamref name="T"/></returns>
/// <exception cref="HttpRequestException">Throws an exception if a non-success HTTP response was returned or if the result couldn't be parsed.</exception>
internal async Task<T> HttpPut<T>(string url = null, object postData = null) where T : ApiResultBase
{
return await HttpRequest<T>(url, HttpMethod.Put, postData);
}
/*
/// <summary>
/// Sends an HTTP request and handles a streaming response. Does basic line splitting and error handling.
/// </summary>
/// <param name="url">(optional) If provided, overrides the url endpoint for this request. If omitted, then <see cref="Url"/> will be used.</param>
/// <param name="verb">(optional) The HTTP verb to use, for example "<see cref="HttpMethod.Get"/>". If omitted, then "GET" is assumed.</param>
/// <param name="postData">(optional) A json-serializable object to include in the request body.</param>
/// <returns>The HttpResponseMessage of the response, which is confirmed to be successful.</returns>
/// <exception cref="HttpRequestException">Throws an exception if a non-success HTTP response was returned</exception>
private async IAsyncEnumerable<string> HttpStreamingRequestRaw(string url = null, HttpMethod verb = null, object postData = null)
{
var response = await HttpRequestRaw(url, verb, postData, true);
using (var stream = await response.Content.ReadAsStreamAsync())
using (StreamReader reader = new StreamReader(stream))
{
string line;
while ((line = await reader.ReadLineAsync()) != null)
{
if (line.StartsWith("data: "))
line = line.Substring("data: ".Length);
if (line == "[DONE]")
{
yield break;
}
else if (!string.IsNullOrWhiteSpace(line))
{
yield return line.Trim();
}
}
}
}
*/
/// <summary>
/// Sends an HTTP request and handles a streaming response. Does basic line splitting and error handling.
/// </summary>
/// <param name="url">(optional) If provided, overrides the url endpoint for this request. If omitted, then <see cref="Url"/> will be used.</param>
/// <param name="verb">(optional) The HTTP verb to use, for example "<see cref="HttpMethod.Get"/>". If omitted, then "GET" is assumed.</param>
/// <param name="postData">(optional) A json-serializable object to include in the request body.</param>
/// <returns>The HttpResponseMessage of the response, which is confirmed to be successful.</returns>
/// <exception cref="HttpRequestException">Throws an exception if a non-success HTTP response was returned</exception>
protected async IAsyncEnumerable<T> HttpStreamingRequest<T>(string url = null, HttpMethod verb = null, object postData = null) where T : ApiResultBase
{
var response = await HttpRequestRaw(url, verb, postData, true);
string organization = null;
string requestId = null;
TimeSpan processingTime = TimeSpan.Zero;
string openaiVersion = null;
string modelFromHeaders = null;
try
{
organization = response.Headers.GetValues("Openai-Organization").FirstOrDefault();
requestId = response.Headers.GetValues("X-Request-ID").FirstOrDefault();
processingTime = TimeSpan.FromMilliseconds(int.Parse(response.Headers.GetValues("Openai-Processing-Ms").First()));
openaiVersion = response.Headers.GetValues("Openai-Version").FirstOrDefault();
modelFromHeaders = response.Headers.GetValues("Openai-Model").FirstOrDefault();
}
catch (Exception e)
{
Debug.Print($"Issue parsing metadata of OpenAi Response. Url: {url}, Error: {e.ToString()}. This is probably ignorable.");
}
string resultAsString = "";
using (var stream = await response.Content.ReadAsStreamAsync())
using (StreamReader reader = new StreamReader(stream))
{
string line;
while ((line = await reader.ReadLineAsync()) != null)
{
resultAsString += line + Environment.NewLine;
if (line.StartsWith("data:"))
line = line.Substring("data:".Length);
line = line.TrimStart();
if (line == "[DONE]")
{
yield break;
}
else if (line.StartsWith(":"))
{ }
else if (!string.IsNullOrWhiteSpace(line))
{
var res = JsonConvert.DeserializeObject<T>(line);
res.Organization = organization;
res.RequestId = requestId;
res.ProcessingTime = processingTime;
res.OpenaiVersion = openaiVersion;
if (string.IsNullOrEmpty(res.Model))
res.Model = modelFromHeaders;
yield return res;
}
}
}
}
internal class ApiErrorResponse
{
/// <summary>
/// The error details
/// </summary>
[JsonProperty("error")]
public ApiErrorResponseError Error { get; set; }
}
internal class ApiErrorResponseError
{
/// <summary>
/// The error message
/// </summary>
[JsonProperty("message")]
public string Message { get; set; }
/// <summary>
/// The type of error
/// </summary>
[JsonProperty("type")]
public string ErrorType { get; set; }
/// <summary>
/// The parameter that caused the error
/// </summary>
[JsonProperty("param")]
public string Parameter { get; set; }
/// <summary>
/// The error code
/// </summary>
[JsonProperty("code")]
public string ErrorCode { get; set; }
}
}
}