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);