Skip to content

Commit

Permalink
fix: fix entity bug
Browse files Browse the repository at this point in the history
  • Loading branch information
2214962083 committed Nov 4, 2024
1 parent b2abd7e commit d5a9a30
Show file tree
Hide file tree
Showing 24 changed files with 135 additions and 184 deletions.
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import type { MessageType } from '@langchain/core/messages'
import { ConversationEntity } from '@shared/entities/conversation-entity'
import type { Conversation } from '@shared/types/chat-context'
import type {
LangchainMessage,
LangchainMessageContents
} from '@shared/types/chat-context/langchain-message'
import { convertToLangchainMessageContents } from '@shared/utils/convert-to-langchain-message-contents'
import { getDefaultConversation } from '@shared/utils/get-default-conversation'

export const convertLangchainMessageToConversation = (
message: LangchainMessage
): Conversation => {
const messageType = message.toDict().type as MessageType
const defaultConversation = getDefaultConversation(messageType)
const defaultConversation = new ConversationEntity({ role: messageType })
.entity
const contents: LangchainMessageContents = convertToLangchainMessageContents(
message.content
)
Expand Down
13 changes: 0 additions & 13 deletions src/extension/webview-api/controllers/chat-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,4 @@ export class ChatController extends Controller {
yield conversations
}
}

// sendMessage(req: { message: string }): Promise<string> {
// return Promise.resolve(`Hi, bro, I'm response to: ${req.message}`)
// }

// async *streamChat(req: {
// prompt: string
// }): AsyncGenerator<string, void, unknown> {
// for (let i = 0; i < 5; i++) {
// yield `Chunk ${i + 1} for prompt: ${req.prompt}`
// await new Promise(resolve => setTimeout(resolve, 1000))
// }
// }
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { aidePaths } from '@extension/file-utils/paths'
import { VsCodeFS } from '@extension/file-utils/vscode-fs'
import { logger } from '@extension/logger'
import type { ChatSession } from '@shared/entities'
import { ChatContextEntity, type ChatSession } from '@shared/entities'
import type { ChatContext, Conversation } from '@shared/types/chat-context'
import { convertChatContextToChatSession } from '@shared/utils/convert-chat-context-to-chat-session'

import { chatSessionsDB } from '../lowdb/chat-sessions-db'
import { Controller } from '../types'
Expand All @@ -16,7 +15,7 @@ export class ChatSessionController extends Controller {
}

