-
Notifications
You must be signed in to change notification settings - Fork 986
feat: add Mistral provider and enhance ToolChoice handling #83
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,180 @@ | ||
| // Package providers implements various LLM providers and their utility functions. | ||
| // This file contains the Mistral provider implementation. | ||
| package providers | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "strings" | ||
| "sync" | ||
| "time" | ||
|
|
||
| "github.com/goccy/go-json" | ||
|
|
||
| schemas "github.com/maximhq/bifrost/core/schemas" | ||
| "github.com/valyala/fasthttp" | ||
| ) | ||
|
|
||
| // MistralResponse represents the response structure from the Mistral API. | ||
| type MistralResponse struct { | ||
| ID string `json:"id"` | ||
| Object string `json:"object"` | ||
| Choices []schemas.BifrostResponseChoice `json:"choices"` | ||
| Model string `json:"model"` | ||
| Created int `json:"created"` | ||
| Usage schemas.LLMUsage `json:"usage"` | ||
| } | ||
|
|
||
| // mistralResponsePool provides a pool for Mistral response objects. | ||
| var mistralResponsePool = sync.Pool{ | ||
| New: func() interface{} { | ||
| return &MistralResponse{} | ||
| }, | ||
| } | ||
|
|
||
| // acquireMistralResponse gets a Mistral response from the pool and resets it. | ||
| func acquireMistralResponse() *MistralResponse { | ||
| resp := mistralResponsePool.Get().(*MistralResponse) | ||
| *resp = MistralResponse{} // Reset the struct | ||
| return resp | ||
| } | ||
|
|
||
| // releaseMistralResponse returns a Mistral response to the pool. | ||
| func releaseMistralResponse(resp *MistralResponse) { | ||
| if resp != nil { | ||
| mistralResponsePool.Put(resp) | ||
| } | ||
| } | ||
|
|
||
| // MistralProvider implements the Provider interface for Mistral's API. | ||
| type MistralProvider struct { | ||
| logger schemas.Logger // Logger for provider operations | ||
| client *fasthttp.Client // HTTP client for API requests | ||
| baseURL string // Base URL for the provider | ||
| } | ||
|
|
||
| // NewMistralProvider creates a new Mistral provider instance. | ||
| // It initializes the HTTP client with the provided configuration and sets up response pools. | ||
| // The client is configured with timeouts, concurrency limits, and optional proxy settings. | ||
| func NewMistralProvider(config *schemas.ProviderConfig, logger schemas.Logger) *MistralProvider { | ||
| config.CheckAndSetDefaults() | ||
|
|
||
| client := &fasthttp.Client{ | ||
| ReadTimeout: time.Second * time.Duration(config.NetworkConfig.DefaultRequestTimeoutInSeconds), | ||
| WriteTimeout: time.Second * time.Duration(config.NetworkConfig.DefaultRequestTimeoutInSeconds), | ||
| MaxConnsPerHost: config.ConcurrencyAndBufferSize.Concurrency, | ||
| } | ||
|
|
||
| // Pre-warm response pools | ||
| for range config.ConcurrencyAndBufferSize.Concurrency { | ||
| mistralResponsePool.Put(&MistralResponse{}) | ||
| bifrostResponsePool.Put(&schemas.BifrostResponse{}) | ||
| } | ||
|
Pratham-Mishra04 marked this conversation as resolved.
|
||
|
|
||
| // Configure proxy if provided | ||
| client = configureProxy(client, config.ProxyConfig, logger) | ||
|
|
||
| baseURL := strings.TrimRight(config.NetworkConfig.BaseURL, "/") | ||
| if baseURL == "" { | ||
| baseURL = "https://api.mistral.ai" | ||
| } | ||
|
|
||
| return &MistralProvider{ | ||
| logger: logger, | ||
| client: client, | ||
| baseURL: baseURL, | ||
| } | ||
| } | ||
|
|
||
| // GetProviderKey returns the provider identifier for Mistral. | ||
| func (provider *MistralProvider) GetProviderKey() schemas.ModelProvider { | ||
| return schemas.Mistral | ||
| } | ||
|
|
||
| // TextCompletion is not supported by the Mistral provider. | ||
| func (provider *MistralProvider) TextCompletion(ctx context.Context, model, key, text string, params *schemas.ModelParameters) (*schemas.BifrostResponse, *schemas.BifrostError) { | ||
| return nil, &schemas.BifrostError{ | ||
| IsBifrostError: false, | ||
| Error: schemas.ErrorField{ | ||
| Message: "text completion is not supported by mistral provider", | ||
| }, | ||
| } | ||
|
Pratham-Mishra04 marked this conversation as resolved.
|
||
| } | ||
|
|
||
| // ChatCompletion performs a chat completion request to the Mistral API. | ||
| func (provider *MistralProvider) ChatCompletion(ctx context.Context, model, key string, messages []schemas.BifrostMessage, params *schemas.ModelParameters) (*schemas.BifrostResponse, *schemas.BifrostError) { | ||
| formattedMessages, preparedParams := prepareOpenAIChatRequest(messages, params) | ||
|
|
||
| requestBody := mergeConfig(map[string]interface{}{ | ||
| "model": model, | ||
| "messages": formattedMessages, | ||
| }, preparedParams) | ||
|
|
||
| jsonBody, err := json.Marshal(requestBody) | ||
| if err != nil { | ||
| return nil, &schemas.BifrostError{ | ||
| IsBifrostError: true, | ||
| Error: schemas.ErrorField{ | ||
| Message: schemas.ErrProviderJSONMarshaling, | ||
| Error: err, | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| // Create request | ||
| req := fasthttp.AcquireRequest() | ||
| resp := fasthttp.AcquireResponse() | ||
| defer fasthttp.ReleaseRequest(req) | ||
| defer fasthttp.ReleaseResponse(resp) | ||
|
|
||
| req.SetRequestURI(provider.baseURL + "/v1/chat/completions") | ||
| req.Header.SetMethod("POST") | ||
| req.Header.SetContentType("application/json") | ||
| req.Header.Set("Authorization", "Bearer "+key) | ||
| req.SetBody(jsonBody) | ||
|
|
||
| // Make request | ||
| bifrostErr := makeRequestWithContext(ctx, provider.client, req, resp) | ||
| if bifrostErr != nil { | ||
| return nil, bifrostErr | ||
| } | ||
|
|
||
| // Handle error response | ||
| if resp.StatusCode() != fasthttp.StatusOK { | ||
| provider.logger.Debug(fmt.Sprintf("error from mistral provider: %s", string(resp.Body()))) | ||
|
|
||
| var errorResp map[string]interface{} | ||
| bifrostErr := handleProviderAPIError(resp, &errorResp) | ||
| bifrostErr.Error.Message = fmt.Sprintf("Mistral error: %v", errorResp) | ||
| return nil, bifrostErr | ||
| } | ||
|
|
||
| responseBody := resp.Body() | ||
|
|
||
| // Pre-allocate response structs from pools | ||
| response := acquireMistralResponse() | ||
| defer releaseMistralResponse(response) | ||
|
|
||
| result := acquireBifrostResponse() | ||
| defer releaseBifrostResponse(result) | ||
|
|
||
|
Pratham-Mishra04 marked this conversation as resolved.
|
||
| // Use enhanced response handler with pre-allocated response | ||
| rawResponse, bifrostErr := handleProviderResponse(responseBody, response) | ||
| if bifrostErr != nil { | ||
| return nil, bifrostErr | ||
| } | ||
|
|
||
| // Populate result from response | ||
| result.ID = response.ID | ||
| result.Choices = response.Choices | ||
| result.Object = response.Object | ||
|
Pratham-Mishra04 marked this conversation as resolved.
|
||
| result.Usage = response.Usage | ||
| result.Model = response.Model | ||
| result.Created = response.Created | ||
| result.ExtraFields = schemas.BifrostResponseExtraFields{ | ||
| Provider: schemas.Mistral, | ||
| RawResponse: rawResponse, | ||
| } | ||
|
|
||
| return result, nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.