需求域: - 需求导入修复内/外培训与外部讲师落库;按模板标题年入库(年-月一致) - 核验确认收窄为「需求归属部门+经理职称角色」,越权提示联系部门经理 - 确认转月计划后自动推送讲师/课长维护;导入后自动推送部门经理核验(站内+企微) 课程域: - 课程管理发布状态字段(迁移000154)+发布/下线;培训中心「和信课程」目录 - 需求讲师改选后回写课程管理;确认同步带出适合人员/课件/试题 - 月计划详情课件/试题更换(上传/知识库选择/题库换绑)回写课程管理, 无关联条目的存量计划自动创建课程条目 模板与表单: - 教育训练需求表:适合人员/内-外培训口径;部门联动课程下拉; 适合人员/讲师按所选课程自动带出;在线提报课程下拉(本部门)自动带出分类/讲师/适合人员 页面与权限: - 培训中心页签重组(和信课程/我的培训/我的考试),移除线上/线下页签 - 数据驾驶舱迁侧栏(职称角色之下);职称角色迁至更多工具配置中心之后 - 配置中心/职称角色对经理开放;页签「职称角色」更名「角色权限」 - 修复年度下拉空白(TDesign options 需对象数组)、月计划列表地点兜底 其他: 培训预览端口修正与 dev:training 脚本;tmp-extract-duckdb 加入 gitignore
322 lines
13 KiB
Go
322 lines
13 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"academy/internal/errors"
|
|
"academy/internal/logger"
|
|
"academy/internal/models/chat"
|
|
"academy/internal/types"
|
|
)
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// AI 课件生成试题(课程详情「AI课件生成试题」入口):
|
|
// 取课件的已索引知识库分块文本 → 默认对话模型生成客观题(不落库)→ 前端预览编辑 →
|
|
// ImportGeneratedQuestionBank 建题库并关联课程,题目文本同步「企业培训(题库)」知识库。
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// aiQuestionGenTimeout 单次 LLM 出题超时(题目数量多,放宽到 3 分钟)。
|
|
const aiQuestionGenTimeout = 3 * time.Minute
|
|
|
|
// aiQuestionLLMOutput LLM 生成题目的解析结构。
|
|
type aiQuestionLLMOutput struct {
|
|
Type string `json:"type"`
|
|
Stem string `json:"stem"`
|
|
Options []string `json:"options"`
|
|
Answer string `json:"answer"`
|
|
KnowledgePoint string `json:"knowledge_point"`
|
|
Analysis string `json:"analysis"`
|
|
Difficulty int `json:"difficulty"`
|
|
}
|
|
|
|
func aiQuestionSystemPrompt() string {
|
|
return "你是企业培训出题专家。基于给定课件内容出客观题,要求:题干清晰、答案准确且能在课件中找到依据;覆盖课件的主要知识点。" +
|
|
"严格只输出 JSON 数组(不要 markdown 代码块,不要任何多余文字),每道题格式:" +
|
|
`{"type":"single|multiple|judge","stem":"题干","options":["A. 选项内容","B. 选项内容","C. 选项内容","D. 选项内容"],"answer":"A","knowledge_point":"所属课程或知识点","difficulty":3,"analysis":"解析"}` +
|
|
"。judge 题固定 options 为 [\"A. 对\",\"B. 错\"],answer 取 A 或 B;multiple 题 answer 为多个字母如 ABD;选项数量 2-6 个;difficulty 取 1-5。"
|
|
}
|
|
|
|
// GenerateCourseQuestions 取课程课件的已索引文本分块,交默认对话模型生成客观题。
|
|
// 题目仅返回不落库,前端预览编辑后经 ImportGeneratedQuestionBank 建库。
|
|
func (s *trainingService) GenerateCourseQuestions(ctx context.Context, tenantID uint64, userID, courseID, materialID string, count int) ([]*types.TrainingQuestion, error) {
|
|
if s.chunkSvc == nil || s.models == nil {
|
|
return nil, errors.NewBadRequestError("AI 能力未就绪(缺少分块/模型服务)")
|
|
}
|
|
material, err := s.repo.GetMaterial(ctx, tenantID, materialID)
|
|
if err != nil || material == nil {
|
|
return nil, errors.NewNotFoundError("课件不存在")
|
|
}
|
|
if material.CourseID != courseID {
|
|
return nil, errors.NewBadRequestError("课件不属于该课程")
|
|
}
|
|
if material.KnowledgeID == "" {
|
|
return nil, errors.NewBadRequestError("该课件未同步知识库,无法 AI 生成试题(请重新上传课件)")
|
|
}
|
|
return s.generateQuestionsFromKnowledge(ctx, tenantID, userID, material.KnowledgeID, material.Name, count)
|
|
}
|
|
|
|
// GenerateLibraryCourseQuestions 课程管理课件 AI 出题(000153):读取课程管理
|
|
// 条目课件同步知识库后的分块文本出题;题目不落库,预览确认后经
|
|
// ImportGeneratedQuestionBank 建库并挂 library_course_id。
|
|
func (s *trainingService) GenerateLibraryCourseQuestions(ctx context.Context, tenantID uint64, userID, libraryCourseID string, count int) ([]*types.TrainingQuestion, error) {
|
|
if s.chunkSvc == nil || s.models == nil {
|
|
return nil, errors.NewBadRequestError("AI 能力未就绪(缺少分块/模型服务)")
|
|
}
|
|
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, libraryCourseID)
|
|
if err != nil || item == nil {
|
|
return nil, errors.NewNotFoundError("课程不存在")
|
|
}
|
|
if item.KnowledgeID == "" {
|
|
return nil, errors.NewBadRequestError("该课程课件未同步知识库,无法 AI 生成试题(请重新上传课件)")
|
|
}
|
|
return s.generateQuestionsFromKnowledge(ctx, tenantID, userID, item.KnowledgeID, item.Name, count)
|
|
}
|
|
|
|
// generateQuestionsFromKnowledge 按知识库文档分块拼上下文并交默认模型出题
|
|
// (GenerateCourseQuestions / GenerateLibraryCourseQuestions 共用管线)。
|
|
func (s *trainingService) generateQuestionsFromKnowledge(ctx context.Context, tenantID uint64, userID, knowledgeID, sourceName string, count int) ([]*types.TrainingQuestion, error) {
|
|
if count <= 0 {
|
|
count = 10
|
|
}
|
|
if count > 30 {
|
|
count = 30
|
|
}
|
|
// 拼接课件的知识库文本分块,截断到 ~12k 字符控制 token。
|
|
// 兜底:knowledge_id 悬空(知识库文档被删除/重建导致引用失效)时,
|
|
// 按课件名在「企业培训(课件)」知识库找同名文档取分块,避免旧引用卡死出题。
|
|
chunks, chunkErr := s.chunkSvc.ListChunksByKnowledgeID(ctx, knowledgeID)
|
|
if chunkErr != nil || len(chunks) == 0 {
|
|
if altID := s.findCoursewareKnowledgeIDByName(ctx, sourceName); altID != "" {
|
|
if altChunks, altErr := s.chunkSvc.ListChunksByKnowledgeID(ctx, altID); altErr == nil && len(altChunks) > 0 {
|
|
knowledgeID = altID
|
|
chunks = altChunks
|
|
}
|
|
}
|
|
}
|
|
if len(chunks) == 0 {
|
|
return nil, errors.NewBadRequestError(
|
|
"课件文本索引缺失(知识库分块已被清理),请在知识库中对该文档「重新解析」,或重新上传课件后再试")
|
|
}
|
|
var sb strings.Builder
|
|
for _, c := range chunks {
|
|
if c == nil || c.Content == "" {
|
|
continue
|
|
}
|
|
sb.WriteString(strings.TrimSpace(c.Content))
|
|
sb.WriteString("\n\n")
|
|
if sb.Len() > 12000 {
|
|
break
|
|
}
|
|
}
|
|
content := strings.TrimSpace(sb.String())
|
|
if content == "" {
|
|
return nil, errors.NewBadRequestError("课件暂无可用文本内容")
|
|
}
|
|
|
|
model, err := s.resolveDefaultChatModel(ctx)
|
|
if err != nil {
|
|
return nil, errors.NewBadRequestError("未配置可用大模型,无法生成试题")
|
|
}
|
|
llmCtx, cancel := context.WithTimeout(ctx, aiQuestionGenTimeout)
|
|
defer cancel()
|
|
llmCtx = types.WithLLMCallMetadata(llmCtx, "training.course_question_gen", knowledgeID)
|
|
thinking := false
|
|
response, err := model.Chat(llmCtx, []chat.Message{
|
|
{Role: "system", Content: aiQuestionSystemPrompt()},
|
|
{Role: "user", Content: fmt.Sprintf("请基于以下课件内容出 %d 道题:\n\n<课件>\n%s\n</课件>", count, content)},
|
|
}, &chat.ChatOptions{
|
|
Temperature: 0.3,
|
|
MaxCompletionTokens: 6000,
|
|
Thinking: &thinking,
|
|
})
|
|
if err != nil {
|
|
logger.Warnf(ctx, "[training] ai question gen llm call failed: %v", err)
|
|
return nil, errors.NewBadRequestError("大模型调用失败:" + aiErrBrief(err))
|
|
}
|
|
return parseAIQuestions(response.Content, sourceName)
|
|
}
|
|
|
|
// findCoursewareKnowledgeIDByName 在「企业培训(课件)」知识库按标题/文件名
|
|
// 精确匹配同名文档,返回其 knowledge_id(悬空引用兜底);找不到返回空串。
|
|
func (s *trainingService) findCoursewareKnowledgeIDByName(ctx context.Context, name string) string {
|
|
name = strings.TrimSpace(name)
|
|
if name == "" {
|
|
return ""
|
|
}
|
|
_, coursewareKB, err := s.ensureTrainingKnowledgeBases(ctx)
|
|
if err != nil || coursewareKB == nil {
|
|
return ""
|
|
}
|
|
docs, err := s.knowledgeSvc.ListKnowledgeByKnowledgeBaseID(ctx, coursewareKB.ID)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
for _, doc := range docs {
|
|
if doc != nil && (doc.Title == name || doc.FileName == name) && doc.ID != "" {
|
|
return doc.ID
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// parseAIQuestions 解析 LLM 输出的题目 JSON 数组并归一化(题型/选项字母前缀/答案口径)。
|
|
func parseAIQuestions(content, courseName string) ([]*types.TrainingQuestion, error) {
|
|
raw := extractJSONBracket(content, '[', ']')
|
|
if raw == "" {
|
|
return nil, errors.NewBadRequestError("大模型未返回有效题目,请重试")
|
|
}
|
|
var items []aiQuestionLLMOutput
|
|
if err := json.Unmarshal([]byte(raw), &items); err != nil {
|
|
return nil, errors.NewBadRequestError("题目解析失败,请重试")
|
|
}
|
|
out := make([]*types.TrainingQuestion, 0, len(items))
|
|
for i, it := range items {
|
|
stem := strings.TrimSpace(it.Stem)
|
|
answer := strings.ToUpper(strings.TrimSpace(it.Answer))
|
|
if stem == "" || answer == "" {
|
|
continue
|
|
}
|
|
qType := it.Type
|
|
if qType != types.TrainingQuestionMultiple && qType != types.TrainingQuestionJudge {
|
|
qType = types.TrainingQuestionSingle
|
|
}
|
|
options := make([]string, 0, len(it.Options))
|
|
for _, opt := range it.Options {
|
|
if v := strings.TrimSpace(opt); v != "" {
|
|
options = append(options, v)
|
|
}
|
|
}
|
|
options = ensureOptionLetterPrefixes(options)
|
|
if qType == types.TrainingQuestionJudge && len(options) == 0 {
|
|
options = []string{"A. 对", "B. 错"}
|
|
}
|
|
answer = normalizeTemplateAnswer(answer, options)
|
|
difficulty := it.Difficulty
|
|
if difficulty < 1 || difficulty > 5 {
|
|
difficulty = 3
|
|
}
|
|
knowledgePoint := strings.TrimSpace(it.KnowledgePoint)
|
|
if knowledgePoint == "" {
|
|
knowledgePoint = courseName
|
|
}
|
|
out = append(out, &types.TrainingQuestion{
|
|
Type: qType,
|
|
Stem: stem,
|
|
Options: trainingJSONFromSlice(options),
|
|
Answer: answer,
|
|
Difficulty: difficulty,
|
|
KnowledgePoint: knowledgePoint,
|
|
Analysis: strings.TrimSpace(it.Analysis),
|
|
Score: 5,
|
|
SeqNo: i + 1,
|
|
})
|
|
}
|
|
if len(out) == 0 {
|
|
return nil, errors.NewBadRequestError("大模型未返回有效题目,请重试")
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// extractJSONBracket 抽取 content 中首个以 open/close 包裹的 JSON 片段(容忍 ```json 围栏)。
|
|
func extractJSONBracket(content string, open, close byte) string {
|
|
start := strings.IndexByte(content, open)
|
|
if start < 0 {
|
|
return ""
|
|
}
|
|
end := strings.LastIndexByte(content, close)
|
|
if end <= start {
|
|
return ""
|
|
}
|
|
return content[start : end+1]
|
|
}
|
|
|
|
// ImportGeneratedQuestionBank 使用(AI 生成并经人工编辑的)题目建题库:
|
|
// 关联课程/课程管理条目;题目以分节文本同步进「企业培训(题库)」知识库(检索与
|
|
// AI 问答可用);未指定归属时继承同名旧题库的关联,同名旧库会被替换。
|
|
func (s *trainingService) ImportGeneratedQuestionBank(ctx context.Context, tenantID uint64, courseID, libraryCourseID, name string, questions []*types.TrainingQuestion, updaterID string) (*types.TrainingQuestionBank, error) {
|
|
if len(questions) == 0 {
|
|
return nil, errors.NewBadRequestError("题目为空")
|
|
}
|
|
name = strings.TrimSpace(name)
|
|
if name == "" {
|
|
name = "AI生成题库"
|
|
}
|
|
oldCourseID, oldLibraryCourseID, err := s.repo.ReplaceQuestionBankByName(ctx, tenantID, name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if courseID == "" {
|
|
courseID = oldCourseID
|
|
}
|
|
if libraryCourseID == "" {
|
|
libraryCourseID = oldLibraryCourseID
|
|
}
|
|
knowledgeID := s.syncQuestionsToBankKB(ctx, questions, name)
|
|
bank := &types.TrainingQuestionBank{Name: name, CourseID: courseID, LibraryCourseID: libraryCourseID, KnowledgeID: knowledgeID}
|
|
return s.ImportQuestionBank(ctx, tenantID, bank, questions, updaterID)
|
|
}
|
|
|
|
// syncQuestionsToBankKB 将题目整理为分节文本同步进「企业培训(题库)」知识库。
|
|
// fail-open:同步失败仅记日志返回空串,不阻断题库创建。
|
|
func (s *trainingService) syncQuestionsToBankKB(ctx context.Context, questions []*types.TrainingQuestion, bankName string) string {
|
|
_, bankKB, err := s.ensureTrainingKnowledgeBases(ctx)
|
|
if err != nil {
|
|
logger.Warnf(ctx, "[training] skip syncing generated questions to KB (ensure failed): %v", err)
|
|
return ""
|
|
}
|
|
knowledge, err := s.knowledgeSvc.CreateKnowledgeFromPassageSync(ctx, bankKB.ID, aiQuestionPassages(questions, bankName), trainingKBChannel)
|
|
if err != nil {
|
|
logger.Warnf(ctx, "[training] skip syncing generated questions to KB (create failed): %v", err)
|
|
return ""
|
|
}
|
|
if knowledge == nil {
|
|
return ""
|
|
}
|
|
return knowledge.ID
|
|
}
|
|
|
|
// aiQuestionPassages 按题型分节的题目文本(每节一段,便于知识库分块索引)。
|
|
func aiQuestionPassages(questions []*types.TrainingQuestion, bankName string) []string {
|
|
sections := map[string][]*types.TrainingQuestion{}
|
|
order := make([]string, 0, 3)
|
|
for _, q := range questions {
|
|
if q == nil {
|
|
continue
|
|
}
|
|
if _, ok := sections[q.Type]; !ok {
|
|
order = append(order, q.Type)
|
|
}
|
|
sections[q.Type] = append(sections[q.Type], q)
|
|
}
|
|
title := map[string]string{
|
|
types.TrainingQuestionSingle: "单选题",
|
|
types.TrainingQuestionMultiple: "多选题",
|
|
types.TrainingQuestionJudge: "判断题",
|
|
}
|
|
passages := make([]string, 0, len(order))
|
|
for _, t := range order {
|
|
var sb strings.Builder
|
|
fmt.Fprintf(&sb, "## %s(题库:%s)\n\n", title[t], bankName)
|
|
for i, q := range sections[t] {
|
|
fmt.Fprintf(&sb, "%d. %s\n", i+1, q.Stem)
|
|
for _, opt := range trainingJSONStrings(string(q.Options)) {
|
|
fmt.Fprintf(&sb, " %s\n", opt)
|
|
}
|
|
fmt.Fprintf(&sb, " 答案:%s · 难度:%d", q.Answer, q.Difficulty)
|
|
if q.KnowledgePoint != "" {
|
|
fmt.Fprintf(&sb, " · 知识点:%s", q.KnowledgePoint)
|
|
}
|
|
if q.Analysis != "" {
|
|
fmt.Fprintf(&sb, "\n 解析:%s", q.Analysis)
|
|
}
|
|
sb.WriteString("\n\n")
|
|
}
|
|
passages = append(passages, sb.String())
|
|
}
|
|
return passages
|
|
}
|