openai_messages_bridge.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package service
  2. import (
  3. "bytes"
  4. "strings"
  5. "github.com/gin-gonic/gin"
  6. "github.com/tidwall/gjson"
  7. )
  8. const openAICompatMessagesBridgeContextKey = "openai_compat_messages_bridge"
  9. func isOpenAICompatMessagesBridgeBody(body []byte) bool {
  10. if len(body) == 0 {
  11. return false
  12. }
  13. if bytes.Contains(body, []byte(openAICompatClaudeCodeTodoGuardMarker)) {
  14. return true
  15. }
  16. return isOpenAICompatMessagesBridgePromptCacheKey(gjson.GetBytes(body, "prompt_cache_key").String())
  17. }
  18. func isOpenAICompatMessagesBridgeRequestBody(reqBody map[string]any) bool {
  19. if reqBody == nil {
  20. return false
  21. }
  22. if input, ok := reqBody["input"].([]any); ok && inputContainsText(input, openAICompatClaudeCodeTodoGuardMarker) {
  23. return true
  24. }
  25. return isOpenAICompatMessagesBridgePromptCacheKey(firstNonEmptyString(reqBody["prompt_cache_key"]))
  26. }
  27. func isOpenAICompatMessagesBridgePromptCacheKey(key string) bool {
  28. key = strings.TrimSpace(key)
  29. return strings.HasPrefix(key, "anthropic-metadata-") ||
  30. strings.HasPrefix(key, "anthropic-cache-") ||
  31. strings.HasPrefix(key, "anthropic-digest-")
  32. }
  33. func setOpenAICompatMessagesBridgeContext(c *gin.Context, enabled bool) {
  34. if c == nil || !enabled {
  35. return
  36. }
  37. c.Set(openAICompatMessagesBridgeContextKey, true)
  38. }
  39. func isOpenAICompatMessagesBridgeContext(c *gin.Context) bool {
  40. if c == nil {
  41. return false
  42. }
  43. value, ok := c.Get(openAICompatMessagesBridgeContextKey)
  44. if !ok {
  45. return false
  46. }
  47. enabled, ok := value.(bool)
  48. return ok && enabled
  49. }