* test(relayconvert): add golden snapshot matrix and relaykit boundary guard Phase 0 of the relaykit extraction plan: pin byte-level output of every registered (from,to) request/response/stream conversion route, and forbid kit-bound packages from growing host-only imports. * wip(relayconvert): drop gin.Context from converter signatures; add convmeta draft Phase 1 in progress: relayconvert now takes context.Context; host media resolver adapts gin.Context back at the service boundary. * refactor(relayconvert): decouple converters from RelayInfo, gin, and settings Phase 1 of the relaykit extraction plan: - converters now depend on convmeta.Meta (implemented by RelayInfo) instead of *relaycommon.RelayInfo; ClaudeConvertInfo and the format guesser move to convmeta with aliases left behind - host settings reach converters via a convmeta.Options snapshot built in RelayInfo.ConvOptions; no more model_setting/reasoning global reads inside the conversion layer - effort-suffix helpers move to service/relayconvert/reasoning (old package forwards); chat-to-responses upgrade policy moves to service (host routing logic, not conversion) - golden conversion matrix unchanged * test(relayconvert): tighten boundary — kit packages now free of gin/setting imports * refactor(dto): drop gin and logger dependencies Phase 2 (part 1): dto.Request.IsStream now takes *http.Request instead of *gin.Context (Gemini's impl reads query/path off the std request); dto's three logger calls become common.SysError. Boundary test allowlist is now empty — kit-bound packages import no gin/setting/logger/model. * refactor(kit): extract dependency-free kitutil; dto/types/relayconvert stop importing common Phase 2 of the relaykit extraction plan: - new service/relayconvert/kitutil holds the pure helpers the kit needs (JSON wrappers, pointer/string/uuid/timestamp utils, MaskSensitiveInfo, pluggable LogInfo/LogError hooks, Debug flag) - dto, types, and all relayconvert packages now use kitutil; their only remaining internal deps are dto/types/constant - common keeps every original symbol (MaskSensitiveInfo delegates to kitutil) so host code is untouched; main.go routes kit logging into common.SysLog/SysError and mirrors DebugEnabled - golden conversion matrix unchanged * refactor(kit): move EndpointType/FinishReason to types; OpenRouter dialect via Options Kit packages (dto/types/relayconvert/reasonmap) no longer import constant: - EndpointType and finish-reason values live in types; constant re-exports - the OpenRouter special-case in claude->openai request conversion reads Options.OpenRouterDialect, set by the host from the channel type; InitChannelMeta invalidates the cached snapshot on channel switch * refactor: extract relaykit submodule (dto/types/relayconvert/reasonmap) Phase 3 of the relaykit extraction plan: - new go module github.com/QuantumNous/new-api/relaykit containing dto (minus task family), types, relayconvert (with convmeta/kitutil/reasoning), and reasonmap; host consumes it via require + replace, go.work for dev - task-family dto (task/suno/midjourney/video) stays in the host dto package; dual-consumer host files alias it as taskdto - relaykit builds and tests standalone (GOWORK=off): no host imports, no gin, no DB, no settings - golden conversion matrix unchanged * build(docker): copy relaykit/go.mod before go mod download The local-replace submodule's go.mod must exist inside the build context for the main module graph to resolve. * fix: address relaykit extraction regressions * fix: address relaykit review regressions * docs: document Meta nil receiver contract * fix(relaykit): fail OpenAI→Claude conversion without max_tokens; reject negative default_max_tokens The Claude Messages API requires max_tokens (omitting it is a 400 "Field required"), but with a nil Options.Claude.DefaultMaxTokens hook the converters silently emitted a request the upstream is guaranteed to reject. Both OpenAI Chat and Responses → Claude conversions now return sharedclaude.ErrMissingMaxTokens when no path (client value, default hook, thinking-adapter floor) supplied one. Unreachable in the host, which always configures the hook. Host side, claude.default_max_tokens now rejects negative values at the option API before persisting — they would wrap into huge unsigned values during conversion. Zero stays allowed: the current API treats max_tokens: 0 as cache pre-warming. * fix: make Gemini safety settings read path race-free
353 lines
9.5 KiB
Go
353 lines
9.5 KiB
Go
package controller
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/QuantumNous/new-api/common"
|
|
"github.com/QuantumNous/new-api/constant"
|
|
"github.com/QuantumNous/new-api/model"
|
|
"github.com/QuantumNous/new-api/relay"
|
|
"github.com/QuantumNous/new-api/relay/channel/ai360"
|
|
"github.com/QuantumNous/new-api/relay/channel/lingyiwanwu"
|
|
"github.com/QuantumNous/new-api/relay/channel/minimax"
|
|
"github.com/QuantumNous/new-api/relay/channel/moonshot"
|
|
relaycommon "github.com/QuantumNous/new-api/relay/common"
|
|
"github.com/QuantumNous/new-api/relay/helper"
|
|
"github.com/QuantumNous/new-api/relaykit/dto"
|
|
"github.com/QuantumNous/new-api/relaykit/types"
|
|
"github.com/QuantumNous/new-api/service"
|
|
"github.com/QuantumNous/new-api/setting/operation_setting"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/samber/lo"
|
|
)
|
|
|
|
// https://platform.openai.com/docs/api-reference/models/list
|
|
|
|
var openAIModels []dto.OpenAIModels
|
|
var openAIModelsMap map[string]dto.OpenAIModels
|
|
var channelId2Models map[int][]string
|
|
|
|
func init() {
|
|
// https://platform.openai.com/docs/models/model-endpoint-compatibility
|
|
for i := 0; i < constant.APITypeDummy; i++ {
|
|
if i == constant.APITypeAIProxyLibrary {
|
|
continue
|
|
}
|
|
adaptor := relay.GetAdaptor(i)
|
|
channelName := adaptor.GetChannelName()
|
|
modelNames := adaptor.GetModelList()
|
|
for _, modelName := range modelNames {
|
|
openAIModels = append(openAIModels, dto.OpenAIModels{
|
|
Id: modelName,
|
|
Object: "model",
|
|
Created: 1626777600,
|
|
OwnedBy: channelName,
|
|
})
|
|
}
|
|
}
|
|
for _, modelName := range ai360.ModelList {
|
|
openAIModels = append(openAIModels, dto.OpenAIModels{
|
|
Id: modelName,
|
|
Object: "model",
|
|
Created: 1626777600,
|
|
OwnedBy: ai360.ChannelName,
|
|
})
|
|
}
|
|
for _, modelName := range moonshot.ModelList {
|
|
openAIModels = append(openAIModels, dto.OpenAIModels{
|
|
Id: modelName,
|
|
Object: "model",
|
|
Created: 1626777600,
|
|
OwnedBy: moonshot.ChannelName,
|
|
})
|
|
}
|
|
for _, modelName := range lingyiwanwu.ModelList {
|
|
openAIModels = append(openAIModels, dto.OpenAIModels{
|
|
Id: modelName,
|
|
Object: "model",
|
|
Created: 1626777600,
|
|
OwnedBy: lingyiwanwu.ChannelName,
|
|
})
|
|
}
|
|
for _, modelName := range minimax.ModelList {
|
|
openAIModels = append(openAIModels, dto.OpenAIModels{
|
|
Id: modelName,
|
|
Object: "model",
|
|
Created: 1626777600,
|
|
OwnedBy: minimax.ChannelName,
|
|
})
|
|
}
|
|
for modelName, _ := range constant.MidjourneyModel2Action {
|
|
openAIModels = append(openAIModels, dto.OpenAIModels{
|
|
Id: modelName,
|
|
Object: "model",
|
|
Created: 1626777600,
|
|
OwnedBy: "midjourney",
|
|
})
|
|
}
|
|
openAIModelsMap = make(map[string]dto.OpenAIModels)
|
|
for _, aiModel := range openAIModels {
|
|
openAIModelsMap[aiModel.Id] = aiModel
|
|
}
|
|
channelId2Models = make(map[int][]string)
|
|
for i := 1; i <= constant.ChannelTypeDummy; i++ {
|
|
apiType, success := common.ChannelType2APIType(i)
|
|
if !success || apiType == constant.APITypeAIProxyLibrary {
|
|
continue
|
|
}
|
|
meta := &relaycommon.RelayInfo{ChannelMeta: &relaycommon.ChannelMeta{
|
|
ChannelType: i,
|
|
}}
|
|
adaptor := relay.GetAdaptor(apiType)
|
|
adaptor.Init(meta)
|
|
channelId2Models[i] = adaptor.GetModelList()
|
|
}
|
|
openAIModels = lo.UniqBy(openAIModels, func(m dto.OpenAIModels) string {
|
|
return m.Id
|
|
})
|
|
}
|
|
|
|
func channelOwnerName(channelType int) string {
|
|
apiType, success := common.ChannelType2APIType(channelType)
|
|
if !success {
|
|
return strings.ToLower(constant.GetChannelTypeName(channelType))
|
|
}
|
|
adaptor := relay.GetAdaptor(apiType)
|
|
if adaptor == nil {
|
|
return strings.ToLower(constant.GetChannelTypeName(channelType))
|
|
}
|
|
adaptor.Init(&relaycommon.RelayInfo{ChannelMeta: &relaycommon.ChannelMeta{
|
|
ChannelType: channelType,
|
|
}})
|
|
if name := strings.TrimSpace(adaptor.GetChannelName()); name != "" {
|
|
return name
|
|
}
|
|
return strings.ToLower(constant.GetChannelTypeName(channelType))
|
|
}
|
|
|
|
func getPreferredModelOwners(modelNames []string, groups []string) map[string]string {
|
|
channelTypes, err := model.GetPreferredModelOwnerChannelTypes(modelNames, groups)
|
|
if err != nil {
|
|
common.SysLog(fmt.Sprintf("GetPreferredModelOwnerChannelTypes error: %v", err))
|
|
return map[string]string{}
|
|
}
|
|
|
|
ownerByChannelType := make(map[int]string)
|
|
owners := make(map[string]string, len(channelTypes))
|
|
for modelName, channelType := range channelTypes {
|
|
owner, ok := ownerByChannelType[channelType]
|
|
if !ok {
|
|
owner = channelOwnerName(channelType)
|
|
ownerByChannelType[channelType] = owner
|
|
}
|
|
if owner != "" {
|
|
owners[modelName] = owner
|
|
}
|
|
}
|
|
return owners
|
|
}
|
|
|
|
func buildOpenAIModel(modelName string, ownerByModel map[string]string) dto.OpenAIModels {
|
|
var oaiModel dto.OpenAIModels
|
|
if staticModel, ok := openAIModelsMap[modelName]; ok {
|
|
oaiModel = staticModel
|
|
} else {
|
|
oaiModel = dto.OpenAIModels{
|
|
Id: modelName,
|
|
Object: "model",
|
|
Created: 1626777600,
|
|
OwnedBy: "custom",
|
|
}
|
|
}
|
|
if owner, ok := ownerByModel[modelName]; ok && owner != "" {
|
|
oaiModel.OwnedBy = owner
|
|
}
|
|
oaiModel.SupportedEndpointTypes = model.GetModelSupportEndpointTypes(modelName)
|
|
return oaiModel
|
|
}
|
|
|
|
type modelListGroups struct {
|
|
userGroup string
|
|
tokenGroup string
|
|
ownerGroups []string
|
|
}
|
|
|
|
func getModelListGroups(c *gin.Context) (modelListGroups, error) {
|
|
tokenGroup := common.GetContextKeyString(c, constant.ContextKeyTokenGroup)
|
|
userGroup := common.GetContextKeyString(c, constant.ContextKeyUserGroup)
|
|
if userGroup == "" && (tokenGroup == "" || tokenGroup == "auto") {
|
|
var err error
|
|
userGroup, err = model.GetUserGroup(c.GetInt("id"), false)
|
|
if err != nil {
|
|
return modelListGroups{}, err
|
|
}
|
|
}
|
|
|
|
if tokenGroup == "auto" {
|
|
return modelListGroups{
|
|
userGroup: userGroup,
|
|
tokenGroup: tokenGroup,
|
|
ownerGroups: service.GetUserAutoGroup(userGroup),
|
|
}, nil
|
|
}
|
|
|
|
group := userGroup
|
|
if tokenGroup != "" {
|
|
group = tokenGroup
|
|
}
|
|
return modelListGroups{
|
|
userGroup: userGroup,
|
|
tokenGroup: tokenGroup,
|
|
ownerGroups: []string{group},
|
|
}, nil
|
|
}
|
|
|
|
func ListModels(c *gin.Context, modelType int) {
|
|
acceptUnsetRatioModel := operation_setting.SelfUseModeEnabled
|
|
if !acceptUnsetRatioModel {
|
|
userId := c.GetInt("id")
|
|
if userId > 0 {
|
|
userSettings, _ := model.GetUserSetting(userId, false)
|
|
if userSettings.AcceptUnsetRatioModel {
|
|
acceptUnsetRatioModel = true
|
|
}
|
|
}
|
|
}
|
|
|
|
userModelNames := make([]string, 0)
|
|
groups, err := getModelListGroups(c)
|
|
if err != nil {
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"success": false,
|
|
"message": "get user group failed",
|
|
})
|
|
return
|
|
}
|
|
ownerGroups := groups.ownerGroups
|
|
modelLimitEnable := common.GetContextKeyBool(c, constant.ContextKeyTokenModelLimitEnabled)
|
|
if modelLimitEnable {
|
|
s, ok := common.GetContextKey(c, constant.ContextKeyTokenModelLimit)
|
|
var tokenModelLimit map[string]bool
|
|
if ok {
|
|
tokenModelLimit = s.(map[string]bool)
|
|
} else {
|
|
tokenModelLimit = map[string]bool{}
|
|
}
|
|
for allowModel, _ := range tokenModelLimit {
|
|
if !acceptUnsetRatioModel {
|
|
if !helper.HasModelBillingConfig(allowModel) {
|
|
continue
|
|
}
|
|
}
|
|
userModelNames = append(userModelNames, allowModel)
|
|
}
|
|
} else {
|
|
models := service.GetGroupsEnabledModels(ownerGroups)
|
|
for _, modelName := range models {
|
|
if !acceptUnsetRatioModel {
|
|
if !helper.HasModelBillingConfig(modelName) {
|
|
continue
|
|
}
|
|
}
|
|
userModelNames = append(userModelNames, modelName)
|
|
}
|
|
}
|
|
|
|
ownerByModel := map[string]string{}
|
|
if len(ownerGroups) > 0 {
|
|
ownerByModel = getPreferredModelOwners(userModelNames, ownerGroups)
|
|
}
|
|
userOpenAiModels := make([]dto.OpenAIModels, 0, len(userModelNames))
|
|
for _, modelName := range userModelNames {
|
|
userOpenAiModels = append(userOpenAiModels, buildOpenAIModel(modelName, ownerByModel))
|
|
}
|
|
|
|
switch modelType {
|
|
case constant.ChannelTypeAnthropic:
|
|
useranthropicModels := make([]dto.AnthropicModel, len(userOpenAiModels))
|
|
for i, model := range userOpenAiModels {
|
|
useranthropicModels[i] = dto.AnthropicModel{
|
|
ID: model.Id,
|
|
CreatedAt: time.Unix(int64(model.Created), 0).UTC().Format(time.RFC3339),
|
|
DisplayName: model.Id,
|
|
Type: "model",
|
|
}
|
|
}
|
|
c.JSON(200, gin.H{
|
|
"data": useranthropicModels,
|
|
"first_id": useranthropicModels[0].ID,
|
|
"has_more": false,
|
|
"last_id": useranthropicModels[len(useranthropicModels)-1].ID,
|
|
})
|
|
case constant.ChannelTypeGemini:
|
|
userGeminiModels := make([]dto.GeminiModel, len(userOpenAiModels))
|
|
for i, model := range userOpenAiModels {
|
|
userGeminiModels[i] = dto.GeminiModel{
|
|
Name: model.Id,
|
|
DisplayName: model.Id,
|
|
}
|
|
}
|
|
c.JSON(200, gin.H{
|
|
"models": userGeminiModels,
|
|
"nextPageToken": nil,
|
|
})
|
|
default:
|
|
c.JSON(200, gin.H{
|
|
"success": true,
|
|
"data": userOpenAiModels,
|
|
"object": "list",
|
|
})
|
|
}
|
|
}
|
|
|
|
func ChannelListModels(c *gin.Context) {
|
|
c.JSON(200, gin.H{
|
|
"success": true,
|
|
"data": openAIModels,
|
|
})
|
|
}
|
|
|
|
func DashboardListModels(c *gin.Context) {
|
|
c.JSON(200, gin.H{
|
|
"success": true,
|
|
"data": channelId2Models,
|
|
})
|
|
}
|
|
|
|
func EnabledListModels(c *gin.Context) {
|
|
c.JSON(200, gin.H{
|
|
"success": true,
|
|
"data": model.GetEnabledModels(),
|
|
})
|
|
}
|
|
|
|
func RetrieveModel(c *gin.Context, modelType int) {
|
|
modelId := c.Param("model")
|
|
if aiModel, ok := openAIModelsMap[modelId]; ok {
|
|
switch modelType {
|
|
case constant.ChannelTypeAnthropic:
|
|
c.JSON(200, dto.AnthropicModel{
|
|
ID: aiModel.Id,
|
|
CreatedAt: time.Unix(int64(aiModel.Created), 0).UTC().Format(time.RFC3339),
|
|
DisplayName: aiModel.Id,
|
|
Type: "model",
|
|
})
|
|
default:
|
|
c.JSON(200, aiModel)
|
|
}
|
|
} else {
|
|
openAIError := types.OpenAIError{
|
|
Message: fmt.Sprintf("The model '%s' does not exist", modelId),
|
|
Type: "invalid_request_error",
|
|
Param: "model",
|
|
Code: "model_not_found",
|
|
}
|
|
c.JSON(200, gin.H{
|
|
"error": openAIError,
|
|
})
|
|
}
|
|
}
|