Skip to content

Commit

Permalink
#29: lint
Browse files Browse the repository at this point in the history
  • Loading branch information
mkrueger12 committed Dec 27, 2023
1 parent 8cbe50e commit c0b6989
Show file tree
Hide file tree
Showing 5 changed files with 12 additions and 137 deletions.
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ require (
go.uber.org/goleak v1.3.0
go.uber.org/multierr v1.11.0
go.uber.org/zap v1.26.0
gopkg.in/yaml.v2 v2.4.0
)

require (
Expand Down
8 changes: 0 additions & 8 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,6 @@ github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/nyaruka/phonenumbers v1.0.55 h1:bj0nTO88Y68KeUQ/n3Lo2KgK7lM1hF7L9NFuwcCl3yg=
github.com/nyaruka/phonenumbers v1.0.55/go.mod h1:sDaTZ/KPX5f8qyV9qN+hIm+4ZBARJrupC6LuhshJq1U=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
Expand Down Expand Up @@ -104,11 +100,7 @@ google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp0
google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ=
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
Expand Down
26 changes: 12 additions & 14 deletions pkg/providers/openai/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"io"
"net/http"
"reflect"
"strconv"
"strings"

"glide/pkg/providers"
Expand All @@ -25,8 +26,8 @@ const (

// Client is a client for the OpenAI API.
type ProviderClient struct {
BaseURL string `json:"baseURL"`
HTTPClient *http.Client `json:"httpClient"`
BaseURL string `json:"baseURL"`
HTTPClient *http.Client `json:"httpClient"`
Telemetry *telemetry.Telemetry `json:"telemetry"`
}

Expand Down Expand Up @@ -95,7 +96,6 @@ type ChatResponse struct {
// - error: An error if the request failed.
func (c *ProviderClient) Chat(u *providers.UnifiedAPIData) (*ChatResponse, error) {
// Create a new chat request

c.Telemetry.Logger.Info("creating new chat request")

chatRequest := c.CreateChatRequest(u)
Expand All @@ -110,7 +110,6 @@ func (c *ProviderClient) Chat(u *providers.UnifiedAPIData) (*ChatResponse, error
}

func (c *ProviderClient) CreateChatRequest(u *providers.UnifiedAPIData) *ChatRequest {

c.Telemetry.Logger.Info("creating chatRequest from payload")

var messages []map[string]string
Expand All @@ -121,7 +120,8 @@ func (c *ProviderClient) CreateChatRequest(u *providers.UnifiedAPIData) *ChatReq
// Add msg variable last
messages = append(messages, u.Message)

// iterate throughunifiedData.Params and add them to the request otherwise leave the default value
// Iterate through unifiedData.Params and add them to the request, otherwise leave the default value
defaultParams := u.Params

chatRequest := &ChatRequest{
Model: u.Model,
Expand All @@ -142,16 +142,13 @@ func (c *ProviderClient) CreateChatRequest(u *providers.UnifiedAPIData) *ChatReq
ResponseFormat: nil,
}

// Use reflection to dynamically assign default parameter values
// TODO: refactor to avoid reflection(?)
defaultParams := u.Params

chatRequestValue := reflect.ValueOf(chatRequest).Elem()
chatRequestType := chatRequestValue.Type()

for i := 0; i < chatRequestValue.NumField(); i++ {
jsonTags := strings.Split(chatRequestType.Field(i).Tag.Get("json"), ",")
jsonTag := jsonTags[0]

if value, ok := defaultParams[jsonTag]; ok {
fieldValue := chatRequestValue.Field(i)
fieldValue.Set(reflect.ValueOf(value))
Expand All @@ -171,14 +168,15 @@ func (c *ProviderClient) CreateChatResponse(ctx context.Context, r *ChatRequest,
if err != nil {
return nil, err
}

if len(resp.Choices) == 0 {
return nil, ErrEmptyResponse
}

return resp, nil
}

func (c *ProviderClient) createChatHTTP(payload *ChatRequest, u *providers.UnifiedAPIData) (*ChatResponse, error) {

c.Telemetry.Logger.Info("running createChatHttp")

if payload.StreamingFunc != nil {
Expand All @@ -197,7 +195,7 @@ func (c *ProviderClient) createChatHTTP(payload *ChatRequest, u *providers.Unifi
}

reqBody := bytes.NewBuffer(payloadBytes)
req, err := http.NewRequest("POST", buildURL(defaultEndpoint), reqBody)
req, err := http.NewRequest(http.MethodPost, buildURL(defaultEndpoint), reqBody)
if err != nil {
c.Telemetry.Logger.Error(err.Error())
return nil, err
Expand All @@ -213,24 +211,24 @@ func (c *ProviderClient) createChatHTTP(payload *ChatRequest, u *providers.Unifi
}
defer resp.Body.Close()

c.Telemetry.Logger.Info("Response Code: ", zap.String("response_code", fmt.Sprintf("%d", resp.StatusCode)))
c.Telemetry.Logger.Info("Response Code: ", zap.String("response_code", strconv.Itoa(resp.StatusCode)))

if resp.StatusCode != http.StatusOK {

bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
c.Telemetry.Logger.Error(err.Error())
}

c.Telemetry.Logger.Warn("Response Body: ", zap.String("response_body", string(bodyBytes)))
}

// Parse response
var response ChatResponse

return &response, json.NewDecoder(resp.Body).Decode(&response)
}

func buildURL(suffix string) string {

// open ai implement:
return fmt.Sprintf("%s%s", defaultBaseURL, suffix)
}
2 changes: 0 additions & 2 deletions pkg/providers/openai/openaiclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,13 @@ var (
// - *Client: A pointer to the created client.
// - error: An error if the client creation failed.
func Client() (*ProviderClient, error) {

tel, err := telemetry.NewTelemetry(&telemetry.Config{LogConfig: telemetry.NewLogConfig()})
if err != nil {
return nil, err
}

tel.Logger.Info("init openai provider client")


// Create a new client
c := &ProviderClient{
BaseURL: defaultBaseURL,
Expand Down
112 changes: 0 additions & 112 deletions pkg/providers/types.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,8 @@
package providers

import (
"fmt"
"log/slog"
"net/http"
"os"
"path/filepath"
"time"

"gopkg.in/yaml.v2"
)

type GatewayConfig struct {
Expand Down Expand Up @@ -62,109 +56,3 @@ type UnifiedAPIData struct {
Message map[string]string `json:"message"`
MessageHistory []map[string]string `json:"messageHistory"`
}

// Helper Functions

func FindPoolByName(pools []Pool, name string) (*Pool, error) {
for i := range pools {
pool := &pools[i]
if pool.Name == name {
return pool, nil
}
}

return nil, fmt.Errorf("pool not found: %s", name)
}

// findProviderByModel find provider params in the given config file by the specified provider name and model name.
//
// Parameters:
// - providers: a slice of Provider, the list of providers to search in.
// - providerName: a string, the name of the provider to search for.
// - modelName: a string, the name of the model to search for.
//
// Returns:
// - *Provider: a pointer to the found provider.
// - error: an error indicating whether a provider was found or not.
func FindProviderByModel(providers []Provider, providerName string, modelName string) (*Provider, error) {
for i := range providers {
provider := &providers[i]
if provider.Name == providerName && provider.Model == modelName {
return provider, nil
}
}

return nil, fmt.Errorf("no provider found in config for model: %s", modelName)
}

func ReadProviderVars(filePath string) ([]ProviderVars, error) {
absPath, err := filepath.Abs(filePath)
if err != nil {
return nil, fmt.Errorf("failed to get absolute file path: %w", err)
}

// Validate that the absolute path is a file
fileInfo, err := os.Stat(absPath)
if err != nil {
return nil, fmt.Errorf("failed to get file info: %w", err)
}
if fileInfo.IsDir() {
return nil, fmt.Errorf("provided path is a directory, not a file")
}

data, err := os.ReadFile(absPath)
if err != nil {
return nil, fmt.Errorf("failed to read provider vars file: %w", err)
}

var provVars []ProviderVars
if err := yaml.Unmarshal(data, &provVars); err != nil {
return nil, fmt.Errorf("failed to unmarshal provider vars data: %w", err)
}

return provVars, nil
}

func GetDefaultBaseURL(provVars []ProviderVars, providerName string) (string, error) {
providerVarsMap := make(map[string]string)
for _, providerVar := range provVars {
providerVarsMap[providerVar.Name] = providerVar.ChatBaseURL
}

defaultBaseURL, ok := providerVarsMap[providerName]
if !ok {
return "", fmt.Errorf("default base URL not found for provider: %s", providerName)
}

return defaultBaseURL, nil
}

func ReadConfig(filePath string) (GatewayConfig, error) {
absPath, err := filepath.Abs(filePath)
if err != nil {
return GatewayConfig{}, fmt.Errorf("failed to get absolute file path: %w", err)
}

// Validate that the absolute path is a file
fileInfo, err := os.Stat(absPath)
if err != nil {
return GatewayConfig{}, fmt.Errorf("failed to get file info: %w", err)
}
if fileInfo.IsDir() {
return GatewayConfig{}, fmt.Errorf("provided path is a directory, not a file")
}

data, err := os.ReadFile(absPath)
if err != nil {
slog.Error("Error:", err)
return GatewayConfig{}, fmt.Errorf("failed to read config file: %w", err)
}

var config GatewayConfig
if err := yaml.Unmarshal(data, &config); err != nil {
slog.Error("Error:", err)
return GatewayConfig{}, fmt.Errorf("failed to unmarshal config data: %w", err)
}

return config, nil
}

0 comments on commit c0b6989

Please sign in to comment.