55 lines
2.0 KiB
TypeScript
55 lines
2.0 KiB
TypeScript
import type { PersistedChatState } from "./GlobalChatbox.types";
|
|
|
|
export const createId = () =>
|
|
`${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
export const CHAT_STORAGE_KEY = "tjwater_agent_chat_state_v1";
|
|
export const PRESET_PROMPTS = [
|
|
"分析当前管网中的水力瓶颈管道,并给出改造建议。",
|
|
"帮我分析当前管网压力异常点,并按风险等级排序。",
|
|
"帮我生成一份今日运行简报,包含问题、原因和建议。",
|
|
"查询关键 SCADA 点位最近 24 小时的异常波动。",
|
|
"排查当前管网爆管风险,并说明优先处置建议。",
|
|
];
|
|
|
|
export const stripMarkdown = (md: string): string =>
|
|
md
|
|
.replace(/```[\s\S]*?```/g, "")
|
|
.replace(/`([^`]+)`/g, "$1")
|
|
.replace(/!\[.*?\]\(.*?\)/g, "")
|
|
.replace(/\[([^\]]+)\]\(.*?\)/g, "$1")
|
|
.replace(/#{1,6}\s+/g, "")
|
|
.replace(/\*\*\*(.+?)\*\*\*/g, "$1")
|
|
.replace(/\*\*(.+?)\*\*/g, "$1")
|
|
.replace(/\*(.+?)\*/g, "$1")
|
|
.replace(/~~(.+?)~~/g, "$1")
|
|
.replace(/>\s+/g, "")
|
|
.replace(/[-*+]\s+/g, "")
|
|
.replace(/\d+\.\s+/g, "")
|
|
.replace(/\n{2,}/g, "\n")
|
|
.replace(/<[^>]+>/g, "")
|
|
.trim();
|
|
|
|
export const getInitialChatState = (): PersistedChatState => {
|
|
if (typeof window === "undefined") {
|
|
return { messages: [], sessionId: undefined };
|
|
}
|
|
try {
|
|
const storedRaw = window.localStorage.getItem(CHAT_STORAGE_KEY);
|
|
if (!storedRaw) return { messages: [], sessionId: undefined };
|
|
const parsed = JSON.parse(storedRaw) as PersistedChatState;
|
|
if (!Array.isArray(parsed.messages)) {
|
|
console.error("[GlobalChatbox] Invalid persisted messages format.");
|
|
window.localStorage.removeItem(CHAT_STORAGE_KEY);
|
|
return { messages: [], sessionId: undefined };
|
|
}
|
|
return { messages: parsed.messages, sessionId: parsed.sessionId };
|
|
} catch (error) {
|
|
console.error(
|
|
"[GlobalChatbox] Failed to read persisted chat state:",
|
|
error,
|
|
);
|
|
window.localStorage.removeItem(CHAT_STORAGE_KEY);
|
|
return { messages: [], sessionId: undefined };
|
|
}
|
|
};
|