mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
feat: 智能体按名称编码反查店铺商品,输入框可引用后直接查数
This commit is contained in:
@@ -16,7 +16,11 @@ _BASE_SYSTEM = (
|
||||
"需要经营数据时优先调用可用工具。"
|
||||
"用户说近 N 天、昨天、本周、本月等相对日期时,先调用 get_current_time,"
|
||||
"用返回的 ranges 或 today 换算 yyyy-MM-dd 后再查数,不要向用户索要日期范围。"
|
||||
"仅当缺少店铺、商品等业务标识时才向用户确认。"
|
||||
"用户用名称或编码指代店铺、商品、SKU 时,先调用 catalog_search;"
|
||||
"恰好一条就用返回的 id 继续查数;多条只列名称和编码让用户选。"
|
||||
"用户消息含 [引用] 且带 id= 时,直接用这些 id,不必再搜索,也不要向用户复述 id。"
|
||||
"禁止向用户索要店铺 ID、商品 ID 或 SKU ID。"
|
||||
"若只给了引用、没有具体问题,按近 7 天概览回答该对象。"
|
||||
"若工具失败或无权限,请说明原因并给出可操作建议。"
|
||||
)
|
||||
|
||||
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogProductHitVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogShopHitVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogSkuHitVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.platform.model.enums.PlatformCode;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.mapper.ProductSkuMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.po.ProductSkuPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 租户内按名称/编码检索店铺、商品、SKU,只返回瘦字段。
|
||||
* 不走分页列表接口,避免把规格、成本、渠道授权塞进模型上下文。
|
||||
*/
|
||||
@Component
|
||||
public class CatalogLookupAdapter {
|
||||
|
||||
static final int FETCH = 40;
|
||||
static final int LIMIT = 8;
|
||||
|
||||
private final ShopMapper shopMapper;
|
||||
private final ProductMapper productMapper;
|
||||
private final ProductSkuMapper productSkuMapper;
|
||||
|
||||
public CatalogLookupAdapter(ShopMapper shopMapper,
|
||||
ProductMapper productMapper,
|
||||
ProductSkuMapper productSkuMapper) {
|
||||
this.shopMapper = shopMapper;
|
||||
this.productMapper = productMapper;
|
||||
this.productSkuMapper = productSkuMapper;
|
||||
}
|
||||
|
||||
public Slice<CatalogShopHitVO> searchShops(Long companyId, String keyword) {
|
||||
LambdaQueryWrapper<ShopPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ShopPO::getCompanyId, companyId)
|
||||
.like(ShopPO::getName, keyword);
|
||||
List<ShopPO> rows = shopMapper.selectPage(new Page<>(1, FETCH, false), wrapper).getRecords();
|
||||
rows.sort(Comparator.comparingInt((ShopPO s) -> score(keyword, s.getName()))
|
||||
.thenComparing(ShopPO::getId, Comparator.nullsLast(Comparator.reverseOrder())));
|
||||
List<CatalogShopHitVO> hits = new ArrayList<>();
|
||||
for (ShopPO shop : head(rows)) {
|
||||
String code = shop.getPlatformCode();
|
||||
hits.add(CatalogShopHitVO.builder()
|
||||
.id(shop.getId())
|
||||
.name(shop.getName())
|
||||
.platformCode(code)
|
||||
.platformName(PlatformCode.ofCode(code).map(PlatformCode::getLabel).orElse(code))
|
||||
.build());
|
||||
}
|
||||
return new Slice<>(hits, rows.size() >= FETCH);
|
||||
}
|
||||
|
||||
public Slice<CatalogProductHitVO> searchProducts(Long companyId, String keyword) {
|
||||
LambdaQueryWrapper<ProductPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ProductPO::getCompanyId, companyId)
|
||||
.and(w -> w.like(ProductPO::getName, keyword).or().like(ProductPO::getProductCode, keyword));
|
||||
List<ProductPO> rows = productMapper.selectPage(new Page<>(1, FETCH, false), wrapper).getRecords();
|
||||
rows.sort(Comparator.comparingInt((ProductPO p) -> score(keyword, p.getName(), p.getProductCode()))
|
||||
.thenComparing(ProductPO::getId, Comparator.nullsLast(Comparator.reverseOrder())));
|
||||
List<CatalogProductHitVO> hits = new ArrayList<>();
|
||||
for (ProductPO product : head(rows)) {
|
||||
hits.add(CatalogProductHitVO.builder()
|
||||
.id(product.getId())
|
||||
.name(product.getName())
|
||||
.productCode(product.getProductCode())
|
||||
.build());
|
||||
}
|
||||
return new Slice<>(hits, rows.size() >= FETCH);
|
||||
}
|
||||
|
||||
public Slice<CatalogSkuHitVO> searchSkus(Long companyId, String keyword) {
|
||||
List<Long> productIds = matchingProductIds(companyId, keyword);
|
||||
LambdaQueryWrapper<ProductSkuPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ProductSkuPO::getCompanyId, companyId)
|
||||
.and(w -> {
|
||||
w.like(ProductSkuPO::getName, keyword)
|
||||
.or().like(ProductSkuPO::getSkuCode, keyword)
|
||||
.or().like(ProductSkuPO::getBarcode, keyword);
|
||||
if (!productIds.isEmpty()) {
|
||||
w.or().in(ProductSkuPO::getProductId, productIds);
|
||||
}
|
||||
});
|
||||
List<ProductSkuPO> rows = productSkuMapper.selectPage(new Page<>(1, FETCH, false), wrapper).getRecords();
|
||||
Map<Long, ProductPO> products = loadProducts(companyId, rows);
|
||||
rows.sort(Comparator.comparingInt((ProductSkuPO sku) -> scoreSku(keyword, sku, products.get(sku.getProductId())))
|
||||
.thenComparing(ProductSkuPO::getId, Comparator.nullsLast(Comparator.reverseOrder())));
|
||||
List<CatalogSkuHitVO> hits = new ArrayList<>();
|
||||
for (ProductSkuPO sku : head(rows)) {
|
||||
ProductPO product = products.get(sku.getProductId());
|
||||
hits.add(CatalogSkuHitVO.builder()
|
||||
.id(sku.getId())
|
||||
.name(sku.getName())
|
||||
.skuCode(sku.getSkuCode())
|
||||
.barcode(sku.getBarcode())
|
||||
.productId(sku.getProductId())
|
||||
.productName(product == null ? null : product.getName())
|
||||
.productCode(product == null ? null : product.getProductCode())
|
||||
.build());
|
||||
}
|
||||
return new Slice<>(hits, rows.size() >= FETCH);
|
||||
}
|
||||
|
||||
private List<Long> matchingProductIds(Long companyId, String keyword) {
|
||||
LambdaQueryWrapper<ProductPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ProductPO::getCompanyId, companyId)
|
||||
.and(w -> w.like(ProductPO::getName, keyword).or().like(ProductPO::getProductCode, keyword))
|
||||
.select(ProductPO::getId);
|
||||
return productMapper.selectPage(new Page<>(1, FETCH, false), wrapper).getRecords().stream()
|
||||
.map(ProductPO::getId)
|
||||
.toList();
|
||||
}
|
||||
|
||||
private Map<Long, ProductPO> loadProducts(Long companyId, List<ProductSkuPO> skus) {
|
||||
List<Long> ids = skus.stream()
|
||||
.map(ProductSkuPO::getProductId)
|
||||
.filter(id -> id != null)
|
||||
.distinct()
|
||||
.toList();
|
||||
if (ids.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
return productMapper.selectBatchIds(ids).stream()
|
||||
.filter(p -> companyId.equals(p.getCompanyId()))
|
||||
.collect(Collectors.toMap(ProductPO::getId, Function.identity(), (a, b) -> a));
|
||||
}
|
||||
|
||||
private static <T> List<T> head(List<T> rows) {
|
||||
if (rows.size() <= LIMIT) {
|
||||
return rows;
|
||||
}
|
||||
return rows.subList(0, LIMIT);
|
||||
}
|
||||
|
||||
private static int scoreSku(String keyword, ProductSkuPO sku, ProductPO product) {
|
||||
if (product == null) {
|
||||
return score(keyword, sku.getName(), sku.getSkuCode(), sku.getBarcode());
|
||||
}
|
||||
return score(keyword, sku.getName(), sku.getSkuCode(), sku.getBarcode(), product.getName(), product.getProductCode());
|
||||
}
|
||||
|
||||
/** 0 全等,1 前缀,2 包含,3 其余。越小越靠前。 */
|
||||
static int score(String keyword, String... fields) {
|
||||
String key = keyword.toLowerCase(Locale.ROOT);
|
||||
int best = 3;
|
||||
for (String field : fields) {
|
||||
if (field == null || field.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
String value = field.trim().toLowerCase(Locale.ROOT);
|
||||
if (value.equals(key)) {
|
||||
return 0;
|
||||
}
|
||||
if (value.startsWith(key)) {
|
||||
best = Math.min(best, 1);
|
||||
} else if (value.contains(key)) {
|
||||
best = Math.min(best, 2);
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
public record Slice<T>(List<T> items, boolean truncated) {
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
/** 商品检索瘦项。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class CatalogProductHitVO {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String productCode;
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** catalog_search 返回体。hint 告诉模型下一步怎么用 id,不要向用户索要。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class CatalogSearchSlimVO {
|
||||
private String keyword;
|
||||
private String kind;
|
||||
private boolean truncated;
|
||||
private String hint;
|
||||
private List<CatalogShopHitVO> shops;
|
||||
private List<CatalogProductHitVO> products;
|
||||
private List<CatalogSkuHitVO> skus;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
/** 店铺检索瘦项。店铺无独立编码,只回名称与平台。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class CatalogShopHitVO {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String platformCode;
|
||||
private String platformName;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
/** SKU 检索瘦项,带所属商品便于消歧。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class CatalogSkuHitVO {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String skuCode;
|
||||
private String barcode;
|
||||
private Long productId;
|
||||
private String productName;
|
||||
private String productCode;
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.application;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.CatalogLookupAdapter;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.CatalogLookupAdapter.Slice;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogProductHitVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogSearchSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogShopHitVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogSkuHitVO;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 目录检索用例:限定当前 MCP 租户,并把命中数写成给模型看的 hint。
|
||||
*/
|
||||
@Service
|
||||
public class CatalogMcpFacade {
|
||||
|
||||
private final CatalogLookupAdapter catalogLookupAdapter;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
|
||||
public CatalogMcpFacade(CatalogLookupAdapter catalogLookupAdapter,
|
||||
CurrentUserContext currentUserContext) {
|
||||
this.catalogLookupAdapter = catalogLookupAdapter;
|
||||
this.currentUserContext = currentUserContext;
|
||||
}
|
||||
|
||||
public CatalogSearchSlimVO search(String keyword, String kind) {
|
||||
String kw = keyword == null ? "" : keyword.trim();
|
||||
String normalized = normalizeKind(kind);
|
||||
if (kw.isEmpty()) {
|
||||
return result(kw, normalized, false, List.of(), List.of(), List.of(),
|
||||
"keyword 不能为空。用店铺名、商品名、商品编码或 SKU 编码搜索,不要向用户要 ID。");
|
||||
}
|
||||
if (kw.length() > 64) {
|
||||
kw = kw.substring(0, 64);
|
||||
}
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Slice<CatalogShopHitVO> shops = want(normalized, "shop")
|
||||
? catalogLookupAdapter.searchShops(companyId, kw)
|
||||
: new Slice<>(List.of(), false);
|
||||
Slice<CatalogProductHitVO> products = want(normalized, "product")
|
||||
? catalogLookupAdapter.searchProducts(companyId, kw)
|
||||
: new Slice<>(List.of(), false);
|
||||
Slice<CatalogSkuHitVO> skus = want(normalized, "sku")
|
||||
? catalogLookupAdapter.searchSkus(companyId, kw)
|
||||
: new Slice<>(List.of(), false);
|
||||
boolean truncated = shops.truncated() || products.truncated() || skus.truncated();
|
||||
int total = shops.items().size() + products.items().size() + skus.items().size();
|
||||
return result(kw, normalized, truncated, shops.items(), products.items(), skus.items(),
|
||||
hint(total, truncated));
|
||||
}
|
||||
|
||||
private static boolean want(String kind, String target) {
|
||||
return "all".equals(kind) || target.equals(kind);
|
||||
}
|
||||
|
||||
/** 非法 kind 按全部搜索,避免模型传错就空手而归。 */
|
||||
private static String normalizeKind(String kind) {
|
||||
if (kind == null || kind.isBlank()) {
|
||||
return "all";
|
||||
}
|
||||
String value = kind.trim().toLowerCase();
|
||||
return switch (value) {
|
||||
case "shop", "product", "sku", "all" -> value;
|
||||
default -> "all";
|
||||
};
|
||||
}
|
||||
|
||||
private static String hint(int total, boolean truncated) {
|
||||
String base = switch (total) {
|
||||
case 0 -> "没有匹配。换更完整的名称或编码再搜,不要向用户索要店铺 ID、商品 ID 或 SKU ID。";
|
||||
case 1 -> "唯一命中。直接用该 id 调用经营查询,不要再向用户确认 ID。";
|
||||
default -> "多条命中。只把名称、编码、平台列给用户选一条,禁止索要或复述数字 ID。";
|
||||
};
|
||||
if (truncated) {
|
||||
return base + "结果已截断,名称太宽时可让用户补充编码。";
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
private static CatalogSearchSlimVO result(String keyword,
|
||||
String kind,
|
||||
boolean truncated,
|
||||
List<CatalogShopHitVO> shops,
|
||||
List<CatalogProductHitVO> products,
|
||||
List<CatalogSkuHitVO> skus,
|
||||
String hint) {
|
||||
return CatalogSearchSlimVO.builder()
|
||||
.keyword(keyword)
|
||||
.kind(kind)
|
||||
.truncated(truncated)
|
||||
.hint(hint)
|
||||
.shops(shops)
|
||||
.products(products)
|
||||
.skus(skus)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -24,7 +24,7 @@ public class BiMcpTools {
|
||||
|
||||
@McpTool(
|
||||
name = "bi_workbench_finance",
|
||||
description = "查询工作台经营概览 KPI(销售额、单量、净利、费比等),按日期范围;可选平台/店铺筛选。租户取自 MCP 绑定的 companyId。")
|
||||
description = "查询工作台经营概览 KPI(销售额、单量、净利、费比等),按日期范围;可选平台/店铺筛选。租户取自 MCP 绑定的 companyId。shopId 只能来自 catalog_search 或用户消息 [引用],不要向用户索要。")
|
||||
public BiWorkbenchFinanceSlimVO workbenchFinance(
|
||||
@McpToolParam(description = "开始日期 yyyy-MM-dd", required = true) String startDate,
|
||||
@McpToolParam(description = "结束日期 yyyy-MM-dd", required = true) String endDate,
|
||||
@@ -36,7 +36,7 @@ public class BiMcpTools {
|
||||
|
||||
@McpTool(
|
||||
name = "bi_shop_overview",
|
||||
description = "查询单店经营概览摘要:销售额、单量、净利、ROI、目标达成率,以及商品销量 Top10。")
|
||||
description = "查询单店经营概览摘要:销售额、单量、净利、ROI、目标达成率,以及商品销量 Top10。shopId 来自 catalog_search 或用户消息 [引用],禁止向用户索要店铺 ID。")
|
||||
public BiShopOverviewSlimVO shopOverview(
|
||||
@McpToolParam(description = "店铺 ID", required = true) Long shopId,
|
||||
@McpToolParam(description = "开始日期 yyyy-MM-dd", required = true) String startDate,
|
||||
@@ -47,7 +47,7 @@ public class BiMcpTools {
|
||||
|
||||
@McpTool(
|
||||
name = "bi_product_overview",
|
||||
description = "查询单商品经营概览摘要:销售额、单量、净利、ROI、目标达成率,以及规格销量 Top10;可选限定店铺。")
|
||||
description = "查询单商品经营概览摘要:销售额、单量、净利、ROI、目标达成率,以及规格销量 Top10;可选限定店铺。productId/shopId 来自 catalog_search 或用户消息 [引用],禁止向用户索要 ID。")
|
||||
public BiProductOverviewSlimVO productOverview(
|
||||
@McpToolParam(description = "商品 ID", required = true) Long productId,
|
||||
@McpToolParam(description = "开始日期 yyyy-MM-dd", required = true) String startDate,
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.tools;
|
||||
|
||||
import org.springaicommunity.mcp.annotation.McpTool;
|
||||
import org.springaicommunity.mcp.annotation.McpToolParam;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogSearchSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.application.CatalogMcpFacade;
|
||||
|
||||
/**
|
||||
* 目录检索 MCP:用名称/编码反查店铺、商品、SKU,再把 id 交给经营查询。
|
||||
*/
|
||||
@Component
|
||||
public class CatalogMcpTools {
|
||||
|
||||
private final CatalogMcpFacade catalogMcpFacade;
|
||||
|
||||
public CatalogMcpTools(CatalogMcpFacade catalogMcpFacade) {
|
||||
this.catalogMcpFacade = catalogMcpFacade;
|
||||
}
|
||||
|
||||
@McpTool(
|
||||
name = "catalog_search",
|
||||
description = "按名称或编码在当前租户检索店铺、商品、SKU,返回 id。"
|
||||
+ "用户提到店名、商品名、商品编码、SKU 编码/规格名时必须先调本工具,禁止向用户索要数字 ID。"
|
||||
+ "店铺没有编码,只按名称匹配。kind:shop、product、sku、all(默认 all)。"
|
||||
+ "恰好一条时用返回 id 调 bi_*;多条时只让用户按名称/编码选择。")
|
||||
public CatalogSearchSlimVO search(
|
||||
@McpToolParam(description = "店铺名、商品名、商品编码或 SKU 编码,必填", required = true) String keyword,
|
||||
@McpToolParam(description = "shop / product / sku / all,默认 all", required = false) String kind) {
|
||||
return catalogMcpFacade.search(keyword, kind);
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
|
||||
Reference in New Issue
Block a user