feat: manually mirror opencoze's code from bytedance

Change-Id: I09a73aadda978ad9511264a756b2ce51f5761adf
This commit is contained in:
fanlv
2025-07-20 17:36:12 +08:00
commit 890153324f
14811 changed files with 1923430 additions and 0 deletions

View File

@@ -0,0 +1,41 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package entity
import "github.com/coze-dev/coze-studio/backend/api/model/crossdomain/modelmgr"
type Model struct {
*modelmgr.Model
}
type ModelMeta = modelmgr.ModelMeta
type ModelMetaStatus = modelmgr.ModelMetaStatus
func (m *Model) FindParameter(name modelmgr.ParameterName) (*modelmgr.Parameter, bool) {
if len(m.DefaultParameters) == 0 {
return nil, false
}
for _, param := range m.DefaultParameters {
if param.Name == name {
return param, true
}
}
return nil, false
}

View File

@@ -0,0 +1,89 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package entity
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
"github.com/coze-dev/coze-studio/backend/api/model/crossdomain/modelmgr"
)
func TestDefaultParameter(t *testing.T) {
dps := []*modelmgr.Parameter{
{
Name: "temperature",
Label: &modelmgr.MultilingualText{
ZH: "生成随机性",
EN: "Temperature",
},
Desc: &modelmgr.MultilingualText{
ZH: "- **temperature**: 调高温度会使得模型的输出更多样性和创新性反之降低温度会使输出内容更加遵循指令要求但减少多样性。建议不要与“Top p”同时调整。",
EN: "**Temperature**:\\n\\n- When you increase this value, the model outputs more diverse and innovative content; when you decrease it, the model outputs less diverse content that strictly follows the given instructions.\\n- It is recommended not to adjust this value with \\\"Top p\\\" at the same time.",
},
Type: modelmgr.ValueTypeFloat,
Min: "0",
Max: "1",
Precision: 1,
DefaultVal: modelmgr.DefaultValue{
modelmgr.DefaultTypeDefault: "1.0",
modelmgr.DefaultTypeCreative: "1",
modelmgr.DefaultTypeBalance: "0.8",
modelmgr.DefaultTypePrecise: "0.3",
},
Style: modelmgr.DisplayStyle{
Widget: modelmgr.WidgetSlider,
Label: &modelmgr.MultilingualText{
ZH: "生成多样性",
EN: "Generation diversity",
},
},
},
{
Name: "max_tokens",
Label: &modelmgr.MultilingualText{
ZH: "最大回复长度",
EN: "Response max length",
},
Desc: &modelmgr.MultilingualText{
ZH: "控制模型输出的Tokens 长度上限。通常 100 Tokens 约等于 150 个中文汉字。",
EN: "You can specify the maximum length of the tokens output through this value. Typically, 100 tokens are approximately equal to 150 Chinese characters.",
},
Type: modelmgr.ValueTypeInt,
Min: "1",
Max: "12288",
Precision: 0,
DefaultVal: modelmgr.DefaultValue{
modelmgr.DefaultTypeDefault: "4096",
},
Style: modelmgr.DisplayStyle{
Widget: modelmgr.WidgetSlider,
Label: &modelmgr.MultilingualText{
ZH: "输入及输出设置",
EN: "Input and output settings",
},
},
},
}
data, err := json.Marshal(dps)
assert.NoError(t, err)
t.Logf("default parameters: %s", string(data))
}

View File

@@ -0,0 +1,23 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package entity
import (
"github.com/coze-dev/coze-studio/backend/api/model/crossdomain/modelmgr"
)
type Capability = modelmgr.Capability

View File

@@ -0,0 +1,69 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package modelmgr
import (
"context"
"github.com/coze-dev/coze-studio/backend/api/model/crossdomain/modelmgr"
"github.com/coze-dev/coze-studio/backend/domain/modelmgr/entity"
)
type Manager interface {
CreateModelMeta(ctx context.Context, meta *entity.ModelMeta) (*entity.ModelMeta, error)
UpdateModelMetaStatus(ctx context.Context, id int64, status entity.ModelMetaStatus) error
DeleteModelMeta(ctx context.Context, id int64) error
ListModelMeta(ctx context.Context, req *ListModelMetaRequest) (*ListModelMetaResponse, error)
MGetModelMetaByID(ctx context.Context, req *MGetModelMetaRequest) ([]*entity.ModelMeta, error)
CreateModel(ctx context.Context, model *entity.Model) (*entity.Model, error)
DeleteModel(ctx context.Context, id int64) error
ListModel(ctx context.Context, req *ListModelRequest) (*ListModelResponse, error)
MGetModelByID(ctx context.Context, req *MGetModelRequest) ([]*entity.Model, error)
}
type ListModelMetaRequest struct {
FuzzyModelName *string
Status []entity.ModelMetaStatus
Limit int
Cursor *string
}
type ListModelMetaResponse struct {
ModelMetaList []*entity.ModelMeta
HasMore bool
NextCursor *string
}
type MGetModelMetaRequest struct {
IDs []int64
}
type ListModelRequest struct {
FuzzyModelName *string
Status []modelmgr.ModelEntityStatus // default is default and in_use status
Limit int
Cursor *string
}
type ListModelResponse struct {
ModelList []*entity.Model
HasMore bool
NextCursor *string
}
type MGetModelRequest = modelmgr.MGetModelRequest

View File

@@ -0,0 +1,136 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dao
import (
"context"
"database/sql/driver"
"strconv"
"gorm.io/gorm"
"github.com/coze-dev/coze-studio/backend/api/model/crossdomain/modelmgr"
"github.com/coze-dev/coze-studio/backend/domain/modelmgr/internal/dal/model"
"github.com/coze-dev/coze-studio/backend/domain/modelmgr/internal/dal/query"
"github.com/coze-dev/coze-studio/backend/pkg/lang/slices"
"github.com/coze-dev/coze-studio/backend/pkg/lang/sqlutil"
)
type ModelEntityRepo interface {
Create(ctx context.Context, modelEntity *model.ModelEntity) error
Delete(ctx context.Context, id int64) error
List(ctx context.Context, fuzzyModelName *string, scenario *int64, status []modelmgr.ModelEntityStatus,
limit int, cursor *string) (resp []*model.ModelEntity, nextCursor *string, hasMore bool, err error)
MGet(ctx context.Context, ids []int64) ([]*model.ModelEntity, error)
}
func NewModelEntityDAO(db *gorm.DB) ModelEntityRepo {
return &ModelEntityDAO{
db: db,
query: query.Use(db),
}
}
type ModelEntityDAO struct {
db *gorm.DB
query *query.Query
}
func (m *ModelEntityDAO) Create(ctx context.Context, modelEntity *model.ModelEntity) error {
return m.query.ModelEntity.WithContext(ctx).Create(modelEntity)
}
func (m *ModelEntityDAO) Delete(ctx context.Context, id int64) error {
me := m.query.ModelEntity
_, err := me.WithContext(ctx).
Debug().
Where(me.ID.Eq(id)).
Delete()
return err
}
func (m *ModelEntityDAO) List(ctx context.Context, fuzzyModelName *string, scenario *int64, status []modelmgr.ModelEntityStatus,
limit int, cursor *string,
) (resp []*model.ModelEntity, nextCursor *string, hasMore bool, err error) {
me := m.query.ModelEntity
do := me.WithContext(ctx)
if fuzzyModelName != nil {
do = do.Where(me.Name.Like(*fuzzyModelName))
}
if scenario != nil {
do = do.Where(me.Scenario.Eq(sqlutil.DriverValue(*scenario)))
}
if len(status) > 0 {
vals := slices.Transform(status, func(a modelmgr.ModelEntityStatus) driver.Valuer {
return sqlutil.DriverValue(int64(a))
})
do = do.Where(me.Status.In(vals...))
}
if cursor != nil {
var id int64
id, err = m.fromCursor(*cursor)
if err != nil {
return nil, nil, false, err
}
do = do.Where(me.ID.Lt(id))
}
if limit == 0 {
limit = defaultLimit
}
pos, err := do.Limit(limit).Order(me.ID.Desc()).Find()
if err != nil {
return nil, nil, false, err
}
if len(pos) == 0 {
return nil, nil, false, nil
}
hasMore = len(pos) == limit
if len(pos) > 0 {
nextCursor = m.toIDCursor(pos[len(pos)-1].ID)
}
return pos, nextCursor, hasMore, nil
}
func (m *ModelEntityDAO) MGet(ctx context.Context, ids []int64) ([]*model.ModelEntity, error) {
if len(ids) == 0 {
return nil, nil
}
me := m.query.ModelEntity
pos, err := me.WithContext(ctx).Where(me.ID.In(ids...)).Find()
if err != nil {
return nil, err
}
return pos, nil
}
func (m *ModelEntityDAO) fromCursor(cursor string) (id int64, err error) {
return strconv.ParseInt(cursor, 10, 64)
}
func (m *ModelEntityDAO) toIDCursor(id int64) (cursor *string) {
s := strconv.FormatInt(id, 10)
return &s
}

