mirror of
https://github.com/QuantumNous/new-api.git
synced 2026-04-15 21:07:26 +00:00
Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3a18c0ce9f | ||
|
|
929668bead | ||
|
|
06a78f9042 | ||
|
|
0f1c4c4ebe | ||
|
|
1bcf7a3c39 | ||
|
|
5f0b3f6d6f |
@@ -48,7 +48,7 @@ func testChannel(channel *model.Channel, testModel string) (err error, openAIErr
|
||||
if strings.Contains(strings.ToLower(testModel), "embedding") ||
|
||||
strings.HasPrefix(testModel, "m3e") || // m3e 系列模型
|
||||
strings.Contains(testModel, "bge-") || // bge 系列模型
|
||||
testModel == "text-embedding-v1" ||
|
||||
strings.Contains(testModel, "embed") ||
|
||||
channel.Type == common.ChannelTypeMokaAI { // 其他 embedding 模型
|
||||
requestPath = "/v1/embeddings" // 修改请求路径
|
||||
}
|
||||
@@ -84,6 +84,12 @@ func testChannel(channel *model.Channel, testModel string) (err error, openAIErr
|
||||
}
|
||||
}
|
||||
|
||||
cache, err := model.GetUserCache(1)
|
||||
if err != nil {
|
||||
return err, nil
|
||||
}
|
||||
cache.WriteContext(c)
|
||||
|
||||
c.Request.Header.Set("Authorization", "Bearer "+channel.Key)
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
c.Set("channel", channel.Type)
|
||||
|
||||
@@ -3,7 +3,7 @@ package model
|
||||
import (
|
||||
"one-api/common"
|
||||
"one-api/setting"
|
||||
"one-api/setting/model_setting"
|
||||
"one-api/setting/config"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -24,6 +24,8 @@ func AllOption() ([]*Option, error) {
|
||||
func InitOptionMap() {
|
||||
common.OptionMapRWMutex.Lock()
|
||||
common.OptionMap = make(map[string]string)
|
||||
|
||||
// 添加原有的系统配置
|
||||
common.OptionMap["FileUploadPermission"] = strconv.Itoa(common.FileUploadPermission)
|
||||
common.OptionMap["FileDownloadPermission"] = strconv.Itoa(common.FileDownloadPermission)
|
||||
common.OptionMap["ImageUploadPermission"] = strconv.Itoa(common.ImageUploadPermission)
|
||||
@@ -111,13 +113,16 @@ func InitOptionMap() {
|
||||
common.OptionMap["DemoSiteEnabled"] = strconv.FormatBool(setting.DemoSiteEnabled)
|
||||
common.OptionMap["ModelRequestRateLimitEnabled"] = strconv.FormatBool(setting.ModelRequestRateLimitEnabled)
|
||||
common.OptionMap["CheckSensitiveOnPromptEnabled"] = strconv.FormatBool(setting.CheckSensitiveOnPromptEnabled)
|
||||
//common.OptionMap["CheckSensitiveOnCompletionEnabled"] = strconv.FormatBool(constant.CheckSensitiveOnCompletionEnabled)
|
||||
common.OptionMap["StopOnSensitiveEnabled"] = strconv.FormatBool(setting.StopOnSensitiveEnabled)
|
||||
common.OptionMap["SensitiveWords"] = setting.SensitiveWordsToString()
|
||||
common.OptionMap["StreamCacheQueueLength"] = strconv.Itoa(setting.StreamCacheQueueLength)
|
||||
common.OptionMap["AutomaticDisableKeywords"] = setting.AutomaticDisableKeywordsToString()
|
||||
common.OptionMap["GeminiSafetySettings"] = model_setting.GeminiSafetySettingsJsonString()
|
||||
common.OptionMap["GeminiVersionSettings"] = model_setting.GeminiVersionSettingsJsonString()
|
||||
|
||||
// 自动添加所有注册的模型配置
|
||||
modelConfigs := config.GlobalConfig.ExportAllConfigs()
|
||||
for k, v := range modelConfigs {
|
||||
common.OptionMap[k] = v
|
||||
}
|
||||
|
||||
common.OptionMapRWMutex.Unlock()
|
||||
loadOptionsFromDatabase()
|
||||
@@ -161,6 +166,13 @@ func updateOptionMap(key string, value string) (err error) {
|
||||
common.OptionMapRWMutex.Lock()
|
||||
defer common.OptionMapRWMutex.Unlock()
|
||||
common.OptionMap[key] = value
|
||||
|
||||
// 检查是否是模型配置 - 使用更规范的方式处理
|
||||
if handleConfigUpdate(key, value) {
|
||||
return nil // 已由配置系统处理
|
||||
}
|
||||
|
||||
// 处理传统配置项...
|
||||
if strings.HasSuffix(key, "Permission") {
|
||||
intValue, _ := strconv.Atoi(value)
|
||||
switch key {
|
||||
@@ -235,9 +247,6 @@ func updateOptionMap(key string, value string) (err error) {
|
||||
setting.CheckSensitiveOnPromptEnabled = boolValue
|
||||
case "ModelRequestRateLimitEnabled":
|
||||
setting.ModelRequestRateLimitEnabled = boolValue
|
||||
|
||||
//case "CheckSensitiveOnCompletionEnabled":
|
||||
// constant.CheckSensitiveOnCompletionEnabled = boolValue
|
||||
case "StopOnSensitiveEnabled":
|
||||
setting.StopOnSensitiveEnabled = boolValue
|
||||
case "SMTPSSLEnabled":
|
||||
@@ -354,12 +363,33 @@ func updateOptionMap(key string, value string) (err error) {
|
||||
setting.SensitiveWordsFromString(value)
|
||||
case "AutomaticDisableKeywords":
|
||||
setting.AutomaticDisableKeywordsFromString(value)
|
||||
case "GeminiSafetySettings":
|
||||
model_setting.GeminiSafetySettingFromJsonString(value)
|
||||
case "GeminiVersionSettings":
|
||||
model_setting.GeminiVersionSettingFromJsonString(value)
|
||||
case "StreamCacheQueueLength":
|
||||
setting.StreamCacheQueueLength, _ = strconv.Atoi(value)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// handleConfigUpdate 处理分层配置更新,返回是否已处理
|
||||
func handleConfigUpdate(key, value string) bool {
|
||||
parts := strings.SplitN(key, ".", 2)
|
||||
if len(parts) != 2 {
|
||||
return false // 不是分层配置
|
||||
}
|
||||
|
||||
configName := parts[0]
|
||||
configKey := parts[1]
|
||||
|
||||
// 获取配置对象
|
||||
cfg := config.GlobalConfig.Get(configName)
|
||||
if cfg == nil {
|
||||
return false // 未注册的配置
|
||||
}
|
||||
|
||||
// 更新配置
|
||||
configMap := map[string]string{
|
||||
configKey: value,
|
||||
}
|
||||
config.UpdateConfigFromMap(cfg, configMap)
|
||||
|
||||
return true // 已处理
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"one-api/dto"
|
||||
"one-api/relay/channel/claude"
|
||||
relaycommon "one-api/relay/common"
|
||||
"one-api/setting/model_setting"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -38,6 +39,7 @@ func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
|
||||
}
|
||||
|
||||
func (a *Adaptor) SetupRequestHeader(c *gin.Context, req *http.Header, info *relaycommon.RelayInfo) error {
|
||||
model_setting.GetClaudeSettings().WriteHeaders(req)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -49,8 +51,10 @@ func (a *Adaptor) ConvertRequest(c *gin.Context, info *relaycommon.RelayInfo, re
|
||||
var claudeReq *claude.ClaudeRequest
|
||||
var err error
|
||||
claudeReq, err = claude.RequestOpenAI2ClaudeMessage(*request)
|
||||
|
||||
c.Set("request_model", request.Model)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.Set("request_model", claudeReq.Model)
|
||||
c.Set("converted_request", claudeReq)
|
||||
return claudeReq, err
|
||||
}
|
||||
@@ -64,7 +68,6 @@ func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.Rela
|
||||
return nil, errors.New("not implemented")
|
||||
}
|
||||
|
||||
|
||||
func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"one-api/dto"
|
||||
"one-api/relay/channel"
|
||||
relaycommon "one-api/relay/common"
|
||||
"one-api/setting/model_setting"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -55,6 +56,7 @@ func (a *Adaptor) SetupRequestHeader(c *gin.Context, req *http.Header, info *rel
|
||||
anthropicVersion = "2023-06-01"
|
||||
}
|
||||
req.Set("anthropic-version", anthropicVersion)
|
||||
model_setting.GetClaudeSettings().WriteHeaders(req)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"one-api/dto"
|
||||
relaycommon "one-api/relay/common"
|
||||
"one-api/service"
|
||||
"one-api/setting/model_setting"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -93,9 +94,10 @@ func RequestOpenAI2ClaudeMessage(textRequest dto.GeneralOpenAIRequest) (*ClaudeR
|
||||
Tools: claudeTools,
|
||||
}
|
||||
|
||||
if strings.HasSuffix(textRequest.Model, "-thinking") {
|
||||
if model_setting.GetClaudeSettings().ThinkingAdapterEnabled &&
|
||||
strings.HasSuffix(textRequest.Model, "-thinking") {
|
||||
if claudeRequest.MaxTokens == 0 {
|
||||
claudeRequest.MaxTokens = 8192
|
||||
claudeRequest.MaxTokens = uint(model_setting.GetClaudeSettings().ThinkingAdapterMaxTokens)
|
||||
}
|
||||
|
||||
// 因为BudgetTokens 必须大于1024
|
||||
@@ -106,7 +108,7 @@ func RequestOpenAI2ClaudeMessage(textRequest dto.GeneralOpenAIRequest) (*ClaudeR
|
||||
// BudgetTokens 为 max_tokens 的 80%
|
||||
claudeRequest.Thinking = &Thinking{
|
||||
Type: "enabled",
|
||||
BudgetTokens: int(float64(claudeRequest.MaxTokens) * 0.8),
|
||||
BudgetTokens: int(float64(claudeRequest.MaxTokens) * model_setting.GetClaudeSettings().ThinkingAdapterBudgetTokensPercentage),
|
||||
}
|
||||
// TODO: 临时处理
|
||||
// https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking#important-considerations-when-using-extended-thinking
|
||||
|
||||
@@ -28,6 +28,7 @@ var claudeModelMap = map[string]string{
|
||||
"claude-3-opus-20240229": "claude-3-opus@20240229",
|
||||
"claude-3-haiku-20240307": "claude-3-haiku@20240307",
|
||||
"claude-3-5-sonnet-20240620": "claude-3-5-sonnet@20240620",
|
||||
"claude-3-7-sonnet-20250219": "claude-3-7-sonnet@20250219",
|
||||
}
|
||||
|
||||
const anthropicVersion = "vertex-2023-10-16"
|
||||
@@ -132,7 +133,7 @@ func (a *Adaptor) ConvertRequest(c *gin.Context, info *relaycommon.RelayInfo, re
|
||||
if err = copier.Copy(vertexClaudeReq, claudeReq); err != nil {
|
||||
return nil, errors.New("failed to copy claude request")
|
||||
}
|
||||
c.Set("request_model", request.Model)
|
||||
c.Set("request_model", claudeReq.Model)
|
||||
return vertexClaudeReq, nil
|
||||
} else if a.RequestMode == RequestModeGemini {
|
||||
geminiRequest, err := gemini.CovertGemini2OpenAI(*request)
|
||||
@@ -156,7 +157,6 @@ func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.Rela
|
||||
return nil, errors.New("not implemented")
|
||||
}
|
||||
|
||||
|
||||
func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
|
||||
return channel.DoApiRequest(a, c, info, requestBody)
|
||||
}
|
||||
|
||||
259
setting/config/config.go
Normal file
259
setting/config/config.go
Normal file
@@ -0,0 +1,259 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"one-api/common"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// ConfigManager 统一管理所有配置
|
||||
type ConfigManager struct {
|
||||
configs map[string]interface{}
|
||||
mutex sync.RWMutex
|
||||
}
|
||||
|
||||
var GlobalConfig = NewConfigManager()
|
||||
|
||||
func NewConfigManager() *ConfigManager {
|
||||
return &ConfigManager{
|
||||
configs: make(map[string]interface{}),
|
||||
}
|
||||
}
|
||||
|
||||
// Register 注册一个配置模块
|
||||
func (cm *ConfigManager) Register(name string, config interface{}) {
|
||||
cm.mutex.Lock()
|
||||
defer cm.mutex.Unlock()
|
||||
cm.configs[name] = config
|
||||
}
|
||||
|
||||
// Get 获取指定配置模块
|
||||
func (cm *ConfigManager) Get(name string) interface{} {
|
||||
cm.mutex.RLock()
|
||||
defer cm.mutex.RUnlock()
|
||||
return cm.configs[name]
|
||||
}
|
||||
|
||||
// LoadFromDB 从数据库加载配置
|
||||
func (cm *ConfigManager) LoadFromDB(options map[string]string) error {
|
||||
cm.mutex.Lock()
|
||||
defer cm.mutex.Unlock()
|
||||
|
||||
for name, config := range cm.configs {
|
||||
prefix := name + "."
|
||||
configMap := make(map[string]string)
|
||||
|
||||
// 收集属于此配置的所有选项
|
||||
for key, value := range options {
|
||||
if strings.HasPrefix(key, prefix) {
|
||||
configKey := strings.TrimPrefix(key, prefix)
|
||||
configMap[configKey] = value
|
||||
}
|
||||
}
|
||||
|
||||
// 如果找到配置项,则更新配置
|
||||
if len(configMap) > 0 {
|
||||
if err := updateConfigFromMap(config, configMap); err != nil {
|
||||
common.SysError("failed to update config " + name + ": " + err.Error())
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SaveToDB 将配置保存到数据库
|
||||
func (cm *ConfigManager) SaveToDB(updateFunc func(key, value string) error) error {
|
||||
cm.mutex.RLock()
|
||||
defer cm.mutex.RUnlock()
|
||||
|
||||
for name, config := range cm.configs {
|
||||
configMap, err := configToMap(config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for key, value := range configMap {
|
||||
dbKey := name + "." + key
|
||||
if err := updateFunc(dbKey, value); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// 辅助函数:将配置对象转换为map
|
||||
func configToMap(config interface{}) (map[string]string, error) {
|
||||
result := make(map[string]string)
|
||||
|
||||
val := reflect.ValueOf(config)
|
||||
if val.Kind() == reflect.Ptr {
|
||||
val = val.Elem()
|
||||
}
|
||||
|
||||
if val.Kind() != reflect.Struct {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
typ := val.Type()
|
||||
for i := 0; i < val.NumField(); i++ {
|
||||
field := val.Field(i)
|
||||
fieldType := typ.Field(i)
|
||||
|
||||
// 跳过未导出字段
|
||||
if !fieldType.IsExported() {
|
||||
continue
|
||||
}
|
||||
|
||||
// 获取json标签作为键名
|
||||
key := fieldType.Tag.Get("json")
|
||||
if key == "" || key == "-" {
|
||||
key = fieldType.Name
|
||||
}
|
||||
|
||||
// 处理不同类型的字段
|
||||
var strValue string
|
||||
switch field.Kind() {
|
||||
case reflect.String:
|
||||
strValue = field.String()
|
||||
case reflect.Bool:
|
||||
strValue = strconv.FormatBool(field.Bool())
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
strValue = strconv.FormatInt(field.Int(), 10)
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
strValue = strconv.FormatUint(field.Uint(), 10)
|
||||
case reflect.Float32, reflect.Float64:
|
||||
strValue = strconv.FormatFloat(field.Float(), 'f', -1, 64)
|
||||
case reflect.Map, reflect.Slice, reflect.Struct:
|
||||
// 复杂类型使用JSON序列化
|
||||
bytes, err := json.Marshal(field.Interface())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
strValue = string(bytes)
|
||||
default:
|
||||
// 跳过不支持的类型
|
||||
continue
|
||||
}
|
||||
|
||||
result[key] = strValue
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// 辅助函数:从map更新配置对象
|
||||
func updateConfigFromMap(config interface{}, configMap map[string]string) error {
|
||||
val := reflect.ValueOf(config)
|
||||
if val.Kind() != reflect.Ptr {
|
||||
return nil
|
||||
}
|
||||
val = val.Elem()
|
||||
|
||||
if val.Kind() != reflect.Struct {
|
||||
return nil
|
||||
}
|
||||
|
||||
typ := val.Type()
|
||||
for i := 0; i < val.NumField(); i++ {
|
||||
field := val.Field(i)
|
||||
fieldType := typ.Field(i)
|
||||
|
||||
// 跳过未导出字段
|
||||
if !fieldType.IsExported() {
|
||||
continue
|
||||
}
|
||||
|
||||
// 获取json标签作为键名
|
||||
key := fieldType.Tag.Get("json")
|
||||
if key == "" || key == "-" {
|
||||
key = fieldType.Name
|
||||
}
|
||||
|
||||
// 检查map中是否有对应的值
|
||||
strValue, ok := configMap[key]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
// 根据字段类型设置值
|
||||
if !field.CanSet() {
|
||||
continue
|
||||
}
|
||||
|
||||
switch field.Kind() {
|
||||
case reflect.String:
|
||||
field.SetString(strValue)
|
||||
case reflect.Bool:
|
||||
boolValue, err := strconv.ParseBool(strValue)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
field.SetBool(boolValue)
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
intValue, err := strconv.ParseInt(strValue, 10, 64)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
field.SetInt(intValue)
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
uintValue, err := strconv.ParseUint(strValue, 10, 64)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
field.SetUint(uintValue)
|
||||
case reflect.Float32, reflect.Float64:
|
||||
floatValue, err := strconv.ParseFloat(strValue, 64)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
field.SetFloat(floatValue)
|
||||
case reflect.Map, reflect.Slice, reflect.Struct:
|
||||
// 复杂类型使用JSON反序列化
|
||||
err := json.Unmarshal([]byte(strValue), field.Addr().Interface())
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ConfigToMap 将配置对象转换为map(导出函数)
|
||||
func ConfigToMap(config interface{}) (map[string]string, error) {
|
||||
return configToMap(config)
|
||||
}
|
||||
|
||||
// UpdateConfigFromMap 从map更新配置对象(导出函数)
|
||||
func UpdateConfigFromMap(config interface{}, configMap map[string]string) error {
|
||||
return updateConfigFromMap(config, configMap)
|
||||
}
|
||||
|
||||
// ExportAllConfigs 导出所有已注册的配置为扁平结构
|
||||
func (cm *ConfigManager) ExportAllConfigs() map[string]string {
|
||||
cm.mutex.RLock()
|
||||
defer cm.mutex.RUnlock()
|
||||
|
||||
result := make(map[string]string)
|
||||
|
||||
for name, cfg := range cm.configs {
|
||||
configMap, err := ConfigToMap(cfg)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// 使用 "模块名.配置项" 的格式添加到结果中
|
||||
for key, value := range configMap {
|
||||
result[name+"."+key] = value
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
@@ -1 +1,49 @@
|
||||
package model_setting
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"one-api/setting/config"
|
||||
)
|
||||
|
||||
//var claudeHeadersSettings = map[string][]string{}
|
||||
//
|
||||
//var ClaudeThinkingAdapterEnabled = true
|
||||
//var ClaudeThinkingAdapterMaxTokens = 8192
|
||||
//var ClaudeThinkingAdapterBudgetTokensPercentage = 0.8
|
||||
|
||||
// ClaudeSettings 定义Claude模型的配置
|
||||
type ClaudeSettings struct {
|
||||
HeadersSettings map[string][]string `json:"headers_settings"`
|
||||
ThinkingAdapterEnabled bool `json:"thinking_adapter_enabled"`
|
||||
ThinkingAdapterMaxTokens int `json:"thinking_adapter_max_tokens"`
|
||||
ThinkingAdapterBudgetTokensPercentage float64 `json:"thinking_adapter_budget_tokens_percentage"`
|
||||
}
|
||||
|
||||
// 默认配置
|
||||
var defaultClaudeSettings = ClaudeSettings{
|
||||
HeadersSettings: map[string][]string{},
|
||||
ThinkingAdapterEnabled: true,
|
||||
ThinkingAdapterMaxTokens: 8192,
|
||||
ThinkingAdapterBudgetTokensPercentage: 0.8,
|
||||
}
|
||||
|
||||
// 全局实例
|
||||
var claudeSettings = defaultClaudeSettings
|
||||
|
||||
func init() {
|
||||
// 注册到全局配置管理器
|
||||
config.GlobalConfig.Register("claude", &claudeSettings)
|
||||
}
|
||||
|
||||
// GetClaudeSettings 获取Claude配置
|
||||
func GetClaudeSettings() *ClaudeSettings {
|
||||
return &claudeSettings
|
||||
}
|
||||
|
||||
func (c *ClaudeSettings) WriteHeaders(headers *http.Header) {
|
||||
for key, values := range c.HeadersSettings {
|
||||
for _, value := range values {
|
||||
headers.Add(key, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,83 +1,52 @@
|
||||
package model_setting
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"one-api/common"
|
||||
"one-api/setting/config"
|
||||
)
|
||||
|
||||
var geminiSafetySettings = map[string]string{
|
||||
"default": "OFF",
|
||||
"HARM_CATEGORY_CIVIC_INTEGRITY": "BLOCK_NONE",
|
||||
// GeminiSettings 定义Gemini模型的配置
|
||||
type GeminiSettings struct {
|
||||
SafetySettings map[string]string `json:"safety_settings"`
|
||||
VersionSettings map[string]string `json:"version_settings"`
|
||||
}
|
||||
|
||||
// 默认配置
|
||||
var defaultGeminiSettings = GeminiSettings{
|
||||
SafetySettings: map[string]string{
|
||||
"default": "OFF",
|
||||
"HARM_CATEGORY_CIVIC_INTEGRITY": "BLOCK_NONE",
|
||||
},
|
||||
VersionSettings: map[string]string{
|
||||
"default": "v1beta",
|
||||
"gemini-1.0-pro": "v1",
|
||||
},
|
||||
}
|
||||
|
||||
// 全局实例
|
||||
var geminiSettings = defaultGeminiSettings
|
||||
|
||||
func init() {
|
||||
// 注册到全局配置管理器
|
||||
config.GlobalConfig.Register("gemini", &geminiSettings)
|
||||
}
|
||||
|
||||
// GetGeminiSettings 获取Gemini配置
|
||||
func GetGeminiSettings() *GeminiSettings {
|
||||
return &geminiSettings
|
||||
}
|
||||
|
||||
// GetGeminiSafetySetting 获取安全设置
|
||||
func GetGeminiSafetySetting(key string) string {
|
||||
if value, ok := geminiSafetySettings[key]; ok {
|
||||
if value, ok := geminiSettings.SafetySettings[key]; ok {
|
||||
return value
|
||||
}
|
||||
return geminiSafetySettings["default"]
|
||||
}
|
||||
|
||||
func GeminiSafetySettingFromJsonString(jsonString string) {
|
||||
geminiSafetySettings = map[string]string{}
|
||||
err := json.Unmarshal([]byte(jsonString), &geminiSafetySettings)
|
||||
if err != nil {
|
||||
geminiSafetySettings = map[string]string{
|
||||
"default": "OFF",
|
||||
"HARM_CATEGORY_CIVIC_INTEGRITY": "BLOCK_NONE",
|
||||
}
|
||||
}
|
||||
// check must have default
|
||||
if _, ok := geminiSafetySettings["default"]; !ok {
|
||||
geminiSafetySettings["default"] = common.GeminiSafetySetting
|
||||
}
|
||||
}
|
||||
|
||||
func GeminiSafetySettingsJsonString() string {
|
||||
// check must have default
|
||||
if _, ok := geminiSafetySettings["default"]; !ok {
|
||||
geminiSafetySettings["default"] = common.GeminiSafetySetting
|
||||
}
|
||||
jsonString, err := json.Marshal(geminiSafetySettings)
|
||||
if err != nil {
|
||||
return "{}"
|
||||
}
|
||||
return string(jsonString)
|
||||
}
|
||||
|
||||
var geminiVersionSettings = map[string]string{
|
||||
"default": "v1beta",
|
||||
"gemini-1.0-pro": "v1",
|
||||
return geminiSettings.SafetySettings["default"]
|
||||
}
|
||||
|
||||
// GetGeminiVersionSetting 获取版本设置
|
||||
func GetGeminiVersionSetting(key string) string {
|
||||
if value, ok := geminiVersionSettings[key]; ok {
|
||||
if value, ok := geminiSettings.VersionSettings[key]; ok {
|
||||
return value
|
||||
}
|
||||
return geminiVersionSettings["default"]
|
||||
}
|
||||
|
||||
func GeminiVersionSettingFromJsonString(jsonString string) {
|
||||
geminiVersionSettings = map[string]string{}
|
||||
err := json.Unmarshal([]byte(jsonString), &geminiVersionSettings)
|
||||
if err != nil {
|
||||
geminiVersionSettings = map[string]string{
|
||||
"default": "v1beta",
|
||||
}
|
||||
}
|
||||
// check must have default
|
||||
if _, ok := geminiVersionSettings["default"]; !ok {
|
||||
geminiVersionSettings["default"] = "v1beta"
|
||||
}
|
||||
}
|
||||
|
||||
func GeminiVersionSettingsJsonString() string {
|
||||
// check must have default
|
||||
if _, ok := geminiVersionSettings["default"]; !ok {
|
||||
geminiVersionSettings["default"] = "v1beta"
|
||||
}
|
||||
jsonString, err := json.Marshal(geminiVersionSettings)
|
||||
if err != nil {
|
||||
return "{}"
|
||||
}
|
||||
return string(jsonString)
|
||||
return geminiSettings.VersionSettings["default"]
|
||||
}
|
||||
|
||||
@@ -6,12 +6,17 @@ import { API, showError, showSuccess } from '../helpers';
|
||||
import SettingsChats from '../pages/Setting/Operation/SettingsChats.js';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import SettingGeminiModel from '../pages/Setting/Model/SettingGeminiModel.js';
|
||||
import SettingClaudeModel from '../pages/Setting/Model/SettingClaudeModel.js';
|
||||
|
||||
const ModelSetting = () => {
|
||||
const { t } = useTranslation();
|
||||
let [inputs, setInputs] = useState({
|
||||
GeminiSafetySettings: '',
|
||||
GeminiVersionSettings: '',
|
||||
'gemini.safety_settings': '',
|
||||
'gemini.version_settings': '',
|
||||
'claude.headers_settings': '',
|
||||
'claude.thinking_adapter_enabled': true,
|
||||
'claude.thinking_adapter_max_tokens': 8192,
|
||||
'claude.thinking_adapter_budget_tokens_percentage': 0.8,
|
||||
});
|
||||
|
||||
let [loading, setLoading] = useState(false);
|
||||
@@ -23,8 +28,9 @@ const ModelSetting = () => {
|
||||
let newInputs = {};
|
||||
data.forEach((item) => {
|
||||
if (
|
||||
item.key === 'GeminiSafetySettings' ||
|
||||
item.key === 'GeminiVersionSettings'
|
||||
item.key === 'gemini.safety_settings' ||
|
||||
item.key === 'gemini.version_settings' ||
|
||||
item.key === 'claude.headers_settings'
|
||||
) {
|
||||
item.value = JSON.stringify(JSON.parse(item.value), null, 2);
|
||||
}
|
||||
@@ -65,6 +71,10 @@ const ModelSetting = () => {
|
||||
<Card style={{ marginTop: '10px' }}>
|
||||
<SettingGeminiModel options={inputs} refresh={onRefresh} />
|
||||
</Card>
|
||||
{/* Claude */}
|
||||
<Card style={{ marginTop: '10px' }}>
|
||||
<SettingClaudeModel options={inputs} refresh={onRefresh} />
|
||||
</Card>
|
||||
</Spin>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -376,7 +376,7 @@ const UsersTable = () => {
|
||||
if (searchKeyword === '') {
|
||||
await loadUsers(activePage, pageSize);
|
||||
} else {
|
||||
await searchUsers(searchKeyword, searchGroup);
|
||||
await searchUsers(activePage, pageSize, searchKeyword, searchGroup);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1074,10 +1074,9 @@
|
||||
"删除所选通道": "Delete selected channels",
|
||||
"标签聚合模式": "Enable tag mode",
|
||||
"没有账户?": "No account? ",
|
||||
"注意,模型部署名称必须和模型名称保持一致,因为 One API 会把请求体中的 model 参数替换为你的部署名称(模型名称中的点会被剔除)": "Note: The model deployment name must match the model name because One API will replace the model parameter in the request body with your deployment name (dots in the model name will be removed)",
|
||||
"请输入 AZURE_OPENAI_ENDPOINT,例如:https://docs-test-001.openai.azure.com": "Please enter AZURE_OPENAI_ENDPOINT, e.g.: https://docs-test-001.openai.azure.com",
|
||||
"默认 API 版本": "Default API Version",
|
||||
"请输入默认 API 版本,例如:2023-06-01-preview,该配置可以被实际的请求查询参数所覆盖": "Please enter default API version, e.g.: 2023-06-01-preview. This configuration can be overridden by actual request query parameters",
|
||||
"请输入默认 API 版本,例如:2024-12-01-preview": "Please enter default API version, e.g.: 2024-12-01-preview.",
|
||||
"请为渠道命名": "Please name the channel",
|
||||
"请选择可以使用该渠道的分组": "Please select groups that can use this channel",
|
||||
"请在系统设置页面编辑分组倍率以添加新的分组:": "Please edit Group ratios in system settings to add new groups:",
|
||||
|
||||
@@ -327,9 +327,6 @@ const EditChannel = (props) => {
|
||||
localInputs.base_url.length - 1
|
||||
);
|
||||
}
|
||||
if (localInputs.type === 3 && localInputs.other === '') {
|
||||
localInputs.other = '2023-06-01-preview';
|
||||
}
|
||||
if (localInputs.type === 18 && localInputs.other === '') {
|
||||
localInputs.other = 'v2.1';
|
||||
}
|
||||
@@ -494,7 +491,7 @@ const EditChannel = (props) => {
|
||||
<Input
|
||||
label={t('默认 API 版本')}
|
||||
name="azure_other"
|
||||
placeholder={t('请输入默认 API 版本,例如:2023-06-01-preview,该配置可以被实际的请求查询参数所覆盖')}
|
||||
placeholder={t('请输入默认 API 版本,例如:2024-12-01-preview')}
|
||||
onChange={(value) => {
|
||||
handleInputChange('other', value);
|
||||
}}
|
||||
|
||||
152
web/src/pages/Setting/Model/SettingClaudeModel.js
Normal file
152
web/src/pages/Setting/Model/SettingClaudeModel.js
Normal file
@@ -0,0 +1,152 @@
|
||||
import React, { useEffect, useState, useRef } from 'react';
|
||||
import { Button, Col, Form, Row, Spin } from '@douyinfe/semi-ui';
|
||||
import {
|
||||
compareObjects,
|
||||
API,
|
||||
showError,
|
||||
showSuccess,
|
||||
showWarning, verifyJSON
|
||||
} from '../../../helpers';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import Text from '@douyinfe/semi-ui/lib/es/typography/text';
|
||||
|
||||
const CLAUDE_HEADER = {
|
||||
'anthropic-beta': ['output-128k-2025-02-19', 'token-efficient-tools-2025-02-19'],
|
||||
};
|
||||
|
||||
export default function SettingClaudeModel(props) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [inputs, setInputs] = useState({
|
||||
'claude.headers_settings': '',
|
||||
'claude.thinking_adapter_enabled': true,
|
||||
'claude.thinking_adapter_max_tokens': 8192,
|
||||
'claude.thinking_adapter_budget_tokens_percentage': 0.8,
|
||||
});
|
||||
const refForm = useRef();
|
||||
const [inputsRow, setInputsRow] = useState(inputs);
|
||||
|
||||
function onSubmit() {
|
||||
const updateArray = compareObjects(inputs, inputsRow);
|
||||
if (!updateArray.length) return showWarning(t('你似乎并没有修改什么'));
|
||||
const requestQueue = updateArray.map((item) => {
|
||||
let value = '';
|
||||
if (typeof inputs[item.key] === 'boolean') {
|
||||
value = String(inputs[item.key]);
|
||||
} else {
|
||||
value = inputs[item.key];
|
||||
}
|
||||
return API.put('/api/option/', {
|
||||
key: item.key,
|
||||
value,
|
||||
});
|
||||
});
|
||||
setLoading(true);
|
||||
Promise.all(requestQueue)
|
||||
.then((res) => {
|
||||
if (requestQueue.length === 1) {
|
||||
if (res.includes(undefined)) return;
|
||||
} else if (requestQueue.length > 1) {
|
||||
if (res.includes(undefined)) return showError(t('部分保存失败,请重试'));
|
||||
}
|
||||
showSuccess(t('保存成功'));
|
||||
props.refresh();
|
||||
})
|
||||
.catch(() => {
|
||||
showError(t('保存失败,请重试'));
|
||||
})
|
||||
.finally(() => {
|
||||
setLoading(false);
|
||||
});
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const currentInputs = {};
|
||||
for (let key in props.options) {
|
||||
if (Object.keys(inputs).includes(key)) {
|
||||
currentInputs[key] = props.options[key];
|
||||
}
|
||||
}
|
||||
setInputs(currentInputs);
|
||||
setInputsRow(structuredClone(currentInputs));
|
||||
refForm.current.setValues(currentInputs);
|
||||
}, [props.options]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Spin spinning={loading}>
|
||||
<Form
|
||||
values={inputs}
|
||||
getFormApi={(formAPI) => (refForm.current = formAPI)}
|
||||
style={{ marginBottom: 15 }}
|
||||
>
|
||||
<Form.Section text={t('Claude设置')}>
|
||||
<Row>
|
||||
<Col span={16}>
|
||||
<Form.TextArea
|
||||
label={t('Claude请求头覆盖')}
|
||||
field={'claude.headers_settings'}
|
||||
placeholder={t('为一个 JSON 文本,例如:') + '\n' + JSON.stringify(CLAUDE_HEADER, null, 2)}
|
||||
extraText={t('示例') + JSON.stringify(CLAUDE_HEADER, null, 2)}
|
||||
autosize={{ minRows: 6, maxRows: 12 }}
|
||||
trigger='blur'
|
||||
stopValidateWithError
|
||||
rules={[
|
||||
{
|
||||
validator: (rule, value) => verifyJSON(value),
|
||||
message: t('不是合法的 JSON 字符串')
|
||||
}
|
||||
]}
|
||||
onChange={(value) => setInputs({ ...inputs, 'claude.headers_settings': value })}
|
||||
/>
|
||||
</Col>
|
||||
</Row>
|
||||
<Row>
|
||||
<Col span={16}>
|
||||
<Form.Switch
|
||||
label={t('启用Claude思考适配(-thinking后缀)')}
|
||||
field={'claude.thinking_adapter_enabled'}
|
||||
onChange={(value) => setInputs({ ...inputs, 'claude.thinking_adapter_enabled': value })}
|
||||
/>
|
||||
</Col>
|
||||
</Row>
|
||||
<Row>
|
||||
<Col span={16}>
|
||||
{/*//展示MaxTokens和BudgetTokens的计算公式, 并展示实际数字*/}
|
||||
<Text>
|
||||
{t('Claude思考适配 BudgetTokens = MaxTokens * BudgetTokens 百分比')}
|
||||
</Text>
|
||||
</Col>
|
||||
</Row>
|
||||
<Row>
|
||||
<Col span={8}>
|
||||
<Form.InputNumber
|
||||
label={t('思考适配 MaxTokens')}
|
||||
field={'claude.thinking_adapter_max_tokens'}
|
||||
initValue={''}
|
||||
onChange={(value) => setInputs({ ...inputs, 'claude.thinking_adapter_max_tokens': value })}
|
||||
/>
|
||||
</Col>
|
||||
<Col span={8}>
|
||||
<Form.InputNumber
|
||||
label={t('思考适配 BudgetTokens 百分比')}
|
||||
field={'claude.thinking_adapter_budget_tokens_percentage'}
|
||||
initValue={''}
|
||||
suffix={t('%')}
|
||||
onChange={(value) => setInputs({ ...inputs, 'claude.thinking_adapter_budget_tokens_percentage': value })}
|
||||
/>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<Row>
|
||||
<Button size='default' onClick={onSubmit}>
|
||||
{t('保存')}
|
||||
</Button>
|
||||
</Row>
|
||||
</Form.Section>
|
||||
</Form>
|
||||
</Spin>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -24,8 +24,8 @@ export default function SettingGeminiModel(props) {
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [inputs, setInputs] = useState({
|
||||
GeminiSafetySettings: '',
|
||||
GeminiVersionSettings: '',
|
||||
'gemini.safety_settings': '',
|
||||
'gemini.version_settings': '',
|
||||
});
|
||||
const refForm = useRef();
|
||||
const [inputsRow, setInputsRow] = useState(inputs);
|
||||
@@ -90,7 +90,7 @@ export default function SettingGeminiModel(props) {
|
||||
<Form.TextArea
|
||||
label={t('Gemini安全设置')}
|
||||
placeholder={t('为一个 JSON 文本,例如:') + '\n' + JSON.stringify(GEMINI_SETTING_EXAMPLE, null, 2)}
|
||||
field={'GeminiSafetySettings'}
|
||||
field={'gemini.safety_settings'}
|
||||
extraText={t('default为默认设置,可单独设置每个分类的安全等级')}
|
||||
autosize={{ minRows: 6, maxRows: 12 }}
|
||||
trigger='blur'
|
||||
@@ -101,7 +101,7 @@ export default function SettingGeminiModel(props) {
|
||||
message: t('不是合法的 JSON 字符串')
|
||||
}
|
||||
]}
|
||||
onChange={(value) => setInputs({ ...inputs, GeminiSafetySettings: value })}
|
||||
onChange={(value) => setInputs({ ...inputs, 'gemini.safety_settings': value })}
|
||||
/>
|
||||
</Col>
|
||||
</Row>
|
||||
@@ -110,7 +110,7 @@ export default function SettingGeminiModel(props) {
|
||||
<Form.TextArea
|
||||
label={t('Gemini版本设置')}
|
||||
placeholder={t('为一个 JSON 文本,例如:') + '\n' + JSON.stringify(GEMINI_VERSION_EXAMPLE, null, 2)}
|
||||
field={'GeminiVersionSettings'}
|
||||
field={'gemini.version_settings'}
|
||||
extraText={t('default为默认设置,可单独设置每个模型的版本')}
|
||||
autosize={{ minRows: 6, maxRows: 12 }}
|
||||
trigger='blur'
|
||||
@@ -121,7 +121,7 @@ export default function SettingGeminiModel(props) {
|
||||
message: t('不是合法的 JSON 字符串')
|
||||
}
|
||||
]}
|
||||
onChange={(value) => setInputs({ ...inputs, GeminiVersionSettings: value })}
|
||||
onChange={(value) => setInputs({ ...inputs, 'gemini.version_settings': value })}
|
||||
/>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
Reference in New Issue
Block a user