Skip to content

Commit

Permalink
feat(core): add set preset command
Browse files Browse the repository at this point in the history
  • Loading branch information
dingyi222666 committed Sep 23, 2023
1 parent e89d236 commit 9b45bc2
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
8 changes: 8 additions & 0 deletions packages/core/src/commands/preset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,14 @@ export function apply(ctx: Context, config: Config, chain: ChatChain) {
})
})

ctx.command('chathub.preset.set <preset:string>', '修改一个预设', {
authority: 3
}).action(async ({ session }, preset) => {
await chain.receiveCommand(session, 'set_preset', {
setPreset: preset
})
})

ctx.command('chathub.preset.delete <preset:string>', '删除一个预设', {
authority: 3
}).action(async ({ session }, preset) => {
Expand Down
61 changes: 61 additions & 0 deletions packages/core/src/middlewares/set_preset.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { Context } from 'koishi'
import { Config } from '../config'
import { ChainMiddlewareRunStatus, ChatChain } from '../chains/chain'
import fs from 'fs/promises'
import { dump, load } from 'js-yaml'
import { RawPreset } from '../llm-core/prompt'

export function apply(ctx: Context, config: Config, chain: ChatChain) {
chain
.middleware('set_preset', async (session, context) => {
const { command } = context

if (command !== 'set_preset') {
return ChainMiddlewareRunStatus.SKIPPED
}

const presetName = context.options.setPreset

const presetService = ctx.chathub.preset

const preset = await presetService.getPreset(presetName)

if (preset.messages.length > 1) {
await context.send(
`不支持修改 ${presetName} 预设!该预设自定义了多条消息,属于复杂预设,无法使用此命令修改,请自行前往控制面板里的资源管理器编辑预设文件。`
)

return ChainMiddlewareRunStatus.STOP
}

await context.send('请发送你的预设内容。')

const result = await session.prompt(1000 * 30)

if (!result) {
context.message = `添加预设超时,已取消添加预设: ${presetName}`
return ChainMiddlewareRunStatus.STOP
}

const presetObject = load(preset.rawText) as RawPreset

presetObject.prompts[0].content = result

await fs.writeFile(preset.path, dump(presetObject))

context.message = `预设修改成功,预设名称为: ${presetName}。 请调用预设列表命令查看。`

return ChainMiddlewareRunStatus.STOP
})
.after('lifecycle-handle_command')
}

declare module '../chains/chain' {
interface ChainMiddlewareName {
set_preset: string
}

interface ChainMiddlewareContextOptions {
setPreset?: string
}
}

0 comments on commit 9b45bc2

Please sign in to comment.