feat: 算力引擎 Go 后端核心(new-api)
- 统一 OpenAI 兼容 /v1 中继 + 渠道/额度/令牌/流水 - 各领域包:relay 模型网关、model 数据层、controller 管理 API
This commit is contained in:
@@ -0,0 +1,200 @@
|
||||
package codex
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"github.com/QuantumNous/new-api/relay/channel"
|
||||
"github.com/QuantumNous/new-api/relay/channel/openai"
|
||||
relaycommon "github.com/QuantumNous/new-api/relay/common"
|
||||
relayconstant "github.com/QuantumNous/new-api/relay/constant"
|
||||
"github.com/QuantumNous/new-api/relaykit/dto"
|
||||
"github.com/QuantumNous/new-api/relaykit/types"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type Adaptor struct {
|
||||
}
|
||||
|
||||
func (a *Adaptor) ConvertGeminiRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.GeminiChatRequest) (any, error) {
|
||||
return nil, errors.New("codex channel: endpoint not supported")
|
||||
}
|
||||
|
||||
func (a *Adaptor) ConvertClaudeRequest(*gin.Context, *relaycommon.RelayInfo, *dto.ClaudeRequest) (any, error) {
|
||||
return nil, errors.New("codex channel: /v1/messages endpoint not supported")
|
||||
}
|
||||
|
||||
func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) {
|
||||
return nil, errors.New("codex channel: endpoint not supported")
|
||||
}
|
||||
|
||||
func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.ImageRequest) (any, error) {
|
||||
return nil, errors.New("codex channel: endpoint not supported")
|
||||
}
|
||||
|
||||
func (a *Adaptor) Init(info *relaycommon.RelayInfo) {
|
||||
}
|
||||
|
||||
func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.GeneralOpenAIRequest) (any, error) {
|
||||
return nil, errors.New("codex channel: /v1/chat/completions endpoint not supported")
|
||||
}
|
||||
|
||||
func (a *Adaptor) ConvertRerankRequest(c *gin.Context, relayMode int, request dto.RerankRequest) (any, error) {
|
||||
return nil, errors.New("codex channel: /v1/rerank endpoint not supported")
|
||||
}
|
||||
|
||||
func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.EmbeddingRequest) (any, error) {
|
||||
return nil, errors.New("codex channel: /v1/embeddings endpoint not supported")
|
||||
}
|
||||
|
||||
func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.OpenAIResponsesRequest) (any, error) {
|
||||
isCompact := info != nil && info.RelayMode == relayconstant.RelayModeResponsesCompact
|
||||
|
||||
if info != nil && info.ChannelSetting.SystemPrompt != "" {
|
||||
systemPrompt := info.ChannelSetting.SystemPrompt
|
||||
|
||||
if len(request.Instructions) == 0 {
|
||||
if b, err := common.Marshal(systemPrompt); err == nil {
|
||||
request.Instructions = b
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
} else if info.ChannelSetting.SystemPromptOverride {
|
||||
var existing string
|
||||
if err := common.Unmarshal(request.Instructions, &existing); err == nil {
|
||||
existing = strings.TrimSpace(existing)
|
||||
if existing == "" {
|
||||
if b, err := common.Marshal(systemPrompt); err == nil {
|
||||
request.Instructions = b
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
if b, err := common.Marshal(systemPrompt + "\n" + existing); err == nil {
|
||||
request.Instructions = b
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if b, err := common.Marshal(systemPrompt); err == nil {
|
||||
request.Instructions = b
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Codex backend requires the `instructions` field to be present.
|
||||
// Keep it consistent with Codex CLI behavior by defaulting to an empty string.
|
||||
if len(request.Instructions) == 0 {
|
||||
request.Instructions = json.RawMessage(`""`)
|
||||
}
|
||||
|
||||
if isCompact {
|
||||
return request, nil
|
||||
}
|
||||
// codex: store must be false
|
||||
request.Store = json.RawMessage("false")
|
||||
// rm max_output_tokens
|
||||
request.MaxOutputTokens = nil
|
||||
request.Temperature = nil
|
||||
request.FrequencyPenalty = nil
|
||||
request.PresencePenalty = nil
|
||||
return request, nil
|
||||
}
|
||||
|
||||
func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
|
||||
return channel.DoApiRequest(a, c, info, requestBody)
|
||||
}
|
||||
|
||||
func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *types.NewAPIError) {
|
||||
switch info.RelayMode {
|
||||
case relayconstant.RelayModeAlphaSearch:
|
||||
// Alpha search responses are handled by relay.AlphaSearchHelper.
|
||||
return nil, types.NewError(errors.New("codex channel: alpha search response should be handled by AlphaSearchHelper"), types.ErrorCodeInvalidRequest)
|
||||
case relayconstant.RelayModeResponsesCompact:
|
||||
return openai.OaiResponsesCompactionHandler(c, resp)
|
||||
case relayconstant.RelayModeResponses:
|
||||
if info.IsStream {
|
||||
return openai.OaiResponsesStreamHandler(c, info, resp)
|
||||
}
|
||||
return openai.OaiResponsesHandler(c, info, resp)
|
||||
default:
|
||||
return nil, types.NewError(errors.New("codex channel: endpoint not supported"), types.ErrorCodeInvalidRequest)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Adaptor) GetModelList() []string {
|
||||
return ModelList
|
||||
}
|
||||
|
||||
func (a *Adaptor) GetChannelName() string {
|
||||
return ChannelName
|
||||
}
|
||||
|
||||
func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
|
||||
var path string
|
||||
switch info.RelayMode {
|
||||
case relayconstant.RelayModeResponses:
|
||||
path = "/backend-api/codex/responses"
|
||||
case relayconstant.RelayModeResponsesCompact:
|
||||
path = "/backend-api/codex/responses/compact"
|
||||
case relayconstant.RelayModeAlphaSearch:
|
||||
path = "/backend-api/codex/alpha/search"
|
||||
default:
|
||||
return "", errors.New("codex channel: only /v1/responses, /v1/responses/compact and /v1/alpha/search are supported")
|
||||
}
|
||||
return relaycommon.GetFullRequestURL(info.ChannelBaseUrl, path, info.ChannelType), nil
|
||||
}
|
||||
|
||||
func (a *Adaptor) SetupRequestHeader(c *gin.Context, req *http.Header, info *relaycommon.RelayInfo) error {
|
||||
channel.SetupApiRequestHeader(info, c, req)
|
||||
|
||||
key := strings.TrimSpace(info.ApiKey)
|
||||
if !strings.HasPrefix(key, "{") {
|
||||
return errors.New("codex channel: key must be a JSON object")
|
||||
}
|
||||
|
||||
oauthKey, err := ParseOAuthKey(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
accessToken := strings.TrimSpace(oauthKey.AccessToken)
|
||||
accountID := strings.TrimSpace(oauthKey.AccountID)
|
||||
|
||||
if accessToken == "" {
|
||||
return errors.New("codex channel: access_token is required")
|
||||
}
|
||||
if accountID == "" {
|
||||
return errors.New("codex channel: account_id is required")
|
||||
}
|
||||
|
||||
req.Set("Authorization", "Bearer "+accessToken)
|
||||
req.Set("chatgpt-account-id", accountID)
|
||||
|
||||
if req.Get("OpenAI-Beta") == "" {
|
||||
req.Set("OpenAI-Beta", "responses=experimental")
|
||||
}
|
||||
if req.Get("originator") == "" {
|
||||
req.Set("originator", "codex_cli_rs")
|
||||
}
|
||||
|
||||
// chatgpt.com/backend-api/codex/responses is strict about Content-Type.
|
||||
// Clients may omit it or include parameters like `application/json; charset=utf-8`,
|
||||
// which can be rejected by the upstream. Force the exact media type.
|
||||
req.Set("Content-Type", "application/json")
|
||||
if info.IsStream {
|
||||
req.Set("Accept", "text/event-stream")
|
||||
} else if req.Get("Accept") == "" {
|
||||
req.Set("Accept", "application/json")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package codex
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/QuantumNous/new-api/constant"
|
||||
relaycommon "github.com/QuantumNous/new-api/relay/common"
|
||||
relayconstant "github.com/QuantumNous/new-api/relay/constant"
|
||||
"github.com/QuantumNous/new-api/relaykit/dto"
|
||||
"github.com/samber/lo"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestGetRequestURLAlphaSearch(t *testing.T) {
|
||||
adaptor := &Adaptor{}
|
||||
info := &relaycommon.RelayInfo{
|
||||
ChannelMeta: &relaycommon.ChannelMeta{
|
||||
ChannelType: constant.ChannelTypeCodex,
|
||||
ChannelBaseUrl: "https://chatgpt.com",
|
||||
},
|
||||
RelayMode: relayconstant.RelayModeAlphaSearch,
|
||||
}
|
||||
|
||||
url, err := adaptor.GetRequestURL(info)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "https://chatgpt.com/backend-api/codex/alpha/search", url)
|
||||
}
|
||||
|
||||
// The Codex backend rejects these fields, so the adaptor clears them rather
|
||||
// than forwarding what the client sent.
|
||||
func TestConvertOpenAIResponsesRequestDropsPenalties(t *testing.T) {
|
||||
adaptor := &Adaptor{}
|
||||
info := &relaycommon.RelayInfo{
|
||||
ChannelMeta: &relaycommon.ChannelMeta{ChannelType: constant.ChannelTypeCodex},
|
||||
RelayMode: relayconstant.RelayModeResponses,
|
||||
}
|
||||
|
||||
converted, err := adaptor.ConvertOpenAIResponsesRequest(nil, info, dto.OpenAIResponsesRequest{
|
||||
Model: "gpt-5-codex",
|
||||
Input: json.RawMessage(`"hello"`),
|
||||
MaxOutputTokens: lo.ToPtr(uint(128)),
|
||||
Temperature: lo.ToPtr(1.0),
|
||||
FrequencyPenalty: json.RawMessage(`1.5`),
|
||||
PresencePenalty: json.RawMessage(`1.5`),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
request, ok := converted.(dto.OpenAIResponsesRequest)
|
||||
require.True(t, ok)
|
||||
assert.Nil(t, request.MaxOutputTokens)
|
||||
assert.Nil(t, request.Temperature)
|
||||
assert.Nil(t, request.FrequencyPenalty)
|
||||
assert.Nil(t, request.PresencePenalty)
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package codex
|
||||
|
||||
var ModelList = []string{
|
||||
"gpt-5.6-sol",
|
||||
"gpt-5.6-terra",
|
||||
"gpt-5.6-luna",
|
||||
"gpt-5.5",
|
||||
"gpt-5.4",
|
||||
"gpt-5.4-mini",
|
||||
"gpt-5.3-codex-spark",
|
||||
"codex-auto-review",
|
||||
}
|
||||
|
||||
const ChannelName = "codex"
|
||||
@@ -0,0 +1,30 @@
|
||||
package codex
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
)
|
||||
|
||||
type OAuthKey struct {
|
||||
IDToken string `json:"id_token,omitempty"`
|
||||
AccessToken string `json:"access_token,omitempty"`
|
||||
RefreshToken string `json:"refresh_token,omitempty"`
|
||||
|
||||
AccountID string `json:"account_id,omitempty"`
|
||||
LastRefresh string `json:"last_refresh,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Type string `json:"type,omitempty"`
|
||||
Expired string `json:"expired,omitempty"`
|
||||
}
|
||||
|
||||
func ParseOAuthKey(raw string) (*OAuthKey, error) {
|
||||
if raw == "" {
|
||||
return nil, errors.New("codex channel: empty oauth key")
|
||||
}
|
||||
var key OAuthKey
|
||||
if err := common.Unmarshal([]byte(raw), &key); err != nil {
|
||||
return nil, errors.New("codex channel: invalid oauth key json")
|
||||
}
|
||||
return &key, nil
|
||||
}
|
||||
Reference in New Issue
Block a user