View File

@@ -0,0 +1,189 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dao
import (
"context"
"database/sql/driver"
"errors"
"strconv"
"time"
"gorm.io/gorm"
"github.com/coze-dev/coze-studio/backend/api/model/crossdomain/modelmgr"
"github.com/coze-dev/coze-studio/backend/domain/modelmgr/internal/dal/model"
"github.com/coze-dev/coze-studio/backend/domain/modelmgr/internal/dal/query"
"github.com/coze-dev/coze-studio/backend/pkg/lang/slices"
"github.com/coze-dev/coze-studio/backend/pkg/lang/sqlutil"
)
const (
defaultLimit = 100
)
type ModelMetaRepo interface {
Create(ctx context.Context, meta *model.ModelMeta) error
UpdateStatus(ctx context.Context, id int64, status modelmgr.ModelMetaStatus) error
Delete(ctx context.Context, id int64) error
List(ctx context.Context, fuzzyShowName *string, status []modelmgr.ModelMetaStatus, limit int, cursor *string) (
resp []*model.ModelMeta, nextCursor *string, hasMore bool, err error)
GetByID(ctx context.Context, id int64) (*model.ModelMeta, error)
MGetByID(ctx context.Context, ids []int64) ([]*model.ModelMeta, error)
}
func NewModelMetaDAO(db *gorm.DB) ModelMetaRepo {
return &ModelMetaDAO{
db: db,
query: query.Use(db),
}
}
type ModelMetaDAO struct {
db *gorm.DB
query *query.Query
}
func (m *ModelMetaDAO) Create(ctx context.Context, meta *model.ModelMeta) error {
return m.query.ModelMeta.WithContext(ctx).Create(meta)
}
func (m *ModelMetaDAO) UpdateStatus(ctx context.Context, id int64, status modelmgr.ModelMetaStatus) error {
mm := m.query.ModelMeta
_, err := mm.WithContext(ctx).
Debug().
Where(mm.ID.Eq(id)).
Select(mm.Status, mm.UpdatedAt).
Updates(&model.ModelMeta{
Status: status,
UpdatedAt: time.Now().UnixMilli(),
})
return err
}
func (m *ModelMetaDAO) Delete(ctx context.Context, id int64) error {
mm := m.query.ModelMeta
_, err := mm.WithContext(ctx).
Debug().
Where(mm.ID.Eq(id)).
Delete()
return err
}
func (m *ModelMetaDAO) List(ctx context.Context, fuzzyShowName *string, status []modelmgr.ModelMetaStatus, limit int, cursor *string) (
resp []*model.ModelMeta, nextCursor *string, hasMore bool, err error,
) {
mm := m.query.ModelMeta
do := mm.WithContext(ctx)
if fuzzyShowName != nil {
do.Where(mm.ModelName.Like(*fuzzyShowName))
}
if len(status) > 0 {
vals := slices.Transform(status, func(a modelmgr.ModelMetaStatus) driver.Valuer {
return sqlutil.DriverValue(a)
})
do.Where(mm.Status.In(vals...))
}
if cursor != nil {
id, err := m.fromCursor(*cursor)
if err != nil {
return nil, nil, false, err
}
do.Where(mm.ID.Lt(id))
}
if limit == 0 {
limit = defaultLimit
}
pos, err := do.Limit(limit).Order(mm.ID.Desc()).Find()
if err != nil {
return nil, nil, false, err
}
if len(pos) == 0 {
return nil, nil, false, nil
}
hasMore = len(pos) == limit
if len(pos) > 0 {
nextCursor = m.toIDCursor(pos[len(pos)-1].ID)
}
return pos, nextCursor, hasMore, nil
}
func (m *ModelMetaDAO) GetByID(ctx context.Context, id int64) (*model.ModelMeta, error) {
mm := m.query.ModelMeta
po, err := mm.WithContext(ctx).Where(mm.ID.Eq(id)).Take()
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return nil, err
}
return po, nil
}
func (m *ModelMetaDAO) MGetByID(ctx context.Context, ids []int64) ([]*model.ModelMeta, error) {
if len(ids) == 0 {
return nil, nil
}
mm := m.query.ModelMeta
do := mm.WithContext(ctx)
pos, err := do.Where(mm.ID.In(ids...)).Find()
if err != nil {
return nil, err
}
// todo::本意是按照ids的顺序返回结果但是这里的查询结果是无序的所以这里先不做排序 @zhaonan
// id2Idx := make(map[int64]int, len(ids))
// for idx, id := range ids {
// id2Idx[id] = idx
// }
//
// resp := make([]*model.ModelMeta, 0, len(ids))
// for _, po := range pos {
// idx, found := id2Idx[po.ID]
// if !found { // unexpected
// return nil, fmt.Errorf("[MGetByID] unexpected data found, id=%v", po.ID)
// }
//
// item := po
// resp[idx] = item
// }
return pos, nil
}
func (m *ModelMetaDAO) fromCursor(cursor string) (id int64, err error) {
return strconv.ParseInt(cursor, 10, 64)
}
func (m *ModelMetaDAO) toIDCursor(id int64) (cursor *string) {
s := strconv.FormatInt(id, 10)
return &s
}

View File

@@ -0,0 +1,31 @@
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
package model
import (
"github.com/coze-dev/coze-studio/backend/api/model/crossdomain/modelmgr"
"gorm.io/gorm"
)
const TableNameModelEntity = "model_entity"
// ModelEntity 模型信息
type ModelEntity struct {
ID int64 `gorm:"column:id;primaryKey;comment:主键ID" json:"id"` // 主键ID
MetaID int64 `gorm:"column:meta_id;not null;comment:模型元信息 id" json:"meta_id"` // 模型元信息 id
Name string `gorm:"column:name;not null;comment:名称" json:"name"` // 名称
Description string `gorm:"column:description;comment:描述" json:"description"` // 描述
DefaultParams []*modelmgr.Parameter `gorm:"column:default_params;comment:默认参数;serializer:json" json:"default_params"` // 默认参数
Scenario modelmgr.Scenario `gorm:"column:scenario;not null;comment:模型应用场景;serializer:json" json:"scenario"` // 模型应用场景
Status modelmgr.ModelEntityStatus `gorm:"column:status;not null;default:1;comment:模型状态;serializer:json" json:"status"` // 模型状态
CreatedAt int64 `gorm:"column:created_at;not null;autoCreateTime:milli;comment:Create Time in Milliseconds" json:"created_at"` // Create Time in Milliseconds
UpdatedAt int64 `gorm:"column:updated_at;not null;autoUpdateTime:milli;comment:Update Time in Milliseconds" json:"updated_at"` // Update Time in Milliseconds
DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;comment:Delete Time in Milliseconds" json:"deleted_at"` // Delete Time in Milliseconds
}
// TableName ModelEntity's table name
func (*ModelEntity) TableName() string {
return TableNameModelEntity
}

