-
Notifications
You must be signed in to change notification settings - Fork 943
Expand file tree
/
Copy pathbifrost.go
More file actions
2910 lines (2603 loc) · 98.4 KB
/
Copy pathbifrost.go
File metadata and controls
2910 lines (2603 loc) · 98.4 KB
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
// Package bifrost provides the core implementation of the Bifrost system.
// Bifrost is a unified interface for interacting with various AI model providers,
// managing concurrent requests, and handling provider-specific configurations.
package bifrost
import (
"context"
"fmt"
"math/rand"
"slices"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/google/uuid"
"github.com/maximhq/bifrost/core/providers/anthropic"
"github.com/maximhq/bifrost/core/providers/azure"
"github.com/maximhq/bifrost/core/providers/bedrock"
"github.com/maximhq/bifrost/core/providers/cerebras"
"github.com/maximhq/bifrost/core/providers/cohere"
"github.com/maximhq/bifrost/core/providers/elevenlabs"
"github.com/maximhq/bifrost/core/providers/gemini"
"github.com/maximhq/bifrost/core/providers/groq"
"github.com/maximhq/bifrost/core/providers/mistral"
"github.com/maximhq/bifrost/core/providers/ollama"
"github.com/maximhq/bifrost/core/providers/openai"
"github.com/maximhq/bifrost/core/providers/openrouter"
"github.com/maximhq/bifrost/core/providers/parasail"
"github.com/maximhq/bifrost/core/providers/perplexity"
"github.com/maximhq/bifrost/core/providers/sgl"
providerUtils "github.com/maximhq/bifrost/core/providers/utils"
"github.com/maximhq/bifrost/core/providers/vertex"
schemas "github.com/maximhq/bifrost/core/schemas"
)
// ChannelMessage represents a message passed through the request channel.
// It contains the request, response and error channels, and the request type.
type ChannelMessage struct {
schemas.BifrostRequest
Context context.Context
Response chan *schemas.BifrostResponse
ResponseStream chan chan *schemas.BifrostStream
Err chan schemas.BifrostError
}
// Bifrost manages providers and maintains specified open channels for concurrent processing.
// It handles request routing, provider management, and response processing.
type Bifrost struct {
ctx context.Context
cancel context.CancelFunc
account schemas.Account // account interface
plugins atomic.Pointer[[]schemas.Plugin] // list of plugins
providers atomic.Pointer[[]schemas.Provider] // list of providers
requestQueues sync.Map // provider request queues (thread-safe)
waitGroups sync.Map // wait groups for each provider (thread-safe)
providerMutexes sync.Map // mutexes for each provider to prevent concurrent updates (thread-safe)
channelMessagePool sync.Pool // Pool for ChannelMessage objects, initial pool size is set in Init
responseChannelPool sync.Pool // Pool for response channels, initial pool size is set in Init
errorChannelPool sync.Pool // Pool for error channels, initial pool size is set in Init
responseStreamPool sync.Pool // Pool for response stream channels, initial pool size is set in Init
pluginPipelinePool sync.Pool // Pool for PluginPipeline objects
bifrostRequestPool sync.Pool // Pool for BifrostRequest objects
logger schemas.Logger // logger instance, default logger is used if not provided
mcpManager *MCPManager // MCP integration manager (nil if MCP not configured)
dropExcessRequests atomic.Bool // If true, in cases where the queue is full, requests will not wait for the queue to be empty and will be dropped instead.
keySelector schemas.KeySelector // Custom key selector function
}
// PluginPipeline encapsulates the execution of plugin PreHooks and PostHooks, tracks how many plugins ran, and manages short-circuiting and error aggregation.
type PluginPipeline struct {
plugins []schemas.Plugin
logger schemas.Logger
// Number of PreHooks that were executed (used to determine which PostHooks to run in reverse order)
executedPreHooks int
// Errors from PreHooks and PostHooks
preHookErrors []error
postHookErrors []error
}
// Global logger instance which is set in the Init function
var logger schemas.Logger
// INITIALIZATION
// Init initializes a new Bifrost instance with the given configuration.
// It sets up the account, plugins, object pools, and initializes providers.
// Returns an error if initialization fails.
// Initial Memory Allocations happens here as per the initial pool size.
func Init(ctx context.Context, config schemas.BifrostConfig) (*Bifrost, error) {
if config.Account == nil {
return nil, fmt.Errorf("account is required to initialize Bifrost")
}
if config.Logger == nil {
config.Logger = NewDefaultLogger(schemas.LogLevelInfo)
}
providerUtils.SetLogger(config.Logger)
bifrostCtx, cancel := context.WithCancel(ctx)
bifrost := &Bifrost{
ctx: bifrostCtx,
cancel: cancel,
account: config.Account,
plugins: atomic.Pointer[[]schemas.Plugin]{},
requestQueues: sync.Map{},
waitGroups: sync.Map{},
keySelector: config.KeySelector,
logger: config.Logger,
}
bifrost.plugins.Store(&config.Plugins)
// Initialize providers slice
bifrost.providers.Store(&[]schemas.Provider{})
bifrost.dropExcessRequests.Store(config.DropExcessRequests)
if bifrost.keySelector == nil {
bifrost.keySelector = WeightedRandomKeySelector
}
// Initialize object pools
bifrost.channelMessagePool = sync.Pool{
New: func() interface{} {
return &ChannelMessage{}
},
}
bifrost.responseChannelPool = sync.Pool{
New: func() interface{} {
return make(chan *schemas.BifrostResponse, 1)
},
}
bifrost.errorChannelPool = sync.Pool{
New: func() interface{} {
return make(chan schemas.BifrostError, 1)
},
}
bifrost.responseStreamPool = sync.Pool{
New: func() interface{} {
return make(chan chan *schemas.BifrostStream, 1)
},
}
bifrost.pluginPipelinePool = sync.Pool{
New: func() interface{} {
return &PluginPipeline{
preHookErrors: make([]error, 0),
postHookErrors: make([]error, 0),
}
},
}
bifrost.bifrostRequestPool = sync.Pool{
New: func() interface{} {
return &schemas.BifrostRequest{}
},
}
// Prewarm pools with multiple objects
for range config.InitialPoolSize {
// Create and put new objects directly into pools
bifrost.channelMessagePool.Put(&ChannelMessage{})
bifrost.responseChannelPool.Put(make(chan *schemas.BifrostResponse, 1))
bifrost.errorChannelPool.Put(make(chan schemas.BifrostError, 1))
bifrost.responseStreamPool.Put(make(chan chan *schemas.BifrostStream, 1))
bifrost.pluginPipelinePool.Put(&PluginPipeline{
preHookErrors: make([]error, 0),
postHookErrors: make([]error, 0),
})
bifrost.bifrostRequestPool.Put(&schemas.BifrostRequest{})
}
providerKeys, err := bifrost.account.GetConfiguredProviders()
if err != nil {
return nil, err
}
// Initialize MCP manager if configured
if config.MCPConfig != nil {
mcpManager, err := newMCPManager(bifrostCtx, *config.MCPConfig, bifrost.logger)
if err != nil {
bifrost.logger.Warn(fmt.Sprintf("failed to initialize MCP manager: %v", err))
} else {
bifrost.mcpManager = mcpManager
bifrost.logger.Info("MCP integration initialized successfully")
}
}
// Create buffered channels for each provider and start workers
for _, providerKey := range providerKeys {
if strings.TrimSpace(string(providerKey)) == "" {
bifrost.logger.Warn("provider key is empty, skipping init")
continue
}
config, err := bifrost.account.GetConfigForProvider(providerKey)
if err != nil {
bifrost.logger.Warn(fmt.Sprintf("failed to get config for provider, skipping init: %v", err))
continue
}
if config == nil {
bifrost.logger.Warn(fmt.Sprintf("config is nil for provider %s, skipping init", providerKey))
continue
}
// Lock the provider mutex during initialization
providerMutex := bifrost.getProviderMutex(providerKey)
providerMutex.Lock()
err = bifrost.prepareProvider(providerKey, config)
providerMutex.Unlock()
if err != nil {
bifrost.logger.Warn(fmt.Sprintf("failed to prepare provider %s: %v", providerKey, err))
}
}
// Set logger
logger = bifrost.logger
return bifrost, nil
}
// ReloadConfig reloads the config from DB
// Currently we only update account and drop excess requests
// We will keep on adding other aspects as required
func (bifrost *Bifrost) ReloadConfig(config schemas.BifrostConfig) error {
bifrost.dropExcessRequests.Store(config.DropExcessRequests)
return nil
}
// PUBLIC API METHODS
// ListModelsRequest sends a list models request to the specified provider.
func (bifrost *Bifrost) ListModelsRequest(ctx context.Context, req *schemas.BifrostListModelsRequest) (*schemas.BifrostListModelsResponse, *schemas.BifrostError) {
if req == nil {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "list models request is nil",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.ListModelsRequest,
},
}
}
if req.Provider == "" {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "provider is required for list models request",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.ListModelsRequest,
},
}
}
if ctx == nil {
ctx = bifrost.ctx
}
// Preparing request
request := &schemas.BifrostListModelsRequest{
Provider: req.Provider,
PageSize: req.PageSize,
PageToken: req.PageToken,
ExtraParams: req.ExtraParams,
}
// Getting provider from the memory
provider := bifrost.getProviderByKey(req.Provider)
if provider == nil {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "provider not found for list models request",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.ListModelsRequest,
Provider: req.Provider,
},
}
}
// Determine the base provider type for key requirement checks
baseProvider := req.Provider
config, err := bifrost.account.GetConfigForProvider(req.Provider)
if err != nil {
bifrostErr := newBifrostErrorFromMsg(fmt.Sprintf("failed to get config for provider %s: %v", req.Provider, err.Error()))
bifrostErr.ExtraFields = schemas.BifrostErrorExtraFields{
RequestType: schemas.ListModelsRequest,
Provider: req.Provider,
}
return nil, bifrostErr
}
if config == nil {
bifrostErr := newBifrostErrorFromMsg(fmt.Sprintf("config is nil for provider %s", req.Provider))
bifrostErr.ExtraFields = schemas.BifrostErrorExtraFields{
RequestType: schemas.ListModelsRequest,
Provider: req.Provider,
}
return nil, bifrostErr
}
if config.CustomProviderConfig != nil && config.CustomProviderConfig.BaseProviderType != "" {
baseProvider = config.CustomProviderConfig.BaseProviderType
}
var keys []schemas.Key
if providerRequiresKey(baseProvider, config.CustomProviderConfig) {
keys, err = bifrost.getAllSupportedKeys(&ctx, req.Provider, baseProvider)
if err != nil {
bifrostErr := newBifrostError(err)
bifrostErr.ExtraFields = schemas.BifrostErrorExtraFields{
RequestType: schemas.ListModelsRequest,
Provider: req.Provider,
}
return nil, bifrostErr
}
}
response, bifrostErr := executeRequestWithRetries(&ctx, config, func() (*schemas.BifrostListModelsResponse, *schemas.BifrostError) {
return provider.ListModels(ctx, keys, request)
}, schemas.ListModelsRequest, req.Provider, "")
if bifrostErr != nil {
bifrostErr.ExtraFields = schemas.BifrostErrorExtraFields{
RequestType: schemas.ListModelsRequest,
Provider: req.Provider,
}
return nil, bifrostErr
}
return response, nil
}
// ListAllModels lists all models from all configured providers.
// It accumulates responses from all providers with a limit of 1000 per provider to get all results.
func (bifrost *Bifrost) ListAllModels(ctx context.Context, request *schemas.BifrostListModelsRequest) (*schemas.BifrostListModelsResponse, *schemas.BifrostError) {
if request == nil {
request = &schemas.BifrostListModelsRequest{}
}
providerKeys, err := bifrost.GetConfiguredProviders()
if err != nil {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: err.Error(),
Error: err,
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.ListModelsRequest,
},
}
}
startTime := time.Now()
// Result structure for collecting provider responses
type providerResult struct {
models []schemas.Model
err *schemas.BifrostError
}
results := make(chan providerResult, len(providerKeys))
var wg sync.WaitGroup
// Launch concurrent requests for all providers
for _, providerKey := range providerKeys {
if strings.TrimSpace(string(providerKey)) == "" {
continue
}
wg.Add(1)
go func(providerKey schemas.ModelProvider) {
defer wg.Done()
providerModels := make([]schemas.Model, 0)
var providerErr *schemas.BifrostError
// Create request for this provider with limit of 1000
providerRequest := &schemas.BifrostListModelsRequest{
Provider: providerKey,
PageSize: schemas.DefaultPageSize,
}
iterations := 0
for {
// check for context cancellation
select {
case <-ctx.Done():
bifrost.logger.Warn(fmt.Sprintf("context cancelled for provider %s", providerKey))
return
default:
}
iterations++
if iterations > schemas.MaxPaginationRequests {
bifrost.logger.Warn(fmt.Sprintf("reached maximum pagination requests (%d) for provider %s, please increase the page size", schemas.MaxPaginationRequests, providerKey))
break
}
response, bifrostErr := bifrost.ListModelsRequest(ctx, providerRequest)
if bifrostErr != nil {
// Skip logging "no keys found" and "not supported" errors as they are expected when a provider is not configured
if !strings.Contains(bifrostErr.Error.Message, "no keys found") &&
!strings.Contains(bifrostErr.Error.Message, "not supported") {
providerErr = bifrostErr
bifrost.logger.Warn(fmt.Sprintf("failed to list models for provider %s: %s", providerKey, GetErrorMessage(bifrostErr)))
}
break
}
if response == nil || len(response.Data) == 0 {
break
}
providerModels = append(providerModels, response.Data...)
// Check if there are more pages
if response.NextPageToken == "" {
break
}
// Set the page token for the next request
providerRequest.PageToken = response.NextPageToken
}
results <- providerResult{models: providerModels, err: providerErr}
}(providerKey)
}
// Wait for all goroutines to complete
wg.Wait()
close(results)
// Accumulate all models from all providers
allModels := make([]schemas.Model, 0)
var firstError *schemas.BifrostError
for result := range results {
if len(result.models) > 0 {
allModels = append(allModels, result.models...)
}
if result.err != nil && firstError == nil {
firstError = result.err
}
}
// If we couldn't get any models from any provider, return the first error
if len(allModels) == 0 && firstError != nil {
return nil, firstError
}
// Sort models alphabetically by ID
sort.Slice(allModels, func(i, j int) bool {
return allModels[i].ID < allModels[j].ID
})
// Return aggregated response with accumulated latency
response := &schemas.BifrostListModelsResponse{
Data: allModels,
ExtraFields: schemas.BifrostResponseExtraFields{
RequestType: schemas.ListModelsRequest,
Latency: time.Since(startTime).Milliseconds(),
},
}
response = response.ApplyPagination(request.PageSize, request.PageToken)
return response, nil
}
// TextCompletionRequest sends a text completion request to the specified provider.
func (bifrost *Bifrost) TextCompletionRequest(ctx context.Context, req *schemas.BifrostTextCompletionRequest) (*schemas.BifrostTextCompletionResponse, *schemas.BifrostError) {
if req == nil {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "text completion request is nil",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.TextCompletionRequest,
},
}
}
if req.Input == nil || (req.Input.PromptStr == nil && req.Input.PromptArray == nil) {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "prompt not provided for text completion request",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.TextCompletionRequest,
Provider: req.Provider,
ModelRequested: req.Model,
},
}
}
// Preparing request
bifrostReq := bifrost.getBifrostRequest()
bifrostReq.RequestType = schemas.TextCompletionRequest
bifrostReq.TextCompletionRequest = req
response, err := bifrost.handleRequest(ctx, bifrostReq)
if err != nil {
return nil, err
}
//TODO: Release the response
return response.TextCompletionResponse, nil
}
// TextCompletionStreamRequest sends a streaming text completion request to the specified provider.
func (bifrost *Bifrost) TextCompletionStreamRequest(ctx context.Context, req *schemas.BifrostTextCompletionRequest) (chan *schemas.BifrostStream, *schemas.BifrostError) {
if req == nil {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "text completion stream request is nil",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.TextCompletionStreamRequest,
},
}
}
if req.Input == nil || (req.Input.PromptStr == nil && req.Input.PromptArray == nil) {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "text not provided for text completion stream request",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.TextCompletionStreamRequest,
Provider: req.Provider,
ModelRequested: req.Model,
},
}
}
bifrostReq := bifrost.getBifrostRequest()
bifrostReq.RequestType = schemas.TextCompletionStreamRequest
bifrostReq.TextCompletionRequest = req
return bifrost.handleStreamRequest(ctx, bifrostReq)
}
// ChatCompletionRequest sends a chat completion request to the specified provider.
func (bifrost *Bifrost) ChatCompletionRequest(ctx context.Context, req *schemas.BifrostChatRequest) (*schemas.BifrostChatResponse, *schemas.BifrostError) {
if req == nil {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "chat completion request is nil",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.ChatCompletionRequest,
},
}
}
if req.Input == nil {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "chats not provided for chat completion request",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.ChatCompletionRequest,
Provider: req.Provider,
ModelRequested: req.Model,
},
}
}
bifrostReq := bifrost.getBifrostRequest()
bifrostReq.RequestType = schemas.ChatCompletionRequest
bifrostReq.ChatRequest = req
response, err := bifrost.handleRequest(ctx, bifrostReq)
if err != nil {
return nil, err
}
//TODO: Release the response
return response.ChatResponse, nil
}
// ChatCompletionStreamRequest sends a chat completion stream request to the specified provider.
func (bifrost *Bifrost) ChatCompletionStreamRequest(ctx context.Context, req *schemas.BifrostChatRequest) (chan *schemas.BifrostStream, *schemas.BifrostError) {
if req == nil {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "chat completion stream request is nil",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.ChatCompletionStreamRequest,
},
}
}
if req.Input == nil {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "chats not provided for chat completion request",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.ChatCompletionStreamRequest,
Provider: req.Provider,
ModelRequested: req.Model,
},
}
}
bifrostReq := bifrost.getBifrostRequest()
bifrostReq.RequestType = schemas.ChatCompletionStreamRequest
bifrostReq.ChatRequest = req
return bifrost.handleStreamRequest(ctx, bifrostReq)
}
// ResponsesRequest sends a responses request to the specified provider.
func (bifrost *Bifrost) ResponsesRequest(ctx context.Context, req *schemas.BifrostResponsesRequest) (*schemas.BifrostResponsesResponse, *schemas.BifrostError) {
if req == nil {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "responses request is nil",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.ResponsesRequest,
},
}
}
if req.Input == nil {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "responses not provided for responses request",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.ResponsesRequest,
Provider: req.Provider,
ModelRequested: req.Model,
},
}
}
bifrostReq := bifrost.getBifrostRequest()
bifrostReq.RequestType = schemas.ResponsesRequest
bifrostReq.ResponsesRequest = req
response, err := bifrost.handleRequest(ctx, bifrostReq)
if err != nil {
return nil, err
}
//TODO: Release the response
return response.ResponsesResponse, nil
}
// ResponsesStreamRequest sends a responses stream request to the specified provider.
func (bifrost *Bifrost) ResponsesStreamRequest(ctx context.Context, req *schemas.BifrostResponsesRequest) (chan *schemas.BifrostStream, *schemas.BifrostError) {
if req == nil {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "responses stream request is nil",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.ResponsesStreamRequest,
},
}
}
if req.Input == nil {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "responses not provided for responses stream request",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.ResponsesStreamRequest,
Provider: req.Provider,
ModelRequested: req.Model,
},
}
}
bifrostReq := bifrost.getBifrostRequest()
bifrostReq.RequestType = schemas.ResponsesStreamRequest
bifrostReq.ResponsesRequest = req
return bifrost.handleStreamRequest(ctx, bifrostReq)
}
// EmbeddingRequest sends an embedding request to the specified provider.
func (bifrost *Bifrost) EmbeddingRequest(ctx context.Context, req *schemas.BifrostEmbeddingRequest) (*schemas.BifrostEmbeddingResponse, *schemas.BifrostError) {
if req == nil {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "embedding request is nil",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.EmbeddingRequest,
},
}
}
if req.Input == nil || (req.Input.Text == nil && req.Input.Texts == nil && req.Input.Embedding == nil && req.Input.Embeddings == nil) {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "embedding input not provided for embedding request",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.EmbeddingRequest,
Provider: req.Provider,
ModelRequested: req.Model,
},
}
}
bifrostReq := bifrost.getBifrostRequest()
bifrostReq.RequestType = schemas.EmbeddingRequest
bifrostReq.EmbeddingRequest = req
response, err := bifrost.handleRequest(ctx, bifrostReq)
if err != nil {
return nil, err
}
//TODO: Release the response
return response.EmbeddingResponse, nil
}
// SpeechRequest sends a speech request to the specified provider.
func (bifrost *Bifrost) SpeechRequest(ctx context.Context, req *schemas.BifrostSpeechRequest) (*schemas.BifrostSpeechResponse, *schemas.BifrostError) {
if req == nil {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "speech request is nil",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.SpeechRequest,
},
}
}
if req.Input == nil || req.Input.Input == "" {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "speech input not provided for speech request",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.SpeechRequest,
Provider: req.Provider,
ModelRequested: req.Model,
},
}
}
bifrostReq := bifrost.getBifrostRequest()
bifrostReq.RequestType = schemas.SpeechRequest
bifrostReq.SpeechRequest = req
response, err := bifrost.handleRequest(ctx, bifrostReq)
if err != nil {
return nil, err
}
//TODO: Release the response
return response.SpeechResponse, nil
}
// SpeechStreamRequest sends a speech stream request to the specified provider.
func (bifrost *Bifrost) SpeechStreamRequest(ctx context.Context, req *schemas.BifrostSpeechRequest) (chan *schemas.BifrostStream, *schemas.BifrostError) {
if req == nil {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "speech stream request is nil",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.SpeechStreamRequest,
},
}
}
if req.Input == nil || req.Input.Input == "" {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "speech input not provided for speech stream request",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.SpeechStreamRequest,
Provider: req.Provider,
ModelRequested: req.Model,
},
}
}
bifrostReq := bifrost.getBifrostRequest()
bifrostReq.RequestType = schemas.SpeechStreamRequest
bifrostReq.SpeechRequest = req
return bifrost.handleStreamRequest(ctx, bifrostReq)
}
// TranscriptionRequest sends a transcription request to the specified provider.
func (bifrost *Bifrost) TranscriptionRequest(ctx context.Context, req *schemas.BifrostTranscriptionRequest) (*schemas.BifrostTranscriptionResponse, *schemas.BifrostError) {
if req == nil {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "transcription request is nil",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.TranscriptionRequest,
},
}
}
if req.Input == nil || req.Input.File == nil {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "transcription input not provided for transcription request",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.TranscriptionRequest,
Provider: req.Provider,
ModelRequested: req.Model,
},
}
}
bifrostReq := bifrost.getBifrostRequest()
bifrostReq.RequestType = schemas.TranscriptionRequest
bifrostReq.TranscriptionRequest = req
response, err := bifrost.handleRequest(ctx, bifrostReq)
if err != nil {
return nil, err
}
//TODO: Release the response
return response.TranscriptionResponse, nil
}
// TranscriptionStreamRequest sends a transcription stream request to the specified provider.
func (bifrost *Bifrost) TranscriptionStreamRequest(ctx context.Context, req *schemas.BifrostTranscriptionRequest) (chan *schemas.BifrostStream, *schemas.BifrostError) {
if req == nil {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "transcription stream request is nil",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.TranscriptionStreamRequest,
},
}
}
if req.Input == nil || req.Input.File == nil {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "transcription input not provided for transcription stream request",
},
ExtraFields: schemas.BifrostErrorExtraFields{
RequestType: schemas.TranscriptionStreamRequest,
Provider: req.Provider,
ModelRequested: req.Model,
},
}
}
bifrostReq := bifrost.getBifrostRequest()
bifrostReq.RequestType = schemas.TranscriptionStreamRequest
bifrostReq.TranscriptionRequest = req
return bifrost.handleStreamRequest(ctx, bifrostReq)
}
// ImageGenerationRequest sends a image generation request to the specified provider.
func (bifrost *Bifrost) ImageGenerationRequest(ctx context.Context,
req *schemas.BifrostImageGenerationRequest) (*schemas.BifrostImageGenerationResponse, *schemas.BifrostError) {
if req == nil {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "image generation request is nil",
},
}
}
if req.Input == nil || req.Input.Prompt == "" {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "prompt not provided for image generation request",
},
}
}
bifrostReq := bifrost.getBifrostRequest()
bifrostReq.RequestType = schemas.ImageGenerationRequest
bifrostReq.ImageGenerationRequest = req
response, err := bifrost.handleRequest(ctx, bifrostReq)
if err != nil {
return nil, err
}
if response == nil || response.ImageGenerationResponse == nil {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "received nil response from provider",
},
}
}
return response.ImageGenerationResponse, nil
}
// ImageGenerationStreamRequest sends a image generation stream request to the specified provider.
func (bifrost *Bifrost) ImageGenerationStreamRequest(ctx context.Context,
req *schemas.BifrostImageGenerationRequest) (chan *schemas.BifrostStream, *schemas.BifrostError) {
if req == nil {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "image generation stream request is nil",
},
}
}
if req.Input == nil || req.Input.Prompt == "" {
return nil, &schemas.BifrostError{
IsBifrostError: false,
Error: &schemas.ErrorField{
Message: "prompt not provided for image generation stream request",
},
}
}
bifrostReq := bifrost.getBifrostRequest()
bifrostReq.RequestType = schemas.ImageGenerationStreamRequest
bifrostReq.ImageGenerationRequest = req
return bifrost.handleStreamRequest(ctx, bifrostReq)
}
// RemovePlugin removes a plugin from the server.
func (bifrost *Bifrost) RemovePlugin(name string) error {
for {
oldPlugins := bifrost.plugins.Load()
if oldPlugins == nil {
return nil
}
var pluginToCleanup schemas.Plugin
found := false
// Create new slice with replaced plugin
newPlugins := make([]schemas.Plugin, len(*oldPlugins))
copy(newPlugins, *oldPlugins)
for i, p := range newPlugins {
if p.GetName() == name {
pluginToCleanup = p
bifrost.logger.Debug("removing plugin %s", name)
newPlugins = append(newPlugins[:i], newPlugins[i+1:]...)
found = true
break
}
}
if !found {
return nil
}
if pluginToCleanup != nil {
// Atomic compare-and-swap
if bifrost.plugins.CompareAndSwap(oldPlugins, &newPlugins) {
// Cleanup the old plugin
err := pluginToCleanup.Cleanup()
if err != nil {
bifrost.logger.Warn("failed to cleanup old plugin %s: %v", pluginToCleanup.GetName(), err)
}
return nil
}
}
// Retrying as swapping did not work
}
}
// ReloadPlugin reloads a plugin with new instance
// During the reload - it's stop the world phase where we take a global lock on the plugin mutex
func (bifrost *Bifrost) ReloadPlugin(plugin schemas.Plugin) error {
for {
var pluginToCleanup schemas.Plugin
found := false
oldPlugins := bifrost.plugins.Load()
if oldPlugins == nil {
return nil
}
// Create new slice with replaced plugin
newPlugins := make([]schemas.Plugin, len(*oldPlugins))
copy(newPlugins, *oldPlugins)
for i, p := range newPlugins {
if p.GetName() == plugin.GetName() {
// Cleaning up old plugin before replacing it
pluginToCleanup = p
bifrost.logger.Debug("replacing plugin %s with new instance", plugin.GetName())
newPlugins[i] = plugin
found = true
break
}
}
if !found {