mirror of
https://github.com/router-for-me/CLIProxyAPI.git
synced 2026-02-02 20:40:52 +08:00
66 lines
2.3 KiB
Go
66 lines
2.3 KiB
Go
package responses
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"context"
|
|
"fmt"
|
|
|
|
"github.com/luispater/CLIProxyAPI/internal/misc"
|
|
"github.com/tidwall/gjson"
|
|
"github.com/tidwall/sjson"
|
|
)
|
|
|
|
// ConvertCodexResponseToOpenAIResponses converts OpenAI Chat Completions streaming chunks
|
|
// to OpenAI Responses SSE events (response.*).
|
|
func ConvertCodexResponseToOpenAIResponses(ctx context.Context, modelName string, originalRequestRawJSON, requestRawJSON, rawJSON []byte, param *any) []string {
|
|
if bytes.HasPrefix(rawJSON, []byte("data: ")) {
|
|
rawJSON = rawJSON[6:]
|
|
if typeResult := gjson.GetBytes(rawJSON, "type"); typeResult.Exists() {
|
|
typeStr := typeResult.String()
|
|
if typeStr == "response.created" || typeStr == "response.in_progress" || typeStr == "response.completed" {
|
|
instructions := misc.CodexInstructions
|
|
instructionsResult := gjson.GetBytes(rawJSON, "response.instructions")
|
|
if instructionsResult.Raw == instructions {
|
|
rawJSON, _ = sjson.SetBytes(rawJSON, "response.instructions", gjson.GetBytes(originalRequestRawJSON, "instructions").String())
|
|
}
|
|
}
|
|
}
|
|
return []string{fmt.Sprintf("data: %s", string(rawJSON))}
|
|
}
|
|
return []string{string(rawJSON)}
|
|
}
|
|
|
|
// ConvertCodexResponseToOpenAIResponsesNonStream builds a single Responses JSON
|
|
// from a non-streaming OpenAI Chat Completions response.
|
|
func ConvertCodexResponseToOpenAIResponsesNonStream(_ context.Context, _ string, originalRequestRawJSON, requestRawJSON, rawJSON []byte, _ *any) string {
|
|
scanner := bufio.NewScanner(bytes.NewReader(rawJSON))
|
|
buffer := make([]byte, 10240*1024)
|
|
scanner.Buffer(buffer, 10240*1024)
|
|
dataTag := []byte("data: ")
|
|
for scanner.Scan() {
|
|
line := scanner.Bytes()
|
|
|
|
if !bytes.HasPrefix(line, dataTag) {
|
|
continue
|
|
}
|
|
rawJSON = line[6:]
|
|
|
|
rootResult := gjson.ParseBytes(rawJSON)
|
|
// Verify this is a response.completed event
|
|
if rootResult.Get("type").String() != "response.completed" {
|
|
continue
|
|
}
|
|
responseResult := rootResult.Get("response")
|
|
template := responseResult.Raw
|
|
|
|
instructions := misc.CodexInstructions
|
|
instructionsResult := gjson.Get(template, "instructions")
|
|
if instructionsResult.Raw == instructions {
|
|
template, _ = sjson.Set(template, "instructions", gjson.GetBytes(originalRequestRawJSON, "instructions").String())
|
|
}
|
|
return template
|
|
}
|
|
return ""
|
|
}
|