mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-10-14 20:12:39 +08:00
fix(moderation): handle trailing Anthropic system messages
This commit is contained in:
@@ -91,13 +91,19 @@ func (collector moderationTextCollector) collectLastAnthropicUserMessage(message
|
||||
if len(array) == 0 {
|
||||
return
|
||||
}
|
||||
last := array[len(array)-1]
|
||||
if strings.ToLower(strings.TrimSpace(last.Get("role").String())) != "user" {
|
||||
// Anthropic requests may append a system message after the user turn. It
|
||||
// does not represent a new model/tool turn, so retain the latest user
|
||||
// content while continuing to reject assistant/tool-ended loops.
|
||||
lastUser := len(array) - 1
|
||||
for lastUser >= 0 && strings.ToLower(strings.TrimSpace(array[lastUser].Get("role").String())) == "system" {
|
||||
lastUser--
|
||||
}
|
||||
if lastUser < 0 || strings.ToLower(strings.TrimSpace(array[lastUser].Get("role").String())) != "user" {
|
||||
return
|
||||
}
|
||||
var candidate []string
|
||||
var candidateImages []string
|
||||
collector.collectAnthropicUserContentValue(last.Get("content"), &candidate, &candidateImages)
|
||||
collector.collectAnthropicUserContentValue(array[lastUser].Get("content"), &candidate, &candidateImages)
|
||||
if normalizeContentModerationText(strings.Join(candidate, "\n")) == "" && len(candidateImages) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -50,6 +50,21 @@ func TestExtractContentModerationInput_AnthropicMultiTurnExtractsLatestUser(t *t
|
||||
require.Equal(t, "Q2", input.Text)
|
||||
}
|
||||
|
||||
func TestExtractContentModerationInput_AnthropicTrailingSystemExtractsLatestUser(t *testing.T) {
|
||||
body := []byte(`{
|
||||
"messages": [
|
||||
{"role":"user","content":"Q1"},
|
||||
{"role":"assistant","content":"A1"},
|
||||
{"role":"user","content":"Q2"},
|
||||
{"role":"system","content":"request metadata"}
|
||||
]
|
||||
}`)
|
||||
|
||||
input := ExtractContentModerationInput(ContentModerationProtocolAnthropicMessages, body)
|
||||
|
||||
require.Equal(t, "Q2", input.Text)
|
||||
}
|
||||
|
||||
func TestExtractContentModerationInput_AnthropicStreamResendExtractsResend(t *testing.T) {
|
||||
body := []byte(`{
|
||||
"messages": [
|
||||
|
||||
Reference in New Issue
Block a user