openai_embeddings.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. package handler
  2. import (
  3. "context"
  4. "errors"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "time"
  9. pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil"
  10. "github.com/Wei-Shaw/sub2api/internal/pkg/ip"
  11. "github.com/Wei-Shaw/sub2api/internal/pkg/logger"
  12. middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
  13. "github.com/Wei-Shaw/sub2api/internal/service"
  14. "github.com/gin-gonic/gin"
  15. "github.com/tidwall/gjson"
  16. "go.uber.org/zap"
  17. )
  18. // Embeddings handles the OpenAI-compatible Embeddings API.
  19. // POST /v1/embeddings
  20. func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) {
  21. streamStarted := false
  22. requestStart := time.Now()
  23. apiKey, ok := middleware2.GetAPIKeyFromContext(c)
  24. if !ok {
  25. h.errorResponse(c, http.StatusUnauthorized, "authentication_error", "Invalid API key")
  26. return
  27. }
  28. subject, ok := middleware2.GetAuthSubjectFromContext(c)
  29. if !ok {
  30. h.errorResponse(c, http.StatusInternalServerError, "api_error", "User context not found")
  31. return
  32. }
  33. reqLog := requestLogger(
  34. c,
  35. "handler.openai_gateway.embeddings",
  36. zap.Int64("user_id", subject.UserID),
  37. zap.Int64("api_key_id", apiKey.ID),
  38. zap.Any("group_id", apiKey.GroupID),
  39. )
  40. if !h.ensureResponsesDependencies(c, reqLog) {
  41. return
  42. }
  43. body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request)
  44. if err != nil {
  45. if maxErr, ok := extractMaxBytesError(err); ok {
  46. h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit))
  47. return
  48. }
  49. h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body")
  50. return
  51. }
  52. if len(body) == 0 {
  53. h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Request body is empty")
  54. return
  55. }
  56. if !gjson.ValidBytes(body) {
  57. logRequestBodyParseFailure(reqLog, body, nil)
  58. h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to parse request body")
  59. return
  60. }
  61. modelResult := gjson.GetBytes(body, "model")
  62. if !modelResult.Exists() || modelResult.Type != gjson.String || strings.TrimSpace(modelResult.String()) == "" {
  63. h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "model is required")
  64. return
  65. }
  66. reqModel := modelResult.String()
  67. ensureCompositeTargetPlatform(c, apiKey, reqModel)
  68. if !compositeTargetPlatformAllowed(c, apiKey, reqModel, service.PlatformOpenAI) {
  69. h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Model is not supported by this OpenAI-compatible endpoint for composite groups")
  70. return
  71. }
  72. reqLog = reqLog.With(zap.String("model", reqModel))
  73. setOpsRequestContext(c, reqModel, false)
  74. setOpsEndpointContext(c, "", int16(service.RequestTypeSync))
  75. if decision := h.checkSecurityAudit(c, reqLog, apiKey, subject, "openai_embeddings", reqModel, body); decision != nil && !decision.AllowNextStage {
  76. h.openAISecurityAuditError(c, decision)
  77. return
  78. }
  79. channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel)
  80. forwardModel := openAIChannelForwardModel(channelMapping, reqModel)
  81. subscription, _ := middleware2.GetSubscriptionFromContext(c)
  82. service.SetOpsLatencyMs(c, service.OpsAuthLatencyMsKey, time.Since(requestStart).Milliseconds())
  83. userReleaseFunc, acquired := h.acquireResponsesUserSlot(c, subject.UserID, subject.Concurrency, false, &streamStarted, reqLog)
  84. if !acquired {
  85. return
  86. }
  87. if userReleaseFunc != nil {
  88. defer userReleaseFunc()
  89. }
  90. if err := h.billingCacheService.CheckBillingEligibility(c.Request.Context(), apiKey.User, apiKey, apiKey.Group, subscription, service.QuotaPlatform(c.Request.Context(), apiKey)); err != nil {
  91. reqLog.Info("openai_embeddings.billing_check_failed", zap.Error(err))
  92. status, code, message, retryAfter := billingErrorDetails(err)
  93. if retryAfter > 0 {
  94. c.Header("Retry-After", strconv.Itoa(retryAfter))
  95. }
  96. h.errorResponse(c, status, code, message)
  97. return
  98. }
  99. profitVetoCount := 0
  100. failedAccountIDs := make(map[int64]struct{})
  101. var lastFailoverErr *service.UpstreamFailoverError
  102. switchCount := 0
  103. maxAccountSwitches := h.maxAccountSwitches
  104. if maxAccountSwitches <= 0 {
  105. maxAccountSwitches = 3
  106. }
  107. routingStart := time.Now()
  108. // 分组利润控制:embeddings 文本入口请求级装门并固定 pricingAt。
  109. embPricingCtx, pricingAt := h.gatewayService.WithOpenAIRequestPricingContext(c.Request.Context(), apiKey.GroupID)
  110. c.Request = c.Request.WithContext(embPricingCtx)
  111. for {
  112. selection, _, err := h.gatewayService.SelectAccountWithSchedulerForCapability(
  113. c.Request.Context(),
  114. apiKey.GroupID,
  115. "",
  116. "",
  117. forwardModel,
  118. failedAccountIDs,
  119. service.OpenAIUpstreamTransportHTTPSSE,
  120. service.OpenAIEndpointCapabilityEmbeddings,
  121. false,
  122. false,
  123. true,
  124. )
  125. if err != nil {
  126. if failoverClientGone(c) {
  127. reqLog.Info("openai_embeddings.account_select_aborted_client_disconnected", zap.Error(err))
  128. return
  129. }
  130. reqLog.Warn("openai_embeddings.account_select_failed",
  131. zap.Error(err),
  132. zap.Int("excluded_account_count", len(failedAccountIDs)),
  133. )
  134. if len(failedAccountIDs) == 0 {
  135. cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, reqModel, reqModel, service.PlatformOpenAI)
  136. if !cls.ModelNotFound {
  137. markOpsRoutingCapacityLimitedIfNoAvailable(c, err)
  138. }
  139. h.errorResponse(c, cls.Status, cls.ErrType, cls.Message)
  140. return
  141. }
  142. if lastFailoverErr != nil {
  143. h.handleFailoverExhausted(c, lastFailoverErr, false)
  144. } else {
  145. h.errorResponse(c, http.StatusBadGateway, "api_error", "Upstream request failed")
  146. }
  147. return
  148. }
  149. if selection == nil || selection.Account == nil {
  150. cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, reqModel, reqModel, service.PlatformOpenAI)
  151. if !cls.ModelNotFound {
  152. markOpsRoutingCapacityLimited(c)
  153. }
  154. h.errorResponse(c, cls.Status, cls.ErrType, cls.Message)
  155. return
  156. }
  157. account := selection.Account
  158. setOpsSelectedAccount(c, account.ID, account.Platform)
  159. accountReleaseFunc, slotResult := h.acquireResponsesAccountSlot(c, apiKey.GroupID, "", selection, false, &streamStarted, reqLog)
  160. if slotResult == openAISlotAcquireProfitVetoed {
  161. // 利润终检否决:排除该账号重新选号;否决次数达上限则按无可用账号终止。
  162. if !recordOpenAIProfitVeto(failedAccountIDs, account.ID, &profitVetoCount) {
  163. h.handleOpenAIProfitVetoExhausted(c, streamStarted, reqLog, profitVetoCount)
  164. return
  165. }
  166. continue
  167. }
  168. if slotResult != openAISlotAcquireOK {
  169. return
  170. }
  171. service.SetOpsLatencyMs(c, service.OpsRoutingLatencyMsKey, time.Since(routingStart).Milliseconds())
  172. forwardStart := time.Now()
  173. forwardBody := body
  174. if channelMapping.Mapped {
  175. forwardBody = h.gatewayService.ReplaceModelInBody(body, channelMapping.MappedModel)
  176. }
  177. writerSizeBeforeForward := c.Writer.Size()
  178. result, err := func() (*service.OpenAIForwardResult, error) {
  179. defer func() {
  180. if accountReleaseFunc != nil {
  181. accountReleaseFunc()
  182. }
  183. }()
  184. return h.gatewayService.ForwardEmbeddings(c.Request.Context(), c, account, forwardBody, "")
  185. }()
  186. forwardDurationMs := time.Since(forwardStart).Milliseconds()
  187. upstreamLatencyMs, _ := getContextInt64(c, service.OpsUpstreamLatencyMsKey)
  188. responseLatencyMs := forwardDurationMs
  189. if upstreamLatencyMs > 0 && forwardDurationMs > upstreamLatencyMs {
  190. responseLatencyMs = forwardDurationMs - upstreamLatencyMs
  191. }
  192. service.SetOpsLatencyMs(c, service.OpsResponseLatencyMsKey, responseLatencyMs)
  193. if err != nil {
  194. var failoverErr *service.UpstreamFailoverError
  195. if errors.As(err, &failoverErr) {
  196. if c.Writer.Size() != writerSizeBeforeForward {
  197. h.handleFailoverExhausted(c, failoverErr, true)
  198. return
  199. }
  200. h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, reqModel, false, result), false, nil, err)
  201. if failoverClientGone(c) {
  202. reqLog.Info("openai_embeddings.failover_aborted_client_disconnected",
  203. zap.Int64("account_id", account.ID),
  204. zap.Int("upstream_status", failoverErr.StatusCode),
  205. )
  206. return
  207. }
  208. h.gatewayService.RecordOpenAIAccountSwitch()
  209. failedAccountIDs[account.ID] = struct{}{}
  210. lastFailoverErr = failoverErr
  211. if switchCount >= maxAccountSwitches {
  212. h.handleFailoverExhausted(c, failoverErr, false)
  213. return
  214. }
  215. switchCount++
  216. reqLog.Warn("openai_embeddings.upstream_failover_switching",
  217. zap.Int64("account_id", account.ID),
  218. zap.Int("upstream_status", failoverErr.StatusCode),
  219. zap.Int("switch_count", switchCount),
  220. zap.Int("max_switches", maxAccountSwitches),
  221. )
  222. continue
  223. }
  224. h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, reqModel, false, result), false, nil, err)
  225. if c.Writer.Size() == writerSizeBeforeForward {
  226. h.errorResponse(c, http.StatusBadGateway, "upstream_error", "Upstream request failed")
  227. }
  228. reqLog.Warn("openai_embeddings.forward_failed",
  229. zap.Int64("account_id", account.ID),
  230. zap.Error(err),
  231. )
  232. return
  233. }
  234. h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, reqModel, false, result), true, nil)
  235. userAgent := c.GetHeader("User-Agent")
  236. clientIP := ip.GetClientIP(c)
  237. inboundEndpoint := GetInboundEndpoint(c)
  238. upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform)
  239. quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
  240. sessionID := service.ExtractClientSessionID(c)
  241. h.submitOpenAIUsageRecordTask(c.Request.Context(), result, func(ctx context.Context) {
  242. if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{
  243. Result: result,
  244. APIKey: apiKey,
  245. User: apiKey.User,
  246. Account: account,
  247. Subscription: subscription,
  248. InboundEndpoint: inboundEndpoint,
  249. UpstreamEndpoint: upstreamEndpoint,
  250. UserAgent: userAgent,
  251. IPAddress: clientIP,
  252. APIKeyService: h.apiKeyService,
  253. QuotaPlatform: quotaPlatform,
  254. SessionID: sessionID,
  255. ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel),
  256. PricingAt: pricingAt,
  257. }); err != nil {
  258. logger.L().With(
  259. zap.String("component", "handler.openai_gateway.embeddings"),
  260. zap.Int64("user_id", subject.UserID),
  261. zap.Int64("api_key_id", apiKey.ID),
  262. zap.Any("group_id", apiKey.GroupID),
  263. zap.String("model", reqModel),
  264. zap.Int64("account_id", account.ID),
  265. ).Error("openai_embeddings.record_usage_failed", zap.Error(err))
  266. }
  267. })
  268. reqLog.Debug("openai_embeddings.request_completed",
  269. zap.Int64("account_id", account.ID),
  270. zap.Int("switch_count", switchCount),
  271. )
  272. return
  273. }
  274. }