11 Commits
Author SHA1 Message Date
admin f2c41efedb gitea,gitea-runner写入docker-compose 2026-08-03 15:02:20 +08:00
admin a24b374af5 gitea,gitea-runner写入docker-compose
Deploy ai-agent to dev k3s / build-and-deploy (push) Successful in 3m53s
2026-08-03 14:45:04 +08:00
admin 6e97da9835 ci: checkout 改为本地 Gitea 手动 clone,摆脱 github.com 不稳定依赖
Deploy ai-agent to dev k3s / build-and-deploy (push) Successful in 3m38s
2026-08-03 14:31:48 +08:00
admin 8a656e27c5 gitea,gitea-runner写入docker-compose
Deploy ai-agent to dev k3s / build-and-deploy (push) Failing after 1m30s
2026-08-03 14:29:00 +08:00
admin 9b33b3f4fb fix: Dockerfile 换阿里云 apk 源,避免构建卡死
Deploy ai-agent to dev k3s / build-and-deploy (push) Successful in 4m1s
2026-08-03 14:18:48 +08:00
admin d4059fec84 ci: 恢复 checkout action (runner 已装 nodejs)
Deploy ai-agent to dev k3s / build-and-deploy (push) Failing after 8m54s
2026-08-03 14:09:02 +08:00
admin a6a6d34eea ci: 移除 checkout action (容器无 node,act_runner 自动 clone)
Deploy ai-agent to dev k3s / build-and-deploy (push) Failing after 0s
2026-08-03 14:01:54 +08:00
admin eebdb6ec38 ci: 重新触发 dev 自动发布验证
Deploy ai-agent to dev k3s / build-and-deploy (push) Failing after 24s
2026-08-03 13:59:48 +08:00
admin 86831c2fd0 ci: dev 分支自动发布到 dev k3s (本地仓库+本地集群)
Deploy ai-agent to dev k3s / build-and-deploy (push) Failing after 17m31s
2026-08-03 13:50:31 +08:00
admin 59d4ef557b ci/cd调整 2026-06-10 16:10:10 +08:00
admin b7b1ee51a1 ci/cd调整 2026-06-10 15:29:21 +08:00
38 changed files with 859 additions and 4068 deletions
-1
View File
@@ -1 +0,0 @@
.git
+1 -1
View File
@@ -8,7 +8,7 @@ name: Deploy ai-agent to dev k3s
on:
push:
branches: [ 2026-06-16 ]
branches: [ master ]
jobs:
build-and-deploy:
+3 -2
View File
@@ -1,8 +1,9 @@
# 阶段1: 构建
FROM golang:alpine AS builder
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories && \
apk add --no-cache git ca-certificates tzdata
# 换国内源,避免 apk 从官方源超时
RUN sed -i 's|dl-cdn.alpinelinux.org|mirrors.aliyun.com|g' /etc/apk/repositories \
&& apk add --no-cache git ca-certificates tzdata
ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
+11 -9
View File
@@ -5,7 +5,7 @@ server:
database:
default:
- type: "pgsql"
host: "192.168.0.83"
host: "116.204.74.41"
port: "15432"
user: "postgres"
pass: "Bjang09@686^*^"
@@ -26,7 +26,7 @@ database:
timeMaintainDisabled: false # (可选)是否完全关闭时间更新特性,为true时CreatedAt/UpdatedAt/DeletedAt都将失效
black_deacon:
- type: "pgsql"
host: "192.168.0.83"
host: "116.204.74.41"
port: "15432"
user: "postgres"
pass: "Bjang09@686^*^"
@@ -46,9 +46,10 @@ database:
deletedAt: "deleted_at" # (可选)软删除时间字段名称
timeMaintainDisabled: false # (可选)是否完全关闭时间更新特性,为true时CreatedAt/UpdatedAt/DeletedAt都将失效
redis:
default:
address: 192.168.0.83:6379
address: 116.204.74.41:6379
db: 0
idleTimeout: "60s" #连接最大空闲时间,使用时间字符串例如30s/1m/1d
maxConnLifetime: "90s" #连接最长存活时间,使用时间字符串例如30s/1m/1d
@@ -59,13 +60,14 @@ redis:
maxActive: 100
consul:
address: 192.168.0.83:8500
address: 116.204.74.41:8500
jaeger:
addr: 192.168.0.83:4318
addr: 116.204.74.41:4318
# 文件上传服务地址,cdn访问地址
filePrefix: "http://cdn.redpowerfuture.com"
# 文件上传服务地址,与oss模块minio中的endpoint一致
filePrefix: "http://116.204.74.41:9000"
# 文件上传服务地址,minio内网访问地址
minioPrefix: "http://192.168.0.83:9000"
model-asynch:
addr: "127.0.0.1:8001"
+15 -19
View File
@@ -1,17 +1,14 @@
module ai-agent
go 1.26.0
go 1.26.1
require (
gitea.redpowerfuture.com/red-future/common v0.0.29
github.com/cloudwego/eino v0.9.12
gitea.redpowerfuture.com/red-future/common v0.0.23
github.com/cloudwego/eino v0.9.5
github.com/cloudwego/eino-ext/components/model/qwen v0.1.9
github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.10.2
github.com/gogf/gf/contrib/nosql/redis/v2 v2.10.2
github.com/gogf/gf/v2 v2.10.2
github.com/google/uuid v1.6.0
github.com/tidwall/gjson v1.19.0
github.com/tidwall/sjson v1.2.5
go.opentelemetry.io/otel/trace v1.44.0
)
@@ -50,6 +47,7 @@ require (
github.com/golang/protobuf v1.5.4 // indirect
github.com/golang/snappy v1.0.0 // indirect
github.com/google/flatbuffers v1.12.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/goph/emperror v0.17.2 // indirect
github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 // indirect
github.com/grokify/html-strip-tags-go v0.1.0 // indirect
@@ -64,8 +62,8 @@ require (
github.com/hashicorp/golang-lru v1.0.2 // indirect
github.com/hashicorp/serf v0.10.1 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.18.2 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/klauspost/compress v1.18.0 // indirect
github.com/klauspost/cpuid/v2 v2.2.11 // indirect
github.com/lib/pq v1.10.9 // indirect
github.com/magiconair/properties v1.8.10 // indirect
github.com/mailru/easyjson v0.9.0 // indirect
@@ -81,22 +79,20 @@ require (
github.com/olekukonko/errors v1.1.0 // indirect
github.com/olekukonko/ll v0.0.9 // indirect
github.com/olekukonko/tablewriter v1.1.0 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/pkg/errors v0.9.2-0.20201214064552-5dd12d0cfe7f // indirect
github.com/pelletier/go-toml/v2 v2.0.9 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/r3labs/diff/v2 v2.15.1 // indirect
github.com/redis/go-redis/v9 v9.17.2 // indirect
github.com/redis/go-redis/v9 v9.12.1 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/slongfield/pyfmt v0.0.0-20220222012616-ea85ff4c361f // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
github.com/tiger1103/gfast-token v1.0.10 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/vcaesar/cedar v0.30.0 // indirect
github.com/vmihailenco/msgpack v4.0.4+incompatible // indirect
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
github.com/yargevad/filepathx v1.0.0 // indirect
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
go.mongodb.org/mongo-driver/v2 v2.4.0 // indirect
go.opencensus.io v0.23.0 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/otel v1.44.0 // indirect
@@ -105,11 +101,11 @@ require (
go.opentelemetry.io/otel/metric v1.44.0 // indirect
go.opentelemetry.io/otel/sdk v1.38.0 // indirect
go.opentelemetry.io/proto/otlp v1.7.1 // indirect
golang.org/x/arch v0.19.0 // indirect
golang.org/x/exp v0.0.0-20250718183923-645b1fa84792 // indirect
golang.org/x/net v0.48.0 // indirect
golang.org/x/sys v0.39.0 // indirect
golang.org/x/text v0.32.0 // indirect
golang.org/x/arch v0.11.0 // indirect
golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 // indirect
golang.org/x/net v0.47.0 // indirect
golang.org/x/sys v0.38.0 // indirect
golang.org/x/text v0.31.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250825161204-c5933d9347a5 // indirect
+35 -46
View File
@@ -1,6 +1,6 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
gitea.redpowerfuture.com/red-future/common v0.0.29 h1:5McaN5pSewvrLUHQzWMX6EaUvD+B5I5bMYoU+clHJk4=
gitea.redpowerfuture.com/red-future/common v0.0.29/go.mod h1:50U1Xi+Ie56z09S5LQbZvaken0Mxv3OeS9LgR7U/ZRY=
gitea.redpowerfuture.com/red-future/common v0.0.23 h1:xieoA00iKOCDm5SO9iXn+cSyMKBAlZwI0fuEVPWrHLg=
gitea.redpowerfuture.com/red-future/common v0.0.23/go.mod h1:50U1Xi+Ie56z09S5LQbZvaken0Mxv3OeS9LgR7U/ZRY=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg=
github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
@@ -56,8 +56,8 @@ github.com/clbanning/mxj/v2 v2.7.0/go.mod h1:hNiWqW14h+kc+MdF9C6/YoRfjEJoR3ou6tn
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
github.com/cloudwego/eino v0.9.12 h1:mHAMo5k7GdvnVD8Lc2sLyfpkxEm0S/y3PkEMhsSYt78=
github.com/cloudwego/eino v0.9.12/go.mod h1:OBD1mrkfkt/pJa4rkg1P0VnaMeOVl7l8IAdEqY//3IQ=
github.com/cloudwego/eino v0.9.5 h1:0Nftjx9gPek/2S/hzm38LVxSjk5/6mqRr3I9VKrKvm4=
github.com/cloudwego/eino v0.9.5/go.mod h1:OBD1mrkfkt/pJa4rkg1P0VnaMeOVl7l8IAdEqY//3IQ=
github.com/cloudwego/eino-ext/components/model/qwen v0.1.9 h1:xCz/mp43JeWqupjPR3zLRArmwC6P29/6lTwbwh1yzYM=
github.com/cloudwego/eino-ext/components/model/qwen v0.1.9/go.mod h1:slTGTuhzkzhNavf+1UtUg1FvUSA31iNAF+rq1mT4SnI=
github.com/cloudwego/eino-ext/libs/acl/openai v0.1.17 h1:EeVcR1TslRA2IdNW1h/2LaGbPlffwGhQm99jM3zWZiI=
@@ -231,10 +231,10 @@ github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7V
github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0/go.mod h1:1NbS8ALrpOvjt0rHPNLyCIeMtbizbir8U//inJ+zuB8=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/klauspost/compress v1.18.2 h1:iiPHWW0YrcFgpBYhsA6D1+fqHssJscY/Tm/y2Uqnapk=
github.com/klauspost/compress v1.18.2/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/klauspost/cpuid/v2 v2.2.11 h1:0OwqZRYI2rFrjS4kvkDnqJkKHdHaRnCm68/DY4OxRzU=
github.com/klauspost/cpuid/v2 v2.2.11/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
@@ -304,13 +304,12 @@ github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1Cpa
github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY=
github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pelletier/go-toml/v2 v2.0.9 h1:uH2qQXheeefCCkuBBSLi7jCiSmj3VRh2+Goq2N7Xxu0=
github.com/pelletier/go-toml/v2 v2.0.9/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.2-0.20201214064552-5dd12d0cfe7f h1:lJqhwddJVYAkyp72a4pwzMClI20xTwL7miDdm2W/KBM=
github.com/pkg/errors v0.9.2-0.20201214064552-5dd12d0cfe7f/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
@@ -330,8 +329,8 @@ github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsT
github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A=
github.com/r3labs/diff/v2 v2.15.1 h1:EOrVqPUzi+njlumoqJwiS/TgGgmZo83619FNDB9xQUg=
github.com/r3labs/diff/v2 v2.15.1/go.mod h1:I8noH9Fc2fjSaMxqF3G2lhDdC0b+JXCfyx85tWFM9kc=
github.com/redis/go-redis/v9 v9.17.2 h1:P2EGsA4qVIM3Pp+aPocCJ7DguDHhqrXNhVcEp4ViluI=
github.com/redis/go-redis/v9 v9.17.2/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370=
github.com/redis/go-redis/v9 v9.12.1 h1:k5iquqv27aBtnTm2tIkROUDp8JBXhXZIVu1InSgvovg=
github.com/redis/go-redis/v9 v9.12.1/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
@@ -370,16 +369,6 @@ github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXl
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/gjson v1.19.0 h1:xwxm7n691Uf3u5OFjzngavjGTh55KX5q/9w9xHW88JU=
github.com/tidwall/gjson v1.19.0/go.mod h1:V37/opeE/JbLUOfH0QTXiNez2l0RUjYUhpT4szFQAfc=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
github.com/tiger1103/gfast-token v1.0.10 h1:fNiBE/Dq5iTHvTGlCx3DmXa2o4hr0NtumFpffZ39k6s=
github.com/tiger1103/gfast-token v1.0.10/go.mod h1:a/21mxmj7zFeNvjhZSC0XpEAFHfb1aT2k6DXnufFU1s=
github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM=
@@ -399,8 +388,8 @@ github.com/yargevad/filepathx v1.0.0 h1:SYcT+N3tYGi+NvazubCNlvgIPbzAk7i7y2dwg3I5
github.com/yargevad/filepathx v1.0.0/go.mod h1:BprfX/gpYNJHJfc35GjRRpVcwWXS89gGulUIU5tK3tA=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
go.mongodb.org/mongo-driver/v2 v2.4.0 h1:Oq6BmUAAFTzMeh6AonuDlgZMuAuEiUxoAD1koK5MuFo=
go.mongodb.org/mongo-driver/v2 v2.4.0/go.mod h1:jHeEDJHJq7tm6ZF45Issun9dbogjfnPySb1vXA7EeAI=
go.opencensus.io v0.23.0 h1:gqCw0LfLxScz8irSi8exQc7fyQ0fKQU/qnC/X8+V/1M=
go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
@@ -425,25 +414,25 @@ go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
golang.org/x/arch v0.19.0 h1:LmbDQUodHThXE+htjrnmVD73M//D9GTH6wFZjyDkjyU=
golang.org/x/arch v0.19.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk=
golang.org/x/arch v0.11.0 h1:KXV8WWKCXm6tRpLirl2szsO5j/oOODwZf4hATmGVNs4=
golang.org/x/arch v0.11.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392/go.mod h1:/lpIB1dKB+9EgE3H3cr1v9wB50oz8l4C4h62xy7jSTY=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
golang.org/x/crypto v0.44.0 h1:A97SsFvM3AIwEEmTBiaxPPTYpDC47w720rdiiUvgoAU=
golang.org/x/crypto v0.44.0/go.mod h1:013i+Nw79BMiQiMsOPcVCB5ZIJbYkerPrGnOa00tvmc=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20250718183923-645b1fa84792 h1:R9PFI6EUdfVKgwKjZef7QIwGcBKu86OEFpJ9nUEP2l4=
golang.org/x/exp v0.0.0-20250718183923-645b1fa84792/go.mod h1:A+z0yzpGtvnG90cToK5n2tu8UJVP2XUATh+r+sfOOOc=
golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 h1:nDVHiLt8aIbd/VzvPWN6kSOPE7+F/fNFDSXLVYkE/Iw=
golang.org/x/exp v0.0.0-20250305212735-054e65f0b394/go.mod h1:sIifuuw/Yco/y6yb6+bDNfyeQ/MdPUy/hKEMYQV17cM=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk=
golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc=
golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA=
golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -460,8 +449,8 @@ golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwY
golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210410081132-afb366fc7cd1/go.mod h1:9tjilg8BloeKEkVJvy7fQ90B1CfIiPueXVOjqfkSzI8=
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -470,8 +459,8 @@ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=
golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@@ -498,17 +487,17 @@ golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q=
golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg=
golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU=
golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
@@ -518,8 +507,8 @@ golang.org/x/tools v0.0.0-20190907020128-2ca718005c18/go.mod h1:b+2E5dAYhXwXZwtn
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ=
golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ=
golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ=
golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
-7
View File
@@ -18,7 +18,6 @@ func main() {
ctx := context.Background()
defer jaeger.ShutDown(ctx)
// 注册路由
http.Httpserver.BindHandler("/httpNodeCallback", workflowController.FlowCallBack.HttpNodeCallback)
http.RouteRegister([]interface{}{
//digitalhuman相关接口
digitalhumanController.Audio, // 语音相关接口
@@ -31,15 +30,9 @@ func main() {
workflowController.FlowUser,
workflowController.FlowTemplate,
workflowNodeController.NodeLibrary,
workflowNodeController.NodePrompt,
workflowSkillController.SkillTemplate,
workflowSkillController.SkillUser,
})
//workflow.ExternalInterruptDemo()
//err := activePullService.ActivePullService.AllList(ctx)
//if err != nil {
// g.Log().Error(ctx, "ActivePullService err: %v", err)
//}
// 保持应用运行
select {}
}
+1 -144
View File
@@ -406,8 +406,6 @@ CREATE TABLE IF NOT EXISTS black_deacon_flow_execution (
-- 业务字段
flow_user_id BIGINT NOT NULL, -- 流程ID
flow_name VARCHAR(128) NOT NULL DEFAULT '',
node_group_id varchar(64) NOT NULL DEFAULT '',
total_tokens integer NOT NULL DEFAULT 0,
trigger_type VARCHAR(32) NOT NULL DEFAULT '', -- 触发类型
duration_ms BIGINT NOT NULL DEFAULT 0, -- 执行时长(毫秒)
status SMALLINT NOT NULL DEFAULT 1, -- 状态:1-运行中,2-成功,3-失败
@@ -437,8 +435,6 @@ COMMENT ON COLUMN black_deacon_flow_execution.updated_at IS '更新时间';
COMMENT ON COLUMN black_deacon_flow_execution.deleted_at IS '删除时间(软删)';
COMMENT ON COLUMN black_deacon_flow_execution.flow_user_id IS '流程ID';
COMMENT ON COLUMN black_deacon_flow_execution.flow_name IS '流程名称';
COMMENT ON COLUMN black_deacon_flow_execution.total_tokens IS '总token消耗';
COMMENT ON COLUMN black_deacon_flow_execution.node_group_id IS '节点组ID';
COMMENT ON COLUMN black_deacon_flow_execution.trigger_type IS '触发类型';
COMMENT ON COLUMN black_deacon_flow_execution.duration_ms IS '执行时长(毫秒)';
COMMENT ON COLUMN black_deacon_flow_execution.status IS '状态:1-运行中,2-成功,3-失败';
@@ -522,143 +518,4 @@ COMMENT ON COLUMN black_deacon_flow_template.category_name IS '流程分类名
COMMENT ON COLUMN black_deacon_flow_template.flow_content IS '流程内容';
COMMENT ON COLUMN black_deacon_flow_template.node_input_params IS '节点输入参数';
COMMENT ON COLUMN black_deacon_flow_template.status IS '流程状态:1启用/0停用';
--------------------pgsql创建black_deacon_flow_template表语句---------------------------
--------------------pgsql创建black_deacon_active_pull表语句---------------------------
-- 主动拉取记录表
CREATE TABLE IF NOT EXISTS black_deacon_active_pull (
-- 基础字段(完全对齐项目规范)
id BIGINT PRIMARY KEY,
tenant_id BIGINT NOT NULL DEFAULT 0,
creator VARCHAR(64) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updater VARCHAR(64) NOT NULL,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
deleted_at timestamp(6),
-- 业务字段
type VARCHAR(64) NOT NULL DEFAULT '',
request_parament JSONB DEFAULT '{}',
response_parament JSONB DEFAULT '{}',
extension JSONB DEFAULT '{}'
);
-- 索引
CREATE INDEX idx_active_pull_tenant_id ON black_deacon_active_pull(tenant_id);
CREATE INDEX idx_active_pull_type ON black_deacon_active_pull("type");
CREATE INDEX idx_active_pull_deleted_at ON black_deacon_active_pull(deleted_at);
-- 注释
COMMENT ON TABLE black_deacon_active_pull IS '主动拉取记录表';
COMMENT ON COLUMN black_deacon_active_pull.id IS '主键ID';
COMMENT ON COLUMN black_deacon_active_pull.tenant_id IS '租户ID';
COMMENT ON COLUMN black_deacon_active_pull.creator IS '创建人';
COMMENT ON COLUMN black_deacon_active_pull.created_at IS '创建时间';
COMMENT ON COLUMN black_deacon_active_pull.updater IS '更新人';
COMMENT ON COLUMN black_deacon_active_pull.updated_at IS '更新时间';
COMMENT ON COLUMN black_deacon_active_pull.deleted_at IS '删除时间(软删)';
COMMENT ON COLUMN black_deacon_active_pull.type IS '类型';
COMMENT ON COLUMN black_deacon_active_pull.request_parament IS '请求参数';
COMMENT ON COLUMN black_deacon_active_pull.response_parament IS '响应参数';
COMMENT ON COLUMN black_deacon_active_pull.extension IS '扩展信息';
--------------------pgsql创建black_deacon_active_pull表语句---------------------------
--------------------pgsql创建black_deacon_node_prompt表语句---------------------------
-- 节点提示词配置表
CREATE TABLE IF NOT EXISTS black_deacon_node_prompt (
-- 基础字段(完全对齐项目规范)
id BIGINT PRIMARY KEY,
tenant_id BIGINT NOT NULL DEFAULT 0,
creator VARCHAR(64) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updater VARCHAR(64) NOT NULL,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
deleted_at timestamp(6),
-- 业务字段
node_type VARCHAR(64) NOT NULL DEFAULT '', -- 节点类型
prompt TEXT NOT NULL DEFAULT '', -- 提示词内容
source_type SMALLINT NOT NULL DEFAULT 1 -- 来源:1=系统初始化,2=用户自定义
);
-- 索引
CREATE INDEX idx_node_prompt_tenant_id ON black_deacon_node_prompt(tenant_id);
CREATE INDEX idx_node_prompt_node_type ON black_deacon_node_prompt(node_type);
CREATE INDEX idx_node_prompt_source_type ON black_deacon_node_prompt(source_type);
CREATE INDEX idx_node_prompt_deleted_at ON black_deacon_node_prompt(deleted_at);
-- 注释
COMMENT ON TABLE black_deacon_node_prompt IS '节点提示词配置表';
COMMENT ON COLUMN black_deacon_node_prompt.id IS '主键ID';
COMMENT ON COLUMN black_deacon_node_prompt.tenant_id IS '租户ID';
COMMENT ON COLUMN black_deacon_node_prompt.creator IS '创建人';
COMMENT ON COLUMN black_deacon_node_prompt.created_at IS '创建时间';
COMMENT ON COLUMN black_deacon_node_prompt.updater IS '更新人';
COMMENT ON COLUMN black_deacon_node_prompt.updated_at IS '更新时间';
COMMENT ON COLUMN black_deacon_node_prompt.deleted_at IS '删除时间(软删)';
COMMENT ON COLUMN black_deacon_node_prompt.node_type IS '节点类型';
COMMENT ON COLUMN black_deacon_node_prompt.prompt IS '提示词内容';
COMMENT ON COLUMN black_deacon_node_prompt.source_type IS '数据来源:1=系统初始化,2=用户自定义';
--------------------pgsql创建black_deacon_node_prompt表语句---------------------------
--------------------pgsql创建black_deacon_node_execution表语句---------------------------
-- 节点执行记录表
-- 记录每个节点的入参、出参、token消耗、执行状态等详细信息
CREATE TABLE IF NOT EXISTS black_deacon_node_execution (
-- 基础字段(完全对齐项目规范)
id BIGINT PRIMARY KEY, -- 主键ID(非自增)
tenant_id BIGINT NOT NULL DEFAULT 0, -- 租户ID int8
creator VARCHAR(64) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updater VARCHAR(64) NOT NULL,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
deleted_at timestamp(6),
-- 业务字段
flow_execution_id BIGINT NOT NULL, -- 流程执行ID
node_id VARCHAR(64) NOT NULL DEFAULT '', -- 节点ID
node_name VARCHAR(128) NOT NULL DEFAULT '', -- 节点名称
node_group_id VARCHAR(64) NOT NULL DEFAULT '', -- 节点分组ID
input_params JSONB DEFAULT '{}', -- 节点输入参数
input_params_path VARCHAR(256) DEFAULT '', -- 节点输入参数路径
output_params JSONB DEFAULT '{}', -- 节点输出参数
output_params_path VARCHAR(256) DEFAULT '',
prompt_tokens INTEGER NOT NULL DEFAULT 0, -- 提示词token消耗
completion_tokens INTEGER NOT NULL DEFAULT 0, -- 补全token消耗
total_tokens INTEGER NOT NULL DEFAULT 0, -- 总token消耗
status SMALLINT NOT NULL DEFAULT 1, -- 执行状态:1-运行中,2-成功,3-失败,4-暂停,5-等待执行
duration_ms BIGINT NOT NULL DEFAULT 0, -- 执行时长(毫秒)
error_message TEXT DEFAULT '' -- 错误信息
);
-- 索引(高频查询)
CREATE INDEX IF NOT EXISTS idx_bne_tenant_id ON black_deacon_node_execution(tenant_id);
CREATE INDEX IF NOT EXISTS idx_bne_flow_execution_id ON black_deacon_node_execution(flow_execution_id);
CREATE INDEX IF NOT EXISTS idx_bne_node_id ON black_deacon_node_execution(node_id);
CREATE INDEX IF NOT EXISTS idx_bne_status ON black_deacon_node_execution(status);
CREATE INDEX IF NOT EXISTS idx_bne_deleted_at ON black_deacon_node_execution(deleted_at);
-- 表和字段注释
COMMENT ON TABLE black_deacon_node_execution IS '节点执行记录表';
COMMENT ON COLUMN black_deacon_node_execution.id IS '主键ID(非自增)';
COMMENT ON COLUMN black_deacon_node_execution.tenant_id IS '租户ID';
COMMENT ON COLUMN black_deacon_node_execution.creator IS '创建人';
COMMENT ON COLUMN black_deacon_node_execution.created_at IS '创建时间';
COMMENT ON COLUMN black_deacon_node_execution.updater IS '更新人';
COMMENT ON COLUMN black_deacon_node_execution.updated_at IS '更新时间';
COMMENT ON COLUMN black_deacon_node_execution.deleted_at IS '删除时间(软删)';
COMMENT ON COLUMN black_deacon_node_execution.flow_execution_id IS '流程执行ID';
COMMENT ON COLUMN black_deacon_node_execution.node_id IS '节点ID';
COMMENT ON COLUMN black_deacon_node_execution.node_name IS '节点名称';
COMMENT ON COLUMN black_deacon_node_execution.node_group_id IS '节点分组ID';
COMMENT ON COLUMN black_deacon_node_execution.input_params IS '节点输入参数';
COMMENT ON COLUMN black_deacon_node_execution.input_params_path IS '节点输入参数路径';
COMMENT ON COLUMN black_deacon_node_execution.output_params IS '节点输出参数';
COMMENT ON COLUMN black_deacon_node_execution.output_params_path IS '节点输出参数路径';
COMMENT ON COLUMN black_deacon_node_execution.prompt_tokens IS '提示词token消耗';
COMMENT ON COLUMN black_deacon_node_execution.completion_tokens IS '补全token消耗';
COMMENT ON COLUMN black_deacon_node_execution.total_tokens IS '总token消耗';
COMMENT ON COLUMN black_deacon_node_execution.status IS '执行状态:1-运行中,2-成功,3-失败,4-暂停,5-等待执行';
COMMENT ON COLUMN black_deacon_node_execution.duration_ms IS '执行时长(毫秒)';
COMMENT ON COLUMN black_deacon_node_execution.error_message IS '错误信息';
--------------------pgsql创建black_deacon_node_execution表语句---------------------------
--------------------pgsql创建black_deacon_flow_template表语句---------------------------
+50 -60
View File
@@ -10,28 +10,26 @@ const (
// 节点名称
const (
NodeNameTextModel = "生成文案"
NodeNameImageModel = "生成图片"
NodeNameVideoModel = "生成视频"
NodeNameAudioModel = "生成音频"
NodeNameBatchModel = "批量处理一起返回"
NodeNameSenseOptimizeModel = "语义优化"
NodeNameStoryOptimizeModel = "分镜优化"
NodeNameScriptOptimizeModel = "剧本优化"
NodeNameDataConversionModel = "参数转换"
NodeNameModel = "模型"
NodeNameMerge = "结果合并"
NodeNameDataMerge = "结果汇集"
NodeNameJudge = "条件判断"
NodeNameForm = "表单"
NodeNameHttp = "HTTP(S)接口"
NodeNameCustomNode = "自定义节点"
NodeNameTextModel = "生成文案"
NodeNameImageModel = "生成图片"
NodeNameVideoModel = "生成视频"
NodeNameSenseOptimize = "语义优化"
NodeNameStoryOptimize = "分镜优化"
NodeNameScriptOptimize = "剧本优化"
NodeNameAudioModel = "音频"
NodeNameModel = "模型"
NodeNameMerge = "结果合并"
NodeNameJudge = "条件判断"
NodeNameForm = "表单"
NodeNameHttp = "HTTP(S)接口"
NodeNameCustomNode = "自定义节点"
)
// 表单字段 Label
const (
FormLabelApiKey = "API Key"
FormLabelModel = "模型名称"
FormLabelApiKey = "API Key"
FormLabelModel = "模型名称"
FormLabelCondition = "判断条件"
)
@@ -48,47 +46,40 @@ type NodeType string
const (
// 组件
NodeTypeTextModel NodeType = "text_model"
NodeTypeImageModel NodeType = "image_model"
NodeTypeVideoModel NodeType = "video_model"
NodeTypeAudioModel NodeType = "audio_model"
NodeTypeBatchModel NodeType = "batch_model"
NodeTypeTextModel NodeType = "text_model"
NodeTypeImageModel NodeType = "image_model"
NodeTypeVideoModel NodeType = "video_model"
NodeTypeSenseOptimize NodeType = "sense_optimize"
NodeTypeStoryOptimize NodeType = "story_optimize"
NodeTypeScriptOptimize NodeType = "script_optimize"
NodeTypeAudioModel NodeType = "audio_model"
NodeTypeSenseOptimizeModel NodeType = "sense_optimize_model"
NodeTypeStoryOptimizeModel NodeType = "story_optimize_model"
NodeTypeScriptOptimizeModel NodeType = "script_optimize_model"
// 基础
NodeTypeDataConversionModel NodeType = "data_conversion_model"
NodeTypeModel NodeType = "model"
NodeTypeMerge NodeType = "merge"
NodeTypeDataMerge NodeType = "data_merge"
NodeTypeJudge NodeType = "judge"
NodeTypeForm NodeType = "form"
NodeTypeIntent NodeType = "intent"
NodeTypeHttp NodeType = "http"
NodeTypeModel NodeType = "model"
NodeTypeMerge NodeType = "merge"
NodeTypeJudge NodeType = "judge"
NodeTypeForm NodeType = "form"
NodeTypeIntent NodeType = "intent"
NodeTypeHttp NodeType = "http"
// 自定义
NodeTypeCustomNode NodeType = "custom_node"
)
const (
ModelTypeText = 100
ModelTypeImage = 200
ModelTypeAudio = 300
ModelTypeModality = 500
ModelTypeVideo = 600
ModelTypeText = 1
ModelTypeImage = 2
)
// ======================== 结构定义 ========================
type NodeFormField struct {
Value any `json:"value"`
Field string `json:"field"`
Label string `json:"label"` // 从常量来
Type string `json:"type"`
Required bool `json:"required"`
Default any `json:"default,omitempty"`
Options []SelectOption `json:"options"`
Expand any `json:"expand"`
FieldConstraint any `json:"fieldConstraint"`
Value string `json:"value"`
Field string `json:"field"`
Label string `json:"label"` // 从常量来
Type string `json:"type"`
Required bool `json:"required"`
Default any `json:"default,omitempty"`
Options []SelectOption `json:"options"`
Expand any `json:"expand"`
}
type SelectOption struct {
@@ -97,21 +88,20 @@ type SelectOption struct {
}
type ModelItem struct {
ModelName string `json:"modelName"`
ModelForm []NodeFormField `json:"modelForm"`
ModelApiKey string `json:"modelApiKey"`
ModelName string `json:"modelName"`
ModelForm map[string]any `json:"modelForm"`
ModelResponse map[string]any `json:"modelResponse"`
}
type NodeItem struct {
NodeId string `json:"nodeId"`
NodeCode NodeType `json:"nodeCode"`
ModelType int `json:"modelType"`
NodeName string `json:"nodeName"` // 从常量来
PatchLayout bool `json:"patchLayout"`
SkillOption bool `json:"skillOption"`
PromptOption bool `json:"promptOption"`
IsSaveFile bool `json:"isSaveFile"`
FormConfig []NodeFormField `json:"formConfig"`
ModelConfig []ModelItem `json:"modelConfig"`
NodeId string `json:"nodeId"`
NodeCode NodeType `json:"nodeCode"`
ModelType int `json:"modelType"`
NodeName string `json:"nodeName"` // 从常量来
SkillOption bool `json:"skillOption"`
FormConfig []NodeFormField `json:"formConfig"`
ModelConfig []ModelItem `json:"modelConfig"`
}
type NodeGroupItem struct {
-26
View File
@@ -1,26 +0,0 @@
package node
import "github.com/gogf/gf/v2/util/gconv"
var (
SourceTypeSystem = newSourceType(gconv.PtrInt8(1), "系统初始化")
SourceTypeUser = newSourceType(gconv.PtrInt8(2), "用户自定义")
)
type SourceType *int8
type sourceType struct {
code SourceType
desc string
}
func (s sourceType) Code() SourceType {
return s.code
}
func (s sourceType) Desc() string {
return s.desc
}
func newSourceType(code SourceType, desc string) sourceType {
return sourceType{code: code, desc: desc}
}
+7 -11
View File
@@ -7,15 +7,11 @@ const (
// 数据库表名
const (
TableNameCreationInfo = "creation_info"
TableNameFlowExecution = "flow_execution"
TableNameFlowTemplate = "flow_template"
TableNameFlowUser = "flow_user"
TableNameSkillTemplate = "skill_template"
TableNameSkillUser = "skill_user"
TableNameFileTemp = "file_temp"
TableNameActivePull = "active_pull"
TableNameWorkflowInterrupt = "workflow_interrupt"
TableNameNodePrompt = "node_prompt"
TableNameNodeExecution = "node_execution"
TableNameCreationInfo = "creation_info"
TableNameFlowExecution = "flow_execution"
TableNameFlowTemplate = "flow_template"
TableNameFlowUser = "flow_user"
TableNameSkillTemplate = "skill_template"
TableNameSkillUser = "skill_user"
TableNameFileTemp = "file_temp"
)
@@ -1,23 +0,0 @@
package flow
import (
flowService "ai-agent/workflow/service/flow"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
type flowCallBack struct{}
var FlowCallBack = new(flowCallBack)
func (c *flowCallBack) HttpNodeCallback(r *ghttp.Request) {
ctx := r.Context()
err := flowService.FlowExecutionService.HttpNodeCallback(ctx)
if err != nil {
r.Response.WriteJson(g.Map{"code": 500, "message": err.Error()})
return
}
r.Response.WriteJson(g.Map{"code": 0, "message": "success"})
return
}
@@ -16,21 +16,11 @@ func (c *flowExecution) Execute(ctx context.Context, req *flowDto.ExecuteReq) (r
return flowService.FlowExecutionService.Execute(ctx, req)
}
func (c *flowExecution) ComposeCallBack(ctx context.Context, req *flowDto.ComposeCallbackReq) (res *beans.ResponseEmpty, err error) {
err = flowService.FlowExecutionService.ComposeCallback(ctx, req)
return
}
func (c *flowExecution) ModelCallback(ctx context.Context, req *flowDto.ModelCallbackReq) (res *beans.ResponseEmpty, err error) {
err = flowService.FlowExecutionService.ModelCallback(ctx, req)
return
}
func (c *flowExecution) VideoCallback(ctx context.Context, req *flowDto.VideoCallbackReq) (res *beans.ResponseEmpty, err error) {
err = flowService.FlowExecutionService.VideoCallback(ctx, req)
return
}
func (c *flowExecution) Get(ctx context.Context, req *flowDto.GetFlowExecutionReq) (res *flowDto.VOFlowExecution, err error) {
return flowService.FlowExecutionService.Get(ctx, req)
}
@@ -38,17 +28,3 @@ func (c *flowExecution) Get(ctx context.Context, req *flowDto.GetFlowExecutionRe
func (c *flowExecution) List(ctx context.Context, req *flowDto.ListFlowExecutionReq) (res *flowDto.ListFlowExecutionTreeRes, err error) {
return flowService.FlowExecutionService.List(ctx, req)
}
func (c *flowExecution) GetSessionList(ctx context.Context, req *flowDto.GetSessionListReq) (res *flowDto.ListFlowExecutionRes, err error) {
return flowService.FlowExecutionService.GetSessionList(ctx, req)
}
func (c *flowExecution) DeleteResult(ctx context.Context, req *flowDto.DeleteResultReq) (res *beans.ResponseEmpty, err error) {
err = flowService.FlowExecutionService.DeleteResult(ctx, req)
return
}
func (c *flowExecution) DeleteSession(ctx context.Context, req *flowDto.DeleteSessionReq) (res *beans.ResponseEmpty, err error) {
err = flowService.FlowExecutionService.DeleteSession(ctx, req)
return
}
@@ -1,45 +0,0 @@
package node
import (
nodeDto "ai-agent/workflow/model/dto/node"
nodeService "ai-agent/workflow/service/node"
"context"
"gitea.redpowerfuture.com/red-future/common/beans"
)
type nodePrompt struct{}
var NodePrompt = new(nodePrompt)
// Create 创建节点提示词
func (c *nodePrompt) Create(ctx context.Context, req *nodeDto.CreateNodePromptReq) (res *nodeDto.CreateNodePromptRes, err error) {
return nodeService.NodePromptService.Create(ctx, req)
}
// Update 更新节点提示词
func (c *nodePrompt) Update(ctx context.Context, req *nodeDto.UpdateNodePromptReq) (res *beans.ResponseEmpty, err error) {
err = nodeService.NodePromptService.Update(ctx, req)
return
}
// Delete 删除节点提示词
func (c *nodePrompt) Delete(ctx context.Context, req *nodeDto.DeleteNodePromptReq) (res *beans.ResponseEmpty, err error) {
err = nodeService.NodePromptService.Delete(ctx, req)
return
}
// Get 根据ID查询节点提示词详情
func (c *nodePrompt) Get(ctx context.Context, req *nodeDto.GetNodePromptReq) (res *nodeDto.NodePromptResp, err error) {
return nodeService.NodePromptService.GetById(ctx, req)
}
// ListMy 查询当前用户自己创建的节点提示词列表
func (c *nodePrompt) ListMy(ctx context.Context, req *nodeDto.ListMyNodePromptReq) (res *nodeDto.ListNodePromptResp, err error) {
return nodeService.NodePromptService.ListMy(ctx, req)
}
// List 查询节点提示词列表,包含系统和当前创建人自定义
func (c *nodePrompt) List(ctx context.Context, req *nodeDto.ListNodePromptReq) (res *nodeDto.ListNodePromptResp, err error) {
return nodeService.NodePromptService.ListWithSystem(ctx, req)
}
+1 -11
View File
@@ -7,7 +7,6 @@ import (
"context"
"gitea.redpowerfuture.com/red-future/common/db/gfdb"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/util/gconv"
)
@@ -50,17 +49,8 @@ func (d *flowExecutionDao) Get(ctx context.Context, req *flowDto.GetFlowExecutio
}
func (d *flowExecutionDao) List(ctx context.Context, req *flowDto.ListFlowExecutionReq, fields ...string) (res []*entity.FlowExecution, total int, err error) {
model := gfdb.DB(ctx, public.DbNameBlackDeacon).Model(ctx, public.TableNameFlowExecution).Fields(fields)
model := gfdb.DB(ctx, public.DbNameBlackDeacon).Model(ctx, public.TableNameFlowExecution).Fields(fields).OmitEmpty()
model.Where(entity.FlowExecutionCol.Creator, req.Creator)
if !g.IsEmpty(req.ResultDel) {
model.Where(entity.FlowExecutionCol.ResultDel, false)
}
if !g.IsEmpty(req.SessionDel) {
model.Where(entity.FlowExecutionCol.SessionDel, false)
}
if req.IsResult {
model.WhereNot(entity.FlowExecutionCol.OutputParams, "[]")
}
model.OrderDesc(entity.FlowExecutionCol.CreatedAt)
if req.Page != nil {
model.Page(int(req.Page.PageNum), int(req.Page.PageSize))
-100
View File
@@ -1,100 +0,0 @@
package node
import (
"ai-agent/workflow/consts/public"
nodeDto "ai-agent/workflow/model/dto/node"
"ai-agent/workflow/model/entity"
"context"
"gitea.redpowerfuture.com/red-future/common/db/gfdb"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/util/gconv"
)
var NodeExecutionDao = &nodeExecutionDao{}
type nodeExecutionDao struct{}
// Insert 插入节点执行记录
func (d *nodeExecutionDao) Insert(ctx context.Context, req *nodeDto.CreateNodeExecutionReq) (id int64, err error) {
nodeExecution := new(entity.NodeExecution)
err = gconv.Struct(req, &nodeExecution)
if err != nil {
return 0, err
}
r, err := gfdb.DB(ctx, public.DbNameBlackDeacon).Model(ctx, public.TableNameNodeExecution).Insert(&nodeExecution)
if err != nil {
return 0, err
}
return r.LastInsertId()
}
// Update 更新节点执行记录
func (d *nodeExecutionDao) Update(ctx context.Context, req *nodeDto.UpdateNodeExecutionReq) (rows int64, err error) {
model := gfdb.DB(ctx, public.DbNameBlackDeacon).Model(ctx, public.TableNameNodeExecution).OmitEmpty()
if !g.IsEmpty(req.CompletionTokens) {
model.Data(entity.NodeExecutionCol.CompletionTokens, &gdb.Counter{
Field: entity.NodeExecutionCol.CompletionTokens,
Value: gconv.Float64(req.CompletionTokens),
})
}
if !g.IsEmpty(req.PromptTokens) {
model.Data(entity.NodeExecutionCol.PromptTokens, &gdb.Counter{
Field: entity.NodeExecutionCol.PromptTokens,
Value: gconv.Float64(req.PromptTokens),
})
}
if !g.IsEmpty(req.TotalTokens) {
model.Data(entity.NodeExecutionCol.TotalTokens, &gdb.Counter{
Field: entity.NodeExecutionCol.TotalTokens,
Value: gconv.Float64(req.TotalTokens),
})
}
r, err := model.Data(&req).Where(entity.NodeExecutionCol.Id, req.Id).Update()
if err != nil {
return 0, err
}
return r.RowsAffected()
}
// Delete 删除节点执行记录
func (d *nodeExecutionDao) Delete(ctx context.Context, req *nodeDto.DeleteNodeExecutionReq) (rows int64, err error) {
r, err := gfdb.DB(ctx, public.DbNameBlackDeacon).Model(ctx, public.TableNameNodeExecution).Where(entity.NodeExecutionCol.Id, req.Id).Delete()
if err != nil {
return 0, err
}
return r.RowsAffected()
}
// Get 根据ID查询节点执行记录
func (d *nodeExecutionDao) Get(ctx context.Context, req *nodeDto.GetNodeExecutionReq, fields ...string) (res *entity.NodeExecution, err error) {
r, err := gfdb.DB(ctx, public.DbNameBlackDeacon).Model(ctx, public.TableNameNodeExecution).NoTenantId(ctx).OmitEmpty().
Where(entity.NodeExecutionCol.Id, req.Id).
Fields(fields).One()
if err != nil {
return nil, err
}
if r.IsEmpty() {
return nil, nil
}
err = r.Struct(&res)
return res, err
}
// ListByFlowExecutionId 查询指定流程执行下的所有节点执行记录
func (d *nodeExecutionDao) ListByFlowExecutionId(ctx context.Context, req *nodeDto.ListNodeExecutionByFlowReq, fields ...string) (res []*entity.NodeExecution, total int, err error) {
model := gfdb.DB(ctx, public.DbNameBlackDeacon).Model(ctx, public.TableNameNodeExecution).NoTenantId(ctx).Fields(fields).OmitEmpty()
model.Where(entity.NodeExecutionCol.FlowExecutionId, req.FlowExecutionId)
model.Where(entity.NodeExecutionCol.NodeGroupId, req.NodeGroupId)
model.OrderAsc(entity.NodeExecutionCol.CreatedAt)
if req.Page != nil {
model.Page(int(req.Page.PageNum), int(req.Page.PageSize))
}
r, total, err := model.AllAndCount(false)
if err != nil {
return nil, 0, err
}
err = r.Structs(&res)
return res, total, err
}
-95
View File
@@ -1,95 +0,0 @@
package node
import (
"ai-agent/workflow/consts/public"
nodeDto "ai-agent/workflow/model/dto/node"
"ai-agent/workflow/model/entity"
"context"
"gitea.redpowerfuture.com/red-future/common/db/gfdb"
"github.com/gogf/gf/v2/util/gconv"
)
var NodePromptDao = &nodePromptDao{}
type nodePromptDao struct{}
// Insert 插入节点提示词
func (d *nodePromptDao) Insert(ctx context.Context, req *nodeDto.CreateNodePromptReq) (id int64, err error) {
nodePrompt := new(entity.NodePrompt)
err = gconv.Struct(req, &nodePrompt)
r, err := gfdb.DB(ctx, public.DbNameBlackDeacon).Model(ctx, public.TableNameNodePrompt).Insert(&nodePrompt)
if err != nil {
return 0, err
}
return r.LastInsertId()
}
// Update 更新节点提示词
func (d *nodePromptDao) Update(ctx context.Context, req *nodeDto.UpdateNodePromptReq) (rows int64, err error) {
r, err := gfdb.DB(ctx, public.DbNameBlackDeacon).Model(ctx, public.TableNameNodePrompt).OmitEmpty().Data(&req).Where(entity.NodePromptCol.Id, req.Id).Update()
if err != nil {
return 0, err
}
return r.RowsAffected()
}
// Delete 删除节点提示词
func (d *nodePromptDao) Delete(ctx context.Context, req *nodeDto.DeleteNodePromptReq) (rows int64, err error) {
r, err := gfdb.DB(ctx, public.DbNameBlackDeacon).Model(ctx, public.TableNameNodePrompt).Where(entity.NodePromptCol.Id, req.Id).Delete()
if err != nil {
return 0, err
}
return r.RowsAffected()
}
// Get 根据ID查询节点提示词
func (d *nodePromptDao) Get(ctx context.Context, req *nodeDto.GetNodePromptReq, fields ...string) (res *entity.NodePrompt, err error) {
r, err := gfdb.DB(ctx, public.DbNameBlackDeacon).Model(ctx, public.TableNameNodePrompt).NoTenantId(ctx).OmitEmpty().
Where(entity.NodePromptCol.Id, req.Id).
Where(entity.NodePromptCol.Prompt, req.Prompt).
Where(entity.NodePromptCol.Creator, req.Creator).
Fields(fields).One()
if err != nil {
return nil, err
}
if r.IsEmpty() {
return nil, nil
}
err = r.Struct(&res)
return res, err
}
// ListByOnlyCreator 查询仅当前创建人自己创建的提示词
func (d *nodePromptDao) ListByOnlyCreator(ctx context.Context, req *nodeDto.ListMyNodePromptReq, fields ...string) (res []*entity.NodePrompt, total int, err error) {
model := gfdb.DB(ctx, public.DbNameBlackDeacon).Model(ctx, public.TableNameNodePrompt).NoTenantId(ctx).Fields(fields).OmitEmpty()
model.Where(entity.NodePromptCol.Creator, req.Creator)
model.Where(entity.NodePromptCol.NodeType, req.NodeType)
model.OrderDesc(entity.NodePromptCol.CreatedAt)
if req.Page != nil {
model.Page(int(req.Page.PageNum), int(req.Page.PageSize))
}
r, total, err := model.AllAndCount(false)
if err != nil {
return nil, 0, err
}
err = r.Structs(&res)
return res, total, err
}
// ListByCreator 查询当前创建人的所有提示词(包含系统和用户)
func (d *nodePromptDao) ListByCreator(ctx context.Context, req *nodeDto.ListNodePromptReq, fields ...string) (res []*entity.NodePrompt, total int, err error) {
// 完整 SQL
sql := ` SELECT * FROM black_deacon_node_prompt WHERE (creator=? OR source_type=1) AND node_type=? AND "deleted_at" IS NULL ORDER BY created_at DESC `
queryParams := []interface{}{req.Creator, req.NodeType}
if req.Page != nil {
sql += " LIMIT ?,?"
queryParams = append(queryParams, req.Page.PageNum, req.Page.PageSize)
}
r, err := gfdb.DB(ctx, public.DbNameBlackDeacon).GetAll(ctx, sql, queryParams...)
if err != nil {
return nil, 0, err
}
err = r.Structs(&res)
return res, total, err
}
-102
View File
@@ -1,102 +0,0 @@
package pull
import (
"ai-agent/workflow/consts/public"
pullDto "ai-agent/workflow/model/dto/pull"
"ai-agent/workflow/model/entity"
"context"
"fmt"
"strings"
"gitea.redpowerfuture.com/red-future/common/db/gfdb"
"github.com/gogf/gf/v2/util/gconv"
)
var ActivePullDao = &activePullDao{}
type activePullDao struct{}
// Insert 创建执行记录
func (d *activePullDao) Insert(ctx context.Context, req *pullDto.CreateActivePullReq) (id int64, err error) {
var activePull = new(entity.ActivePull)
err = gconv.Struct(req, &activePull)
if err != nil {
return
}
r, err := gfdb.DB(ctx, public.DbNameBlackDeacon).Model(ctx, public.TableNameActivePull).Insert(activePull)
if err != nil {
return
}
return r.LastInsertId()
}
func (d *activePullDao) Update(ctx context.Context, req *pullDto.UpdateActivePullReq) (rows int64, err error) {
r, err := gfdb.DB(ctx, public.DbNameBlackDeacon).Model(ctx, public.TableNameActivePull).OmitEmpty().Data(&req).Where(entity.ActivePullCol.Id, req.Id).Update()
if err != nil {
return
}
return r.RowsAffected()
}
func (d *activePullDao) Delete(ctx context.Context, req *pullDto.DeleteActivePullReq) (rows int64, err error) {
r, err := gfdb.DB(ctx, public.DbNameBlackDeacon).Model(ctx, public.TableNameActivePull).Where(entity.ActivePullCol.Id, req.Id).Delete()
if err != nil {
return
}
return r.RowsAffected()
}
func (d *activePullDao) List(ctx context.Context, req *pullDto.ListActivePullReq, fields ...string) (res []*entity.ActivePull, total int, err error) {
model := gfdb.DB(ctx, public.DbNameBlackDeacon).Model(ctx, public.TableNameActivePull).Fields(fields).OmitEmpty()
model.OrderDesc(entity.ActivePullCol.CreatedAt)
if req.Page != nil {
model.Page(int(req.Page.PageNum), int(req.Page.PageSize))
}
r, total, err := model.AllAndCount(false)
if err != nil {
return
}
err = r.Structs(&res)
return
}
func (d *activePullDao) ListNative(ctx context.Context, req *pullDto.ListActivePullReq, fields ...string) (res []*entity.ActivePull, total int, err error) {
db := gfdb.DB(ctx, public.DbNameBlackDeacon)
// Select fields
selectFields := "*"
if len(fields) > 0 {
selectFields = strings.Join(fields, ",")
}
// Build count query first for total
countSql := fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE deleted_at is null", "black_deacon_"+public.TableNameActivePull)
countResult, err := db.GetAll(ctx, countSql)
if err != nil {
return nil, 0, err
}
if len(countResult) > 0 {
total = countResult[0]["COUNT(*)"].Int()
}
// Build data query with native SQL
sql := fmt.Sprintf("SELECT %s FROM %s WHERE deleted_at is null ORDER BY created_at DESC", selectFields, "black_deacon_"+public.TableNameActivePull)
if req.Page != nil && req.Page.PageNum > 0 && req.Page.PageSize > 0 {
offset := (req.Page.PageNum - 1) * req.Page.PageSize
sql += fmt.Sprintf(" LIMIT %d OFFSET %d", req.Page.PageSize, offset)
}
// Execute query with GetAll
result, err := db.GetAll(ctx, sql)
if err != nil {
return nil, total, err
}
// Scan to entity slice
var models []*entity.ActivePull
if err = result.Structs(&models); err != nil {
return nil, total, err
}
return models, total, nil
}
+93 -173
View File
@@ -2,7 +2,6 @@ package flow
import (
"ai-agent/workflow/consts/flow"
"ai-agent/workflow/consts/node"
"ai-agent/workflow/model/entity"
"gitea.redpowerfuture.com/red-future/common/beans"
@@ -12,98 +11,40 @@ import (
// NodeExecutionInput 节点执行入参(包含配置+表单架构)
type NodeExecutionInput struct {
Config *entity.FlowNode `json:"config"` // 节点配置
Global *FlowExecutionInput `json:"global"`
NodeExecutionId int64 `json:"nodeExecutionId"`
}
// ExecutedNode 已执行节点记录,包含节点ID和执行状态
type ExecutedNode struct {
NodeId string `json:"nodeId"`
Status node.NodeExecutionStatus `json:"status"` // 执行状态:成功/失败
Config *entity.FlowNode // 节点配置
Global *FlowExecutionInput `json:"-"`
}
// FlowExecutionInput 工作流执行入参(全程不变)
type FlowExecutionInput struct {
NodeGroupId string `json:"nodeGroupId"`
IsDialogue bool `json:"isDialogue"`
ExecutionId int64 `json:"executionId"`
ConfigMap map[string]*entity.FlowNode `json:"configMap"`
SessionId string `json:"sessionId" dc:"会话ID"`
Templates []map[string]any `json:"templates"`
Desc string `json:"desc"`
SkillName string `json:"skillName"`
FileUrl []string `json:"fileUrl"`
ExecutedNodes []ExecutedNode `json:"executedNodes"` // 已执行节点列表,包含执行状态
}
type GetIsChatModelRes struct {
Model struct {
ModelName string `json:"modelName"`
ResponseBody map[string]any `json:"responseBody"`
}
}
type GetModelInfoReq struct {
ModelName string `json:"modelName"`
}
type GetModelInfoRes struct {
Model struct {
FirstFrame string `json:"firstFrame"`
LastFrame string `json:"lastFrame"`
ResponseTokenField string `json:"responseTokenField"`
ResponseMapping map[string]any `json:"responseMapping"`
ResponseBody string `json:"responseBody"`
//QueryConfig struct {
// ResponseType string `json:"responseType"`
// CallbackUrl string `json:"callbackUrl"`
// Method string `json:"method"`
// Url string `json:"url"`
// Headers map[string]any `json:"headers"`
// Body map[string]any `json:"body"`
// Response []map[string]any `json:"response"`
// ResponseBody string `json:"responseBody"`
// ResponseTokenField string `json:"responseTokenField"`
//} `json:"queryConfig"`
} `json:"model"`
ExecutedNodes []string `json:"executedNodes"`
}
type ComposeMessagesReq struct {
BuildType int `json:"buildType"`
ModelName string `json:"modelName"`
SkillName string `json:"skillName"`
CallbackUrl string `json:"callbackUrl"`
Form []map[string]any `json:"form"`
UserForm []map[string]any `json:"userForm"`
UserPrompt string `json:"userPrompt" dc:"用户提示词"`
Consult []Consult `json:"consult"`
SessionId string `json:"sessionId" dc:"会话ID"`
NodeId string `json:"nodeId"`
Cause string `json:"cause"`
}
type Consult struct {
Type string `json:"type"`
Url string `json:"url"`
BuildType int `json:"buildType"`
ModelName string `json:"modelName"`
SkillName string `json:"skillName"`
Form map[string]any `json:"form"`
UserForm map[string]any `json:"userForm"`
UserFiles []string `json:"userFiles"`
SessionId string `json:"sessionId" dc:"会话ID"`
IsBuild bool `json:"isBuild"`
Cause string `json:"cause"`
}
type ComposeMessagesRes struct {
TaskId string `json:"taskId"`
Messages map[string]any `json:"messages"`
EpicycleId int64 `json:"epicycleId" dc:"轮次ID"`
}
type VideoConcatReq struct {
VideoUrls []string `json:"video_urls"`
Method string `json:"method"`
Upload bool `json:"upload"`
CallbackUrl string `json:"callback_url"`
}
type VideoConcatRes struct {
TaskId string `json:"taskId"`
}
type ModelGatewayReq struct {
type CreateTaskReq struct {
ModelName string `json:"modelName"`
ModelKey string `json:"modelKey"`
BizName string `json:"bizName"`
@@ -113,79 +54,86 @@ type ModelGatewayReq struct {
EpicycleId int64 `json:"epicycleId" dc:"轮次ID"`
}
type ModelGatewayRes struct {
type CreateTaskRes struct {
TaskId string `json:"taskId"`
}
type ComposeCallbackReq struct {
g.Meta `path:"/composeCallBack" method:"post" tags:"提示词处理" summary:"提示词 回调" dc:"提示词 成功后 GET 回调:callbackUrl/{bizName}"`
TaskId string `json:"taskId"`
Status string `json:"status"`
Messages struct {
TotalRounds int `json:"total_rounds"` // 总轮数
Rounds []map[string]any `json:"rounds"` // 每轮详情(动态类型)
} `json:"messages,omitempty"`
EpicycleId int64 `json:"epicycleId"`
ErrorMsg string `json:"errorMsg,omitempty"`
BillingData []map[string]any `json:"billing_data"`
type GetIsChatModelRes struct {
ModelName string `json:"modelName"`
ResponseBody map[string]any `json:"responseBody"`
}
type ModelCallbackReq struct {
g.Meta `path:"/modelCallback" method:"post" tags:"提示词处理" summary:"model-gateway 回调" dc:"model-gateway 成功后 GET 回调:callbackUrl/{bizName}"`
TaskId string `p:"task_id" json:"task_id" v:"required#task_id不能为空" dc:"网关任务ID"`
State int `p:"state" json:"state" dc:"网关任务状态"`
OssFile string `p:"oss_file" json:"oss_file" dc:"结果文件地址"`
FileType string `p:"file_type" json:"file_type" dc:"结果文件类型"`
ErrorMsg string `json:"error_msg"`
BillingData []map[string]any `json:"billing_data"`
g.Meta `path:"/modelCallback" method:"post" tags:"提示词处理" summary:"model-gateway 回调" dc:"model-gateway 成功后 GET 回调:callbackUrl/{bizName}"`
TaskId string `p:"task_id" json:"task_id" v:"required#task_id不能为空" dc:"网关任务ID"`
State int `p:"state" json:"state" dc:"网关任务状态"`
OssFile string `p:"oss_file" json:"oss_file" dc:"结果文件地址"`
FileType string `p:"file_type" json:"file_type" dc:"结果文件类型"`
Text string `p:"text" json:"text" dc:"文本结果(可选,最多约 2000 字符)"`
}
type VideoCallbackReq struct {
g.Meta `path:"/videoCallback" method:"post" tags:"视频处理" summary:"media 回调" dc:"media 成功后 GET 回调:callbackUrl/{bizName}"`
TaskId string `json:"taskId"`
FileURL string `json:"fileUrl"`
type TaskCallback struct {
TaskID string `json:"taskId"`
State int `json:"state"` // 0排队中/1执行中/2成功/3失败/4已下载
OssFile string `json:"ossFile"`
FileType string `json:"fileType"`
Text string `json:"text"`
//ImgContent *Image `json:"imgContent"`
}
type Text struct {
Choices []struct {
FinishReason string `json:"finish_reason"`
Index int `json:"index"`
Message struct {
Content string `json:"content"`
Role string `json:"role"`
} `json:"message"`
} `json:"choices"`
Created int `json:"created"`
Id string `json:"id"`
Model string `json:"model"`
Object string `json:"object"`
Usage struct {
CompletionTokens int `json:"completion_tokens"`
PromptTokens int `json:"prompt_tokens"`
PromptTokensDetails struct {
CachedTokens int `json:"cached_tokens"`
}
TotalTokens int `json:"total_tokens"`
} `json:"usage"`
}
type Image struct {
Output struct {
Choices []struct {
FinishReason string `json:"finish_reason"`
Message struct {
Content []struct {
Image string `json:"image"`
} `json:"content"`
Role string `json:"role"`
} `json:"message"`
} `json:"choices"`
} `json:"output"`
Usage struct {
Height int `json:"height"`
ImageCount int `json:"image_count"`
Width int `json:"width"`
} `json:"usage"`
RequestId string `json:"request_id"`
}
//=============================================================================
// 原始入参结构体
type Word struct {
Confidence float64 `json:"confidence"`
StartTime float64 `json:"startTime"`
EndTime float64 `json:"endTime"`
Word string `json:"word"`
}
type Sentence struct {
EndTime float64 `json:"endTime"`
StartTime float64 `json:"startTime"`
Text string `json:"text"`
Words []Word `json:"words"`
}
type InputData struct {
Data struct {
Sentences []Sentence `json:"sentences"`
} `json:"data"`
}
// 输出目标结构体(对应截图subtitles格式)
type Subtitle struct {
Start float64 `json:"start"`
End float64 `json:"end"`
Text string `json:"text"`
}
//==============================================================================
type ExecuteReq struct {
g.Meta `path:"/execute" method:"post" tags:"任务管理" summary:"执行任务" dc:"执行任务"`
FlowId int64 `json:"flowId" dc:"用户流程ID"`
FlowName string `json:"flowName"`
NodeGroupId string `json:"nodeGroupId"`
FlowContent *entity.FlowInfo `json:"flowContent" description:"流程内容"`
NodeInputParams []*entity.FlowNode `json:"nodeInputParams" description:"节点输入参数"`
SessionId string `json:"sessionId" dc:"会话ID"`
Templates []map[string]any `json:"templates"`
Desc string `json:"desc"`
SkillName string `json:"skillName"`
FileUrl []string `json:"fileUrl"`
@@ -205,7 +153,6 @@ type CancelReq struct {
type CreateFlowExecutionReq struct {
FlowUserId int64 `json:"flowUserId" description:"流程ID"`
FlowName string `json:"flowName"`
NodeGroupId string `json:"nodeGroupId"`
TriggerType flow.FlowExecutionTriggerType `json:"triggerType" description:"触发类型"`
DurationMs int64 `json:"durationMs" description:"执行时长(毫秒)"`
Status flow.FlowExecutionStatus `json:"status" description:"状态:1-运行中,2-成功,3-失败"`
@@ -215,7 +162,6 @@ type CreateFlowExecutionReq struct {
ErrorMessage string `json:"errorMessage" description:"错误信息"`
TraceId string `json:"traceId" description:"跟踪ID"`
SessionId string `json:"sessionId" dc:"会话ID"`
Extension map[string]interface{} `json:"extension"`
}
type CreateFlowExecutionRes struct {
@@ -223,33 +169,12 @@ type CreateFlowExecutionRes struct {
}
type UpdateFlowExecutionReq struct {
Id int64 `json:"id" v:"required#ID不能为空"`
NodeGroupId string `json:"nodeGroupId"`
DurationMs int64 `json:"durationMs" description:"执行时长(毫秒)"`
Status flow.FlowExecutionStatus `json:"status" description:"状态:1-运行中,2-成功,3-失败"`
FlowContent *entity.FlowInfo `json:"flowContent" description:"流程内容"`
NodeInputParams []*entity.FlowNode `json:"nodeInputParams" description:"节点输入参数"`
OutputParams []map[string]interface{} `json:"outputParams" description:"输出参数"`
ErrorMessage string `json:"errorMessage" description:"错误信息"`
TraceId string `json:"traceId" description:"跟踪ID"`
TotalTokens int `json:"totalTokens" description:"总token"`
TotalFee float64 `json:"totalFee" description:"总费用"`
SessionDel bool `json:"sessionDel" description:"会话是否删除"`
ResultDel bool `json:"resultDel" description:"结果是否删除"`
Extension map[string]interface{} `json:"extension"`
}
type DeleteResultReq struct {
g.Meta `path:"/deleteResult" method:"delete" tags:"任务管理" summary:"删除结果" dc:"删除结果"`
Id int64 `json:"id" v:"required#ID不能为空"`
Content string `json:"content"`
}
type DeleteSessionReq struct {
g.Meta `path:"/deleteSession" method:"delete" tags:"任务管理" summary:"删除会话" dc:"删除会话"`
Id int64 `json:"id" v:"required#ID不能为空"`
Id int64 `json:"id" v:"required#ID不能为空"`
DurationMs int64 `json:"durationMs" description:"执行时长(毫秒)"`
Status flow.FlowExecutionStatus `json:"status" description:"状态:1-运行中,2-成功,3-失败"`
OutputParams []map[string]interface{} `json:"outputParams" description:"输出参数"`
ErrorMessage string `json:"errorMessage" description:"错误信息"`
TraceId string `json:"traceId" description:"跟踪ID"`
}
type GetFlowExecutionReq struct {
@@ -259,20 +184,11 @@ type GetFlowExecutionReq struct {
SessionId string `json:"sessionId" dc:"会话ID"`
}
type GetSessionListReq struct {
g.Meta `path:"/sessionList" method:"get" tags:"任务管理" summary:"会话列表" dc:"会话列表"`
*beans.Page `json:"page"`
}
type ListFlowExecutionReq struct {
g.Meta `path:"/list" method:"get" tags:"任务管理" summary:"任务列表" dc:"任务列表"`
*beans.Page `json:"page"`
Creator string `json:"creator"`
SessionDel *bool `json:"sessionDel"`
ResultDel *bool `json:"resultDel"`
IsResult bool `json:"isResult"`
Page *beans.Page `json:"page"`
Creator string `json:"creator"`
}
type ListFlowExecutionRes struct {
@@ -291,7 +207,6 @@ type VOFlowExecution struct {
NodeInputParams []*entity.FlowNode `json:"nodeInputParams" description:"节点输入参数"`
OutputParams []map[string]interface{} `json:"outputParams" description:"输出参数"`
ErrorMessage string `json:"errorMessage" description:"错误信息"`
Extension map[string]interface{} `json:"extension"`
TraceId string `json:"traceId" description:"跟踪ID"`
SessionId string `json:"sessionId" dc:"会话ID"`
CreatedAt *gtime.Time `json:"createdAt" dc:"创建时间"`
@@ -300,19 +215,24 @@ type VOFlowExecution struct {
}
// ========== 核心:构建树状结构 ==========
// 定义树结构
type OutputItem struct {
Id int64 `json:"id,string" description:"ID"`
Timestamp string `json:"timestamp" description:"时间戳key"`
Content string `json:"content" description:"内容值"`
Type string `json:"type" description:"类型"`
Label string `json:"label" description:"后缀+数字标号"`
}
type FlowNode struct {
FlowName string `json:"flowName" description:"流程名称"`
Id int64 `json:"Id,string" description:"任务ID"`
SessionId string `json:"sessionId" description:"会话ID"`
Items []OutputItem `json:"items" description:"输出项列表"`
}
type DateNode struct {
CreateDate string `json:"createDate" description:"创建日期"`
Items []OutputItem `json:"items" description:"直接是结果项列表"`
CreateDate string `json:"createDate" description:"创建日期"`
Flows []FlowNode `json:"flows" description:"流程列表"`
}
// 最终树结构返回体
type ListFlowExecutionTreeRes struct {
Tree []DateNode `json:"tree"`
ImgAddressPrefix string `json:"imgAddressPrefix"`
@@ -1,76 +0,0 @@
package node
import (
"ai-agent/workflow/consts/node"
flowDto "ai-agent/workflow/model/dto/flow"
"ai-agent/workflow/model/entity"
"gitea.redpowerfuture.com/red-future/common/beans"
"github.com/gogf/gf/v2/frame/g"
)
// CreateNodeExecutionReq 创建节点执行记录请求
type CreateNodeExecutionReq struct {
g.Meta `path:"/create" method:"post" tags:"节点执行记录" summary:"创建节点执行记录" dc:"创建节点执行记录"`
FlowExecutionId int64 `json:"flowExecutionId" v:"required#流程执行ID不能为空"`
NodeId string `json:"nodeId" v:"required#节点ID不能为空"`
NodeName string `json:"nodeName"`
NodeGroupId string `json:"nodeGroupId"`
Status node.NodeExecutionStatus `json:"status"`
InputParams *flowDto.NodeExecutionInput `json:"inputParams"`
InputParamsPath string
OutputParams *flowDto.NodeExecutionInput `json:"outputParams"`
OutputParamsPath string
}
type CreateNodeExecutionRes struct {
Id int64 `json:"id,string"`
}
// UpdateNodeExecutionReq 更新节点执行记录请求
type UpdateNodeExecutionReq struct {
g.Meta `path:"/update" method:"put" tags:"节点执行记录" summary:"更新节点执行记录" dc:"更新节点执行记录状态和结果"`
Id int64 `json:"id" v:"required#ID不能为空"`
InputParams *flowDto.NodeExecutionInput `json:"inputParams"`
InputParamsPath string
OutputParams *flowDto.NodeExecutionInput `json:"outputParams"`
OutputParamsPath string
PromptTokens int `json:"promptTokens"`
CompletionTokens int `json:"completionTokens"`
TotalTokens int `json:"totalTokens"`
TokenInfo []map[string]any `json:"tokenInfo"`
Status node.NodeExecutionStatus `json:"status"`
DurationMs int64 `json:"durationMs"`
ErrorMessage string `json:"errorMessage"`
}
// DeleteNodeExecutionReq 删除节点执行记录请求
type DeleteNodeExecutionReq struct {
g.Meta `path:"/delete" method:"delete" tags:"节点执行记录" summary:"删除节点执行记录" dc:"删除节点执行记录"`
Id int64 `json:"id" v:"required#ID不能为空"`
}
// GetNodeExecutionReq 根据ID查询节点执行记录请求
type GetNodeExecutionReq struct {
g.Meta `path:"/get" method:"get" tags:"节点执行记录" summary:"查询节点执行记录详情" dc:"根据ID查询节点执行记录详情"`
Id int64 `json:"id" v:"required#ID不能为空"`
}
// ListNodeExecutionByFlowReq 查询流程下所有节点执行记录请求
type ListNodeExecutionByFlowReq struct {
g.Meta `path:"/listByFlow" method:"get" tags:"节点执行记录" summary:"查询流程节点执行列表" dc:"查询指定流程执行下的所有节点执行记录"`
Page *beans.Page `json:"page"`
FlowExecutionId int64 `json:"flowExecutionId" v:"required#流程执行ID不能为空"`
NodeGroupId string `json:"nodeGroupId"`
}
// NodeExecutionResp 节点执行记录响应
type NodeExecutionResp struct {
*entity.NodeExecution
}
// ListNodeExecutionResp 节点执行记录列表响应
type ListNodeExecutionResp struct {
List []*entity.NodeExecution `json:"list"`
Total int `json:"total"`
}
@@ -27,7 +27,3 @@ type ModelItem struct {
Name string `json:"name"`
Form []node.NodeFormField `json:"form"`
}
type ModelTypeResponse struct {
Type map[int]string `json:"type"` // key 自动解析为整数 100/200/300...
}
@@ -1,70 +0,0 @@
package node
import (
"ai-agent/workflow/consts/node"
"ai-agent/workflow/model/entity"
"gitea.redpowerfuture.com/red-future/common/beans"
"github.com/gogf/gf/v2/frame/g"
)
// CreateNodePromptReq 创建节点提示词请求
type CreateNodePromptReq struct {
g.Meta `path:"/create" method:"post" tags:"节点提示词管理" summary:"创建节点提示词" dc:"创建用户自定义节点提示词"`
NodeType node.NodeType `json:"nodeType" v:"required#节点类型不能为空"`
Prompt string `json:"prompt" v:"required#提示词不能为空"`
SourceType node.SourceType `json:"sourceType"`
}
type CreateNodePromptRes struct {
Id int64 `json:"id,string"`
}
// UpdateNodePromptReq 更新节点提示词请求
type UpdateNodePromptReq struct {
g.Meta `path:"/update" method:"put" tags:"节点提示词管理" summary:"更新节点提示词" dc:"更新用户自定义节点提示词"`
Id int64 `json:"id" v:"required#ID不能为空"`
NodeType node.NodeType `json:"nodeType"`
Prompt string `json:"prompt"`
}
// DeleteNodePromptReq 删除节点提示词请求
type DeleteNodePromptReq struct {
g.Meta `path:"/delete" method:"delete" tags:"节点提示词管理" summary:"删除节点提示词" dc:"删除用户自定义节点提示词"`
Id int64 `json:"id" v:"required#ID不能为空"`
}
// GetNodePromptReq 根据ID查询节点提示词请求
type GetNodePromptReq struct {
g.Meta `path:"/get" method:"get" tags:"节点提示词管理" summary:"查询节点提示词详情" dc:"根据ID查询节点提示词详情"`
Id int64 `json:"id"`
Prompt string `json:"prompt"`
Creator string `json:"creator"`
}
// ListNodePromptReq 查询节点提示词列表请求
type ListNodePromptReq struct {
g.Meta `path:"/list" method:"get" tags:"节点提示词管理" summary:"查询节点提示词列表" dc:"查询当前创建人的节点提示词,包含系统和用户自定义"`
Page *beans.Page `json:"page"`
Creator string `json:"creator"`
NodeType node.NodeType `json:"nodeType"`
}
// ListMyNodePromptReq 查询当前用户节点提示词列表请求
type ListMyNodePromptReq struct {
g.Meta `path:"/listMy" method:"get" tags:"节点提示词管理" summary:"查询当前用户节点提示词列表" dc:"查询当前创建人自己创建的节点提示词列表"`
Page *beans.Page `json:"page"`
NodeType node.NodeType `json:"nodeType"`
Creator string `json:"creator"`
}
// NodePromptResp 节点提示词响应
type NodePromptResp struct {
*entity.NodePrompt
}
// ListNodePromptResp 节点提示词列表响应
type ListNodePromptResp struct {
List []*entity.NodePrompt `json:"list"`
Total int `json:"total"`
}
@@ -1,54 +0,0 @@
package pull
import (
"ai-agent/workflow/consts/flow"
"ai-agent/workflow/model/entity"
"gitea.redpowerfuture.com/red-future/common/beans"
"github.com/gogf/gf/v2/os/gtime"
)
type CreateActivePullReq struct {
Type string `json:"type"`
RequestParament map[string]any `json:"requestParament"`
ResponseParament map[string]any `json:"responseParament"`
Extension map[string]any `json:"extension"`
}
type CreateActivePullRes struct {
Id int64 `json:"id,string"`
}
type UpdateActivePullReq struct {
Id int64 `json:"id" v:"required#ID不能为空"`
Type string `json:"type"`
RequestParament map[string]any `json:"requestParament"`
ResponseParament map[string]any `json:"responseParament"`
Extension map[string]any `json:"extension"`
}
type DeleteActivePullReq struct {
Id int64 `json:"id" v:"required#ID不能为空"`
}
type ListActivePullReq struct {
Page *beans.Page `json:"page"`
Type string `json:"type"`
}
type ListActivePullRes struct {
List []*ActivePullVO `json:"list"`
Total int `json:"total"`
}
type ActivePullVO struct {
Id int64 `json:"id,string" dc:"id"`
FlowName string `json:"flowName" description:"流程名称"`
Description string `json:"description" description:"流程描述"`
FlowContent *entity.FlowInfo `json:"flowContent" description:"流程内容"`
NodeInputParams []*entity.FlowNode `json:"nodeInputParams" description:"节点输入参数"`
AccessLevel flow.FlowUserAccessLevel `json:"accessLevel" description:"访问权限:1私有,2团队,3公开"`
SourceFlowTemplateId int64 `json:"sourceFlowTemplateId,string" description:"来源流程模板ID"`
CreatedAt *gtime.Time `json:"createdAt" dc:"创建时间"`
UpdatedAt *gtime.Time `json:"updatedAt" dc:"更新时间"`
}
-28
View File
@@ -1,28 +0,0 @@
package entity
import "gitea.redpowerfuture.com/red-future/common/beans"
type ActivePull struct {
beans.SQLBaseDO `orm:",inherit"` // 嵌入基础字段:Id, TenantId, Creator, CreatedAt, Updater, UpdatedAt, DeletedAt
Type string `orm:"type" json:"type"`
RequestParament map[string]any `orm:"request_parament" json:"requestParament"`
ResponseParament map[string]any `orm:"response_parament" json:"responseParament"`
Extension map[string]any `orm:"extension" json:"extension"`
}
type activePullCol struct {
beans.SQLBaseCol
Type string
RequestParament string
ResponseParament string
Extension string
}
var ActivePullCol = activePullCol{
SQLBaseCol: beans.DefSQLBaseCol,
Type: "type",
RequestParament: "request_parament",
ResponseParament: "response_parament",
Extension: "extension",
}
-18
View File
@@ -11,7 +11,6 @@ type FlowExecution struct {
// 业务字段
FlowUserId int64 `orm:"flow_user_id" json:"flowUserId" description:"流程ID"`
FlowName string `orm:"flow_name" json:"flowName" description:"流程名称"`
NodeGroupId string `orm:"node_group_id" json:"nodeGroupId" description:"节点组ID"`
TriggerType flow.FlowExecutionTriggerType `orm:"trigger_type" json:"triggerType" description:"触发类型"`
DurationMs int64 `orm:"duration_ms" json:"durationMs" description:"执行时长(毫秒)"`
Status flow.FlowExecutionStatus `orm:"status" json:"status" description:"状态:1-运行中,2-成功,3-失败"`
@@ -21,18 +20,12 @@ type FlowExecution struct {
ErrorMessage string `orm:"error_message" json:"errorMessage" description:"错误信息"`
TraceId string `orm:"trace_id" json:"traceId" description:"跟踪ID"`
SessionId string `orm:"session_id" json:"sessionId" description:"会话ID"`
TotalTokens int `orm:"total_tokens" json:"totalTokens" description:"总token消耗"`
TotalFee int `orm:"total_fee" json:"totalFee" description:"总费用"`
SessionDel bool `orm:"session_del" json:"sessionDel" description:"会话是否删除"`
ResultDel bool `orm:"result_del" json:"resultDel" description:"结果是否删除"`
Extension map[string]interface{} `orm:"extension" json:"extension" description:"扩展字段"`
}
type flowExecutionCol struct {
beans.SQLBaseCol
FlowUserId string
FlowName string
NodeGroupId string
TriggerType string
DurationMs string
Status string
@@ -42,18 +35,12 @@ type flowExecutionCol struct {
ErrorMessage string
TraceId string
SessionId string
TotalTokens string
TotalFee string
SessionDel string
ResultDel string
Extension string
}
var FlowExecutionCol = flowExecutionCol{
SQLBaseCol: beans.DefSQLBaseCol,
FlowUserId: "flow_user_id",
FlowName: "flow_name",
NodeGroupId: "node_group_id",
TriggerType: "trigger_type",
DurationMs: "duration_ms",
Status: "status",
@@ -63,9 +50,4 @@ var FlowExecutionCol = flowExecutionCol{
ErrorMessage: "error_message",
TraceId: "trace_id",
SessionId: "session_id",
TotalTokens: "total_tokens",
TotalFee: "total_fee",
SessionDel: "session_del",
ResultDel: "result_del",
Extension: "extension",
}
+9 -14
View File
@@ -15,20 +15,15 @@ type FlowInfo struct {
}
type FlowNode struct {
Id string `json:"id"`
NodeCode node.NodeType `json:"nodeCode"`
Name string `json:"name"`
Config map[string]interface{} `json:"config"`
PatchLayout bool `json:"patchLayout"`
SkillName string `json:"skillName"`
PromptContent string `json:"promptContent"`
IsSaveFile bool `json:"isSaveFile"`
InputSource []FlowNodeInputSource `json:"inputSource"` // 前端指定:来源节点ID
FormConfig []node.NodeFormField `json:"formConfig"`
ModelConfig node.ModelItem `json:"modelConfig"`
ModelOutputFields []string `json:"modelOutputFields"`
OutputConfig []node.NodeFormField `json:"outputConfig"`
OutputResult []node.NodeFormField `json:"outputResult" ds:"节点输出结果"`
Id string `json:"id"`
NodeCode node.NodeType `json:"nodeCode"`
Name string `json:"name"`
Config map[string]interface{} `json:"config"`
SkillName string `json:"skillName"`
InputSource []FlowNodeInputSource `json:"inputSource"` // 前端指定:来源节点ID
FormConfig []node.NodeFormField `json:"formConfig"`
ModelConfig node.ModelItem `json:"modelConfig"`
OutputResult []node.NodeFormField `json:"outputResult" ds:"节点输出结果"`
}
type FlowNodeInputSource struct {
-67
View File
@@ -1,67 +0,0 @@
package entity
import (
"ai-agent/workflow/consts/node"
"gitea.redpowerfuture.com/red-future/common/beans"
)
// NodeExecution 节点执行记录
// 记录每个节点的入参、出参、token消耗、执行状态等信息
type NodeExecution struct {
beans.SQLBaseDO `orm:",inherit"` // 嵌入基础字段:Id, TenantId, Creator, CreatedAt, Updater, UpdatedAt, DeletedAt
FlowExecutionId int64 `orm:"flow_execution_id" json:"flowExecutionId" description:"流程执行ID"`
NodeId string `orm:"node_id" json:"nodeId" description:"节点ID"`
NodeName string `orm:"node_name" json:"nodeName" description:"节点名称"`
NodeGroupId string `orm:"node_group_id" json:"nodeGroupId" description:"节点组ID"`
InputParams map[string]interface{} `orm:"input_params" json:"inputParams" description:"节点输入参数"`
InputParamsPath string `orm:"input_params_path" json:"inputParamsPath" description:"节点输入参数路径"`
OutputParams map[string]interface{} `orm:"output_params" json:"outputParams" description:"节点输出参数"`
OutputParamsPath string `orm:"output_params_path" json:"outputParamsPath" description:"节点输出参数路径"`
PromptTokens int `orm:"prompt_tokens" json:"promptTokens" description:"提示词token消耗"`
CompletionTokens int `orm:"completion_tokens" json:"completionTokens" description:"补全token消耗"`
TotalTokens int `orm:"total_tokens" json:"totalTokens" description:"总token消耗"`
TokenInfo []map[string]interface{} `orm:"token_info" json:"tokenInfo" description:"token信息"`
Status node.NodeExecutionStatus `orm:"status" json:"status" description:"执行状态:1-运行中,2-成功,3-失败,4-暂停,5-等待执行"`
DurationMs int64 `orm:"duration_ms" json:"durationMs" description:"执行时长(毫秒)"`
ErrorMessage string `orm:"error_message" json:"errorMessage" description:"错误信息"`
}
type nodeExecutionCol struct {
beans.SQLBaseCol
FlowExecutionId string
NodeId string
NodeName string
NodeGroupId string
InputParams string
InputParamsPath string
OutputParams string
OutputParamsPath string
PromptTokens string
CompletionTokens string
TotalTokens string
TokenInfo string
Status string
DurationMs string
ErrorMessage string
}
var NodeExecutionCol = nodeExecutionCol{
SQLBaseCol: beans.DefSQLBaseCol,
FlowExecutionId: "flow_execution_id",
NodeId: "node_id",
NodeName: "node_name",
NodeGroupId: "node_group_id",
InputParams: "input_params",
InputParamsPath: "input_params_path",
OutputParams: "output_params",
OutputParamsPath: "output_params_path",
PromptTokens: "prompt_tokens",
CompletionTokens: "completion_tokens",
TotalTokens: "total_tokens",
TokenInfo: "token_info",
Status: "status",
DurationMs: "duration_ms",
ErrorMessage: "error_message",
}
-29
View File
@@ -1,29 +0,0 @@
package entity
import (
"ai-agent/workflow/consts/node"
"gitea.redpowerfuture.com/red-future/common/beans"
)
type NodePrompt struct {
beans.SQLBaseDO `orm:",inherit"` // 嵌入基础字段:Id, TenantId, Creator, CreatedAt, Updater, UpdatedAt, DeletedAt
NodeType node.NodeType `orm:"node_type" json:"nodeType"`
Prompt string `orm:"prompt" json:"prompt"`
SourceType node.SourceType `orm:"source_type" json:"sourceType"`
}
type nodePromptCol struct {
beans.SQLBaseCol
NodeType string
Prompt string
SourceType string
}
var NodePromptCol = nodePromptCol{
SQLBaseCol: beans.DefSQLBaseCol,
NodeType: "node_type",
Prompt: "prompt",
SourceType: "source_type",
}
@@ -1,101 +0,0 @@
package pull
import (
pullDao "ai-agent/workflow/dao/pull"
pullDto "ai-agent/workflow/model/dto/pull"
"context"
"github.com/gogf/gf/v2/util/gconv"
)
var ActivePullService = &activePullService{}
type activePullService struct{}
func (s *activePullService) Create(ctx context.Context, req *pullDto.CreateActivePullReq) (res *pullDto.CreateActivePullRes, err error) {
id, err := pullDao.ActivePullDao.Insert(ctx, req)
if err != nil {
return
}
return &pullDto.CreateActivePullRes{Id: id}, nil
}
func (s *activePullService) Update(ctx context.Context, req *pullDto.UpdateActivePullReq) (err error) {
_, err = pullDao.ActivePullDao.Update(ctx, req)
return
}
func (s *activePullService) Delete(ctx context.Context, req *pullDto.DeleteActivePullReq) (err error) {
_, err = pullDao.ActivePullDao.Delete(ctx, req)
return
}
//func (s *activePullService) AllList(ctx context.Context) (err error) {
// ctx = context.WithValue(ctx, "user", &beans.User{
// UserName: "admin",
// })
// for {
// select {
// case <-ctx.Done():
// return ctx.Err()
// default:
// }
//
// var list []*entity.ActivePull
// list, _, err = pullDao.ActivePullDao.ListNative(ctx, &pullDto.ListActivePullReq{})
// if err != nil {
// g.Log().Error(ctx, "AllList query failed: %v", err)
// time.Sleep(time.Second * 3)
// continue
// }
//
// // Get all active pull tasks and check each one for results
// for _, item := range list {
// var result map[string]any
// result, err = flow.PullTaskResult(ctx, item.RequestParament, item.Extension)
// if err != nil {
// g.Log().Error(ctx, "PullTaskResult failed for item %d: %v", item.Id, err)
// continue
// }
// if !g.IsEmpty(result) {
// // Find the task ID that matches the creation pattern
// // When created in CreateGatewayTask (flow/lambda_node_util.go),
// // the last parameter value extracted from the response becomes the waiting task ID
// var id string
// if taskId, ok := item.RequestParament["task_id"]; ok {
// id = gconv.String(taskId)
// } else if requestId, ok := item.RequestParament["id"]; ok {
// id = gconv.String(requestId)
// } else if jobId, ok := item.RequestParament["job_id"]; ok {
// id = gconv.String(jobId)
// } else {
// // Fallback to original behavior: use last value (matches creation logic)
// for _, v := range item.RequestParament {
// id = gconv.String(v)
// }
// }
// if id != "" {
// flow.Notify(id, result)
// // Delete after successful notification
// _, _ = pullDao.ActivePullDao.Delete(ctx, &pullDto.DeleteActivePullReq{Id: item.Id})
// } else {
// g.Log().Warning(ctx, "AllList: could not extract task ID for item %d", item.Id)
// }
// }
// }
//
// time.Sleep(time.Second * 10)
// }
//}
func (s *activePullService) List(ctx context.Context, req *pullDto.ListActivePullReq) (res *pullDto.ListActivePullRes, err error) {
list, total, err := pullDao.ActivePullDao.List(ctx, req)
if err != nil {
return nil, err
}
res = &pullDto.ListActivePullRes{
Total: total,
}
err = gconv.Struct(list, &res.List)
return
}
+148 -293
View File
@@ -5,25 +5,22 @@ import (
"ai-agent/workflow/consts/node"
fileDao "ai-agent/workflow/dao/file"
flowDao "ai-agent/workflow/dao/flow"
nodeDao "ai-agent/workflow/dao/node"
"ai-agent/workflow/model/dto"
fileDto "ai-agent/workflow/model/dto/file"
flowDto "ai-agent/workflow/model/dto/flow"
nodeDto "ai-agent/workflow/model/dto/node"
"ai-agent/workflow/model/entity"
"context"
"errors"
"fmt"
"sort"
"strconv"
"strings"
"sync"
"time"
"gitea.redpowerfuture.com/red-future/common/utils"
"github.com/cloudwego/eino/compose"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gtime"
"github.com/gogf/gf/v2/util/gconv"
"github.com/google/uuid"
"go.opentelemetry.io/otel/trace"
)
@@ -45,94 +42,54 @@ func (s *flowExecutionService) Get(ctx context.Context, req *flowDto.GetFlowExec
return res, err
}
func (s *flowExecutionService) DeleteResult(ctx context.Context, req *flowDto.DeleteResultReq) (err error) {
r, err := flowDao.FlowExecutionDao.Get(ctx, &flowDto.GetFlowExecutionReq{Id: req.Id})
if err != nil {
return err
}
// 遍历并剔除值等于 req.Url 的数据
newOutputParams := make([]map[string]any, 0)
for _, paramMap := range r.OutputParams {
// 单个 paramMap 过滤
cleanMap := make(map[string]any)
for k, v := range paramMap {
// 转为字符串对比
if gconv.String(v) != req.Content {
cleanMap[k] = v
}
}
// 只保留非空 map,避免出现空层级
if len(cleanMap) > 0 {
newOutputParams = append(newOutputParams, cleanMap)
}
}
// 赋值回原数据
r.OutputParams = newOutputParams
// 执行更新:更新 OutputParams + 标记删除
flowUpdateReq := new(flowDto.UpdateFlowExecutionReq)
flowUpdateReq.Id = req.Id
flowUpdateReq.OutputParams = r.OutputParams
_, err = flowDao.FlowExecutionDao.Update(ctx, flowUpdateReq)
return
}
func (s *flowExecutionService) DeleteSession(ctx context.Context, req *flowDto.DeleteSessionReq) (err error) {
flowUpdateReq := new(flowDto.UpdateFlowExecutionReq)
flowUpdateReq.Id = req.Id
flowUpdateReq.SessionDel = true
_, err = flowDao.FlowExecutionDao.Update(ctx, flowUpdateReq)
return
}
func (s *flowExecutionService) GetSessionList(ctx context.Context, req *flowDto.GetSessionListReq) (res *flowDto.ListFlowExecutionRes, err error) {
user, err := utils.GetUserInfo(ctx)
if err != nil {
return
}
flowReq := new(flowDto.ListFlowExecutionReq)
flowReq.Page = req.Page
flowReq.Creator = user.UserName
flowReq.SessionDel = gconv.PtrBool(true)
list, total, err := flowDao.FlowExecutionDao.List(ctx, flowReq)
if err != nil {
return nil, err
}
res = &flowDto.ListFlowExecutionRes{
Total: total,
}
err = gconv.Struct(list, &res.List)
return res, err
}
func (s *flowExecutionService) List(ctx context.Context, req *flowDto.ListFlowExecutionReq) (res *flowDto.ListFlowExecutionTreeRes, err error) {
user, err := utils.GetUserInfo(ctx)
if err != nil {
return
}
req.Creator = user.UserName
req.ResultDel = gconv.PtrBool(true)
req.IsResult = true
list, _, err := flowDao.FlowExecutionDao.List(ctx, req)
if err != nil {
return nil, err
}
// 过滤出有有效输出的执行记录
var validList []*entity.FlowExecution
// ===================== 核心修复:只统计【有数据】的执行记录,空的直接跳过 =====================
executionNumber := make(map[int64]int) // executionId -> 倒序编号(最新=1
// 第一次遍历:只处理【有输出参数】的记录,统计并分配编号
var validList []*entity.FlowExecution // 只存有效(非空)记录
for _, execution := range list {
if !g.IsEmpty(execution.OutputParams) {
validList = append(validList, execution)
if g.IsEmpty(execution.OutputParams) {
continue // 空数据直接过滤,不参与编号、不展示
}
validList = append(validList, execution)
}
// 1. 按日期归集,严格使用 Y-m-d 格式
dateMap := make(map[string][]flowDto.OutputItem)
// 给有效记录分配【时间倒序编号】(最新=1)
totalValid := len(validList)
for idx, execution := range validList {
executionNumber[execution.Id] = totalValid - idx
}
// 2. 分组映射:日期 -> 流程节点
type flowWrap struct {
flowNode flowDto.FlowNode
createdAt *gtime.Time
}
dateMap := make(map[string]*[]flowWrap)
// 遍历【有效数据】构建结构
for _, execution := range validList {
// 按要求使用 Y-m-d
createDate := execution.CreatedAt.Format("Y-m-d")
execID := execution.Id
flowName := execution.FlowName
outputParams := execution.OutputParams
// 编号只算有效数据,不会把空的算进去
num := executionNumber[execution.Id]
displayFlowName := fmt.Sprintf("会话-%d(%s)", num, flowName)
// 3. 解析 outputParams
var tempItems []flowDto.OutputItem
for _, paramMap := range outputParams {
for tsKey, value := range paramMap {
@@ -140,116 +97,90 @@ func (s *flowExecutionService) List(ctx context.Context, req *flowDto.ListFlowEx
continue
}
tempItems = append(tempItems, flowDto.OutputItem{
Id: execID,
Timestamp: tsKey,
Content: gconv.String(value),
})
}
}
// ===================== 修复1:如果解析后依然为空,直接跳过,不生成第二层节点 =====================
if len(tempItems) == 0 {
continue
}
// 单条执行内按时间戳正序
// 时间戳正序
sort.Slice(tempItems, func(i, j int) bool {
t1, _ := strconv.ParseInt(tempItems[i].Timestamp, 10, 64)
t2, _ := strconv.ParseInt(tempItems[j].Timestamp, 10, 64)
return t1 < t2
})
dateMap[createDate] = append(dateMap[createDate], tempItems...)
}
// ========== 修复编号乱序核心逻辑 ==========
// 1. 取出所有日期并 倒序排序(和前端展示顺序一致)
var sortedDates []string
for d := range dateMap {
sortedDates = append(sortedDates, d)
}
// 日期字符串倒序
sort.Slice(sortedDates, func(i, j int) bool {
return sortedDates[i] > sortedDates[j]
})
// 2. 按【前端展示顺序】拼接所有条目,用于统计总数量
var allItems []flowDto.OutputItem
for _, d := range sortedDates {
allItems = append(allItems, dateMap[d]...)
}
// 3. 统计各类型总数
type totalCnt struct {
total int
idx int
}
typeTotal := make(map[string]*totalCnt)
for _, item := range allItems {
val := item.Content
suffix := "内容"
ext := GetFileTypeByPath(val)
switch ext {
case "image":
suffix = "图片"
case "video":
suffix = "视频"
case "audio":
suffix = "音频"
case "text":
suffix = "文案"
case "html":
suffix = "HTML"
}
if _, ok := typeTotal[suffix]; !ok {
typeTotal[suffix] = &totalCnt{}
}
typeTotal[suffix].total++
}
// 初始序号 = 总数,从最大值开始倒序
for _, v := range typeTotal {
v.idx = v.total
}
// ======================================
var tree []flowDto.DateNode
// 按有序日期遍历生成最终数据
for _, date := range sortedDates {
items := dateMap[date]
if len(items) == 0 {
continue
}
// 逐个生成倒序标签
for idx := range items {
item := &items[idx]
// 标号:相同类型递增,不同重置
suffixCount := make(map[string]int)
for idx := range tempItems {
item := &tempItems[idx]
val := item.Content
suffix := "内容"
ext := GetFileTypeByPath(val)
switch ext {
case "image":
switch {
case strings.Contains(val, "img") || strings.Contains(val, "png") || strings.Contains(val, "jpg"):
suffix = "图片"
case "video":
suffix = "视频"
case "audio":
suffix = "音频"
case "text":
suffix = "文案"
case "html":
case strings.Contains(val, "html") || strings.Contains(val, "HTML"):
suffix = "HTML"
case strings.Contains(val, "inc") || len(val) > 50:
suffix = "文案"
}
cnt := typeTotal[suffix]
item.Type = ext
item.Label = fmt.Sprintf("%s_%d", suffix, cnt.idx)
cnt.idx--
suffixCount[suffix]++
item.Label = fmt.Sprintf("%s_%d", suffix, suffixCount[suffix])
}
// 组装节点
node := flowDto.FlowNode{
FlowName: displayFlowName,
Id: execution.Id,
SessionId: gconv.String(execution.SessionId),
Items: tempItems,
}
if dateMap[createDate] == nil {
dateMap[createDate] = &[]flowWrap{}
}
*dateMap[createDate] = append(*dateMap[createDate], flowWrap{
flowNode: node,
createdAt: execution.CreatedAt,
})
}
// 6. 构建树 + 排序
var tree []flowDto.DateNode
for date, wraps := range dateMap {
// 第二层按创建时间倒序(最新在前)
sort.Slice(*wraps, func(i, j int) bool {
return (*wraps)[i].createdAt.After((*wraps)[j].createdAt)
})
var flowNodes []flowDto.FlowNode
for _, w := range *wraps {
flowNodes = append(flowNodes, w.flowNode)
}
// ===================== 修复2:日期下没有流程,也过滤掉 =====================
if len(flowNodes) == 0 {
continue
}
tree = append(tree, flowDto.DateNode{
CreateDate: date,
Items: items,
Flows: flowNodes,
})
}
// 第一层日期倒序
sort.Slice(tree, func(i, j int) bool {
return tree[i].CreateDate > tree[j].CreateDate
})
imgPrefix, err := utils.GetFileAddressPrefix(ctx)
return &flowDto.ListFlowExecutionTreeRes{
Tree: tree,
@@ -257,12 +188,6 @@ func (s *flowExecutionService) List(ctx context.Context, req *flowDto.ListFlowEx
}, nil
}
// ComposeCallback 提示词回调接口
func (s *flowExecutionService) ComposeCallback(ctx context.Context, req *flowDto.ComposeCallbackReq) (err error) {
Notify(req.TaskId, req)
return nil
}
// ModelCallback 模型回调接口
func (s *flowExecutionService) ModelCallback(ctx context.Context, req *flowDto.ModelCallbackReq) (err error) {
// 唤醒等待的任务
@@ -270,19 +195,43 @@ func (s *flowExecutionService) ModelCallback(ctx context.Context, req *flowDto.M
return nil
}
// VideoCallback 视频拼接回调接口
func (s *flowExecutionService) VideoCallback(ctx context.Context, req *flowDto.VideoCallbackReq) (err error) {
// 唤醒等待的任务
Notify(req.TaskId, req)
return nil
// 全局等待任务回调的工具
var (
asyncMu sync.Mutex
asyncTasks = make(map[string]chan any)
)
// Wait 阻塞等待回调结果
// 调用后会一直卡住,直到 Notify 唤醒 或 超时/取消
func Wait(ctx context.Context, taskId string) (any, error) {
asyncMu.Lock()
ch := make(chan any, 1)
asyncTasks[taskId] = ch
asyncMu.Unlock()
select {
case result := <-ch:
return result, nil
case <-ctx.Done():
asyncMu.Lock()
delete(asyncTasks, taskId)
asyncMu.Unlock()
return nil, ctx.Err()
}
}
// HttpNodeCallback http节点回调接口
func (s *flowExecutionService) HttpNodeCallback(ctx context.Context) (err error) {
r := g.RequestFromCtx(ctx)
taskId := r.Get("task_id").String()
Notify(taskId, r)
return nil
// Notify 回调时调用,唤醒等待的任务
func Notify(taskId string, result any) {
asyncMu.Lock()
defer asyncMu.Unlock()
ch, exist := asyncTasks[taskId]
if !exist {
return
}
ch <- result
delete(asyncTasks, taskId)
}
// ===================== 核心改造:替换为 sync.Map 存储取消上下文 =====================
@@ -349,25 +298,16 @@ func (s *flowExecutionService) Execute(ctx context.Context, req *flowDto.Execute
}
var executionId int64
var isDialogue bool
var nodeGroupId = uuid.NewString()
flowName := req.FlowName
if !g.IsEmpty(req.Desc) {
flowName = req.Desc
}
isDialogue = false
if flowInfo == nil {
isDialogue = false
var r = new(flowDto.CreateFlowExecutionReq)
r.FlowUserId = req.FlowId
r.FlowName = flowName
r.NodeGroupId = nodeGroupId
r.FlowName = req.FlowName
r.TriggerType = flow.FlowExecutionTriggerTypeManual.Code()
r.FlowContent = req.FlowContent
r.NodeInputParams = req.NodeInputParams
r.SessionId = req.SessionId
r.Status = flow.FlowExecutionStatusRunning.Code()
r.Extension = map[string]any{
"templates": req.Templates,
}
span := trace.SpanFromContext(ctx)
if span != nil && span.SpanContext().HasTraceID() {
r.TraceId = span.SpanContext().TraceID().String()
@@ -379,6 +319,7 @@ func (s *flowExecutionService) Execute(ctx context.Context, req *flowDto.Execute
return
}
} else {
isDialogue = true
executionId = flowInfo.Id
span := trace.SpanFromContext(ctx)
if span != nil && span.SpanContext().HasTraceID() {
@@ -386,13 +327,7 @@ func (s *flowExecutionService) Execute(ctx context.Context, req *flowDto.Execute
cancelMap.Store(traceId, cancel)
}
executionReq := flowDto.UpdateFlowExecutionReq{
Id: executionId,
NodeGroupId: nodeGroupId,
FlowContent: req.FlowContent,
NodeInputParams: req.NodeInputParams,
Extension: map[string]any{
"templates": req.Templates,
},
Id: executionId,
Status: flow.FlowExecutionStatusRunning.Code(),
TraceId: traceId,
}
@@ -416,20 +351,19 @@ func (s *flowExecutionService) Execute(ctx context.Context, req *flowDto.Execute
}
}
//if isDialogue && !g.IsEmpty(flowInfo) && !g.IsEmpty(req.ResultUrl) {
// req.NodeGroupId = nodeGroupId
// if strings.HasSuffix(gconv.String(req.ResultUrl), ".inc") {
// err = TextModelSingleLambda(ctx, req, flowInfo)
// return
// } else if strings.HasSuffix(gconv.String(req.ResultUrl), ".png") {
// err = ImgModelSingleLambda(ctx, req, flowInfo)
// return
// } else if strings.HasSuffix(gconv.String(req.ResultUrl), ".html") {
// err = TextImgModelSingleLambda(ctx, req, flowInfo)
// return
// }
// return nil, errors.New("文件格式不支持")
//}
if isDialogue && !g.IsEmpty(flowInfo) && !g.IsEmpty(req.ResultUrl) {
if strings.HasSuffix(gconv.String(req.ResultUrl), ".inc") {
err = TextModelSingleLambda(ctx, req, flowInfo)
return
} else if strings.HasSuffix(gconv.String(req.ResultUrl), ".png") {
err = ImgModelSingleLambda(ctx, req, flowInfo)
return
} else if strings.HasSuffix(gconv.String(req.ResultUrl), ".html") {
err = TextImgModelSingleLambda(ctx, req, flowInfo)
return
}
return nil, errors.New("文件格式不支持")
}
// =========================================================================
// ✅【第1步】给所有判断节点自动生成意图识别节点
@@ -506,11 +440,9 @@ func (s *flowExecutionService) Execute(ctx context.Context, req *flowDto.Execute
// ✅【第4步】构建全局执行入参(现在 schemaMap 是有值的!)
// =========================================================================
execInput := &flowDto.FlowExecutionInput{
NodeGroupId: nodeGroupId,
IsDialogue: isDialogue,
ExecutionId: executionId,
ConfigMap: configMap,
Templates: req.Templates,
SessionId: req.SessionId,
Desc: req.Desc,
SkillName: req.SkillName,
@@ -544,17 +476,6 @@ func (s *flowExecutionService) Execute(ctx context.Context, req *flowDto.Execute
// BuildGraphFromFlowContent 根据前端保存的工作流JSON,自动构建执行图
func BuildGraphFromFlowContent(ctx context.Context, flowContent *entity.FlowInfo, judge2IntentNodeMap map[string]string, summaryNodeID string) (compose.Runnable[any, any], error) {
// 注册自定义合并函数:处理 *flowDto.FlowExecutionInput 类型合并
// 由于 ConfigMap 是 map 引用类型,所有并行分支修改已经写入共享内存
// 直接返回第一个实例即可,所有修改都已经可见
compose.RegisterValuesMergeFunc(func(values []*flowDto.FlowExecutionInput) (*flowDto.FlowExecutionInput, error) {
if len(values) == 0 {
return nil, nil
}
// 返回第一个实例,ConfigMap 是指针,所有修改都已经写入共享数据结构
return values[0], nil
})
graph := compose.NewGraph[any, any]()
nodeMap := make(map[string]entity.FlowNode)
@@ -661,7 +582,7 @@ func BuildGraphFromFlowContent(ctx context.Context, flowContent *entity.FlowInfo
}
_ = graph.AddEdge(summaryNodeID, compose.END)
return graph.Compile(ctx, compose.WithGraphName("auto_build_workflow"), compose.WithNodeTriggerMode(compose.AllPredecessor))
return graph.Compile(ctx, compose.WithGraphName("auto_build_workflow"))
}
// -------------------------- 节点自动注册器(核心分发) --------------------------
@@ -685,7 +606,7 @@ func registerNodeToGraph(graph *compose.Graph[any, any], flowNode entity.FlowNod
}
// 获取入参 - 适配切片类型:遍历所有来源节点
realInput := new(flowDto.NodeExecutionInput)
var realInput any
if len(flowNode.InputSource) > 0 { // 改为判断切片长度
// 遍历所有指定的来源节点,聚合输出结果
for _, inputSource := range flowNode.InputSource { // 遍历切片
@@ -700,71 +621,19 @@ func registerNodeToGraph(graph *compose.Graph[any, any], flowNode entity.FlowNod
Config: currentConfig,
Global: execInput, // ✅ 把【全部节点】的对象直接塞进来
}
// ✅ 插入节点执行记录,初始状态为运行中
startTime := time.Now()
// 上传OSS(每条独立上传)
ossResult, err := Upload(ctx, &dto.UploadFileBytesReq{
FileBytes: gconv.Bytes(gconv.String(realInput)),
FileName: fmt.Sprintf("nodeInput:%v.txt", time.Now().UnixMilli()),
})
if err != nil {
return nil, err
}
nodeExecutionId, err := nodeDao.NodeExecutionDao.Insert(ctx, &nodeDto.CreateNodeExecutionReq{
FlowExecutionId: execInput.ExecutionId,
NodeId: nodeID,
NodeName: flowNode.Name,
NodeGroupId: execInput.NodeGroupId,
InputParamsPath: ossResult.FileURL,
Status: node.NodeExecutionStatusRunning.Code(),
})
if err != nil {
// 记录失败到已执行列表
execInput.ExecutedNodes = append(execInput.ExecutedNodes, flowDto.ExecutedNode{
NodeId: nodeID,
Status: node.NodeExecutionStatusFailed.Code(),
})
return nil, err
}
realInput.NodeExecutionId = nodeExecutionId
// 执行节点
_, err = lambda(ctx, realInput)
durationMs := time.Since(startTime).Milliseconds()
updateReq := &nodeDto.UpdateNodeExecutionReq{
Id: nodeExecutionId,
DurationMs: durationMs,
}
if err != nil {
// 执行失败,更新状态
updateReq.Status = node.NodeExecutionStatusFailed.Code()
updateReq.ErrorMessage = err.Error()
_, _ = nodeDao.NodeExecutionDao.Update(ctx, updateReq)
// 记录失败到已执行列表
execInput.ExecutedNodes = append(execInput.ExecutedNodes, flowDto.ExecutedNode{
NodeId: nodeID,
Status: node.NodeExecutionStatusFailed.Code(),
})
return nil, err
}
// 上传OSS(每条独立上传)
ossResult1, err := Upload(ctx, &dto.UploadFileBytesReq{
FileBytes: gconv.Bytes(gconv.String(realInput)),
FileName: fmt.Sprintf("nodeInput:%v.txt", time.Now().UnixMilli()),
})
output, err := lambda(ctx, realInput)
if err != nil {
return nil, err
}
updateReq.OutputParamsPath = ossResult1.FileURL
// 执行成功,更新状态
updateReq.Status = node.NodeExecutionStatusSuccess.Code()
_, _ = nodeDao.NodeExecutionDao.Update(ctx, updateReq)
// 记录成功到已执行列表
execInput.ExecutedNodes = append(execInput.ExecutedNodes, flowDto.ExecutedNode{
NodeId: nodeID,
Status: node.NodeExecutionStatusSuccess.Code(),
})
// ✅ 自动把当前节点ID 加入已执行列表
execInput.ExecutedNodes = append(execInput.ExecutedNodes, nodeID)
// 输出存入 FlowNodeConfig
if outConfig, ok := output.(*entity.FlowNode); ok {
currentConfig.OutputResult = outConfig.OutputResult
}
// ✅ 关键:返回整个 execInput,让下一个节点继续用!
return execInput, nil
@@ -785,16 +654,6 @@ func registerNodeToGraph(graph *compose.Graph[any, any], flowNode entity.FlowNod
_ = graph.AddLambdaNode(nodeID, compose.InvokableLambda(wrapLambda(VideoModelLambda)))
case node.NodeTypeAudioModel:
_ = graph.AddLambdaNode(nodeID, compose.InvokableLambda(wrapLambda(AudioModelLambda)))
case node.NodeTypeBatchModel:
_ = graph.AddLambdaNode(nodeID, compose.InvokableLambda(wrapLambda(BatchModelLambda)))
case node.NodeTypeDataConversionModel:
_ = graph.AddLambdaNode(nodeID, compose.InvokableLambda(wrapLambda(DataConversionLambda)))
//case node.NodeTypeSenseOptimizeModel:
// _ = graph.AddLambdaNode(nodeID, compose.InvokableLambda(wrapLambda(SenseOptimizeModelLambda)))
//case node.NodeTypeStoryOptimizeModel:
// _ = graph.AddLambdaNode(nodeID, compose.InvokableLambda(wrapLambda(StoryOptimizeModelLambda)))
//case node.NodeTypeScriptOptimizeModel:
// _ = graph.AddLambdaNode(nodeID, compose.InvokableLambda(wrapLambda(ScriptOptimizeModelLambda)))
case node.NodeTypeCustomNode:
_ = graph.AddLambdaNode(nodeID, compose.InvokableLambda(wrapLambda(CustomLambda)))
case node.NodeTypeForm:
@@ -803,10 +662,6 @@ func registerNodeToGraph(graph *compose.Graph[any, any], flowNode entity.FlowNod
_ = graph.AddLambdaNode(nodeID, compose.InvokableLambda(wrapLambda(IntentLambda)))
case node.NodeTypeMerge:
_ = graph.AddLambdaNode(nodeID, compose.InvokableLambda(wrapLambda(MergeLambda)))
case node.NodeTypeDataMerge:
_ = graph.AddLambdaNode(nodeID, compose.InvokableLambda(wrapLambda(DataMergeLambda)))
case node.NodeTypeHttp:
_ = graph.AddLambdaNode(nodeID, compose.InvokableLambda(wrapLambda(HttpLambda)))
}
}
+22 -26
View File
@@ -2,14 +2,13 @@ package flow
import (
"ai-agent/workflow/consts/flow"
"ai-agent/workflow/consts/node"
flowDao "ai-agent/workflow/dao/flow"
flowDto "ai-agent/workflow/model/dto/flow"
"ai-agent/workflow/model/entity"
"ai-agent/workflow/service"
"context"
"gitea.redpowerfuture.com/red-future/common/beans"
commonHttp "gitea.redpowerfuture.com/red-future/common/http"
"gitea.redpowerfuture.com/red-future/common/utils"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/util/gconv"
@@ -19,8 +18,25 @@ var FlowUserService = &flowUserService{}
type flowUserService struct{}
// IsAdmin 调用admin-go服务检查是否是管理员
func IsAdmin(ctx context.Context) (res bool, err error) {
headers := make(map[string]string)
if r := g.RequestFromCtx(ctx); r != nil {
for k, v := range r.Request.Header {
if len(v) > 0 {
headers[k] = v[0]
}
}
}
var r = make(map[string]bool)
if err = commonHttp.Get(ctx, "admin-go/api/v1/system/user/checkIsSuperAdmin", headers, &r); err != nil {
return false, err
}
return r["isSuperAdmin"], err
}
func (s *flowUserService) Create(ctx context.Context, req *flowDto.CreateFlowUserReq) (res *flowDto.CreateFlowUserRes, err error) {
admin, err := service.UtilService.IsAdmin(ctx)
admin, err := IsAdmin(ctx)
if err != nil {
return
}
@@ -41,7 +57,7 @@ func (s *flowUserService) Create(ctx context.Context, req *flowDto.CreateFlowUse
}
func (s *flowUserService) Update(ctx context.Context, req *flowDto.UpdateFlowUserReq) (err error) {
admin, err := service.UtilService.IsAdmin(ctx)
admin, err := IsAdmin(ctx)
if err != nil {
return
}
@@ -81,26 +97,6 @@ func (s *flowUserService) Update(ctx context.Context, req *flowDto.UpdateFlowUse
}
func ExtractFlowNodeFrom(flowContent *entity.FlowInfo) []*entity.FlowNode {
// 构建每个节点的上游节点映射
upstreamMap := make(map[string][]string)
for _, edge := range flowContent.Edges {
upstreamMap[edge.To] = append(upstreamMap[edge.To], edge.From)
}
// 同时更新 flowContent.Nodes 中的 DataMerge 节点
for i := range flowContent.Nodes {
n := &flowContent.Nodes[i]
// 对于 DataMerge 节点,自动根据边关系填充 InputSource
if n.NodeCode == node.NodeTypeDataMerge {
n.InputSource = nil
for _, fromId := range upstreamMap[n.Id] {
n.InputSource = append(n.InputSource, entity.FlowNodeInputSource{
NodeId: fromId,
})
}
}
}
var flowNodes []*entity.FlowNode
for _, item := range flowContent.Nodes {
flowNodes = append(flowNodes, &item)
@@ -109,7 +105,7 @@ func ExtractFlowNodeFrom(flowContent *entity.FlowInfo) []*entity.FlowNode {
}
func (s *flowUserService) Delete(ctx context.Context, req *flowDto.DeleteFlowUserReq) (err error) {
admin, err := service.UtilService.IsAdmin(ctx)
admin, err := IsAdmin(ctx)
if err != nil {
return
}
@@ -150,7 +146,7 @@ func (s *flowUserService) Get(ctx context.Context, req *flowDto.GetFlowUserReq)
}
func (s *flowUserService) List(ctx context.Context, req *flowDto.ListFlowUserReq) (res *flowDto.ListFlowRes, err error) {
admin, err := service.UtilService.IsAdmin(ctx)
admin, err := IsAdmin(ctx)
if err != nil {
return
}
+92 -443
View File
@@ -6,17 +6,13 @@ import (
"ai-agent/workflow/consts/public"
fileDao "ai-agent/workflow/dao/file"
flowDao "ai-agent/workflow/dao/flow"
nodeDao "ai-agent/workflow/dao/node"
"ai-agent/workflow/model/dto"
fileDto "ai-agent/workflow/model/dto/file"
flowDto "ai-agent/workflow/model/dto/flow"
nodeDto "ai-agent/workflow/model/dto/node"
"ai-agent/workflow/model/entity"
"context"
"fmt"
"strconv"
"strings"
"sync"
"time"
"gitea.redpowerfuture.com/red-future/common/db/gfdb"
@@ -31,35 +27,6 @@ func StartLambda(ctx context.Context, input any) (any, error) {
}
func FormLambda(ctx context.Context, input any) (any, error) {
nodeInput, ok := input.(*flowDto.NodeExecutionInput)
if !ok {
return nil, fmt.Errorf("入参类型错误")
}
if !g.IsEmpty(nodeInput.Config.FormConfig) {
for _, v := range nodeInput.Config.FormConfig {
if strings.Contains(v.Field, "视频时长") {
if g.IsEmpty(v.Value) {
return nil, fmt.Errorf("视频时长不能为空")
}
if gconv.Int(v.Value) >= 16 {
return nil, fmt.Errorf("视频时长超过15秒了")
}
if gconv.Int(v.Value) <= 3 {
return nil, fmt.Errorf("视频时长不能小于4秒")
}
}
if strings.Contains(v.Field, "视频分辨率") {
if gconv.String(v.Value) != "480p" && gconv.String(v.Value) != "720p" {
return nil, fmt.Errorf("视频分辨率不合法, 可选值: 480p, 720p")
}
}
if strings.Contains(v.Field, "宽高比例") {
if gconv.String(v.Value) != "21:9" && gconv.String(v.Value) != "1:1" && gconv.String(v.Value) != "16:9" && gconv.String(v.Value) != "4:3" && gconv.String(v.Value) != "9:16" && gconv.String(v.Value) != "3:4" {
return nil, fmt.Errorf("宽高比例不合法, 可选值: 21:9, 1:1, 16:9, 4:3, 9:16, 3:4")
}
}
}
}
return input, nil
}
@@ -76,23 +43,22 @@ func JudgeLambda(ctx context.Context, input any) (string, error) {
// 1. 直接用你原来的方法(返回两个 map)
inputMap, outputMap, modelMap := GetNodeContextContent(nodeInput.Global, nodeInput.Config)
var outputResult []node.NodeFormField
outputResult = append(outputResult, inputMap...)
outputResult = append(outputResult, outputMap...)
//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 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)
@@ -102,146 +68,53 @@ func JudgeLambda(ctx context.Context, input any) (string, error) {
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
}
composeResult, err := GetComposeResult(ctx, nodeInput.NodeExecutionId, 2, getIsChatModel.Model.ModelName, "", "", []map[string]any{{"prompt": strings.Join(branchIdNameLines, "\n")}}, []map[string]any{{"prompt": contextParts}}, nodeInput.Global.FileUrl, nodeInput.Global.SessionId, nodeInput.Config.Id, "判断节点")
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(composeResult.TaskId) {
if g.IsEmpty(msg.Messages) {
return "", fmt.Errorf("msg is empty")
}
content := ""
for key, _ := range getIsChatModel.Model.ResponseBody {
content = gconv.String(composeResult.Messages.Rounds[0][key])
for key, _ := range getIsChatModel.ResponseBody {
content = gconv.String(msg.Messages[key])
}
fmt.Printf("JudgeLambda路由:目标节点ID=%s\n", gconv.String(content))
return content, nil
}
func BatchModelLambda(ctx context.Context, input any) (any, error) {
nodeInput, ok := input.(*flowDto.NodeExecutionInput)
if !ok {
return nil, fmt.Errorf("入参类型错误")
}
skillName, from, userFrom := BuildParam(nodeInput)
reqMap := make([]map[string]any, 0)
for _, userItem := range userFrom {
m := gconv.Map(userItem)
for _, i := range nodeInput.Config.InputSource {
for _, f := range i.Field {
val := m[f]
if !g.IsEmpty(val) {
if g.NewVar(val).IsSlice() {
slice := gconv.SliceAny(val)
for _, item := range slice {
reqMap = append(reqMap, map[string]any{f: item})
}
} else {
reqMap = append(reqMap, map[string]any{f: val})
}
}
}
}
}
// 结果按索引存放,切片不同下标并发写无竞争,不用锁
res := make([][]node.NodeFormField, len(reqMap))
var wg sync.WaitGroup
// 只创建基础上下文,不再主动批量 cancel
subCtx := context.WithoutCancel(ctx)
// 缓冲1错误通道,仅接收第一个错误
errCh := make(chan error, 1)
// 并发执行任务
for idx, item := range reqMap {
wg.Add(1)
go func(idx int, userItem map[string]any) {
defer wg.Done()
// 基础上下文仅响应上游原始 ctx 取消,内部任务失败不触发这里
select {
case <-subCtx.Done():
return
default:
}
singleUserFrom := []map[string]any{userItem}
// 下游调用使用 subCtx,不会因为同批次其他任务报错而取消
output, err := TextNode(subCtx, nodeInput, skillName, from, singleUserFrom)
if err != nil {
// 只往错误通道塞第一个错误,不调用全局 cancel
select {
case errCh <- err:
default:
}
return
}
res[idx] = output
}(idx, item)
}
// 所有协程跑完再关闭通道
go func() {
wg.Wait()
close(errCh)
}()
// ========== 修复区域 start ==========
var execErr error
select {
case execErr = <-errCh:
// 捕获第一个业务错误,等待剩余协程收尾
wg.Wait()
case <-subCtx.Done():
// 上游根上下文被终止,读取已存在的错误
execErr = <-errCh
wg.Wait()
if execErr != nil {
execErr = fmt.Errorf("global context canceled: %w", execErr)
}
}
// 有错误直接返回,不再走结果拼接
if execErr != nil {
return nil, execErr
}
// 拼接输出结果
var globalIndex int
var outputRes []node.NodeFormField
for _, items := range res {
for _, item := range items {
oldField := item.Field
if idx := strings.LastIndex(oldField, ":"); idx != -1 {
item.Field = oldField[:idx+1] + fmt.Sprint(globalIndex)
}
oldLabel := item.Label
if idx := strings.LastIndex(oldLabel, ":"); idx != -1 {
item.Label = oldLabel[:idx+1] + fmt.Sprint(globalIndex)
}
outputRes = append(outputRes, item)
}
globalIndex++
}
nodeInput.Config.OutputResult = outputRes
return nodeInput, nil
}
// TextModelLambda 构建文案
func TextModelLambda(ctx context.Context, input any) (any, error) {
nodeInput, ok := input.(*flowDto.NodeExecutionInput)
@@ -249,7 +122,7 @@ func TextModelLambda(ctx context.Context, input any) (any, error) {
return nil, fmt.Errorf("入参类型错误")
}
skillName, from, userFrom := BuildParam(nodeInput)
outputRes, err := TextNode(ctx, nodeInput, skillName, from, userFrom)
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
}
@@ -264,7 +137,7 @@ func ImageModelLambda(ctx context.Context, input any) (any, error) {
return nil, fmt.Errorf("入参类型错误")
}
skillName, from, userFrom := BuildParam(nodeInput)
outputRes, err := ImgNode(ctx, nodeInput, skillName, from, userFrom)
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
}
@@ -272,235 +145,7 @@ func ImageModelLambda(ctx context.Context, input any) (any, error) {
return nodeInput, nil
}
// AudioModelLambda 构建音频
func AudioModelLambda(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 := AudioOptimizeNode(ctx, nodeInput, skillName, from, userFrom)
if err != nil {
return nil, err
}
nodeInput.Config.OutputResult = outputRes
return nodeInput, nil
}
// VideoModelLambda 构建视频
func VideoModelLambda(ctx context.Context, input any) (any, error) {
nodeInput, ok := input.(*flowDto.NodeExecutionInput)
if !ok {
return nil, fmt.Errorf("入参类型错误")
}
skillName, from, userFrom := BuildParam(nodeInput)
res, err := VideoOptimizeNode(ctx, nodeInput, skillName, from, userFrom)
if err != nil {
return nil, err
}
videoUrl := ""
videoURL := make([]string, 0)
for _, v := range res {
if strings.Contains(v.Field, "content") {
videoURL = append(videoURL, gconv.String(v.Value))
}
}
if g.IsEmpty(videoURL) {
return nil, fmt.Errorf("视频合成失败:模型生成视频失败")
}
if len(videoURL) > 1 {
var waitRes any
waitRes, err = VideoConcat(ctx, videoURL)
if err != nil {
return nil, err
}
msg := new(flowDto.VideoCallbackReq)
if err = gconv.Struct(waitRes, msg); err != nil {
return nil, err
}
var urlPrefix string
urlPrefix, err = utils.GetFileAddressPrefix(ctx)
newS := strings.ReplaceAll(urlPrefix, g.Cfg().MustGet(ctx, "filePrefix").String(), g.Cfg().MustGet(ctx, "minioPrefix").String())
if err != nil {
return nil, err
}
videoUrl = newS + msg.FileURL
} else {
var bytes []byte
bytes, err = GetFileBytesFromURL(ctx, videoURL[0])
if err != nil {
return nil, fmt.Errorf("下载图片失败: %w", err)
}
// 构造文件名
fileName := fmt.Sprintf("ai_video_%d%s", time.Now().UnixMilli(), GetUrlSuffix(videoURL[0], true))
// 上传到你的OSS(你项目已有的Upload方法)
var upResp *dto.UploadFileBytesRes
upResp, err = Upload(ctx, &dto.UploadFileBytesReq{
FileName: fileName,
FileBytes: bytes,
})
if err != nil {
return nil, fmt.Errorf("上传OSS失败: %w", err)
}
videoUrl = upResp.FileURL
}
outputRes := make([]node.NodeFormField, 0)
if nodeInput.Config.IsSaveFile {
outputRes = append(outputRes, node.NodeFormField{
Field: fmt.Sprintf("video_oss_url:content:%d", 0),
Value: videoUrl,
Label: fmt.Sprintf("video_oss_url:content:%d", 0),
Type: "string",
})
}
outputRes = append(outputRes, node.NodeFormField{
Field: fmt.Sprintf("concat_video_url:content:%d", 0),
Value: videoUrl,
Label: fmt.Sprintf("concat_video_url:content:%d", 0),
Type: "string",
})
nodeInput.Config.OutputResult = outputRes
return nodeInput, nil
}
// HttpLambda 构建HTTP(S)接口
func HttpLambda(ctx context.Context, input any) (any, error) {
nodeInput, ok := input.(*flowDto.NodeExecutionInput)
if !ok {
return nil, fmt.Errorf("入参类型错误")
}
outputRes := make([]node.NodeFormField, 0)
var err error
outputRes, err = HttpNode(ctx, nodeInput)
if err != nil {
return nil, err
}
nodeInput.Config.OutputResult = outputRes
return nodeInput, nil
}
// DataConversionLambda 构建数据转换
func DataConversionLambda(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 := DataConversionNode(ctx, nodeInput, skillName, from, userFrom)
if err != nil {
return nil, err
}
nodeInput.Config.OutputResult = outputRes
return nodeInput, nil
}
func DataMergeLambda(ctx context.Context, input any) (res any, err error) {
nodeInput, ok := input.(*flowDto.NodeExecutionInput)
if !ok {
return nil, fmt.Errorf("参数合并入参类型错误")
}
// var nodeIds []string
// for _, item := range nodeInput.Config.InputSource {
// nodeIds = append(nodeIds, item.NodeId)
// }
//
// // 检查是否所有输入节点都执行完成,并且检查是否有节点失败
// checkAllExecuted := func() (allExecuted bool, hasFailed bool, failedNode string) {
// executedCount := 0
// for _, executedNode := range nodeInput.Global.ExecutedNodes {
// // 检查是否是我们需要的输入节点,并且它失败了
// for _, targetId := range nodeIds {
// if executedNode.NodeId == targetId {
// if executedNode.Status == node.NodeExecutionStatusFailed.Code() {
// return false, true, targetId
// }
// executedCount++
// break
// }
// }
// }
// return executedCount == len(nodeIds), false, ""
// }
//
// // 初次检查
// allExecuted, hasFailed, failedNode := checkAllExecuted()
// if hasFailed {
// return nil, fmt.Errorf("输入节点[%s]执行失败", failedNode)
// }
//
// // 如果不是全部都已执行,阻塞等待直到全部完成、上下文取消或有节点失败
// if !allExecuted {
// // 轮询检查,每500ms检查一次,依赖ctx超时控制
// ticker := time.NewTicker(500 * time.Millisecond)
// defer ticker.Stop()
//
// for {
// select {
// case <-ctx.Done():
// // 如果上下文已经取消,说明已有节点报错,直接退出
// return nil, ctx.Err()
// case <-ticker.C:
// // 重新检查所有节点
// allExecuted, hasFailed, failedNode := checkAllExecuted()
// if hasFailed {
// // 有一个输入节点失败,直接退出
// return nil, fmt.Errorf("输入节点[%s]执行失败", failedNode)
// }
// if allExecuted {
// // 全部执行完成,退出循环继续执行
// goto allDone
// }
//
// // 再次检查上下文是否已经取消,如果已经取消则立即退出
// select {
// case <-ctx.Done():
// return nil, ctx.Err()
// default:
// }
// }
// }
// }
//allDone:
//
// // 最终检查:所有输入节点都成功了吗
// _, hasFailed, failedNode = checkAllExecuted()
// if hasFailed {
// // 有一个输入节点失败,直接退出
// return nil, fmt.Errorf("输入节点[%s]执行失败", failedNode)
// }
//
// // 构建已执行节点ID的map,方便合并时查找
// executedMap := make(map[string]*flowDto.ExecutedNode, len(nodeInput.Global.ExecutedNodes))
// for _, en := range nodeInput.Global.ExecutedNodes {
// executedMap[en.NodeId] = &en
// }
//
// // 合并所有输入源节点的输出结果
// for _, inputSource := range nodeInput.Config.InputSource {
// // 每次循环都检查上下文是否已取消,提前退出
// select {
// case <-ctx.Done():
// return nil, ctx.Err()
// default:
// }
// // 再次检查该节点是否失败
// if en, ok := executedMap[inputSource.NodeId]; ok && en.Status == node.NodeExecutionStatusFailed.Code() {
// return nil, fmt.Errorf("输入节点[%s]执行失败", inputSource.NodeId)
// }
// sourceNodeConfig := nodeInput.Global.ConfigMap[inputSource.NodeId]
// if sourceNodeConfig != nil && len(sourceNodeConfig.OutputResult) > 0 {
// nodeInput.Config.OutputResult = append(nodeInput.Config.OutputResult, sourceNodeConfig.OutputResult...)
// }
// }
return nodeInput, nil
}
func MergeLambda(ctx context.Context, input any) (res any, err error) {
func MergeLambda(ctx context.Context, input any) (any, error) {
nodeInput, ok := input.(*flowDto.NodeExecutionInput)
if !ok {
return nil, fmt.Errorf("汇总节点入参类型错误")
@@ -509,20 +154,16 @@ func MergeLambda(ctx context.Context, input any) (res any, err error) {
// 1. 把所有节点输出拍平成 字段名->内容 的map
dataMap := make(map[string]node.NodeFormField)
_, outputMap, _ := GetNodeContextContent(nodeInput.Global, nodeInput.Config)
//for _, valueAny := range outputMap {
// field := node.NodeFormField{}
// if field, ok = valueAny.(node.NodeFormField); ok {
// dataMap[field.Field] = field
// }
//}
for _, field := range outputMap {
dataMap[field.Field] = field
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_content:%d", i)
key := fmt.Sprintf("text_url:%d", i)
val, has := dataMap[key]
if !has || val.Value == "" {
break
@@ -538,7 +179,7 @@ func MergeLambda(ctx context.Context, input any) (res any, err error) {
if !has || val.Value == "" {
break
}
images = append(images, gconv.String(val.Value))
images = append(images, val.Value)
}
// 4. 🔥 核心算法:图片按顺序连续归属给每条文案
@@ -591,8 +232,8 @@ func MergeLambda(ctx context.Context, input any) (res any, err error) {
if len(contents) > 0 {
for i, val := range contents {
item := Item{
Content: url + gconv.String(val.Value), // 文案
Images: textImgMap[i], // 自动绑定该条目的图片(没有则为空切片)
Content: url + val.Value, // 文案
Images: textImgMap[i], // 自动绑定该条目的图片(没有则为空切片)
}
allItems = append(allItems, item)
}
@@ -613,8 +254,24 @@ func MergeLambda(ctx context.Context, input any) (res any, err error) {
// 遍历所有【独立图文条目】 → 每条生成独立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),
@@ -622,26 +279,25 @@ func MergeLambda(ctx context.Context, input any) (res any, err error) {
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",
},
)
if nodeInput.Config.IsSaveFile {
// 上传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
}
outputRecords = append(outputRecords,
node.NodeFormField{
Field: fmt.Sprintf("item_html_url_%d", idx),
Value: ossResult.FileURL,
Label: fmt.Sprintf("条目%d 地址", idx+1),
Type: "text",
},
)
}
}
// 最终输出多条记录
@@ -657,16 +313,15 @@ func SummaryLambda(ctx context.Context, input any) (any, error) {
// 聚合所有已执行节点的输出结果
var summaryResult []map[string]interface{}
for _, executedNode := range execInput.Global.ExecutedNodes {
nodeID := executedNode.NodeId
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, "http_file_url") || strings.Contains(field.Field, "audio_oss_url") || strings.Contains(field.Field, "video_oss_url") || strings.Contains(field.Field, "item_html_url") || strings.Contains(field.Field, "img_oss_url") || strings.Contains(field.Field, "text_url") {
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] = ProcessPath(ctx, gconv.String(field.Value))
item[timeKey] = field.Value
summaryResult = append(summaryResult, item)
}
}
@@ -684,28 +339,10 @@ func SummaryLambda(ctx context.Context, input any) (any, error) {
return err
}
res, _, err := nodeDao.NodeExecutionDao.ListByFlowExecutionId(ctx, &nodeDto.ListNodeExecutionByFlowReq{
NodeGroupId: execInput.Global.NodeGroupId,
}, entity.NodeExecutionCol.TokenInfo)
if err != nil {
return err
}
var totalTokens int
var totalFee float64
for _, item := range res {
for _, itemToken := range item.TokenInfo {
m := gconv.Map(itemToken)
totalTokens += gconv.Int(m["total_tokens"])
totalFee += gconv.Float64(m["total_fee"])
}
}
executionReq := flowDto.UpdateFlowExecutionReq{
Id: execInput.Global.ExecutionId,
Status: flow.FlowExecutionStatusSuccess.Code(),
OutputParams: summaryResult,
TotalTokens: totalTokens,
TotalFee: totalFee,
}
_, err = flowDao.FlowExecutionDao.Update(ctx, &executionReq)
@@ -739,6 +376,18 @@ func SummaryLambda(ctx context.Context, input any) (any, error) {
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)
File diff suppressed because it is too large Load Diff
+86 -646
View File
@@ -1,78 +1,24 @@
package flow
import (
"ai-agent/workflow/consts/node"
nodeDao "ai-agent/workflow/dao/node"
"ai-agent/workflow/model/dto"
flowDto "ai-agent/workflow/model/dto/flow"
nodeDto "ai-agent/workflow/model/dto/node"
"ai-agent/workflow/model/entity"
"bytes"
"context"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
commonHttp "gitea.redpowerfuture.com/red-future/common/http"
"gitea.redpowerfuture.com/red-future/common/utils"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/util/gconv"
"github.com/tidwall/sjson"
)
// 全局等待任务回调的工具
var (
asyncMu sync.Mutex
asyncTasks = make(map[string]chan any)
)
// Wait 阻塞等待回调结果
// 调用后会一直卡住,直到 Notify 唤醒 或 超时/取消
func Wait(ctx context.Context, taskId string) (any, error) {
asyncMu.Lock()
ch := make(chan any, 1)
asyncTasks[taskId] = ch
asyncMu.Unlock()
defer close(ch)
for {
select {
case result := <-ch:
return result, nil
case <-ctx.Done():
asyncMu.Lock()
delete(asyncTasks, taskId)
asyncMu.Unlock()
return nil, ctx.Err()
}
}
}
// Notify 回调时调用,唤醒等待的任务
func Notify(taskId string, result any) {
asyncMu.Lock()
defer asyncMu.Unlock()
ch, exist := asyncTasks[taskId]
if !exist {
return
}
ch <- result
delete(asyncTasks, taskId)
}
func GetIsChatModel(ctx context.Context) (res *flowDto.GetIsChatModelRes, err error) {
headers := make(map[string]string)
if r := g.RequestFromCtx(ctx); r != nil {
@@ -87,7 +33,7 @@ func GetIsChatModel(ctx context.Context) (res *flowDto.GetIsChatModelRes, err er
return
}
func GetModelInfo(ctx context.Context, req *flowDto.GetModelInfoReq) (res *flowDto.GetModelInfoRes, err error) {
func ComposeMessages(ctx context.Context, req *flowDto.ComposeMessagesReq) (res *flowDto.ComposeMessagesRes, err error) {
headers := make(map[string]string)
if r := g.RequestFromCtx(ctx); r != nil {
for k, v := range r.Request.Header {
@@ -96,507 +42,58 @@ func GetModelInfo(ctx context.Context, req *flowDto.GetModelInfoReq) (res *flowD
}
}
}
res = new(flowDto.GetModelInfoRes)
err = commonHttp.Get(ctx, "model-gateway/model/getModel", headers, res, req)
res = new(flowDto.ComposeMessagesRes)
err = commonHttp.Post(ctx, "prompts-core/prompt/composeMessages", headers, res, &req)
return
}
func GetComposeResult(ctx context.Context, nodeExecutionId int64, buildType int, modelName, promptContent, skillName string, form []map[string]any, userForm []map[string]any, fileUrl []string, sessionId, nodeId string, cause string) (res *flowDto.ComposeCallbackReq, err error) {
var callbackUrl = utils.GetCallbackURL(ctx, "/flow/execution/composeCallBack")
var consult = make([]flowDto.Consult, 0)
var collectFileUrls func(val any) (fullyConsumed bool)
collectFileUrls = func(val any) (fullyConsumed bool) {
switch {
case g.NewVar(val).IsSlice():
slice := gconv.SliceAny(val)
allConsumed := false
for _, item := range slice {
if collectFileUrls(item) {
allConsumed = true
}
}
return allConsumed
case g.NewVar(val).IsMap():
m := gconv.Map(val)
allConsumed := false
for _, item := range m {
if collectFileUrls(item) {
allConsumed = true
}
}
return allConsumed
default:
s := gconv.String(val)
if s != "" {
getFileTypeByPath := GetFileTypeByPath(s)
if getFileTypeByPath != "" {
consult = append(consult, flowDto.Consult{
Type: getFileTypeByPath,
Url: s,
})
return true
}
}
return false
}
}
var newUserForm []map[string]any
for _, m := range userForm {
// 先替换字段
if val, ok := m["audioDuration"]; ok {
delete(m, "audioDuration")
m["视频总时长"] = val
}
if val, ok := m["videoDuration"]; ok {
delete(m, "videoDuration")
m["视频总时长"] = val
}
// 收集待删除 key
var delKeys []string
for k, v := range m {
if collectFileUrls(v) {
delKeys = append(delKeys, k)
}
}
// 统一删除
for _, k := range delKeys {
delete(m, k)
}
if len(m) > 0 {
newUserForm = append(newUserForm, m)
}
}
for _, v := range fileUrl {
getFileTypeByPath := GetFileTypeByPath(gconv.String(v))
if getFileTypeByPath != "" {
consult = append(consult, flowDto.Consult{
Type: getFileTypeByPath,
Url: gconv.String(v),
})
}
}
func GetModelResult(ctx context.Context, modelName, skillName string, form, userFrom map[string]any, fileUrl []string, sessionId string, cause string) (mapTaskResult map[string]any, err error) {
msgReq := flowDto.ComposeMessagesReq{
BuildType: buildType,
ModelName: modelName,
SkillName: skillName,
CallbackUrl: callbackUrl,
Cause: cause,
Form: form,
UserForm: newUserForm,
UserPrompt: promptContent,
Consult: consult,
SessionId: sessionId,
NodeId: nodeId,
BuildType: 1,
ModelName: modelName,
SkillName: skillName,
Cause: cause,
Form: form,
UserForm: userFrom,
UserFiles: fileUrl,
SessionId: sessionId,
}
msgRes := new(flowDto.ComposeMessagesRes)
// 1. 隔离上游取消(防止节点执行被中断时下游请求被 cancel)+ 设置独立超时
baseCtx := context.WithoutCancel(ctx)
postCtx, cancel := context.WithTimeout(baseCtx, 30*time.Minute)
defer cancel() // 必须释放,防止上下文泄露
// 2. 克隆 commonHttp 客户端(保留 Consul 服务发现),显式设置超时和 ResponseHeaderTimeout
client := commonHttp.Httpclient.Clone()
client.SetTimeout(30 * time.Minute)
if tr, ok := client.Transport.(*http.Transport); ok {
tr.ResponseHeaderTimeout = 30 * time.Minute
}
if r := g.RequestFromCtx(ctx); r != nil {
for k, v := range r.Request.Header {
if len(v) > 0 {
client.SetHeader(k, v[0])
}
}
}
resp, err := client.ContentJson().Post(postCtx, "prompts-core/prompt/composeMessages", &msgReq)
msg, err := ComposeMessages(ctx, &msgReq)
if err != nil {
return
}
defer resp.Close()
result, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("读取composeMessages响应失败: %w", err)
}
// 统一处理内部API响应格式:{code:200,message:"",data:{...}}
resultStrut := &ghttp.DefaultHandlerResponse{}
if err = gconv.Struct(result, &resultStrut); err != nil { // 修复:增加err检查
return nil, fmt.Errorf("响应解析失败: " + err.Error())
}
// 添加调试日志:打印解析后的结构
g.Log().Debugf(ctx, "[HTTP] 解析后结构: Code=%d, Message=%s, Data类型=%T, Data值=%+v",
resultStrut.Code, resultStrut.Message, resultStrut.Data, resultStrut.Data)
if resultStrut.Code == 200 || resultStrut.Code == 0 {
if err = gconv.Struct(resultStrut.Data, &msgRes); err != nil { // 修复:增加err检查
return nil, fmt.Errorf("数据解析失败: " + err.Error())
}
// 添加调试日志:打印最终的target
g.Log().Debugf(ctx, "[HTTP] 最终target: %+v", &msgRes)
} else {
err = errors.New(resultStrut.Message)
}
if g.IsEmpty(msgRes.TaskId) {
if g.IsEmpty(msg.Messages) {
return nil, fmt.Errorf("msg is empty")
}
waitRes, err := Wait(ctx, msgRes.TaskId)
if err != nil {
return nil, err
}
msg := new(flowDto.ComposeCallbackReq)
if err = gconv.Struct(waitRes, msg); err != nil {
return nil, err
}
updateTokenCount(ctx, nodeExecutionId, msg.BillingData)
if !g.IsEmpty(msg.ErrorMsg) {
return nil, fmt.Errorf(msg.ErrorMsg)
}
return msg, nil
}
func CreateGatewayTask(ctx context.Context, nodeExecutionId int64, epicycleId int64, model string, content map[string]any) (map[string]any, error) {
taskId, err := createGatewayTaskOnly(ctx, epicycleId, model, content)
if err != nil {
return nil, err
}
return waitGatewayResult(ctx, nodeExecutionId, taskId)
}
// createGatewayTaskOnly creates a gateway task and returns the taskId only
// doesn't wait for completion
func createGatewayTaskOnly(ctx context.Context, epicycleId int64, model string, content map[string]any) (string, error) {
callbackUrl := utils.GetCallbackURL(ctx, "/flow/execution/modelCallback")
req := flowDto.ModelGatewayReq{
ModelName: model,
BizName: g.Cfg().MustGet(ctx, "server.name").String(),
CallbackUrl: callbackUrl,
RequestPayload: content,
EpicycleId: epicycleId,
}
res := new(flowDto.ModelGatewayRes)
// 1. 隔离上游取消(防止节点执行被中断时下游请求被 cancel)+ 设置独立超时
baseCtx := context.WithoutCancel(ctx)
postCtx, cancel := context.WithTimeout(baseCtx, 30*time.Minute)
defer cancel() // 必须释放,防止上下文泄露
// 2. 克隆 commonHttp 客户端(保留 Consul 服务发现),显式设置超时和 ResponseHeaderTimeout
client := commonHttp.Httpclient.Clone()
client.SetTimeout(30 * time.Minute)
if tr, ok := client.Transport.(*http.Transport); ok {
tr.ResponseHeaderTimeout = 30 * time.Minute
}
if r := g.RequestFromCtx(ctx); r != nil {
for k, v := range r.Request.Header {
if len(v) > 0 {
client.SetHeader(k, v[0])
}
}
}
rpcResp, err := client.ContentJson().Post(postCtx, "model-gateway/task/createTask", &req)
if err != nil {
return "", err
}
defer rpcResp.Close()
result, err := io.ReadAll(rpcResp.Body)
if err != nil {
return "", fmt.Errorf("读取createTask响应失败: %w", err)
}
// 统一处理内部API响应格式:{code:200,message:"",data:{...}}
resultStrut := &ghttp.DefaultHandlerResponse{}
if err = gconv.Struct(result, &resultStrut); err != nil { // 修复:增加err检查
return "", fmt.Errorf("响应解析失败: " + err.Error())
}
// 添加调试日志:打印解析后的结构
g.Log().Debugf(ctx, "[HTTP] 解析后结构: Code=%d, Message=%s, Data类型=%T, Data值=%+v",
resultStrut.Code, resultStrut.Message, resultStrut.Data, resultStrut.Data)
if resultStrut.Code == 200 || resultStrut.Code == 0 {
if err = gconv.Struct(resultStrut.Data, &res); err != nil { // 修复:增加err检查
return "", fmt.Errorf("数据解析失败: " + err.Error())
}
// 添加调试日志:打印最终的target
g.Log().Debugf(ctx, "[HTTP] 最终target: %+v", &res)
} else {
err = errors.New(resultStrut.Message)
}
if g.IsEmpty(res.TaskId) {
return "", fmt.Errorf("创建模型任务失败,taskId为空")
}
return res.TaskId, nil
}
// waitGatewayResult waits for a created gateway task to complete and returns the result
func waitGatewayResult(ctx context.Context, nodeExecutionId int64, taskId string) (map[string]any, error) {
waitRes, err := Wait(ctx, taskId)
if err != nil {
return nil, err
}
task := new(flowDto.ModelCallbackReq)
if err = gconv.Struct(waitRes, task); err != nil {
return nil, err
}
updateTokenCount(ctx, nodeExecutionId, task.BillingData)
if task.State == 3 || !g.IsEmpty(task.ErrorMsg) {
return nil, fmt.Errorf("模型执行失败:%s", task.ErrorMsg)
}
if g.IsEmpty(task.OssFile) {
return nil, fmt.Errorf("模型返回结果为空")
}
// 获取远程文件内容
file, err := GetFileBytesFromURL(ctx, task.OssFile)
if err != nil {
return nil, err
}
return gconv.Map(file), nil
}
// updateTokenCount updates the token count in node execution
func updateTokenCount(ctx context.Context, nodeExecutionId int64, tokenInfo []map[string]any) {
res, err := nodeDao.NodeExecutionDao.Get(ctx, &nodeDto.GetNodeExecutionReq{
Id: nodeExecutionId,
}, entity.NodeExecutionCol.TokenInfo)
var taskResult any
taskResult, err = GatewayTask(ctx, msg.EpicycleId, modelName, msg.Messages)
if err != nil {
return
}
var t []map[string]any
for _, item := range res.TokenInfo {
t = append(t, item)
}
for _, item := range tokenInfo {
t = append(t, item)
}
_, _ = nodeDao.NodeExecutionDao.Update(ctx, &nodeDto.UpdateNodeExecutionReq{
Id: nodeExecutionId,
TokenInfo: t,
})
}
func GetModelResult(ctx context.Context, sessionId string, nodeInput *flowDto.NodeExecutionInput, skillName string, form []map[string]any, userForm []map[string]any) (mapTaskResult []map[string]any, err error) {
buildType := 1
if nodeInput.Config.NodeCode == node.NodeTypeDataConversionModel {
buildType = 3
}
if !nodeInput.Global.IsDialogue {
sessionId = ""
}
needSequential := false
for _, item := range userForm {
if g.NewVar(item).IsMap() {
valMap := gconv.Map(item)
for _, v := range valMap {
if g.NewVar(v).IsMap() {
vv := gconv.Map(v)
for kk, vvv := range vv {
if kk == "return_last_frame" {
needSequential = vvv.(bool)
}
}
}
}
}
}
composeResult, err := GetComposeResult(ctx, nodeInput.NodeExecutionId, buildType, nodeInput.Config.ModelConfig.ModelName, nodeInput.Config.PromptContent, skillName, form, userForm, nodeInput.Global.FileUrl, sessionId, nodeInput.Config.Id, nodeInput.Config.Name)
var getTaskResult *flowDto.TaskCallback
getTaskResult, err = GetTaskResult(ctx, taskResult)
if err != nil {
return nil, err
}
if composeResult.Status != "success" {
return nil, fmt.Errorf("模型提示词构建错误")
}
modelInfo, err := GetModelInfo(ctx, &flowDto.GetModelInfoReq{ModelName: nodeInput.Config.ModelConfig.ModelName})
if err != nil {
return nil, err
}
mapTaskResult = make([]map[string]any, len(composeResult.Messages.Rounds))
var taskResultMap map[string]any
if buildType == 1 {
if needSequential {
for idx, item := range composeResult.Messages.Rounds {
if !g.IsEmpty(taskResultMap) {
var set string
set, err = sjson.Set(gconv.String(item), modelInfo.Model.FirstFrame, gconv.String(taskResultMap["content"]))
if err != nil {
return nil, err
}
item = gconv.Map(set)
}
var taskResult map[string]any
taskResult, err = CreateGatewayTask(ctx, nodeInput.NodeExecutionId, composeResult.EpicycleId, nodeInput.Config.ModelConfig.ModelName, item)
if err != nil {
return nil, err
}
if g.IsEmpty(taskResult) {
return nil, fmt.Errorf("模型返回结果为空")
}
if nodeInput.Config.NodeCode == node.NodeTypeVideoModel {
ext := GetFileTypeByPath(gconv.String(taskResult["content"]))
if ext == "image" {
taskResultMap = taskResult
} else {
taskResultMap = make(map[string]any)
}
} else {
taskResultMap = make(map[string]any)
}
mapTaskResult[idx] = taskResult
//updateTokenCount(ctx, nodeInput.NodeExecutionId, modelInfo.Model.ResponseTokenField, taskResult)
}
} else {
// 全局共享子上下文,实现一处报错全部终止
subCtx, globalCancel := context.WithCancel(ctx)
defer globalCancel() // 函数退出兜底释放
var wg sync.WaitGroup
errChan := make(chan error, len(composeResult.Messages.Rounds))
// 加互斥锁保护结果map
var mu sync.Mutex
// 每个任务创建后立即启动等待协程:把「回调 vs Wait 注册」的竞争窗口从整个创建循环
// 压缩到微秒级,避免创建期间完成的回调被 Notify 静默丢弃导致 Wait 永久阻塞
for idx, item := range composeResult.Messages.Rounds {
taskId, err := createGatewayTaskOnly(ctx, composeResult.EpicycleId, nodeInput.Config.ModelConfig.ModelName, item)
if err != nil {
globalCancel() // 取消已启动的等待协程,避免泄漏
return nil, err
}
wg.Add(1)
go func(idx int, taskId string) {
defer wg.Done()
taskResult, err := waitGatewayResult(subCtx, nodeInput.NodeExecutionId, taskId)
if err != nil {
errChan <- err
globalCancel() // 全局取消,所有协程收到ctx取消信号快速退出
return
}
// 加锁写入map,解决并发竞态
mu.Lock()
mapTaskResult[idx] = taskResult
mu.Unlock()
//updateTokenCount(ctx, nodeInput.NodeExecutionId, modelInfo.Model.ResponseTokenField, taskResult)
}(idx, taskId)
}
wg.Wait()
close(errChan)
// 收集全部错误,而非只读一条
var errs []error
for len(errChan) > 0 {
errs = append(errs, <-errChan)
}
if len(errs) > 0 {
// 返回第一个错误;如需汇总所有错误可拼接
return nil, errs[0]
}
}
} else {
for idx, item := range composeResult.Messages.Rounds {
mapTaskResult[idx] = item
//updateTokenCount(ctx, nodeInput.NodeExecutionId, modelInfo.Model.ResponseTokenField, item)
}
return
}
mapTaskResult = gconv.Map(getTaskResult.Text)
return mapTaskResult, nil
}
func BuildNestedJson(body g.Map, global *flowDto.FlowExecutionInput) g.Map {
jsonStr := "{}"
for originKey, originItem := range body {
if originKey == "templates" && !g.IsEmpty(global.Templates) {
jsonStr, _ = sjson.Set(jsonStr, originKey, global.Templates)
continue
}
bodyItemMap := gconv.Map(originItem)
val := bodyItemMap["value"]
if v, ok := bodyItemMap["value"]; ok {
jsonStr, _ = sjson.Set(jsonStr, originKey, v)
}
// 判断 value 是不是引用结构(map)
if g.NewVar(val).IsMap() {
valMap := gconv.Map(val)
nodeId := gconv.String(valMap["nodeId"])
fieldName := gconv.String(valMap["field"])
if configValue, ok := global.ConfigMap[nodeId]; ok {
if !g.IsEmpty(configValue.OutputResult) {
for _, v := range configValue.OutputResult {
if strings.Contains(v.Field, fieldName) {
if configValue.NodeCode == node.NodeTypeDataConversionModel {
switch {
case g.NewVar(v.Value).IsSlice() || g.NewVar(v.Value).IsMap():
// 核心:自动判断两种结构,精准赋值
vm := gconv.Map(v.Value)
// 先判断是否是 单个key包裹的对象(如 {"subtitle_style": {...}}
if len(vm) == 1 {
// 遍历取出唯一的 key 和 真实值
for innerKey, innerVal := range vm {
// 直接用 innerKeysubtitle_style)赋值
jsonStr, _ = sjson.Set(jsonStr, innerKey, innerVal)
}
} else {
// 直接是对象,用 originKey 赋值
jsonStr, _ = sjson.Set(jsonStr, originKey, v.Value)
}
default:
jsonStr, _ = sjson.Set(jsonStr, originKey, v.Value)
}
} else {
jsonStr, _ = sjson.Set(jsonStr, originKey, v.Value)
}
}
}
}
if !g.IsEmpty(configValue.FormConfig) {
for _, v := range configValue.FormConfig {
if v.Field == fieldName {
if v.Type == "uploadMultiple" {
if g.NewVar(v.FieldConstraint).IsMap() {
mapFieldConstraint := gconv.Map(v.FieldConstraint)
for key, value := range mapFieldConstraint {
if key == "maxFileCount" {
if gconv.Int(value) == 1 {
// 如果是单文件上传,则替换成字符串重新赋值给v.Value
if g.NewVar(v.Value).IsSlice() {
sliceVal := gconv.SliceAny(v.Value)
if len(sliceVal) > 0 {
v.Value = sliceVal[0]
}
}
}
}
}
}
}
jsonStr, _ = sjson.Set(jsonStr, originKey, v.Value)
}
}
}
}
}
func GatewayTask(ctx context.Context, epicycleId int64, model string, content map[string]any) (any, error) {
modelTaskId, err := CreateGatewayTask(ctx, &flowDto.CreateTaskReq{
ModelName: model,
BizName: g.Cfg().MustGet(ctx, "server.name").String(),
CallbackUrl: "/flow/execution/modelCallback",
RequestPayload: content,
EpicycleId: epicycleId,
})
if err != nil {
return nil, err
}
return gconv.Map(jsonStr)
return Wait(ctx, modelTaskId)
}
func VideoConcat(ctx context.Context, videoUrls []string) (r any, err error) {
var httpUrl = "media/video/concat/async"
func CreateGatewayTask(ctx context.Context, req *flowDto.CreateTaskReq) (string, error) {
headers := make(map[string]string)
if r := g.RequestFromCtx(ctx); r != nil {
for k, v := range r.Request.Header {
@@ -605,42 +102,69 @@ func VideoConcat(ctx context.Context, videoUrls []string) (r any, err error) {
}
}
}
var callbackUrl = utils.GetCallbackURL(ctx, "/flow/execution/videoCallback")
var newBody = flowDto.VideoConcatReq{
VideoUrls: videoUrls,
Method: "auto",
Upload: true,
CallbackUrl: callbackUrl,
res := new(flowDto.CreateTaskRes)
err := commonHttp.Post(ctx, "model-gateway/task/createTask", headers, res, &req)
if err != nil {
return "", err
}
res := new(flowDto.VideoConcatRes)
err = commonHttp.Post(ctx, httpUrl, headers, &res, newBody)
return res.TaskId, nil
}
func GetTaskResult(ctx context.Context, result any) (*flowDto.TaskCallback, error) {
task := new(flowDto.TaskCallback)
if err := gconv.Struct(result, task); err != nil {
return nil, err
}
url, err := utils.GetFileAddressPrefix(ctx)
if err != nil {
return nil, err
}
return Wait(ctx, res.TaskId)
// 获取远程文件内容
file, err := FetchRemoteJsonFile(ctx, url+task.OssFile)
if err != nil {
return nil, err
}
task.Text = gconv.String(file)
return task, nil
}
func GetFileBytesFromURL(ctx context.Context, fileUrl string) ([]byte, error) {
newS := strings.ReplaceAll(fileUrl, g.Cfg().MustGet(ctx, "filePrefix").String(), g.Cfg().MustGet(ctx, "minioPrefix").String())
// 使用 GoFrame 客户端(自带超时、追踪、日志等能力)
resp, err := g.Client().Get(ctx, newS)
func FetchRemoteJsonFile(ctx context.Context, fileUrl string) ([]byte, error) {
// 1. 下载文件
resp, err := g.Client().Get(ctx, fileUrl)
if err != nil {
return nil, gerror.Wrapf(err, "failed to request url: %s", newS)
return nil, fmt.Errorf("get file failed: %w", err)
}
defer resp.Close()
// 校验状态码
if resp.StatusCode != http.StatusOK {
return nil, gerror.Newf("request failed with status code: %d, url: %s", resp.StatusCode, newS)
return nil, fmt.Errorf("http status error: %d", resp.StatusCode)
}
// 读取全部内容
allBytes, err := io.ReadAll(resp.Body)
return io.ReadAll(resp.Body)
}
func GetFileBytesFromURL(url string) (all []byte, err error) {
resp, err := http.Get(url)
if err != nil {
return nil, gerror.Wrapf(err, "failed to read response body, url: %s", fileUrl)
fmt.Printf("请求失败 %s: %v", url, err)
return
}
return allBytes, nil
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
fmt.Printf("请求失败,状态码: %d\n", resp.StatusCode)
return
}
all, err = io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("读取内容失败 %s: %v", url, err)
return
}
return
}
func Upload(ctx context.Context, req *dto.UploadFileBytesReq) (*dto.UploadFileBytesRes, error) {
@@ -668,8 +192,8 @@ func Upload(ctx context.Context, req *dto.UploadFileBytesReq) (*dto.UploadFileBy
// 发起上传请求
res := &dto.UploadFileBytesRes{}
httpUrl := "oss/file/uploadFile"
if err = commonHttp.Post(ctx, httpUrl, headers, res, body.Bytes()); err != nil {
url := "oss/file/uploadFile"
if err = commonHttp.Post(ctx, url, headers, res, body.Bytes()); err != nil {
return nil, err
}
@@ -677,90 +201,6 @@ func Upload(ctx context.Context, req *dto.UploadFileBytesReq) (*dto.UploadFileBy
return res, nil
}
func GetFileTypeByPath(filePath string) string {
if filePath == "" {
return ""
}
// 解析 URL,获取真实路径(兼容 http 链接)
u, err := url.Parse(filePath)
if err == nil {
filePath = u.Path
}
// 获取后缀(小写)
ext := filepath.Ext(filePath)
ext = strings.ToLower(ext)
// 判断类型
switch ext {
case ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp":
return "image"
case ".mp4", ".mov", ".avi", ".flv", ".wmv", ".mkv":
return "video"
case ".mp3", ".wav", ".m4a", ".flac", ".aac", ".ogg":
return "audio"
case ".txt", ".md", ".log", ".json", ".xml", ".inc":
return "text"
case ".html":
return "html"
case ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx":
return "document"
default:
return ""
}
}
// GetUrlSuffix 获取URL文件后缀
// rawUrl: 原始链接
// withDot: true 返回 .mp4 false 返回 mp4
func GetUrlSuffix(rawUrl string, withDot bool) string {
// 解析URL,剥离查询参数
u, err := url.Parse(rawUrl)
if err != nil {
return ""
}
// 提取路径部分
filePath := u.Path
// 获取文件名
fileName := path.Base(filePath)
if fileName == "" || !strings.Contains(fileName, ".") {
return ""
}
// 截取后缀
suffix := path.Ext(fileName)
if !withDot {
suffix = strings.TrimPrefix(suffix, ".")
}
return suffix
}
// ProcessPath 处理请求路径
// 1. 判断是否为合法完整请求路径(以/开头)
// 2. 包含 tenantId-1 则截断其及前面所有内容
func ProcessPath(ctx context.Context, path string) string {
// 判断是否是完整请求路径:以 / 开头
if strings.HasPrefix(path, "/") {
return path
}
target, err := utils.GetBucketName(ctx)
if err != nil {
return path
}
idx := strings.Index(path, target)
if idx == -1 {
// 不包含目标字符串,原样返回
return path
}
// 截取 tenantId-1 后面的内容
newPath := path[idx+len(target):]
return newPath
}
func BuildText(text string) string {
// 生成单条HTML
var htmlBuilder strings.Builder
@@ -914,7 +354,7 @@ func BuildHtml(text string, images []string) string {
border-radius: 12px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.06);
}
</style>
</head>
<body>
@@ -1017,8 +457,8 @@ func SplitMultiContents(htmlContent string) []string {
func GetAllImgSrcFromHtml(html string) []string {
var imgSrcList []string
re := regexp.MustCompile(`<img[^>]*src\s*=\s*["']([^"']+)["']`)
submatch := re.FindAllStringSubmatch(html, -1)
for _, match := range submatch {
matchs := re.FindAllStringSubmatch(html, -1)
for _, match := range matchs {
if len(match) >= 2 {
imgSrcList = append(imgSrcList, match[1])
}
@@ -1028,7 +468,7 @@ func GetAllImgSrcFromHtml(html string) []string {
// ReplaceImgSrc 替换img src的方法
func ReplaceImgSrc(html string, oldSrc string, newSrc string) string {
// 精准替换:找到 <img xxx src="oldSrc" xxx>
// 精准替换:找到 <img xxx src="oldSrc" xxx> 并替换
re := regexp.MustCompile(`(<img[^>]*src\s*=\s*["'])` + regexp.QuoteMeta(oldSrc) + `(["'])`)
return re.ReplaceAllString(html, `${1}`+newSrc+`${2}`)
}
+36 -289
View File
@@ -7,7 +7,6 @@ import (
"fmt"
"gitea.redpowerfuture.com/red-future/common/beans"
commonHttp "gitea.redpowerfuture.com/red-future/common/http"
"github.com/gogf/gf/v2/encoding/gjson"
"github.com/gogf/gf/v2/frame/g"
)
@@ -16,123 +15,35 @@ var NodeLibraryService = &nodeLibraryService{}
type nodeLibraryService struct{}
func GetModelType(ctx context.Context) (mainTypeMap map[int]string, err error) {
headers := make(map[string]string)
if r := g.RequestFromCtx(ctx); r != nil {
for k, v := range r.Request.Header {
if len(v) > 0 {
headers[k] = v[0]
}
}
}
res := new(nodeDto.ModelTypeResponse)
err = commonHttp.Get(ctx, "model-gateway/model/listType", headers, res, nil)
// 通用过滤:只保留 能被 100 整除的主类型(100/200/300...
mainTypeMap = make(map[int]string)
for typ, name := range res.Type {
if typ%100 == 0 {
mainTypeMap[typ] = name
}
}
return
}
func (s *nodeLibraryService) GetNodeLibrary(ctx context.Context, req *nodeDto.WorkflowNodeTreeReq) (*nodeDto.WorkflowNodeTreeRes, error) {
WorkflowNodeGroups := []node.NodeGroupItem{
{
Group: node.NodeGroupComponent,
Label: node.NodeGroupNameComponent,
Items: []node.NodeItem{
{
NodeCode: node.NodeTypeTextModel,
NodeName: node.NodeNameTextModel,
ModelType: node.ModelTypeText,
SkillOption: false,
PromptOption: true,
IsSaveFile: true,
FormConfig: []node.NodeFormField{},
ModelConfig: []node.ModelItem{},
NodeCode: node.NodeTypeTextModel,
NodeName: node.NodeNameTextModel,
ModelType: node.ModelTypeText,
SkillOption: true,
FormConfig: []node.NodeFormField{}, // 技能下拉
ModelConfig: []node.ModelItem{},
},
{
NodeCode: node.NodeTypeImageModel,
NodeName: node.NodeNameImageModel,
ModelType: node.ModelTypeImage,
SkillOption: false,
PromptOption: true,
IsSaveFile: true,
FormConfig: []node.NodeFormField{},
ModelConfig: []node.ModelItem{},
NodeCode: node.NodeTypeImageModel,
NodeName: node.NodeNameImageModel,
ModelType: node.ModelTypeImage,
SkillOption: true,
FormConfig: []node.NodeFormField{}, // 技能下拉
ModelConfig: []node.ModelItem{},
},
{
NodeCode: node.NodeTypeVideoModel,
NodeName: node.NodeNameVideoModel,
ModelType: node.ModelTypeVideo,
PatchLayout: true,
SkillOption: false,
PromptOption: true,
IsSaveFile: true,
FormConfig: []node.NodeFormField{},
ModelConfig: []node.ModelItem{},
},
{
NodeCode: node.NodeTypeAudioModel,
NodeName: node.NodeNameAudioModel,
ModelType: node.ModelTypeAudio,
SkillOption: false,
PromptOption: true,
IsSaveFile: true,
FormConfig: []node.NodeFormField{},
ModelConfig: []node.ModelItem{},
},
{
NodeCode: node.NodeTypeBatchModel,
NodeName: node.NodeNameBatchModel,
ModelType: node.ModelTypeText,
SkillOption: false,
PromptOption: true,
IsSaveFile: true,
FormConfig: []node.NodeFormField{},
ModelConfig: []node.ModelItem{},
},
//{
// NodeCode: node.NodeTypeSenseOptimizeModel,
// NodeName: node.NodeNameSenseOptimizeModel,
// ModelType: node.ModelTypeText,
// SkillOption: false,
// FormConfig: []node.NodeFormField{},
// ModelConfig: []node.ModelItem{},
//},
//{
// NodeCode: node.NodeTypeStoryOptimizeModel,
// NodeName: node.NodeNameStoryOptimizeModel,
// ModelType: node.ModelTypeText,
// SkillOption: false,
// FormConfig: []node.NodeFormField{},
// ModelConfig: []node.ModelItem{},
//},
//{
// NodeCode: node.NodeTypeScriptOptimizeModel,
// NodeName: node.NodeNameScriptOptimizeModel,
// ModelType: node.ModelTypeText,
// SkillOption: false,
// FormConfig: []node.NodeFormField{},
// ModelConfig: []node.ModelItem{},
//},
},
},
{
Group: node.NodeGroupBase,
Label: node.NodeGroupNameBase,
Items: []node.NodeItem{
{
NodeCode: node.NodeTypeDataConversionModel,
NodeName: node.NodeNameDataConversionModel,
ModelType: node.ModelTypeText,
SkillOption: false,
PromptOption: true,
FormConfig: []node.NodeFormField{},
ModelConfig: []node.ModelItem{},
},
{
NodeCode: node.NodeTypeMerge,
NodeName: node.NodeNameMerge,
@@ -140,13 +51,6 @@ func (s *nodeLibraryService) GetNodeLibrary(ctx context.Context, req *nodeDto.Wo
FormConfig: []node.NodeFormField{},
ModelConfig: []node.ModelItem{},
},
{
NodeCode: node.NodeTypeDataMerge,
NodeName: node.NodeNameDataMerge,
SkillOption: false,
FormConfig: []node.NodeFormField{},
ModelConfig: []node.ModelItem{},
},
{
NodeCode: node.NodeTypeJudge,
NodeName: node.NodeNameJudge,
@@ -163,161 +67,6 @@ func (s *nodeLibraryService) GetNodeLibrary(ctx context.Context, req *nodeDto.Wo
FormConfig: []node.NodeFormField{},
ModelConfig: []node.ModelItem{},
},
{
NodeCode: node.NodeTypeHttp,
NodeName: node.NodeNameHttp,
SkillOption: false,
IsSaveFile: true,
FormConfig: []node.NodeFormField{
{
Field: "method",
Label: "请求方式",
Type: "select",
Required: true,
Options: []node.SelectOption{
{Label: "GET", Value: "GET"},
{Label: "POST", Value: "POST"},
{Label: "PUT", Value: "PUT"},
{Label: "DELETE", Value: "DELETE"},
},
},
{
Field: "url",
Label: "请求地址",
Type: "input",
Required: true,
},
{
Field: "headers",
Label: "请求头(支持Authorization鉴权)",
Type: "keyValue",
Required: false,
},
{
Field: "bodyType",
Label: "请求体类型",
Type: "select",
Required: true,
Options: []node.SelectOption{
{Label: "无", Value: "None"},
{Label: "JSON", Value: "JSON"},
//{Label: "表单", Value: "FormUrlEncoded"},
//{Label: "文件上传", Value: "FormData"},
//{Label: "原生文本", Value: "Raw"},
},
},
{
Field: "body",
Label: "请求体内容",
Type: "keyValue",
Required: false,
},
{
Field: "response",
Label: "结果返回结构",
Type: "keyValue",
Required: false,
},
{
Field: "responseType",
Label: "结果返回方式",
Type: "select",
Required: true,
Options: []node.SelectOption{
{Label: "同步返回", Value: "sync"},
{Label: "等候回调", Value: "callback"},
{Label: "主动拉取", Value: "pull"},
},
Expand: []node.NodeFormField{
{
Field: "method",
Label: "请求方式",
Type: "select",
Required: true,
Options: []node.SelectOption{
{Label: "GET", Value: "GET"},
{Label: "POST", Value: "POST"},
{Label: "PUT", Value: "PUT"},
{Label: "DELETE", Value: "DELETE"},
},
},
{
Field: "url",
Label: "请求地址",
Type: "input",
Required: true,
},
{
Field: "headers",
Label: "请求头(支持Authorization鉴权)",
Type: "keyValue",
Required: false,
},
{
Field: "bodyType",
Label: "请求体类型",
Type: "select",
Required: true,
Options: []node.SelectOption{
{Label: "无", Value: "None"},
{Label: "JSON", Value: "JSON"},
//{Label: "表单", Value: "FormUrlEncoded"},
//{Label: "文件上传", Value: "FormData"},
//{Label: "原生文本", Value: "Raw"},
},
},
{
Field: "body",
Label: "请求体内容",
Type: "keyValue",
Required: false,
},
{
Field: "response",
Label: "结果返回结构",
Type: "keyValue",
Required: false,
},
{
Field: "timeout",
Label: "超时时间(秒)",
Type: "inputNumber",
Required: false,
Default: 30,
},
{
Field: "insecureSkipVerify",
Label: "跳过HTTPS证书校验",
Type: "switch",
Required: false,
Default: false,
},
},
},
{
Field: "callbackUrl",
Label: "回调地址(只需要填写字段名称)",
Type: "input",
Required: false,
Default: "",
},
{
Field: "timeout",
Label: "超时时间(秒)",
Type: "inputNumber",
Required: false,
Default: 30,
},
{
Field: "insecureSkipVerify",
Label: "跳过HTTPS证书校验",
Type: "switch",
Required: false,
Default: false,
},
},
ModelConfig: []node.ModelItem{},
},
//{
// NodeCode: node.NodeTypeModel,
// NodeName: node.NodeNameModel,
@@ -327,22 +76,22 @@ func (s *nodeLibraryService) GetNodeLibrary(ctx context.Context, req *nodeDto.Wo
//},
},
},
//{
// Group: node.NodeGroupCustom,
// Label: node.NodeGroupNameCustom,
// Items: []node.NodeItem{
// {
// NodeCode: node.NodeTypeCustomNode,
// NodeName: node.NodeNameCustomNode,
// SkillOption: true,
// FormConfig: []node.NodeFormField{
// {Field: "nodeName", Label: node.FormLabelApiKey, Type: "input", Required: true},
// {Field: "nodeType", Label: node.FormLabelModel, Type: "input", Required: true},
// },
// ModelConfig: []node.ModelItem{},
// },
// },
//},
{
Group: node.NodeGroupCustom,
Label: node.NodeGroupNameCustom,
Items: []node.NodeItem{
{
NodeCode: node.NodeTypeCustomNode,
NodeName: node.NodeNameCustomNode,
SkillOption: true,
FormConfig: []node.NodeFormField{
{Field: "nodeName", Label: node.FormLabelApiKey, Type: "input", Required: true},
{Field: "nodeType", Label: node.FormLabelModel, Type: "input", Required: true},
},
ModelConfig: []node.ModelItem{},
},
},
},
}
tree := &nodeDto.WorkflowNodeTreeRes{
Groups: WorkflowNodeGroups,
@@ -355,19 +104,17 @@ func (s *nodeLibraryService) GetNodeLibrary(ctx context.Context, req *nodeDto.Wo
// 遍历分组下的每个节点
for itemIdx := range group.Items {
item := &group.Items[itemIdx]
if item.NodeCode == node.NodeTypeTextModel ||
item.NodeCode == node.NodeTypeImageModel ||
item.NodeCode == node.NodeTypeVideoModel ||
item.NodeCode == node.NodeTypeAudioModel ||
item.NodeCode == node.NodeTypeBatchModel ||
item.NodeCode == node.NodeTypeDataConversionModel ||
item.NodeCode == node.NodeTypeSenseOptimizeModel ||
item.NodeCode == node.NodeTypeStoryOptimizeModel ||
item.NodeCode == node.NodeTypeScriptOptimizeModel {
if item.NodeCode == node.NodeTypeTextModel {
item.ModelConfig = append(item.ModelConfig, node.ModelItem{
ModelName: "自定义",
})
}
if item.NodeCode == node.NodeTypeImageModel {
item.ModelConfig = append(item.ModelConfig, node.ModelItem{
ModelName: "自定义",
})
}
}
}
@@ -1,123 +0,0 @@
package node
import (
"ai-agent/workflow/consts/node"
nodeDao "ai-agent/workflow/dao/node"
nodeDto "ai-agent/workflow/model/dto/node"
"ai-agent/workflow/service"
"context"
"gitea.redpowerfuture.com/red-future/common/utils"
"github.com/gogf/gf/v2/frame/g"
)
var NodePromptService = &nodePromptService{}
type nodePromptService struct{}
// Create 创建节点提示词
func (s *nodePromptService) Create(ctx context.Context, req *nodeDto.CreateNodePromptReq) (res *nodeDto.CreateNodePromptRes, err error) {
user, err := utils.GetUserInfo(ctx)
if err != nil {
return nil, err
}
get, err := nodeDao.NodePromptDao.Get(ctx, &nodeDto.GetNodePromptReq{Prompt: req.Prompt, Creator: user.UserName})
if err != nil {
return
}
if g.IsEmpty(get) {
var isAdmin bool
isAdmin, err = service.UtilService.IsAdmin(ctx)
if err != nil {
return
}
if isAdmin {
req.SourceType = node.SourceTypeSystem.Code()
} else {
req.SourceType = node.SourceTypeUser.Code()
}
var id int64
id, err = nodeDao.NodePromptDao.Insert(ctx, req)
if err != nil {
return
}
return &nodeDto.CreateNodePromptRes{Id: id}, err
}
return
}
// Update 更新节点提示词
func (s *nodePromptService) Update(ctx context.Context, req *nodeDto.UpdateNodePromptReq) (err error) {
get, err := nodeDao.NodePromptDao.Get(ctx, &nodeDto.GetNodePromptReq{Id: req.Id})
if err != nil {
return
}
isAdmin, err := service.UtilService.IsAdmin(ctx)
if err != nil {
return
}
if !isAdmin && get.SourceType == node.SourceTypeSystem.Code() {
_, err = s.Create(ctx, &nodeDto.CreateNodePromptReq{
NodeType: req.NodeType,
Prompt: req.Prompt,
})
} else {
_, err = nodeDao.NodePromptDao.Update(ctx, req)
}
return
}
// Delete 删除节点提示词
func (s *nodePromptService) Delete(ctx context.Context, req *nodeDto.DeleteNodePromptReq) (err error) {
_, err = nodeDao.NodePromptDao.Delete(ctx, req)
return
}
// GetById 根据ID查询节点提示词
func (s *nodePromptService) GetById(ctx context.Context, req *nodeDto.GetNodePromptReq) (res *nodeDto.NodePromptResp, err error) {
r, err := nodeDao.NodePromptDao.Get(ctx, req)
if err != nil {
return nil, err
}
res = &nodeDto.NodePromptResp{
NodePrompt: r,
}
return
}
// ListMy 查询当前创建人自己创建的提示词列表
func (s *nodePromptService) ListMy(ctx context.Context, req *nodeDto.ListMyNodePromptReq) (*nodeDto.ListNodePromptResp, error) {
user, err := utils.GetUserInfo(ctx)
if err != nil {
return nil, err
}
req.Creator = user.UserName
list, total, err := nodeDao.NodePromptDao.ListByOnlyCreator(ctx, req)
if err != nil {
return nil, err
}
return &nodeDto.ListNodePromptResp{
List: list,
Total: total,
}, nil
}
// ListWithSystem 查询当前创建人+系统的提示词列表
func (s *nodePromptService) ListWithSystem(ctx context.Context, req *nodeDto.ListNodePromptReq) (*nodeDto.ListNodePromptResp, error) {
user, err := utils.GetUserInfo(ctx)
if err != nil {
return nil, err
}
// 如果请求中没有传creator,使用当前用户
if g.IsEmpty(req.Creator) {
req.Creator = user.UserName
}
list, total, err := nodeDao.NodePromptDao.ListByCreator(ctx, req)
if err != nil {
return nil, err
}
return &nodeDto.ListNodePromptResp{
List: list,
Total: total,
}, nil
}
+24 -7
View File
@@ -4,13 +4,13 @@ import (
skillDao "ai-agent/workflow/dao/skill"
skillDto "ai-agent/workflow/model/dto/skill"
"ai-agent/workflow/model/entity"
"ai-agent/workflow/service"
"context"
"fmt"
"path/filepath"
"strings"
"gitea.redpowerfuture.com/red-future/common/beans"
commonHttp "gitea.redpowerfuture.com/red-future/common/http"
"gitea.redpowerfuture.com/red-future/common/utils"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/util/gconv"
@@ -20,12 +20,29 @@ var SkillUserService = &skillUserService{}
type skillUserService struct{}
// IsAdmin 调用admin-go服务检查是否是管理员
func IsAdmin(ctx context.Context) (res bool, err error) {
headers := make(map[string]string)
if r := g.RequestFromCtx(ctx); r != nil {
for k, v := range r.Request.Header {
if len(v) > 0 {
headers[k] = v[0]
}
}
}
var r = make(map[string]bool)
if err = commonHttp.Get(ctx, "admin-go/api/v1/system/user/checkIsSuperAdmin", headers, &r); err != nil {
return false, err
}
return r["isSuperAdmin"], err
}
func (s *skillUserService) Create(ctx context.Context, req *skillDto.CreateSkillUserReq) (res *skillDto.CreateSkillUserRes, err error) {
ext := strings.TrimPrefix(filepath.Ext(req.FileUrl), ".")
if ext != "zip" {
return nil, fmt.Errorf("文件格式不支持,请上传zip格式文件")
}
admin, err := service.UtilService.IsAdmin(ctx)
admin, err := IsAdmin(ctx)
if err != nil {
return
}
@@ -74,7 +91,7 @@ func (s *skillUserService) Update(ctx context.Context, req *skillDto.UpdateSkill
if ext != "zip" {
return fmt.Errorf("文件格式不支持,请上传zip格式文件")
}
admin, err := service.UtilService.IsAdmin(ctx)
admin, err := IsAdmin(ctx)
if err != nil {
return
}
@@ -121,7 +138,7 @@ func (s *skillUserService) Update(ctx context.Context, req *skillDto.UpdateSkill
}
func (s *skillUserService) Delete(ctx context.Context, req *skillDto.DeleteSkillUserReq) (err error) {
admin, err := service.UtilService.IsAdmin(ctx)
admin, err := IsAdmin(ctx)
if err != nil {
return
}
@@ -136,7 +153,7 @@ func (s *skillUserService) Delete(ctx context.Context, req *skillDto.DeleteSkill
}
func (s *skillUserService) Get(ctx context.Context, req *skillDto.GetSkillUserReq) (res *skillDto.SkillUserVO, err error) {
admin, err := service.UtilService.IsAdmin(ctx)
admin, err := IsAdmin(ctx)
if err != nil {
return
}
@@ -179,7 +196,7 @@ func (s *skillUserService) Get(ctx context.Context, req *skillDto.GetSkillUserRe
}
func (s *skillUserService) List(ctx context.Context, req *skillDto.ListSkillReq) (res *skillDto.ListSkillUserRes, err error) {
admin, err := service.UtilService.IsAdmin(ctx)
admin, err := IsAdmin(ctx)
if err != nil {
return
}
@@ -263,7 +280,7 @@ func (s *skillUserService) GetUserOrTemplate(ctx context.Context, req *skillDto.
return
}
req.Creator = user.UserName
userList := new(entity.SkillUser)
var userList *entity.SkillUser
userList, err = skillDao.SkillUserDao.Get(ctx, &skillDto.GetSkillUserReq{
Id: req.Id,
Creator: user.UserName,
-29
View File
@@ -1,29 +0,0 @@
package service
import (
"context"
commonHttp "gitea.redpowerfuture.com/red-future/common/http"
"github.com/gogf/gf/v2/frame/g"
)
var UtilService = &utilService{}
type utilService struct{}
// IsAdmin 调用admin-go服务检查是否是管理员
func (s *utilService) IsAdmin(ctx context.Context) (res bool, err error) {
headers := make(map[string]string)
if r := g.RequestFromCtx(ctx); r != nil {
for k, v := range r.Request.Header {
if len(v) > 0 {
headers[k] = v[0]
}
}
}
var r = make(map[string]bool)
if err = commonHttp.Get(ctx, "admin-go/api/v1/system/user/checkIsSuperAdmin", headers, &r); err != nil {
return false, err
}
return r["isSuperAdmin"], err
}