chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,295 @@
|
||||
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 能力未就绪(缺少分块/模型服务)")
|
||||
}
|
||||
if count <= 0 {
|
||||
count = 10
|
||||
}
|
||||
if count > 30 {
|
||||
count = 30
|
||||
}
|
||||
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 生成试题(请重新上传课件)")
|
||||
}
|
||||
// 拼接课件的知识库文本分块,截断到 ~12k 字符控制 token。
|
||||
// 兜底:knowledge_id 悬空(知识库文档被删除/重建导致引用失效)时,
|
||||
// 按课件名在「企业培训(课件)」知识库找同名文档取分块,避免旧引用卡死出题。
|
||||
chunks, chunkErr := s.chunkSvc.ListChunksByKnowledgeID(ctx, material.KnowledgeID)
|
||||
if chunkErr != nil || len(chunks) == 0 {
|
||||
if altID := s.findCoursewareKnowledgeIDByName(ctx, material.Name); altID != "" {
|
||||
if altChunks, altErr := s.chunkSvc.ListChunksByKnowledgeID(ctx, altID); altErr == nil && len(altChunks) > 0 {
|
||||
material.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", material.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, material.Name)
|
||||
}
|
||||
|
||||
// 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, 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, err := s.repo.ReplaceQuestionBankByName(ctx, tenantID, name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if courseID == "" {
|
||||
courseID = oldCourseID
|
||||
}
|
||||
knowledgeID := s.syncQuestionsToBankKB(ctx, questions, name)
|
||||
bank := &types.TrainingQuestionBank{Name: name, CourseID: courseID, 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
|
||||
}
|
||||
Reference in new issue
Block a user