-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgateway.bal
1433 lines (1272 loc) · 51.3 KB
/
gateway.bal
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import ballerina/io;
import ballerina/http;
import ballerina/log;
import ai_gateway.llms;
import ai_gateway.analytics;
import ai_gateway.logging;
import ballerina/time;
import ballerina/uuid;
import ballerina/grpc;
import ballerina/crypto;
configurable llms:OpenAIConfig? & readonly openAIConfig = ();
configurable llms:AnthropicConfig? & readonly anthropicConfig = ();
configurable llms:GeminiConfig? & readonly geminiConfig = ();
configurable llms:OllamaConfig? & readonly ollamaConfig = ();
configurable llms:OpenAIConfig? & readonly mistralConfig = ();
configurable llms:OpenAIConfig? & readonly cohereConfig = ();
type GatewayConfig record {
int port = 8080;
int adminPort = 8081;
boolean verboseLogging = false;
};
// Gateway configuration
configurable GatewayConfig gateway = {};
// Add system prompt storage
string systemPrompt = "";
// Add guardrails configuration type
type GuardrailConfig record {
string[] bannedPhrases;
int minLength;
int maxLength;
boolean requireDisclaimer;
string disclaimer?;
};
// Add guardrails storage
GuardrailConfig guardrails = {
bannedPhrases: [],
minLength: 0,
maxLength: 500000,
requireDisclaimer: false
};
// Add guardrails processing function
function applyGuardrails(string text) returns string|error {
if (text.length() < guardrails.minLength) {
return error("Response too short. Minimum length: " + guardrails.minLength.toString());
}
string textRes = text;
if (text.length() > guardrails.maxLength) {
textRes = text.substring(0, guardrails.maxLength);
}
foreach string phrase in guardrails.bannedPhrases {
if (text.toLowerAscii().includes(phrase)) {
return error("Response contains banned phrase: " + phrase);
}
}
if (guardrails.requireDisclaimer && guardrails.disclaimer != null) {
textRes = text + "\n\n" + (guardrails.disclaimer ?: "");
}
return textRes;
}
// Add cache type and storage
type CacheEntry record {
llms:LLMResponse response;
int timestamp;
};
map<CacheEntry> promptCache = {};
// Add cache configuration
configurable int cacheTTLSeconds = 3600; // Default 1 hour TTL
// Using this to read initial logging configuration from system startup
// When the configurable is read from Config.toml at system startup, cannot assign or update
// that value later using the /admin service. So copying this at init()
configurable logging:LoggingConfig defaultLoggingConfig = {};
logging:LoggingConfig loggingConfig = {
enableSplunk: false,
enableDatadog: false,
enableElasticSearch: false,
openTelemetryEndpoint: "",
splunkEndpoint: "",
datadogEndpoint: "",
elasticSearchEndpoint: "",
elasticApiKey: ""
};
// Add logging state
boolean isVerboseLogging = gateway.verboseLogging;
function logEvent(string level, string component, string message, map<json> metadata = {}) {
if (!isVerboseLogging && level == "DEBUG") {
return;
}
// Create a copy of metadata to avoid modifying the original
map<any> sanitizedMetadata = metadata.clone();
// Mask sensitive data in metadata
foreach string key in sanitizedMetadata.keys() {
if (key.toLowerAscii().includes("apikey")) {
sanitizedMetadata[key] = "********";
}
}
json logEntry = {
timestamp: time:utcToString(time:utcNow()),
level: level,
component: component,
message: message,
metadata: sanitizedMetadata.toString()
};
// Always log to console
log:printInfo(logEntry.toString());
// Publish to configured services
if (loggingConfig.enableSplunk) {
_ = start logging:publishToSplunk(loggingConfig, logEntry);
}
if (loggingConfig.enableDatadog) {
_ = start logging:publishToDatadog(loggingConfig, logEntry);
}
if (loggingConfig.enableElasticSearch) {
_ = start logging:publishToElasticSearch(loggingConfig, logEntry);
}
}
// Add rate limiting types and storage
type RateLimitPlan record {|
string name;
int requestsPerWindow;
int windowSeconds;
|};
type RateLimitState record {|
int requests;
int windowStart;
|};
// Store rate limit states by IP
map<RateLimitState> rateLimitStates = {};
RateLimitPlan? currentRateLimitPlan = ();
// Add rate limiting function
function checkRateLimit(string clientIP) returns [boolean, int, int, int]|error {
if currentRateLimitPlan is () {
return [true, 0, 0, 0];
}
RateLimitPlan plan = <RateLimitPlan>currentRateLimitPlan;
int currentTime = time:utcNow()[0];
lock {
RateLimitState state = rateLimitStates[clientIP] ?: {
requests: 0,
windowStart: currentTime
};
// Check if we need to reset window
if (currentTime - state.windowStart >= plan.windowSeconds) {
state = {
requests: 0,
windowStart: currentTime
};
}
// Calculate remaining quota and time
int remaining = plan.requestsPerWindow - state.requests;
int resetSeconds = plan.windowSeconds - (currentTime - state.windowStart);
if (state.requests >= plan.requestsPerWindow) {
rateLimitStates[clientIP] = state;
return [false, plan.requestsPerWindow, remaining, resetSeconds];
}
// Increment request count
state.requests += 1;
rateLimitStates[clientIP] = state;
return [true, plan.requestsPerWindow, remaining - 1, resetSeconds];
}
}
@grpc:Descriptor {value: AI_GATEWAY_DESC}
service "AIGateway" on new grpc:Listener(8082) {
private http:Client? openaiClient = ();
private http:Client? anthropicClient = ();
private http:Client? geminiClient = ();
private http:Client? ollamaClient = ();
private http:Client? mistralClient = ();
private http:Client? cohereClient = ();
function init() returns error? {
check self.initializeClients();
}
remote function ChatCompletion(ChatCompletionRequest request) returns ChatCompletionResponse|error {
// Convert gRPC request to internal LLMRequest format
llms:LLMRequest llmRequest = {
messages: from var msg in request.messages
select {
role: msg.role,
content: msg.content
},
temperature: request.temperature,
maxTokens: request.max_tokens
};
// Reuse existing provider handling logic
llms:LLMResponse|error response = self.tryProvider(request.llm_provider, llmRequest);
if response is error {
return response;
}
// Convert LLMResponse to gRPC response format
return <ChatCompletionResponse>{
id: response.id,
'object: response.'object,
created: response.created,
model: response.model,
choices: from var choice in response.choices
select {
index: choice.index,
message: {
role: choice.message.role,
content: choice.message.content
},
finish_reason: choice.finish_reason
},
usage: {
prompt_tokens: response.usage.prompt_tokens,
completion_tokens: response.usage.completion_tokens,
total_tokens: response.usage.prompt_tokens + response.usage.completion_tokens
}
};
}
private function initializeClients() returns error? {
logEvent("INFO", "gRPC:init", "Initializing AI Gateway gRPC interface");
// Read initial logging configuration
loggingConfig = defaultLoggingConfig;
logEvent("DEBUG", "gRPC:init", "Loaded logging configuration", <map<json>>loggingConfig.toJson());
// Check if at least one provider is configured
if openAIConfig == () && anthropicConfig == () && geminiConfig == () && ollamaConfig == () && mistralConfig == () && cohereConfig == () {
logEvent("ERROR", "gRPC:init", "No LLM providers configured");
return error("At least one LLM provider must be configured");
}
if openAIConfig?.endpoint != () {
string endpoint = openAIConfig?.endpoint ?: "";
if (endpoint == "") {
logEvent("ERROR", "gRPC:init", "Invalid OpenAI configuration", {"error": "Empty endpoint"});
return error("OpenAI endpoint is required");
} else {
self.openaiClient = check new (endpoint);
logEvent("INFO", "gRPC:init", "OpenAI client initialized", {"endpoint": endpoint});
}
}
if anthropicConfig?.endpoint != () {
string endpoint = anthropicConfig?.endpoint ?: "";
if (endpoint == "") {
return error("Anthropic endpoint is required");
} else {
self.anthropicClient = check new (endpoint);
}
}
if geminiConfig?.endpoint != () {
string endpoint = geminiConfig?.endpoint ?: "";
if (endpoint == "") {
return error("Gemini endpoint is required");
} else {
self.geminiClient = check new (endpoint);
}
}
if ollamaConfig?.endpoint != () {
string endpoint = ollamaConfig?.endpoint ?: "";
if (endpoint == "") {
return error("Ollama endpoint is required");
} else {
self.ollamaClient = check new (endpoint);
}
}
if mistralConfig?.endpoint != () {
string endpoint = mistralConfig?.endpoint ?: "";
if (endpoint == "") {
return error("Mistral endpoint is required");
} else {
self.mistralClient = check new (endpoint);
}
}
if cohereConfig?.endpoint != () {
string endpoint = cohereConfig?.endpoint ?: "";
if (endpoint == "") {
return error("Cohere endpoint is required");
} else {
self.cohereClient = check new (endpoint);
}
}
logEvent("INFO", "gRPC:init", "AI Gateway initialization complete", {
"providers": [
openAIConfig != () ? "openai" : "",
anthropicConfig != () ? "anthropic" : "",
geminiConfig != () ? "gemini" : "",
ollamaConfig != () ? "ollama" : "",
mistralConfig != () ? "mistral" : "",
cohereConfig != () ? "cohere" : ""
].filter(p => p != "")
});
}
private function tryProvider(string provider, llms:LLMRequest payload) returns llms:LLMResponse|error {
// Reuse provider handling logic from HTTP service
string requestId = uuid:createType1AsString();
logEvent("DEBUG", "gRPC:provider", "Attempting provider request", {
requestId: requestId,
provider: provider,
prompt: payload.toString()
});
// Map of provider to client
map<http:Client?> clientMap = {
"openai": self.openaiClient,
"anthropic": self.anthropicClient,
"gemini": self.geminiClient,
"ollama": self.ollamaClient,
"mistral": self.mistralClient,
"cohere": self.cohereClient
};
// Map of provider to handler function
map<function (http:Client, llms:LLMRequest) returns llms:LLMResponse|error> handlerMap = {
"openai": handleOpenAIRequest,
"anthropic": handleAnthropicRequest,
"gemini": handleGeminiRequest,
"ollama": handleOllamaRequest,
"mistral": handleMistralRequest,
"cohere": handleCohereRequest
};
http:Client? llmClient = clientMap[provider];
var handler = handlerMap[provider];
if llmClient is http:Client && handler is function {
llms:LLMResponse|error response = handler(llmClient, payload);
if response is llms:LLMResponse {
logEvent("INFO", "gRPC:provider", "Provider request successful", {
requestId: requestId,
provider: provider,
model: response.model,
tokens: {
input: response.usage.prompt_tokens,
output: response.usage.completion_tokens
}
});
// Update stats for successful request
lock {
requestStats.totalRequests += 1;
requestStats.successfulRequests += 1;
requestStats.requestsByProvider[provider] = (requestStats.requestsByProvider[provider] ?: 0) + 1;
tokenStats.totalInputTokens += response.usage.prompt_tokens;
tokenStats.totalOutputTokens += response.usage.completion_tokens;
tokenStats.inputTokensByProvider[provider] = (tokenStats.inputTokensByProvider[provider] ?: 0) + response.usage.prompt_tokens;
tokenStats.outputTokensByProvider[provider] = (tokenStats.outputTokensByProvider[provider] ?: 0) + response.usage.completion_tokens;
}
}
return response;
}
logEvent("ERROR", "gRPC:provider", "Provider not configured", {
requestId: requestId,
provider: provider
});
return error("Provider not configured: " + provider);
}
}
function handleOpenAIRequest(http:Client openaiClient, llms:LLMRequest req) returns llms:LLMResponse|error {
string requestId = uuid:createType1AsString();
if openAIConfig == () {
logEvent("ERROR", "openai", "OpenAI not configured", {requestId});
return error("OpenAI is not configured");
}
[string,string]|error prompts = getPrompts(req);
if prompts is error {
return error("Invalid request");
}
string reqSystemPrompt = prompts[0];
string reqUserPrompt = prompts[1];
// Transform to OpenAI format
json openAIPayload = {
"model": openAIConfig?.model,
"messages": [
{
"role": "system",
"content": reqSystemPrompt + " " + systemPrompt
},
{
"role": "user",
"content": reqUserPrompt
}
],
"temperature": req.temperature ?: 0.7,
"max_tokens": req.maxTokens ?: 1000
};
if openAIConfig?.apiKey != "" {
map<string|string[]> headers = { "Authorization": "Bearer " + (openAIConfig?.apiKey ?: "") };
logEvent("DEBUG", "openai", "Sending request to OpenAI", {
requestId,
model: openAIConfig?.model ?: "",
promptLength: reqUserPrompt.length()
});
http:Response|error response = openaiClient->post("/v1/chat/completions", openAIPayload, headers);
if response is error {
logEvent("ERROR", "openai", "HTTP request failed", {
requestId,
'error: response.message() + ":" + response.detail().toString()
});
return response;
}
json|error responsePayload = response.getJsonPayload();
if responsePayload is error {
logEvent("ERROR", "openai", "Invalid JSON response", {
requestId,
'error: responsePayload.message() + ":" + responsePayload.detail().toString()
});
return responsePayload;
}
llms:OpenAIResponse|error openAIResponse = responsePayload.cloneWithType(llms:OpenAIResponse);
if openAIResponse is error {
logEvent("ERROR", "openai", "Response type conversion failed", {
requestId,
'error: openAIResponse.message() + ":" + openAIResponse.detail().toString()
});
return openAIResponse;
}
// Apply guardrails
string|error guardedText = applyGuardrails(openAIResponse.choices[0].message.content);
if guardedText is error {
logEvent("ERROR", "guardrails", "Guardrails check failed", {
requestId,
'error: guardedText.message() + ":" + guardedText.detail().toString()
});
return guardedText;
}
return {
id: uuid:createType1AsString(),
'object: "chat.completion",
created: time:utcNow()[0],
model: openAIResponse.model,
system_fingerprint: (),
choices: [{
index: openAIResponse.choices[0].index,
message: {
role: "assistant",
content: guardedText
},
finish_reason: openAIResponse.choices[0].finish_reason ?: "stop"
}],
usage: {
prompt_tokens: openAIResponse.usage.prompt_tokens,
completion_tokens: openAIResponse.usage.completion_tokens,
total_tokens: openAIResponse.usage.total_tokens
}
};
} else {
logEvent("ERROR", "openai", "Invalid API key configuration", {requestId});
return error("OpenAI configuration is invalid");
}
}
function handleOllamaRequest(http:Client ollamaClient, llms:LLMRequest req) returns llms:LLMResponse|error {
if ollamaConfig == () {
return error("Ollama is not configured");
}
[string,string]|error prompts = getPrompts(req);
if prompts is error {
return error("Invalid request");
}
string reqSystemPrompt = prompts[0];
string reqUserPrompt = prompts[1];
json ollamaPayload = {
"model": ollamaConfig?.model,
"messages": [
{
"role": "system",
"content": reqSystemPrompt + " " + systemPrompt
},
{
"role": "user",
"content": reqUserPrompt
}
],
"stream": false
};
if ollamaConfig?.apiKey != "" {
map<string|string[]> headers = { "Authorization": "Bearer " + (ollamaConfig?.apiKey ?: "") };
http:Response response = check ollamaClient->post("/api/chat", ollamaPayload, headers);
json responsePayload = check response.getJsonPayload();
log:printInfo("Ollama response: " + responsePayload.toString());
llms:OllamaResponse ollamaResponse = check responsePayload.cloneWithType(llms:OllamaResponse);
// Apply guardrails before returning
string guardedText = check applyGuardrails(ollamaResponse.message.content);
return {
id: uuid:createType1AsString(),
'object: "chat.completion",
created: time:utcNow()[0],
model: ollamaResponse.model,
system_fingerprint: (),
choices: [{
index: 0,
message: {
role: "assistant",
content: guardedText
},
finish_reason: ollamaResponse.done_reason
}],
usage: {
prompt_tokens: ollamaResponse.prompt_eval_count,
completion_tokens: ollamaResponse.eval_count,
total_tokens: ollamaResponse.prompt_eval_count + ollamaResponse.eval_count
}
};
} else {
return error("Ollama configuration is invalid");
}
}
function handleAnthropicRequest(http:Client anthropicClient, llms:LLMRequest req) returns llms:LLMResponse|error {
if anthropicConfig == () {
return error("Anthropic is not configured");
}
[string,string]|error prompts = getPrompts(req);
if prompts is error {
return error("Invalid request");
}
string reqSystemPrompt = prompts[0];
string reqUserPrompt = prompts[1];
json anthropicPayload = {
"model": anthropicConfig?.model,
"messages": [
{
"role": "system",
"content": reqSystemPrompt + " " + systemPrompt
},
{
"role": "user",
"content": reqUserPrompt
}
],
"max_tokens": req.maxTokens ?: 1000
};
if anthropicConfig?.apiKey != "" {
map<string|string[]> headers = {
"Authorization": "Bearer " + (anthropicConfig?.apiKey ?: ""),
"anthropic-version": "2023-06-01"
};
http:Response response = check anthropicClient->post("/v1/messages", anthropicPayload, headers);
json responsePayload = check response.getJsonPayload();
log:printInfo("Anthropic response: " + responsePayload.toString());
llms:AnthropicResponse anthropicResponse = check responsePayload.cloneWithType(llms:AnthropicResponse);
// Apply guardrails before returning
string guardedText = check applyGuardrails(anthropicResponse.contents.content[0].text);
return {
id: uuid:createType1AsString(),
'object: "chat.completion",
created: time:utcNow()[0],
model: anthropicResponse.model,
system_fingerprint: (),
choices: [{
index: 0,
message: {
role: "assistant",
content: guardedText
},
finish_reason: ""
}],
usage: {
prompt_tokens: 0,
completion_tokens: 0,
total_tokens: 0
}
};
} else {
return error("Anthropic configuration is invalid");
}
}
function handleGeminiRequest(http:Client geminiClient, llms:LLMRequest req) returns llms:LLMResponse|error {
if geminiConfig == () {
return error("Gemini is not configured");
}
[string,string]|error prompts = getPrompts(req);
if prompts is error {
return error("Invalid request");
}
string reqSystemPrompt = prompts[0];
string reqUserPrompt = prompts[1];
json geminiPayload = {
"model": geminiConfig?.model,
"messages": [
{
"role": "system",
"content": reqSystemPrompt + " " + systemPrompt
},
{
"role": "user",
"content": reqUserPrompt
}
],
"temperature": req.temperature ?: 0.7,
"max_tokens": req.maxTokens ?: 1000
};
if geminiConfig?.apiKey != "" {
map<string|string[]> headers = { "Authorization": "Bearer " + (geminiConfig?.apiKey ?: "") };
http:Response response = check geminiClient->post(":chatCompletions", geminiPayload, headers);
json responsePayload = check response.getJsonPayload();
log:printInfo("Gemini response: " + responsePayload.toString());
llms:OpenAIResponse geminiResponse = check responsePayload.cloneWithType(llms:OpenAIResponse);
// Apply guardrails before returning
string guardedText = check applyGuardrails(geminiResponse.choices[0].message.content);
return {
id: uuid:createType1AsString(),
'object: "chat.completion",
created: time:utcNow()[0],
model: geminiResponse.model,
system_fingerprint: (),
choices: [{
index: 0,
message: {
role: "assistant",
content: guardedText
},
finish_reason: geminiResponse.choices[0].finish_reason ?: ""
}],
usage: {
prompt_tokens: 0,
completion_tokens: 0,
total_tokens: 0
}
};
} else {
return error("Gemini configuration is invalid");
}
}
function handleMistralRequest(http:Client mistralClient, llms:LLMRequest req) returns llms:LLMResponse|error {
if mistralConfig == () {
return error("Mistral is not configured");
}
[string,string]|error prompts = getPrompts(req);
if prompts is error {
return error("Invalid request");
}
string reqSystemPrompt = prompts[0];
string reqUserPrompt = prompts[1];
json mistralPayload = {
"model": mistralConfig?.model,
"messages": [
{
"role": "system",
"content": reqSystemPrompt + " " + systemPrompt
},
{
"role": "user",
"content": reqUserPrompt
}
],
"temperature": req.temperature ?: 0.7,
"max_tokens": req.maxTokens ?: 1000
};
if mistralConfig?.apiKey != "" {
map<string|string[]> headers = { "Authorization": "Bearer " + (mistralConfig?.apiKey ?: "") };
http:Response response = check mistralClient->post("/v1/chat/completions", mistralPayload, headers);
json responsePayload = check response.getJsonPayload();
log:printInfo("Mistral response: " + responsePayload.toString());
llms:OpenAIResponse mistralResponse = check responsePayload.cloneWithType(llms:OpenAIResponse);
// Apply guardrails before returning
string guardedText = check applyGuardrails(mistralResponse.choices[0].message.content);
return {
id: uuid:createType1AsString(),
'object: "chat.completion",
created: time:utcNow()[0],
model: mistralResponse.model,
system_fingerprint: (),
choices: [{
index: 0,
message: {
role: "assistant",
content: guardedText
},
finish_reason: mistralResponse.choices[0].finish_reason ?: ""
}],
usage: {
prompt_tokens: 0,
completion_tokens: 0,
total_tokens: 0
}
};
} else {
return error("Mistral configuration is invalid");
}
}
function handleCohereRequest(http:Client cohereClient, llms:LLMRequest req) returns llms:LLMResponse|error {
if cohereConfig == () {
return error("Cohere is not configured");
}
[string,string]|error prompts = getPrompts(req);
if prompts is error {
return error("Invalid request");
}
string reqSystemPrompt = prompts[0];
string reqUserPrompt = prompts[1];
string cohereSystemPromt = "test";
if (systemPrompt != "") {
cohereSystemPromt = reqUserPrompt + " " + systemPrompt;
}
json coherePayload = {
"message": reqUserPrompt,
"chat_history": [{
"role": "USER",
"message": reqUserPrompt
},
{
"role": "SYSTEM",
"message": cohereSystemPromt + " " + reqSystemPrompt
}],
"temperature": req.temperature ?: 0.7,
"max_tokens": req.maxTokens ?: 1000,
"model": cohereConfig?.model,
"preamble": "You are an AI-assistant chatbot. You are trained to assist users by providing thorough and helpful responses to their queries."
};
if cohereConfig?.apiKey != "" {
map<string|string[]> headers = {
"Authorization": "Bearer " + (cohereConfig?.apiKey ?: ""),
"Content-Type": "application/json",
"Accept": "application/json"
};
http:Response response = check cohereClient->post("/v1/chat", coherePayload, headers);
json responsePayload = check response.getJsonPayload();
log:printInfo("Cohere response: " + responsePayload.toString());
llms:CohereResponse cohereResponse = check responsePayload.cloneWithType(llms:CohereResponse);
// Apply guardrails before returning
string guardedText = check applyGuardrails(cohereResponse.text);
return {
id: uuid:createType1AsString(),
'object: "chat.completion",
created: time:utcNow()[0],
model: cohereConfig?.model ?: "",
system_fingerprint: (),
choices: [{
index: 0,
message: {
role: "assistant",
content: guardedText
},
finish_reason: "stop"
}],
usage: {
prompt_tokens: cohereResponse.meta.tokens.input_tokens,
completion_tokens: cohereResponse.meta.tokens.output_tokens,
total_tokens: cohereResponse.meta.tokens.input_tokens + cohereResponse.meta.tokens.output_tokens
}
};
} else {
return error("Cohere configuration is invalid");
}
}
service class ResponseInterceptor {
*http:ResponseInterceptor;
remote function interceptResponse(http:RequestContext ctx, http:Response res) returns http:NextService|error? {
res.setHeader("Server", "ai-gateway/v1.1.0");
return ctx.next();
}
}
// Add request interceptor for cache handling
service class RequestInterceptor {
*http:RequestInterceptor;
resource function 'default[string... path](http:RequestContext ctx, http:Request req) returns http:NextService|http:Response|error? {
// Only intercept POST requests to chat completions endpoint
// if req.method != "POST" || !req.rawPath.startsWith("/v1/chat/completions") {
// return ctx.next();
// }
log:printInfo("START REQUEST INTERCEPTOR ----------------------------");
// Check Cache-Control header
string|http:HeaderNotFoundError cacheControl = req.getHeader("Cache-Control");
if cacheControl is string && cacheControl == "no-cache" {
return ctx.next();
}
// Get provider and payload
string|http:HeaderNotFoundError provider = req.getHeader("x-llm-provider");
if provider is http:HeaderNotFoundError {
return ctx.next();
}
json|error payload = req.getJsonPayload();
if payload is error {
return ctx.next();
}
// Generate cache key using SHA1
string cacheKey = check generateCacheKey(provider, payload);
log:printInfo(">>>>>>>>>>>>>>>>>>>>>>>>>> " + cacheKey);
// Check cache
if promptCache.hasKey(cacheKey) {
CacheEntry entry = promptCache.get(cacheKey);
int currentTime = time:utcNow()[0];
// Check if cache entry is still valid
if (currentTime - entry.timestamp < cacheTTLSeconds) {
logEvent("INFO", "cache", "Cache hit", {
cacheKey: cacheKey
});
// Update cache stats
lock {
requestStats.totalRequests += 1;
requestStats.cacheHits += 1;
requestStats.requestsByProvider[provider] = (requestStats.requestsByProvider[provider] ?: 0) + 1;
tokenStats.totalInputTokens += entry.response.usage.prompt_tokens;
tokenStats.totalOutputTokens += entry.response.usage.completion_tokens;
tokenStats.inputTokensByProvider[provider] = (tokenStats.inputTokensByProvider[provider] ?: 0) + entry.response.usage.prompt_tokens;
tokenStats.outputTokensByProvider[provider] = (tokenStats.outputTokensByProvider[provider] ?: 0) + entry.response.usage.completion_tokens;
}
// Set cached response
http:Response cachedResponse = new;
cachedResponse.setPayload(entry.response);
return cachedResponse;
} else {
logEvent("DEBUG", "cache", "Cache entry expired", {
cacheKey: cacheKey,
age: currentTime - entry.timestamp
});
_ = promptCache.remove(cacheKey);
}
}
// Store cache key in context for later use
ctx.set("cacheKey", cacheKey);
return ctx.next();
}
}
// Add helper function to generate cache key
function generateCacheKey(string provider, json payload) returns string|error {
// byte[] hash = crypto:hashSha1(provider.toBytes().concat(payload.toString().toBytes()));
byte[] hash = crypto:hashSha1((provider+payload.toString()).toBytes());
return hash.toBase16();
}
// Update service to use both interceptors
service http:InterceptableService / on new http:Listener(8080) {
private http:Client? openaiClient = ();
private http:Client? anthropicClient = ();
private http:Client? geminiClient = ();
private http:Client? ollamaClient = ();
private http:Client? mistralClient = ();
private http:Client? cohereClient = ();
public function createInterceptors() returns [RequestInterceptor, ResponseInterceptor] {
return [new RequestInterceptor(), new ResponseInterceptor()];
}
function init() returns error? {
logEvent("INFO", "HTTP:init", "Initializing AI Gateway");
// Read initial logging configuration
loggingConfig = defaultLoggingConfig;
logEvent("DEBUG", "HTTP:init", "Loaded logging configuration", <map<json>>loggingConfig.toJson());
// Check if at least one provider is configured
if openAIConfig == () && anthropicConfig == () && geminiConfig == () && ollamaConfig == () && mistralConfig == () && cohereConfig == () {
logEvent("ERROR", "HTTP:init", "No LLM providers configured");
return error("At least one LLM provider must be configured");
}
if openAIConfig?.endpoint != () {
string endpoint = openAIConfig?.endpoint ?: "";
if (endpoint == "") {
logEvent("ERROR", "HTTP:init", "Invalid OpenAI configuration", {"error": "Empty endpoint"});
return error("OpenAI endpoint is required");
} else {
self.openaiClient = check new (endpoint);
logEvent("INFO", "HTTP:init", "OpenAI client initialized", {"endpoint": endpoint});
}
}
if anthropicConfig?.endpoint != () {
string endpoint = anthropicConfig?.endpoint ?: "";
if (endpoint == "") {
return error("Anthropic endpoint is required");
} else {
self.anthropicClient = check new (endpoint);
}
}
if geminiConfig?.endpoint != () {
string endpoint = geminiConfig?.endpoint ?: "";
if (endpoint == "") {
return error("Gemini endpoint is required");
} else {
self.geminiClient = check new (endpoint);
}
}
if ollamaConfig?.endpoint != () {
string endpoint = ollamaConfig?.endpoint ?: "";
if (endpoint == "") {
return error("Ollama endpoint is required");
} else {
self.ollamaClient = check new (endpoint);
}
}
if mistralConfig?.endpoint != () {
string endpoint = mistralConfig?.endpoint ?: "";
if (endpoint == "") {
return error("Mistral endpoint is required");
} else {
self.mistralClient = check new (endpoint);
}
}
if cohereConfig?.endpoint != () {
string endpoint = cohereConfig?.endpoint ?: "";
if (endpoint == "") {
return error("Cohere endpoint is required");
} else {
self.cohereClient = check new (endpoint);
}
}
logEvent("INFO", "HTTP:init", "AI Gateway initialization complete", {
"providers": [
openAIConfig != () ? "openai" : "",
anthropicConfig != () ? "anthropic" : "",
geminiConfig != () ? "gemini" : "",
ollamaConfig != () ? "ollama" : "",
mistralConfig != () ? "mistral" : "",
cohereConfig != () ? "cohere" : ""
].filter(p => p != "")
});
}
resource function post v1/chat/completions(
@http:Header {name: "x-llm-provider"} string llmProvider,
@http:Payload llms:LLMRequest payload,
http:Request request,