refactor: 后端仓库层收口(A1:课程/产品/素材)+ 收进工作区既有对象化重构
本提交含两部分。第一部分是本轮工作;第二部分是此前一直留在工作区、
从未提交的对象化重构,与第一部分在文件上互相咬合(internal/repository
整个包都是未跟踪状态,且 api 层已有文件引用它),无法拆成两个可编译的提交。
一、仓库层收口 A1 批(本轮工作)
把 api 层手写的 store.DB 查询收进具名仓库方法,只给真正获益的对象做方法,
不机械包裹全量。本批迁移 22 处裸查询(courses.go 9 / media.go 12 / products.go 1),
新增方法:
- MediaFileRepo.ListByBind / ListForAudit / MarkExtracted
- KnowledgeChunkRepo.CountByMediaFile
- ProductRepo.GetVisibleByID
两条业务口径改由仓库单点持有,避免各处手写漂移:
「只有 approved 素材出现在课程详情」与「已停用产品不在课程详情露出」。
修掉两个真实缺陷:
- ProductRepo.GetByID 缺 Where 条件。此前 GET /api/products/{id} 对任意 id 都返回
第一条产品、对不存在的 id 返回 200,且 PUT /api/products/{id} 会覆盖第一条产品
—— 数据损坏级。全仓扫描确认这是唯一一处同型写法。
- ProductRepo.Delete 写 status="deleted",而 DELETE 处理器文档与回包都声称
"inactive",接口在说谎;管理员用 status=all 拉列表会看到前端不认识的状态。
已对齐为 inactive(与 CourseRepo.Delete 一致)。
删除 8 个零调用且列名不存在的死方法(一调即 SQL 报错):
- media_file 上的 file_path / file_type / approval_status 三列并不存在,
GetByPath / ListByType / UpdateStatus 全废
- knowledge_chunk 上的 space_id 列不存在(模型早已改为 knowledge_space_key),
List / Total / ListBySpaceIDs / DeleteBySpace / SearchByVector 全废
取舍边界:能对当前 schema 跑通的死方法保留,跑不通的删或修。
CourseRepo.List 补齐 status=all 档(此前传给它会当作 status='all' 过滤出空列表)。
该方法此前零调用,现与产品列表语义对齐。
验证:go build ./... 与 go test ./... 全绿;另用真实 HTTP 请求验证 34 项
(课程 17 / 产品 3 / 素材 14),跑在数据库副本与独立 KB_DATA_DIR 上,
含 multipart 真上传 → 审批 → pdftotext 提取 → 分片入库的完整链路。
二、此前未提交的对象化重构(非本轮工作)
- 新增 internal/repository 仓库层、connectors、skills、specialists、xapps、jsonutil,
model/task_record|task_run|task_artifact、api/task_runtime|action_definition|chat_message
- 删除 api/app_definition、connectors、my_app_center、notification、office_skill、
export_docx|pptx|xlsx、official_account_* 等,随 XApp/Skill/Specialist/Connector
可插拔打包方向(AR10/AR11)调整
- 资产目录归位:backend-go/knowledge_source → assets/knowledge/source、
training_materials → assets/training/materials;README 内相对路径同步加深两级;
deploy env 补 ASSET_ROOT_DIR 并改 KNOWLEDGE_SOURCE_DIR / TRAINING_MATERIALS_DIR
- 前端新增 skills/ specialists/ connectors/ xapps/ 目录与对应页面
验证:前端 npm run build 通过(7.26s)。
Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,122 @@
|
||||
package skillapi
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
skillmodel "eai_agentplatform/backend/internal/skills/model"
|
||||
"eai_agentplatform/backend/internal/store"
|
||||
"eai_agentplatform/backend/internal/web"
|
||||
)
|
||||
|
||||
func CreateSkillDefinition(c *gin.Context) {
|
||||
var req definitionReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
web.Fail(c, web.NewBadRequest("请求参数错误"))
|
||||
return
|
||||
}
|
||||
if appErr := validateDefinitionReq(&req); appErr != nil {
|
||||
web.Fail(c, appErr)
|
||||
return
|
||||
}
|
||||
|
||||
item := skillmodel.SkillDefinition{
|
||||
Key: req.Key,
|
||||
Label: req.Label,
|
||||
Description: req.Description,
|
||||
ObjectKind: req.ObjectKind,
|
||||
Source: req.Source,
|
||||
ObjectEntryRoute: req.ObjectEntryRoute,
|
||||
ExposedToUser: req.ExposedToUser,
|
||||
StarterPromptsJSON: req.StarterPromptsJSON,
|
||||
PromptTemplate: req.PromptTemplate,
|
||||
InputSchemaJSON: req.InputSchemaJSON,
|
||||
OutputSchemaJSON: req.OutputSchemaJSON,
|
||||
ArtifactSchemaJSON: req.ArtifactSchemaJSON,
|
||||
ActionRefsJSON: req.ActionRefsJSON,
|
||||
PolicyRefsJSON: req.PolicyRefsJSON,
|
||||
OntologyBindingJSON: req.OntologyBindingJSON,
|
||||
State: req.State,
|
||||
SortOrder: req.SortOrder,
|
||||
}
|
||||
if err := store.DB.Create(&item).Error; err != nil {
|
||||
web.Fail(c, web.NewBadRequest("创建技能定义失败"))
|
||||
return
|
||||
}
|
||||
web.OK(c, item)
|
||||
}
|
||||
|
||||
func UpdateSkillDefinition(c *gin.Context) {
|
||||
id, ok := parseID(c, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var item skillmodel.SkillDefinition
|
||||
if err := store.DB.First(&item, id).Error; err != nil {
|
||||
web.Fail(c, web.NewNotFoundError("技能定义不存在"))
|
||||
return
|
||||
}
|
||||
|
||||
var req definitionReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
web.Fail(c, web.NewBadRequest("请求参数错误"))
|
||||
return
|
||||
}
|
||||
if appErr := validateDefinitionReq(&req); appErr != nil {
|
||||
web.Fail(c, appErr)
|
||||
return
|
||||
}
|
||||
|
||||
item.Key = req.Key
|
||||
item.Label = req.Label
|
||||
item.Description = req.Description
|
||||
item.ObjectKind = req.ObjectKind
|
||||
item.Source = req.Source
|
||||
item.ObjectEntryRoute = req.ObjectEntryRoute
|
||||
item.ExposedToUser = req.ExposedToUser
|
||||
item.StarterPromptsJSON = req.StarterPromptsJSON
|
||||
item.PromptTemplate = req.PromptTemplate
|
||||
item.InputSchemaJSON = req.InputSchemaJSON
|
||||
item.OutputSchemaJSON = req.OutputSchemaJSON
|
||||
item.ArtifactSchemaJSON = req.ArtifactSchemaJSON
|
||||
item.ActionRefsJSON = req.ActionRefsJSON
|
||||
item.PolicyRefsJSON = req.PolicyRefsJSON
|
||||
item.OntologyBindingJSON = req.OntologyBindingJSON
|
||||
item.State = req.State
|
||||
item.SortOrder = req.SortOrder
|
||||
|
||||
if err := store.DB.Save(&item).Error; err != nil {
|
||||
web.Fail(c, web.NewBadRequest("更新技能定义失败"))
|
||||
return
|
||||
}
|
||||
web.OK(c, item)
|
||||
}
|
||||
|
||||
func DeleteSkillDefinition(c *gin.Context) {
|
||||
id, ok := parseID(c, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var item skillmodel.SkillDefinition
|
||||
if err := store.DB.First(&item, id).Error; err != nil {
|
||||
web.Fail(c, web.NewNotFoundError("技能定义不存在"))
|
||||
return
|
||||
}
|
||||
if err := store.DB.Delete(&item).Error; err != nil {
|
||||
web.Fail(c, web.NewBadRequest("删除技能定义失败"))
|
||||
return
|
||||
}
|
||||
web.OK(c, gin.H{"id": id, "deleted": true})
|
||||
}
|
||||
|
||||
func parseID(c *gin.Context, name string) (uint, bool) {
|
||||
id, err := strconv.ParseUint(c.Param(name), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
web.Fail(c, web.NewBadRequest("无效的 "+name))
|
||||
return 0, false
|
||||
}
|
||||
return uint(id), true
|
||||
}
|
||||
@@ -0,0 +1,471 @@
|
||||
package skillapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
skilloffice "eai_agentplatform/backend/internal/skills/runtime/office"
|
||||
officecontracts "eai_agentplatform/backend/internal/skills/runtime/office/contracts"
|
||||
specialistruntime "eai_agentplatform/backend/internal/specialists/runtime"
|
||||
|
||||
"eai_agentplatform/backend/internal/middleware"
|
||||
"eai_agentplatform/backend/internal/model"
|
||||
"eai_agentplatform/backend/internal/store"
|
||||
"eai_agentplatform/backend/internal/web"
|
||||
)
|
||||
|
||||
type officeSkillExecuteReq struct {
|
||||
TaskID uint `json:"task_id"`
|
||||
SkillKey string `json:"skill_key"`
|
||||
InputText string `json:"input_text"`
|
||||
Mode string `json:"mode"`
|
||||
}
|
||||
|
||||
type paddleOCRPayload struct {
|
||||
Text string `json:"text"`
|
||||
Lines []map[string]any `json:"lines"`
|
||||
Engine string `json:"engine"`
|
||||
Error string `json:"error"`
|
||||
Raw map[string]any `json:"-"`
|
||||
}
|
||||
|
||||
func ExecuteOfficeSkill(c *gin.Context) {
|
||||
user := middleware.CurrentUser(c)
|
||||
if user == nil {
|
||||
web.Fail(c, web.NewAuthError("未登录"))
|
||||
return
|
||||
}
|
||||
|
||||
var req officeSkillExecuteReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
web.Fail(c, web.NewBadRequest("请求参数错误"))
|
||||
return
|
||||
}
|
||||
req.SkillKey = strings.TrimSpace(req.SkillKey)
|
||||
req.InputText = strings.TrimSpace(req.InputText)
|
||||
if req.TaskID == 0 || req.SkillKey == "" || req.InputText == "" {
|
||||
web.Fail(c, web.NewBadRequest("task_id、skill_key、input_text 为必填"))
|
||||
return
|
||||
}
|
||||
|
||||
task, ok := loadMyOwnedTask(c, user, req.TaskID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
definition, ok := skilloffice.BuiltinRegistry().ByKey(req.SkillKey)
|
||||
if !ok {
|
||||
web.Fail(c, web.NewNotFoundError("技能不存在"))
|
||||
return
|
||||
}
|
||||
|
||||
result := skilloffice.BuildOfficeSkillResultMap(definition, req.InputText)
|
||||
run, createdArtifacts, err := persistOfficeExecution(task, definition, req.InputText, result)
|
||||
if err != nil {
|
||||
web.Fail(c, web.NewBadRequest(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
freshTask, _ := reloadTask(task.ID)
|
||||
web.OK(c, gin.H{
|
||||
"result": result,
|
||||
"task": freshTask,
|
||||
"run": run,
|
||||
"artifacts": createdArtifacts,
|
||||
})
|
||||
}
|
||||
|
||||
func ExecuteOfficeSkillOCR(c *gin.Context) {
|
||||
user := middleware.CurrentUser(c)
|
||||
if user == nil {
|
||||
web.Fail(c, web.NewAuthError("未登录"))
|
||||
return
|
||||
}
|
||||
|
||||
taskID, ok := parseUintFromForm(c.PostForm("task_id"))
|
||||
if !ok || taskID == 0 {
|
||||
web.Fail(c, web.NewBadRequest("task_id 必填"))
|
||||
return
|
||||
}
|
||||
prompt := strings.TrimSpace(c.PostForm("prompt"))
|
||||
|
||||
task, taskOK := loadMyOwnedTask(c, user, taskID)
|
||||
if !taskOK {
|
||||
return
|
||||
}
|
||||
|
||||
file, err := c.FormFile("file")
|
||||
if err != nil {
|
||||
web.Fail(c, web.NewBadRequest("请上传图片文件"))
|
||||
return
|
||||
}
|
||||
if !looksLikeImage(file.Filename) {
|
||||
web.Fail(c, web.NewBadRequest("目前仅支持上传图片进行 OCR 识别"))
|
||||
return
|
||||
}
|
||||
|
||||
src, err := file.Open()
|
||||
if err != nil {
|
||||
web.Fail(c, web.NewBadRequest("读取上传文件失败"))
|
||||
return
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
tempFile, err := os.CreateTemp("", "office-ocr-*"+strings.ToLower(filepath.Ext(file.Filename)))
|
||||
if err != nil {
|
||||
web.Fail(c, web.NewBadRequest("创建临时文件失败"))
|
||||
return
|
||||
}
|
||||
defer os.Remove(tempFile.Name())
|
||||
defer tempFile.Close()
|
||||
|
||||
if _, err := io.Copy(tempFile, src); err != nil {
|
||||
web.Fail(c, web.NewBadRequest("保存上传文件失败"))
|
||||
return
|
||||
}
|
||||
|
||||
ocrPayload, err := runPaddleOCR(tempFile.Name())
|
||||
if err != nil {
|
||||
web.Fail(c, web.NewBadRequest(err.Error()))
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(ocrPayload.Text) == "" {
|
||||
web.Fail(c, web.NewBadRequest("没有识别到可用文字,请换一张更清晰的图片"))
|
||||
return
|
||||
}
|
||||
|
||||
uploadItem := gin.H{
|
||||
"title": file.Filename,
|
||||
"detail": "这张图片已作为 OCR 输入材料保留在任务里。",
|
||||
"file_format": strings.TrimPrefix(strings.ToLower(filepath.Ext(file.Filename)), "."),
|
||||
"file_size": file.Size,
|
||||
}
|
||||
artifactPayload := gin.H{
|
||||
"engine": firstNonEmpty(ocrPayload.Engine, "paddleocr"),
|
||||
"prompt": prompt,
|
||||
"text": ocrPayload.Text,
|
||||
"lines": ocrPayload.Lines,
|
||||
"upload_item": uploadItem,
|
||||
}
|
||||
artifactPayloadJSON, _ := json.Marshal(artifactPayload)
|
||||
sourceRefsJSON, _ := json.Marshal([]gin.H{
|
||||
{
|
||||
"type": "upload",
|
||||
"title": file.Filename,
|
||||
"size": file.Size,
|
||||
},
|
||||
})
|
||||
now := time.Now()
|
||||
inputJSON, _ := json.Marshal(gin.H{
|
||||
"prompt": prompt,
|
||||
"file_name": file.Filename,
|
||||
"file_size": file.Size,
|
||||
})
|
||||
outputJSON, _ := json.Marshal(gin.H{
|
||||
"summary": fmt.Sprintf("已识别图片《%s》中的文本,并整理为可复制的 OCR 结果。", file.Filename),
|
||||
"text": ocrPayload.Text,
|
||||
"lines": ocrPayload.Lines,
|
||||
})
|
||||
logsJSON, _ := json.Marshal([]string{
|
||||
fmt.Sprintf("接收上传文件:%s", file.Filename),
|
||||
fmt.Sprintf("OCR 引擎:%s", firstNonEmpty(ocrPayload.Engine, "paddleocr")),
|
||||
"已生成 OCR 识别结果",
|
||||
})
|
||||
|
||||
var run model.TaskRun
|
||||
var artifact model.TaskArtifact
|
||||
err = store.DB.Transaction(func(tx *gorm.DB) error {
|
||||
run = model.TaskRun{
|
||||
TaskID: task.ID,
|
||||
SpecialistKey: task.SpecialistKey,
|
||||
ActionKey: "ocr-understanding",
|
||||
ActionTitle: "OCR / 图文理解",
|
||||
ActionType: "ocr",
|
||||
Status: "done",
|
||||
InputJSON: string(inputJSON),
|
||||
OutputJSON: string(outputJSON),
|
||||
LogsJSON: string(logsJSON),
|
||||
StartedAt: now,
|
||||
FinishedAt: &now,
|
||||
}
|
||||
if err := tx.Create(&run).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
artifact = model.TaskArtifact{
|
||||
TaskID: task.ID,
|
||||
SpecialistKey: task.SpecialistKey,
|
||||
Title: fmt.Sprintf("%s - OCR 识别结果", task.Title),
|
||||
ArtifactType: "ocr_text",
|
||||
Status: specialistruntime.ArtifactStatusDraft,
|
||||
ContentText: ocrPayload.Text,
|
||||
ContentJSON: string(artifactPayloadJSON),
|
||||
SourceRefsJSON: string(sourceRefsJSON),
|
||||
CreatedByRunID: &run.ID,
|
||||
}
|
||||
if err := tx.Create(&artifact).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
contextJSON := specialistruntime.ParseTaskContextJSON(task.ContextJSON)
|
||||
contextJSON["uploaded_items"] = appendUploadItem(contextJSON["uploaded_items"], uploadItem)
|
||||
task.ContextJSON = mustMarshalJSON(contextJSON)
|
||||
task.CurrentRunID = &run.ID
|
||||
task.CurrentResult = fmt.Sprintf("已识别图片《%s》中的文本。", file.Filename)
|
||||
task.Status = specialistruntime.TaskStatusDraft
|
||||
task.LastTriggeredAt = &now
|
||||
return tx.Save(&task).Error
|
||||
})
|
||||
if err != nil {
|
||||
web.Fail(c, web.NewBadRequest("保存 OCR 结果失败"))
|
||||
return
|
||||
}
|
||||
|
||||
freshTask, _ := reloadTask(task.ID)
|
||||
web.OK(c, gin.H{
|
||||
"text": ocrPayload.Text,
|
||||
"lines": ocrPayload.Lines,
|
||||
"engine": firstNonEmpty(ocrPayload.Engine, "paddleocr"),
|
||||
"artifact": artifact,
|
||||
"task": freshTask,
|
||||
"upload_item": uploadItem,
|
||||
})
|
||||
}
|
||||
|
||||
func persistOfficeExecution(task model.TaskRecord, definition officecontracts.Runtime, inputText string, result gin.H) (model.TaskRun, []model.TaskArtifact, error) {
|
||||
now := time.Now()
|
||||
inputJSON, _ := json.Marshal(gin.H{
|
||||
"skill_key": definition.Key,
|
||||
"input_text": inputText,
|
||||
})
|
||||
outputJSON, _ := json.Marshal(result)
|
||||
logsJSON, _ := json.Marshal([]string{
|
||||
fmt.Sprintf("已执行技能:%s", definition.Label),
|
||||
"已生成结果并写入任务产物",
|
||||
})
|
||||
run := model.TaskRun{}
|
||||
artifacts := make([]model.TaskArtifact, 0)
|
||||
|
||||
err := store.DB.Transaction(func(tx *gorm.DB) error {
|
||||
run = model.TaskRun{
|
||||
TaskID: task.ID,
|
||||
SpecialistKey: task.SpecialistKey,
|
||||
ActionKey: definition.Key,
|
||||
ActionTitle: definition.Label,
|
||||
ActionType: definition.ActionType,
|
||||
Status: "done",
|
||||
InputJSON: string(inputJSON),
|
||||
OutputJSON: string(outputJSON),
|
||||
LogsJSON: string(logsJSON),
|
||||
StartedAt: now,
|
||||
FinishedAt: &now,
|
||||
}
|
||||
if err := tx.Create(&run).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, item := range toArtifactMaps(result["artifacts"]) {
|
||||
contentJSON, _ := json.Marshal(item)
|
||||
contentText := firstNonEmpty(asString(item["content"]), asString(result["summary"]))
|
||||
artifact := model.TaskArtifact{
|
||||
TaskID: task.ID,
|
||||
SpecialistKey: task.SpecialistKey,
|
||||
Title: firstNonEmpty(asString(item["title"]), definition.ResultTitle),
|
||||
ArtifactType: firstNonEmpty(asString(item["kind"]), definition.ActionType, "text"),
|
||||
Status: specialistruntime.ArtifactStatusDraft,
|
||||
ContentText: contentText,
|
||||
ContentJSON: string(contentJSON),
|
||||
SourceRefsJSON: "[]",
|
||||
CreatedByRunID: &run.ID,
|
||||
}
|
||||
if err := tx.Create(&artifact).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
artifacts = append(artifacts, artifact)
|
||||
}
|
||||
|
||||
task.CurrentRunID = &run.ID
|
||||
task.CurrentResult = firstNonEmpty(asString(result["summary"]), definition.Summary)
|
||||
task.Status = specialistruntime.TaskStatusDraft
|
||||
task.LastTriggeredAt = &now
|
||||
return tx.Save(&task).Error
|
||||
})
|
||||
return run, artifacts, err
|
||||
}
|
||||
|
||||
func loadMyOwnedTask(c *gin.Context, user *model.User, taskID uint) (model.TaskRecord, bool) {
|
||||
var task model.TaskRecord
|
||||
if err := specialistruntime.MyTaskQuery(user).Where("id = ?", taskID).First(&task).Error; err != nil {
|
||||
web.Fail(c, web.NewNotFoundError("任务不存在"))
|
||||
return task, false
|
||||
}
|
||||
return task, true
|
||||
}
|
||||
|
||||
func reloadTask(taskID uint) (model.TaskRecord, error) {
|
||||
var task model.TaskRecord
|
||||
err := store.DB.First(&task, taskID).Error
|
||||
return task, err
|
||||
}
|
||||
|
||||
func anyToStrings(value any) []string {
|
||||
switch items := value.(type) {
|
||||
case []string:
|
||||
return items
|
||||
case []any:
|
||||
out := make([]string, 0, len(items))
|
||||
for _, item := range items {
|
||||
text := asString(item)
|
||||
if text != "" {
|
||||
out = append(out, text)
|
||||
}
|
||||
}
|
||||
return out
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func asString(value any) string {
|
||||
if value == nil {
|
||||
return ""
|
||||
}
|
||||
switch v := value.(type) {
|
||||
case string:
|
||||
return strings.TrimSpace(v)
|
||||
default:
|
||||
text := strings.TrimSpace(fmt.Sprint(value))
|
||||
if text == "<nil>" {
|
||||
return ""
|
||||
}
|
||||
return text
|
||||
}
|
||||
}
|
||||
|
||||
func toArtifactMaps(value any) []gin.H {
|
||||
items, ok := value.([]gin.H)
|
||||
if ok {
|
||||
return items
|
||||
}
|
||||
raw, ok := value.([]any)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
out := make([]gin.H, 0, len(raw))
|
||||
for _, item := range raw {
|
||||
if mapped, ok := item.(map[string]any); ok {
|
||||
out = append(out, gin.H(mapped))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func appendUploadItem(value any, item gin.H) []any {
|
||||
list, ok := value.([]any)
|
||||
if !ok {
|
||||
list = []any{}
|
||||
}
|
||||
return append(list, item)
|
||||
}
|
||||
|
||||
func mustMarshalJSON(value any) string {
|
||||
data, _ := json.Marshal(value)
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func parseUintFromForm(value string) (uint, bool) {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return 0, false
|
||||
}
|
||||
var parsed uint64
|
||||
if _, err := fmt.Sscanf(value, "%d", &parsed); err != nil {
|
||||
return 0, false
|
||||
}
|
||||
return uint(parsed), true
|
||||
}
|
||||
|
||||
func looksLikeImage(name string) bool {
|
||||
ext := strings.ToLower(filepath.Ext(strings.TrimSpace(name)))
|
||||
switch ext {
|
||||
case ".png", ".jpg", ".jpeg", ".bmp", ".webp", ".tif", ".tiff":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func runPaddleOCR(imagePath string) (*paddleOCRPayload, error) {
|
||||
scriptPath, err := resolvePaddleOCRScriptPath()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("未找到 PaddleOCR 脚本:%w", err)
|
||||
}
|
||||
cmd := exec.Command("python3", scriptPath, imagePath)
|
||||
var stdout bytes.Buffer
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
return nil, fmt.Errorf("PaddleOCR 执行失败:%s", firstNonEmpty(strings.TrimSpace(stderr.String()), err.Error()))
|
||||
}
|
||||
payload := &paddleOCRPayload{}
|
||||
if err := json.Unmarshal(stdout.Bytes(), payload); err != nil {
|
||||
return nil, fmt.Errorf("PaddleOCR 返回结果解析失败")
|
||||
}
|
||||
if payload.Error != "" {
|
||||
return nil, fmt.Errorf("PaddleOCR 返回错误:%s", payload.Error)
|
||||
}
|
||||
return payload, nil
|
||||
}
|
||||
|
||||
func resolvePaddleOCRScriptPath() (string, error) {
|
||||
candidates := []string{
|
||||
filepath.Join("scripts", "paddle_ocr_extract.py"),
|
||||
filepath.Join("backend-go", "scripts", "paddle_ocr_extract.py"),
|
||||
}
|
||||
for _, candidate := range candidates {
|
||||
if _, err := os.Stat(candidate); err == nil {
|
||||
return candidate, nil
|
||||
}
|
||||
}
|
||||
return "", os.ErrNotExist
|
||||
}
|
||||
|
||||
func escapeSVGText(value string) string {
|
||||
replacer := strings.NewReplacer("&", "&", "<", "<", ">", ">", `"`, """)
|
||||
return replacer.Replace(value)
|
||||
}
|
||||
|
||||
func maxInt(a, b int) int {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func minInt(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, value := range values {
|
||||
value = strings.TrimSpace(value)
|
||||
if value != "" {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package skillapi
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
skillmodel "eai_agentplatform/backend/internal/skills/model"
|
||||
"eai_agentplatform/backend/internal/store"
|
||||
"eai_agentplatform/backend/internal/web"
|
||||
)
|
||||
|
||||
func ListSkillDefinitions(c *gin.Context) {
|
||||
q := store.DB.Model(&skillmodel.SkillDefinition{})
|
||||
if c.Query("state") == "" {
|
||||
q = q.Where("state = ?", "active")
|
||||
} else {
|
||||
q = q.Where("state = ?", c.Query("state"))
|
||||
}
|
||||
if c.Query("exposed_to_user") != "" {
|
||||
q = q.Where("exposed_to_user = ?", c.Query("exposed_to_user") == "true")
|
||||
}
|
||||
|
||||
var items []skillmodel.SkillDefinition
|
||||
if err := q.Order("sort_order ASC, id ASC").Find(&items).Error; err != nil {
|
||||
web.Fail(c, web.NewBadRequest("查询技能定义失败"))
|
||||
return
|
||||
}
|
||||
web.OK(c, items)
|
||||
}
|
||||
|
||||
func GetSkillDefinitionByKey(c *gin.Context) {
|
||||
key := strings.TrimSpace(c.Param("key"))
|
||||
if key == "" {
|
||||
web.Fail(c, web.NewBadRequest("技能 key 不能为空"))
|
||||
return
|
||||
}
|
||||
|
||||
var item skillmodel.SkillDefinition
|
||||
if err := store.DB.Where("key = ?", key).First(&item).Error; err != nil {
|
||||
web.Fail(c, web.NewNotFoundError("技能定义不存在"))
|
||||
return
|
||||
}
|
||||
web.OK(c, item)
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package skillapi
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"eai_agentplatform/backend/internal/middleware"
|
||||
reportgeneration "eai_agentplatform/backend/internal/skills/packages/report_generation"
|
||||
"eai_agentplatform/backend/internal/web"
|
||||
)
|
||||
|
||||
// ReportGenerate POST /api/report/generate —— 调用 LLM 生成报告正文
|
||||
func ReportGenerate(c *gin.Context) {
|
||||
user := middleware.CurrentUser(c)
|
||||
if user == nil {
|
||||
web.Fail(c, web.NewAuthError("未登录"))
|
||||
return
|
||||
}
|
||||
var req reportgeneration.ReportGenRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil || strings.TrimSpace(req.Topic) == "" {
|
||||
web.Fail(c, web.NewBadRequest("topic 必填"))
|
||||
return
|
||||
}
|
||||
|
||||
// 1. 检索知识库片段
|
||||
spaceKey := ""
|
||||
if req.Knowledge != "" {
|
||||
spaceKey = req.Knowledge
|
||||
}
|
||||
knowledgeContent := reportgeneration.RetrieveReportKnowledge(req.Topic, spaceKey)
|
||||
|
||||
// 2. 构建 LLM 提示词
|
||||
var chapters []reportgeneration.ReportChapter
|
||||
if len(req.Sections) > 0 {
|
||||
// 使用用户指定的章节
|
||||
chapters = reportgeneration.PromptReportWithSections(req, knowledgeContent)
|
||||
} else {
|
||||
// LLM 自动规划章节
|
||||
chapters = reportgeneration.PromptReportAutoChapters(req, knowledgeContent)
|
||||
}
|
||||
|
||||
// 3. 组装报告
|
||||
report := reportgeneration.ReportContent{
|
||||
Topic: req.Topic,
|
||||
Summary: strings.TrimSpace(req.Summary),
|
||||
Chapters: chapters,
|
||||
CreatedAt: time.Now().Format("2006-01-02 15:04:05"),
|
||||
}
|
||||
|
||||
web.OK(c, gin.H{
|
||||
"report": report,
|
||||
})
|
||||
}
|
||||
|
||||
// ReportExportPDF POST /api/report/export/pdf —— 导出报告为 PDF 文件
|
||||
func ReportExportPDF(c *gin.Context) {
|
||||
user := middleware.CurrentUser(c)
|
||||
if user == nil {
|
||||
web.Fail(c, web.NewAuthError("未登录"))
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Report reportgeneration.ReportContent `json:"report"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil || req.Report.Topic == "" {
|
||||
web.Fail(c, web.NewBadRequest("report 不能为空"))
|
||||
return
|
||||
}
|
||||
|
||||
data, err := reportgeneration.ExportReportPDF(req.Report)
|
||||
if err != nil {
|
||||
web.Fail(c, web.NewBadRequest("PDF 生成失败: "+err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
c.Header("Content-Type", "application/pdf")
|
||||
c.Header("Content-Disposition",
|
||||
"attachment; filename=\""+strings.ReplaceAll(req.Report.Topic, " ", "_")+".pdf\"")
|
||||
c.Data(200, "application/pdf", data)
|
||||
}
|
||||
|
||||
// ReportPreview GET /api/report/preview —— 预览报告(JSON,用于前端预览)
|
||||
func ReportPreview(c *gin.Context) {
|
||||
user := middleware.CurrentUser(c)
|
||||
if user == nil {
|
||||
web.Fail(c, web.NewAuthError("未登录"))
|
||||
return
|
||||
}
|
||||
var req reportgeneration.ReportGenRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil || strings.TrimSpace(req.Topic) == "" {
|
||||
web.Fail(c, web.NewBadRequest("topic 必填"))
|
||||
return
|
||||
}
|
||||
|
||||
// 使用 LLM 生成报告内容
|
||||
report := reportgeneration.PromptReportPreview(req)
|
||||
|
||||
web.OK(c, gin.H{
|
||||
"report": report,
|
||||
})
|
||||
}
|
||||
|
||||
// ReportExportXLSX POST /api/report/export/xlsx —— 导出报告为 Excel
|
||||
func ReportExportXLSX(c *gin.Context) {
|
||||
user := middleware.CurrentUser(c)
|
||||
if user == nil {
|
||||
web.Fail(c, web.NewAuthError("未登录"))
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Report reportgeneration.ReportContent `json:"report"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil || req.Report.Topic == "" {
|
||||
web.Fail(c, web.NewBadRequest("report 不能为空"))
|
||||
return
|
||||
}
|
||||
data, err := reportgeneration.ExportReportXLSX(req.Report)
|
||||
if err != nil {
|
||||
web.Fail(c, web.NewBadRequest("Excel 生成失败: "+err.Error()))
|
||||
return
|
||||
}
|
||||
c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
c.Header("Content-Disposition", "attachment; filename=\""+strings.ReplaceAll(req.Report.Topic, " ", "_")+".xlsx\"")
|
||||
c.Data(200, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", data)
|
||||
}
|
||||
|
||||
// ReportExportDOCX POST /api/report/export/docx —— 导出报告为 Word
|
||||
func ReportExportDOCX(c *gin.Context) {
|
||||
user := middleware.CurrentUser(c)
|
||||
if user == nil {
|
||||
web.Fail(c, web.NewAuthError("未登录"))
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Report reportgeneration.ReportContent `json:"report"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil || req.Report.Topic == "" {
|
||||
web.Fail(c, web.NewBadRequest("report 不能为空"))
|
||||
return
|
||||
}
|
||||
data, err := reportgeneration.ExportReportDOCX(req.Report)
|
||||
if err != nil {
|
||||
web.Fail(c, web.NewBadRequest("Word 生成失败: "+err.Error()))
|
||||
return
|
||||
}
|
||||
c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
|
||||
c.Header("Content-Disposition", "attachment; filename=\""+strings.ReplaceAll(req.Report.Topic, " ", "_")+".docx\"")
|
||||
c.Data(200, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", data)
|
||||
}
|
||||
|
||||
// ReportExportPPTX POST /api/report/export/pptx —— 导出报告为 PPTX
|
||||
func ReportExportPPTX(c *gin.Context) {
|
||||
user := middleware.CurrentUser(c)
|
||||
if user == nil {
|
||||
web.Fail(c, web.NewAuthError("未登录"))
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Report reportgeneration.ReportContent `json:"report"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil || req.Report.Topic == "" {
|
||||
web.Fail(c, web.NewBadRequest("report 不能为空"))
|
||||
return
|
||||
}
|
||||
data, err := reportgeneration.ExportReportPPTX(req.Report)
|
||||
if err != nil {
|
||||
web.Fail(c, web.NewBadRequest("PPTX 生成失败: "+err.Error()))
|
||||
return
|
||||
}
|
||||
c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.presentationml.presentation")
|
||||
c.Header("Content-Disposition", "attachment; filename=\""+strings.ReplaceAll(req.Report.Topic, " ", "_")+".pptx\"")
|
||||
c.Data(200, "application/vnd.openxmlformats-officedocument.presentationml.presentation", data)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package skillapi
|
||||
|
||||
type definitionReq struct {
|
||||
Key string `json:"key"`
|
||||
Label string `json:"label"`
|
||||
Description string `json:"description"`
|
||||
ObjectKind string `json:"object_kind"`
|
||||
Source string `json:"source"`
|
||||
ObjectEntryRoute string `json:"object_entry_route"`
|
||||
ExposedToUser bool `json:"exposed_to_user"`
|
||||
StarterPromptsJSON string `json:"starter_prompts_json"`
|
||||
PromptTemplate string `json:"prompt_template"`
|
||||
InputSchemaJSON string `json:"input_schema_json"`
|
||||
OutputSchemaJSON string `json:"output_schema_json"`
|
||||
ArtifactSchemaJSON string `json:"artifact_schema_json"`
|
||||
ActionRefsJSON string `json:"action_refs_json"`
|
||||
PolicyRefsJSON string `json:"policy_refs_json"`
|
||||
OntologyBindingJSON string `json:"ontology_binding_json"`
|
||||
State string `json:"state"`
|
||||
SortOrder int `json:"sort_order"`
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package skillapi
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"eai_agentplatform/backend/internal/jsonutil"
|
||||
"eai_agentplatform/backend/internal/web"
|
||||
)
|
||||
|
||||
func normalizeDefinitionReq(req *definitionReq) {
|
||||
req.Key = strings.TrimSpace(req.Key)
|
||||
req.Label = strings.TrimSpace(req.Label)
|
||||
req.Description = strings.TrimSpace(req.Description)
|
||||
req.ObjectKind = strings.TrimSpace(req.ObjectKind)
|
||||
req.Source = strings.TrimSpace(req.Source)
|
||||
req.ObjectEntryRoute = strings.TrimSpace(req.ObjectEntryRoute)
|
||||
req.StarterPromptsJSON = strings.TrimSpace(req.StarterPromptsJSON)
|
||||
req.PromptTemplate = strings.TrimSpace(req.PromptTemplate)
|
||||
req.InputSchemaJSON = strings.TrimSpace(req.InputSchemaJSON)
|
||||
req.OutputSchemaJSON = strings.TrimSpace(req.OutputSchemaJSON)
|
||||
req.ArtifactSchemaJSON = strings.TrimSpace(req.ArtifactSchemaJSON)
|
||||
req.ActionRefsJSON = strings.TrimSpace(req.ActionRefsJSON)
|
||||
req.PolicyRefsJSON = strings.TrimSpace(req.PolicyRefsJSON)
|
||||
req.OntologyBindingJSON = strings.TrimSpace(req.OntologyBindingJSON)
|
||||
req.State = strings.TrimSpace(req.State)
|
||||
}
|
||||
|
||||
func validateDefinitionReq(req *definitionReq) *web.AppError {
|
||||
normalizeDefinitionReq(req)
|
||||
if req.Key == "" || req.Label == "" {
|
||||
return web.NewBadRequest("key、label 为必填")
|
||||
}
|
||||
if req.ObjectKind == "" {
|
||||
req.ObjectKind = "skill"
|
||||
}
|
||||
switch req.ObjectKind {
|
||||
case "specialist", "skill":
|
||||
default:
|
||||
return web.NewBadRequest("object_kind 只能是 specialist 或 skill")
|
||||
}
|
||||
if req.Source == "" {
|
||||
req.Source = "eai"
|
||||
}
|
||||
if req.State == "" {
|
||||
req.State = "active"
|
||||
}
|
||||
if req.State != "active" && req.State != "inactive" {
|
||||
return web.NewBadRequest("state 只能是 active 或 inactive")
|
||||
}
|
||||
if !jsonutil.ValidateStringArrayJSON(req.StarterPromptsJSON) {
|
||||
return web.NewBadRequest("starter_prompts_json 必须是字符串数组")
|
||||
}
|
||||
if !jsonutil.ValidateObjectJSON(req.InputSchemaJSON) {
|
||||
return web.NewBadRequest("input_schema_json 必须是 JSON 对象")
|
||||
}
|
||||
if !jsonutil.ValidateObjectJSON(req.OutputSchemaJSON) {
|
||||
return web.NewBadRequest("output_schema_json 必须是 JSON 对象")
|
||||
}
|
||||
if !jsonutil.ValidateObjectJSON(req.ArtifactSchemaJSON) {
|
||||
return web.NewBadRequest("artifact_schema_json 必须是 JSON 对象")
|
||||
}
|
||||
if !jsonutil.ValidateStringArrayJSON(req.ActionRefsJSON) {
|
||||
return web.NewBadRequest("action_refs_json 必须是字符串数组")
|
||||
}
|
||||
if !jsonutil.ValidateStringArrayJSON(req.PolicyRefsJSON) {
|
||||
return web.NewBadRequest("policy_refs_json 必须是字符串数组")
|
||||
}
|
||||
if !jsonutil.ValidateObjectJSON(req.OntologyBindingJSON) {
|
||||
return web.NewBadRequest("ontology_binding_json 必须是 JSON 对象")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user