View File

@@ -0,0 +1,34 @@
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
package model
import (
"github.com/coze-dev/coze-studio/backend/api/model/crossdomain/modelmgr"
"github.com/coze-dev/coze-studio/backend/infra/contract/chatmodel"
"gorm.io/gorm"
)
const TableNameModelMeta = "model_meta"
// ModelMeta 模型元信息
type ModelMeta struct {
ID int64 `gorm:"column:id;primaryKey;comment:主键ID" json:"id"` // 主键ID
ModelName string `gorm:"column:model_name;not null;comment:模型名称" json:"model_name"` // 模型名称
Protocol string `gorm:"column:protocol;not null;comment:模型协议" json:"protocol"` // 模型协议
IconURI string `gorm:"column:icon_uri;not null;comment:Icon URI" json:"icon_uri"` // Icon URI
Capability *modelmgr.Capability `gorm:"column:capability;comment:模型能力;serializer:json" json:"capability"` // 模型能力
ConnConfig *chatmodel.Config `gorm:"column:conn_config;comment:模型连接配置;serializer:json" json:"conn_config"` // 模型连接配置
Status modelmgr.ModelMetaStatus `gorm:"column:status;not null;default:1;comment:模型状态;serializer:json" json:"status"` // 模型状态
Description string `gorm:"column:description;not null;comment:模型描述" json:"description"` // 模型描述
CreatedAt int64 `gorm:"column:created_at;not null;autoCreateTime:milli;comment:Create Time in Milliseconds" json:"created_at"` // Create Time in Milliseconds
UpdatedAt int64 `gorm:"column:updated_at;not null;autoUpdateTime:milli;comment:Update Time in Milliseconds" json:"updated_at"` // Update Time in Milliseconds
DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;comment:Delete Time in Milliseconds" json:"deleted_at"` // Delete Time in Milliseconds
IconURL string `gorm:"column:icon_url;not null;comment:Icon URL" json:"icon_url"` // Icon URL
}
// TableName ModelMeta's table name
func (*ModelMeta) TableName() string {
return TableNameModelMeta
}

View File

@@ -0,0 +1,111 @@
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
package query
import (
"context"
"database/sql"
"gorm.io/gorm"
"gorm.io/gen"
"gorm.io/plugin/dbresolver"
)
var (
Q = new(Query)
ModelEntity *modelEntity
ModelMeta *modelMeta
)
func SetDefault(db *gorm.DB, opts ...gen.DOOption) {
*Q = *Use(db, opts...)
ModelEntity = &Q.ModelEntity
ModelMeta = &Q.ModelMeta
}
func Use(db *gorm.DB, opts ...gen.DOOption) *Query {
return &Query{
db: db,
ModelEntity: newModelEntity(db, opts...),
ModelMeta: newModelMeta(db, opts...),
}
}
type Query struct {
db *gorm.DB
ModelEntity modelEntity
ModelMeta modelMeta
}
func (q *Query) Available() bool { return q.db != nil }
func (q *Query) clone(db *gorm.DB) *Query {
return &Query{
db: db,
ModelEntity: q.ModelEntity.clone(db),
ModelMeta: q.ModelMeta.clone(db),
}
}
func (q *Query) ReadDB() *Query {
return q.ReplaceDB(q.db.Clauses(dbresolver.Read))
}
func (q *Query) WriteDB() *Query {
return q.ReplaceDB(q.db.Clauses(dbresolver.Write))
}
func (q *Query) ReplaceDB(db *gorm.DB) *Query {
return &Query{
db: db,
ModelEntity: q.ModelEntity.replaceDB(db),
ModelMeta: q.ModelMeta.replaceDB(db),
}
}
type queryCtx struct {
ModelEntity IModelEntityDo
ModelMeta IModelMetaDo
}
func (q *Query) WithContext(ctx context.Context) *queryCtx {
return &queryCtx{
ModelEntity: q.ModelEntity.WithContext(ctx),
ModelMeta: q.ModelMeta.WithContext(ctx),
}
}
func (q *Query) Transaction(fc func(tx *Query) error, opts ...*sql.TxOptions) error {
return q.db.Transaction(func(tx *gorm.DB) error { return fc(q.clone(tx)) }, opts...)
}
func (q *Query) Begin(opts ...*sql.TxOptions) *QueryTx {
tx := q.db.Begin(opts...)
return &QueryTx{Query: q.clone(tx), Error: tx.Error}
}
type QueryTx struct {
*Query
Error error
}
func (q *QueryTx) Commit() error {
return q.db.Commit().Error
}
func (q *QueryTx) Rollback() error {
return q.db.Rollback().Error
}
func (q *QueryTx) SavePoint(name string) error {
return q.db.SavePoint(name).Error
}
func (q *QueryTx) RollbackTo(name string) error {
return q.db.RollbackTo(name).Error
}

View File

