Skip to content

useAiPersistence 对话持久化 Hook

基础用法

useAiPersistence Hook 提供了对话历史持久化功能,基于 IndexedDB 实现。

ts
import { useAiPersistence } from '@yh-ui/hooks'

const {
  conversations,
  currentConversationId,
  createConversation,
  addMessage
  // ...
} = useAiPersistence()

API

Options

参数说明类型默认值
storage自定义存储适配器StorageAdapternew IndexedDBAdapter()
conversationKey持久化存储 keystring'ai-conversations'
autoSave数据变更后自动保存booleantrue

返回值

属性说明类型
conversations所有对话列表Ref<Conversation[]>
currentConversationId当前对话 IDRef<string | null>
isLoading是否正在加载Ref<boolean>
isSaving是否正在保存Ref<boolean>
error错误信息Ref<Error | null>

方法

方法名说明参数
loadConversations加载对话() => Promise<void>
saveConversations保存对话() => Promise<void>
createConversation创建对话(title?: string) => Conversation
deleteConversation删除对话(id: string) => void
getCurrentConversation获取当前对话() => Conversation | undefined
addMessage添加消息(message: Omit<ConversationMessage, 'id' | 'timestamp'>) => ConversationMessage | undefined
updateMessage更新消息(messageId: string, updates: Partial<ConversationMessage>) => void
clearCurrentConversation清空当前对话() => void
exportConversations导出对话() => string
importConversations导入对话(json: string) => Promise<boolean>
setCurrentConversation设置当前对话(id: string) => void

类型定义

Conversation

ts
interface Conversation {
  id: string
  title: string
  messages: ConversationMessage[]
  createdAt: number
  updatedAt: number
}

ConversationMessage

ts
interface ConversationMessage {
  id: string
  role: 'user' | 'assistant' | 'system'
  content: string
  timestamp: number
  metadata?: Record<string, any>
}

存储适配器

使用自定义存储

ts
import { useAiPersistence } from '@yh-ui/hooks'
import { APIClient } from '@yh-ui/hooks'

const apiClient = new APIClient('https://api.example.com', {
  Authorization: 'Bearer token'
})

const { conversations } = useAiPersistence({
  storage: apiClient,
  conversationKey: 'my-conversations'
})

IndexedDBAdapter

默认使用 IndexedDB 存储,适合浏览器环境。

APIClient

可配置的后端 API 客户端,预留接口用于对接企业后端服务。

Released under the MIT License.