| 1 | import { CustomCommand, SlashCommand, SlashCommandDescription } from "../"; |
| 2 | import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString"; |
| 3 | import { replaceSlashCommandWithPromptInChatHistory } from "../promptFiles/v1/updateChatHistory"; |
| 4 | import { renderPromptFileV2 } from "../promptFiles/v2/renderPromptFile"; |
| 5 | import { renderChatMessage } from "../util/messageContent"; |
| 6 | |
| 7 | import SlashCommands from "./slash"; |
| 8 | |
| 9 | export function slashFromCustomCommand( |
| 10 | customCommand: CustomCommand, |
| 11 | ): SlashCommand { |
| 12 | const commandName = customCommand.name.startsWith("/") |
| 13 | ? customCommand.name.substring(1) |
| 14 | : customCommand.name; |
| 15 | return { |
| 16 | name: commandName, |
| 17 | description: customCommand.description ?? "", |
| 18 | prompt: customCommand.prompt, |
| 19 | run: async function* ({ |
| 20 | input, |
| 21 | llm, |
| 22 | history, |
| 23 | ide, |
| 24 | completionOptions, |
| 25 | config, |
| 26 | selectedCode, |
| 27 | fetch, |
| 28 | }) { |
| 29 | // Render prompt template |
| 30 | let renderedPrompt: string; |
| 31 | if (customCommand.prompt.includes("{{{ input }}}")) { |
| 32 | renderedPrompt = await renderTemplatedString( |
| 33 | customCommand.prompt, |
| 34 | ide.readFile.bind(ide), |
| 35 | { input }, |
| 36 | ); |
| 37 | } else { |
| 38 | const renderedPromptFile = await renderPromptFileV2( |
| 39 | customCommand.prompt, |
| 40 | { |
| 41 | config, |
| 42 | llm, |
| 43 | ide, |
| 44 | selectedCode, |
| 45 | fetch, |
| 46 | fullInput: input, |
| 47 | embeddingsProvider: config.modelsByRole.embed[0], |
| 48 | reranker: config.modelsByRole.rerank[0], |
| 49 | }, |
| 50 | ); |
| 51 | |
| 52 | renderedPrompt = renderedPromptFile[1]; |
| 53 | } |
| 54 | |
| 55 | // Replaces slash command messages with the rendered prompt |
| 56 | // which INCLUDES the input |
| 57 | const messages = replaceSlashCommandWithPromptInChatHistory( |
| 58 | history, |
| 59 | commandName, |
| 60 | renderedPrompt, |
| 61 | undefined, |
| 62 | ); |
| 63 | |
| 64 | for await (const chunk of llm.streamChat( |
| 65 | messages, |
| 66 | new AbortController().signal, |
| 67 | completionOptions, |
| 68 | )) { |
| 69 | yield renderChatMessage(chunk); |
| 70 | } |
| 71 | }, |
| 72 | }; |
| 73 | } |
| 74 | |
| 75 | export function slashCommandFromDescription( |
| 76 | desc: SlashCommandDescription, |
| 77 | ): SlashCommand | undefined { |
| 78 | const cmd = SlashCommands.find((cmd) => cmd.name === desc.name); |
| 79 | if (!cmd) { |
| 80 | return undefined; |
| 81 | } |
| 82 | return { |
| 83 | ...cmd, |
| 84 | params: desc.params, |
| 85 | description: desc.description ?? cmd.description, |
| 86 | }; |
| 87 | } |