@@ -0,0 +1,417 @@
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
package query
import (
"context"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/schema"
"gorm.io/gen"
"gorm.io/gen/field"
"gorm.io/plugin/dbresolver"
"github.com/coze-dev/coze-studio/backend/domain/modelmgr/internal/dal/model"
)
func newModelEntity(db *gorm.DB, opts ...gen.DOOption) modelEntity {
_modelEntity := modelEntity{}
_modelEntity.modelEntityDo.UseDB(db, opts...)
_modelEntity.modelEntityDo.UseModel(&model.ModelEntity{})
tableName := _modelEntity.modelEntityDo.TableName()
_modelEntity.ALL = field.NewAsterisk(tableName)
_modelEntity.ID = field.NewInt64(tableName, "id")
_modelEntity.MetaID = field.NewInt64(tableName, "meta_id")
_modelEntity.Name = field.NewString(tableName, "name")
_modelEntity.Description = field.NewString(tableName, "description")
_modelEntity.DefaultParams = field.NewField(tableName, "default_params")
_modelEntity.Scenario = field.NewField(tableName, "scenario")
_modelEntity.Status = field.NewField(tableName, "status")
_modelEntity.CreatedAt = field.NewInt64(tableName, "created_at")
_modelEntity.UpdatedAt = field.NewInt64(tableName, "updated_at")
_modelEntity.DeletedAt = field.NewField(tableName, "deleted_at")
_modelEntity.fillFieldMap()
return _modelEntity
}
// modelEntity 模型信息
type modelEntity struct {
modelEntityDo
ALL field.Asterisk
ID field.Int64 // 主键ID
MetaID field.Int64 // 模型元信息 id
Name field.String // 名称
Description field.String // 描述
DefaultParams field.Field // 默认参数
Scenario field.Field // 模型应用场景
Status field.Field // 模型状态
CreatedAt field.Int64 // Create Time in Milliseconds
UpdatedAt field.Int64 // Update Time in Milliseconds
DeletedAt field.Field // Delete Time in Milliseconds
fieldMap map[string]field.Expr
}
func (m modelEntity) Table(newTableName string) *modelEntity {
m.modelEntityDo.UseTable(newTableName)
return m.updateTableName(newTableName)
}
func (m modelEntity) As(alias string) *modelEntity {
m.modelEntityDo.DO = *(m.modelEntityDo.As(alias).(*gen.DO))
return m.updateTableName(alias)
}
func (m *modelEntity) updateTableName(table string) *modelEntity {
m.ALL = field.NewAsterisk(table)
m.ID = field.NewInt64(table, "id")
m.MetaID = field.NewInt64(table, "meta_id")
m.Name = field.NewString(table, "name")
m.Description = field.NewString(table, "description")
m.DefaultParams = field.NewField(table, "default_params")
m.Scenario = field.NewField(table, "scenario")
m.Status = field.NewField(table, "status")
m.CreatedAt = field.NewInt64(table, "created_at")
m.UpdatedAt = field.NewInt64(table, "updated_at")
m.DeletedAt = field.NewField(table, "deleted_at")
m.fillFieldMap()
return m
}
func (m *modelEntity) GetFieldByName(fieldName string) (field.OrderExpr, bool) {
_f, ok := m.fieldMap[fieldName]
if !ok || _f == nil {
return nil, false
}
_oe, ok := _f.(field.OrderExpr)
return _oe, ok
}
func (m *modelEntity) fillFieldMap() {
m.fieldMap = make(map[string]field.Expr, 10)
m.fieldMap["id"] = m.ID
m.fieldMap["meta_id"] = m.MetaID
m.fieldMap["name"] = m.Name
m.fieldMap["description"] = m.Description
m.fieldMap["default_params"] = m.DefaultParams
m.fieldMap["scenario"] = m.Scenario
m.fieldMap["status"] = m.Status
m.fieldMap["created_at"] = m.CreatedAt
m.fieldMap["updated_at"] = m.UpdatedAt
m.fieldMap["deleted_at"] = m.DeletedAt
}
func (m modelEntity) clone(db *gorm.DB) modelEntity {
m.modelEntityDo.ReplaceConnPool(db.Statement.ConnPool)
return m
}
func (m modelEntity) replaceDB(db *gorm.DB) modelEntity {
m.modelEntityDo.ReplaceDB(db)
return m
}
type modelEntityDo struct{ gen.DO }
type IModelEntityDo interface {
gen.SubQuery
Debug() IModelEntityDo
WithContext(ctx context.Context) IModelEntityDo
WithResult(fc func(tx gen.Dao)) gen.ResultInfo
ReplaceDB(db *gorm.DB)
ReadDB() IModelEntityDo
WriteDB() IModelEntityDo
As(alias string) gen.Dao
Session(config *gorm.Session) IModelEntityDo
Columns(cols ...field.Expr) gen.Columns
Clauses(conds ...clause.Expression) IModelEntityDo
Not(conds ...gen.Condition) IModelEntityDo
Or(conds ...gen.Condition) IModelEntityDo
Select(conds ...field.Expr) IModelEntityDo
Where(conds ...gen.Condition) IModelEntityDo
Order(conds ...field.Expr) IModelEntityDo
Distinct(cols ...field.Expr) IModelEntityDo
Omit(cols ...field.Expr) IModelEntityDo
Join(table schema.Tabler, on ...field.Expr) IModelEntityDo
LeftJoin(table schema.Tabler, on ...field.Expr) IModelEntityDo
RightJoin(table schema.Tabler, on ...field.Expr) IModelEntityDo
Group(cols ...field.Expr) IModelEntityDo
Having(conds ...gen.Condition) IModelEntityDo
Limit(limit int) IModelEntityDo
Offset(offset int) IModelEntityDo
Count() (count int64, err error)
Scopes(funcs ...func(gen.Dao) gen.Dao) IModelEntityDo
Unscoped() IModelEntityDo
Create(values ...*model.ModelEntity) error
CreateInBatches(values []*model.ModelEntity, batchSize int) error
Save(values ...*model.ModelEntity) error
First() (*model.ModelEntity, error)
Take() (*model.ModelEntity, error)
Last() (*model.ModelEntity, error)
Find() ([]*model.ModelEntity, error)
FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.ModelEntity, err error)
FindInBatches(result *[]*model.ModelEntity, batchSize int, fc func(tx gen.Dao, batch int) error) error
Pluck(column field.Expr, dest interface{}) error
Delete(...*model.ModelEntity) (info gen.ResultInfo, err error)
Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error)
UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error)
Updates(value interface{}) (info gen.ResultInfo, err error)
UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error)
UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error)
UpdateColumns(value interface{}) (info gen.ResultInfo, err error)
UpdateFrom(q gen.SubQuery) gen.Dao
Attrs(attrs ...field.AssignExpr) IModelEntityDo
Assign(attrs ...field.AssignExpr) IModelEntityDo
Joins(fields ...field.RelationField) IModelEntityDo
Preload(fields ...field.RelationField) IModelEntityDo
FirstOrInit() (*model.ModelEntity, error)
FirstOrCreate() (*model.ModelEntity, error)
FindByPage(offset int, limit int) (result []*model.ModelEntity, count int64, err error)
ScanByPage(result interface{}, offset int, limit int) (count int64, err error)
Scan(result interface{}) (err error)
Returning(value interface{}, columns ...string) IModelEntityDo
UnderlyingDB() *gorm.DB
schema.Tabler
}
func (m modelEntityDo) Debug() IModelEntityDo {
return m.withDO(m.DO.Debug())
}
func (m modelEntityDo) WithContext(ctx context.Context) IModelEntityDo {
return m.withDO(m.DO.WithContext(ctx))
}
func (m modelEntityDo) ReadDB() IModelEntityDo {
return m.Clauses(dbresolver.Read)
}
func (m modelEntityDo) WriteDB() IModelEntityDo {
return m.Clauses(dbresolver.Write)
}
func (m modelEntityDo) Session(config *gorm.Session) IModelEntityDo {
return m.withDO(m.DO.Session(config))
}
func (m modelEntityDo) Clauses(conds ...clause.Expression) IModelEntityDo {
return m.withDO(m.DO.Clauses(conds...))
}
func (m modelEntityDo) Returning(value interface{}, columns ...string) IModelEntityDo {
return m.withDO(m.DO.Returning(value, columns...))
}
func (m modelEntityDo) Not(conds ...gen.Condition) IModelEntityDo {
return m.withDO(m.DO.Not(conds...))
}
func (m modelEntityDo) Or(conds ...gen.Condition) IModelEntityDo {
return m.withDO(m.DO.Or(conds...))
}
func (m modelEntityDo) Select(conds ...field.Expr) IModelEntityDo {
return m.withDO(m.DO.Select(conds...))
}
func (m modelEntityDo) Where(conds ...gen.Condition) IModelEntityDo {
return m.withDO(m.DO.Where(conds...))
}
func (m modelEntityDo) Order(conds ...field.Expr) IModelEntityDo {
return m.withDO(m.DO.Order(conds...))
}
func (m modelEntityDo) Distinct(cols ...field.Expr) IModelEntityDo {
return m.withDO(m.DO.Distinct(cols...))
}
func (m modelEntityDo) Omit(cols ...field.Expr) IModelEntityDo {
return m.withDO(m.DO.Omit(cols...))
}
func (m modelEntityDo) Join(table schema.Tabler, on ...field.Expr) IModelEntityDo {
return m.withDO(m.DO.Join(table, on...))
}
func (m modelEntityDo) LeftJoin(table schema.Tabler, on ...field.Expr) IModelEntityDo {
return m.withDO(m.DO.LeftJoin(table, on...))
}
func (m modelEntityDo) RightJoin(table schema.Tabler, on ...field.Expr) IModelEntityDo {
return m.withDO(m.DO.RightJoin(table, on...))
}
func (m modelEntityDo) Group(cols ...field.Expr) IModelEntityDo {
return m.withDO(m.DO.Group(cols...))
}
func (m modelEntityDo) Having(conds ...gen.Condition) IModelEntityDo {
return m.withDO(m.DO.Having(conds...))
}
func (m modelEntityDo) Limit(limit int) IModelEntityDo {
return m.withDO(m.DO.Limit(limit))
}
func (m modelEntityDo) Offset(offset int) IModelEntityDo {
return m.withDO(m.DO.Offset(offset))
}
func (m modelEntityDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IModelEntityDo {
return m.withDO(m.DO.Scopes(funcs...))
}
func (m modelEntityDo) Unscoped() IModelEntityDo {
return m.withDO(m.DO.Unscoped())
}
func (m modelEntityDo) Create(values ...*model.ModelEntity) error {
if len(values) == 0 {
return nil
}
return m.DO.Create(values)
}
func (m modelEntityDo) CreateInBatches(values []*model.ModelEntity, batchSize int) error {
return m.DO.CreateInBatches(values, batchSize)
}
// Save : !!! underlying implementation is different with GORM
// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values)
func (m modelEntityDo) Save(values ...*model.ModelEntity) error {
if len(values) == 0 {
return nil
}
return m.DO.Save(values)
}
func (m modelEntityDo) First() (*model.ModelEntity, error) {
if result, err := m.DO.First(); err != nil {
return nil, err
} else {
return result.(*model.ModelEntity), nil
}
}
func (m modelEntityDo) Take() (*model.ModelEntity, error) {
if result, err := m.DO.Take(); err != nil {
return nil, err
} else {
return result.(*model.ModelEntity), nil
}
}
func (m modelEntityDo) Last() (*model.ModelEntity, error) {
if result, err := m.DO.Last(); err != nil {
return nil, err
} else {
return result.(*model.ModelEntity), nil
}
}
func (m modelEntityDo) Find() ([]*model.ModelEntity, error) {
result, err := m.DO.Find()
return result.([]*model.ModelEntity), err
}
func (m modelEntityDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.ModelEntity, err error) {
buf := make([]*model.ModelEntity, 0, batchSize)
err = m.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error {
defer func() { results = append(results, buf...) }()
return fc(tx, batch)
})
return results, err
}
func (m modelEntityDo) FindInBatches(result *[]*model.ModelEntity, batchSize int, fc func(tx gen.Dao, batch int) error) error {
return m.DO.FindInBatches(result, batchSize, fc)
}
func (m modelEntityDo) Attrs(attrs ...field.AssignExpr) IModelEntityDo {
return m.withDO(m.DO.Attrs(attrs...))
}
func (m modelEntityDo) Assign(attrs ...field.AssignExpr) IModelEntityDo {
return m.withDO(m.DO.Assign(attrs...))
}
func (m modelEntityDo) Joins(fields ...field.RelationField) IModelEntityDo {
for _, _f := range fields {
m = *m.withDO(m.DO.Joins(_f))
}
return &m
}
func (m modelEntityDo) Preload(fields ...field.RelationField) IModelEntityDo {
for _, _f := range fields {
m = *m.withDO(m.DO.Preload(_f))
}
return &m
}
func (m modelEntityDo) FirstOrInit() (*model.ModelEntity, error) {
if result, err := m.DO.FirstOrInit(); err != nil {
return nil, err
} else {
return result.(*model.ModelEntity), nil
}
}
func (m modelEntityDo) FirstOrCreate() (*model.ModelEntity, error) {
if result, err := m.DO.FirstOrCreate(); err != nil {
return nil, err
} else {
return result.(*model.ModelEntity), nil
}
}
func (m modelEntityDo) FindByPage(offset int, limit int) (result []*model.ModelEntity, count int64, err error) {
result, err = m.Offset(offset).Limit(limit).Find()
if err != nil {
return
}
if size := len(result); 0 < limit && 0 < size && size < limit {
count = int64(size + offset)
return
}
count, err = m.Offset(-1).Limit(-1).Count()
return
}
func (m modelEntityDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) {
count, err = m.Count()
if err != nil {
return
}
err = m.Offset(offset).Limit(limit).Scan(result)
return
}
func (m modelEntityDo) Scan(result interface{}) (err error) {
return m.DO.Scan(result)
}
func (m modelEntityDo) Delete(models ...*model.ModelEntity) (result gen.ResultInfo, err error) {
return m.DO.Delete(models)
}
func (m *modelEntityDo) withDO(do gen.Dao) *modelEntityDo {
m.DO = *do.(*gen.DO)
return m
}

