Compare commits

..

No commits in common. "6f386709e26a5311e428586e7a2e8973c4558ed8" and "6bb9247c6c04618dd4ad9dae91adbc7ed62de326" have entirely different histories.

20 changed files with 399 additions and 415 deletions

View File

@ -11,7 +11,8 @@ const defaultData: IodRegistryEntry[] = [
{
name: "固态电池固体电解质材料数据集",
doId: "CSTR:16666.11.nbsdc.9bjqrscd",
description: "国家基础学科公共科学数据中心"
description:
"国家基础学科公共科学数据中心"
},
{
name: "固体颗粒物与流体耦合",
@ -97,22 +98,31 @@ type Props = {
className?: string
}
export const PlaygroundData: React.FC<Props> = ({ className }) => {
const { iodLoading } = useMessageOption()
const { messages, iodLoading, currentMessageId, iodSearch } =
useMessageOption()
const {
setShowPlayground,
setDetailHeader,
setDetailMain,
currentIodMessage
} = useIodPlaygroundContext()
const { setShowPlayground, setDetailHeader, setDetailMain } =
useIodPlaygroundContext()
const data = useMemo<IodRegistryEntry[]>(() => {
return currentIodMessage ? currentIodMessage.data?.data ?? [] : defaultData
}, [currentIodMessage])
// 确保loading状态时数据大于3
if (iodLoading) {
return defaultData
}
if (messages.length && iodSearch) {
const currentMessage = messages?.find(
(message) => message.id === currentMessageId
)
return currentMessage?.iodSources.data.data ?? []
}
return defaultData
}, [currentMessageId, messages, iodLoading, iodSearch])
const title = useMemo(() => {
return currentIodMessage ? "推荐数据" : "热点数据"
}, [currentIodMessage])
return messages.length > 0 ? "推荐数据" : "热点数据"
}, [messages])
const showMore = () => {
setShowPlayground(false)
@ -123,7 +133,7 @@ export const PlaygroundData: React.FC<Props> = ({ className }) => {
onClick={() => setShowPlayground(false)}
/>
)
setDetailMain(<Main loading={iodLoading && Boolean(currentIodMessage)} data={data} truncate={false} />)
setDetailMain(<Main loading={iodLoading} data={data} truncate={false} />)
}
return (
@ -132,7 +142,7 @@ export const PlaygroundData: React.FC<Props> = ({ className }) => {
{/* 数据导航 */}
<Header title={title} onClick={showMore} />
{/* 数据列表 */}
<Main loading={iodLoading && Boolean(currentIodMessage)} data={data.slice(0, 3)} />
<Main loading={iodLoading} data={data.slice(0, 3)} />
</div>
</Card>
)

View File

@ -10,7 +10,6 @@ import { DatasetIcon } from "@/components/Icons/Dataset.tsx"
import { TechCompanyIcon } from "@/components/Icons/TechCompany.tsx"
import { ResearchInstitutesIcon } from "@/components/Icons/ResearchInstitutes.tsx"
import { NSDCIcon } from "@/components/Icons/NSDC.tsx"
import { useIodPlaygroundContext } from "@/components/Option/Playground/PlaygroundIod.tsx"
const rotate = keyframes`
0% {
@ -33,8 +32,8 @@ const breathe = keyframes`
}
`
// 花瓣 /* ${(props) => (props.playing ? "running" : "paused")}; */
const CircleElement = styled.div<{ delay: number }>`
// 花瓣
const CircleElement = styled.div<{ delay: number; playing: boolean }>`
position: absolute;
width: 300px;
height: 160px;
@ -47,7 +46,7 @@ const CircleElement = styled.div<{ delay: number }>`
${rotate} 6s linear infinite,
${breathe} 2s infinite alternate;
animation-delay: ${(props) => props.delay}s;
animation-play-state: running;
animation-play-state: ${(props) => (props.playing ? "running" : "paused")};
animation-duration: 3s; /* 添加动画总持续时间 */
animation-fill-mode: forwards; /* 保持动画结束时的状态 */
`
@ -222,19 +221,24 @@ type Props = {
className?: string
}
export const PlaygroundIodRelevant: React.FC<Props> = ({ className }) => {
const { iodLoading, iodSearch } = useMessageOption()
const { currentIodMessage } = useIodPlaygroundContext()
const { messages, iodLoading, currentMessageId, iodSearch } =
useMessageOption()
const showSearchData = useMemo(() => {
return currentIodMessage && !iodLoading
}, [currentIodMessage, iodLoading])
return iodSearch && messages.length > 0 && !iodLoading
}, [iodSearch, messages, iodLoading])
const data = useMemo(() => {
const loading = iodSearch && iodLoading
const text = loading ? "正" : "已"
const text2 = loading ? "进行" : "完成"
const text3 = loading ? "……" : ""
const currentMessage = messages?.find(
(message) => message.id === currentMessageId
)
const loading = (iodSearch && iodLoading)
const text = loading ? '正' : '已'
const text2 = loading ? '进行' : '完成'
const text3 = loading ? '……' : ''
const duration = loading ? 2.5 : 0
return [
@ -252,12 +256,7 @@ export const PlaygroundIodRelevant: React.FC<Props> = ({ className }) => {
</span>
<span className="text-[#f00000]">
<CountUp
decimals={1}
end={53.7}
duration={duration}
separator=","
/>
<CountUp decimals={1} end={53.7} duration={duration} separator="," />
</span>
{text2}{text3}
@ -269,7 +268,7 @@ export const PlaygroundIodRelevant: React.FC<Props> = ({ className }) => {
<span className="text-green-700">
{" "}
<CountUp
end={currentIodMessage?.data.total ?? 0}
end={currentMessage?.iodSources.data.total ?? 0}
duration={2.5}
separator=","
/>
@ -289,14 +288,9 @@ export const PlaygroundIodRelevant: React.FC<Props> = ({ className }) => {
<CountUp end={138} duration={duration} separator="," />
</span>
<span className="text-[#f00000]">
<CountUp
end={18.3}
decimals={1}
duration={duration}
separator=","
/>
<CountUp end={18.3} decimals={1} duration={duration} separator="," />
</span>
{text2}{text3}
@ -308,7 +302,7 @@ export const PlaygroundIodRelevant: React.FC<Props> = ({ className }) => {
<span className="text-green-700">
{" "}
<CountUp
end={currentIodMessage?.scenario.total ?? 0}
end={currentMessage?.iodSources.scenario.total ?? 0}
duration={2.5}
separator=","
/>
@ -330,13 +324,7 @@ export const PlaygroundIodRelevant: React.FC<Props> = ({ className }) => {
<span className="text-[#f00000]">
{" "}
<CountUp
end={2.1}
decimals={1}
duration={duration}
separator=","
/>
<CountUp end={2.1} decimals={1} duration={duration} separator="," />
</span>
<span className="text-[#f00000]">
@ -352,7 +340,7 @@ export const PlaygroundIodRelevant: React.FC<Props> = ({ className }) => {
<span className="text-green-700">
{" "}
<CountUp
end={currentIodMessage?.organization.total ?? 0}
end={currentMessage?.iodSources.organization.total ?? 0}
duration={2.5}
separator=","
/>
@ -365,7 +353,7 @@ export const PlaygroundIodRelevant: React.FC<Props> = ({ className }) => {
)
}
]
}, [showSearchData, iodLoading])
}, [messages, iodLoading])
return (
<Card
@ -377,9 +365,9 @@ export const PlaygroundIodRelevant: React.FC<Props> = ({ className }) => {
<div
className={`absolute inset-0 pointer-events-none z-0 overflow-hidden ${showSearchData ? "" : ""}`}>
<div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-64 h-64">
<CircleElement delay={0} />
<CircleElement delay={1} />
<CircleElement delay={2} />
<CircleElement delay={0} playing={true} />
<CircleElement delay={1} playing={true} />
<CircleElement delay={2} playing={true} />
</div>
</div>
@ -388,14 +376,16 @@ export const PlaygroundIodRelevant: React.FC<Props> = ({ className }) => {
<h2 className="text-xl font-semibold text-[#1a3c87] flex justify-center items-center">
<div className="flex items-center gap-2">
<SearchIcon />
{currentIodMessage ? "科创数联网深度搜索" : "科创数联网连接资源"}
{messages.length > 0
? "科创数联网深度搜索"
: "科创数联网连接资源"}
</div>
{/*<button className="bg-[#2563eb1a] text-[#08307f] font-medium py-1 px-3 rounded-full text-sm hover:bg-[#2563eb1a] transition-colors float-right">*/}
{/* {data.length}个结果*/}
{/*</button>*/}
</h2>
<p className="text-sm text-[#1a3c87] mt-1 text-center">
{currentIodMessage
{messages.length > 0
? "下面是在科创数联网上进行深度搜索得到的相关数据、场景和团队"
: "下面是科创数联网连接的数据、场景和团队"}
</p>
@ -403,7 +393,7 @@ export const PlaygroundIodRelevant: React.FC<Props> = ({ className }) => {
{/* Content */}
<div className="space-y-2 flex-1 overflow-y-auto">
{currentIodMessage ? (
{messages.length ? (
<AnimatePresence mode="wait">
<motion.div
key="search-results"
@ -432,16 +422,16 @@ export const PlaygroundIodRelevant: React.FC<Props> = ({ className }) => {
/>
)}
</div>
<div
<p
className={`text-gray-700 ${showSearchData ? "text-sm" : "text-lg"}`}>
{item.title}
</div>
</p>
</div>
{item.description && (
<div className="flex-1">
<div className="text-xs text-gray-500 mt-1 pl-7">
<p className="text-xs text-gray-500 mt-1 pl-7">
{item.description}
</div>
</p>
</div>
)}
</div>

View File

@ -25,10 +25,8 @@ import { GenerationInfo } from "./GenerationInfo"
import { parseReasoning } from "@/libs/reasoning"
import { humanizeMilliseconds } from "@/utils/humanize-milliseconds"
import { AllIodRegistryEntry } from "@/types/iod.ts"
import { PiNetwork } from "react-icons/pi"
type Props = {
id?: string
message: string
message_type?: string
hideCopy?: boolean
@ -52,11 +50,9 @@ type Props = {
generationInfo?: any
isStreaming: boolean
reasoningTimeTaken?: number
iodSearch?: boolean
setCurrentMessageId: (id: string) => void
}
export const PlaygroundMessage: React.FC<Props> = (props) => {
export const PlaygroundMessage = (props: Props) => {
const [isBtnPressed, setIsBtnPressed] = React.useState(false)
const [editMode, setEditMode] = React.useState(false)
@ -262,18 +258,6 @@ export const PlaygroundMessage: React.FC<Props> = (props) => {
)}
{props.isBot && (
<>
{/*数联网搜索*/}
{props.iodSearch && (
<Tooltip title="数联网信息">
<button
onClick={() => props.setCurrentMessageId(props.id)}
aria-label="数联网信息"
className="flex items-center justify-center w-6 h-6 rounded-full bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500">
<PiNetwork className="w-3 h-3 text-gray-400 group-hover:text-gray-500" />
</button>
</Tooltip>
)}
{!props.hideCopy && (
<Tooltip title={t("copyToClipboard")}>
<button

View File

@ -1,6 +1,6 @@
import React, { useMemo } from "react"
import React, { useEffect, useMemo, useState } from "react"
import { DataNavigation } from "@/components/Common/DataNavigation.tsx"
import { Card, Skeleton } from "antd"
import { Card, Drawer, Skeleton } from "antd"
import { IodRegistryEntry } from "@/types/iod.ts"
import { useIodPlaygroundContext } from "@/components/Option/Playground/PlaygroundIod.tsx"
@ -33,11 +33,7 @@ type HeaderProps = {
showButton?: boolean
onClick?: () => void
}
const Header: React.FC<HeaderProps> = ({
title,
showButton = true,
onClick
}) => (
const Header: React.FC<HeaderProps> = ({ title, showButton = true, onClick }) => (
<DataNavigation
Header={
<div className="flex items-center text-[#4ab01a] gap-1">
@ -101,28 +97,36 @@ const Main: React.FC<MainProps> = ({ data, loading, truncate = true }) => (
</div>
)
type Props = {
className?: string
}
export const PlaygroundScene: React.FC<Props> = ({ className }) => {
const { iodLoading } = useMessageOption()
const { messages, iodLoading, currentMessageId, iodSearch } =
useMessageOption()
const {
setShowPlayground,
setDetailHeader,
setDetailMain,
currentIodMessage
} = useIodPlaygroundContext()
const { setShowPlayground, setDetailHeader, setDetailMain } =
useIodPlaygroundContext()
const data = useMemo<IodRegistryEntry[]>(() => {
return currentIodMessage
? currentIodMessage.scenario?.data ?? []
: defaultData
}, [currentIodMessage])
// 确保loading状态时数据大于3
if (iodLoading) {
return defaultData
}
if (messages.length && iodSearch) {
const currentMessage = messages?.find(
(message) => message.id === currentMessageId
)
return currentMessage?.iodSources.scenario.data ?? []
}
return defaultData
}, [currentMessageId, messages, iodLoading])
const title = useMemo(() => {
return currentIodMessage ? "推荐场景" : "热点场景"
}, [currentIodMessage])
return messages.length > 0 ? "推荐场景" : "热点场景"
}, [messages])
const showMore = () => {
setShowPlayground(false)
@ -133,17 +137,19 @@ export const PlaygroundScene: React.FC<Props> = ({ className }) => {
onClick={() => setShowPlayground(false)}
/>
)
setDetailMain(<Main loading={iodLoading && Boolean(currentIodMessage)} data={data} truncate={false} />)
setDetailMain(<Main loading={iodLoading} data={data} truncate={false} />)
}
return (
<Card className={`${className}`} hoverable>
<Card
className={`${className}`}
hoverable>
<div className="h-full flex flex-col gap-2 relative">
{/* 数据导航 */}
<Header title={title} onClick={showMore} />
{/* 数据列表 */}
<Main loading={iodLoading && Boolean(currentIodMessage)} data={data.slice(0, 3)} />
<Main loading={iodLoading} data={data.slice(0, 3)} />
</div>
</Card>
)

View File

@ -1,4 +1,4 @@
import React, { useMemo } from "react"
import React, { useEffect, useMemo } from "react"
import { DataNavigation } from "@/components/Common/DataNavigation.tsx"
import { Card, Skeleton } from "antd"
import { IodRegistryEntry } from "@/types/iod.ts"
@ -17,10 +17,11 @@ const defaultData: IodRegistryEntry[] = [
doId: "91320507MAEKWL5Y2L"
},
{
name: "伊利诺伊大学香槟分校UIUC",
description: "创建于1867年坐落于伊利诺伊州双子城厄巴纳香槟市",
doId: "bdware.org/uiuc"
}
doId: "bdware.org/uiuc",
},
]
type HeaderProps = {
@ -112,24 +113,31 @@ type Props = {
className?: string
}
export const PlaygroundTeam: React.FC<Props> = ({ className }) => {
const { iodLoading } = useMessageOption()
const { messages, iodLoading, currentMessageId, iodSearch } =
useMessageOption()
const {
setShowPlayground,
setDetailHeader,
setDetailMain,
currentIodMessage
} = useIodPlaygroundContext()
const { setShowPlayground, setDetailHeader, setDetailMain } =
useIodPlaygroundContext()
const data = useMemo<IodRegistryEntry[]>(() => {
return currentIodMessage
? currentIodMessage.organization?.data ?? []
: defaultData
}, [currentIodMessage])
// 确保loading状态时数据大于3
if (iodLoading) {
return defaultData
}
if (messages.length && iodSearch) {
const currentMessage = messages?.find(
(message) => message.id === currentMessageId
)
return currentMessage?.iodSources.organization.data ?? []
}
return defaultData
}, [currentMessageId, messages, iodLoading])
const title = useMemo(() => {
return currentIodMessage ? "推荐团队" : "热点团队"
}, [currentIodMessage])
return messages.length > 0 ? "推荐团队" : "热点团队"
}, [messages])
const showMore = () => {
setShowPlayground(false)
@ -140,18 +148,17 @@ export const PlaygroundTeam: React.FC<Props> = ({ className }) => {
onClick={() => setShowPlayground(false)}
/>
)
setDetailMain(
<Main loading={iodLoading && Boolean(currentIodMessage)} data={data} truncate={false} flat={false} />
)
setDetailMain(<Main loading={iodLoading} data={data} truncate={false} flat={false} />)
}
return (
<Card className={`${className}`} hoverable>
<div className="h-full flex flex-col gap-2 relative">
{/* 数据导航 */}
<Header title={title} onClick={showMore} />
{/* 数据列表 */}
<Main loading={iodLoading && Boolean(currentIodMessage)} data={data.slice(0, 3)} />
<Main loading={iodLoading} data={data.slice(0, 3)} />
</div>
</Card>
)

View File

@ -1,13 +1,15 @@
import { Form, Image, Input, message, Modal } from "antd"
import React from "react"
import { Form, Image, Input, Modal, Tooltip, message } from "antd"
import { Share } from "lucide-react"
import { useState } from "react"
import type { Message } from "~/store/option"
import Markdown from "./Markdown"
import React from "react"
import { useMutation } from "@tanstack/react-query"
import { getPageShareUrl } from "~/services/ollama"
import { cleanUrl } from "~/libs/clean-url"
import { getTitleById, getUserId, saveWebshare } from "@/db"
import { useTranslation } from "react-i18next"
import fetcher from "@/libs/fetcher"
import { Message } from "@/types/message.ts"
type Props = {
messages: Message[]

View File

@ -11,8 +11,7 @@ export const PlaygroundChat = () => {
regenerateLastMessage,
isSearchingInternet,
editMessage,
ttsEnabled,
setCurrentMessageId,
ttsEnabled
} = useMessageOption()
const [isSourceOpen, setIsSourceOpen] = React.useState(false)
const [source, setSource] = React.useState<any>(null)
@ -28,7 +27,6 @@ export const PlaygroundChat = () => {
{messages.map((message, index) => (
<PlaygroundMessage
key={index}
id={message.id}
isBot={message.isBot}
message={message.message}
name={message.name}
@ -51,8 +49,6 @@ export const PlaygroundChat = () => {
generationInfo={message?.generationInfo}
isStreaming={streaming}
reasoningTimeTaken={message?.reasoning_time_taken}
setCurrentMessageId={setCurrentMessageId}
iodSearch={message.iodSearch}
/>
))}
</div>

View File

@ -218,7 +218,7 @@ export const PlaygroundForm = ({ dropedFile }: Props) => {
{
key: 0,
label: (
<div
<p
onClick={() => {
setIodSearch(true)
}}>
@ -227,13 +227,13 @@ export const PlaygroundForm = ({ dropedFile }: Props) => {
<PiNetwork className="h-5 w-5" />
</p>
<p className="text-[#00000080]"></p>
</div>
</p>
)
},
{
key: 1,
label: (
<div
<p
onClick={() => {
setIodSearch(false)
}}>
@ -242,7 +242,7 @@ export const PlaygroundForm = ({ dropedFile }: Props) => {
<PiNetwork className="h-5 w-5" />
</p>
<p className="text-[#00000080]"></p>
</div>
</p>
)
}
]
@ -397,7 +397,7 @@ export const PlaygroundForm = ({ dropedFile }: Props) => {
className={`!px-[5px] flex items-center justify-center dark:text-gray-300 ${
chatMode === "rag" ? "hidden" : "block"
}`}>
<ImageIcon strokeWidth={1} className="h-5 w-5" />
<ImageIcon stroke-width={1} className="h-5 w-5" />
</Button>
</Tooltip>
)}
@ -420,12 +420,12 @@ export const PlaygroundForm = ({ dropedFile }: Props) => {
}}
className={`flex items-center justify-center dark:text-gray-300 !px-[5px]`}>
{!isListening ? (
<MicIcon strokeWidth={1} className="h-5 w-5" />
<MicIcon stroke-width={1} className="h-5 w-5" />
) : (
<div className="relative">
<span className="animate-ping absolute inline-flex h-3 w-3 rounded-full bg-red-400 opacity-75"></span>
<MicIcon
strokeWidth={1}
stroke-width={1}
className="h-5 w-5"
/>
</div>

View File

@ -9,7 +9,7 @@ import { PlaygroundTeam } from "@/components/Common/Playground/Team.tsx"
import { Card } from "antd"
import { CloseOutlined } from "@ant-design/icons"
import { useMessageOption } from "@/hooks/useMessageOption.tsx"
import { AllIodRegistryEntry } from "@/types/iod.ts"
import { Message } from "@/types/message.ts"
// 定义 Context 类型
interface IodPlaygroundContextType {
@ -19,7 +19,7 @@ interface IodPlaygroundContextType {
setDetailHeader: React.Dispatch<React.SetStateAction<React.ReactNode>>
detailMain: React.ReactNode
setDetailMain: React.Dispatch<React.SetStateAction<React.ReactNode>>
currentIodMessage?: AllIodRegistryEntry
currentIodMessage: Message | null
}
// 创建 Context
@ -41,34 +41,36 @@ export const useIodPlaygroundContext = () => {
const PlaygroundIodProvider: React.FC<{ children: React.ReactNode }> = ({
children
}) => {
const { messages, iodLoading, currentMessageId } = useMessageOption()
const { messages, iodLoading, currentMessageId, iodSearch } =
useMessageOption()
const [showPlayground, setShowPlayground] = useState<boolean>(true)
const [detailHeader, setDetailHeader] = useState(<></>)
const [detailMain, setDetailMain] = useState(<></>)
const currentIodMessage = useMemo<AllIodRegistryEntry | undefined>(() => {
console.log('messages', messages)
console.log("currentMessageId", currentMessageId)
console.log("iodLoading", iodLoading)
// loading 返回 undefined是为了避免数据不足三个的情况
if (iodLoading || !messages.length) {
return undefined
const currentIodMessage = useMemo<Message | null>(() => {
if (iodLoading) {
return null
}
if (messages.length && iodSearch) {
// 如果不存在currentMessageId默认返回最后一个message
if (!currentMessageId) {
const lastMessage = messages.at(-1)
// 如果最后一次message没有开启数联网搜索则返回undefined
return lastMessage?.iodSearch ? lastMessage.iodSources : undefined
return messages.at(-1)
}
const currentMessage = messages?.find(
(message) => message.id === currentMessageId
)
console.log("currentMessage", currentMessage)
return currentMessage?.iodSearch ? currentMessage.iodSources : undefined
}, [currentMessageId, messages, iodLoading])
if (currentMessage) {
return currentMessage
}
// 如果当前message不存在最后一个message
return messages.at(-1)
}
return null
}, [currentMessageId, messages, iodLoading, iodSearch])
return (
<PlaygroundContext.Provider
@ -152,6 +154,7 @@ const PlaygroundContent = () => {
)
}
export const PlaygroundIod = () => {
return (
<div className="w-[36%] h-full pt-16 pr-5 pb-0">

View File

@ -0,0 +1,25 @@
import { PencilIcon } from "lucide-react"
import { useMessage } from "../../../hooks/useMessage"
import { useTranslation } from 'react-i18next';
export const PlaygroundNewChat = () => {
const { setHistory, setMessages, setHistoryId } = useMessage()
const { t } = useTranslation('optionChat')
const handleClick = () => {
setHistoryId(null)
setMessages([])
setHistory([])
}
return (
<button
onClick={handleClick}
className="flex w-full border bg-transparent hover:bg-gray-200 dark:hover:bg-gray-800 text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 focus:ring-offset-gray-100 rounded-md p-2 dark:border-gray-800">
<PencilIcon className="mx-3 h-5 w-5" aria-hidden="true" />
<span className="inline-flex font-semibol text-white text-sm">
{t('newChat')}
</span>
</button>
)
}

View File

@ -1,20 +1,41 @@
import { useTranslation } from "react-i18next"
import TextArea from "antd/es/input/TextArea"
import { IodDb } from "@/db/iod.ts"
import { useState } from "react"
import { useEffect, useState } from "react"
export const IodApp = () => {
const { t } = useTranslation("settings")
const db = IodDb.getInstance()
const [connection, setConnection] = useState(JSON.stringify(db.getIodConnection(), null, 2))
const [connectVal, setConnectVal] = useState<string>('')
const setConnectValWrap = (val: string) => {
db.insertIodConnection(JSON.parse(val))
setConnection(val)
localStorage.setItem("iod-connect", val)
setConnectVal(val)
}
useEffect(() => {
const val = localStorage.getItem("iod-connect")
const defaultVal = {
gatewayUrl: "tcp://reg01.public.internetofdata.cn:21037",
registry: "data/Registry",
localRepository: "data/Repository",
doBrowser: "http://021.node.internetapi.cn:21030/SCIDE/SCManager"
}
if (!val) {
localStorage.setItem(
"iod-connect",
JSON.stringify(defaultVal)
)
setConnectVal(JSON.stringify(defaultVal, null, 2))
return
}
try {
const val = localStorage.getItem("iod-connect")
setConnectVal(JSON.stringify(JSON.parse(val), null, 2))
} catch (e) {
setConnectVal(JSON.stringify(defaultVal, null, 2))
}
}, [])
return (
<dl className="flex flex-col space-y-6 text-sm">
@ -26,7 +47,7 @@ export const IodApp = () => {
</div>
<div className="flex flex-col gap-3">
<span className="text-gray-700 dark:text-neutral-50"></span>
<TextArea rows={6} placeholder="请输入数联网连接配置" value={connection} onChange={(e) => setConnectValWrap(e.target.value)} />
<TextArea rows={6} placeholder="请输入数联网连接配置" value={connectVal} onChange={(e) => setConnectValWrap(e.target.value)} />
</div>
</dl>
)

View File

@ -1,7 +1,8 @@
import { type ChatHistory as ChatHistoryType } from "~/store/option"
import {
type ChatHistory as ChatHistoryType,
type Message as MessageType
} from "~/store/option"
import { AllIodRegistryEntry } from "@/types/iod.ts"
import { type Message as MessageType } from "@/types/message.ts"
import { getDefaultIodSources } from "@/libs/iod.ts"
type HistoryInfo = {
id: string
@ -248,31 +249,38 @@ export const saveHistory = async (
await db.addChatHistory(history)
return history
}
export type HistoryMessage = {
history_id: string
name: string
role: string
content: string
images: string[]
iodSearch?: boolean
webSearch?: boolean
webSources?: any[]
iodSources?: AllIodRegistryEntry
createdAt?: number
messageType?: string
generationInfo?: any
export const saveMessage = async (
history_id: string,
name: string,
role: string,
content: string,
images: string[],
webSources?: any[],
iodSources?: AllIodRegistryEntry,
time?: number,
message_type?: string,
generationInfo?: any,
reasoning_time_taken?: number
}
export const saveMessage = async (msg: HistoryMessage): Promise<Message> => {
) => {
const id = generateID()
let createdAt = Date.now()
if (msg.createdAt) {
createdAt += msg.createdAt
if (time) {
createdAt += time
}
const message = {
...msg,
id,
history_id,
name,
role,
content,
images,
createdAt,
webSources,
iodSources,
messageType: message_type,
generationInfo: generationInfo,
reasoning_time_taken
}
const db = new PageAssitDatabase()
await db.addMessage(message)
@ -296,12 +304,11 @@ export const formatToMessage = (messages: MessageHistory): MessageType[] => {
messages.sort((a, b) => a.createdAt - b.createdAt)
return messages.map((message) => {
return {
...message,
isBot: message.role === "assistant",
message: message.content,
name: message.name,
webSources: message?.webSources || [],
iodSources: message?.iodSources || getDefaultIodSources(),
iodSources: message?.iodSources || { data: [], scenario: [], organization: []},
images: message.images || [],
generationInfo: message?.generationInfo,
reasoning_time_taken: message?.reasoning_time_taken

View File

@ -1,74 +0,0 @@
const iodConnection = "iodConnection-g3"
export const defaultIodConnectionConfig = {
gatewayUrl: "tcp://reg01.public.internetofdata.cn:21037",
registry: "data/Registry",
localRepository: "data/Repository",
doBrowser: "http://021.node.internetapi.cn:21030/SCIDE/SCManager"
} as const
export type IodConnectionConfig = {
gatewayUrl: string
registry: string
localRepository: string
doBrowser: string
}
export class IodDb {
private static instance: IodDb
private static iodConnectionConfig: IodConnectionConfig | null = null
// 单例模式
static getInstance(): IodDb {
if (!IodDb.instance) {
IodDb.instance = new IodDb()
}
return IodDb.instance
}
insertIodConnection(config: IodConnectionConfig): void {
try {
localStorage.setItem(iodConnection, JSON.stringify(config))
IodDb.iodConnectionConfig = config
} catch (error) {
console.error('Failed to save IOD connection config:', error)
throw new Error('Failed to save IOD connection configuration')
}
}
getIodConnection(): IodConnectionConfig {
// 如果已经有缓存,直接返回
if (IodDb.iodConnectionConfig) {
return IodDb.iodConnectionConfig
}
try {
const val = localStorage.getItem(iodConnection)
if (!val) {
return defaultIodConnectionConfig
}
IodDb.iodConnectionConfig = JSON.parse(val)
} catch (error) {
console.warn('Failed to parse IOD connection config, using default:', error)
return defaultIodConnectionConfig
}
}
// 添加清除配置的方法
clearIodConnection(): void {
try {
localStorage.removeItem(iodConnection)
IodDb.iodConnectionConfig = null
} catch (error) {
console.error('Failed to clear IOD connection config:', error)
throw new Error('Failed to clear IOD connection configuration')
}
}
getIodConfig() {
return {
connection: this.getIodConnection(),
}
}
}

View File

@ -1,4 +1,4 @@
import { HistoryMessage, saveHistory, saveMessage } from "@/db"
import { saveHistory, saveMessage } from "@/db"
import {
setLastUsedChatModel,
setLastUsedChatSystemPrompt
@ -23,9 +23,7 @@ export const saveMessageOnError = async ({
message_source = "web-ui",
message_type,
prompt_content,
prompt_id,
iodSearch,
webSearch,
prompt_id
}: {
e: any
setHistory: (history: ChatHistory) => void
@ -40,9 +38,7 @@ export const saveMessageOnError = async ({
message_source?: "copilot" | "web-ui"
message_type?: string
prompt_id?: string
prompt_content?: string,
iodSearch?: boolean,
webSearch?: boolean,
prompt_content?: string
}) => {
if (
e?.name === "AbortError" ||
@ -63,31 +59,31 @@ export const saveMessageOnError = async ({
}
])
const defaultMessage: HistoryMessage = {
history_id: historyId,
name: selectedModel,
role: "assistant",
content: botMessage,
webSources: [],
iodSources: getDefaultIodSources(),
messageType: message_type,
iodSearch,
webSearch,
images: []
}
if (historyId) {
if (!isRegenerating) {
await saveMessage({
...JSON.parse(JSON.stringify(defaultMessage)),
role: "user",
content: userMessage,
images: [image]
})
await saveMessage(
historyId,
selectedModel,
"user",
userMessage,
[image],
[],
getDefaultIodSources(),
1,
message_type
)
}
await saveMessage({
...JSON.parse(JSON.stringify(defaultMessage))
})
await saveMessage(
historyId,
selectedModel,
"assistant",
botMessage,
[],
[],
getDefaultIodSources(),
2,
message_type
)
await setLastUsedChatModel(historyId, selectedModel)
if (prompt_id || prompt_content) {
await setLastUsedChatSystemPrompt(historyId, {
@ -99,19 +95,28 @@ export const saveMessageOnError = async ({
const title = await generateTitle(selectedModel, userMessage, userMessage)
const newHistoryId = await saveHistory(title, false, message_source)
if (!isRegenerating) {
await saveMessage({
...JSON.parse(JSON.stringify(defaultMessage)),
history_id: newHistoryId.id,
content: userMessage,
role: "user",
images: [image]
})
await saveMessage(
newHistoryId.id,
selectedModel,
"user",
userMessage,
[image],
[],
getDefaultIodSources(),
1,
message_type
)
}
await saveMessage(
{
...JSON.parse(JSON.stringify(defaultMessage)),
history_id: newHistoryId.id,
},
newHistoryId.id,
selectedModel,
"assistant",
botMessage,
[],
[],
getDefaultIodSources(),
2,
message_type
)
setHistoryId(newHistoryId.id)
await setLastUsedChatModel(newHistoryId.id, selectedModel)
@ -137,8 +142,6 @@ export const saveMessageOnSuccess = async ({
message,
image,
fullText,
iodSearch,
webSearch,
webSources,
iodSources,
message_source = "web-ui",
@ -155,8 +158,6 @@ export const saveMessageOnSuccess = async ({
message: string
image: string
fullText: string
iodSearch?: boolean
webSearch?: boolean
webSources: any[]
iodSources: AllIodRegistryEntry
message_source?: "copilot" | "web-ui"
@ -167,38 +168,34 @@ export const saveMessageOnSuccess = async ({
reasoning_time_taken?: number
}) => {
var botMessage
const defaultMessage: HistoryMessage = {
history_id: historyId,
name: selectedModel,
role: "assistant",
content: fullText,
webSources: webSources,
iodSources: iodSources,
messageType: message_type,
images: [],
iodSearch,
webSearch,
generationInfo,
reasoning_time_taken,
}
if (historyId) {
if (!isRegenerate) {
await saveMessage(
{
...JSON.parse(JSON.stringify(defaultMessage)),
role: "user",
content: message,
images: [image],
webSources: [],
iodSources: getDefaultIodSources(),
},
historyId,
selectedModel,
"user",
message,
[image],
[],
getDefaultIodSources(),
1,
message_type,
generationInfo,
reasoning_time_taken
)
}
botMessage = await saveMessage(
{
...JSON.parse(JSON.stringify(defaultMessage)),
}
historyId,
selectedModel!,
"assistant",
fullText,
[],
webSources,
iodSources,
2,
message_type,
generationInfo,
reasoning_time_taken
)
updateDialog(historyId, botMessage)
await setLastUsedChatModel(historyId, selectedModel!)
@ -212,21 +209,30 @@ export const saveMessageOnSuccess = async ({
const title = await generateTitle(selectedModel, message, message)
const newHistoryId = await saveHistory(title, false, message_source)
await saveMessage(
{
...JSON.parse(JSON.stringify(defaultMessage)),
history_id: newHistoryId.id,
role: "user",
content: message,
images: [image],
webSources: [],
iodSources: getDefaultIodSources(),
},
newHistoryId.id,
selectedModel,
"user",
message,
[image],
[],
getDefaultIodSources(),
1,
message_type,
generationInfo,
reasoning_time_taken
)
botMessage = await saveMessage(
{
...JSON.parse(JSON.stringify(defaultMessage)),
history_id: newHistoryId.id,
}
newHistoryId.id,
selectedModel!,
"assistant",
fullText,
[],
webSources,
iodSources,
2,
message_type,
generationInfo,
reasoning_time_taken
)
updateDialog(newHistoryId.id, botMessage)
setHistoryId(newHistoryId.id)

View File

@ -2,12 +2,12 @@ import React from "react"
import { cleanUrl } from "~/libs/clean-url"
import {
defaultEmbeddingModelForRag,
getOllamaURL,
geWebSearchFollowUpPrompt,
getOllamaURL,
promptForRag,
systemPromptForNonRag
} from "~/services/ollama"
import { useStoreMessageOption } from "~/store/option"
import { useStoreMessageOption, type Message } from "~/store/option"
import { useStoreMessage } from "~/store"
import { SystemMessage } from "@langchain/core/messages"
import { getDataFromCurrentTab } from "~/libs/get-html"
@ -43,7 +43,6 @@ import {
} from "@/libs/reasoning"
import { AllIodRegistryEntry } from "@/types/iod.ts"
import { getDefaultIodSources } from "@/libs/iod.ts"
import { Message } from "@/types/message.ts"
export const useMessage = () => {
const {

View File

@ -7,7 +7,7 @@ import {
promptForRag,
systemPromptForNonRagOption
} from "~/services/ollama"
import type { ChatHistory, MeteringEntry } from "~/store/option"
import type { ChatHistory, Message, MeteringEntry } from "~/store/option"
import { useStoreMessageOption } from "~/store/option"
import { SystemMessage } from "@langchain/core/messages"
import {
@ -47,7 +47,6 @@ import {
removeReasoning
} from "@/libs/reasoning"
import { getDefaultIodSources } from "@/libs/iod.ts"
import type { Message } from "@/types/message.ts"
export const useMessageOption = () => {
const {
@ -215,39 +214,36 @@ export const useMessageOption = () => {
data: meter
})
let defaultMessage: Message = {
isBot: true,
name: selectedModel,
message,
iodSearch,
webSearch,
webSources: [],
iodSources: getDefaultIodSources(),
images: [image]
}
if (!isRegenerate) {
newMessage = [
...messages,
{
...JSON.parse(JSON.stringify(defaultMessage)),
id: generateID(),
isBot: false,
name: "You",
message,
webSources: [],
iodSources: getDefaultIodSources(),
images: [image]
},
{
...JSON.parse(JSON.stringify(defaultMessage)),
id: generateMessageId,
isBot: true,
name: selectedModel,
message: "",
webSources: [],
iodSources: getDefaultIodSources(),
id: generateMessageId
}
]
} else {
newMessage = [
...messages,
{
...JSON.parse(JSON.stringify(defaultMessage)),
id: generateMessageId,
message: " ",
isBot: true,
name: selectedModel,
message: "▋",
webSources: [],
iodSources: getDefaultIodSources(),
id: generateMessageId
}
]
}
@ -529,8 +525,6 @@ export const useMessageOption = () => {
message,
image,
fullText,
iodSearch,
webSearch,
webSources,
iodSources,
generationInfo,
@ -572,9 +566,7 @@ export const useMessageOption = () => {
setHistory,
setHistoryId,
userMessage: message,
isRegenerating: isRegenerate,
iodSearch,
webSearch,
isRegenerating: isRegenerate
})
if (!errorSave) {
@ -680,7 +672,6 @@ export const useMessageOption = () => {
let newMessage: Message[] = []
let generateMessageId = generateID()
setCurrentMessageId(generateMessageId)
const meter: MeteringEntry = {
id: generateMessageId,
queryContent: message,
@ -691,6 +682,7 @@ export const useMessageOption = () => {
loading: true,
data: meter
})
if (!isRegenerate) {
newMessage = [
...messages,
@ -698,7 +690,6 @@ export const useMessageOption = () => {
isBot: false,
name: "You",
message,
id: generateID(),
webSources: [],
iodSources: getDefaultIodSources(),
images: [image]
@ -898,6 +889,7 @@ export const useMessageOption = () => {
content: fullText
}
])
await saveMessageOnSuccess({
historyId,
setHistoryId,
@ -906,8 +898,6 @@ export const useMessageOption = () => {
message,
image,
fullText,
iodSearch,
webSearch,
source: [],
generationInfo,
prompt_content: promptContent,
@ -924,8 +914,8 @@ export const useMessageOption = () => {
const { cot, content } = responseResolver(fullText)
const currentMeteringEntry = {
...meter,
modelInputTokenCount: prompt? prompt.length : 0,
modelOutputTokenCount: fullText? fullText.length : 0,
modelInputTokenCount: prompt.length,
modelOutputTokenCount: fullText.length,
model: ollama.modelName ?? ollama.model,
relatedDataCount: 0,
timeTaken: new Date().getTime() - chatStartTime.getTime(),
@ -953,9 +943,7 @@ export const useMessageOption = () => {
userMessage: message,
isRegenerating: isRegenerate,
prompt_content: promptContent,
prompt_id: promptId,
iodSearch,
webSearch,
prompt_id: promptId
})
if (!errorSave) {
@ -1286,9 +1274,7 @@ export const useMessageOption = () => {
fullText,
source,
generationInfo,
reasoning_time_taken: timetaken,
iodSearch,
webSearch,
reasoning_time_taken: timetaken
})
setIsProcessing(false)
@ -1304,9 +1290,7 @@ export const useMessageOption = () => {
setHistory,
setHistoryId,
userMessage: message,
isRegenerating: isRegenerate,
iodSearch,
webSearch,
isRegenerating: isRegenerate
})
if (!errorSave) {

View File

@ -6,7 +6,6 @@ import {
} from "@/db"
import { exportKnowledge, importKnowledge } from "@/db/knowledge"
import { exportVectors, importVectors } from "@/db/vector"
import { IodDb } from "@/db/iod"
import { message } from "antd"
export const exportPageAssistData = async () => {
@ -14,14 +13,12 @@ export const exportPageAssistData = async () => {
const chat = await exportChatHistory()
const vector = await exportVectors()
const prompts = await exportPrompts()
const iod = IodDb.getInstance().getIodConfig()
const data = {
knowledge,
chat,
vector,
prompts,
iod
prompts
}
const dataStr = JSON.stringify(data)
@ -37,7 +34,6 @@ export const exportPageAssistData = async () => {
}
export const importPageAssistData = async (file: File) => {
debugger
const reader = new FileReader()
reader.onload = async () => {
try {
@ -59,10 +55,6 @@ export const importPageAssistData = async (file: File) => {
await importPrompts(data.prompts)
}
if(data?.iod) {
IodDb.getInstance().insertIodConnection(data.iod)
}
message.success("Data imported successfully")
} catch (e) {
console.error(e)

View File

@ -1,6 +1,28 @@
import { Knowledge } from "@/db/knowledge"
import { create } from "zustand"
import { Message } from "esbuild"
import { AllIodRegistryEntry } from "@/types/iod.ts"
type WebSearch = {
search_engine: string
search_url: string
search_query: string
search_results: {
title: string
link: string
}[]
}
export type Message = {
isBot: boolean
name: string
message: string
webSources: any[]
iodSources: AllIodRegistryEntry
images?: string[]
search?: WebSearch
reasoning_time_taken?: number
id?: string
messageType?: string
}
export type ChatHistory = {
role: "user" | "assistant" | "system"
@ -14,11 +36,8 @@ type State = {
setMessages: (messages: Message[]) => void
history: ChatHistory
setHistory: (history: ChatHistory) => void
currentMeteringEntry: { data: MeteringEntry; loading: boolean }
setCurrentMeteringEntry: (meteringEntry: {
data: MeteringEntry
loading: boolean
}) => void
currentMeteringEntry: {data: MeteringEntry, loading: boolean}
setCurrentMeteringEntry: (meteringEntry: {data: MeteringEntry, loading: boolean}) => void
meteringEntries: MeteringEntry[]
setMeteringEntries: (meteringEntries: MeteringEntry[]) => void
streaming: boolean
@ -104,12 +123,9 @@ export const useStoreMessageOption = create<State>((set) => ({
setMessages: (messages) => set({ messages }),
history: [],
setHistory: (history) => set({ history }),
currentMeteringEntry: { data: {} as MeteringEntry, loading: false },
setCurrentMeteringEntry: (currentMeteringEntry) =>
set({ currentMeteringEntry }),
meteringEntries: JSON.parse(
localStorage.getItem("meteringEntries") || JSON.stringify([])
),
currentMeteringEntry: {data: {} as MeteringEntry, loading: false},
setCurrentMeteringEntry: (currentMeteringEntry) => set({ currentMeteringEntry }),
meteringEntries: JSON.parse(localStorage.getItem("meteringEntries") || JSON.stringify([])),
setMeteringEntries: (meteringEntries) => set({ meteringEntries }),
streaming: false,
setStreaming: (streaming) => set({ streaming }),

View File

@ -13,9 +13,7 @@ export type Message = {
isBot: boolean
name: string
message: string
webSearch?: boolean
webSources: any[]
iodSearch?: boolean
iodSources: AllIodRegistryEntry
images?: string[]
search?: WebSearch
@ -24,5 +22,3 @@ export type Message = {
generationInfo?: any
reasoning_time_taken?: number
}
export type Messages = Message[]

View File

@ -13,7 +13,6 @@ import { PageAssitDatabase } from "@/db"
import { enPOSTag, Segment, useDefault } from "segmentit"
import { getDefaultIodSources } from "@/libs/iod.ts"
import { IodDb } from "@/db/iod.ts"
const segment = useDefault(new Segment())
export const tokenizeInput = function (input: string): string[] {
@ -25,9 +24,24 @@ export const tokenizeInput = function (input: string): string[] {
)
return words.filter((word) => word.w.length > 1).map((word) => word.w)
}
//doipUrl = tcp://reg01.public.internetofdata.cn:21037
export const _iodConfig = {
gatewayUrl: "tcp://reg01.public.internetofdata.cn:21037",
registry: "data/Registry",
localRepository: "data/Repository",
doBrowser: "http://021.node.internetapi.cn:21030/SCIDE/SCManager"
}
function getIodConfig() {
return IodDb.getInstance().getIodConnection()
const val = localStorage.getItem("iod-connect")
if (!val) {
return _iodConfig
}
try {
return JSON.parse(val)
} catch {
return _iodConfig
}
}
export const iodConfigLocal = {
gatewayUrl: "tcp://127.0.0.1:21036",
@ -258,7 +272,7 @@ export const updateDialog = async function (
})) ?? []
updateBody.IoDSources =
Object.values((botMessage?.iodSources ?? {}) as AllIodRegistryEntry).flatMap(iod => iod.data)?.map((r) => ({
Object.values( botMessage.iodSources as AllIodRegistryEntry).flatMap(iod => iod.data)?.map((r) => ({
id: r.doId,
tokenCount:
r.content || r.description