async createSession(req: { chatContext: ChatContext }): Promise<ChatSession> {
const chatSession = convertChatContextToChatSession(req.chatContext)
const chatSession = new ChatContextEntity(req.chatContext).toChatSession()
const now = new Date().getTime()
const session = await chatSessionsDB.add({
...chatSession,
Expand Down Expand Up @@ -48,7 +47,7 @@ export class ChatSessionController extends Controller {
async updateSession(req: { chatContext: ChatContext }): Promise<void> {
const now = new Date().getTime()
const session = await chatSessionsDB.update(req.chatContext.id, {
...convertChatContextToChatSession(req.chatContext),
...new ChatContextEntity(req.chatContext).toChatSession(),
updatedAt: now
})

Expand All @@ -65,7 +64,7 @@ export class ChatSessionController extends Controller {
}): Promise<void> {
const now = new Date().getTime()
const session = await chatSessionsDB.createOrUpdate({
...convertChatContextToChatSession(req.chatContext),
...new ChatContextEntity(req.chatContext).toChatSession(),
updatedAt: now
})

Expand Down
3 changes: 1 addition & 2 deletions src/extension/webview-api/lowdb/ai-model-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ class AIModelDB extends BaseDB<AIModel> {
static readonly schemaVersion = 1

constructor() {
// Use entity's defaults
const defaults = new AIModelEntity().getDefaults()
const defaults = new AIModelEntity().entity

super(
path.join(aidePaths.getGlobalLowdbPath(), 'ai-models.json'),
Expand Down
5 changes: 2 additions & 3 deletions src/extension/webview-api/lowdb/ai-provider-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,15 @@ const findNewModel = async (
new AIModelEntity({
name,
providerOrBaseUrl
})
}).entity
)
}

class AIProviderDB extends BaseDB<AIProvider> {
static readonly schemaVersion = 1

constructor() {
// Use entity's defaults
const defaults = new AIProviderEntity().getDefaults()
const defaults = new AIProviderEntity().entity

super(
path.join(aidePaths.getGlobalLowdbPath(), 'ai-providers.json'),
Expand Down
3 changes: 1 addition & 2 deletions src/extension/webview-api/lowdb/chat-sessions-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ class ChatSessionsDB extends BaseDB<ChatSession> {
static readonly schemaVersion = 1

constructor() {
// Use entity's defaults
const defaults = new ChatSessionEntity().getDefaults()
const defaults = new ChatSessionEntity().entity

super(
path.join(aidePaths.getWorkspaceLowdbPath(), 'sessions.json'),
Expand Down
6 changes: 3 additions & 3 deletions src/extension/webview-api/lowdb/doc-sites-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class DocSitesDB extends BaseDB<DocSite> {
static readonly schemaVersion = 1

constructor() {
const defaults = new DocSiteEntity().getDefaults()
const defaults = new DocSiteEntity().entity
super(
path.join(aidePaths.getGlobalLowdbPath(), 'doc-sites.json'),
defaults,
Expand All @@ -21,7 +21,7 @@ class DocSitesDB extends BaseDB<DocSite> {
id?: string
}
): Promise<DocSite> {
const docSite = new DocSiteEntity(item)
const docSite = new DocSiteEntity(item).entity
return super.add(docSite)
}

Expand All @@ -30,7 +30,7 @@ class DocSitesDB extends BaseDB<DocSite> {
id?: string
})[]
): Promise<DocSite[]> {
const docSites = items.map(item => new DocSiteEntity(item))
const docSites = items.map(item => new DocSiteEntity(item).entity)
return super.batchAdd(docSites)
}

Expand Down
5 changes: 3 additions & 2 deletions src/extension/webview-api/lowdb/settings-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class SettingsDB extends BaseDB<Settings> {
static readonly schemaVersion = 1

constructor(filePath: string) {
const defaults = new SettingsEntity().getDefaults()
const defaults = new SettingsEntity().entity
super(filePath, defaults, SettingsDB.schemaVersion)
}

Expand All @@ -39,7 +39,8 @@ class SettingsDB extends BaseDB<Settings> {
value,
category: config.category,
updatedAt: Date.now()
})
}).entity

return this.add(setting)
}

Expand Down
16 changes: 2 additions & 14 deletions src/shared/entities/ai-model-entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,8 @@ export interface AIModel extends IBaseEntity {
toolsCallSupport: AIModelSupport
}

export class AIModelEntity extends BaseEntity<AIModel> implements AIModel {
id!: string

providerOrBaseUrl!: AIProviderType | string

name!: string

imageSupport!: AIModelSupport

audioSupport!: AIModelSupport

toolsCallSupport!: AIModelSupport

getDefaults(): AIModel {
export class AIModelEntity extends BaseEntity<AIModel> {
protected getDefaults(): AIModel {
return {
id: uuidv4(),
providerOrBaseUrl: AIProviderType.OpenAI,
Expand Down
23 changes: 2 additions & 21 deletions src/shared/entities/ai-provider-entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,27 +12,8 @@ export interface AIProvider extends IBaseEntity {
manualModels: string[]
}

export class AIProviderEntity
extends BaseEntity<AIProvider>
implements AIProvider
{
id!: string

name!: string

type!: AIProviderType

order!: number

extraFields!: Record<string, string>

allowRealTimeModels!: boolean

realTimeModels!: string[]

manualModels!: string[]

getDefaults(): AIProvider {
export class AIProviderEntity extends BaseEntity<AIProvider> {
protected getDefaults(): AIProvider {
return {
id: uuidv4(),
name: 'unknown',
Expand Down
6 changes: 4 additions & 2 deletions src/shared/entities/base-entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ export interface IBaseEntity {
}

export abstract class BaseEntity<T extends IBaseEntity> {
entity: T

constructor(data?: Partial<T>) {
Object.assign(this, this.getDefaults(), data ?? {})
this.entity = { ...this.getDefaults(), ...(data ?? {}) }
}

abstract getDefaults(): Partial<T>
protected abstract getDefaults(): T
}
65 changes: 65 additions & 0 deletions src/shared/entities/chat-context-entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { ChatContextType, type Conversation } from '@shared/types/chat-context'
import type { SettingsContext } from '@shared/types/chat-context/settings-context'
import { v4 as uuidv4 } from 'uuid'

import { BaseEntity, type IBaseEntity } from './base-entity'
import { ChatSessionEntity, type ChatSession } from './chat-session-entity'

export interface ChatContext extends IBaseEntity {
type: ChatContextType
createdAt: number
updatedAt: number
conversations: Conversation[]
settings: SettingsContext
}

export class ChatContextEntity extends BaseEntity<ChatContext> {
getDefaults(): ChatContext {
const now = Date.now()
return {
id: uuidv4(),
type: ChatContextType.Chat,
createdAt: now,
updatedAt: now,
conversations: [],
settings: {
allowLongFileScan: false,
explicitContext: '总是用中文回复',
fastApplyModelName: 'gpt-4o-mini',
modelName: 'gpt-4o',
useFastApply: true
}
}
}

toChatSession(): ChatSession {
const { entity } = this

return new ChatSessionEntity({
id: entity.id,
title: this.getTitleFromConversations(entity.conversations),
type: entity.type,
createdAt: entity.createdAt,
updatedAt: entity.updatedAt
}).entity
}

private getTitleFromConversations = (
conversations: Conversation[],
defaultTitle = 'New Chat'
) => {
let firstHumanMessageText = ''

conversations
.filter(conversation => conversation.role === 'human')
.forEach(conversation =>
conversation.contents.forEach(content => {
if (content.type === 'text' && !firstHumanMessageText) {
firstHumanMessageText = content.text
}
})
)

return firstHumanMessageText || defaultTitle
}
}
17 changes: 2 additions & 15 deletions src/shared/entities/chat-session-entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,8 @@ export interface ChatSession extends IBaseEntity {
title: string
}

export class ChatSessionEntity
extends BaseEntity<ChatSession>
implements ChatSession
{
id!: string

type!: ChatContextType

createdAt!: number

updatedAt!: number

title!: string

getDefaults(): ChatSession {
export class ChatSessionEntity extends BaseEntity<ChatSession> {
protected getDefaults(): ChatSession {
const now = Date.now()
return {
id: uuidv4(),
Expand Down
26 changes: 26 additions & 0 deletions src/shared/entities/conversation-entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import type { MessageType } from '@langchain/core/messages'
import type { PluginState } from '@shared/plugins/base/types'
import type { LangchainMessageContents } from '@shared/types/chat-context/langchain-message'
import { v4 as uuidv4 } from 'uuid'

import { BaseEntity, type IBaseEntity } from './base-entity'

export interface Conversation extends IBaseEntity {
createdAt: number
role: MessageType
contents: LangchainMessageContents
richText?: string
pluginStates: Record<string, PluginState>
}

export class ConversationEntity extends BaseEntity<Conversation> {
protected getDefaults(): Conversation {
return {
id: uuidv4(),
createdAt: Date.now(),
role: 'human',
contents: [],
pluginStates: {}
}
}
}
14 changes: 2 additions & 12 deletions src/shared/entities/doc-site-entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,8 @@ export interface DocSite extends IBaseEntity {
isIndexed: boolean
}

export class DocSiteEntity extends BaseEntity<DocSite> implements DocSite {
id!: string

name!: string

url!: string

isCrawled!: boolean

isIndexed!: boolean

getDefaults(): DocSite {
export class DocSiteEntity extends BaseEntity<DocSite> {
protected getDefaults(): DocSite {
return {
id: uuidv4(),
name: 'unknown',
Expand Down
2 changes: 2 additions & 0 deletions src/shared/entities/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
export * from './ai-model-entity'
export * from './ai-provider-entity'
export * from './base-entity'
export * from './chat-context-entity'
export * from './chat-session-entity'
export * from './conversation-entity'
export * from './doc-site-entity'
export * from './settings-entity'
14 changes: 2 additions & 12 deletions src/shared/entities/settings-entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,8 @@ export interface Settings extends IBaseEntity {
updatedAt: number
}

export class SettingsEntity extends BaseEntity<Settings> implements Settings {
id!: string

key!: SettingKey

value!: SettingValue<SettingKey>

category!: SettingCategory

updatedAt!: number

getDefaults(): Settings {
export class SettingsEntity extends BaseEntity<Settings> {
protected getDefaults(): Settings {
return {
id: uuidv4(),
key: 'unknown' as SettingKey,
Expand Down
Loading

0 comments on commit d5a9a30

Please sign in to comment.