View File

@@ -0,0 +1,425 @@
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
package query
import (
"context"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/schema"
"gorm.io/gen"
"gorm.io/gen/field"
"gorm.io/plugin/dbresolver"
"github.com/coze-dev/coze-studio/backend/domain/modelmgr/internal/dal/model"
)
func newModelMeta(db *gorm.DB, opts ...gen.DOOption) modelMeta {
_modelMeta := modelMeta{}
_modelMeta.modelMetaDo.UseDB(db, opts...)
_modelMeta.modelMetaDo.UseModel(&model.ModelMeta{})
tableName := _modelMeta.modelMetaDo.TableName()
_modelMeta.ALL = field.NewAsterisk(tableName)
_modelMeta.ID = field.NewInt64(tableName, "id")
_modelMeta.ModelName = field.NewString(tableName, "model_name")
_modelMeta.Protocol = field.NewString(tableName, "protocol")
_modelMeta.IconURI = field.NewString(tableName, "icon_uri")
_modelMeta.Capability = field.NewField(tableName, "capability")
_modelMeta.ConnConfig = field.NewField(tableName, "conn_config")
_modelMeta.Status = field.NewField(tableName, "status")
_modelMeta.Description = field.NewString(tableName, "description")
_modelMeta.CreatedAt = field.NewInt64(tableName, "created_at")
_modelMeta.UpdatedAt = field.NewInt64(tableName, "updated_at")
_modelMeta.DeletedAt = field.NewField(tableName, "deleted_at")
_modelMeta.IconURL = field.NewString(tableName, "icon_url")
_modelMeta.fillFieldMap()
return _modelMeta
}
// modelMeta 模型元信息
type modelMeta struct {
modelMetaDo
ALL field.Asterisk
ID field.Int64 // 主键ID
ModelName field.String // 模型名称
Protocol field.String // 模型协议
IconURI field.String // Icon URI
Capability field.Field // 模型能力
ConnConfig field.Field // 模型连接配置
Status field.Field // 模型状态
Description field.String // 模型描述
CreatedAt field.Int64 // Create Time in Milliseconds
UpdatedAt field.Int64 // Update Time in Milliseconds
DeletedAt field.Field // Delete Time in Milliseconds
IconURL field.String // Icon URL
fieldMap map[string]field.Expr
}
func (m modelMeta) Table(newTableName string) *modelMeta {
m.modelMetaDo.UseTable(newTableName)
return m.updateTableName(newTableName)
}
func (m modelMeta) As(alias string) *modelMeta {
m.modelMetaDo.DO = *(m.modelMetaDo.As(alias).(*gen.DO))
return m.updateTableName(alias)
}
func (m *modelMeta) updateTableName(table string) *modelMeta {
m.ALL = field.NewAsterisk(table)
m.ID = field.NewInt64(table, "id")
m.ModelName = field.NewString(table, "model_name")
m.Protocol = field.NewString(table, "protocol")
m.IconURI = field.NewString(table, "icon_uri")
m.Capability = field.NewField(table, "capability")
m.ConnConfig = field.NewField(table, "conn_config")
m.Status = field.NewField(table, "status")
m.Description = field.NewString(table, "description")
m.CreatedAt = field.NewInt64(table, "created_at")
m.UpdatedAt = field.NewInt64(table, "updated_at")
m.DeletedAt = field.NewField(table, "deleted_at")
m.IconURL = field.NewString(table, "icon_url")
m.fillFieldMap()
return m
}
func (m *modelMeta) GetFieldByName(fieldName string) (field.OrderExpr, bool) {
_f, ok := m.fieldMap[fieldName]
if !ok || _f == nil {
return nil, false
}
_oe, ok := _f.(field.OrderExpr)
return _oe, ok
}
func (m *modelMeta) fillFieldMap() {
m.fieldMap = make(map[string]field.Expr, 12)
m.fieldMap["id"] = m.ID
m.fieldMap["model_name"] = m.ModelName
m.fieldMap["protocol"] = m.Protocol
m.fieldMap["icon_uri"] = m.IconURI
m.fieldMap["capability"] = m.Capability
m.fieldMap["conn_config"] = m.ConnConfig
m.fieldMap["status"] = m.Status
m.fieldMap["description"] = m.Description
m.fieldMap["created_at"] = m.CreatedAt
m.fieldMap["updated_at"] = m.UpdatedAt
m.fieldMap["deleted_at"] = m.DeletedAt
m.fieldMap["icon_url"] = m.IconURL
}
func (m modelMeta) clone(db *gorm.DB) modelMeta {
m.modelMetaDo.ReplaceConnPool(db.Statement.ConnPool)
return m
}
func (m modelMeta) replaceDB(db *gorm.DB) modelMeta {
m.modelMetaDo.ReplaceDB(db)
return m
}
type modelMetaDo struct{ gen.DO }
type IModelMetaDo interface {
gen.SubQuery
Debug() IModelMetaDo
WithContext(ctx context.Context) IModelMetaDo
WithResult(fc func(tx gen.Dao)) gen.ResultInfo
ReplaceDB(db *gorm.DB)
ReadDB() IModelMetaDo
WriteDB() IModelMetaDo
As(alias string) gen.Dao
Session(config *gorm.Session) IModelMetaDo
Columns(cols ...field.Expr) gen.Columns
Clauses(conds ...clause.Expression) IModelMetaDo
Not(conds ...gen.Condition) IModelMetaDo
Or(conds ...gen.Condition) IModelMetaDo
Select(conds ...field.Expr) IModelMetaDo
Where(conds ...gen.Condition) IModelMetaDo
Order(conds ...field.Expr) IModelMetaDo
Distinct(cols ...field.Expr) IModelMetaDo
Omit(cols ...field.Expr) IModelMetaDo
Join(table schema.Tabler, on ...field.Expr) IModelMetaDo
LeftJoin(table schema.Tabler, on ...field.Expr) IModelMetaDo
RightJoin(table schema.Tabler, on ...field.Expr) IModelMetaDo
Group(cols ...field.Expr) IModelMetaDo
Having(conds ...gen.Condition) IModelMetaDo
Limit(limit int) IModelMetaDo
Offset(offset int) IModelMetaDo
Count() (count int64, err error)
Scopes(funcs ...func(gen.Dao) gen.Dao) IModelMetaDo
Unscoped() IModelMetaDo
Create(values ...*model.ModelMeta) error
CreateInBatches(values []*model.ModelMeta, batchSize int) error
Save(values ...*model.ModelMeta) error
First() (*model.ModelMeta, error)
Take() (*model.ModelMeta, error)
Last() (*model.ModelMeta, error)
Find() ([]*model.ModelMeta, error)
FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.ModelMeta, err error)
FindInBatches(result *[]*model.ModelMeta, batchSize int, fc func(tx gen.Dao, batch int) error) error
Pluck(column field.Expr, dest interface{}) error
Delete(...*model.ModelMeta) (info gen.ResultInfo, err error)
Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error)
UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error)
Updates(value interface{}) (info gen.ResultInfo, err error)
UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error)
UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error)
UpdateColumns(value interface{}) (info gen.ResultInfo, err error)
UpdateFrom(q gen.SubQuery) gen.Dao
Attrs(attrs ...field.AssignExpr) IModelMetaDo
Assign(attrs ...field.AssignExpr) IModelMetaDo
Joins(fields ...field.RelationField) IModelMetaDo
Preload(fields ...field.RelationField) IModelMetaDo
FirstOrInit() (*model.ModelMeta, error)
FirstOrCreate() (*model.ModelMeta, error)
FindByPage(offset int, limit int) (result []*model.ModelMeta, count int64, err error)
ScanByPage(result interface{}, offset int, limit int) (count int64, err error)
Scan(result interface{}) (err error)
Returning(value interface{}, columns ...string) IModelMetaDo
UnderlyingDB() *gorm.DB
schema.Tabler
}
func (m modelMetaDo) Debug() IModelMetaDo {
return m.withDO(m.DO.Debug())
}
func (m modelMetaDo) WithContext(ctx context.Context) IModelMetaDo {
return m.withDO(m.DO.WithContext(ctx))
}
func (m modelMetaDo) ReadDB() IModelMetaDo {
return m.Clauses(dbresolver.Read)
}
func (m modelMetaDo) WriteDB() IModelMetaDo {
return m.Clauses(dbresolver.Write)
}
func (m modelMetaDo) Session(config *gorm.Session) IModelMetaDo {
return m.withDO(m.DO.Session(config))
}
func (m modelMetaDo) Clauses(conds ...clause.Expression) IModelMetaDo {
return m.withDO(m.DO.Clauses(conds...))
}
func (m modelMetaDo) Returning(value interface{}, columns ...string) IModelMetaDo {
return m.withDO(m.DO.Returning(value, columns...))
}
func (m modelMetaDo) Not(conds ...gen.Condition) IModelMetaDo {
return m.withDO(m.DO.Not(conds...))
}
func (m modelMetaDo) Or(conds ...gen.Condition) IModelMetaDo {
return m.withDO(m.DO.Or(conds...))
}
func (m modelMetaDo) Select(conds ...field.Expr) IModelMetaDo {
return m.withDO(m.DO.Select(conds...))
}
func (m modelMetaDo) Where(conds ...gen.Condition) IModelMetaDo {
return m.withDO(m.DO.Where(conds...))
}
func (m modelMetaDo) Order(conds ...field.Expr) IModelMetaDo {
return m.withDO(m.DO.Order(conds...))
}
func (m modelMetaDo) Distinct(cols ...field.Expr) IModelMetaDo {
return m.withDO(m.DO.Distinct(cols...))
}
func (m modelMetaDo) Omit(cols ...field.Expr) IModelMetaDo {
return m.withDO(m.DO.Omit(cols...))
}
func (m modelMetaDo) Join(table schema.Tabler, on ...field.Expr) IModelMetaDo {
return m.withDO(m.DO.Join(table, on...))
}
func (m modelMetaDo) LeftJoin(table schema.Tabler, on ...field.Expr) IModelMetaDo {
return m.withDO(m.DO.LeftJoin(table, on...))
}
func (m modelMetaDo) RightJoin(table schema.Tabler, on ...field.Expr) IModelMetaDo {
return m.withDO(m.DO.RightJoin(table, on...))
}
func (m modelMetaDo) Group(cols ...field.Expr) IModelMetaDo {
return m.withDO(m.DO.Group(cols...))
}
func (m modelMetaDo) Having(conds ...gen.Condition) IModelMetaDo {
return m.withDO(m.DO.Having(conds...))
}
func (m modelMetaDo) Limit(limit int) IModelMetaDo {
return m.withDO(m.DO.Limit(limit))
}
func (m modelMetaDo) Offset(offset int) IModelMetaDo {
return m.withDO(m.DO.Offset(offset))
}
func (m modelMetaDo) Scopes(funcs ...func(gen.Dao) gen.Dao) IModelMetaDo {
return m.withDO(m.DO.Scopes(funcs...))
}
func (m modelMetaDo) Unscoped() IModelMetaDo {
return m.withDO(m.DO.Unscoped())
}
func (m modelMetaDo) Create(values ...*model.ModelMeta) error {
if len(values) == 0 {
return nil
}
return m.DO.Create(values)
}
func (m modelMetaDo) CreateInBatches(values []*model.ModelMeta, batchSize int) error {
return m.DO.CreateInBatches(values, batchSize)
}
// Save : !!! underlying implementation is different with GORM
// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values)
func (m modelMetaDo) Save(values ...*model.ModelMeta) error {
if len(values) == 0 {
return nil
}
return m.DO.Save(values)
}
func (m modelMetaDo) First() (*model.ModelMeta, error) {
if result, err := m.DO.First(); err != nil {
return nil, err
} else {
return result.(*model.ModelMeta), nil
}
}
func (m modelMetaDo) Take() (*model.ModelMeta, error) {
if result, err := m.DO.Take(); err != nil {
return nil, err
} else {
return result.(*model.ModelMeta), nil
}
}
func (m modelMetaDo) Last() (*model.ModelMeta, error) {
if result, err := m.DO.Last(); err != nil {
return nil, err
} else {
return result.(*model.ModelMeta), nil
}
}
func (m modelMetaDo) Find() ([]*model.ModelMeta, error) {
result, err := m.DO.Find()
return result.([]*model.ModelMeta), err
}
func (m modelMetaDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.ModelMeta, err error) {
buf := make([]*model.ModelMeta, 0, batchSize)
err = m.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error {
defer func() { results = append(results, buf...) }()
return fc(tx, batch)
})
return results, err
}
func (m modelMetaDo) FindInBatches(result *[]*model.ModelMeta, batchSize int, fc func(tx gen.Dao, batch int) error) error {
return m.DO.FindInBatches(result, batchSize, fc)
}
func (m modelMetaDo) Attrs(attrs ...field.AssignExpr) IModelMetaDo {
return m.withDO(m.DO.Attrs(attrs...))
}
func (m modelMetaDo) Assign(attrs ...field.AssignExpr) IModelMetaDo {
return m.withDO(m.DO.Assign(attrs...))
}
func (m modelMetaDo) Joins(fields ...field.RelationField) IModelMetaDo {
for _, _f := range fields {
m = *m.withDO(m.DO.Joins(_f))
}
return &m
}
func (m modelMetaDo) Preload(fields ...field.RelationField) IModelMetaDo {
for _, _f := range fields {
m = *m.withDO(m.DO.Preload(_f))
}
return &m
}
func (m modelMetaDo) FirstOrInit() (*model.ModelMeta, error) {
if result, err := m.DO.FirstOrInit(); err != nil {
return nil, err
} else {
return result.(*model.ModelMeta), nil
}
}
func (m modelMetaDo) FirstOrCreate() (*model.ModelMeta, error) {
if result, err := m.DO.FirstOrCreate(); err != nil {
return nil, err
} else {
return result.(*model.ModelMeta), nil
}
}
func (m modelMetaDo) FindByPage(offset int, limit int) (result []*model.ModelMeta, count int64, err error) {
result, err = m.Offset(offset).Limit(limit).Find()
if err != nil {
return
}
if size := len(result); 0 < limit && 0 < size && size < limit {
count = int64(size + offset)
return
}
count, err = m.Offset(-1).Limit(-1).Count()
return
}
func (m modelMetaDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) {
count, err = m.Count()
if err != nil {
return
}
err = m.Offset(offset).Limit(limit).Scan(result)
return
}
func (m modelMetaDo) Scan(result interface{}) (err error) {
return m.DO.Scan(result)
}
func (m modelMetaDo) Delete(models ...*model.ModelMeta) (result gen.ResultInfo, err error) {
return m.DO.Delete(models)
}
func (m *modelMetaDo) withDO(do gen.Dao) *modelMetaDo {
m.DO = *do.(*gen.DO)
return m
}

