-
Notifications
You must be signed in to change notification settings - Fork 1k
feat: add Ollama provider support #84
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,182 @@ | ||
| // Package providers implements various LLM providers and their utility functions. | ||
| // This file contains the Ollama 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" | ||
| ) | ||
|
|
||
| // OllamaResponse represents the response structure from the Ollama API. | ||
| type OllamaResponse 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"` | ||
| } | ||
|
|
||
| // ollamaResponsePool provides a pool for Ollama response objects. | ||
| var ollamaResponsePool = sync.Pool{ | ||
| New: func() interface{} { | ||
| return &OllamaResponse{} | ||
| }, | ||
| } | ||
|
|
||
| // acquireOllamaResponse gets a Ollama response from the pool and resets it. | ||
| func acquireOllamaResponse() *OllamaResponse { | ||
| resp := ollamaResponsePool.Get().(*OllamaResponse) | ||
| *resp = OllamaResponse{} // Reset the struct | ||
| return resp | ||
| } | ||
|
|
||
| // releaseOllamaResponse returns a Ollama response to the pool. | ||
| func releaseOllamaResponse(resp *OllamaResponse) { | ||
| if resp != nil { | ||
| ollamaResponsePool.Put(resp) | ||
| } | ||
| } | ||
|
|
||
| // OllamaProvider implements the Provider interface for Ollama's API. | ||
| type OllamaProvider struct { | ||
| logger schemas.Logger // Logger for provider operations | ||
| client *fasthttp.Client // HTTP client for API requests | ||
| baseURL string // Base URL for the provider | ||
| } | ||
|
|
||
| // NewOllamaProvider creates a new Ollama 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 NewOllamaProvider(config *schemas.ProviderConfig, logger schemas.Logger) (*OllamaProvider, error) { | ||
| config.CheckAndSetDefaults() | ||
|
|
||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| client := &fasthttp.Client{ | ||
| ReadTimeout: time.Second * time.Duration(config.NetworkConfig.DefaultRequestTimeoutInSeconds), | ||
| WriteTimeout: time.Second * time.Duration(config.NetworkConfig.DefaultRequestTimeoutInSeconds), | ||
| MaxConnsPerHost: config.ConcurrencyAndBufferSize.BufferSize, | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| // Pre-warm response pools | ||
| for range config.ConcurrencyAndBufferSize.Concurrency { | ||
| ollamaResponsePool.Put(&OllamaResponse{}) | ||
| bifrostResponsePool.Put(&schemas.BifrostResponse{}) | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| // Configure proxy if provided | ||
| client = configureProxy(client, config.ProxyConfig, logger) | ||
|
|
||
| baseURL := strings.TrimRight(config.NetworkConfig.BaseURL, "/") | ||
| if baseURL == "" { | ||
| return nil, fmt.Errorf("base_url is required for ollama provider") | ||
| } | ||
|
|
||
| return &OllamaProvider{ | ||
| logger: logger, | ||
| client: client, | ||
| baseURL: baseURL, | ||
| }, nil | ||
| } | ||
|
|
||
| // GetProviderKey returns the provider identifier for Ollama. | ||
| func (provider *OllamaProvider) GetProviderKey() schemas.ModelProvider { | ||
| return schemas.Ollama | ||
| } | ||
|
|
||
| // TextCompletion is not supported by the Ollama provider. | ||
| func (provider *OllamaProvider) 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 ollama provider", | ||
| }, | ||
| } | ||
| } | ||
|
Pratham-Mishra04 marked this conversation as resolved.
|
||
|
|
||
| // ChatCompletion performs a chat completion request to the Ollama API. | ||
| func (provider *OllamaProvider) 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") | ||
| if key != "" { | ||
| 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 ollama provider: %s", string(resp.Body()))) | ||
|
|
||
| var errorResp map[string]interface{} | ||
| bifrostErr := handleProviderAPIError(resp, &errorResp) | ||
| bifrostErr.Error.Message = fmt.Sprintf("Ollama error: %v", errorResp) | ||
| return nil, bifrostErr | ||
| } | ||
|
|
||
| responseBody := resp.Body() | ||
|
|
||
| // Pre-allocate response structs from pools | ||
| response := acquireOllamaResponse() | ||
| defer releaseOllamaResponse(response) | ||
|
|
||
| result := acquireBifrostResponse() | ||
| defer releaseBifrostResponse(result) | ||
|
|
||
|
coderabbitai[bot] 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 | ||
| result.Usage = response.Usage | ||
| result.Model = response.Model | ||
| result.Created = response.Created | ||
| result.ExtraFields = schemas.BifrostResponseExtraFields{ | ||
| Provider: schemas.Ollama, | ||
| 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
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,30 @@ | ||
| // Package tests provides test utilities and configurations for the Bifrost system. | ||
| // It includes test implementations of schemas, mock objects, and helper functions | ||
| // for testing the Bifrost functionality with various AI providers. | ||
| package tests | ||
|
|
||
| import ( | ||
| "testing" | ||
|
|
||
| schemas "github.com/maximhq/bifrost/core/schemas" | ||
| ) | ||
|
|
||
| func TestOllama(t *testing.T) { | ||
| bifrost, err := getBifrost() | ||
| if err != nil { | ||
| t.Fatalf("Error initializing bifrost: %v", err) | ||
| return | ||
| } | ||
|
Pratham-Mishra04 marked this conversation as resolved.
|
||
|
|
||
| config := TestConfig{ | ||
| Provider: schemas.Ollama, | ||
| TextModel: "llama3.2", | ||
| ChatModel: "llama3.2", | ||
| SetupText: false, // Ollama does not support text completion | ||
| SetupToolCalls: true, | ||
| SetupImage: true, | ||
| SetupBaseImage: true, | ||
| } | ||
|
|
||
| SetupAllRequests(bifrost, config) | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
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.