-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathOpenAiProvider.cs
291 lines (260 loc) · 12 KB
/
OpenAiProvider.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
using System.Diagnostics;
using System.Net;
using System.Net.Http.Headers;
using Microsoft.Extensions.Logging;
using ServiceStack;
using AiServer.ServiceModel;
namespace AiServer.ServiceInterface;
public class OpenAiProvider(ILogger<OpenAiProvider> log) : OpenAiProviderBase(log)
{
}
public class OllamaAiProvider(ILogger<OllamaAiProvider> log) : OpenAiProviderBase(log), IOllamaAiProvider
{
protected virtual async Task<OllamaGenerateResponse> SendOllamaGenerateRequestAsync(AiProvider provider, OllamaGenerate request,
Action<HttpRequestMessage>? requestFilter=null, Action<HttpResponseMessage>? responseFilter=null, CancellationToken token=default)
{
request.Stream ??= false;
if (request.Images?.Count > 0)
{
for (var i = 0; i < request.Images.Count; i++)
{
var imgUrl = request.Images[i];
if (imgUrl.StartsWith("http://") || imgUrl.StartsWith("https://"))
{
log.LogInformation($"Downloading image {imgUrl} ...");
var bytes = await imgUrl.GetBytesFromUrlAsync(token:token);
request.Images[i] = Convert.ToBase64String(bytes);
log.LogInformation($"Downloaded image {bytes.Length} bytes, {request.Images[i].Length} base64 chars");
}
}
}
var url = GetApiEndpointUrlFor(provider,TaskType.OllamaGenerate);
var responseJson = await url.PostJsonToUrlAsync(request,
requestFilter: requestFilter,
responseFilter: responseFilter, token: token);
var response = responseJson.FromJson<OllamaGenerateResponse>();
return response;
}
public virtual async Task<OllamaGenerationResult> GenerateAsync(AiProvider provider, OllamaGenerate request, CancellationToken token = default)
{
var requestFilter = CreateRequestFilter(provider);
return await GenerateAsync(provider, request, token, requestFilter);
}
protected virtual Action<HttpRequestMessage>? CreateRequestFilter(AiProvider provider)
{
Action<HttpRequestMessage>? requestFilter = provider.ApiKey != null
? req =>
{
if (provider.ApiKeyHeader != null)
{
req.Headers.Add(provider.ApiKeyHeader, provider.ApiKey);
}
else
{
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", provider.ApiKey);
}
}
: null;
return requestFilter;
}
public async Task<OllamaGenerationResult> GenerateAsync(AiProvider provider, OllamaGenerate request, CancellationToken token, Action<HttpRequestMessage>? requestFilter)
{
var sw = Stopwatch.StartNew();
var origModel = request.Model;
request.Model = provider.GetAiModel(request.Model);
Exception? firstEx = null;
var retries = 0;
while (retries++ < 10)
{
var headers = Array.Empty<string>();
var contentHeaders = Array.Empty<string>();
string? errorResponse = null;
int retryAfter = 0;
var sleepMs = 1000 * retries;
try
{
Action<HttpResponseMessage>? responseFilter = res =>
{
headers = res.Headers.Select(x => $"{x.Key}: {x.Value.FirstOrDefault()}").ToArray();
contentHeaders = res.Content.Headers.Select(x => $"{x.Key}: {x.Value.FirstOrDefault()}")
.ToArray();
// GROQ
if (res.Headers.TryGetValues("retry-after", out var retryAfterValues))
{
var retryAfterStr = retryAfterValues.FirstOrDefault();
log.LogWarning("retry-after: {RetryAfter}", retryAfterStr ?? "null");
if (retryAfterStr != null)
int.TryParse(retryAfterStr, out retryAfter);
}
if (res.StatusCode >= HttpStatusCode.BadRequest)
{
errorResponse = res.Content.ReadAsString();
}
};
var response = await SendOllamaGenerateRequestAsync(provider, request, requestFilter, responseFilter, token);
var durationMs = (int)sw.ElapsedMilliseconds;
request.Model = origModel;
return new(response, durationMs);
}
catch (HttpRequestException e)
{
log.LogInformation("[{Name}] Headers:\n{Headers}", provider.Name, string.Join('\n', headers));
log.LogInformation("[{Name}] Content Headers:\n{Headers}", provider.Name,
string.Join('\n', contentHeaders));
if (!string.IsNullOrEmpty(errorResponse))
{
log.LogError("[{Name}] Error Response:\n{ErrorResponse}", provider.Name, errorResponse);
}
firstEx ??= e;
if (e.StatusCode is null or HttpStatusCode.TooManyRequests or >= HttpStatusCode.InternalServerError)
{
if (retryAfter > 0)
sleepMs = retryAfter * 1000;
log.LogInformation("[{Name}] {Message} for {Provider}, retrying after {SleepMs}ms",
provider.Name, e.Message, provider.Name, sleepMs);
await Task.Delay(sleepMs, token);
}
else throw;
}
}
throw firstEx ?? new Exception($"[{provider.Name}] Failed to complete OpenAI Chat request after {retries} retries");
}
}
public class OpenAiProviderBase(ILogger log) : IOpenAiProvider
{
public string GetApiEndpointUrlFor(AiProvider aiProvider, TaskType taskType)
{
var apiBaseUrl = aiProvider.ApiBaseUrl ?? aiProvider.AiType?.ApiBaseUrl
?? throw new NotSupportedException($"[{aiProvider.Name}] No ApiBaseUrl found in AiProvider or AiType");
if (taskType == TaskType.OllamaGenerate)
return apiBaseUrl.CombineWith("/api/generate");
if (taskType == TaskType.OpenAiChat)
return apiBaseUrl.CombineWith("/v1/chat/completions");
throw new NotSupportedException($"[{aiProvider.Name}] does not support {taskType}");
}
public virtual async Task<OpenAiChatResult> ChatAsync(AiProvider provider, OpenAiChat request, CancellationToken token = default)
{
var requestFilter = CreateRequestFilter(provider);
return await ChatAsync(provider, request, token, requestFilter);
}
protected virtual Action<HttpRequestMessage>? CreateRequestFilter(AiProvider provider)
{
Action<HttpRequestMessage>? requestFilter = provider.ApiKey != null
? req =>
{
if (provider.ApiKeyHeader != null)
{
req.Headers.Add(provider.ApiKeyHeader, provider.ApiKey);
}
else
{
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", provider.ApiKey);
}
}
: null;
return requestFilter;
}
protected virtual async Task<OpenAiChatResult> ChatAsync(AiProvider provider, OpenAiChat request, CancellationToken token, Action<HttpRequestMessage>? requestFilter)
{
var sw = Stopwatch.StartNew();
var origModel = request.Model;
request.Model = provider.GetAiModel(request.Model);
Exception? firstEx = null;
var retries = 0;
while (retries++ < 10)
{
var headers = Array.Empty<string>();
var contentHeaders = Array.Empty<string>();
string? errorResponse = null;
int retryAfter = 0;
var sleepMs = 1000 * retries;
try
{
Action<HttpResponseMessage>? responseFilter = res =>
{
headers = res.Headers.Select(x => $"{x.Key}: {x.Value.FirstOrDefault()}").ToArray();
contentHeaders = res.Content.Headers.Select(x => $"{x.Key}: {x.Value.FirstOrDefault()}")
.ToArray();
// GROQ
if (res.Headers.TryGetValues("retry-after", out var retryAfterValues))
{
var retryAfterStr = retryAfterValues.FirstOrDefault();
log.LogWarning("retry-after: {RetryAfter}", retryAfterStr ?? "null");
if (retryAfterStr != null)
int.TryParse(retryAfterStr, out retryAfter);
}
if (res.StatusCode >= HttpStatusCode.BadRequest)
{
errorResponse = res.Content.ReadAsString();
}
};
var response = await SendOpenAiChatRequestAsync(provider, request, requestFilter, responseFilter, token);
var durationMs = (int)sw.ElapsedMilliseconds;
request.Model = origModel;
return new(response, durationMs);
}
catch (HttpRequestException e)
{
log.LogInformation("[{Name}] Headers:\n{Headers}", provider.Name, string.Join('\n', headers));
log.LogInformation("[{Name}] Content Headers:\n{Headers}", provider.Name,
string.Join('\n', contentHeaders));
if (!string.IsNullOrEmpty(errorResponse))
{
log.LogError("[{Name}] Error Response:\n{ErrorResponse}", provider.Name, errorResponse);
}
firstEx ??= e;
if (e.StatusCode is null or HttpStatusCode.TooManyRequests or >= HttpStatusCode.InternalServerError)
{
if (retryAfter > 0)
sleepMs = retryAfter * 1000;
log.LogInformation("[{Name}] {Message} for {Provider}, retrying after {SleepMs}ms",
provider.Name, e.Message, provider.Name, sleepMs);
await Task.Delay(sleepMs, token);
}
else throw;
}
}
throw firstEx ?? new Exception($"[{provider.Name}] Failed to complete OpenAI Chat request after {retries} retries");
}
protected virtual async Task<OpenAiChatResponse> SendOpenAiChatRequestAsync(AiProvider provider, OpenAiChat request,
Action<HttpRequestMessage>? requestFilter=null, Action<HttpResponseMessage>? responseFilter=null, CancellationToken token=default)
{
var url = GetApiEndpointUrlFor(provider,TaskType.OpenAiChat);
var responseJson = await url.PostJsonToUrlAsync(request,
requestFilter: requestFilter,
responseFilter: responseFilter, token: token);
var response = responseJson.FromJson<OpenAiChatResponse>();
return response;
}
public virtual async Task<bool> IsOnlineAsync(AiProvider provider, CancellationToken token = default)
{
try
{
var requestFilter = CreateRequestFilter(provider);
var heartbeatUrl = provider.HeartbeatUrl;
if (heartbeatUrl != null)
{
await heartbeatUrl.GetStringFromUrlAsync(requestFilter:requestFilter, token: token);
}
var apiModel = provider.GetPreferredAiModel();
var request = new OpenAiChat
{
Model = apiModel,
Messages = [
new() { Role = "user", Content = "1+1=" },
],
MaxTokens = 2,
Stream = false,
};
var response = await SendOpenAiChatRequestAsync(provider, request,
requestFilter: requestFilter, responseFilter: null, token: token);
return true;
}
catch (Exception e)
{
if (e is TaskCanceledException)
throw;
return false;
}
}
}