feat(suggested-questions): implement suggested questions feature for chat interface

- Added a new API endpoint to fetch suggested questions based on the agent's associated knowledge bases.
- Implemented frontend components to display suggested questions in both chat and create chat views, enhancing user interaction.
- Updated localization files to include translations for suggested questions in English, Korean, Russian, and Chinese.
- Introduced debounce logic for fetching suggestions to optimize performance during knowledge base changes.
- Enhanced backend services to support fetching and returning suggested questions, improving the overall chat experience.
This commit is contained in:
wizardchen
2026-03-25 20:58:21 +08:00
committed by lyingbug
parent 1416217a0a
commit 1960fc2d90
14 changed files with 763 additions and 4 deletions
+23
View File
@@ -212,3 +212,26 @@ export function deleteIMChannel(id: string) {
export function toggleIMChannel(id: string) {
return post<{ data: IMChannel }>(`/api/v1/im-channels/${id}/toggle`);
}
// ===== 推荐问题 =====
// 推荐问题
export interface SuggestedQuestion {
question: string;
source: 'faq' | 'document' | 'agent_config';
knowledge_base_id?: string;
}
// 获取智能体推荐问题
// 根据智能体关联的知识库范围返回推荐问题,用于前端对话面板快捷提问
export function getSuggestedQuestions(
agentId: string,
params?: { knowledge_base_ids?: string[]; knowledge_ids?: string[]; limit?: number }
) {
const query = new URLSearchParams();
if (params?.knowledge_base_ids?.length) query.set('knowledge_base_ids', params.knowledge_base_ids.join(','));
if (params?.knowledge_ids?.length) query.set('knowledge_ids', params.knowledge_ids.join(','));
if (params?.limit) query.set('limit', String(params.limit));
const qs = query.toString();
return get<{ data: { questions: SuggestedQuestion[] } }>(`/api/v1/agents/${agentId}/suggested-questions${qs ? '?' + qs : ''}`);
}
+2
View File
@@ -1696,6 +1696,8 @@ export default {
chat: {
title: 'Chat',
newChat: 'New Chat',
suggestedQuestions: 'You can ask me',
suggestedQuestionsLoading: 'Loading suggestions...',
inputPlaceholder: 'Enter your message...',
send: 'Send',
thinking: 'Thinking...',
+2
View File
@@ -289,6 +289,8 @@ export default {
chat: {
title: "대화",
newChat: "새 대화",
suggestedQuestions: "이렇게 물어보세요",
suggestedQuestionsLoading: "추천 질문 로딩 중...",
inputPlaceholder: "메시지를 입력하세요...",
send: "전송",
thinking: "생각 중...",
+2
View File
@@ -1857,6 +1857,8 @@ export default {
chat: {
title: 'Диалог',
newChat: 'Новый чат',
suggestedQuestions: 'Вы можете спросить меня',
suggestedQuestionsLoading: 'Загрузка предложений...',
inputPlaceholder: 'Введите ваше сообщение...',
send: 'Отправить',
thinking: 'Думаю...',
+2
View File
@@ -297,6 +297,8 @@ export default {
chat: {
title: "对话",
newChat: "新对话",
suggestedQuestions: "你可以这样问我",
suggestedQuestionsLoading: "正在加载推荐问题...",
inputPlaceholder: "请输入您的消息...",
send: "发送",
thinking: "思考中...",
+173
View File
@@ -2,6 +2,25 @@
<div class="chat">
<div ref="scrollContainer" class="chat_scroll_box" @scroll="handleScroll">
<div class="msg_list">
<!-- 推荐问题卡片 - 仅在新会话(无消息)时展示 -->
<div v-if="messagesList.length === 0 && !loading" class="suggested-questions-container" :class="{ 'has-questions': suggestedQuestions.length > 0 }">
<transition name="sq-fade">
<div v-if="suggestedQuestions.length > 0" class="suggested-questions-inner">
<div class="suggested-questions-title">{{ t('chat.suggestedQuestions') }}</div>
<div class="suggested-questions-grid">
<div
v-for="(item, index) in suggestedQuestions"
:key="item.question"
class="suggested-question-card"
@click="handleSuggestedQuestionClick(item.question)"
>
<span class="suggested-question-text">{{ item.question }}</span>
<span v-if="item.source === 'faq'" class="suggested-question-badge faq">FAQ</span>
</div>
</div>
</div>
</transition>
</div>
<div v-for="(session, id) in messagesList" :key='id'>
<div v-if="session.role == 'user'">
<usermsg :content="session.content" :mentioned_items="session.mentioned_items" :images="session.images"></usermsg>
@@ -48,6 +67,7 @@ import InputField from '../../components/Input-field.vue';
import botmsg from './components/botmsg.vue';
import usermsg from './components/usermsg.vue';
import { getMessageList, generateSessionsTitle, getSession } from "@/api/chat/index";
import { getSuggestedQuestions } from "@/api/agent/index";
import { useStream } from '../../api/chat/streame'
import { useMenuStore } from '@/stores/menu';
import { useSettingsStore } from '@/stores/settings';
@@ -83,6 +103,68 @@ const handleKBEditorSuccess = (kbId) => {
navigateToKnowledgeBaseList(kbId)
}
// ===== 推荐问题 =====
const suggestedQuestions = ref([]);
const suggestedQuestionsLoading = ref(false);
let suggestedQuestionsFetchId = 0; // 用于取消过时的请求
let suggestedDebounceTimer = null;
const fetchSuggestedQuestions = async () => {
const fetchId = ++suggestedQuestionsFetchId;
suggestedQuestionsLoading.value = true;
// 加载期间保留旧数据,不清空,避免布局抖动
try {
const agentId = useSettingsStoreInstance.selectedAgentId;
if (!agentId) return;
const selectedKBs = useSettingsStoreInstance.getSelectedKnowledgeBases();
const selectedFiles = useSettingsStoreInstance.getSelectedFiles();
const res = await getSuggestedQuestions(agentId, {
knowledge_base_ids: selectedKBs.length > 0 ? selectedKBs : undefined,
knowledge_ids: selectedFiles.length > 0 ? selectedFiles : undefined,
limit: 6,
});
if (fetchId === suggestedQuestionsFetchId) {
suggestedQuestions.value = res?.data?.questions || [];
}
} catch (err) {
console.warn('[SuggestedQuestions] Failed to fetch:', err);
if (fetchId === suggestedQuestionsFetchId) {
suggestedQuestions.value = [];
}
} finally {
if (fetchId === suggestedQuestionsFetchId) {
suggestedQuestionsLoading.value = false;
}
}
};
const handleSuggestedQuestionClick = (question) => {
// 触发发送消息
sendMsg(question);
};
// 防抖包装,切换知识库/文件时300ms内不重复请求
const debouncedFetchSuggestions = () => {
if (suggestedDebounceTimer) clearTimeout(suggestedDebounceTimer);
suggestedDebounceTimer = setTimeout(() => { fetchSuggestedQuestions(); }, 300);
};
// 监听 Agent / 知识库 / 文件切换,重新获取推荐问题
watch(
() => useSettingsStoreInstance.selectedAgentId,
debouncedFetchSuggestions,
);
watch(
() => useSettingsStoreInstance.settings.selectedKnowledgeBases,
debouncedFetchSuggestions,
{ deep: true },
);
watch(
() => useSettingsStoreInstance.settings.selectedFiles,
debouncedFetchSuggestions,
{ deep: true },
);
function fileToBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
@@ -1002,6 +1084,9 @@ onMounted(async () => {
}
getmsgList(data)
}
// 初始加载推荐问题
fetchSuggestedQuestions();
})
const clearData = () => {
stopStream();
@@ -1132,4 +1217,92 @@ onBeforeRouteUpdate((to, from, next) => {
transform: translateY(-8px);
}
}
.suggested-questions-container {
display: flex;
flex-direction: column;
align-items: center;
padding: 32px 16px 16px;
max-width: 800px;
margin: 0 auto;
width: 100%;
min-height: 0;
transition: min-height 0.3s ease;
&.has-questions {
min-height: 80px;
}
}
.suggested-questions-inner {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
}
.sq-fade-enter-active,
.sq-fade-leave-active {
transition: opacity 0.25s ease;
}
.sq-fade-enter-from,
.sq-fade-leave-to {
opacity: 0;
}
.suggested-questions-title {
font-size: 14px;
color: var(--td-text-color-secondary);
margin-bottom: 16px;
font-weight: 500;
}
.suggested-questions-grid {
display: flex;
flex-wrap: wrap;
gap: 10px;
justify-content: center;
width: 100%;
}
.suggested-question-card {
display: flex;
align-items: center;
gap: 6px;
padding: 10px 16px;
border-radius: 20px;
border: 1px solid var(--td-component-stroke);
background: var(--td-bg-color-container);
cursor: pointer;
transition: all 0.2s ease;
max-width: 100%;
&:hover {
border-color: var(--td-brand-color);
background: var(--td-brand-color-light);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}
}
.suggested-question-text {
font-size: 13px;
color: var(--td-text-color-primary);
line-height: 1.4;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.suggested-question-badge {
font-size: 10px;
padding: 1px 5px;
border-radius: 4px;
flex-shrink: 0;
font-weight: 500;
&.faq {
background: var(--td-success-color-1);
color: var(--td-success-color);
}
}
</style>
+152 -1
View File
@@ -4,6 +4,25 @@
<div class="dialogue-title">
<span>{{ $t('createChat.title') }}</span>
</div>
<!-- 推荐问题 -->
<div class="suggested-questions-container" :class="{ 'has-questions': suggestedQuestions.length > 0 }">
<transition name="fade">
<div v-if="suggestedQuestions.length > 0" class="suggested-questions-inner">
<div class="suggested-questions-title">{{ $t('chat.suggestedQuestions') }}</div>
<div class="suggested-questions-grid">
<div
v-for="(item, index) in suggestedQuestions"
:key="item.question"
class="suggested-question-card"
@click="sendMsg(item.question, '', [], [])"
>
<span class="suggested-question-text">{{ item.question }}</span>
<span v-if="item.source === 'faq'" class="suggested-question-badge faq">FAQ</span>
</div>
</div>
</div>
</transition>
</div>
<InputField @send-msg="sendMsg"></InputField>
</div>
</div>
@@ -19,9 +38,11 @@
/>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { ref, watch, onMounted } from 'vue';
import InputField from '@/components/Input-field.vue';
import { createSessions } from "@/api/chat/index";
import { getSuggestedQuestions } from "@/api/agent/index";
import type { SuggestedQuestion } from "@/api/agent/index";
import { useMenuStore } from '@/stores/menu';
import { useSettingsStore } from '@/stores/settings';
import { useUIStore } from '@/stores/ui';
@@ -39,6 +60,48 @@ const uiStore = useUIStore();
const { t } = useI18n();
const { navigateToKnowledgeBaseList } = useKnowledgeBaseCreationNavigation();
// ===== 推荐问题 =====
const suggestedQuestions = ref<SuggestedQuestion[]>([]);
let suggestedQuestionsFetchId = 0;
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
const fetchSuggestedQuestions = async () => {
const fetchId = ++suggestedQuestionsFetchId;
// 加载期间保留旧数据,不清空,避免布局抖动
try {
const agentId = settingsStore.selectedAgentId;
if (!agentId) return;
const selectedKBs = settingsStore.getSelectedKnowledgeBases();
const selectedFiles = settingsStore.getSelectedFiles();
const res = await getSuggestedQuestions(agentId, {
knowledge_base_ids: selectedKBs.length > 0 ? selectedKBs : undefined,
knowledge_ids: selectedFiles.length > 0 ? selectedFiles : undefined,
limit: 6,
});
if (fetchId === suggestedQuestionsFetchId) {
suggestedQuestions.value = res?.data?.questions || [];
}
} catch (err) {
console.warn('[SuggestedQuestions] Failed to fetch:', err);
if (fetchId === suggestedQuestionsFetchId) {
suggestedQuestions.value = [];
}
}
};
// 防抖包装,切换知识库/文件时300ms内不重复请求
const debouncedFetch = () => {
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => { fetchSuggestedQuestions(); }, 300);
};
// 监听 Agent / 知识库 / 文件切换
watch(() => settingsStore.selectedAgentId, debouncedFetch);
watch(() => settingsStore.settings.selectedKnowledgeBases, debouncedFetch, { deep: true });
watch(() => settingsStore.settings.selectedFiles, debouncedFetch, { deep: true });
onMounted(() => { fetchSuggestedQuestions(); });
const sendMsg = (value: string, modelId: string, mentionedItems: any[], imageFiles: any[] = []) => {
createNewSession(value, modelId, mentionedItems, imageFiles);
}
@@ -144,6 +207,94 @@ const handleKBEditorSuccess = (kbId: string) => {
}
}
.suggested-questions-container {
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 24px;
width: 100%;
max-width: 800px;
min-height: 0;
transition: min-height 0.3s ease;
&.has-questions {
min-height: 80px; // 有内容时保持最小高度,避免加载新数据时塌缩
}
}
.suggested-questions-inner {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
}
// 淡入淡出过渡
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.25s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
.suggested-questions-title {
font-size: 14px;
color: var(--td-text-color-secondary);
margin-bottom: 12px;
font-weight: 500;
}
.suggested-questions-grid {
display: flex;
flex-wrap: wrap;
gap: 10px;
justify-content: center;
width: 100%;
}
.suggested-question-card {
display: flex;
align-items: center;
gap: 6px;
padding: 10px 16px;
border-radius: 20px;
border: 1px solid var(--td-component-stroke);
background: var(--td-bg-color-container);
cursor: pointer;
transition: all 0.2s ease;
max-width: 100%;
&:hover {
border-color: var(--td-brand-color);
background: var(--td-brand-color-light);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}
}
.suggested-question-text {
font-size: 13px;
color: var(--td-text-color-primary);
line-height: 1.4;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.suggested-question-badge {
font-size: 10px;
padding: 1px 5px;
border-radius: 4px;
flex-shrink: 0;
font-weight: 500;
&.faq {
background: var(--td-success-color-1);
color: var(--td-success-color);
}
}
@media (max-width: 1250px) and (min-width: 1045px) {
.answers-input {
transform: translateX(-329px);
+96
View File
@@ -910,3 +910,99 @@ func (r *chunkRepository) FAQChunkDiff(
return chunksToAdd, chunksToDelete, nil
}
// ListRecommendedFAQChunks lists FAQ chunks with the recommended flag set.
// Filter by kbIDs and/or knowledgeIDs (OR relationship). At least one must be non-empty.
// Returns up to `limit` chunks sorted by updated_at descending.
func (r *chunkRepository) ListRecommendedFAQChunks(
ctx context.Context,
tenantID uint64,
kbIDs []string,
knowledgeIDs []string,
limit int,
) ([]*types.Chunk, error) {
if limit <= 0 {
limit = 10
}
if len(kbIDs) == 0 && len(knowledgeIDs) == 0 {
return nil, nil
}
var chunks []*types.Chunk
query := r.db.WithContext(ctx).
Select("id, knowledge_base_id, chunk_type, metadata, flags, updated_at").
Where("tenant_id = ? AND chunk_type = ? AND status IN ? AND is_enabled = ? AND flags & ? != 0",
tenantID, types.ChunkTypeFAQ, []int{int(types.ChunkStatusIndexed), int(types.ChunkStatusDefault)}, true, int(types.ChunkFlagRecommended))
if len(knowledgeIDs) > 0 {
// 指定了具体知识文档,直接按 knowledge_id 过滤(忽略 kbIDs)
query = query.Where("knowledge_id IN ?", knowledgeIDs)
} else {
query = query.Where("knowledge_base_id IN ?", kbIDs)
}
if err := query.
Order("updated_at DESC").
Limit(limit).
Find(&chunks).Error; err != nil {
return nil, err
}
return chunks, nil
}
// ListRecentDocumentChunksWithQuestions lists recent document chunks that have generated questions.
// Filter by kbIDs and/or knowledgeIDs (OR relationship). At least one must be non-empty.
// Returns up to `limit` chunks sorted by updated_at descending.
func (r *chunkRepository) ListRecentDocumentChunksWithQuestions(
ctx context.Context,
tenantID uint64,
kbIDs []string,
knowledgeIDs []string,
limit int,
) ([]*types.Chunk, error) {
if limit <= 0 {
limit = 10
}
if len(kbIDs) == 0 && len(knowledgeIDs) == 0 {
return nil, nil
}
var chunks []*types.Chunk
baseQuery := r.db.WithContext(ctx).
Select("id, knowledge_base_id, chunk_type, metadata, updated_at").
Where("tenant_id = ? AND chunk_type = ? AND status IN ? AND is_enabled = ?",
tenantID, types.ChunkTypeText, []int{int(types.ChunkStatusIndexed), int(types.ChunkStatusDefault)}, true)
if len(knowledgeIDs) > 0 {
// 指定了具体知识文档,直接按 knowledge_id 过滤(忽略 kbIDs)
baseQuery = baseQuery.Where("knowledge_id IN ?", knowledgeIDs)
} else {
baseQuery = baseQuery.Where("knowledge_base_id IN ?", kbIDs)
}
// Query chunks that have non-empty generated_questions in metadata
switch r.db.Name() {
case "postgres":
if err := baseQuery.
Where("metadata IS NOT NULL AND metadata::text != '{}' AND jsonb_array_length(COALESCE(metadata->'generated_questions', '[]'::jsonb)) > 0").
Order("updated_at DESC").
Limit(limit).
Find(&chunks).Error; err != nil {
return nil, err
}
case "mysql":
if err := baseQuery.
Where("metadata IS NOT NULL AND JSON_LENGTH(JSON_EXTRACT(metadata, '$.generated_questions')) > 0").
Order("updated_at DESC").
Limit(limit).
Find(&chunks).Error; err != nil {
return nil, err
}
default: // sqlite
if err := baseQuery.
Where("metadata IS NOT NULL AND json_array_length(json_extract(metadata, '$.generated_questions')) > 0").
Order("updated_at DESC").
Limit(limit).
Find(&chunks).Error; err != nil {
return nil, err
}
}
return chunks, nil
}
+192 -3
View File
@@ -3,6 +3,7 @@ package service
import (
"context"
"errors"
"sort"
"strings"
"time"
@@ -23,13 +24,21 @@ var (
// customAgentService implements the CustomAgentService interface
type customAgentService struct {
repo interfaces.CustomAgentRepository
repo interfaces.CustomAgentRepository
chunkRepo interfaces.ChunkRepository
kbService interfaces.KnowledgeBaseService
}
// NewCustomAgentService creates a new custom agent service
func NewCustomAgentService(repo interfaces.CustomAgentRepository) interfaces.CustomAgentService {
func NewCustomAgentService(
repo interfaces.CustomAgentRepository,
chunkRepo interfaces.ChunkRepository,
kbService interfaces.KnowledgeBaseService,
) interfaces.CustomAgentService {
return &customAgentService{
repo: repo,
repo: repo,
chunkRepo: chunkRepo,
kbService: kbService,
}
}
@@ -410,3 +419,183 @@ func (s *customAgentService) CopyAgent(ctx context.Context, id string) (*types.C
logger.Infof(ctx, "Agent copied successfully, source ID: %s, new ID: %s", id, newAgent.ID)
return newAgent, nil
}
// GetSuggestedQuestions returns suggested questions for the agent based on its
// associated knowledge bases.
func (s *customAgentService) GetSuggestedQuestions(
ctx context.Context,
agentID string,
kbIDs []string,
knowledgeIDs []string,
limit int,
) ([]types.SuggestedQuestion, error) {
if limit <= 0 {
limit = 6
}
// Get tenant ID from context
tenantID, ok := types.TenantIDFromContext(ctx)
if !ok {
return nil, ErrInvalidTenantID
}
// Get agent configuration
agent, err := s.GetAgentByID(ctx, agentID)
if err != nil {
return nil, err
}
var result []types.SuggestedQuestion
// 1. Add agent config suggested_prompts first (highest priority)
if len(agent.Config.SuggestedPrompts) > 0 {
for _, prompt := range agent.Config.SuggestedPrompts {
if strings.TrimSpace(prompt) == "" {
continue
}
result = append(result, types.SuggestedQuestion{
Question: prompt,
Source: "agent_config",
})
}
}
// 2. Determine knowledge base scope
effectiveKBIDs := kbIDs
if len(effectiveKBIDs) == 0 {
// Use agent's KB configuration
switch agent.Config.KBSelectionMode {
case "all":
kbs, err := s.kbService.ListKnowledgeBases(ctx)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"agent_id": agentID,
})
// Return what we have so far (agent_config suggestions)
return s.truncateQuestions(result, limit), nil
}
for _, kb := range kbs {
effectiveKBIDs = append(effectiveKBIDs, kb.ID)
}
case "selected":
effectiveKBIDs = agent.Config.KnowledgeBases
case "none":
// No KB access, return agent_config suggestions only
return s.truncateQuestions(result, limit), nil
default:
// Default to agent's configured KBs
effectiveKBIDs = agent.Config.KnowledgeBases
}
}
if len(effectiveKBIDs) == 0 && len(knowledgeIDs) == 0 {
return s.truncateQuestions(result, limit), nil
}
// Deduplicate questions we've already collected
seen := make(map[string]bool)
for _, q := range result {
seen[q.Question] = true
}
remaining := limit - len(result)
if remaining <= 0 {
return s.truncateQuestions(result, limit), nil
}
// 3. Collect all candidate chunks from both FAQ and Document KBs,
// then sort by updated_at uniformly (not FAQ-first).
type candidate struct {
question types.SuggestedQuestion
updatedAt time.Time
}
var candidates []candidate
// Determine query scope
queryKBIDs := effectiveKBIDs
queryKnowledgeIDs := knowledgeIDs
// Fetch more than needed from each source, we'll merge-sort and truncate
fetchLimit := remaining * 2
if fetchLimit < 10 {
fetchLimit = 10
}
// Collect FAQ recommended chunks
faqChunks, err := s.chunkRepo.ListRecommendedFAQChunks(ctx, tenantID, queryKBIDs, queryKnowledgeIDs, fetchLimit)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"agent_id": agentID,
})
} else {
for _, chunk := range faqChunks {
meta, err := chunk.FAQMetadata()
if err != nil || meta == nil || meta.StandardQuestion == "" {
continue
}
if seen[meta.StandardQuestion] {
continue
}
seen[meta.StandardQuestion] = true
candidates = append(candidates, candidate{
question: types.SuggestedQuestion{
Question: meta.StandardQuestion,
Source: "faq",
KnowledgeBaseID: chunk.KnowledgeBaseID,
},
updatedAt: chunk.UpdatedAt,
})
}
}
// Collect Document chunks with generated questions
docChunks, err := s.chunkRepo.ListRecentDocumentChunksWithQuestions(ctx, tenantID, queryKBIDs, queryKnowledgeIDs, fetchLimit)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"agent_id": agentID,
})
} else {
for _, chunk := range docChunks {
meta, err := chunk.DocumentMetadata()
if err != nil || meta == nil || len(meta.GeneratedQuestions) == 0 {
continue
}
q := meta.GeneratedQuestions[0].Question
if q == "" || seen[q] {
continue
}
seen[q] = true
candidates = append(candidates, candidate{
question: types.SuggestedQuestion{
Question: q,
Source: "document",
KnowledgeBaseID: chunk.KnowledgeBaseID,
},
updatedAt: chunk.UpdatedAt,
})
}
}
// 4. Sort all candidates by updated_at descending (newest first)
sort.Slice(candidates, func(i, j int) bool {
return candidates[i].updatedAt.After(candidates[j].updatedAt)
})
// 5. Pick top N
for _, c := range candidates {
if len(result) >= limit {
break
}
result = append(result, c.question)
}
return s.truncateQuestions(result, limit), nil
}
// truncateQuestions truncates the question list to the specified limit
func (s *customAgentService) truncateQuestions(questions []types.SuggestedQuestion, limit int) []types.SuggestedQuestion {
if len(questions) > limit {
return questions[:limit]
}
return questions
}
+79
View File
@@ -2,6 +2,8 @@ package handler
import (
"net/http"
"strconv"
"strings"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/errors"
@@ -376,3 +378,80 @@ func (h *CustomAgentHandler) GetPlaceholders(c *gin.Context) {
},
})
}
// GetSuggestedQuestions godoc
// @Summary 获取推荐问题
// @Description 基于智能体关联的知识库,返回推荐问题供用户快捷提问
// @Tags 智能体
// @Accept json
// @Produce json
// @Param id path string true "智能体ID"
// @Param knowledge_base_ids query string false "知识库ID列表(逗号分隔),覆盖智能体默认配置"
// @Param knowledge_ids query string false "知识ID列表(逗号分隔),限定到具体文档"
// @Param limit query int false "返回数量上限(默认6)"
// @Success 200 {object} map[string]interface{} "推荐问题列表"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 404 {object} errors.AppError "智能体不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /agents/{id}/suggested-questions [get]
func (h *CustomAgentHandler) GetSuggestedQuestions(c *gin.Context) {
ctx := c.Request.Context()
// Get agent ID from URL parameter
id := secutils.SanitizeForLog(c.Param("id"))
if id == "" {
logger.Error(ctx, "Agent ID is empty")
c.Error(errors.NewBadRequestError("Agent ID cannot be empty"))
return
}
// Parse optional query parameters
var kbIDs []string
if kbIDsStr := strings.TrimSpace(c.Query("knowledge_base_ids")); kbIDsStr != "" {
for _, id := range strings.Split(kbIDsStr, ",") {
if trimmed := strings.TrimSpace(id); trimmed != "" {
kbIDs = append(kbIDs, trimmed)
}
}
}
var knowledgeIDs []string
if kIDsStr := strings.TrimSpace(c.Query("knowledge_ids")); kIDsStr != "" {
for _, id := range strings.Split(kIDsStr, ",") {
if trimmed := strings.TrimSpace(id); trimmed != "" {
knowledgeIDs = append(knowledgeIDs, trimmed)
}
}
}
limit := 6
if limitStr := c.Query("limit"); limitStr != "" {
if parsed, err := strconv.Atoi(limitStr); err == nil && parsed > 0 {
limit = parsed
}
}
logger.Infof(ctx, "Getting suggested questions for agent %s, kbIDs: %v, limit: %d",
secutils.SanitizeForLog(id), kbIDs, limit)
questions, err := h.service.GetSuggestedQuestions(ctx, id, kbIDs, knowledgeIDs, limit)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"agent_id": id,
})
if err == service.ErrAgentNotFound {
c.Error(errors.NewNotFoundError("Agent not found"))
return
}
c.Error(errors.NewInternalServerError(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"questions": questions,
},
})
}
+2
View File
@@ -491,6 +491,8 @@ func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomA
// Copy agent
agents.POST("/:id/copy", agentHandler.CopyAgent)
}
// Registered outside the group to avoid Gin route conflict with /agents/:id/shares in organization routes
r.GET("/agents/:id/suggested-questions", agentHandler.GetSuggestedQuestions)
}
// RegisterSkillRoutes registers skill routes
+14
View File
@@ -175,6 +175,10 @@ type CustomAgentConfig struct {
FallbackResponse string `yaml:"fallback_response" json:"fallback_response"`
// Fallback prompt (when FallbackStrategy is "model")
FallbackPrompt string `yaml:"fallback_prompt" json:"fallback_prompt"`
// ===== Suggested Prompts =====
// 推荐问题列表,用于在前端对话面板展示快捷提问
SuggestedPrompts []string `yaml:"suggested_prompts" json:"suggested_prompts,omitempty"`
}
// Value implements driver.Valuer interface for CustomAgentConfig
@@ -255,6 +259,16 @@ func (a *CustomAgent) IsAgentMode() bool {
return a.Config.AgentMode == AgentModeSmartReasoning
}
// SuggestedQuestion 推荐问题
type SuggestedQuestion struct {
// 问题文本
Question string `json:"question"`
// 来源类型: "faq", "document", "agent_config"
Source string `json:"source"`
// 来源知识库ID(仅 faq/document 来源时有值)
KnowledgeBaseID string `json:"knowledge_base_id,omitempty"`
}
// BuiltinAgentRegistry provides a registry of all built-in agents.
// It is initialised empty and populated by LoadBuiltinAgentsConfig from
// config/builtin_agents.yaml at startup via rebuildRegistryFromConfig.
+10
View File
@@ -89,6 +89,16 @@ type ChunkRepository interface {
// FAQChunkDiff compares FAQ chunks between two knowledge bases and returns the differences.
// Returns: chunksToAdd (content_hash in src but not in dst), chunksToDelete (content_hash in dst but not in src)
FAQChunkDiff(ctx context.Context, srcTenantID uint64, srcKBID string, dstTenantID uint64, dstKBID string) (chunksToAdd []string, chunksToDelete []string, err error)
// ListRecommendedFAQChunks lists FAQ chunks with the recommended flag set.
// Filter by kbIDs and/or knowledgeIDs. At least one of them must be non-empty.
// Returns up to `limit` chunks sorted by updated_at descending.
ListRecommendedFAQChunks(ctx context.Context, tenantID uint64, kbIDs []string, knowledgeIDs []string, limit int) ([]*types.Chunk, error)
// ListRecentDocumentChunksWithQuestions lists recent document chunks that have generated questions.
// Filter by kbIDs and/or knowledgeIDs. At least one of them must be non-empty.
// Returns up to `limit` chunks sorted by updated_at descending.
ListRecentDocumentChunksWithQuestions(ctx context.Context, tenantID uint64, kbIDs []string, knowledgeIDs []string, limit int) ([]*types.Chunk, error)
}
// ChunkService defines the interface for chunk service operations
+14
View File
@@ -64,6 +64,20 @@ type CustomAgentService interface {
// - The newly created agent copy
// - Possible errors such as not existing, insufficient permissions, etc.
CopyAgent(ctx context.Context, id string) (*types.CustomAgent, error)
// GetSuggestedQuestions returns suggested questions for the agent based on its
// associated knowledge bases. When kbIDs or knowledgeIDs are provided, they override
// the agent's default knowledge base selection.
// Parameters:
// - ctx: Context information
// - agentID: Agent ID
// - kbIDs: Optional knowledge base IDs to override agent config
// - knowledgeIDs: Optional knowledge item IDs to further filter
// - limit: Maximum number of questions to return
// Returns:
// - List of suggested questions
// - Possible errors
GetSuggestedQuestions(ctx context.Context, agentID string, kbIDs []string, knowledgeIDs []string, limit int) ([]types.SuggestedQuestion, error)
}
// CustomAgentRepository defines the custom agent repository interface