feat(agent): add question suggestions with after-answer follow-ups

Enable agents to configure starter prompts and async follow-up questions after completed answers, with durable caching, analytics events, and chat/embed UI integration.
This commit is contained in:
wizardchen
2026-07-14 11:06:13 +08:00
committed by lyingbug
parent a6c85dad28
commit 087fcc9fe7
50 changed files with 3781 additions and 179 deletions
+23 -1
View File
@@ -8,6 +8,28 @@ import { get, post, put, del } from "../../utils/request";
// 'custom' : 完全自定义(不应用预设)
export type AgentType = 'rag-qa' | 'wiki-qa' | 'hybrid-rag-wiki' | 'data-analysis' | 'custom';
export interface QuestionSuggestionConfig {
starters: {
enabled: boolean;
mode: 'curated' | 'knowledge' | 'hybrid';
items: string[];
count: number;
};
follow_ups: {
enabled: boolean;
mode: 'generated' | 'knowledge' | 'hybrid';
count: number;
model_id?: string;
additional_instruction?: string;
categories: Array<'clarify' | 'deepen' | 'action'>;
max_context_turns: number;
suppress_on_fallback: boolean;
suppress_when_answer_asks_question: boolean;
knowledge_fallback: boolean;
allow_regenerate: boolean;
};
}
export interface CustomAgentConfig {
// ===== 基础设置 =====
agent_mode?: 'quick-answer' | 'smart-reasoning'; // 运行模式:quick-answer=RAG模式, smart-reasoning=ReAct Agent模式
@@ -92,7 +114,7 @@ export interface CustomAgentConfig {
// ===== 已废弃字段(保留兼容)=====
welcome_message?: string;
suggested_prompts?: string[];
question_suggestions?: QuestionSuggestionConfig;
}
// 智能体
+4 -1
View File
@@ -36,7 +36,7 @@ export function useStream() {
let renderTimer: number | null = null
// 启动流式请求
const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; tag_ids?: string[]; agent_enabled?: boolean; agent_id?: string; web_search_enabled?: boolean; enable_memory?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; skill_names?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string; kb_id?: string; kb_name?: string; service_id?: string; skill_name?: string}>; images?: Array<{data: string}>; attachment_uploads?: Array<{data: string; file_name: string; file_size: number}>; method: string; url: string; embed_token?: string; embed_session_sig?: string; embed_visitor_id?: string }) => {
const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; tag_ids?: string[]; agent_enabled?: boolean; agent_id?: string; web_search_enabled?: boolean; enable_memory?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; skill_names?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string; kb_id?: string; kb_name?: string; service_id?: string; skill_name?: string}>; images?: Array<{data: string}>; attachment_uploads?: Array<{data: string; file_name: string; file_size: number}>; suggestion_attribution?: { suggestion_set_id: string; question_id: string }; method: string; url: string; embed_token?: string; embed_session_sig?: string; embed_visitor_id?: string }) => {
const myGeneration = ++streamGeneration
// 重置状态
output.value = '';
@@ -133,6 +133,9 @@ export function useStream() {
if (params.attachment_uploads !== undefined && params.attachment_uploads.length > 0) {
postBody.attachment_uploads = params.attachment_uploads;
}
if (params.suggestion_attribution) {
postBody.suggestion_attribution = params.suggestion_attribution;
}
postBody.channel = embedToken ? "embed" : "web";
lastStreamRequest.value = {
+61
View File
@@ -170,6 +170,20 @@ export interface SuggestedQuestion {
source?: string
}
export interface EmbedMessageSuggestionItem {
id: string
text: string
category?: string
source: string
}
export interface EmbedMessageSuggestionSet {
id: string
status: 'generating' | 'ready' | 'suppressed' | 'failed'
allow_regenerate: boolean
questions: EmbedMessageSuggestionItem[]
}
export async function getEmbedChunkById(channelId: string, token: string, chunkId: string) {
return get<{ success: boolean; data: { content?: string } }>(
`/api/v1/embed/${channelId}/chunks/${chunkId}`,
@@ -184,6 +198,53 @@ export async function getEmbedSuggestedQuestions(channelId: string, token: strin
)
}
export async function ensureEmbedMessageSuggestions(
channelId: string,
token: string,
sessionId: string,
messageId: string,
sessionSig: string,
visitorId: string,
regenerate = false,
) {
return post<{ success: boolean; data: EmbedMessageSuggestionSet }>(
`/api/v1/embed/${channelId}/sessions/${sessionId}/messages/${messageId}/suggestions`,
{ regenerate },
{ headers: embedSessionHeaders(token, sessionSig, visitorId) },
)
}
export async function getEmbedMessageSuggestions(
channelId: string,
token: string,
sessionId: string,
messageId: string,
sessionSig: string,
visitorId: string,
) {
return get<{ success: boolean; data: EmbedMessageSuggestionSet }>(
`/api/v1/embed/${channelId}/sessions/${sessionId}/messages/${messageId}/suggestions`,
{ headers: embedSessionHeaders(token, sessionSig, visitorId) },
)
}
export async function recordEmbedMessageSuggestionEvent(
channelId: string,
token: string,
sessionId: string,
sessionSig: string,
visitorId: string,
suggestionSetId: string,
eventType: 'impression' | 'click' | 'dismiss',
questionId = '',
) {
return post(
`/api/v1/embed/${channelId}/sessions/${sessionId}/suggestion-events`,
{ suggestion_set_id: suggestionSetId, question_id: questionId, event_type: eventType },
{ headers: embedSessionHeaders(token, sessionSig, visitorId) },
)
}
export async function getEmbedConfig(channelId: string, token: string) {
return get<{ success: boolean; data: EmbedChannelPublicConfig }>(
`/api/v1/embed/${channelId}/config`,
+45
View File
@@ -0,0 +1,45 @@
import { get, post } from '@/utils/request'
export interface MessageSuggestionItem {
id: string
text: string
category?: 'clarify' | 'deepen' | 'action'
source: 'model' | 'faq' | 'document' | 'wiki' | string
knowledge_base_ids?: string[]
}
export interface MessageSuggestionSet {
id: string
session_id: string
assistant_message_id: string
status: 'generating' | 'ready' | 'suppressed' | 'failed'
allow_regenerate: boolean
suppression_reason?: string
questions: MessageSuggestionItem[]
generated_at?: string
}
export function ensureMessageSuggestions(sessionId: string, messageId: string, regenerate = false) {
return post<{ data: MessageSuggestionSet }>(
`/api/v1/sessions/${sessionId}/messages/${messageId}/suggestions`,
{ regenerate },
)
}
export function getMessageSuggestions(sessionId: string, messageId: string) {
return get<{ data: MessageSuggestionSet }>(
`/api/v1/sessions/${sessionId}/messages/${messageId}/suggestions`,
)
}
export function recordMessageSuggestionEvent(
sessionId: string,
suggestionSetId: string,
eventType: 'impression' | 'click' | 'dismiss',
questionId = '',
) {
return post(
`/api/v1/sessions/${sessionId}/suggestion-events`,
{ suggestion_set_id: suggestionSetId, question_id: questionId, event_type: eventType },
)
}
@@ -0,0 +1,144 @@
<template>
<div v-if="loading || suggestionSet?.status === 'ready'" class="follow-ups" aria-live="polite">
<div class="follow-ups__header">
<span>{{ t('chat.followUpQuestions') }}</span>
<div class="follow-ups__actions">
<button v-if="allowRegenerate" type="button" :disabled="loading" @click="emit('regenerate')">
<t-icon :name="loading ? 'loading' : 'refresh'" :class="{ 'is-spinning': loading }" />
<span>{{ t('chat.refreshSuggestedQuestions') }}</span>
</button>
<button type="button" :aria-label="t('common.close')" @click="dismiss">
<t-icon name="close" />
</button>
</div>
</div>
<div v-if="loading && !suggestionSet?.questions?.length" class="follow-ups__skeletons">
<span v-for="n in 3" :key="n" :style="{ width: skeletonWidths[n - 1] }" />
</div>
<div v-else class="follow-ups__list">
<button v-for="item in suggestionSet?.questions || []" :key="item.id" type="button"
class="follow-ups__item" @click="emit('select', item)">
<span>{{ item.text }}</span>
<t-icon name="arrow-up-right" />
</button>
</div>
</div>
</template>
<script setup lang="ts">
import { watch } from 'vue'
import { useI18n } from 'vue-i18n'
import type { MessageSuggestionItem, MessageSuggestionSet } from '@/api/message-suggestion'
const props = defineProps<{
suggestionSet?: MessageSuggestionSet | null
loading?: boolean
allowRegenerate?: boolean
}>()
const emit = defineEmits<{
(event: 'select', item: MessageSuggestionItem): void
(event: 'regenerate'): void
(event: 'impression', set: MessageSuggestionSet): void
(event: 'dismiss', set: MessageSuggestionSet): void
}>()
const { t } = useI18n()
const impressed = new Set<string>()
const skeletonWidths = ['92%', '78%', '85%']
watch(
() => props.suggestionSet,
(set) => {
if (set?.status === 'ready' && set.questions.length > 0 && !impressed.has(set.id)) {
impressed.add(set.id)
emit('impression', set)
}
},
{ immediate: true },
)
const dismiss = () => {
if (props.suggestionSet) emit('dismiss', props.suggestionSet)
}
</script>
<style scoped lang="less">
.follow-ups {
max-width: 760px;
margin: -4px 0 28px 46px;
padding: 12px;
border: 1px solid var(--td-component-stroke);
border-radius: 12px;
background: var(--td-bg-color-secondarycontainer);
}
.follow-ups__header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
color: var(--td-text-color-secondary);
font-size: 13px;
font-weight: 600;
}
.follow-ups__actions { display: flex; gap: 4px; }
.follow-ups__actions button {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 4px 8px;
border: 0;
border-radius: 6px;
background: transparent;
color: var(--td-text-color-secondary);
cursor: pointer;
transition: background-color .2s, color .2s;
}
.follow-ups__actions button:hover:not(:disabled) {
background: var(--td-bg-color-container-hover, rgba(0, 0, 0, .06));
color: var(--td-brand-color);
}
.follow-ups__actions button:disabled {
cursor: not-allowed;
opacity: .6;
}
.follow-ups__list { display: flex; flex-direction: column; gap: 6px; }
.follow-ups__item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
width: 100%;
padding: 9px 11px;
border: 1px solid transparent;
border-radius: 8px;
background: var(--td-bg-color-container);
color: var(--td-text-color-primary);
text-align: left;
cursor: pointer;
}
.follow-ups__item { transition: border-color .2s, box-shadow .2s, transform .2s; }
.follow-ups__item:hover {
border-color: var(--td-brand-color);
box-shadow: 0 4px 14px rgba(0, 0, 0, .12);
transform: translateY(-1px);
}
.follow-ups__item:hover .t-icon { color: var(--td-brand-color); }
.follow-ups__skeletons { display: flex; flex-direction: column; gap: 6px; }
.follow-ups__skeletons span {
height: 38px;
border-radius: 8px;
background: linear-gradient(
100deg,
var(--td-bg-color-component) 30%,
var(--td-bg-color-container-hover, rgba(255, 255, 255, .35)) 50%,
var(--td-bg-color-component) 70%
);
background-size: 200% 100%;
animation: shimmer 3s ease-in-out infinite;
}
.is-spinning { animation: spin 1s linear infinite; }
@keyframes shimmer {
0% { background-position: 200% 0; }
100% { background-position: -200% 0; }
}
@keyframes spin { to { transform: rotate(360deg); } }
</style>
@@ -13,6 +13,7 @@ export interface UseChatStreamHandlerOptions {
isAgentStreamSession: () => boolean
scrollToBottom: (force?: boolean) => void
onReplyComplete?: (content: string) => void
onTurnComplete?: (message: ChatMessage) => void
onError?: (message: string) => void
/** Main chat: keep the last incomplete message reactive for continue-stream. */
preserveIncompleteStreamReactive?: boolean
@@ -42,6 +43,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
isAgentStreamSession,
scrollToBottom,
onReplyComplete,
onTurnComplete,
onError,
preserveIncompleteStreamReactive = false,
isFirstEnter,
@@ -808,6 +810,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
isReplying.value = false
message.is_completed = true
onReplyComplete?.(String(message.content || ''))
onTurnComplete?.(message)
fullContent.value = ''
currentAssistantMessageId.value = ''
if (message.agentEventStream) {
@@ -1003,6 +1006,10 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
currentAssistantMessageId.value = ''
}
updateAssistantSession(obj)
if (data.done) {
const completed = resolveActiveAssistantMessage(data) || obj
onTurnComplete?.(completed)
}
}
return {
@@ -35,6 +35,8 @@ export function useEmbedChatSession(options: {
hostContext?: Ref<Record<string, unknown>>
onMessagesChange?: (has: boolean) => void
onSessionTitle?: (title: string) => void
onTurnComplete?: (message: Record<string, unknown>) => void
onMessagesLoaded?: (messages: Record<string, unknown>[]) => void
}) {
const { t } = useI18n()
const { onChunk, error, startStream, stopStream } = useStream()
@@ -59,6 +61,7 @@ export function useEmbedChatSession(options: {
const hasMoreHistory = ref(true)
const created_at = ref('')
const fullContent = ref('')
let pendingSuggestionAttribution: { suggestion_set_id: string; question_id: string } | null = null
const scrollContainer = ref<HTMLElement | null>(null)
const userHasScrolledUp = ref(false)
const SCROLL_BOTTOM_THRESHOLD = 80
@@ -130,6 +133,8 @@ export function useEmbedChatSession(options: {
isAgentStreamSession,
scrollToBottom,
onReplyComplete: notifyEmbedReceived,
onTurnComplete: options.onTurnComplete,
onAfterMsgList: () => options.onMessagesLoaded?.(messagesList),
onError: embedToast,
isFirstEnter,
scrollContainer,
@@ -298,6 +303,8 @@ export function useEmbedChatSession(options: {
? `/api/v1/embed/${options.channelId}/agent-chat`
: `/api/v1/embed/${options.channelId}/knowledge-chat`
const suggestionAttribution = pendingSuggestionAttribution
pendingSuggestionAttribution = null
await startStream({
session_id: options.sessionId.value,
knowledge_base_ids: options.kbIds,
@@ -312,6 +319,7 @@ export function useEmbedChatSession(options: {
images: imageAttachments.length > 0 ? imageAttachments : undefined,
attachment_uploads: attachmentUploads.length > 0 ? attachmentUploads : undefined,
query: outboundQuery,
suggestion_attribution: suggestionAttribution || undefined,
method: 'POST',
url: endpoint,
embed_token: options.token,
@@ -391,5 +399,8 @@ export function useEmbedChatSession(options: {
onClickScrollToBottom,
sendMsg,
handleStopGeneration,
setSuggestionAttribution: (suggestionSetId: string, questionId: string) => {
pendingSuggestionAttribution = { suggestion_set_id: suggestionSetId, question_id: questionId }
},
}
}
+8
View File
@@ -77,6 +77,8 @@ const messages = {
"newChat": "新对话",
"suggestedQuestions": "你可以这样问我",
"suggestedQuestionsLoading": "正在加载推荐问题...",
"followUpQuestions": "接下来可以继续问",
"refreshSuggestedQuestions": "换一批推荐问题",
"inputPlaceholder": "请输入您的消息...",
"send": "发送",
"thinking": "思考中...",
@@ -550,6 +552,8 @@ const messages = {
"newChat": "New Chat",
"suggestedQuestions": "You can ask me",
"suggestedQuestionsLoading": "Loading suggestions...",
"followUpQuestions": "Continue with a follow-up",
"refreshSuggestedQuestions": "Refresh suggestions",
"inputPlaceholder": "Enter your message...",
"send": "Send",
"thinking": "Thinking...",
@@ -1008,6 +1012,8 @@ const koEmbedPublish = {
},
chat: {
suggestedQuestions: '이렇게 물어보세요',
followUpQuestions: '이어서 질문해 보세요',
refreshSuggestedQuestions: '추천 질문 새로고침',
imageTooMany: '이미지는 최대 5장까지 업로드할 수 있습니다',
imageTypeSizeError: 'JPG/PNG/GIF/WEBP만 지원하며, 각 파일은 10MB 이하여야 합니다',
imageReadFailed: '이미지를 읽지 못했습니다',
@@ -1091,6 +1097,8 @@ const ruEmbedPublish = {
},
chat: {
suggestedQuestions: 'Вы можете спросить так',
followUpQuestions: 'Продолжите уточняющим вопросом',
refreshSuggestedQuestions: 'Обновить предложения',
imageTooMany: 'Можно загрузить не более 5 изображений',
imageTypeSizeError: 'Поддерживаются только JPG/PNG/GIF/WEBP, каждый файл до 10 МБ',
imageReadFailed: 'Не удалось прочитать изображение',
+36
View File
@@ -3081,6 +3081,7 @@ export default {
title: 'Chat',
newChat: 'New Chat',
suggestedQuestions: 'You can ask me',
followUpQuestions: 'Continue with a follow-up',
suggestedQuestionsLoading: 'Loading suggestions...',
refreshSuggestedQuestions: 'Refresh suggestions',
inputPlaceholder: 'Enter your message...',
@@ -5487,6 +5488,41 @@ export default {
capability: 'Extensions',
integration: 'Publish & Integrations',
},
questionSuggestions: {
navLabel: 'Question suggestions',
title: 'Conversation question suggestions',
description: 'Configure starters and contextual follow-ups in one agent-owned policy. Channels may hide them but cannot override the policy.',
startersTitle: 'Conversation starters',
followUpsTitle: 'After-answer follow-ups',
enableStarters: 'Show starter questions',
enableStartersDesc: 'Shown before the first user message from curated, knowledge, or mixed sources.',
enableFollowUps: 'Generate follow-up questions',
enableFollowUpsDesc: 'Generated asynchronously after every completed answer. Enabling this adds model usage.',
sourceMode: 'Source mode',
count: 'Question count',
curatedItems: 'Curated questions',
curatedItemsDesc: 'Used for starters and prioritized in hybrid mode.',
addItem: 'Add question',
model: 'Generation model',
modelDesc: 'Uses the model from the completed turn when empty.',
advancedSettings: 'Advanced generation settings',
advancedSettingsDesc: 'Context, question types, instructions, and display rules',
displayRules: 'Display and fallback rules',
contextTurns: 'Context turns',
categories: 'Question types',
instruction: 'Additional instruction',
suppressFallback: 'Hide after fallback answers',
suppressQuestion: 'Hide when the answer ends with a question',
knowledgeFallback: 'Use knowledge candidates if generation fails',
allowRegenerate: 'Allow users to regenerate',
modeCurated: 'Curated',
modeKnowledge: 'Knowledge',
modeGenerated: 'Generated',
modeHybrid: 'Hybrid',
categoryClarify: 'Clarify',
categoryDeepen: 'Deepen',
categoryAction: 'Next step',
},
placeholders: {
available: 'Available variables: ',
clickToInsert: '(click to insert)',
+19
View File
@@ -895,6 +895,7 @@ export default {
title: "대화",
newChat: "새 대화",
suggestedQuestions: "이렇게 물어보세요",
followUpQuestions: "이어서 질문해 보세요",
suggestedQuestionsLoading: "추천 질문 로딩 중...",
refreshSuggestedQuestions: "추천 질문 새로고침",
inputPlaceholder: "메시지를 입력하세요...",
@@ -5498,6 +5499,24 @@ export default {
capability: '기능 확장',
integration: '게시 및 통합',
},
questionSuggestions: {
navLabel: '질문 추천', title: '대화 질문 추천',
description: '대화 시작 질문과 답변 후 후속 질문을 에이전트 정책으로 통합 설정합니다.',
startersTitle: '시작 질문', followUpsTitle: '답변 후 후속 질문',
enableStarters: '시작 질문 표시', enableStartersDesc: '첫 질문 전에 운영 설정 또는 지식 기반 질문을 표시합니다.',
enableFollowUps: '후속 질문 생성', enableFollowUpsDesc: '완료된 답변마다 비동기로 생성하며 추가 모델 사용량이 발생합니다.',
sourceMode: '콘텐츠 소스', count: '표시 개수', curatedItems: '운영 설정 질문',
curatedItemsDesc: '혼합 모드에서 우선 표시됩니다.', addItem: '질문 추가',
model: '생성 모델', modelDesc: '비워 두면 현재 대화 모델을 사용합니다.',
advancedSettings: '고급 생성 설정',
advancedSettingsDesc: '컨텍스트, 질문 유형, 생성 지침 및 표시 규칙',
displayRules: '표시 및 폴백 규칙',
contextTurns: '컨텍스트 턴 수', categories: '질문 유형', instruction: '추가 생성 지침',
suppressFallback: '대체 답변 뒤에는 숨기기', suppressQuestion: '답변이 질문으로 끝나면 숨기기',
knowledgeFallback: '생성 실패 시 지식 후보 사용', allowRegenerate: '새 질문 묶음 허용',
modeCurated: '운영 설정', modeKnowledge: '지식 기반', modeGenerated: '모델 생성', modeHybrid: '혼합',
categoryClarify: '명확화', categoryDeepen: '심화', categoryAction: '다음 단계',
},
placeholders: {
available: '사용 가능한 변수: ',
clickToInsert: '(클릭하여 삽입)',
+19
View File
@@ -3663,6 +3663,7 @@ export default {
title: 'Диалог',
newChat: 'Новый чат',
suggestedQuestions: 'Вы можете спросить меня',
followUpQuestions: 'Продолжите уточняющим вопросом',
suggestedQuestionsLoading: 'Загрузка предложений...',
refreshSuggestedQuestions: 'Обновить предложения',
inputPlaceholder: 'Введите ваше сообщение...',
@@ -4998,6 +4999,24 @@ export default {
capability: 'Расширения',
integration: 'Публикация и интеграция',
},
questionSuggestions: {
navLabel: 'Рекомендуемые вопросы', title: 'Рекомендации вопросов в диалоге',
description: 'Единая политика агента для стартовых и контекстных вопросов после ответа.',
startersTitle: 'Стартовые вопросы', followUpsTitle: 'Вопросы после ответа',
enableStarters: 'Показывать стартовые вопросы', enableStartersDesc: 'Показываются до первого сообщения пользователя.',
enableFollowUps: 'Генерировать уточнения', enableFollowUpsDesc: 'Создаются асинхронно после каждого полного ответа и расходуют модель.',
sourceMode: 'Источник', count: 'Количество', curatedItems: 'Редакторские вопросы',
curatedItemsDesc: 'Имеют приоритет в гибридном режиме.', addItem: 'Добавить вопрос',
model: 'Модель генерации', modelDesc: 'Если не выбрана, используется модель текущего ответа.',
advancedSettings: 'Расширенные настройки генерации',
advancedSettingsDesc: 'Контекст, типы вопросов, инструкции и правила показа',
displayRules: 'Правила показа и резерва',
contextTurns: 'Ходы контекста', categories: 'Типы вопросов', instruction: 'Дополнительная инструкция',
suppressFallback: 'Скрывать после резервного ответа', suppressQuestion: 'Скрывать, если ответ заканчивается вопросом',
knowledgeFallback: 'Использовать базу знаний при ошибке', allowRegenerate: 'Разрешить обновление',
modeCurated: 'Редакторские', modeKnowledge: 'База знаний', modeGenerated: 'Модель', modeHybrid: 'Гибрид',
categoryClarify: 'Уточнение', categoryDeepen: 'Углубление', categoryAction: 'Следующий шаг',
},
placeholders: {
available: 'Доступные переменные: ',
clickToInsert: '(нажмите для вставки)',
+36
View File
@@ -893,6 +893,7 @@ export default {
title: "对话",
newChat: "新对话",
suggestedQuestions: "你可以这样问我",
followUpQuestions: "接下来可以继续问",
suggestedQuestionsLoading: "正在加载推荐问题...",
refreshSuggestedQuestions: "换一批推荐问题",
inputPlaceholder: "请输入您的消息...",
@@ -5504,6 +5505,41 @@ export default {
capability: "能力扩展",
integration: "发布集成",
},
questionSuggestions: {
navLabel: "问题推荐",
title: "对话问题推荐",
description: "统一配置开场问题与回答后的上下文追问;渠道可关闭展示,但不能改写智能体策略。",
startersTitle: "开场推荐",
followUpsTitle: "回答后推荐",
enableStarters: "展示开场问题",
enableStartersDesc: "在用户首次提问前展示,可使用运营配置、知识库或混合来源。",
enableFollowUps: "生成回答后推荐",
enableFollowUpsDesc: "每次完整回答结束后异步生成,不阻塞主回答。启用后会产生额外模型调用。",
sourceMode: "内容来源",
count: "展示数量",
curatedItems: "运营配置问题",
curatedItemsDesc: "用于开场推荐;混合模式下优先展示。",
addItem: "添加问题",
model: "生成模型",
modelDesc: "留空时使用本轮对话模型。",
advancedSettings: "高级生成设置",
advancedSettingsDesc: "上下文、问题类型、生成要求与展示规则",
displayRules: "展示与兜底规则",
contextTurns: "上下文轮数",
categories: "问题类型",
instruction: "附加生成要求",
suppressFallback: "兜底回答后不展示",
suppressQuestion: "回答本身以提问结尾时不展示",
knowledgeFallback: "模型生成失败时使用知识库候选",
allowRegenerate: "允许用户换一批",
modeCurated: "运营配置",
modeKnowledge: "知识库",
modeGenerated: "模型生成",
modeHybrid: "混合",
categoryClarify: "澄清",
categoryDeepen: "深入",
categoryAction: "下一步",
},
placeholders: {
available: "可用变量:",
clickToInsert: "(点击插入)",
+316 -7
View File
@@ -825,6 +825,187 @@
</div>
</div>
<!-- 对话问题推荐 -->
<div v-show="currentSection === 'suggestions'" class="section">
<div class="section-header">
<h2>{{ $t('agentEditor.questionSuggestions.title') }}</h2>
<p class="section-description">{{ $t('agentEditor.questionSuggestions.description') }}</p>
</div>
<t-tabs v-model="suggestionTab" class="suggestion-tabs">
<t-tab-panel value="starters"
:label="$t('agentEditor.questionSuggestions.startersTitle')" />
<t-tab-panel value="followUps"
:label="$t('agentEditor.questionSuggestions.followUpsTitle')" />
</t-tabs>
<div v-show="suggestionTab === 'starters'" class="settings-group">
<div class="setting-row">
<div class="setting-info">
<label>{{ $t('agentEditor.questionSuggestions.enableStarters') }}</label>
<p class="desc">{{ $t('agentEditor.questionSuggestions.enableStartersDesc') }}</p>
</div>
<div class="setting-control">
<t-switch v-model="formData.config.question_suggestions.starters.enabled"
:aria-label="$t('agentEditor.questionSuggestions.enableStarters')" />
</div>
</div>
<div v-if="formData.config.question_suggestions.starters.enabled" class="setting-row">
<div class="setting-info">
<label>{{ $t('agentEditor.questionSuggestions.sourceMode') }}</label>
</div>
<div class="setting-control">
<t-select v-model="formData.config.question_suggestions.starters.mode"
:options="starterSuggestionModeOptions" />
</div>
</div>
<div v-if="formData.config.question_suggestions.starters.enabled" class="setting-row">
<div class="setting-info">
<label>{{ $t('agentEditor.questionSuggestions.count') }}</label>
</div>
<div class="setting-control">
<t-input-number v-model="formData.config.question_suggestions.starters.count"
:min="1" :max="8" theme="column" />
</div>
</div>
<div
v-if="formData.config.question_suggestions.starters.enabled && ['curated', 'hybrid'].includes(formData.config.question_suggestions.starters.mode)"
class="setting-row setting-row-vertical">
<div class="setting-info">
<div class="setting-info-header setting-info-header--inline">
<label>{{ $t('agentEditor.questionSuggestions.curatedItems') }}</label>
<span class="curated-items-count">
{{ formData.config.question_suggestions.starters.items.length }}/8
</span>
</div>
<p class="desc">{{ $t('agentEditor.questionSuggestions.curatedItemsDesc') }}</p>
</div>
<div class="setting-control setting-control-full">
<div class="suggested-prompts-list">
<div v-for="(_prompt, index) in formData.config.question_suggestions.starters.items"
:key="index" class="prompt-item">
<t-input v-model="formData.config.question_suggestions.starters.items[index]"
:maxlength="200" />
<t-button variant="text" theme="danger" shape="square"
:aria-label="$t('common.delete')" @click="removeStarterSuggestion(Number(index))">
<t-icon name="delete" />
</t-button>
</div>
<t-button variant="dashed"
:disabled="formData.config.question_suggestions.starters.items.length >= 8"
@click="addStarterSuggestion">
<template #icon><t-icon name="add" /></template>
{{ $t('agentEditor.questionSuggestions.addItem') }}
</t-button>
</div>
</div>
</div>
</div>
<div v-show="suggestionTab === 'followUps'" class="settings-group">
<div class="setting-row">
<div class="setting-info">
<label>{{ $t('agentEditor.questionSuggestions.enableFollowUps') }}</label>
<p class="desc">{{ $t('agentEditor.questionSuggestions.enableFollowUpsDesc') }}</p>
</div>
<div class="setting-control">
<t-switch v-model="formData.config.question_suggestions.follow_ups.enabled"
:aria-label="$t('agentEditor.questionSuggestions.enableFollowUps')" />
</div>
</div>
<template v-if="formData.config.question_suggestions.follow_ups.enabled">
<div class="setting-row">
<div class="setting-info">
<label>{{ $t('agentEditor.questionSuggestions.sourceMode') }}</label>
</div>
<div class="setting-control">
<t-select v-model="formData.config.question_suggestions.follow_ups.mode"
:options="followUpSuggestionModeOptions" />
</div>
</div>
<div class="setting-row">
<div class="setting-info">
<label>{{ $t('agentEditor.questionSuggestions.count') }}</label>
</div>
<div class="setting-control">
<t-input-number v-model="formData.config.question_suggestions.follow_ups.count"
:min="1" :max="5" theme="column" />
</div>
</div>
<div v-if="formData.config.question_suggestions.follow_ups.mode !== 'knowledge'"
class="setting-row">
<div class="setting-info">
<label>{{ $t('agentEditor.questionSuggestions.model') }}</label>
<p class="desc">{{ $t('agentEditor.questionSuggestions.modelDesc') }}</p>
</div>
<div class="setting-control">
<ModelSelector model-type="KnowledgeQA"
:selected-model-id="formData.config.question_suggestions.follow_ups.model_id"
:all-models="allModels"
@update:selected-model-id="(val: string) => formData.config.question_suggestions.follow_ups.model_id = val"
@add-model="handleAddModel('summary')" />
</div>
</div>
<div class="suggestion-advanced-divider">
<span>{{ $t('agentEditor.questionSuggestions.advancedSettings') }}</span>
</div>
<div class="setting-row">
<div class="setting-info">
<label>{{ $t('agentEditor.questionSuggestions.contextTurns') }}</label>
</div>
<div class="setting-control">
<t-input-number
v-model="formData.config.question_suggestions.follow_ups.max_context_turns"
:min="1" :max="5" theme="column" />
</div>
</div>
<div class="setting-row setting-row-vertical">
<div class="setting-info">
<label>{{ $t('agentEditor.questionSuggestions.categories') }}</label>
</div>
<div class="setting-control setting-control-full">
<t-checkbox-group v-model="formData.config.question_suggestions.follow_ups.categories"
:options="followUpCategoryOptions" />
</div>
</div>
<div class="setting-row setting-row-vertical">
<div class="setting-info">
<label>{{ $t('agentEditor.questionSuggestions.instruction') }}</label>
</div>
<div class="setting-control setting-control-full">
<t-textarea
v-model="formData.config.question_suggestions.follow_ups.additional_instruction"
:maxlength="2000" :autosize="{ minRows: 3, maxRows: 8 }" />
</div>
</div>
<div class="setting-row setting-row-vertical">
<div class="setting-info">
<label>{{ $t('agentEditor.questionSuggestions.displayRules') }}</label>
</div>
<div class="setting-control setting-control-full">
<div class="suggestion-checkboxes">
<t-checkbox v-model="formData.config.question_suggestions.follow_ups.suppress_on_fallback">{{ $t('agentEditor.questionSuggestions.suppressFallback') }}</t-checkbox>
<t-checkbox v-model="formData.config.question_suggestions.follow_ups.suppress_when_answer_asks_question">{{ $t('agentEditor.questionSuggestions.suppressQuestion') }}</t-checkbox>
<t-checkbox v-model="formData.config.question_suggestions.follow_ups.knowledge_fallback">{{ $t('agentEditor.questionSuggestions.knowledgeFallback') }}</t-checkbox>
<t-checkbox v-model="formData.config.question_suggestions.follow_ups.allow_regenerate">{{ $t('agentEditor.questionSuggestions.allowRegenerate') }}</t-checkbox>
</div>
</div>
</div>
</template>
</div>
</div>
<!-- 工具配置(仅 Agent 模式) -->
<div v-show="currentSection === 'tools' && isAgentMode" class="section">
<div class="section-header">
@@ -1487,6 +1668,7 @@ const copyAgentId = async () => {
};
const currentSection = ref(props.initialSection || 'basic');
const suggestionTab = ref<'starters' | 'followUps'>('starters');
const contentWrapperRef = ref<HTMLElement | null>(null);
const highlightedField = ref<AgentNotReadyReasonKey | null>(null);
let highlightClearTimer: ReturnType<typeof setTimeout> | null = null;
@@ -1922,6 +2104,7 @@ const navItems = computed(() => {
{ key: 'basic', icon: 'info-circle', label: t('agent.editor.basicInfo') },
{ key: 'prompts', icon: 'file-paste', label: t('agent.editor.promptsConfig') },
{ key: 'model', icon: 'control-platform', label: t('agent.editor.modelConfig') },
{ key: 'suggestions', icon: 'help-circle', label: t('agentEditor.questionSuggestions.navLabel') },
];
// 多轮对话(仅普通模式显示,Agent模式内部自动控制)
if (!isAgentMode.value) {
@@ -1958,7 +2141,7 @@ const navGroups = computed(() => {
{
key: 'basic',
label: t('agentEditor.navGroups.basic'),
items: pickItems(['basic', 'prompts', 'model', 'conversation']),
items: pickItems(['basic', 'prompts', 'model', 'conversation', 'suggestions']),
},
{
key: 'knowledge',
@@ -2049,14 +2232,59 @@ const defaultFormData = {
fallback_strategy: 'model' as 'fixed' | 'model',
fallback_response: '',
fallback_prompt: '',
question_suggestions: {
starters: {
enabled: true,
mode: 'hybrid' as 'curated' | 'knowledge' | 'hybrid',
items: [] as string[],
count: 6,
},
follow_ups: {
enabled: false,
mode: 'hybrid' as 'generated' | 'knowledge' | 'hybrid',
count: 3,
model_id: '',
additional_instruction: '',
categories: ['clarify', 'deepen', 'action'] as Array<'clarify' | 'deepen' | 'action'>,
max_context_turns: 2,
suppress_on_fallback: true,
suppress_when_answer_asks_question: true,
knowledge_fallback: true,
allow_regenerate: false,
},
},
// 已废弃字段(保留兼容)
welcome_message: '',
suggested_prompts: [] as string[],
}
};
const formData = ref(JSON.parse(JSON.stringify(defaultFormData)));
const starterSuggestionModeOptions = computed(() => [
{ value: 'curated', label: t('agentEditor.questionSuggestions.modeCurated') },
{ value: 'knowledge', label: t('agentEditor.questionSuggestions.modeKnowledge') },
{ value: 'hybrid', label: t('agentEditor.questionSuggestions.modeHybrid') },
]);
const followUpSuggestionModeOptions = computed(() => [
{ value: 'generated', label: t('agentEditor.questionSuggestions.modeGenerated') },
{ value: 'knowledge', label: t('agentEditor.questionSuggestions.modeKnowledge') },
{ value: 'hybrid', label: t('agentEditor.questionSuggestions.modeHybrid') },
]);
const followUpCategoryOptions = computed(() => [
{ value: 'clarify', label: t('agentEditor.questionSuggestions.categoryClarify') },
{ value: 'deepen', label: t('agentEditor.questionSuggestions.categoryDeepen') },
{ value: 'action', label: t('agentEditor.questionSuggestions.categoryAction') },
]);
const addStarterSuggestion = () => {
const items = formData.value.config.question_suggestions.starters.items;
if (items.length < 8) items.push('');
};
const removeStarterSuggestion = (index: number) => {
formData.value.config.question_suggestions.starters.items.splice(index, 1);
};
const applyDefaultChatModelIfEmpty = () => {
if (props.mode !== 'create' || !formData.value) return
const chat =
@@ -2570,8 +2798,20 @@ watch(() => props.visible, async (val) => {
agentData.config.thinking = false;
}
agentData.config.question_suggestions = {
starters: {
...defaultFormData.config.question_suggestions.starters,
...(agentData.config.question_suggestions?.starters || {}),
items: agentData.config.question_suggestions?.starters?.items || [],
},
follow_ups: {
...defaultFormData.config.question_suggestions.follow_ups,
...(agentData.config.question_suggestions?.follow_ups || {}),
categories: agentData.config.question_suggestions?.follow_ups?.categories
|| [...defaultFormData.config.question_suggestions.follow_ups.categories],
},
};
// 确保数组字段存在
if (!agentData.config.suggested_prompts) agentData.config.suggested_prompts = [];
if (!agentData.config.knowledge_bases) agentData.config.knowledge_bases = [];
if (!agentData.config.allowed_tools) agentData.config.allowed_tools = [];
if (!agentData.config.mcp_services) agentData.config.mcp_services = [];
@@ -3890,10 +4130,10 @@ const handleSave = async () => {
// ReRank 模型按运行范围按需使用:知识库范围为 none,或未启用
// knowledge_search 时不需要;其余情况由对话入口在使用前给出明确提示。
// 过滤空推荐问题
if (formData.value.config.suggested_prompts) {
formData.value.config.suggested_prompts = formData.value.config.suggested_prompts.filter((p: string) => p.trim() !== '');
}
formData.value.config.question_suggestions.starters.items =
formData.value.config.question_suggestions.starters.items
.map((p: string) => p.trim())
.filter(Boolean);
if (!formData.value.config.intent_prompts || Object.keys(formData.value.config.intent_prompts).length === 0) {
delete formData.value.config.intent_prompts;
@@ -4629,6 +4869,75 @@ const handleSave = async () => {
}
}
// 开场 / 回答后推荐用顶部 tab 区分(参照模型管理),避免整块包围框
.suggestion-tabs {
margin-bottom: 4px;
:deep(.t-tabs__nav-item) {
font-size: 14px;
}
:deep(.t-tabs__operations) {
display: none;
}
// 只用 tab 作导航,内容自行渲染在下方
:deep(.t-tabs__content) {
display: none;
}
}
.suggestion-advanced-divider {
display: flex;
align-items: center;
gap: 12px;
padding: 4px 0 2px;
color: var(--td-text-color-placeholder);
font-size: 12px;
line-height: 18px;
&::before,
&::after {
content: '';
flex: 1;
height: 1px;
background: var(--td-component-stroke);
}
span {
flex-shrink: 0;
color: var(--td-text-color-secondary);
font-weight: 500;
}
}
// 计数徽标紧贴标签,避免在整宽行里被 space-between 甩开
// 需与基础 `.setting-info .setting-info-header`(space-between)同等特异性才能覆盖
.setting-info-header.setting-info-header--inline {
justify-content: flex-start;
gap: 8px;
}
.curated-items-count {
flex-shrink: 0;
padding: 0 8px;
height: 20px;
display: inline-flex;
align-items: center;
border-radius: 10px;
background: var(--td-bg-color-secondarycontainer);
font-size: 12px;
font-variant-numeric: tabular-nums;
color: var(--td-text-color-secondary);
}
.suggestion-checkboxes {
display: flex;
flex-direction: column;
gap: 10px;
width: 100%;
}
// ===== 工具配置:overview 面板 =====
.tools-overview {
display: flex;
+74
View File
@@ -84,6 +84,14 @@
<botmsg :content="session.content" :session="session" :session-id="session_id"
:user-query="getUserQuery(index)" @scroll-bottom="scrollToBottom"
:isFirstEnter="isFirstEnter" :embeddedMode="embeddedMode"></botmsg>
<FollowUpSuggestions v-if="!session.suggestionsDismissed"
:suggestion-set="session.suggestionSet"
:loading="session.suggestionLoading"
:allow-regenerate="session.suggestionSet?.allow_regenerate"
@select="(item) => handleFollowUpSelect(session, item)"
@regenerate="loadFollowUpSuggestions(session, true, true)"
@impression="(set) => recordSuggestionEvent(session, set, 'impression')"
@dismiss="(set) => dismissSuggestions(session, set)" />
</div>
</div>
<div v-if="showGlobalTypingIndicator"
@@ -134,6 +142,12 @@ import { useChatStreamHandler } from '@/composables/useChatStreamHandler';
import { useStickyBottomOnResize } from '@/composables/useStickyBottomOnResize';
import { clearCitationChunkCache } from '@/utils/citationChunkCache';
import ChatReferencesDrawer from '@/components/ChatReferencesDrawer.vue';
import FollowUpSuggestions from '@/components/chat/FollowUpSuggestions.vue';
import {
ensureMessageSuggestions,
getMessageSuggestions,
recordMessageSuggestionEvent,
} from '@/api/message-suggestion';
import { provideChatReferencesDrawer } from '@/composables/useChatReferencesDrawer';
const referencesDrawer = provideChatReferencesDrawer();
@@ -252,6 +266,7 @@ const suggestedQuestions = ref([]);
const suggestedQuestionsLoading = ref(false);
let suggestedQuestionsFetchId = 0; // 用于取消过时的请求
let suggestedDebounceTimer = null;
let pendingSuggestionAttribution = null;
const cancelSuggestedQuestionsFetch = () => {
suggestedQuestionsFetchId++;
@@ -309,6 +324,54 @@ const handleSuggestedQuestionClick = (question) => {
}
};
const resolveAssistantMessageId = (message) => message?.id || message?.assistant_message_id;
const loadFollowUpSuggestions = async (message, ensure = false, regenerate = false) => {
const messageId = resolveAssistantMessageId(message);
const targetSessionId = session_id.value;
if (!messageId || !targetSessionId || message.suggestionsDismissed) return;
message.suggestionLoading = true;
try {
let response = ensure
? await ensureMessageSuggestions(targetSessionId, messageId, regenerate)
: await getMessageSuggestions(targetSessionId, messageId);
let set = response?.data;
for (let attempt = 0; set?.status === 'generating' && attempt < 120; attempt++) {
await new Promise((resolve) => setTimeout(resolve, 1000));
if (session_id.value !== targetSessionId || message.suggestionsDismissed) return;
response = await getMessageSuggestions(targetSessionId, messageId);
set = response?.data;
}
message.suggestionSet = set?.status === 'ready' ? set : null;
} catch (error) {
if (ensure) console.warn('[FollowUpSuggestions] Failed to generate:', error);
message.suggestionSet = null;
} finally {
message.suggestionLoading = false;
nextTick(() => scrollToBottom());
}
};
const recordSuggestionEvent = (message, set, eventType, questionId = '') => {
if (!set?.id) return;
void recordMessageSuggestionEvent(session_id.value, set.id, eventType, questionId).catch(() => undefined);
};
const handleFollowUpSelect = (message, item) => {
recordSuggestionEvent(message, message.suggestionSet, 'click', item.id);
pendingSuggestionAttribution = {
suggestion_set_id: message.suggestionSet.id,
question_id: item.id,
};
if (inputFieldRef.value?.triggerSend) inputFieldRef.value.triggerSend(item.text);
else sendMsg(item.text);
};
const dismissSuggestions = (message, set) => {
message.suggestionsDismissed = true;
recordSuggestionEvent(message, set, 'dismiss');
};
// 防抖包装,切换知识库/文件时300ms内不重复请求
const debouncedFetchSuggestions = () => {
if (historyLoading.value || messagesList.length > 0) return;
@@ -466,6 +529,11 @@ const {
scrollContainer,
debug: import.meta.env.DEV,
onAfterMsgList: async () => {
for (const message of messagesList) {
if (message.role === 'assistant' && message.is_completed && message.suggestionSet === undefined) {
void loadFollowUpSuggestions(message, false);
}
}
const lastMessage = messagesList[messagesList.length - 1];
if (lastMessage && !lastMessage.is_completed) {
isReplying.value = true;
@@ -507,6 +575,9 @@ const {
attachStreamDebugToMessage(message);
pendingStreamDebug.value = null;
},
onTurnComplete: (message) => {
void loadFollowUpSuggestions(message, true);
},
});
const showGlobalTypingIndicator = computed(() =>
@@ -668,6 +739,8 @@ const sendMsg = async (value, modelId = '', mentionedItems = [], imageFiles = []
const requestMcpServiceIds = agentEnabled ? mcpServiceIds : [];
const requestSkillNames = agentEnabled ? skillNames : [];
const suggestionAttribution = pendingSuggestionAttribution;
pendingSuggestionAttribution = null;
await startStream({
session_id: session_id.value,
knowledge_base_ids: kbIds,
@@ -684,6 +757,7 @@ const sendMsg = async (value, modelId = '', mentionedItems = [], imageFiles = []
images: imageAttachments.length > 0 ? imageAttachments : undefined,
attachment_uploads: attachmentUploads.length > 0 ? attachmentUploads : undefined,
query: value,
suggestion_attribution: suggestionAttribution || undefined,
method: 'POST',
url: endpoint,
});
+96 -1
View File
@@ -69,6 +69,14 @@
:embed-session-sig="sessionSig"
:embed-visitor-id="visitorId"
/>
<FollowUpSuggestions v-if="!session.suggestionsDismissed"
:suggestion-set="session.suggestionSet as any"
:loading="Boolean(session.suggestionLoading)"
:allow-regenerate="Boolean((session.suggestionSet as any)?.allow_regenerate)"
@select="(item) => handleFollowUpSelect(session, item)"
@regenerate="loadFollowUpSuggestions(session, true, true)"
@impression="(set) => recordFollowUpEvent(set, 'impression')"
@dismiss="(set) => dismissFollowUps(session, set)" />
</div>
</div>
@@ -107,13 +115,22 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, toRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { getEmbedSuggestedQuestions, onEmbedHostOpenWithQuery, type SuggestedQuestion } from '@/api/embed'
import {
ensureEmbedMessageSuggestions,
getEmbedMessageSuggestions,
getEmbedSuggestedQuestions,
onEmbedHostOpenWithQuery,
recordEmbedMessageSuggestionEvent,
type SuggestedQuestion,
} from '@/api/embed'
import EmbedInputField from '@/components/EmbedInputField.vue'
import EmbedBotMessage from '@/views/embed/EmbedBotMessage.vue'
import EmbedUserMessage from '@/views/embed/EmbedUserMessage.vue'
import ChatReferencesDrawer from '@/components/ChatReferencesDrawer.vue'
import { provideChatReferencesDrawer } from '@/composables/useChatReferencesDrawer'
import { useEmbedChatSession } from '@/composables/useEmbedChatSession'
import FollowUpSuggestions from '@/components/chat/FollowUpSuggestions.vue'
import type { MessageSuggestionItem, MessageSuggestionSet } from '@/api/message-suggestion'
provideChatReferencesDrawer()
@@ -151,6 +168,49 @@ const suggestedQuestions = ref<SuggestedQuestion[]>([])
const suggestedLoading = ref(false)
const hostContextRef = ref<Record<string, unknown>>(props.hostContext || {})
const loadFollowUpSuggestions = async (
message: Record<string, unknown>,
ensure = false,
regenerate = false,
) => {
const messageId = String(message.id || message.assistant_message_id || '')
const targetSessionId = props.sessionId
if (!props.showSuggestedQuestions || !messageId || !targetSessionId || message.suggestionsDismissed) return
message.suggestionLoading = true
try {
let response = ensure
? await ensureEmbedMessageSuggestions(
props.channelId, props.token, targetSessionId, messageId, props.sessionSig, props.visitorId, regenerate,
)
: await getEmbedMessageSuggestions(
props.channelId, props.token, targetSessionId, messageId, props.sessionSig, props.visitorId,
)
let set = response?.data
for (let attempt = 0; set?.status === 'generating' && attempt < 120; attempt++) {
await new Promise((resolve) => setTimeout(resolve, 1000))
if (props.sessionId !== targetSessionId || message.suggestionsDismissed) return
response = await getEmbedMessageSuggestions(
props.channelId, props.token, targetSessionId, messageId, props.sessionSig, props.visitorId,
)
set = response?.data
}
message.suggestionSet = set?.status === 'ready' ? set : null
} catch {
message.suggestionSet = null
} finally {
message.suggestionLoading = false
scrollToBottom()
}
}
const loadPersistedFollowUps = (messages: Record<string, unknown>[]) => {
for (const message of messages) {
if (message.role === 'assistant' && message.is_completed && message.suggestionSet === undefined) {
void loadFollowUpSuggestions(message, false)
}
}
}
function asUnknownArray(value: unknown): unknown[] | undefined {
return Array.isArray(value) ? value : undefined
}
@@ -210,6 +270,7 @@ const {
onClickScrollToBottom,
sendMsg,
handleStopGeneration,
setSuggestionAttribution,
} = useEmbedChatSession({
sessionId: sessionIdRef,
sessionSig: sessionSigRef,
@@ -227,6 +288,8 @@ const {
emit('session-title', title)
}
},
onTurnComplete: (message) => { void loadFollowUpSuggestions(message, true) },
onMessagesLoaded: loadPersistedFollowUps,
})
const welcomeText = computed(() => props.welcomeMessage?.trim() || '')
@@ -279,6 +342,38 @@ const handleSuggestedClick = (question: string) => {
void sendMsg(text, { webSearchEnabled: webSearchEnabled.value })
}
const recordFollowUpEvent = (
set: MessageSuggestionSet,
eventType: 'impression' | 'click' | 'dismiss',
questionId = '',
) => {
if (!set?.id) return
void recordEmbedMessageSuggestionEvent(
props.channelId,
props.token,
props.sessionId,
props.sessionSig,
props.visitorId,
set.id,
eventType,
questionId,
).catch(() => undefined)
}
const handleFollowUpSelect = (message: Record<string, unknown>, item: MessageSuggestionItem) => {
const set = message.suggestionSet as MessageSuggestionSet | undefined
if (set) {
recordFollowUpEvent(set, 'click', item.id)
setSuggestionAttribution(set.id, item.id)
}
if (!isReplying.value) void sendMsg(item.text, { webSearchEnabled: webSearchEnabled.value })
}
const dismissFollowUps = (message: Record<string, unknown>, set: MessageSuggestionSet) => {
message.suggestionsDismissed = true
recordFollowUpEvent(set, 'dismiss')
}
let removeOpenQueryListener: (() => void) | null = null
onMounted(() => {
@@ -439,7 +439,6 @@
</section>
<div class="sr-only" role="status" aria-live="polite">{{ saveAnnouncement }}</div>
</template>
<t-dialog
v-model:visible="passwordResetVisible"
:header="t('system.globalSettings.passwordReset.dialogTitle')"