fix: add newline separation for Claude Code system prompt

This commit is contained in:
cyhhao
2026-01-29 01:28:43 +08:00
parent 59231668c5
commit 31f817d189
2 changed files with 7 additions and 4 deletions

View File

@@ -123,7 +123,7 @@ func createTestPayload(modelID string) (map[string]any, error) {
"system": []map[string]any{ "system": []map[string]any{
{ {
"type": "text", "type": "text",
"text": "You are Claude Code, Anthropic's official CLI for Claude.", "text": claudeCodeSystemPrompt,
"cache_control": map[string]string{ "cache_control": map[string]string{
"type": "ephemeral", "type": "ephemeral",
}, },

View File

@@ -39,7 +39,9 @@ const (
claudeAPICountTokensURL = "https://api.anthropic.com/v1/messages/count_tokens?beta=true" claudeAPICountTokensURL = "https://api.anthropic.com/v1/messages/count_tokens?beta=true"
stickySessionTTL = time.Hour // 粘性会话TTL stickySessionTTL = time.Hour // 粘性会话TTL
defaultMaxLineSize = 40 * 1024 * 1024 defaultMaxLineSize = 40 * 1024 * 1024
claudeCodeSystemPrompt = "You are Claude Code, Anthropic's official CLI for Claude." // Keep a trailing blank line so that when upstream concatenates system strings,
// the injected Claude Code banner doesn't run into the next system instruction.
claudeCodeSystemPrompt = "You are Claude Code, Anthropic's official CLI for Claude.\n\n"
maxCacheControlBlocks = 4 // Anthropic API 允许的最大 cache_control 块数量 maxCacheControlBlocks = 4 // Anthropic API 允许的最大 cache_control 块数量
) )
@@ -2479,7 +2481,8 @@ func injectClaudeCodePrompt(body []byte, system any) []byte {
case nil: case nil:
newSystem = []any{claudeCodeBlock} newSystem = []any{claudeCodeBlock}
case string: case string:
if v == "" || v == claudeCodeSystemPrompt { // Be tolerant of older/newer clients that may differ only by trailing whitespace/newlines.
if strings.TrimSpace(v) == "" || strings.TrimSpace(v) == strings.TrimSpace(claudeCodeSystemPrompt) {
newSystem = []any{claudeCodeBlock} newSystem = []any{claudeCodeBlock}
} else { } else {
newSystem = []any{claudeCodeBlock, map[string]any{"type": "text", "text": v}} newSystem = []any{claudeCodeBlock, map[string]any{"type": "text", "text": v}}
@@ -2489,7 +2492,7 @@ func injectClaudeCodePrompt(body []byte, system any) []byte {
newSystem = append(newSystem, claudeCodeBlock) newSystem = append(newSystem, claudeCodeBlock)
for _, item := range v { for _, item := range v {
if m, ok := item.(map[string]any); ok { if m, ok := item.(map[string]any); ok {
if text, ok := m["text"].(string); ok && text == claudeCodeSystemPrompt { if text, ok := m["text"].(string); ok && strings.TrimSpace(text) == strings.TrimSpace(claudeCodeSystemPrompt) {
continue continue
} }
} }