51 lines
1.5 KiB
TypeScript
51 lines
1.5 KiB
TypeScript
import { IKBotTask } from '../types'
|
|
import OpenAI from 'openai'
|
|
import { marked } from 'marked'
|
|
import { markedTerminal } from 'marked-terminal'
|
|
import * as path from 'path'
|
|
import { sync as write } from '@polymech/fs/write'
|
|
import { resolve } from '@polymech/commons'
|
|
|
|
import { logger } from '../index.js'
|
|
import { dumpAsScript } from '../utils/script.js'
|
|
import { applyFilters, Filter } from '../filters.js'
|
|
import { variables } from '../variables.js'
|
|
|
|
|
|
export const onCompletion = async (result: any = "", options: IKBotTask) => {
|
|
result = applyFilters(result, options.filters as Filter[] || [])
|
|
const vars = variables(options)
|
|
if (options.dst) {
|
|
const dstPath = path.resolve(resolve(options.dst, false, {
|
|
...vars,
|
|
MODEL: path.parse(options.model).name,
|
|
ROUTER: options.router,
|
|
}))
|
|
write(dstPath, result)
|
|
logger.debug(`Wrote completion result to ${dstPath} : ${options.dst}`)
|
|
} else {
|
|
marked.use(markedTerminal({
|
|
emoji: false,
|
|
}))
|
|
const content: string = marked(result) as string;
|
|
process.stdout.write(content)
|
|
}
|
|
dumpAsScript(options)
|
|
// process.exit(0)
|
|
return result
|
|
}
|
|
|
|
export const runCompletion = async (client: OpenAI, params: any, options: IKBotTask) => {
|
|
if (options.dry) {
|
|
logger.info('Dry run - skipping API call')
|
|
return false
|
|
}
|
|
const completion = await client.chat.completions.create({
|
|
model: options.model,
|
|
messages: params.messages,
|
|
})
|
|
const result = completion.choices[0].message.content
|
|
onCompletion(result, options)
|
|
return result
|
|
}
|