Skip to content

Commit

Permalink
Code cleanup, fix bugs in chats (esp. running commands autonomously)
Browse files Browse the repository at this point in the history
  • Loading branch information
SKaplanOfficial committed Jun 30, 2023
1 parent b35c10f commit 88e2a49
Show file tree
Hide file tree
Showing 33 changed files with 282 additions and 241 deletions.
2 changes: 1 addition & 1 deletion src/chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export default function Command(props: { arguments: { initialQuery: string } })
const preferences = getPreferenceValues<CommandPreferences>();

const options = {
minNumFiles: 0,
minNumFiles: 1,
acceptedFileExtensions: undefined,
useMetadata: true,
useAudioDetails: true,
Expand Down
2 changes: 1 addition & 1 deletion src/components/Chats/ChatSettingsForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,7 @@ export default function ChatSettingsForm(props: {
/>
</Form.Dropdown>

<Form.TextField
<Form.TextArea
title="Base Prompt"
placeholder="Context prompt for all queries"
info="A context prompt provided to the model endpoint alongside all queries. This maintains context throughout the conversation."
Expand Down
58 changes: 31 additions & 27 deletions src/components/Chats/CommandChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export default function CommandChatView(props: {
fileContents,
isLoading: loadingSelectedFiles,
revalidate: revalidateFiles,
} = useFileContents(options);
} = useFileContents({ ...options, minNumFiles: options.minNumFiles && query != "" ? 1 : 0 });
const {
data,
isLoading: loadingData,
Expand All @@ -95,8 +95,12 @@ export default function CommandChatView(props: {
const namePrompt =
"Come up with a title, in Title Case, for a conversation started with the following query. The title must summarize the intent of the query. The title must be three words or shorter. Output only the title without commentary or labels. For example, if the query is 'What are galaxies?', the title you output might be 'Question About Galaxies'. Here is the query: ";
const nameComponent =
(await runModel(namePrompt, namePrompt + `'''${subbedQuery}'''`, subbedQuery)) ||
query.trim().split(" ").splice(0, 2).join(" ");
(await runModel(
namePrompt,
namePrompt +
`'''${subbedQuery.match(/(?<=My next query is: ###)[\s\S]*(?=### <END OF QUERY>)/g)?.[0]?.trim() || ""}'''`,
subbedQuery
)) || query.trim().split(" ").splice(0, 2).join(" ");
const dateComponent = new Date().toLocaleDateString("en-US", {
year: "numeric",
month: "long",
Expand Down Expand Up @@ -151,12 +155,7 @@ export default function CommandChatView(props: {
const conversation = currentChat ? chats.loadConversation(currentChat.name) || [] : [];

// Get the most up-to-date file selection
await new Promise((resolve) => {
revalidateFiles();
if (!loadingSelectedFiles) {
resolve(true);
}
});
const { selectedFiles: files, fileContents: contents } = await revalidateFiles();

// Get command descriptions
const commands = await LocalStorage.allItems();
Expand All @@ -167,38 +166,40 @@ export default function CommandChatView(props: {

// Prepend instructions to the query, enable the model, and reattempt
subbedQuery = `${`You are an interactive chatbot, and I am giving you instructions. You will use this base prompt for context as you consider my next input. It is currently ${new Date().toISOString()}. Here is the prompt: ###${basePrompt}###\n\n${
currentChat && !conversation.join("\n").includes(currentChat.basePrompt)
? `You will also consider the following contextual information: ###${currentChat.contextData
currentChat &&
currentChat.contextData.length > 0 &&
!conversation.join("\n").includes(currentChat.contextData[0].data)
? `\n\nYou will also consider this information: ###${currentChat.contextData
.map((data) => `${data.source}:${data.data}`)
.join("\n\n")}###\n\n`
: ``
}${
((currentChat && currentChat.useSelectedFilesContext) ||
useFiles ||
(currentChat == undefined && useFiles == undefined)) &&
selectedFiles?.paths?.length
? ` You will also consider the following details about selected files. Here are the file details, provided by your knowledge system: ###${
fileContents?.contents || ""
}###\n\n`
files?.paths?.length
? `\n\nYou will also consider these files: ###${contents?.contents || ""}###\n\n`
: ``
}${
((currentChat && currentChat.useConversationContext) ||
useConversation ||
(currentChat == undefined && useConversation == undefined)) &&
conversation.length
? `You will also consider our conversation history. The history so far: ###${conversation
.map((entry) => entry.replaceAll(/(USER_QUERY|MODEL_REPONSE):/g, "").replaceAll(/{{cmd:(.*?):(.*?)}}/g, ""))
? `\n\nYou will also consider our conversation history. The history so far: ###${conversation
.map((entry) =>
entry.replaceAll(/(USER_QUERY|MODEL_RESPONSE):/g, "").replaceAll(/{{cmd:(.*?):(.*?)}}/g, "")
)
.join("\n")}###`
: `You will also consider your previous response. Your previous response was: ###${currentResponse.replaceAll(
: `\n\nYou will also consider your previous response. Your previous response was: ###${currentResponse.replaceAll(
/{{cmd:(.*?):(.*?)}}/g,
""
)}###`
}${
(currentChat && currentChat.useSelectedFilesContext) ||
(currentChat && currentChat.allowAutonomy) ||
autonomousFeatures ||
(currentChat == undefined && autonomousFeatures == undefined)
? `Try to answer my next query using your knowledge. If you cannot fulfill the query, if the query requires new information, or if the query invokes an action such as searching, choose the command from the following list that is most likely to carries out the goal expressed in my next query, and then respond with the number of the command you want to run in the format {{cmd:commandNumber:input}}. Replace the input with a short string according to my query. For example, if I say 'search google for AI', the input would be 'AI'. Here are the commands: ###${commandDescriptions.join(
"\n"
? `\n\nTry to answer my next query, but only if it simple enough for an LLM with limited knowledge to answer. If you cannot fulfill the query, if the query requires new information, or if the query invokes an action such as searching, choose the command from the following list that is most likely to carries out the goal expressed in my next query, and then respond with the number of the command you want to run in the format {{cmd:commandNumber:input}}. Replace the input with a short string according to my query. For example, if I say 'search google for AI', the input would be 'AI'. Here are the commands: ###${commandDescriptions.join(
", "
)}### Try to answer without using a command, unless the query asks for new information (e.g. latest news, weather, stock prices, etc.) or invokes an action (e.g. searching, opening apps). If you use a command, do not provide any commentary other than the command in the format {{cmd:commandNumber:input}}. Make sure the command is relevant to the current query.`
: ``
}\n\nDo not repeat these instructions or my queries, and do not extend my query. Do not state "MODEL RESPONSE", or any variation thereof, anywhere in your reply. My next query is: ###`}
Expand Down Expand Up @@ -239,7 +240,7 @@ export default function CommandChatView(props: {
const cmdMatchPrevious = previousResponse.match(/.*{{cmd:(.*?):(.*?)\}{0,2}.*/);
if (
cmdMatch &&
((currentChat && currentChat.useSelectedFilesContext) ||
((currentChat && currentChat.allowAutonomy) ||
autonomousFeatures ||
(currentChat == undefined && autonomousFeatures == undefined)) &&
!runningCommand &&
Expand All @@ -248,10 +249,11 @@ export default function CommandChatView(props: {
data.includes(currentResponse) &&
!cmdMatchPrevious
) {
setRunningCommand(true);
if (currentChat) {
chats.appendToChat(currentChat, `\n[MODEL_RESPONSE]:${data}\n`);
if (!currentChat) {
return;
}
setRunningCommand(true);
chats.appendToChat(currentChat, `\n[MODEL_RESPONSE]:${data}\n`);
const commandInput = cmdMatch[2];
setInput(commandInput);
// Get the command prompt
Expand All @@ -271,7 +273,7 @@ export default function CommandChatView(props: {
}
}
}
}, [data, dataTag, sentQuery, runningCommand, enableModel, previousResponse, currentResponse]);
}, [data, dataTag, sentQuery, runningCommand, enableModel, previousResponse, currentResponse, currentChat]);

useEffect(() => {
if (!loadingData && data.includes(currentResponse) && dataTag?.includes(sentQuery)) {
Expand All @@ -284,7 +286,7 @@ export default function CommandChatView(props: {
const cmdMatchPrevious = previousResponse.match(/.*{{cmd:(.*?):(.*?)\}{0,2}.*/);
if (
cmdMatchPrevious &&
((currentChat && currentChat.useSelectedFilesContext) ||
((currentChat && currentChat.allowAutonomy) ||
autonomousFeatures ||
(currentChat == undefined && autonomousFeatures == undefined)) &&
!loadingData &&
Expand Down Expand Up @@ -396,6 +398,8 @@ export default function CommandChatView(props: {
query={sentQuery}
basePrompt={basePrompt}
onSubmit={(values) => {
setEnableModel(false);
stopModel();
setInput("");
setRunningCommand(false);
submitQuery(values.queryField);
Expand Down
2 changes: 1 addition & 1 deletion src/components/Chats/actions/ChatActionPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { DeleteAllChatsAction, DeleteChatAction } from "./DeleteChatActions";
import { defaultAdvancedSettings } from "../../../data/default-advanced-settings";
import ChatSettingsForm from "../ChatSettingsForm";
import { CopyChatActionsSection } from "./CopyChatActions";
import { anyActionsEnabled, isActionEnabled } from "../../actions/action-utils";
import { anyActionsEnabled, isActionEnabled } from "../../../utils/action-utils";
import { AdvancedActionSubmenu } from "../../actions/AdvancedActionSubmenu";
import ContextSettingsActionSection from "./ContextSettingsActionSection";
import { Chat, ChatManager } from "../../../utils/types";
Expand Down
2 changes: 1 addition & 1 deletion src/components/Chats/actions/CopyChatActions.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Action, ActionPanel } from "@raycast/api";
import { defaultAdvancedSettings } from "../../../data/default-advanced-settings";
import { anyActionsEnabled } from "../../actions/action-utils";
import { anyActionsEnabled } from "../../../utils/action-utils";

export const CopyChatActionsSection = (props: {
response: string;
Expand Down
4 changes: 3 additions & 1 deletion src/components/Commands/CommandDetailView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ export default function CommandDetailView(props: {
return (
<Detail
isLoading={isLoading}
markdown={`# ${commandName}\n${response}`}
markdown={`# ${commandName}\n${response
.replaceAll("<", "\\<")
.replaceAll(/(?<!(```|\t..| {2}.))([\s\S]*?)\n$/gm, "$1\n\n$2")}`}
navigationTitle={commandName}
actions={
<ResponseActions
Expand Down
2 changes: 1 addition & 1 deletion src/components/Commands/CommandForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import * as fs from "fs";
import path from "path";
import { ADVANCED_SETTINGS_FILENAME, commandCategories } from "../../utils/constants";
import { useAdvancedSettings } from "../../hooks/useAdvancedSettings";
import { isActionEnabled } from "../actions/action-utils";
import { isActionEnabled } from "../../utils/action-utils";

interface CommandFormValues {
name: string;
Expand Down
2 changes: 1 addition & 1 deletion src/components/Commands/actions/CommandControlActions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import CommandForm from "../CommandForm";
import { QUICKLINK_URL_BASE } from "../../../utils/constants";
import { updateCommand } from "../../../utils/command-utils";
import { defaultAdvancedSettings } from "../../../data/default-advanced-settings";
import { anyActionsEnabled } from "../../actions/action-utils";
import { anyActionsEnabled } from "../../../utils/action-utils";

/**
* Section for actions related to modifying commands (editing, deleting, etc.).
Expand Down
2 changes: 1 addition & 1 deletion src/components/Commands/actions/CopyCommandActions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Command, ExtensionPreferences, StoreCommand, isCommand } from "../../..
import path from "path";
import * as fs from "fs";
import { defaultAdvancedSettings } from "../../../data/default-advanced-settings";
import { isActionEnabled } from "../../actions/action-utils";
import { isActionEnabled } from "../../../utils/action-utils";

/**
* Action panel section for actions related to copying command data to the clipboard.
Expand Down
2 changes: 1 addition & 1 deletion src/components/Commands/actions/InstallCommandAction.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Action, Icon, LocalStorage, Toast, showToast } from "@raycast/api";
import { Command, StoreCommand } from "../../../utils/types";
import { defaultAdvancedSettings } from "../../../data/default-advanced-settings";
import { isActionEnabled } from "../../actions/action-utils";
import { isActionEnabled } from "../../../utils/action-utils";

/**
* Action to install a command from the PromptLab store.
Expand Down
2 changes: 1 addition & 1 deletion src/components/Commands/actions/RunCommandAction.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Action, Icon } from "@raycast/api";
import { Command, StoreCommand, isCommand, isTrueStr } from "../../../utils/types";
import CommandResponse from "../CommandResponse";
import { defaultAdvancedSettings } from "../../../data/default-advanced-settings";
import { isActionEnabled } from "../../actions/action-utils";
import { isActionEnabled } from "../../../utils/action-utils";

/**
* Action to run a command.
Expand Down
2 changes: 1 addition & 1 deletion src/components/Commands/actions/ShareCommandAction.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Command, StoreCommand } from "../../../utils/types";
import { STORE_ENDPOINT, STORE_KEY } from "../../../utils/constants";
import fetch from "node-fetch";
import { defaultAdvancedSettings } from "../../../data/default-advanced-settings";
import { isActionEnabled } from "../../actions/action-utils";
import { isActionEnabled } from "../../../utils/action-utils";

/**
* Action to share a command to the PromptLab store.
Expand Down
2 changes: 1 addition & 1 deletion src/components/Models/actions/AddNewModelAction.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Action, Icon } from "@raycast/api";
import ModelForm from "../ModelForm";
import { ModelManager } from "../../../utils/types";
import { isActionEnabled } from "../../actions/action-utils";
import { isActionEnabled } from "../../../utils/action-utils";
import { defaultAdvancedSettings } from "../../../data/default-advanced-settings";

/**
Expand Down
2 changes: 1 addition & 1 deletion src/components/Models/actions/CopyModelActions.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Action } from "@raycast/api";
import { defaultAdvancedSettings } from "../../../data/default-advanced-settings";
import { Model, ModelManager } from "../../../utils/types";
import { isActionEnabled } from "../../actions/action-utils";
import { isActionEnabled } from "../../../utils/action-utils";

/**
* Action to copy a model's JSON representation to the clipboard.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Action, Icon, useNavigation } from "@raycast/api";
import ModelForm from "../ModelForm";
import { Model, ModelManager } from "../../../utils/types";
import { defaultAdvancedSettings } from "../../../data/default-advanced-settings";
import { isActionEnabled } from "../../actions/action-utils";
import { isActionEnabled } from "../../../utils/action-utils";

/**
* Action to create a new model based on an existing model.
Expand Down
2 changes: 1 addition & 1 deletion src/components/Models/actions/DeleteModelActions.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Action, Alert, Icon, confirmAlert, showToast } from "@raycast/api";
import { defaultAdvancedSettings } from "../../../data/default-advanced-settings";
import { Model, ModelManager } from "../../../utils/types";
import { isActionEnabled } from "../../actions/action-utils";
import { isActionEnabled } from "../../../utils/action-utils";

/**
* Action to delete a model.
Expand Down
2 changes: 1 addition & 1 deletion src/components/Models/actions/EditModelAction.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Action, Icon } from "@raycast/api";
import ModelForm from "../ModelForm";
import { Model, ModelManager } from "../../../utils/types";
import { defaultAdvancedSettings } from "../../../data/default-advanced-settings";
import { isActionEnabled } from "../../actions/action-utils";
import { isActionEnabled } from "../../../utils/action-utils";

/**
* Action to edit a model.
Expand Down
2 changes: 1 addition & 1 deletion src/components/Models/actions/ManageModelsActionsPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import CreateModelDerivativeAction from "./CreateModelDerivativeAction";
import { DeleteAllModelsAction, DeleteModelAction } from "./DeleteModelActions";
import { AdvancedActionSubmenu } from "../../actions/AdvancedActionSubmenu";
import { defaultAdvancedSettings } from "../../../data/default-advanced-settings";
import { anyActionsEnabled } from "../../actions/action-utils";
import { anyActionsEnabled } from "../../../utils/action-utils";
import { Model, ModelManager } from "../../../utils/types";

export default function ManageModelsActionPanel(props: {
Expand Down
2 changes: 1 addition & 1 deletion src/components/Models/actions/ToggleModelDefaultAction.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Action, Icon } from "@raycast/api";
import { defaultAdvancedSettings } from "../../../data/default-advanced-settings";
import { Model, ModelManager } from "../../../utils/types";
import { isActionEnabled } from "../../actions/action-utils";
import { isActionEnabled } from "../../../utils/action-utils";

/**
* Action to toggle a model's default status.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Action, Icon } from "@raycast/api";
import { Model, ModelManager } from "../../../utils/types";
import { defaultAdvancedSettings } from "../../../data/default-advanced-settings";
import { isActionEnabled } from "../../actions/action-utils";
import { isActionEnabled } from "../../../utils/action-utils";

/**
* Action to toggle a model's favorite status.
Expand Down
2 changes: 1 addition & 1 deletion src/components/actions/OpenFileActions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
} from "../../utils/constants";
import path from "path";
import { defaultAdvancedSettings } from "../../data/default-advanced-settings";
import { isActionEnabled } from "./action-utils";
import { isActionEnabled } from "../../utils/action-utils";

/**
* Action to open the placeholders guide in the default markdown text editor.
Expand Down
2 changes: 1 addition & 1 deletion src/data/default-commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ export const defaultCommands = {
"Summarize Selected Files": {
name: "Summarize Selected Files",
prompt:
"I want you to derive insights from the following information about some files. You will respond with a descriptive discussion of each file, its main topics, and its significance. You will use all information provided to infer more insights. Provide several insights derived from metadata or EXIF data. Give an overview of lists, content, objects, etc. without listing specific details. Discuss the general position of any objects, points, or rectangles within images and videos without using numbers. Don't repeat yourself. Don't list properties without describing their value.\n\n{{images:Discuss the payload of any barcodes or QR codes. For images, use the general size and arrangement of objects to help predict what the file is about.}}\n\n{{videos:For videos, discuss what they are about in friendly paragraphs without listing off specific details. You must summarize any transcribed text in 100 words or fewer, while limited the entire output to two paragraphs.}}\n\n{{svg:For SVGs, predict what object(s) the overall code will render as.:Draw connections between different pieces of information and discuss the significance of any relationships therein. Use the file names as headings. Limit your discussion to one short paragraph. At the end, include a list of relevant links formatted as a markdown list. Here are the files:}}",
"I want you to derive insights from the following information about some files. You will respond with a descriptive discussion of each file, its main topics, and its significance. You will use all information provided to infer more insights. Provide several insights derived from metadata or EXIF data. Give an overview of lists, content, objects, etc. without listing specific details. Discuss the general position of any objects, points, or rectangles within images and videos without using numbers. Don't repeat yourself. Don't list properties without describing their value.{{images:\nDiscuss the payload of any barcodes or QR codes, if relevant. For images, use the general size and arrangement of objects to help predict what the file is about.}}{{videos:\nFor videos, discuss what they are about in friendly paragraphs without listing off specific details. You must summarize any transcribed text in 100 words or fewer, while limited the entire output to two paragraphs.}}{{svg:\nFor SVGs, predict what object(s) the overall code will render as based on shapes, colors, and other details.}} Draw connections between different pieces of information and discuss the significance of any relationships therein. Use the file names as headings. Limit your discussion to one short paragraph. At the end, include a list of relevant links formatted as a markdown list. Here are the files:",
icon: "speech-bubble-important-16",
iconColor: "raycast-primary-text",
minNumFiles: "1",
Expand Down
Loading

0 comments on commit 88e2a49

Please sign in to comment.