openai_image_intent_hint.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package service
  2. import "github.com/gin-gonic/gin"
  3. // 请求级 hint 仅限 HTTP:缺失表示 unknown,false/true 都表示已完成 canonical 判定。
  4. const openAIImageIntentHintContextKey = "openai_image_intent_hint"
  5. type openAIImageIntentClassifier func(endpoint string, requestedModel string, body []byte) bool
  6. // SetOpenAIImageIntentHint 只写入请求级 canonical 判定,不记录 attempt-local 结果。
  7. func SetOpenAIImageIntentHint(c *gin.Context, imageIntent bool) {
  8. if c == nil || GetOpenAIClientTransport(c) != OpenAIClientTransportHTTP {
  9. return
  10. }
  11. c.Set(openAIImageIntentHintContextKey, imageIntent)
  12. }
  13. func getOpenAIImageIntentHint(c *gin.Context) (imageIntent bool, known bool) {
  14. if c == nil || GetOpenAIClientTransport(c) != OpenAIClientTransportHTTP {
  15. return false, false
  16. }
  17. value, ok := c.Get(openAIImageIntentHintContextKey)
  18. if !ok {
  19. return false, false
  20. }
  21. imageIntent, ok = value.(bool)
  22. return imageIntent, ok
  23. }
  24. func resolveOpenAIImageIntentHint(
  25. c *gin.Context,
  26. requestedModel string,
  27. canonicalBody []byte,
  28. classify openAIImageIntentClassifier,
  29. ) bool {
  30. if imageIntent, known := getOpenAIImageIntentHint(c); known {
  31. return imageIntent
  32. }
  33. imageIntent := classify(openAIResponsesEndpoint, requestedModel, canonicalBody)
  34. SetOpenAIImageIntentHint(c, imageIntent)
  35. return imageIntent
  36. }
  37. func resolveOpenAIPassthroughImageIntent(
  38. c *gin.Context,
  39. canonicalRequestedModel string,
  40. canonicalBody []byte,
  41. attemptRequestedModel string,
  42. attemptBody []byte,
  43. attemptInvalidated bool,
  44. classify openAIImageIntentClassifier,
  45. ) bool {
  46. imageIntent := resolveOpenAIImageIntentHint(c, canonicalRequestedModel, canonicalBody, classify)
  47. if attemptInvalidated {
  48. // strip/compact 改写只重算当前 attempt,不得把变换后的结果写回请求级 canonical hint。
  49. imageIntent = classify(openAIResponsesEndpoint, attemptRequestedModel, attemptBody)
  50. }
  51. return imageIntent
  52. }