feat: 智能体按名称编码反查店铺商品,输入框可引用后直接查数

This commit is contained in:
2026-09-19 23:13:26 +08:00
parent 457d776f9f
commit 67c661fd46
12 changed files with 713 additions and 6 deletions
@@ -0,0 +1,159 @@
<script lang="ts" setup>
import { onBeforeUnmount, ref, watch } from 'vue';
import { Empty, Input, Spin } from 'ant-design-vue';
import { getProductPageApi } from '#/api/ec/product';
import { getProductSkuPageApi } from '#/api/ec/product/sku';
import { getShopPageApi } from '#/api/ec/shop';
import {
catalogCiteLabel,
toProductCite,
toShopCite,
toSkuCite,
type CatalogCite,
type CatalogCiteKind,
} from './catalog-cite';
/** 输入框上方的引用面板:按名称/编码搜店铺、商品、SKU。 */
const props = defineProps<{
/** 由输入框末尾 @ 同步过来的关键字,可空 */
seed: string;
}>();
const emit = defineEmits<{
pick: [item: CatalogCite];
}>();
const kinds: CatalogCiteKind[] = ['shop', 'product', 'sku'];
const kind = ref<CatalogCiteKind>('shop');
const keyword = ref(props.seed);
const loading = ref(false);
const items = ref<CatalogCite[]>([]);
let timer: ReturnType<typeof setTimeout> | undefined;
let seq = 0;
watch(
() => props.seed,
(value) => {
keyword.value = value;
},
);
watch([keyword, kind], () => scheduleSearch());
function scheduleSearch() {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
void load();
}, 250);
}
async function load() {
const current = ++seq;
loading.value = true;
const q = keyword.value.trim();
try {
const next = await fetchKind(kind.value, q);
if (current === seq) items.value = next;
} catch {
if (current === seq) items.value = [];
} finally {
if (current === seq) loading.value = false;
}
}
async function fetchKind(target: CatalogCiteKind, q: string) {
if (target === 'shop') {
const data = await getShopPageApi({
page: 1,
pageSize: 8,
filters: q ? { name: q } : {},
});
return (data.records || []).map((shop) => toShopCite(shop));
}
if (target === 'product') {
const data = await getProductPageApi({
page: 1,
pageSize: 8,
filters: q ? { keywords: q } : {},
});
return (data.records || []).map((product) => toProductCite(product));
}
const data = await getProductSkuPageApi({
page: 1,
pageSize: 8,
filters: q ? { keywords: q } : {},
});
return (data.records || []).map((sku) => toSkuCite(sku));
}
function onPick(item: CatalogCite) {
emit('pick', item);
}
scheduleSearch();
onBeforeUnmount(() => {
if (timer) clearTimeout(timer);
seq += 1;
});
</script>
<template>
<div class="rounded-lg border border-border bg-card p-2">
<div class="mb-2 flex gap-1">
<button
v-for="item in kinds"
:key="item"
type="button"
class="rounded-md px-2 py-1 text-xs"
:class="
item === kind
? 'bg-primary/10 text-primary'
: 'text-muted-foreground hover:bg-muted'
"
@click="kind = item"
>
{{ catalogCiteLabel(item) }}
</button>
</div>
<Input
v-model:value="keyword"
allow-clear
placeholder="名称或编码"
size="small"
/>
<div class="relative mt-2 max-h-52 overflow-y-auto">
<div
v-if="loading"
class="text-muted-foreground flex items-center justify-center py-6 text-xs"
>
<Spin size="small" />
</div>
<Empty
v-else-if="items.length === 0"
:image="Empty.PRESENTED_IMAGE_SIMPLE"
description="没有匹配"
/>
<template v-else>
<button
v-for="item in items"
:key="item.key"
type="button"
class="hover:bg-muted flex w-full flex-col rounded-md px-2 py-1.5 text-left"
@click="onPick(item)"
>
<span class="truncate text-sm">{{ item.title }}</span>
<span
v-if="item.subtitle"
class="text-muted-foreground truncate text-xs"
>
{{ item.subtitle }}
</span>
</button>
</template>
</div>
</div>
</template>
@@ -0,0 +1,99 @@
/** 输入框引用的店铺 / 商品 / SKU。line 会跟消息一起发给模型。 */
export type CatalogCiteKind = 'shop' | 'product' | 'sku';
export interface CatalogCite {
key: string;
kind: CatalogCiteKind;
id: number;
title: string;
subtitle: string;
line: string;
}
const KIND_LABEL: Record<CatalogCiteKind, string> = {
shop: '店铺',
product: '商品',
sku: 'SKU',
};
export function catalogCiteLabel(kind: CatalogCiteKind) {
return KIND_LABEL[kind];
}
/** 输入框末尾的 @ 查询;没有则 null。空字符串表示刚输入 @。 */
export function trailingMentionQuery(text: string): null | string {
const matched = text.match(/(^|\s)@([^\s@]*)$/);
return matched ? matched[2] ?? '' : null;
}
/** 选中引用后去掉末尾 @词,避免把触发符发给模型。 */
export function stripTrailingMention(text: string) {
return text.replace(/(^|\s)@[^\s@]*$/, '$1').replace(/\s+$/, '');
}
export function toShopCite(shop: {
id: number;
name: string;
platformCode?: string;
platformName?: string;
}): CatalogCite {
const platform = shop.platformName || shop.platformCode || '';
return {
key: `shop:${shop.id}`,
kind: 'shop',
id: shop.id,
title: shop.name,
subtitle: platform,
line: joinLine('店铺', shop.name, shop.id, platform ? `平台=${platform}` : ''),
};
}
export function toProductCite(product: {
id: number;
name: string;
productCode?: string;
}): CatalogCite {
const code = product.productCode?.trim() || '';
return {
key: `product:${product.id}`,
kind: 'product',
id: product.id,
title: product.name,
subtitle: code,
line: joinLine('商品', product.name, product.id, code ? `编码=${code}` : ''),
};
}
export function toSkuCite(sku: {
id: number;
name?: string;
skuCode?: string;
productName?: string;
}): CatalogCite {
const title = sku.name?.trim() || sku.skuCode?.trim() || `SKU ${sku.id}`;
const bits = [
sku.skuCode?.trim() ? `编码=${sku.skuCode.trim()}` : '',
sku.productName?.trim() ? `商品=${sku.productName.trim()}` : '',
].filter(Boolean);
return {
key: `sku:${sku.id}`,
kind: 'sku',
id: sku.id,
title,
subtitle: bits.join(' '),
line: joinLine('SKU', title, sku.id, bits.join(' ')),
};
}
/** 正文 + 引用块。只有引用时也允许发送。 */
export function composeMessageWithCites(text: string, cites: CatalogCite[]) {
const body = text.trim();
if (cites.length === 0) return body;
const block = ['[引用]', ...cites.map((item) => item.line)].join('\n');
return body ? `${body}\n${block}` : block;
}
function joinLine(kind: string, title: string, id: number, extra: string) {
const head = `${kind}「${title}」 id=${id}`;
return extra ? `${head} ${extra}` : head;
}
@@ -31,6 +31,15 @@ import {
updateAgentLlmSettingsApi,
} from '#/api/agent';
import CatalogCitePicker from './catalog-cite-picker.vue';
import {
catalogCiteLabel,
composeMessageWithCites,
stripTrailingMention,
trailingMentionQuery,
type CatalogCite,
} from './catalog-cite';
defineOptions({ name: 'AgentChat' });
/** 新对话空态快捷提示:点击只填入输入框,不直接发送 */
@@ -61,6 +70,10 @@ const messages = ref<AgentVO.Message[]>([]);
/** 当前流式助手正文(与 messages 末条同步) */
const streamingText = ref('');
const draft = ref('');
/** 本条消息附带的店铺/商品/SKU,发送时写成 [引用] 块 */
const citations = ref<CatalogCite[]>([]);
const citeOpen = ref(false);
const mentionSeed = ref('');
const settingsOpen = ref(false);
const savingSettings = ref(false);
const memories = ref<AgentVO.Memory[]>([]);
@@ -124,6 +137,8 @@ function onSessionClick(threadId: string) {
return;
}
composingNew.value = false;
citations.value = [];
citeOpen.value = false;
activeThreadId.value = threadId;
}
@@ -192,6 +207,8 @@ function beginNewChat() {
messages.value = [];
streamingText.value = '';
draft.value = '';
citations.value = [];
citeOpen.value = false;
}
/** 第一条消息发出时才落库 */
@@ -269,7 +286,8 @@ function appendStreamToken(t: string) {
}
async function send(textOverride?: string) {
const text = (textOverride ?? draft.value).trim();
const raw = textOverride ?? draft.value;
const text = composeMessageWithCites(stripTrailingMention(raw), citations.value);
if (!text || sending.value) return;
sending.value = true;
@@ -292,6 +310,8 @@ async function send(textOverride?: string) {
streamingText.value = '';
draft.value = '';
citations.value = [];
citeOpen.value = false;
messages.value.push({
seq: (messages.value.at(-1)?.seq || 0) + 1,
role: 'user',
@@ -343,6 +363,32 @@ function applyStarterPrompt(text: string) {
draft.value = text;
}
function onCitePick(item: CatalogCite) {
if (citations.value.some((cite) => cite.key === item.key)) {
message.info('已经引用过了');
return;
}
if (citations.value.length >= 5) {
message.warning('一条消息最多引用 5 个');
return;
}
citations.value = [...citations.value, item];
draft.value = stripTrailingMention(draft.value);
mentionSeed.value = '';
citeOpen.value = false;
}
function removeCite(key: string) {
citations.value = citations.value.filter((cite) => cite.key !== key);
}
watch(draft, (value) => {
const query = trailingMentionQuery(value);
if (query === null) return;
mentionSeed.value = query;
citeOpen.value = true;
});
function onSenderStop() {
abort?.abort();
sending.value = false;
@@ -486,11 +532,37 @@ void refreshSessions();
/>
</div>
<div class="shrink-0 border-t border-border p-3">
<div class="mb-2 flex flex-wrap items-center gap-1">
<Button size="small" :disabled="sending" @click="citeOpen = !citeOpen">
引用
</Button>
<span
v-for="cite in citations"
:key="cite.key"
class="bg-primary/10 text-primary inline-flex max-w-full items-center gap-1 rounded-full px-2 py-0.5 text-xs"
>
<span class="shrink-0">{{ catalogCiteLabel(cite.kind) }}</span>
<span class="truncate">{{ cite.title }}</span>
<button
type="button"
class="text-primary/70 hover:text-primary"
@click="removeCite(cite.key)"
>
×
</button>
</span>
</div>
<CatalogCitePicker
v-if="citeOpen"
class="mb-2"
:seed="mentionSeed"
@pick="onCitePick"
/>
<ChatSender
v-model="draft"
class="agent-td-sender"
:loading="sending"
placeholder="输入问题,Enter 发送"
placeholder="输入问题,@ 引用店铺/商品/SKU,Enter 发送"
:textarea-props="{ autosize: { minRows: 2, maxRows: 6 } }"
@send="onSenderSend"
@stop="onSenderStop"