File size: 18,484 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 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 | package semanticcache
import (
"context"
"strings"
"testing"
bifrost "github.com/maximhq/bifrost/core"
"github.com/maximhq/bifrost/core/schemas"
)
// TestParameterVariations tests that different parameters don't cache hit inappropriately
func TestParameterVariations(t *testing.T) {
setup := NewTestSetup(t)
defer setup.Cleanup()
basePrompt := "What is the capital of France?"
tests := []struct {
name string
request1 *schemas.BifrostChatRequest
request2 *schemas.BifrostChatRequest
shouldCache bool
}{
{
name: "Same Parameters",
request1: CreateBasicChatRequest(basePrompt, 0.5, 50),
request2: CreateBasicChatRequest(basePrompt, 0.5, 50),
shouldCache: true,
},
{
name: "Different Temperature",
request1: CreateBasicChatRequest(basePrompt, 0.1, 50),
request2: CreateBasicChatRequest(basePrompt, 0.9, 50),
shouldCache: false,
},
{
name: "Different MaxTokens",
request1: CreateBasicChatRequest(basePrompt, 0.5, 50),
request2: CreateBasicChatRequest(basePrompt, 0.5, 200),
shouldCache: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create a fresh context for each subtest to avoid context pollution
ctx := CreateContextWithCacheKey("param-variations-test")
// Clear cache for this subtest
clearTestKeysWithStore(t, setup.Store)
// Make first request
_, err1 := setup.Client.ChatCompletionRequest(ctx, tt.request1)
if err1 != nil {
return // Test will be skipped by retry function
}
WaitForCache(setup.Plugin)
// Make second request
response2, err2 := setup.Client.ChatCompletionRequest(ctx, tt.request2)
if err2 != nil {
if err2.Error != nil {
t.Fatalf("Second request failed: %v", err2.Error.Message)
} else {
t.Fatalf("Second request failed: %v", err2)
}
}
// Check cache behavior
if tt.shouldCache {
AssertCacheHit(t, &schemas.BifrostResponse{ChatResponse: response2}, string(CacheTypeDirect))
} else {
AssertNoCacheHit(t, &schemas.BifrostResponse{ChatResponse: response2})
}
})
}
}
// TestToolVariations tests caching behavior with different tool configurations
func TestToolVariations(t *testing.T) {
setup := NewTestSetup(t)
defer setup.Cleanup()
ctx := CreateContextWithCacheKey("tool-variations-test")
// Base request without tools
baseRequest := &schemas.BifrostChatRequest{
Provider: schemas.OpenAI,
Model: "gpt-4o-mini",
Input: []schemas.ChatMessage{
{
Role: schemas.ChatMessageRoleUser,
Content: &schemas.ChatMessageContent{
ContentStr: bifrost.Ptr("What's the weather like today?"),
},
},
},
Params: &schemas.ChatParameters{
MaxCompletionTokens: bifrost.Ptr(100),
Temperature: bifrost.Ptr(0.5),
},
}
// Request with tools
requestWithTools := &schemas.BifrostChatRequest{
Provider: schemas.OpenAI,
Model: "gpt-4o-mini",
Input: []schemas.ChatMessage{
{
Role: schemas.ChatMessageRoleUser,
Content: &schemas.ChatMessageContent{
ContentStr: bifrost.Ptr("What's the weather like today?"),
},
},
},
Params: &schemas.ChatParameters{
MaxCompletionTokens: bifrost.Ptr(100),
Temperature: bifrost.Ptr(0.5),
Tools: []schemas.ChatTool{
{
Type: schemas.ChatToolTypeFunction,
Function: &schemas.ChatToolFunction{
Name: "get_weather",
Description: bifrost.Ptr("Get the current weather"),
Parameters: &schemas.ToolFunctionParameters{
Type: "object",
Properties: schemas.NewOrderedMapFromPairs(
schemas.KV("location", map[string]interface{}{
"type": "string",
"description": "The city and state",
}),
),
},
Strict: bifrost.Ptr(false),
},
},
},
},
}
// Request with different tools
requestWithDifferentTools := &schemas.BifrostChatRequest{
Provider: schemas.OpenAI,
Model: "gpt-4o-mini",
Input: []schemas.ChatMessage{
{
Role: schemas.ChatMessageRoleUser,
Content: &schemas.ChatMessageContent{
ContentStr: bifrost.Ptr("What's the weather like today?"),
},
},
},
Params: &schemas.ChatParameters{
MaxCompletionTokens: bifrost.Ptr(100),
Temperature: bifrost.Ptr(0.5),
Tools: []schemas.ChatTool{
{
Type: schemas.ChatToolTypeFunction,
Function: &schemas.ChatToolFunction{
Name: "get_current_weather",
Description: bifrost.Ptr("Get current weather information"),
Parameters: &schemas.ToolFunctionParameters{
Type: "object",
Properties: schemas.NewOrderedMapFromPairs(
schemas.KV("city", map[string]interface{}{ // Different parameter name
"type": "string",
"description": "The city name",
}),
),
},
Strict: bifrost.Ptr(false),
},
},
},
},
}
// Test 1: Request without tools
t.Log("Making request without tools...")
_, err1 := setup.Client.ChatCompletionRequest(ctx, baseRequest)
if err1 != nil {
t.Fatalf("Request without tools failed: %v", err1)
}
WaitForCache(setup.Plugin)
// Test 2: Request with tools (should NOT cache hit)
t.Log("Making request with tools...")
response2, err2 := setup.Client.ChatCompletionRequest(ctx, requestWithTools)
if err2 != nil {
return // Test will be skipped by retry function
}
AssertNoCacheHit(t, &schemas.BifrostResponse{ChatResponse: response2})
WaitForCache(setup.Plugin)
// Test 3: Same request with tools (should cache hit)
t.Log("Making same request with tools again...")
response3, err3 := setup.Client.ChatCompletionRequest(ctx, requestWithTools)
if err3 != nil {
t.Fatalf("Second request with tools failed: %v", err3)
}
AssertCacheHit(t, &schemas.BifrostResponse{ChatResponse: response3}, "")
// Test 4: Request with different tools (should NOT cache hit)
t.Log("Making request with different tools...")
response4, err4 := setup.Client.ChatCompletionRequest(ctx, requestWithDifferentTools)
if err4 != nil {
return // Test will be skipped by retry function
}
AssertNoCacheHit(t, &schemas.BifrostResponse{ChatResponse: response4})
t.Log("✅ Tool variations test completed!")
}
// TestContentVariations tests caching behavior with different content types
func TestContentVariations(t *testing.T) {
setup := NewTestSetup(t)
defer setup.Cleanup()
tests := []struct {
name string
request *schemas.BifrostChatRequest
}{
{
name: "Image URL Content",
request: &schemas.BifrostChatRequest{
Provider: schemas.OpenAI,
Model: "gpt-4o-mini",
Input: []schemas.ChatMessage{
{
Role: schemas.ChatMessageRoleUser,
Content: &schemas.ChatMessageContent{
ContentBlocks: []schemas.ChatContentBlock{
{
Type: schemas.ChatContentBlockTypeText,
Text: bifrost.Ptr("Analyze this image"),
},
{
Type: schemas.ChatContentBlockTypeImage,
ImageURLStruct: &schemas.ChatInputImage{
URL: "https://pub-cdead89c2f004d8f963fd34010c479d0.r2.dev/Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
},
},
},
},
},
},
Params: &schemas.ChatParameters{
MaxCompletionTokens: bifrost.Ptr(200),
Temperature: bifrost.Ptr(0.3),
},
},
},
{
name: "Multiple Images",
request: &schemas.BifrostChatRequest{
Provider: schemas.OpenAI,
Model: "gpt-4o-mini",
Input: []schemas.ChatMessage{
{
Role: schemas.ChatMessageRoleUser,
Content: &schemas.ChatMessageContent{
ContentBlocks: []schemas.ChatContentBlock{
{
Type: schemas.ChatContentBlockTypeText,
Text: bifrost.Ptr("Compare these images"),
},
{
Type: schemas.ChatContentBlockTypeImage,
ImageURLStruct: &schemas.ChatInputImage{
URL: "https://pub-cdead89c2f004d8f963fd34010c479d0.r2.dev/Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
},
},
{
Type: schemas.ChatContentBlockTypeImage,
ImageURLStruct: &schemas.ChatInputImage{
URL: "https://upload.wikimedia.org/wikipedia/commons/b/b5/Scenery_.jpg",
},
},
},
},
},
},
Params: &schemas.ChatParameters{
MaxCompletionTokens: bifrost.Ptr(200),
Temperature: bifrost.Ptr(0.3),
},
},
},
{
name: "Very Long Content",
request: &schemas.BifrostChatRequest{
Provider: schemas.OpenAI,
Model: "gpt-4o-mini",
Input: []schemas.ChatMessage{
{
Role: schemas.ChatMessageRoleUser,
Content: &schemas.ChatMessageContent{
ContentStr: bifrost.Ptr(strings.Repeat("This is a very long prompt. ", 100)),
},
},
},
Params: &schemas.ChatParameters{
MaxCompletionTokens: bifrost.Ptr(50),
Temperature: bifrost.Ptr(0.2),
},
},
},
{
name: "Multi-turn Conversation",
request: &schemas.BifrostChatRequest{
Provider: schemas.OpenAI,
Model: "gpt-4o-mini",
Input: []schemas.ChatMessage{
{
Role: schemas.ChatMessageRoleUser,
Content: &schemas.ChatMessageContent{
ContentStr: bifrost.Ptr("What is AI?"),
},
},
{
Role: schemas.ChatMessageRoleAssistant,
Content: &schemas.ChatMessageContent{
ContentStr: bifrost.Ptr("AI stands for Artificial Intelligence..."),
},
},
{
Role: schemas.ChatMessageRoleUser,
Content: &schemas.ChatMessageContent{
ContentStr: bifrost.Ptr("Can you give me examples?"),
},
},
},
Params: &schemas.ChatParameters{
MaxCompletionTokens: bifrost.Ptr(150),
Temperature: bifrost.Ptr(0.5),
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Logf("Testing content variation: %s", tt.name)
// Create a fresh context for each subtest to avoid context pollution
ctx := CreateContextWithCacheKey("content-variations-test")
// Make first request
_, err1 := setup.Client.ChatCompletionRequest(ctx, tt.request)
if err1 != nil {
t.Logf("⚠️ First %s request failed: %v", tt.name, err1)
return // Skip this test case
}
WaitForCache(setup.Plugin)
// Make second identical request
response2, err2 := setup.Client.ChatCompletionRequest(ctx, tt.request)
if err2 != nil {
t.Fatalf("Second %s request failed: %v", tt.name, err2)
}
// Should be cached
AssertCacheHit(t, &schemas.BifrostResponse{ChatResponse: response2}, string(CacheTypeDirect))
t.Logf("✅ %s content variation successful", tt.name)
})
}
}
// TestBoundaryParameterValues tests edge case parameter values
func TestBoundaryParameterValues(t *testing.T) {
setup := NewTestSetup(t)
defer setup.Cleanup()
tests := []struct {
name string
request *schemas.BifrostChatRequest
}{
{
name: "Maximum Parameter Values",
request: &schemas.BifrostChatRequest{
Provider: schemas.OpenAI,
Model: "gpt-4o-mini",
Input: []schemas.ChatMessage{
{
Role: schemas.ChatMessageRoleUser,
Content: &schemas.ChatMessageContent{
ContentStr: bifrost.Ptr("Test max parameters"),
},
},
},
Params: &schemas.ChatParameters{
MaxCompletionTokens: bifrost.Ptr(4096),
PresencePenalty: bifrost.Ptr(2.0),
FrequencyPenalty: bifrost.Ptr(2.0),
Temperature: bifrost.Ptr(2.0),
TopP: bifrost.Ptr(1.0),
},
},
},
{
name: "Minimum Parameter Values",
request: &schemas.BifrostChatRequest{
Provider: schemas.OpenAI,
Model: "gpt-4o-mini",
Input: []schemas.ChatMessage{
{
Role: schemas.ChatMessageRoleUser,
Content: &schemas.ChatMessageContent{
ContentStr: bifrost.Ptr("Test min parameters"),
},
},
},
Params: &schemas.ChatParameters{
MaxCompletionTokens: bifrost.Ptr(1),
PresencePenalty: bifrost.Ptr(-2.0),
FrequencyPenalty: bifrost.Ptr(-2.0),
Temperature: bifrost.Ptr(0.0),
TopP: bifrost.Ptr(0.01),
},
},
},
{
name: "Edge Case Parameters",
request: &schemas.BifrostChatRequest{
Provider: schemas.OpenAI,
Model: "gpt-4o-mini",
Input: []schemas.ChatMessage{
{
Role: schemas.ChatMessageRoleUser,
Content: &schemas.ChatMessageContent{
ContentStr: bifrost.Ptr("Test edge case parameters"),
},
},
},
Params: &schemas.ChatParameters{
MaxCompletionTokens: bifrost.Ptr(1),
User: bifrost.Ptr("test-user-id-12345"),
Temperature: bifrost.Ptr(0.0),
TopP: bifrost.Ptr(0.1),
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Logf("Testing boundary parameters: %s", tt.name)
// Create a fresh context for each subtest to avoid context pollution
ctx := CreateContextWithCacheKey("boundary-params-test")
_, err := setup.Client.ChatCompletionRequest(ctx, tt.request)
if err != nil {
t.Logf("⚠️ %s request failed (may be expected): %v", tt.name, err)
} else {
t.Logf("✅ %s handled gracefully", tt.name)
}
})
}
}
// TestSemanticSimilarityEdgeCases tests edge cases in semantic similarity matching
func TestSemanticSimilarityEdgeCases(t *testing.T) {
setup := NewTestSetup(t)
defer setup.Cleanup()
setup.Config.Threshold = 0.9
// Test case: Similar questions with different wording
similarTests := []struct {
prompt1 string
prompt2 string
shouldMatch bool
description string
}{
{
prompt1: "What is machine learning?",
prompt2: "Can you explain machine learning?",
shouldMatch: true,
description: "Similar questions about ML",
},
{
prompt1: "How does AI work?",
prompt2: "Explain artificial intelligence",
shouldMatch: true,
description: "AI-related questions",
},
{
prompt1: "What is the weather today?",
prompt2: "What do you know about bifrost?",
shouldMatch: false,
description: "Completely different topics",
},
{
prompt1: "Hello, how are you?",
prompt2: "Hi, how are you doing?",
shouldMatch: true,
description: "Similar greetings",
},
}
for i, test := range similarTests {
t.Run(test.description, func(t *testing.T) {
// Create a fresh context for each subtest to avoid context pollution
ctx := CreateContextWithCacheKey("semantic-edge-test")
// Clear cache for this subtest
clearTestKeysWithStore(t, setup.Store)
// Make first request
request1 := CreateBasicChatRequest(test.prompt1, 0.1, 50)
_, err1 := setup.Client.ChatCompletionRequest(ctx, request1)
if err1 != nil {
return // Test will be skipped by retry function
}
// Wait for cache to be written
WaitForCache(setup.Plugin)
// Make second request with similar content
request2 := CreateBasicChatRequest(test.prompt2, 0.1, 50) // Same parameters
response2, err2 := setup.Client.ChatCompletionRequest(ctx, request2)
if err2 != nil {
if err2.Error != nil {
t.Fatalf("Second request failed: %v", err2.Error.Message)
} else {
t.Fatalf("Second request failed: %v", err2)
}
}
var cacheThresholdFloat float64
var cacheSimilarityFloat float64
// Check if semantic matching occurred
semanticMatch := false
if response2.ExtraFields.CacheDebug != nil && response2.ExtraFields.CacheDebug.CacheHit {
if response2.ExtraFields.CacheDebug.HitType != nil && *response2.ExtraFields.CacheDebug.HitType == string(CacheTypeSemantic) {
semanticMatch = true
if response2.ExtraFields.CacheDebug.Threshold != nil {
cacheThresholdFloat = *response2.ExtraFields.CacheDebug.Threshold
}
if response2.ExtraFields.CacheDebug.Similarity != nil {
cacheSimilarityFloat = *response2.ExtraFields.CacheDebug.Similarity
}
}
}
if test.shouldMatch {
if semanticMatch {
t.Logf("✅ Test %d: Semantic match found as expected for '%s'", i+1, test.description)
} else {
t.Logf("ℹ️ Test %d: No semantic match found for '%s', check with threshold: %f and found similarity: %f", i+1, test.description, cacheThresholdFloat, cacheSimilarityFloat)
}
} else {
if semanticMatch {
t.Errorf("❌ Test %d: Unexpected semantic match for different topics: '%s', check with threshold: %f and found similarity: %f", i+1, test.description, cacheThresholdFloat, cacheSimilarityFloat)
} else {
t.Logf("✅ Test %d: Correctly no semantic match for different topics: '%s'", i+1, test.description)
}
}
})
}
}
// TestErrorHandlingEdgeCases tests various error scenarios
func TestErrorHandlingEdgeCases(t *testing.T) {
setup := NewTestSetup(t)
defer setup.Cleanup()
testRequest := CreateBasicChatRequest("Test error handling scenarios", 0.5, 50)
// Test without cache key (should not crash and bypass cache)
t.Run("Request without cache key", func(t *testing.T) {
ctxNoKey := schemas.NewBifrostContext(context.Background(), schemas.NoDeadline)
response, err := setup.Client.ChatCompletionRequest(ctxNoKey, testRequest)
if err != nil {
t.Errorf("Request without cache key failed: %v", err)
return
}
// Should bypass cache since there's no cache key
AssertNoCacheHit(t, &schemas.BifrostResponse{ChatResponse: response})
t.Log("✅ Request without cache key correctly bypassed cache")
})
// Test with invalid cache key type
t.Run("Request with invalid cache key type", func(t *testing.T) {
// First establish a cached response with valid context
validCtx := CreateContextWithCacheKey("error-handling-test")
_, err := setup.Client.ChatCompletionRequest(validCtx, testRequest)
if err != nil {
t.Fatalf("First request with valid cache key failed: %v", err)
}
WaitForCache(setup.Plugin)
// Now test with invalid key type - should bypass cache
ctxInvalidKey := schemas.NewBifrostContext(context.Background(), schemas.NoDeadline).WithValue(CacheKey, 12345)
response, err := setup.Client.ChatCompletionRequest(ctxInvalidKey, testRequest)
if err != nil {
t.Errorf("Request with invalid cache key type failed: %v", err)
return
}
// Should bypass cache due to invalid key type
AssertNoCacheHit(t, &schemas.BifrostResponse{ChatResponse: response})
t.Log("✅ Request with invalid cache key type correctly bypassed cache")
})
t.Log("✅ Error handling edge cases completed!")
}
|