-
Notifications
You must be signed in to change notification settings - Fork 11.2k
fix(relay): inject channel system prompt for Claude/Gemini-format requests #5864
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
zhoubeiqing
wants to merge
1
commit into
QuantumNous:main
Choose a base branch
from
zhoubeiqing:fix/claude-channel-system-prompt
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| package relay | ||
|
|
||
| import ( | ||
| "strings" | ||
|
|
||
| "github.com/QuantumNous/new-api/common" | ||
| "github.com/QuantumNous/new-api/constant" | ||
| "github.com/QuantumNous/new-api/dto" | ||
| relaycommon "github.com/QuantumNous/new-api/relay/common" | ||
|
|
||
| "github.com/gin-gonic/gin" | ||
| ) | ||
|
|
||
| // applySystemPromptToOpenAIRequest injects the channel-level system prompt into an | ||
| // OpenAI-format request. When the request already contains a system message and | ||
| // SystemPromptOverride is disabled, the existing system message is left untouched. | ||
| func applySystemPromptToOpenAIRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.GeneralOpenAIRequest) { | ||
| if request == nil { | ||
| return | ||
| } | ||
| systemRole := request.GetSystemRoleName() | ||
| containSystemPrompt := false | ||
| for _, message := range request.Messages { | ||
| if message.Role == systemRole { | ||
| containSystemPrompt = true | ||
| break | ||
| } | ||
| } | ||
| if !containSystemPrompt { | ||
| systemMessage := dto.Message{ | ||
| Role: systemRole, | ||
| Content: info.ChannelSetting.SystemPrompt, | ||
| } | ||
| request.Messages = append([]dto.Message{systemMessage}, request.Messages...) | ||
| return | ||
| } | ||
| if !info.ChannelSetting.SystemPromptOverride { | ||
| return | ||
| } | ||
| common.SetContextKey(c, constant.ContextKeySystemPromptOverride, true) | ||
| for i, message := range request.Messages { | ||
| if message.Role != systemRole { | ||
| continue | ||
| } | ||
| if message.IsStringContent() { | ||
| request.Messages[i].SetStringContent(info.ChannelSetting.SystemPrompt + "\n" + message.StringContent()) | ||
| } else { | ||
| contents := message.ParseContent() | ||
| contents = append([]dto.MediaContent{ | ||
| { | ||
| Type: dto.ContentTypeText, | ||
| Text: info.ChannelSetting.SystemPrompt, | ||
| }, | ||
| }, contents...) | ||
| request.Messages[i].Content = contents | ||
| } | ||
| break | ||
| } | ||
| } | ||
|
|
||
| // applySystemPromptToClaudeRequest injects the channel-level system prompt into a | ||
| // Claude-format request. Mirrors the behavior previously inlined in ClaudeHelper. | ||
| func applySystemPromptToClaudeRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.ClaudeRequest) { | ||
| if request == nil { | ||
| return | ||
| } | ||
| if request.System == nil { | ||
| request.SetStringSystem(info.ChannelSetting.SystemPrompt) | ||
| return | ||
| } | ||
| if !info.ChannelSetting.SystemPromptOverride { | ||
| return | ||
| } | ||
| common.SetContextKey(c, constant.ContextKeySystemPromptOverride, true) | ||
| if request.IsStringSystem() { | ||
| existing := strings.TrimSpace(request.GetStringSystem()) | ||
| if existing == "" { | ||
| request.SetStringSystem(info.ChannelSetting.SystemPrompt) | ||
| } else { | ||
| request.SetStringSystem(info.ChannelSetting.SystemPrompt + "\n" + existing) | ||
| } | ||
| return | ||
| } | ||
| systemContents := request.ParseSystem() | ||
| newSystem := dto.ClaudeMediaMessage{Type: dto.ContentTypeText} | ||
| newSystem.SetText(info.ChannelSetting.SystemPrompt) | ||
| if len(systemContents) == 0 { | ||
| request.System = []dto.ClaudeMediaMessage{newSystem} | ||
| } else { | ||
| request.System = append([]dto.ClaudeMediaMessage{newSystem}, systemContents...) | ||
| } | ||
| } | ||
|
|
||
| // applySystemPromptToGeminiRequest injects the channel-level system prompt into a | ||
| // Gemini-format request. Mirrors the behavior previously inlined in GeminiHelper. | ||
| func applySystemPromptToGeminiRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.GeminiChatRequest) { | ||
| if request == nil { | ||
| return | ||
| } | ||
| if request.SystemInstructions == nil { | ||
| request.SystemInstructions = &dto.GeminiChatContent{ | ||
| Parts: []dto.GeminiPart{ | ||
| {Text: info.ChannelSetting.SystemPrompt}, | ||
| }, | ||
| } | ||
| return | ||
| } | ||
| if len(request.SystemInstructions.Parts) == 0 { | ||
| request.SystemInstructions.Parts = []dto.GeminiPart{{Text: info.ChannelSetting.SystemPrompt}} | ||
| return | ||
| } | ||
| if !info.ChannelSetting.SystemPromptOverride { | ||
| return | ||
| } | ||
| common.SetContextKey(c, constant.ContextKeySystemPromptOverride, true) | ||
| merged := false | ||
| for i := range request.SystemInstructions.Parts { | ||
| if request.SystemInstructions.Parts[i].Text == "" { | ||
| continue | ||
| } | ||
| request.SystemInstructions.Parts[i].Text = info.ChannelSetting.SystemPrompt + "\n" + request.SystemInstructions.Parts[i].Text | ||
| merged = true | ||
| break | ||
| } | ||
| if !merged { | ||
| request.SystemInstructions.Parts = append([]dto.GeminiPart{{Text: info.ChannelSetting.SystemPrompt}}, request.SystemInstructions.Parts...) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| package relay | ||
|
|
||
| import ( | ||
| "net/http/httptest" | ||
| "testing" | ||
|
|
||
| "github.com/QuantumNous/new-api/common" | ||
| "github.com/QuantumNous/new-api/constant" | ||
| "github.com/QuantumNous/new-api/dto" | ||
| relaycommon "github.com/QuantumNous/new-api/relay/common" | ||
| "github.com/gin-gonic/gin" | ||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func newRelayInfoWithSystemPrompt(systemPrompt string, override bool) *relaycommon.RelayInfo { | ||
| info := &relaycommon.RelayInfo{} | ||
| info.ChannelSetting.SystemPrompt = systemPrompt | ||
| info.ChannelSetting.SystemPromptOverride = override | ||
| return info | ||
| } | ||
|
|
||
| func newTestGinContext() *gin.Context { | ||
| c, _ := gin.CreateTestContext(httptest.NewRecorder()) | ||
| return c | ||
| } | ||
|
|
||
| func TestApplySystemPromptToClaudeRequest_InjectsWhenAbsent(t *testing.T) { | ||
| info := newRelayInfoWithSystemPrompt("hide model info", false) | ||
| request := &dto.ClaudeRequest{System: nil} | ||
| applySystemPromptToClaudeRequest(newTestGinContext(), info, request) | ||
| require.True(t, request.IsStringSystem()) | ||
| assert.Equal(t, "hide model info", request.GetStringSystem()) | ||
| } | ||
|
|
||
| func TestApplySystemPromptToClaudeRequest_NoOverrideKeepsExisting(t *testing.T) { | ||
| info := newRelayInfoWithSystemPrompt("hide model info", false) | ||
| request := &dto.ClaudeRequest{System: "keep me"} | ||
| applySystemPromptToClaudeRequest(newTestGinContext(), info, request) | ||
| require.True(t, request.IsStringSystem()) | ||
| assert.Equal(t, "keep me", request.GetStringSystem()) | ||
| assert.False(t, common.GetContextKeyBool(newTestGinContext(), constant.ContextKeySystemPromptOverride)) | ||
| } | ||
|
|
||
| func TestApplySystemPromptToClaudeRequest_OverrideStringPrepends(t *testing.T) { | ||
| c := newTestGinContext() | ||
| info := newRelayInfoWithSystemPrompt("hide model info", true) | ||
| request := &dto.ClaudeRequest{System: "keep me"} | ||
| applySystemPromptToClaudeRequest(c, info, request) | ||
| require.True(t, request.IsStringSystem()) | ||
| assert.Equal(t, "hide model info\nkeep me", request.GetStringSystem()) | ||
| assert.True(t, common.GetContextKeyBool(c, constant.ContextKeySystemPromptOverride)) | ||
| } | ||
|
|
||
| func TestApplySystemPromptToOpenAIRequest_InjectsWhenAbsent(t *testing.T) { | ||
| info := newRelayInfoWithSystemPrompt("hide model info", false) | ||
| request := &dto.GeneralOpenAIRequest{ | ||
| Model: "gpt-test", | ||
| Messages: []dto.Message{ | ||
| {Role: "user", Content: "hi"}, | ||
| }, | ||
| } | ||
| applySystemPromptToOpenAIRequest(newTestGinContext(), info, request) | ||
| require.Len(t, request.Messages, 2) | ||
| assert.Equal(t, "system", request.Messages[0].Role) | ||
| assert.Equal(t, "hide model info", request.Messages[0].StringContent()) | ||
| } | ||
|
|
||
| func TestApplySystemPromptToGeminiRequest_InjectsWhenAbsent(t *testing.T) { | ||
| info := newRelayInfoWithSystemPrompt("hide model info", false) | ||
| request := &dto.GeminiChatRequest{} | ||
| applySystemPromptToGeminiRequest(newTestGinContext(), info, request) | ||
| require.NotNil(t, request.SystemInstructions) | ||
| require.Len(t, request.SystemInstructions.Parts, 1) | ||
| assert.Equal(t, "hide model info", request.SystemInstructions.Parts[0].Text) | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Assertion checks the wrong context instance.
Line 42 creates a brand-new
newTestGinContext()instead of reusing thecpassed toapplySystemPromptToClaudeRequestat line 39. Since each call togin.CreateTestContext()returns an independent context, this assertion always evaluates against an untouched context and will pass regardless of whether the override key was incorrectly set on the real context — it doesn't actually verify the "no override" invariant.As per path instructions, "Backend tests must protect real behavior, API contracts, billing/accounting invariants, data compatibility, or regression paths."
🐛 Proposed fix
func TestApplySystemPromptToClaudeRequest_NoOverrideKeepsExisting(t *testing.T) { + c := newTestGinContext() info := newRelayInfoWithSystemPrompt("hide model info", false) request := &dto.ClaudeRequest{System: "keep me"} - applySystemPromptToClaudeRequest(newTestGinContext(), info, request) + applySystemPromptToClaudeRequest(c, info, request) require.True(t, request.IsStringSystem()) assert.Equal(t, "keep me", request.GetStringSystem()) - assert.False(t, common.GetContextKeyBool(newTestGinContext(), constant.ContextKeySystemPromptOverride)) + assert.False(t, common.GetContextKeyBool(c, constant.ContextKeySystemPromptOverride)) }📝 Committable suggestion
🤖 Prompt for AI Agents
Source: Path instructions