mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 00:05:30 +00:00
Merge pull request #8499 from feeeei/fix/openai-passthrough-instructions-echo
fix(openai): 透传放行空 instructions,响应回显按客户端原值还原
This commit is contained in:
9 files changed
+400
-96
No files matched your search
@@ -2343,8 +2343,7 @@ func isOpsLocalBusinessLimitError(code string, msg string) bool {
|
||||
(strings.Contains(msg, "beta feature ") && strings.Contains(msg, " is not allowed")) ||
|
||||
(strings.Contains(msg, "openai service_tier=") && strings.Contains(msg, " is not allowed for model")) ||
|
||||
strings.Contains(msg, "this account only allows codex official clients") ||
|
||||
strings.Contains(msg, "openai wsv1 is temporarily unsupported") ||
|
||||
strings.Contains(msg, "openai codex passthrough requires a non-empty instructions field")
|
||||
strings.Contains(msg, "openai wsv1 is temporarily unsupported")
|
||||
}
|
||||
|
||||
func hasOpsUpstreamErrorContext(c *gin.Context) bool {
|
||||
|
||||
@@ -1324,15 +1324,6 @@ func TestClassifyOpsLocalBusinessLimitErrorsExcludedFromSLA(t *testing.T) {
|
||||
wantErrType: "invalid_request_error",
|
||||
wantPhase: "request",
|
||||
},
|
||||
{
|
||||
name: "openai passthrough instructions policy block",
|
||||
errType: "forbidden_error",
|
||||
message: "OpenAI codex passthrough requires a non-empty instructions field",
|
||||
code: "",
|
||||
status: http.StatusForbidden,
|
||||
wantErrType: "forbidden_error",
|
||||
wantPhase: "request",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
@@ -1561,12 +1552,6 @@ func TestClassifyOpsUpstreamAuthTextStillCountsForSLA(t *testing.T) {
|
||||
code: "400",
|
||||
status: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "provider passthrough instructions shaped error",
|
||||
message: "OpenAI codex passthrough requires a non-empty instructions field",
|
||||
code: "403",
|
||||
status: http.StatusForbidden,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
|
||||
@@ -33,6 +33,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
clearOpenAIResponsesClientToolMapping(c)
|
||||
clearOpenAIResponsesNamespaceNames(c)
|
||||
setCodexToolNameReverse(c, nil)
|
||||
rememberOpenAIResponsesClientInstructions(c, body)
|
||||
if _, err := s.prepareCodexAccountIdentitySource(ctx, c, account); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -1042,6 +1043,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
upstreamCtx, releaseUpstreamCtx, startTime.Add(firstOutputTimeout),
|
||||
)
|
||||
}
|
||||
syncOpenAIResponsesInstructionsEcho(c, body)
|
||||
upstreamReq, err := s.buildUpstreamRequest(upstreamCtx, c, account, body, token, reqStream, promptCacheKey, isCodexCLI)
|
||||
if headerGuard == nil {
|
||||
releaseUpstreamCtx()
|
||||
|
||||
@@ -151,18 +151,6 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough(
|
||||
}
|
||||
|
||||
if account != nil && account.UsesOpenAICodexProtocol() {
|
||||
if rejectReason := detectOpenAIPassthroughInstructionsRejectReason(reqModel, body); rejectReason != "" {
|
||||
rejectMsg := "OpenAI codex passthrough requires a non-empty instructions field"
|
||||
MarkOpsClientBusinessLimited(c, OpsClientBusinessLimitedReasonLocalPolicyDenied)
|
||||
logOpenAIPassthroughInstructionsRejected(ctx, c, account, reqModel, rejectReason, body)
|
||||
c.JSON(http.StatusForbidden, gin.H{
|
||||
"error": gin.H{
|
||||
"type": "forbidden_error",
|
||||
"message": rejectMsg,
|
||||
},
|
||||
})
|
||||
return nil, fmt.Errorf("openai passthrough rejected before upstream: %s", rejectReason)
|
||||
}
|
||||
if isOpenAICodexModel(reqModel) && !gjson.GetBytes(body, "instructions").Exists() {
|
||||
nextBody, setErr := sjson.SetBytes(body, "instructions", defaultCodexSynthInstructions(reqModel))
|
||||
if setErr != nil {
|
||||
@@ -376,6 +364,7 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough(
|
||||
}
|
||||
SetOpsUpstreamModel(c, actualModel)
|
||||
upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx)
|
||||
syncOpenAIResponsesInstructionsEcho(c, body)
|
||||
upstreamReq, buildErr := s.buildUpstreamRequestOpenAIPassthrough(upstreamCtx, c, account, body, token)
|
||||
releaseUpstreamCtx()
|
||||
if buildErr != nil {
|
||||
@@ -553,37 +542,6 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough(
|
||||
return forwardResult, nil
|
||||
}
|
||||
|
||||
func logOpenAIPassthroughInstructionsRejected(
|
||||
ctx context.Context,
|
||||
c *gin.Context,
|
||||
account *Account,
|
||||
reqModel string,
|
||||
rejectReason string,
|
||||
body []byte,
|
||||
) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
accountID := int64(0)
|
||||
accountName := ""
|
||||
accountType := ""
|
||||
if account != nil {
|
||||
accountID = account.ID
|
||||
accountName = strings.TrimSpace(account.Name)
|
||||
accountType = strings.TrimSpace(string(account.Type))
|
||||
}
|
||||
fields := []zap.Field{
|
||||
zap.String("component", "service.openai_gateway"),
|
||||
zap.Int64("account_id", accountID),
|
||||
zap.String("account_name", accountName),
|
||||
zap.String("account_type", accountType),
|
||||
zap.String("request_model", strings.TrimSpace(reqModel)),
|
||||
zap.String("reject_reason", strings.TrimSpace(rejectReason)),
|
||||
}
|
||||
fields = appendCodexCLIOnlyRejectedRequestFields(fields, c, body)
|
||||
logger.FromContext(ctx).With(fields...).Warn("OpenAI passthrough 本地拦截:Codex 请求缺少有效 instructions")
|
||||
}
|
||||
|
||||
func (s *OpenAIGatewayService) buildUpstreamRequestOpenAIPassthrough(
|
||||
ctx context.Context,
|
||||
c *gin.Context,
|
||||
@@ -2066,6 +2024,7 @@ func (s *OpenAIGatewayService) handleStreamingResponsePassthrough(
|
||||
return resultWithUsage(), fmt.Errorf("restore OpenAI passthrough namespace response: %w", restoreErr)
|
||||
}
|
||||
restoredData = restoreCodexToolNamesFromSSEContext(c, restoredData, rawEventType)
|
||||
restoredData = restoreOpenAIResponsesInstructionsEchoInEvent(c, restoredData)
|
||||
if !bytes.Equal(restoredData, dataBytes) {
|
||||
dataBytes = restoredData
|
||||
trimmedData = strings.TrimSpace(string(restoredData))
|
||||
@@ -2378,6 +2337,7 @@ func (s *OpenAIGatewayService) handleNonStreamingResponsePassthrough(
|
||||
return nil, fmt.Errorf("restore OpenAI passthrough namespace response: %w", err)
|
||||
}
|
||||
body = restoreCodexToolNamesFromContext(c, body)
|
||||
body = restoreOpenAIResponsesInstructionsEchoInResponse(c, body)
|
||||
body, err = restoreOpenAIResponsesClientToolPayload(c, body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("restore OpenAI Responses client tools: %w", err)
|
||||
@@ -2445,11 +2405,12 @@ func (s *OpenAIGatewayService) handlePassthroughSSEToJSON(resp *http.Response, c
|
||||
return nil, fmt.Errorf("restore OpenAI passthrough namespace response: %w", restoreErr)
|
||||
}
|
||||
restoredBody = restoreCodexToolNamesFromContext(c, restoredBody)
|
||||
body = restoredBody
|
||||
body = restoreOpenAIResponsesInstructionsEchoInResponse(c, restoredBody)
|
||||
} else {
|
||||
if originalModel != "" && mappedModel != "" && originalModel != mappedModel {
|
||||
bodyText = s.replaceModelInSSEBody(bodyText, mappedModel, originalModel)
|
||||
}
|
||||
bodyText = restoreOpenAIResponsesInstructionsEchoInSSEBody(c, bodyText)
|
||||
body = []byte(bodyText)
|
||||
}
|
||||
|
||||
|
||||
@@ -1691,24 +1691,6 @@ func normalizeOpenAIPassthroughOAuthBody(body []byte, compact bool) ([]byte, boo
|
||||
return normalized, changed, nil
|
||||
}
|
||||
|
||||
func detectOpenAIPassthroughInstructionsRejectReason(reqModel string, body []byte) string {
|
||||
if !isOpenAICodexModel(reqModel) {
|
||||
return ""
|
||||
}
|
||||
|
||||
instructions := gjson.GetBytes(body, "instructions")
|
||||
if !instructions.Exists() {
|
||||
return ""
|
||||
}
|
||||
if instructions.Type != gjson.String {
|
||||
return "instructions_not_string"
|
||||
}
|
||||
if strings.TrimSpace(instructions.String()) == "" {
|
||||
return "instructions_empty"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func isOpenAICodexModel(model string) bool {
|
||||
return strings.Contains(strings.ToLower(strings.TrimSpace(model)), "codex")
|
||||
}
|
||||
|
||||
@@ -653,6 +653,7 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context.
|
||||
return
|
||||
}
|
||||
restoredData = restoreCodexToolNamesFromSSEContext(c, restoredData, eventType)
|
||||
restoredData = restoreOpenAIResponsesInstructionsEchoInEvent(c, restoredData)
|
||||
if !bytes.Equal(restoredData, dataBytes) {
|
||||
dataBytes = restoredData
|
||||
data = string(restoredData)
|
||||
@@ -1674,6 +1675,7 @@ func (s *OpenAIGatewayService) handleNonStreamingResponse(ctx context.Context, r
|
||||
return nil, fmt.Errorf("restore OpenAI namespace response: %w", err)
|
||||
}
|
||||
body = restoreCodexToolNamesFromContext(c, body)
|
||||
body = restoreOpenAIResponsesInstructionsEchoInResponse(c, body)
|
||||
body = ensureOpenAIResponseObjectCreatedAt(body)
|
||||
responseheaders.WriteFilteredHeaders(c.Writer.Header(), resp.Header, s.responseHeaderFilter)
|
||||
// Codex 协议要求 /responses/compact JSON 响应携带 x-codex-turn-state
|
||||
@@ -1778,11 +1780,13 @@ func (s *OpenAIGatewayService) handleSSEToJSON(resp *http.Response, c *gin.Conte
|
||||
return nil, fmt.Errorf("restore OpenAI namespace response: %w", restoreErr)
|
||||
}
|
||||
restoredBody = restoreCodexToolNamesFromContext(c, restoredBody)
|
||||
restoredBody = restoreOpenAIResponsesInstructionsEchoInResponse(c, restoredBody)
|
||||
body = ensureOpenAIResponseObjectCreatedAt(restoredBody)
|
||||
} else {
|
||||
if originalModel != mappedModel {
|
||||
bodyText = s.replaceModelInSSEBody(bodyText, mappedModel, originalModel)
|
||||
}
|
||||
bodyText = restoreOpenAIResponsesInstructionsEchoInSSEBody(c, bodyText)
|
||||
body = []byte(bodyText)
|
||||
}
|
||||
|
||||
|
||||
@@ -358,20 +358,3 @@ func TestNormalizeOpenAIPassthroughOAuthBody_ArrayInputUnchanged(t *testing.T) {
|
||||
require.Len(t, input.Array(), 1)
|
||||
require.Equal(t, "message", input.Array()[0].Get("type").String())
|
||||
}
|
||||
|
||||
func TestDetectOpenAIPassthroughInstructionsRejectReason(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
body string
|
||||
want string
|
||||
}{
|
||||
{name: "missing is optional", body: `{"model":"gpt-5.1-codex"}`, want: ""},
|
||||
{name: "non string remains rejected", body: `{"instructions":{"text":"invalid"}}`, want: "instructions_not_string"},
|
||||
{name: "empty remains rejected", body: `{"instructions":" "}`, want: "instructions_empty"},
|
||||
{name: "non empty remains accepted", body: `{"instructions":"client guidance"}`, want: ""},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
require.Equal(t, tt.want, detectOpenAIPassthroughInstructionsRejectReason("gpt-5.1-codex", []byte(tt.body)))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
)
|
||||
|
||||
// Responses 的 response 对象回显上游实际收到的 instructions。网关补写、追加或
|
||||
// 搬运 instructions 后,回显按客户端请求里的原始取值还原;客户端未传时还原为 null。
|
||||
|
||||
const (
|
||||
openAIResponsesClientInstructionsKey = "openai_responses_client_instructions"
|
||||
openAIResponsesInstructionsEchoRestoreKey = "openai_responses_instructions_echo_restore"
|
||||
)
|
||||
|
||||
var openAIResponsesInstructionsFieldMarker = []byte(`"instructions"`)
|
||||
|
||||
type openAIResponsesClientInstructions struct {
|
||||
// raw 是客户端 instructions 压缩成单行后的 JSON;未传时为空串。
|
||||
// 单行保证还原值写回 SSE data 行时不会拆帧。
|
||||
raw string
|
||||
}
|
||||
|
||||
// rememberOpenAIResponsesClientInstructions 记录本次转发尝试的客户端原始
|
||||
// instructions,并清空还原值,使未登记上游请求体的转发分支不做还原。
|
||||
func rememberOpenAIResponsesClientInstructions(c *gin.Context, body []byte) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
raw := ""
|
||||
if value := gjson.GetBytes(body, "instructions"); value.Exists() {
|
||||
raw = compactOpenAIResponsesInstructionsRaw(value.Raw)
|
||||
}
|
||||
c.Set(openAIResponsesClientInstructionsKey, openAIResponsesClientInstructions{raw: raw})
|
||||
c.Set(openAIResponsesInstructionsEchoRestoreKey, "")
|
||||
}
|
||||
|
||||
// syncOpenAIResponsesInstructionsEcho 比较即将发往上游的 instructions 与客户端
|
||||
// 原始取值,不一致时登记回显还原值。
|
||||
func syncOpenAIResponsesInstructionsEcho(c *gin.Context, upstreamBody []byte) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
stored, ok := c.Get(openAIResponsesClientInstructionsKey)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
client, ok := stored.(openAIResponsesClientInstructions)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
upstreamRaw := ""
|
||||
if value := gjson.GetBytes(upstreamBody, "instructions"); value.Exists() {
|
||||
upstreamRaw = value.Raw
|
||||
}
|
||||
restore := ""
|
||||
if !openAIResponsesInstructionsRawEqual(client.raw, upstreamRaw) {
|
||||
restore = client.raw
|
||||
if restore == "" {
|
||||
restore = "null"
|
||||
}
|
||||
}
|
||||
c.Set(openAIResponsesInstructionsEchoRestoreKey, restore)
|
||||
}
|
||||
|
||||
// compactOpenAIResponsesInstructionsRaw 去掉 JSON 值里的格式空白;无法解析时
|
||||
// 返回 null。
|
||||
func compactOpenAIResponsesInstructionsRaw(raw string) string {
|
||||
var buf bytes.Buffer
|
||||
if err := json.Compact(&buf, []byte(raw)); err != nil {
|
||||
return "null"
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func openAIResponsesInstructionsRawEqual(left, right string) bool {
|
||||
if left == right {
|
||||
return true
|
||||
}
|
||||
if left == "" || right == "" {
|
||||
return false
|
||||
}
|
||||
l := gjson.Parse(left)
|
||||
r := gjson.Parse(right)
|
||||
if l.Type != r.Type {
|
||||
return false
|
||||
}
|
||||
if l.Type == gjson.String {
|
||||
return l.Str == r.Str
|
||||
}
|
||||
return compactOpenAIResponsesInstructionsRaw(l.Raw) == compactOpenAIResponsesInstructionsRaw(r.Raw)
|
||||
}
|
||||
|
||||
func openAIResponsesInstructionsEchoRestoreValue(c *gin.Context) string {
|
||||
if c == nil {
|
||||
return ""
|
||||
}
|
||||
stored, ok := c.Get(openAIResponsesInstructionsEchoRestoreKey)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
restore, _ := stored.(string)
|
||||
return restore
|
||||
}
|
||||
|
||||
func restoreOpenAIResponsesInstructionsAtPath(data []byte, path, restore string) []byte {
|
||||
if restore == "" || !bytes.Contains(data, openAIResponsesInstructionsFieldMarker) {
|
||||
return data
|
||||
}
|
||||
if !gjson.GetBytes(data, path).Exists() {
|
||||
return data
|
||||
}
|
||||
restored, err := sjson.SetRawBytes(data, path, []byte(restore))
|
||||
if err != nil {
|
||||
return data
|
||||
}
|
||||
return restored
|
||||
}
|
||||
|
||||
// restoreOpenAIResponsesInstructionsEchoInEvent 还原单个 SSE 事件里
|
||||
// response.instructions 的回显。
|
||||
func restoreOpenAIResponsesInstructionsEchoInEvent(c *gin.Context, data []byte) []byte {
|
||||
return restoreOpenAIResponsesInstructionsAtPath(data, "response.instructions", openAIResponsesInstructionsEchoRestoreValue(c))
|
||||
}
|
||||
|
||||
// restoreOpenAIResponsesInstructionsEchoInResponse 还原非流式 response 对象里
|
||||
// instructions 的回显。
|
||||
func restoreOpenAIResponsesInstructionsEchoInResponse(c *gin.Context, body []byte) []byte {
|
||||
return restoreOpenAIResponsesInstructionsAtPath(body, "instructions", openAIResponsesInstructionsEchoRestoreValue(c))
|
||||
}
|
||||
|
||||
// restoreOpenAIResponsesInstructionsEchoInSSEBody 逐个 data 行还原整段 SSE 文本里的回显。
|
||||
func restoreOpenAIResponsesInstructionsEchoInSSEBody(c *gin.Context, body string) string {
|
||||
restore := openAIResponsesInstructionsEchoRestoreValue(c)
|
||||
if restore == "" || !strings.Contains(body, `"instructions"`) {
|
||||
return body
|
||||
}
|
||||
lines := strings.Split(body, "\n")
|
||||
changed := false
|
||||
for i, line := range lines {
|
||||
data, ok := extractOpenAISSEDataLine(line)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
restored := restoreOpenAIResponsesInstructionsAtPath([]byte(data), "response.instructions", restore)
|
||||
if string(restored) == data {
|
||||
continue
|
||||
}
|
||||
lines[i] = "data: " + string(restored)
|
||||
changed = true
|
||||
}
|
||||
if !changed {
|
||||
return body
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
const instructionsEchoMarker = "UPSTREAM-ECHOED-INSTRUCTIONS"
|
||||
|
||||
func instructionsEchoUpstreamSSE(echo string) string {
|
||||
return strings.Join([]string{
|
||||
`data: {"type":"response.created","response":{"id":"resp_echo","status":"in_progress","instructions":` + echo + `}}`,
|
||||
"",
|
||||
`data: {"type":"response.output_text.delta","delta":"OK"}`,
|
||||
"",
|
||||
`data: {"type":"response.completed","response":{"id":"resp_echo","status":"completed","instructions":` + echo + `,"output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"OK"}]}],"usage":{"input_tokens":11,"output_tokens":5,"total_tokens":16}}}`,
|
||||
"",
|
||||
"data: [DONE]",
|
||||
"",
|
||||
}, "\n")
|
||||
}
|
||||
|
||||
func instructionsEchoUpstream(echo string) *httpUpstreamRecorder {
|
||||
return &httpUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid_echo"}},
|
||||
Body: io.NopCloser(strings.NewReader(instructionsEchoUpstreamSSE(echo))),
|
||||
}}
|
||||
}
|
||||
|
||||
func instructionsEchoOAuthAccount(passthrough bool) *Account {
|
||||
account := &Account{
|
||||
ID: 501, Name: "oauth", Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1,
|
||||
Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-acc"},
|
||||
Status: StatusActive, Schedulable: true, RateMultiplier: f64p(1),
|
||||
}
|
||||
if passthrough {
|
||||
account.Extra = map[string]any{"openai_passthrough": true}
|
||||
}
|
||||
return account
|
||||
}
|
||||
|
||||
func instructionsEchoForward(t *testing.T, account *Account, upstream *httpUpstreamRecorder, body string) (*OpenAIForwardResult, *httptest.ResponseRecorder, error) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(nil))
|
||||
c.Request.Header.Set("User-Agent", "OpenAI/Python 2.8.0")
|
||||
SetOpenAIClientTransport(c, OpenAIClientTransportHTTP)
|
||||
svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream}
|
||||
result, err := svc.Forward(context.Background(), c, account, []byte(body))
|
||||
return result, rec, err
|
||||
}
|
||||
|
||||
func sseResponseInstructions(t *testing.T, body, eventType string) gjson.Result {
|
||||
t.Helper()
|
||||
for _, line := range strings.Split(body, "\n") {
|
||||
data, ok := extractOpenAISSEDataLine(line)
|
||||
if !ok || gjson.Get(data, "type").String() != eventType {
|
||||
continue
|
||||
}
|
||||
return gjson.Get(data, "response.instructions")
|
||||
}
|
||||
t.Fatalf("event %s not found in body: %s", eventType, body)
|
||||
return gjson.Result{}
|
||||
}
|
||||
|
||||
func TestOpenAIResponsesInstructionsEchoRestoreHelpers(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
clientBody string
|
||||
upstream string
|
||||
wantRestore string
|
||||
}{
|
||||
{name: "missing then injected restores null", clientBody: `{"model":"m"}`, upstream: `{"instructions":"injected"}`, wantRestore: "null"},
|
||||
{name: "blank then injected restores blank", clientBody: `{"instructions":" "}`, upstream: `{"instructions":"injected"}`, wantRestore: `" "`},
|
||||
{name: "client text appended restores client text", clientBody: `{"instructions":"mine"}`, upstream: `{"instructions":"mine\n\nbridge"}`, wantRestore: `"mine"`},
|
||||
{name: "unchanged text keeps upstream echo", clientBody: `{"instructions":"mine"}`, upstream: `{"instructions":"mine"}`, wantRestore: ""},
|
||||
{name: "escaped spelling of same text keeps upstream echo", clientBody: `{"instructions":"a\/b"}`, upstream: `{"instructions":"a/b"}`, wantRestore: ""},
|
||||
{name: "reformatted object keeps upstream echo", clientBody: "{\"instructions\": {\n \"k\": [1, 2]\n}}", upstream: `{"instructions":{"k":[1,2]}}`, wantRestore: ""},
|
||||
{name: "multi-line object then injected restores single line", clientBody: "{\"instructions\": [\n {\"role\": \"developer\", \"content\": \"x\"}\n]}", upstream: `{"instructions":"injected"}`, wantRestore: `[{"role":"developer","content":"x"}]`},
|
||||
{name: "missing on both sides keeps upstream echo", clientBody: `{"model":"m"}`, upstream: `{"model":"m"}`, wantRestore: ""},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
rememberOpenAIResponsesClientInstructions(c, []byte(tt.clientBody))
|
||||
syncOpenAIResponsesInstructionsEcho(c, []byte(tt.upstream))
|
||||
require.Equal(t, tt.wantRestore, openAIResponsesInstructionsEchoRestoreValue(c))
|
||||
})
|
||||
}
|
||||
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
event := []byte(`{"type":"response.created","response":{"id":"r","instructions":"injected"}}`)
|
||||
delta := []byte(`{"type":"response.output_text.delta","delta":"the word \"instructions\" in text"}`)
|
||||
require.Equal(t, event, restoreOpenAIResponsesInstructionsEchoInEvent(c, event), "unregistered context must not rewrite")
|
||||
|
||||
rememberOpenAIResponsesClientInstructions(c, []byte(`{"model":"m"}`))
|
||||
syncOpenAIResponsesInstructionsEcho(c, []byte(`{"instructions":"injected"}`))
|
||||
require.JSONEq(t, `{"type":"response.created","response":{"id":"r","instructions":null}}`, string(restoreOpenAIResponsesInstructionsEchoInEvent(c, event)))
|
||||
require.Equal(t, delta, restoreOpenAIResponsesInstructionsEchoInEvent(c, delta))
|
||||
require.JSONEq(t, `{"id":"r","instructions":null}`, string(restoreOpenAIResponsesInstructionsEchoInResponse(c, []byte(`{"id":"r","instructions":"injected"}`))))
|
||||
sseBody := "event: response.created\ndata: " + string(event) + "\n\ndata: " + string(delta) + "\n"
|
||||
restoredSSE := restoreOpenAIResponsesInstructionsEchoInSSEBody(c, sseBody)
|
||||
require.NotContains(t, restoredSSE, `"instructions":"injected"`)
|
||||
require.Contains(t, restoredSSE, `"instructions":null`)
|
||||
require.Contains(t, restoredSSE, string(delta))
|
||||
|
||||
rememberOpenAIResponsesClientInstructions(c, []byte(`{"model":"m"}`))
|
||||
require.Equal(t, event, restoreOpenAIResponsesInstructionsEchoInEvent(c, event), "a new attempt clears the previous restore value")
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayService_OAuthPassthrough_CodexBlankInstructionsForwardedAsIs(t *testing.T) {
|
||||
for _, raw := range []string{`""`, `" "`, `{"text":"x"}`} {
|
||||
t.Run(raw, func(t *testing.T) {
|
||||
upstream := instructionsEchoUpstream(raw)
|
||||
result, rec, err := instructionsEchoForward(t, instructionsEchoOAuthAccount(true), upstream,
|
||||
`{"model":"gpt-5.3-codex","stream":true,"instructions":`+raw+`,"input":[{"type":"message","role":"user","content":"Hi"}]}`)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
require.JSONEq(t, raw, gjson.GetBytes(upstream.lastBody, "instructions").Raw)
|
||||
require.JSONEq(t, raw, sseResponseInstructions(t, rec.Body.String(), "response.completed").Raw)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayService_OAuthPassthrough_MissingInstructionsForwardedWithoutField(t *testing.T) {
|
||||
upstream := instructionsEchoUpstream("null")
|
||||
result, rec, err := instructionsEchoForward(t, instructionsEchoOAuthAccount(true), upstream,
|
||||
`{"model":"gpt-6.1-sol","stream":true,"input":[{"type":"message","role":"user","content":"Hi"}]}`)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.False(t, gjson.GetBytes(upstream.lastBody, "instructions").Exists())
|
||||
require.Equal(t, gjson.Null, sseResponseInstructions(t, rec.Body.String(), "response.created").Type)
|
||||
require.Equal(t, gjson.Null, sseResponseInstructions(t, rec.Body.String(), "response.completed").Type)
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayService_OAuthPassthrough_InjectedCodexInstructionsEchoRestored(t *testing.T) {
|
||||
upstream := instructionsEchoUpstream(`"` + instructionsEchoMarker + `"`)
|
||||
result, rec, err := instructionsEchoForward(t, instructionsEchoOAuthAccount(true), upstream,
|
||||
`{"model":"gpt-5.3-codex","stream":true,"input":[{"type":"message","role":"user","content":"Hi"}]}`)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.NotEmpty(t, gjson.GetBytes(upstream.lastBody, "instructions").String())
|
||||
require.NotContains(t, rec.Body.String(), instructionsEchoMarker)
|
||||
require.Equal(t, gjson.Null, sseResponseInstructions(t, rec.Body.String(), "response.created").Type)
|
||||
require.Equal(t, gjson.Null, sseResponseInstructions(t, rec.Body.String(), "response.completed").Type)
|
||||
|
||||
nonStreamUpstream := instructionsEchoUpstream(`"` + instructionsEchoMarker + `"`)
|
||||
result, rec, err = instructionsEchoForward(t, instructionsEchoOAuthAccount(true), nonStreamUpstream,
|
||||
`{"model":"gpt-5.3-codex","stream":false,"input":[{"type":"message","role":"user","content":"Hi"}]}`)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.NotContains(t, rec.Body.String(), instructionsEchoMarker)
|
||||
instructions := gjson.Get(rec.Body.String(), "instructions")
|
||||
require.True(t, instructions.Exists())
|
||||
require.Equal(t, gjson.Null, instructions.Type)
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayService_OAuthResponses_MultiLineInstructionsEchoKeepsSSEFraming(t *testing.T) {
|
||||
upstream := instructionsEchoUpstream(`"` + instructionsEchoMarker + `"`)
|
||||
result, rec, err := instructionsEchoForward(t, instructionsEchoOAuthAccount(false), upstream,
|
||||
"{\"model\":\"gpt-6.1-sol\",\"stream\":true,\"instructions\": [\n {\"role\": \"developer\", \"content\": \"x\"}\n],\"input\":[{\"type\":\"message\",\"role\":\"user\",\"content\":\"Hi\"}]}")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.NotContains(t, rec.Body.String(), instructionsEchoMarker)
|
||||
for _, line := range strings.Split(rec.Body.String(), "\n") {
|
||||
if strings.TrimSpace(line) == "" || strings.HasPrefix(line, "event:") || strings.HasPrefix(line, ":") {
|
||||
continue
|
||||
}
|
||||
data, ok := extractOpenAISSEDataLine(line)
|
||||
require.True(t, ok, "unexpected non-data line %q", line)
|
||||
if data == "[DONE]" {
|
||||
continue
|
||||
}
|
||||
require.True(t, gjson.Valid(data), "data line must stay a complete JSON document: %q", data)
|
||||
}
|
||||
require.JSONEq(t, `[{"role":"developer","content":"x"}]`, sseResponseInstructions(t, rec.Body.String(), "response.completed").Raw)
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayService_OAuthResponses_InjectedInstructionsEchoRestored(t *testing.T) {
|
||||
t.Run("stream", func(t *testing.T) {
|
||||
upstream := instructionsEchoUpstream(`"` + instructionsEchoMarker + `"`)
|
||||
result, rec, err := instructionsEchoForward(t, instructionsEchoOAuthAccount(false), upstream,
|
||||
`{"model":"gpt-6.1-sol","stream":true,"input":[{"type":"message","role":"user","content":"Hi"}]}`)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.NotEmpty(t, gjson.GetBytes(upstream.lastBody, "instructions").String())
|
||||
require.NotContains(t, rec.Body.String(), instructionsEchoMarker)
|
||||
require.Equal(t, gjson.Null, sseResponseInstructions(t, rec.Body.String(), "response.created").Type)
|
||||
require.Equal(t, gjson.Null, sseResponseInstructions(t, rec.Body.String(), "response.completed").Type)
|
||||
})
|
||||
|
||||
t.Run("non-stream", func(t *testing.T) {
|
||||
upstream := instructionsEchoUpstream(`"` + instructionsEchoMarker + `"`)
|
||||
result, rec, err := instructionsEchoForward(t, instructionsEchoOAuthAccount(false), upstream,
|
||||
`{"model":"gpt-6.1-sol","stream":false,"input":[{"type":"message","role":"user","content":"Hi"}]}`)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.NotContains(t, rec.Body.String(), instructionsEchoMarker)
|
||||
instructions := gjson.Get(rec.Body.String(), "instructions")
|
||||
require.True(t, instructions.Exists())
|
||||
require.Equal(t, gjson.Null, instructions.Type)
|
||||
})
|
||||
|
||||
t.Run("client instructions kept", func(t *testing.T) {
|
||||
upstream := instructionsEchoUpstream(`"client rule"`)
|
||||
result, rec, err := instructionsEchoForward(t, instructionsEchoOAuthAccount(false), upstream,
|
||||
`{"model":"gpt-6.1-sol","stream":true,"instructions":"client rule","input":[{"type":"message","role":"user","content":"Hi"}]}`)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.Equal(t, "client rule", gjson.GetBytes(upstream.lastBody, "instructions").String())
|
||||
require.Equal(t, "client rule", sseResponseInstructions(t, rec.Body.String(), "response.completed").String())
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user