57 lines
1.6 KiB
Go
57 lines
1.6 KiB
Go
|
|
package proxy
|
|||
|
|
|
|||
|
|
import (
|
|||
|
|
"context"
|
|||
|
|
|
|||
|
|
"apps/backend/internal/middleware"
|
|||
|
|
usageDomain "apps/backend/internal/module/usage/domain"
|
|||
|
|
"apps/backend/internal/response"
|
|||
|
|
"apps/backend/internal/svc"
|
|||
|
|
"apps/backend/internal/types"
|
|||
|
|
|
|||
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
type AICompleteLogic struct {
|
|||
|
|
logx.Logger
|
|||
|
|
ctx context.Context
|
|||
|
|
svcCtx *svc.ServiceContext
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
func NewAICompleteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AICompleteLogic {
|
|||
|
|
return &AICompleteLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
func (l *AICompleteLogic) AIComplete(req *types.AICompleteReq) (*types.AICompleteData, error) {
|
|||
|
|
if l.svcCtx.Usage == nil || l.svcCtx.AI == nil || l.svcCtx.KeyResolver == nil {
|
|||
|
|
return nil, response.Biz(503, 503001, "ai proxy not configured")
|
|||
|
|
}
|
|||
|
|
uid, ok := middleware.UIDFrom(l.ctx)
|
|||
|
|
if !ok {
|
|||
|
|
return nil, response.Biz(401, 401001, "missing authorization")
|
|||
|
|
}
|
|||
|
|
meter := req.Meter
|
|||
|
|
if meter == "" {
|
|||
|
|
meter = usageDomain.MeterAICopy
|
|||
|
|
}
|
|||
|
|
mode, err := l.svcCtx.Usage.PrepareCall(l.ctx, uid, meter)
|
|||
|
|
if err != nil {
|
|||
|
|
return nil, err
|
|||
|
|
}
|
|||
|
|
mode, apiKey, err := l.svcCtx.KeyResolver.ResolveKey(l.ctx, uid, meter)
|
|||
|
|
if err != nil {
|
|||
|
|
return nil, err
|
|||
|
|
}
|
|||
|
|
model := req.Model
|
|||
|
|
if model == "" {
|
|||
|
|
model = "grok-3"
|
|||
|
|
}
|
|||
|
|
// 語言 system prompt 已由 middleware 注入 ctx;AI client 強制加 system message
|
|||
|
|
text, err := l.svcCtx.AI.Complete(l.ctx, apiKey, model, req.Prompt)
|
|||
|
|
if err != nil {
|
|||
|
|
return nil, response.Biz(502, 502001, err.Error())
|
|||
|
|
}
|
|||
|
|
_, _ = l.svcCtx.Usage.RecordCall(l.ctx, uid, meter, mode, "AI complete", "proxy.ai")
|
|||
|
|
return &types.AICompleteData{Text: text, KeyMode: mode, Model: model}, nil
|
|||
|
|
}
|