fix(gateway): 补齐跨族账号池 compact 路由、生图门禁、推理强度策略与流式错误输出

This commit is contained in:
shaw committed 2026-12-05 10:41:13 +08:00
1 parent e7fcf51343
commit b89c2c98c7
10 files changed
+162 -15

No files matched your search

@@ -314,8 +314,12 @@ func applyCompositePoolReasoningEffortPolicyForSelectedAccount(c *gin.Context, a
if _, isPool := compositeAccountPoolCandidates(c); !isPool {
return body, false, nil
}
if account.Platform != service.PlatformOpenAI {
if account.Platform != service.PlatformOpenAI && account.Platform != service.PlatformAnthropic {
return body, false, nil
}
return service.ApplyOpenAIReasoningEffortPolicy(body, apiKey.Group.MaxReasoningEffort, apiKey.Group.ReasoningEffortMappings, apiKey.Group.MaxReasoningEffortOverLimit)
maxEffort, mappings := apiKey.Group.MaxReasoningEffort, apiKey.Group.ReasoningEffortMappings
if account.Platform == service.PlatformAnthropic {
maxEffort, mappings = anthropicCompatibleReasoningEffortPolicy(maxEffort, mappings)
}
return service.ApplyOpenAIReasoningEffortPolicy(body, maxEffort, mappings, apiKey.Group.MaxReasoningEffortOverLimit)
}
@@ -124,3 +124,52 @@ func TestCompositeCrossFamilyPoolMessagesAppliesReasoningEffortCapToAnthropic(t
require.Len(t, calls, 1)
require.Equal(t, "medium", gjson.GetBytes(calls[0].Body, "output_config.effort").String(), "upstream body=%s", calls[0].Body)
}
// 跨族池在 /v1/responses 与 /v1/chat/completions 选中 anthropic 账号时,同样须补齐
// 分组推理强度策略(含 deny 拦截)。
func TestCompositeCrossFamilyPoolTextEndpointsApplyReasoningEffortPolicyToAnthropic(t *testing.T) {
for _, tc := range []struct {
name, path, body string
}{
{
name: "responses",
path: "/v1/responses",
body: `{"model":"my-model","stream":false,"input":"hello","reasoning":{"effort":"high"}}`,
},
{
name: "chat_completions",
path: "/v1/chat/completions",
body: `{"model":"my-model","stream":false,"messages":[{"role":"user","content":"hello"}],"reasoning_effort":"high"}`,
},
} {
t.Run(tc.name, func(t *testing.T) {
h := newCompositePoolMessagesHarness(t, []*service.Account{poolAnthropicAccount(44203, 41011, 0)})
h.group.MaxReasoningEffort = "low"
h.group.MaxReasoningEffortOverLimit = "deny"
c, rec := h.newRequest(t, tc.path, tc.body, service.PlatformAnthropic, service.PlatformOpenAI)
if tc.path == "/v1/responses" {
h.handler.Responses(c)
} else {
h.handler.ChatCompletions(c)
}
require.Equal(t, http.StatusForbidden, rec.Code, rec.Body.String())
require.Empty(t, h.gwUpstream.snapshot())
})
}
}
// 跨族池 /v1/responses 在分组禁用生图时,须拦截显式生图工具请求,不得经委派绕过。
func TestCompositeCrossFamilyPoolResponsesEnforcesGroupImageGenerationGate(t *testing.T) {
h := newCompositePoolMessagesHarness(t, []*service.Account{poolOpenAIAccount(44204, 41011, 0)})
h.group.AllowImageGeneration = false
c, rec := h.newRequest(t, "/v1/responses",
`{"model":"my-model","stream":false,"input":"draw a cat","tools":[{"type":"image_generation"}]}`,
service.PlatformAnthropic, service.PlatformOpenAI)
h.handler.Responses(c)
require.Equal(t, http.StatusForbidden, rec.Code, rec.Body.String())
require.Contains(t, rec.Body.String(), service.ImageGenerationPermissionMessage())
require.Empty(t, h.openAIUpstream.snapshot())
}
+7 -3
View File
@@ -812,18 +812,21 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
}
// 账号池选中 anthropic 账号:按单目标 anthropic 语义补齐分组推理强度策略(放在槽位获取前)。
if isPoolRequest {
streamAwareWrite := func(cc *gin.Context, status int, code, message string) {
h.handleStreamingAwareError(cc, status, code, message, streamStarted)
}
cappedBody, changed, policyErr := applyCompositePoolAnthropicReasoningEffortPolicy(apiKey, account, attemptParsedReq.Body.Bytes())
if policyErr != nil {
releaseCompositePoolSelection(selection)
h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey)
respondOpenAIReasoningEffortPolicyError(c, policyErr, h.errorResponse)
respondOpenAIReasoningEffortPolicyError(c, policyErr, streamAwareWrite)
return
}
if changed {
if err := attemptParsedReq.ReplaceBody(cappedBody); err != nil {
releaseCompositePoolSelection(selection)
h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey)
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to apply reasoning effort policy")
streamAwareWrite(c, http.StatusBadRequest, "invalid_request_error", "Failed to apply reasoning effort policy")
return
}
}
@@ -1020,7 +1023,8 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
// 渠道定价作用域与计费 QuotaPlatform 跟随实际平台,对齐 OpenAI 池 attempt 语义。
if isPoolRequest {
requestCtx = compositePoolAttemptContext(requestCtx, account)
} else if channelMapping.Mapped {
}
if attemptChannelMapping.Mapped {
// 选号按客户端模型,转发按渠道映射后的模型:模型级账号状态按选号模型记录。
requestCtx = service.WithGatewaySchedulingModel(requestCtx, reqModel)
}
@@ -367,14 +367,21 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
if attemptChannelMapping.Mapped {
forwardBody = h.gatewayService.ReplaceModelInBody(body, attemptChannelMapping.MappedModel)
}
// 账号池按选中账号应用分组推理强度策略(与 OpenAI handler 同语义,仅 openai 账号)。
// 账号池按选中账号应用分组推理强度策略(与单目标同语义,覆盖 openai / anthropic 账号)。
if isPoolRequest {
cappedBody, changed, policyErr := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, forwardBody)
if policyErr != nil {
if accountReleaseFunc != nil {
accountReleaseFunc()
}
respondOpenAIReasoningEffortPolicyError(c, policyErr, h.chatCompletionsErrorResponse)
streamAwareWrite := func(cc *gin.Context, status int, code, message string) {
if streamStarted {
h.handleStreamingAwareError(cc, status, code, message, true)
return
}
h.chatCompletionsErrorResponse(cc, status, code, message)
}
respondOpenAIReasoningEffortPolicyError(c, policyErr, streamAwareWrite)
return
}
if changed {
@@ -130,6 +130,13 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", service.ImageGenerationPermissionMessage())
return
}
if apiKey.Group != nil && apiKey.Group.Platform == service.PlatformComposite &&
service.IsExplicitImageGenerationIntentValidated("/v1/responses", reqModel, body) &&
!service.GroupAllowsImageGeneration(apiKey.Group) {
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
h.responsesErrorResponse(c, http.StatusForbidden, "permission_error", service.ImageGenerationPermissionMessage())
return
}
if decision := h.checkSecurityAudit(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, reqModel, body); decision != nil && !decision.AllowNextStage {
h.responsesSecurityAuditError(c, decision)
@@ -280,8 +287,13 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
poolDenials.deny(account.Platform)
fs.FailedAccountIDs[account.ID] = struct{}{}
if _, ok := compositePoolSelectionRetryContext(requestCtx, poolDenials); !ok {
h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error",
"Model is only available on Gemini accounts in this group, which do not support /v1/responses")
if streamStarted {
h.handleStreamingAwareError(c, http.StatusBadRequest, "invalid_request_error",
"Model is only available on Gemini accounts in this group, which do not support /v1/responses", true)
} else {
h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error",
"Model is only available on Gemini accounts in this group, which do not support /v1/responses")
}
return
}
continue
@@ -382,14 +394,21 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
if attemptChannelMapping.Mapped {
forwardBody = h.gatewayService.ReplaceModelInBody(body, attemptChannelMapping.MappedModel)
}
// 账号池按选中账号应用分组推理强度策略(与 OpenAI handler 同语义,仅 openai 账号)。
// 账号池按选中账号应用分组推理强度策略(与单目标同语义,覆盖 openai / anthropic 账号)。
if isPoolRequest {
cappedBody, changed, policyErr := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, forwardBody)
if policyErr != nil {
if accountReleaseFunc != nil {
accountReleaseFunc()
}
respondOpenAIReasoningEffortPolicyError(c, policyErr, h.responsesErrorResponse)
streamAwareWrite := func(cc *gin.Context, status int, code, message string) {
if streamStarted {
h.handleStreamingAwareError(cc, status, code, message, true)
return
}
h.responsesErrorResponse(cc, status, code, message)
}
respondOpenAIReasoningEffortPolicyError(c, policyErr, streamAwareWrite)
return
}
if changed {
@@ -252,7 +252,9 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
poolPolicyBody := body
if cappedBody, changed, err := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, body); err != nil {
releaseCompositePoolSelection(selection)
respondOpenAIReasoningEffortPolicyError(c, err, h.errorResponse)
respondOpenAIReasoningEffortPolicyError(c, err, func(cc *gin.Context, status int, code, message string) {
h.handleStreamingAwareError(cc, status, code, message, streamStarted)
})
return
} else if changed {
poolPolicyBody = cappedBody
@@ -852,8 +852,8 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
"the account that owns previous_response_id is temporarily unavailable; retry later", streamStarted)
return
}
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error",
"previous_response_id belongs to a response owned by a different account; continue on the account that owns this response state or start a new response")
h.handleStreamingAwareError(c, http.StatusBadRequest, "invalid_request_error",
"previous_response_id belongs to a response owned by a different account; continue on the account that owns this response state or start a new response", streamStarted)
return
}
// 仅实际 openai 平台账号要求 API-key 才支持 HTTP continuation;
@@ -895,7 +895,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
poolPolicyBody := forwardBody
if cappedBody, changed, err := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, forwardBody); err != nil {
releaseCompositePoolSelection(selection)
respondOpenAIReasoningEffortPolicyError(c, err, h.errorResponse)
respondOpenAIReasoningEffortPolicyError(c, err, func(cc *gin.Context, status int, code, message string) {
h.handleStreamingAwareError(cc, status, code, message, streamStarted)
})
return
} else if changed {
poolPolicyBody = cappedBody
+19
View File
@@ -711,6 +711,14 @@ func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver)
writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf("Model %q has no OpenAI-compatible account in this composite group to continue previous_response_id; resend the full conversation without previous_response_id", model))
return
}
} else if isCompositePoolResponsesCompact(c, decision) {
// /responses/compact 仅由 OpenAI 网关链支持(含 compact 归一化、渠道限制与心跳):
// 跨族候选池收窄到 OpenAI 兼容族,避免落入通用网关按普通 Responses 误转协议。
decision.CandidatePlatforms = openAICompatibleCandidatePlatforms(decision.CandidatePlatforms)
if len(decision.CandidatePlatforms) == 0 {
writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf("Model %q has no OpenAI-compatible account in this composite group to support /responses/compact", model))
return
}
}
c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision))
if upstreamModel := strings.TrimSpace(decision.UpstreamModel); upstreamModel != "" && upstreamModel != model && gjson.ValidBytes(body) {
@@ -796,6 +804,17 @@ func isCompositePoolResponsesContinuation(c *gin.Context, decision service.Compo
return strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String()) != ""
}
func isCompositePoolResponsesCompact(c *gin.Context, decision service.CompositeRouteDecision) bool {
if c == nil || c.Request == nil || c.Request.URL == nil {
return false
}
if strings.TrimSpace(decision.TargetPlatform) != "" || len(decision.CandidatePlatforms) == 0 {
return false
}
path := strings.TrimRight(c.Request.URL.Path, "/")
return strings.HasSuffix(path, "/responses/compact")
}
// openAICompatibleCandidatePlatforms 返回候选平台中经 OpenAI 网关转发的平台(保持顺序)。
func openAICompatibleCandidatePlatforms(candidates []string) []string {
out := make([]string, 0, len(candidates))
@@ -94,3 +94,39 @@ func TestCompositePoolContinuationWithoutOpenAICompatibleCandidateRejected(t *te
require.Contains(t, w.Body.String(), "previous_response_id")
require.Empty(t, upstream.capturedSnapshot())
}
// 跨族账号池访问 /v1/responses/compact:候选池收窄到 OpenAI 兼容族交由 OpenAI handler
// 处理,优先级更高的 Anthropic 账号不会收到 compact 请求;无兼容族候选时入口明确拒绝。
func TestCompositeCrossFamilyPoolCompactNarrowsToOpenAICompatible(t *testing.T) {
upstream := &captureUpstream{}
openai := newPoolPolicyAccountWithMapping(4331, service.PlatformOpenAI, 5, map[string]any{"compact-model": "gpt-5.4"})
anthropic := newPoolPolicyAccountWithMapping(4332, service.PlatformAnthropic, 0, map[string]any{"compact-model": "claude-sonnet-4-5"})
router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{
group: newPoolPolicyGroup(nil),
accounts: []service.Account{openai, anthropic},
upstream: upstream,
})
w := postPoolPolicyRequest(t, router, "/v1/responses/compact",
`{"model":"compact-model","input":"compact this"}`)
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
captured := upstream.capturedSnapshot()
require.Len(t, captured, 1)
require.Equal(t, "openai-pool-fake.test", captured[0].host)
require.True(t, strings.HasSuffix(captured[0].path, "/responses/compact"), "path=%q", captured[0].path)
upstreamNone := &captureUpstream{}
routerNone, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{
group: newPoolPolicyGroup(nil),
accounts: []service.Account{
newPoolPolicyAccountWithMapping(4333, service.PlatformAnthropic, 0, map[string]any{"np-compact": "claude-sonnet-4-5"}),
newPoolPolicyAccountWithMapping(4334, service.PlatformGemini, 1, map[string]any{"np-compact": "gemini-3.1-pro"}),
},
upstream: upstreamNone,
})
wNone := postPoolPolicyRequest(t, routerNone, "/v1/responses/compact",
`{"model":"np-compact","input":"compact this"}`)
require.Equal(t, http.StatusBadRequest, wNone.Code, wNone.Body.String())
require.Contains(t, wNone.Body.String(), "/responses/compact")
require.Empty(t, upstreamNone.capturedSnapshot())
}
@@ -165,6 +165,7 @@ func (c *stickyMemoryGatewayCache) GetReasoningContent(context.Context, string)
type poolPolicyCapturedRequest struct {
accountID int64
host string
path string
body []byte
}
@@ -187,6 +188,7 @@ func (u *captureUpstream) capture(req *http.Request, accountID int64) []byte {
u.captured = append(u.captured, poolPolicyCapturedRequest{
accountID: accountID,
host: req.URL.Hostname(),
path: req.URL.Path,
body: body,
})
u.mu.Unlock()
@@ -210,6 +212,9 @@ func (u *captureUpstream) respondFor(req *http.Request) *http.Response {
Body: io.NopCloser(strings.NewReader(`{"error":{"message":"rate limited"}}`)),
}
}
if strings.HasSuffix(req.URL.Path, "/responses/compact") {
return compositeDispatchResponse("application/json", `{"id":"resp_compact","object":"response.compaction","output":[],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}`)
}
if strings.Contains(req.URL.Path, "/responses") {
sse := "event: response.completed\n" +
`data: {"type":"response.completed","response":{"id":"resp_pool","object":"response","status":"completed","model":"deepseek-chat","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}}` + "\n\n"