mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 00:05:30 +00:00
fix(gateway): limit composite model rewrite to message_start events
On the Anthropic forward streaming path the public model was written into any event carrying a message object, while the API key passthrough path only rewrites message_start. Rewrite message_start only on both. The passthrough path also added a model field to a message_start that had none, which the non-streaming path does not do. Skip the rewrite when the field is absent.
This commit is contained in:
1 parent
aee71b85b9
commit
7349750c01
3 files changed
+81
-2
No files matched your search
@@ -218,3 +218,82 @@ func TestRestoreCompositeClientModelOnlyWhenRouteRewroteModel(t *testing.T) {
|
||||
noModel := []byte(`{"type":"error"}`)
|
||||
require.Equal(t, string(noModel), string(restoreCompositeClientModel(renamedCtx, noModel)))
|
||||
}
|
||||
|
||||
func forwardCompositeAnthropicStream(t *testing.T, newAccount func() *Account, upstreamSSE string) string {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
client := []byte(`{"model":"public-model","max_tokens":16,"stream":true,"messages":[{"role":"user","content":"hi"}]}`)
|
||||
ctx, body := routeCompositeBody(t, publicModelRoute(), CompositeRouteEndpointMessages, client)
|
||||
upstream := &anthropicHTTPUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
|
||||
Body: io.NopCloser(strings.NewReader(upstreamSSE)),
|
||||
}}
|
||||
svc := newForwardPartialUsageServiceForTest(upstream)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil).WithContext(ctx)
|
||||
parsed, err := ParseGatewayRequest(NewRequestBodyRef(body), PlatformAnthropic)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = svc.Forward(ctx, c, newAccount(), parsed)
|
||||
require.NoError(t, err)
|
||||
return rec.Body.String()
|
||||
}
|
||||
|
||||
func anthropicStreamEventData(t *testing.T, sse, eventType string) string {
|
||||
t.Helper()
|
||||
for _, line := range strings.Split(sse, "\n") {
|
||||
data, ok := strings.CutPrefix(line, "data:")
|
||||
data = strings.TrimSpace(data)
|
||||
if ok && gjson.Get(data, "type").String() == eventType {
|
||||
return data
|
||||
}
|
||||
}
|
||||
t.Fatalf("no %s event in stream:\n%s", eventType, sse)
|
||||
return ""
|
||||
}
|
||||
|
||||
func TestCompositeRouteStreamRewritesOnlyMessageStartModel(t *testing.T) {
|
||||
accounts := map[string]func() *Account{
|
||||
"oauth": newAnthropicOAuthAccountForPartialUsageTest,
|
||||
"apikey-passthrough": newAnthropicAPIKeyAccountForTest,
|
||||
}
|
||||
for accountName, newAccount := range accounts {
|
||||
t.Run(accountName, func(t *testing.T) {
|
||||
sse := forwardCompositeAnthropicStream(t, newAccount, strings.Join([]string{
|
||||
`event: message_start`,
|
||||
`data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":"claude-opus-5-5-20260901","content":[],"usage":{"input_tokens":1}}}`,
|
||||
"",
|
||||
`event: ping`,
|
||||
`data: {"type":"ping","message":{"model":"other-model"}}`,
|
||||
"",
|
||||
`event: message_delta`,
|
||||
`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`,
|
||||
"",
|
||||
`event: message_stop`,
|
||||
`data: {"type":"message_stop"}`,
|
||||
"",
|
||||
"",
|
||||
}, "\n"))
|
||||
|
||||
require.Equal(t, "public-model", gjson.Get(anthropicStreamEventData(t, sse, "message_start"), "message.model").String())
|
||||
require.Equal(t, "other-model", gjson.Get(anthropicStreamEventData(t, sse, "ping"), "message.model").String())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompositeRoutePassthroughStreamKeepsMessageStartWithoutModel(t *testing.T) {
|
||||
sse := forwardCompositeAnthropicStream(t, newAnthropicAPIKeyAccountForTest, strings.Join([]string{
|
||||
`event: message_start`,
|
||||
`data:{"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","content":[],"usage":{"input_tokens":1}}}`,
|
||||
"",
|
||||
`event: message_stop`,
|
||||
`data: {"type":"message_stop"}`,
|
||||
"",
|
||||
"",
|
||||
}, "\n"))
|
||||
|
||||
require.False(t, gjson.Get(anthropicStreamEventData(t, sse, "message_start"), "message.model").Exists())
|
||||
}
|
||||
@@ -561,7 +561,7 @@ func (s *GatewayService) handleStreamingResponseAnthropicAPIKeyPassthrough(
|
||||
}
|
||||
}
|
||||
|
||||
if data, ok := extractAnthropicSSEDataLine(line); ok && clientModel != "" && gjson.Get(data, "type").String() == "message_start" {
|
||||
if data, ok := extractAnthropicSSEDataLine(line); ok && clientModel != "" && gjson.Get(data, "type").String() == "message_start" && gjson.Get(data, "message.model").Exists() {
|
||||
if rewritten, err := sjson.Set(data, "message.model", clientModel); err == nil {
|
||||
line = "data: " + rewritten
|
||||
}
|
||||
|
||||
@@ -993,7 +993,7 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http
|
||||
}
|
||||
}
|
||||
}
|
||||
if clientModel != "" {
|
||||
if clientModel != "" && eventType == "message_start" {
|
||||
if msg, ok := event["message"].(map[string]any); ok {
|
||||
if _, ok := msg["model"].(string); ok {
|
||||
msg["model"] = clientModel
|
||||
|
||||
Reference in new issue
Block a user