View File

@@ -0,0 +1,389 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package service
import (
"context"
"encoding/json"
"fmt"
"time"
"gorm.io/gorm"
modelmgrModel "github.com/coze-dev/coze-studio/backend/api/model/crossdomain/modelmgr"
"github.com/coze-dev/coze-studio/backend/domain/modelmgr"
"github.com/coze-dev/coze-studio/backend/domain/modelmgr/entity"
"github.com/coze-dev/coze-studio/backend/domain/modelmgr/internal/dal/dao"
dmodel "github.com/coze-dev/coze-studio/backend/domain/modelmgr/internal/dal/model"
uploadEntity "github.com/coze-dev/coze-studio/backend/domain/upload/entity"
modelcontract "github.com/coze-dev/coze-studio/backend/infra/contract/chatmodel"
"github.com/coze-dev/coze-studio/backend/infra/contract/idgen"
"github.com/coze-dev/coze-studio/backend/infra/contract/storage"
"github.com/coze-dev/coze-studio/backend/pkg/lang/slices"
)
func NewModelManager(db *gorm.DB, idgen idgen.IDGenerator, oss storage.Storage) modelmgr.Manager {
return &modelManager{
idgen: idgen,
oss: oss,
modelMetaRepo: dao.NewModelMetaDAO(db),
modelEntityRepo: dao.NewModelEntityDAO(db),
}
}
type modelManager struct {
idgen idgen.IDGenerator
oss storage.Storage
modelMetaRepo dao.ModelMetaRepo
modelEntityRepo dao.ModelEntityRepo
}
func (m *modelManager) CreateModelMeta(ctx context.Context, meta *entity.ModelMeta) (resp *entity.ModelMeta, err error) {
if err = m.alignProtocol(meta); err != nil {
return nil, err
}
id := meta.ID
if id == 0 {
id, err = m.idgen.GenID(ctx)
if err != nil {
return nil, err
}
}
desc, err := json.Marshal(meta.Description)
if err != nil {
return nil, err
}
now := time.Now().UnixMilli()
if err = m.modelMetaRepo.Create(ctx, &dmodel.ModelMeta{
ID: id,
ModelName: meta.Name,
Protocol: string(meta.Protocol),
IconURI: meta.IconURI,
IconURL: meta.IconURL,
Capability: meta.Capability,
ConnConfig: meta.ConnConfig,
Status: meta.Status,
Description: string(desc),
CreatedAt: now,
UpdatedAt: now,
DeletedAt: gorm.DeletedAt{},
}); err != nil {
return nil, err
}
return &entity.ModelMeta{
ID: id,
Name: meta.Name,
Description: meta.Description,
CreatedAtMs: now,
UpdatedAtMs: now,
Protocol: meta.Protocol,
Capability: meta.Capability,
ConnConfig: meta.ConnConfig,
Status: meta.Status,
}, nil
}
func (m *modelManager) UpdateModelMetaStatus(ctx context.Context, id int64, status entity.ModelMetaStatus) error {
return m.modelMetaRepo.UpdateStatus(ctx, id, status)
}
func (m *modelManager) DeleteModelMeta(ctx context.Context, id int64) error {
return m.modelMetaRepo.Delete(ctx, id)
}
func (m *modelManager) ListModelMeta(ctx context.Context, req *modelmgr.ListModelMetaRequest) (*modelmgr.ListModelMetaResponse, error) {
status := req.Status
if len(status) == 0 {
status = []entity.ModelMetaStatus{modelmgrModel.StatusInUse}
}
pos, next, hasMore, err := m.modelMetaRepo.List(ctx, req.FuzzyModelName, status, req.Limit, req.Cursor)
if err != nil {
return nil, err
}
dos, err := m.fromModelMetaPOs(ctx, pos)
if err != nil {
return nil, err
}
return &modelmgr.ListModelMetaResponse{
ModelMetaList: dos,
HasMore: hasMore,
NextCursor: next,
}, nil
}
func (m *modelManager) MGetModelMetaByID(ctx context.Context, req *modelmgr.MGetModelMetaRequest) ([]*entity.ModelMeta, error) {
if len(req.IDs) == 0 {
return nil, nil
}
pos, err := m.modelMetaRepo.MGetByID(ctx, req.IDs)
if err != nil {
return nil, err
}
dos, err := m.fromModelMetaPOs(ctx, pos)
if err != nil {
return nil, err
}
return dos, nil
}
func (m *modelManager) CreateModel(ctx context.Context, e *entity.Model) (*entity.Model, error) {
// check if meta id exists
metaPO, err := m.modelMetaRepo.GetByID(ctx, e.Meta.ID)
if err != nil {
return nil, err
}
if metaPO == nil {
return nil, fmt.Errorf("[CreateModel] mode meta not found, model_meta id=%d", e.Meta.ID)
}
id := e.ID
if id == 0 {
id, err = m.idgen.GenID(ctx)
if err != nil {
return nil, err
}
}
now := time.Now().UnixMilli()
// TODO(@fanlv) : do -> po 放到 dal 里面去
if err = m.modelEntityRepo.Create(ctx, &dmodel.ModelEntity{
ID: id,
MetaID: e.Meta.ID,
Name: e.Name,
Description: e.Description,
DefaultParams: e.DefaultParameters,
Status: modelmgrModel.ModelEntityStatusInUse,
CreatedAt: now,
UpdatedAt: now,
}); err != nil {
return nil, err
}
resp := &entity.Model{
Model: &modelmgrModel.Model{
ID: id,
Name: e.Name,
CreatedAtMs: now,
UpdatedAtMs: now,
Meta: e.Meta,
},
}
return resp, nil
}
func (m *modelManager) DeleteModel(ctx context.Context, id int64) error {
return m.modelEntityRepo.Delete(ctx, id)
}
func (m *modelManager) ListModel(ctx context.Context, req *modelmgr.ListModelRequest) (*modelmgr.ListModelResponse, error) {
var sc *int64
status := req.Status
if len(status) == 0 {
status = []modelmgrModel.ModelEntityStatus{modelmgrModel.ModelEntityStatusDefault, modelmgrModel.ModelEntityStatusInUse}
}
pos, next, hasMore, err := m.modelEntityRepo.List(ctx, req.FuzzyModelName, sc, status, req.Limit, req.Cursor)
if err != nil {
return nil, err
}
pos = moveDefaultModelToFirst(pos)
resp, err := m.fromModelPOs(ctx, pos)
if err != nil {
return nil, err
}
return &modelmgr.ListModelResponse{
ModelList: resp,
HasMore: hasMore,
NextCursor: next,
}, nil
}
func (m *modelManager) MGetModelByID(ctx context.Context, req *modelmgr.MGetModelRequest) ([]*entity.Model, error) {
if len(req.IDs) == 0 {
return nil, nil
}
pos, err := m.modelEntityRepo.MGet(ctx, req.IDs)
if err != nil {
return nil, err
}
resp, err := m.fromModelPOs(ctx, pos)
if err != nil {
return nil, err
}
return resp, nil
}
func (m *modelManager) alignProtocol(meta *entity.ModelMeta) error {
if meta.Protocol == "" {
return fmt.Errorf("protocol not provided")
}
config := meta.ConnConfig
if config == nil {
return fmt.Errorf("ConnConfig not provided, protocol=%s", meta.Protocol)
}
return nil
}
func (m *modelManager) fromModelMetaPOs(ctx context.Context, pos []*dmodel.ModelMeta) ([]*entity.ModelMeta, error) {
uris := make(map[string]string)
for _, po := range pos {
if po == nil || po.IconURL != "" {
continue
}
if po.IconURI == "" {
po.IconURI = uploadEntity.ModelIconURI
}
uris[po.IconURI] = ""
}
for uri := range uris {
url, err := m.oss.GetObjectUrl(ctx, uri)
if err != nil {
return nil, err
}
uris[uri] = url
}
dos, err := slices.TransformWithErrorCheck(pos, func(po *dmodel.ModelMeta) (*entity.ModelMeta, error) {
if po == nil {
return nil, nil
}
url := po.IconURL
if url == "" {
url = uris[po.IconURI]
}
desc := &modelmgrModel.MultilingualText{}
if unmarshalErr := json.Unmarshal([]byte(po.Description), desc); unmarshalErr != nil {
return nil, unmarshalErr
}
return &entity.ModelMeta{
ID: po.ID,
Name: po.ModelName,
IconURI: po.IconURI,
IconURL: url,
Description: desc,
CreatedAtMs: po.CreatedAt,
UpdatedAtMs: po.UpdatedAt,
DeletedAtMs: po.DeletedAt.Time.UnixMilli(),
Protocol: modelcontract.Protocol(po.Protocol),
Capability: po.Capability,
ConnConfig: po.ConnConfig,
Status: po.Status,
}, nil
})
if err != nil {
return nil, err
}
return dos, nil
}
func (m *modelManager) fromModelPOs(ctx context.Context, pos []*dmodel.ModelEntity) ([]*entity.Model, error) {
if len(pos) == 0 {
return nil, nil
}
resp := make([]*entity.Model, 0, len(pos))
metaIDSet := make(map[int64]struct{})
for _, po := range pos {
resp = append(resp, &entity.Model{
Model: &modelmgrModel.Model{
ID: po.ID,
Name: po.Name,
Description: po.Description,
DefaultParameters: po.DefaultParams,
CreatedAtMs: po.CreatedAt,
UpdatedAtMs: po.UpdatedAt,
Meta: entity.ModelMeta{
ID: po.MetaID,
},
},
})
metaIDSet[po.MetaID] = struct{}{}
}
metaIDSlice := make([]int64, 0, len(metaIDSet))
for id := range metaIDSet {
metaIDSlice = append(metaIDSlice, id)
}
modelMetaSlice, err := m.MGetModelMetaByID(ctx, &modelmgr.MGetModelMetaRequest{IDs: metaIDSlice})
if err != nil {
return nil, err
}
metaID2Meta := make(map[int64]*entity.ModelMeta)
for i := range modelMetaSlice {
item := modelMetaSlice[i]
if item.IconURL == "" {
url, err := m.oss.GetObjectUrl(ctx, item.IconURI)
if err != nil {
return nil, err
}
item.IconURL = url
}
metaID2Meta[item.ID] = item
}
for _, r := range resp {
meta, found := metaID2Meta[r.Meta.ID]
if !found {
return nil, fmt.Errorf("[ListModel] model meta not found, model_entity id=%v, model_meta id=%v", r.ID, r.Meta.ID)
}
r.Meta = *meta
}
return resp, nil
}
func moveDefaultModelToFirst(ms []*dmodel.ModelEntity) []*dmodel.ModelEntity {
orders := make([]*dmodel.ModelEntity, len(ms))
copy(orders, ms)
for i, m := range orders {
if i != 0 && m.Status == modelmgrModel.ModelEntityStatusDefault {
orders[0], orders[i] = orders[i], orders[0]
break
}
}
return orders
}

View File

@@ -0,0 +1,41 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package service
// TODO: 考虑到 model manager 被外部高频读+运行,修改/删除频率很低,基本没有实时更新需求,可进行 cache
// 1. model_meta
// 2. model_entity
// 3. ChatModel
// func (m *modelManager) buildOptions(req *model.ChatRequest) []cm.Option {
// var opts []cm.Option
//
// if len(req.Tools) > 0 {
// opts = append(opts, cm.WithTools(req.Tools))
// }
// if req.Temperature != nil {
// opts = append(opts, cm.WithTemperature(float32(*req.Temperature)))
// }
// if req.MaxTokens != nil {
// opts = append(opts, cm.WithMaxTokens(*req.MaxTokens))
// }
// if req.TopP != nil {
// opts = append(opts, cm.WithTopP(float32(*req.TopP)))
// }
// // TODO: support frequency_penalty, presence_penalty, top_k
// return opts
//}