-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseModels.ts
86 lines (72 loc) · 2.35 KB
/
useModels.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { useCallback, useEffect } from 'react'
import {
ExtensionTypeEnum,
Model,
ModelEvent,
ModelExtension,
ModelFile,
events,
} from '@janhq/core'
import { useSetAtom } from 'jotai'
import { extensionManager } from '@/extension'
import {
configuredModelsAtom,
defaultModelAtom,
downloadedModelsAtom,
} from '@/helpers/atoms/Model.atom'
/**
* useModels hook - Handles the state of models
* It fetches the downloaded models, configured models and default model from Model Extension
* and updates the atoms accordingly.
*/
const useModels = () => {
const setDownloadedModels = useSetAtom(downloadedModelsAtom)
const setConfiguredModels = useSetAtom(configuredModelsAtom)
const setDefaultModel = useSetAtom(defaultModelAtom)
const getData = useCallback(() => {
const getDownloadedModels = async () => {
const models = await getLocalDownloadedModels()
setDownloadedModels(models)
}
const getConfiguredModels = async () => {
const models = await getLocalConfiguredModels()
setConfiguredModels(models)
}
const getDefaultModel = async () => {
const defaultModel = await getLocalDefaultModel()
setDefaultModel(defaultModel)
}
// Fetch all data
Promise.all([
getDownloadedModels(),
getConfiguredModels(),
getDefaultModel(),
])
}, [setDownloadedModels, setConfiguredModels, setDefaultModel])
useEffect(() => {
// Try get data on mount
getData()
// Listen for model updates
events.on(ModelEvent.OnModelsUpdate, async () => getData())
return () => {
// Remove listener on unmount
events.off(ModelEvent.OnModelsUpdate, async () => {})
}
}, [getData])
}
// TODO: Deprecated - Remove when moving to cortex.cpp
const getLocalDefaultModel = async (): Promise<Model | undefined> =>
extensionManager
.get<ModelExtension>(ExtensionTypeEnum.Model)
?.getDefaultModel()
// TODO: Deprecated - Remove when moving to cortex.cpp
const getLocalConfiguredModels = async (): Promise<ModelFile[]> =>
extensionManager
.get<ModelExtension>(ExtensionTypeEnum.Model)
?.getConfiguredModels() ?? []
// TODO: Deprecated - Remove when moving to cortex.cpp
const getLocalDownloadedModels = async (): Promise<ModelFile[]> =>
extensionManager
.get<ModelExtension>(ExtensionTypeEnum.Model)
?.getDownloadedModels() ?? []
export default useModels