Files
ai-agent/workflow/service/flow/lambda_node.go
2026-06-08 13:39:20 +08:00

396 lines
12 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package flow
import (
"ai-agent/workflow/consts/flow"
"ai-agent/workflow/consts/node"
"ai-agent/workflow/consts/public"
fileDao "ai-agent/workflow/dao/file"
flowDao "ai-agent/workflow/dao/flow"
"ai-agent/workflow/model/dto"
fileDto "ai-agent/workflow/model/dto/file"
flowDto "ai-agent/workflow/model/dto/flow"
"context"
"fmt"
"strconv"
"strings"
"time"
"gitea.com/red-future/common/db/gfdb"
"gitea.com/red-future/common/utils"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/util/gconv"
)
func StartLambda(ctx context.Context, input any) (any, error) {
return input, nil
}
func FormLambda(ctx context.Context, input any) (any, error) {
return input, nil
}
func IntentLambda(ctx context.Context, input any) (any, error) {
return input, nil
}
// JudgeLambda 分支判断核心读取IntentLambda的输出 → 返回目标节点ID做路由
func JudgeLambda(ctx context.Context, input any) (string, error) {
nodeInput, ok := input.(*flowDto.NodeExecutionInput)
if !ok {
return "", fmt.Errorf("入参类型错误,期望 *flowDto.NodeExecutionInput实际 %T", input)
}
// 1. 直接用你原来的方法(返回两个 map
inputMap, outputMap, modelMap := GetNodeContextContent(nodeInput.Global, nodeInput.Config)
var outputResult []node.NodeFormField
for _, valueAny := range inputMap {
if field, ok := valueAny.(node.NodeFormField); ok {
outputResult = append(outputResult, field)
}
}
for _, valueAny := range outputMap {
if field, ok := valueAny.(node.NodeFormField); ok {
outputResult = append(outputResult, field)
}
}
for _, valueAny := range modelMap {
if field, ok := valueAny.(node.NodeFormField); ok {
outputResult = append(outputResult, field)
}
}
contextParts := ""
for _, v := range nodeInput.Config.FormConfig {
contextParts = fmt.Sprintf("%s,%s:%s", contextParts, v.Label, v.Value)
}
if !nodeInput.Global.IsDialogue {
for _, v := range outputResult {
contextParts = fmt.Sprintf("%s,%s:%s", contextParts, v.Label, v.Value)
}
}
if !g.IsEmpty(nodeInput.Global.Desc) {
contextParts = fmt.Sprintf("%s,%s:%s", contextParts, "描述", nodeInput.Global.Desc)
}
configMap := gconv.Map(nodeInput.Config.Config)
ids := gconv.Strings(configMap["branch_ids"])
branchIdNameMap := gconv.Map(configMap["branch_id_name_map"])
// 【重构】构建提示词展示ID和对应的名称
var branchIdNameLines []string
for _, id := range ids {
name := gconv.String(branchIdNameMap[id])
branchIdNameLines = append(branchIdNameLines, fmt.Sprintf("%s: %s", id, name))
}
getIsChatModel, err := GetIsChatModel(ctx)
if err != nil {
return "", err
}
req := flowDto.ComposeMessagesReq{
BuildType: 2,
ModelName: getIsChatModel.ModelName,
SkillName: "",
Cause: "判断节点",
Form: map[string]any{"prompt": strings.Join(branchIdNameLines, "\n")},
UserForm: map[string]any{"prompt": contextParts},
UserFiles: nodeInput.Global.FileUrl,
SessionId: nodeInput.Global.SessionId,
}
msg, err := ComposeMessages(ctx, &req)
if err != nil {
return "", err
}
if g.IsEmpty(msg.Messages) {
return "", fmt.Errorf("msg is empty")
}
content := ""
for key, _ := range getIsChatModel.ResponseBody {
content = gconv.String(msg.Messages[key])
}
fmt.Printf("JudgeLambda路由目标节点ID=%s\n", gconv.String(content))
return content, nil
}
// TextModelLambda 构建文案
func TextModelLambda(ctx context.Context, input any) (any, error) {
nodeInput, ok := input.(*flowDto.NodeExecutionInput)
if !ok {
return nil, fmt.Errorf("入参类型错误")
}
skillName, from, userFrom := BuildParam(nodeInput)
outputRes, err := TextNode(ctx, nodeInput.Global.SessionId, nodeInput.Config.ModelConfig.ModelName, skillName, from, userFrom, nodeInput.Config.ModelConfig.ModelResponse, nodeInput.Global.FileUrl)
if err != nil {
return nil, err
}
nodeInput.Config.OutputResult = outputRes
return nodeInput, nil
}
// ImageModelLambda 构建图片
func ImageModelLambda(ctx context.Context, input any) (any, error) {
nodeInput, ok := input.(*flowDto.NodeExecutionInput)
if !ok {
return nil, fmt.Errorf("入参类型错误")
}
skillName, from, userFrom := BuildParam(nodeInput)
outputRes, err := ImgNode(ctx, nodeInput.Global.SessionId, nodeInput.Config.ModelConfig.ModelName, skillName, from, userFrom, nodeInput.Config.ModelConfig.ModelResponse, nodeInput.Global.FileUrl)
if err != nil {
return nil, err
}
nodeInput.Config.OutputResult = outputRes
return nodeInput, nil
}
func MergeLambda(ctx context.Context, input any) (any, error) {
nodeInput, ok := input.(*flowDto.NodeExecutionInput)
if !ok {
return nil, fmt.Errorf("汇总节点入参类型错误")
}
// 1. 把所有节点输出拍平成 字段名->内容 的map
dataMap := make(map[string]node.NodeFormField)
_, outputMap, _ := GetNodeContextContent(nodeInput.Global, nodeInput.Config)
for _, valueAny := range outputMap {
if field, ok := valueAny.(node.NodeFormField); ok {
dataMap[field.Field] = field
}
}
// 2. 提取所有文案text_content_0,1,2...
var contents []node.NodeFormField
for i := 0; ; i++ {
key := fmt.Sprintf("text_url:%d", i)
val, has := dataMap[key]
if !has || val.Value == "" {
break
}
contents = append(contents, val)
}
// 3. 提取所有图片image_0,1,2...
var images []string
for i := 0; ; i++ {
key := fmt.Sprintf("img_url:%d", i)
val, has := dataMap[key]
if !has || val.Value == "" {
break
}
images = append(images, val.Value)
}
// 4. 🔥 核心算法:图片按顺序连续归属给每条文案
textImgMap := make(map[int][]string) // key:文案下标value:图片列表
if len(contents) > 0 && len(images) > 0 {
imgIndex := 0 // 当前用到第几张图片
totalImg := len(images)
for i, item := range contents {
// 图片已分配完,直接退出
if imgIndex >= totalImg {
break
}
// 当前文案需要挂载的图片数量
needCount := gconv.Int(item.Expand)
if needCount <= 0 {
continue
}
var imgList []string
for imgc := 0; imgc < needCount; imgc++ {
// 关键:必须判断是否越界
if imgIndex >= totalImg {
break
}
imgList = append(imgList, images[imgIndex])
imgIndex++
}
// 有图片才存入 map
if len(imgList) > 0 {
textImgMap[i] = imgList
}
}
}
type Item struct {
Content string // 文案(可为空)
Images []string // 图片(可空、可多张)
}
// 🔥 把现有数据转换成通用 Item 列表(支持:纯文案、纯图片、图文任意组合)
var allItems []Item
url, err := utils.GetFileAddressPrefix(ctx)
if err != nil {
return nil, err
}
// 情况1有文案 → 按文案条目生成 Item每条文案+对应图片)
if len(contents) > 0 {
for i, val := range contents {
item := Item{
Content: url + val.Value, // 文案
Images: textImgMap[i], // 自动绑定该条目的图片(没有则为空切片)
}
allItems = append(allItems, item)
}
} else {
// 情况2没有文案只有图片 → 每张/每组图片生成独立 Item纯图片条目
if len(images) > 0 {
for _, img := range images {
allItems = append(allItems, Item{
Content: "",
Images: []string{img},
})
}
}
}
// 5. 生成多条独立HTML记录通用方案任意图文组合每条独立生成+独立上传)
var outputRecords []node.NodeFormField
// 遍历所有【独立图文条目】 → 每条生成独立HTML、独立上传OSS、独立输出记录
for idx, item := range allItems {
// item 结构包含Content(string) + Images([]string)
// 支持任意来源:文生图、图生文、单独文、单独图、文图合并
// 生成单条HTML
htmlContent := BuildHtml(item.Content, item.Images)
// 上传OSS每条独立上传
fileName := fmt.Sprintf("item_%d_%d.html", idx, time.Now().UnixMilli())
ossResult, err := Upload(ctx, &dto.UploadFileBytesReq{
FileBytes: []byte(htmlContent),
FileName: fileName,
})
if err != nil {
return nil, err
}
// 拼接成一条输出记录
// 每条记录包含HTML内容 + 访问URL + 文案 + 图片列表
outputRecords = append(outputRecords,
node.NodeFormField{
Field: fmt.Sprintf("item_html_%d", idx),
Value: htmlContent,
Label: fmt.Sprintf("条目%d HTML", idx+1),
Type: "textarea",
},
node.NodeFormField{
Field: fmt.Sprintf("item_html_url_%d", idx),
Value: ossResult.FileURL,
Label: fmt.Sprintf("条目%d 地址", idx+1),
Type: "text",
},
node.NodeFormField{
Field: fmt.Sprintf("item_txt_url_%d", idx),
Value: item.Content,
Label: fmt.Sprintf("条目%d 文案", idx+1),
Type: "text",
},
node.NodeFormField{
Field: fmt.Sprintf("item_image_url_%d", idx),
Value: strings.Join(item.Images, ","),
Label: fmt.Sprintf("条目%d 图片", idx+1),
Type: "text",
},
)
}
// 最终输出多条记录
nodeInput.Config.OutputResult = outputRecords
return nodeInput, nil
}
func SummaryLambda(ctx context.Context, input any) (any, error) {
execInput, ok := input.(*flowDto.NodeExecutionInput)
if !ok {
return nil, fmt.Errorf("汇总节点入参类型错误,实际是 %T", input)
}
// 聚合所有已执行节点的输出结果
var summaryResult []map[string]interface{}
for _, nodeID := range execInput.Global.ExecutedNodes {
nodeConfig := execInput.Global.ConfigMap[nodeID]
if nodeConfig != nil && len(nodeConfig.OutputResult) > 0 {
for _, field := range nodeConfig.OutputResult {
if strings.Contains(field.Field, "item_html_url") || strings.Contains(field.Field, "img_url") || strings.Contains(field.Field, "text_url") {
// 生成 毫秒时间戳 作为 KEY
timeKey := strconv.FormatInt(time.Now().UnixMilli(), 10)
item := make(map[string]interface{})
item[timeKey] = field.Value
summaryResult = append(summaryResult, item)
}
}
}
}
// 把汇总结果存入当前节点的输出
g.Log().Info(ctx, fmt.Sprintf("结果汇总完成,汇总数据:%+v", summaryResult))
err := gfdb.DB(ctx, public.DbNameBlackDeacon).Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
flowInfo, err := flowDao.FlowExecutionDao.Get(ctx, &flowDto.GetFlowExecutionReq{
SessionId: execInput.Global.SessionId,
})
if err != nil {
return err
}
executionReq := flowDto.UpdateFlowExecutionReq{
Id: execInput.Global.ExecutionId,
Status: flow.FlowExecutionStatusSuccess.Code(),
OutputParams: summaryResult,
}
_, err = flowDao.FlowExecutionDao.Update(ctx, &executionReq)
if flowInfo != nil {
var url string
url, err = utils.GetFileAddressPrefix(ctx)
if err != nil {
return err
}
createFileTempReq := make([]*fileDto.CreateFileTempReq, 0, len(flowInfo.OutputParams))
for _, fileUrl := range flowInfo.OutputParams {
m := gconv.Map(fileUrl)
for _, v := range m {
var createReq = new(fileDto.CreateFileTempReq)
createReq.BusinessId = flowInfo.SessionId
createReq.FileUrl = url + gconv.String(v)
createFileTempReq = append(createFileTempReq, createReq)
}
}
if len(createFileTempReq) > 0 {
_, err = fileDao.FileTempDao.BatchInsert(ctx, createFileTempReq)
if err != nil {
return err
}
}
}
return nil
})
return execInput, err
}
// VideoModelLambda 构建视频
func VideoModelLambda(ctx context.Context, input any) (any, error) {
fmt.Println("VideoModelLambda:", input)
return input, nil
}
// AudioModelLambda 构建音频
func AudioModelLambda(ctx context.Context, input any) (any, error) {
fmt.Println("AudioModelLambda:", input)
return input, nil
}
// CustomLambda 构建自定义
func CustomLambda(ctx context.Context, input any) (any, error) {
fmt.Println("CustomLambda:", input)
return input, nil
}