File size: 7,670 Bytes
8baf122 | 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 | // Package maxim provides integration for Maxim's SDK as a Bifrost plugin.
// It includes tests for plugin initialization, Bifrost integration, and request/response tracing.
package maxim
import (
"context"
"fmt"
"log"
"os"
"testing"
bifrost "github.com/maximhq/bifrost/core"
"github.com/maximhq/bifrost/core/schemas"
)
// getPlugin initializes and returns a Plugin instance for testing purposes.
// It sets up the Maxim logger with configuration from environment variables.
//
// Environment Variables:
// - MAXIM_API_KEY: API key for Maxim SDK authentication
// - MAXIM_LOG_REPO_ID: ID for the Maxim logger instance
//
// Returns:
// - schemas.LLMPlugin: A configured plugin instance for request/response tracing
// - error: Any error that occurred during plugin initialization
func getPlugin() (schemas.LLMPlugin, error) {
// check if Maxim Logger variables are set
if os.Getenv("MAXIM_API_KEY") == "" {
return nil, fmt.Errorf("MAXIM_API_KEY is not set, please set it in your environment variables")
}
logger := bifrost.NewDefaultLogger(schemas.LogLevelDebug)
plugin, err := Init(&Config{
APIKey: os.Getenv("MAXIM_API_KEY"),
LogRepoID: os.Getenv("MAXIM_LOG_REPO_ID"),
}, logger)
if err != nil {
return nil, err
}
return plugin, nil
}
// BaseAccount implements the schemas.Account interface for testing purposes.
// It provides mock implementations of the required methods to test the Maxim plugin
// with a basic OpenAI configuration.
type BaseAccount struct{}
// GetConfiguredProviders returns a list of supported providers for testing.
// Currently only supports OpenAI for simplicity in testing. You are free to add more providers as needed.
func (baseAccount *BaseAccount) GetConfiguredProviders() ([]schemas.ModelProvider, error) {
return []schemas.ModelProvider{schemas.OpenAI}, nil
}
// GetKeysForProvider returns a mock API key configuration for testing.
// Uses the OPENAI_API_KEY environment variable for authentication.
func (baseAccount *BaseAccount) GetKeysForProvider(ctx context.Context, providerKey schemas.ModelProvider) ([]schemas.Key, error) {
return []schemas.Key{
{
Value: *schemas.NewEnvVar("env.OPENAI_API_KEY"),
Models: []string{"gpt-4o-mini", "gpt-4-turbo"},
Weight: 1.0,
},
}, nil
}
// GetConfigForProvider returns default provider configuration for testing.
// Uses standard network and concurrency settings.
func (baseAccount *BaseAccount) GetConfigForProvider(providerKey schemas.ModelProvider) (*schemas.ProviderConfig, error) {
return &schemas.ProviderConfig{
NetworkConfig: schemas.DefaultNetworkConfig,
ConcurrencyAndBufferSize: schemas.DefaultConcurrencyAndBufferSize,
}, nil
}
func (baseAccount *BaseAccount) GetGlobalKeys(ctx context.Context) ([]schemas.Key, error) {
return nil, nil
}
// TestMaximLoggerPlugin tests the integration of the Maxim Logger plugin with Bifrost.
// It performs the following steps:
// 1. Initializes the Maxim plugin with environment variables
// 2. Sets up a test Bifrost instance with the plugin
// 3. Makes a test chat completion request
//
// Required environment variables:
// - MAXIM_API_KEY: Your Maxim API key
// - MAXIM_LOGGER_ID: Your Maxim logger repository ID
// - OPENAI_API_KEY: Your OpenAI API key for the test request
func TestMaximLoggerPlugin(t *testing.T) {
ctx := context.Background()
// Initialize the Maxim plugin
plugin, err := getPlugin()
if err != nil {
t.Fatalf("Error setting up the plugin: %v", err)
}
account := BaseAccount{}
// Initialize Bifrost with the plugin
client, err := bifrost.Init(ctx, schemas.BifrostConfig{
Account: &account,
LLMPlugins: []schemas.LLMPlugin{plugin},
Logger: bifrost.NewDefaultLogger(schemas.LogLevelDebug),
})
if err != nil {
t.Fatalf("Error initializing Bifrost: %v", err)
}
// Make a test chat completion request
_, bifrostErr := client.ChatCompletionRequest(schemas.NewBifrostContext(context.Background(), schemas.NoDeadline), &schemas.BifrostChatRequest{
Provider: schemas.OpenAI,
Model: "gpt-4o-mini",
Input: []schemas.ChatMessage{
{
Role: "user",
Content: &schemas.ChatMessageContent{
ContentStr: bifrost.Ptr("Hello, how are you?"),
},
},
},
})
if bifrostErr != nil {
log.Printf("Error in Bifrost request: %v", bifrostErr)
}
log.Println("Bifrost request completed, check your Maxim Dashboard for the trace")
client.Shutdown()
}
// TestLogRepoIDSelection tests the single repository selection logic
func TestLogRepoIDSelection(t *testing.T) {
tests := []struct {
name string
defaultRepo string
headerRepo string
expectedRepo string
shouldLog bool
}{
{
name: "Header repo takes priority",
defaultRepo: "default-repo",
headerRepo: "header-repo",
expectedRepo: "header-repo",
shouldLog: true,
},
{
name: "Fall back to default repo when no header",
defaultRepo: "default-repo",
headerRepo: "",
expectedRepo: "default-repo",
shouldLog: true,
},
{
name: "Use header repo when no default",
defaultRepo: "",
headerRepo: "header-repo",
expectedRepo: "header-repo",
shouldLog: true,
},
{
name: "Skip logging when neither available",
defaultRepo: "",
headerRepo: "",
expectedRepo: "",
shouldLog: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create plugin with default repo
plugin := &Plugin{
defaultLogRepoID: tt.defaultRepo,
}
// Create context with header repo if provided
ctx := schemas.NewBifrostContext(context.Background(), schemas.NoDeadline)
if tt.headerRepo != "" {
ctx.SetValue(LogRepoIDKey, tt.headerRepo)
}
// Test the selection logic
result := plugin.getEffectiveLogRepoID(ctx)
if result != tt.expectedRepo {
t.Errorf("Expected repo '%s', got '%s'", tt.expectedRepo, result)
}
shouldLog := result != ""
if shouldLog != tt.shouldLog {
t.Errorf("Expected shouldLog=%t, got shouldLog=%t", tt.shouldLog, shouldLog)
}
})
}
}
// TestPluginInitialization tests plugin initialization with different configs
func TestPluginInitialization(t *testing.T) {
logger := bifrost.NewDefaultLogger(schemas.LogLevelDebug)
tests := []struct {
name string
config Config
expectError bool
}{
{
name: "Valid config with both fields",
config: Config{
APIKey: "test-api-key",
LogRepoID: "test-repo-id",
},
expectError: false,
},
{
name: "Valid config with only API key",
config: Config{
APIKey: "test-api-key",
LogRepoID: "",
},
expectError: false,
},
{
name: "Invalid config - missing API key",
config: Config{
APIKey: "",
LogRepoID: "test-repo-id",
},
expectError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Skip actual Maxim SDK initialization in tests
if tt.expectError {
_, err := Init(&tt.config, logger)
if err == nil {
t.Error("Expected error but got none")
}
} else {
// For valid configs, we can't test actual initialization without real API key
// Just test the validation logic
if tt.config.APIKey == "" {
t.Skip("Skipping valid config test - would need real Maxim API key")
}
}
})
}
}
// TestPluginName tests the plugin name functionality
func TestPluginName(t *testing.T) {
plugin := &Plugin{}
if plugin.GetName() != PluginName {
t.Errorf("Expected plugin name '%s', got '%s'", PluginName, plugin.GetName())
}
if PluginName != "maxim" {
t.Errorf("Expected PluginName constant to be 'maxim', got '%s'", PluginName)
}
}
|