From 9d8a25c0b02df084a5f3f94f932159cb5be3364c Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Wed, 6 Dec 2023 10:43:03 -0800 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20refactoring=20redux=20stor?= =?UTF-8?q?e?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/README.md | 4 + core/llm/constructMessages.ts | 19 + core/llm/index.ts | 39 +- core/llm/llms/FreeTrial.ts | 128 +++++++ core/llm/types.d.ts | 25 +- core/package-lock.json | 106 ++++++ core/package.json | 14 + gui/src/components/gui/StepContainer.tsx | 23 +- gui/src/components/gui/TimelineItem.tsx | 6 +- gui/src/pages/gui.tsx | 438 +++++++++-------------- gui/src/redux/slices/stateSlice.ts | 67 ++++ gui/src/redux/store.ts | 14 +- 12 files changed, 584 insertions(+), 299 deletions(-) create mode 100644 core/llm/constructMessages.ts create mode 100644 core/llm/llms/FreeTrial.ts create mode 100644 core/package-lock.json create mode 100644 core/package.json create mode 100644 gui/src/redux/slices/stateSlice.ts diff --git a/core/README.md b/core/README.md index 8bd1d35c3..d1e0ea709 100644 --- a/core/README.md +++ b/core/README.md @@ -22,6 +22,10 @@ Reasons to avoid Python TODO: +Little stuff: + +- create_client_session -> createAxiosConfig from requestOptions + Imports - tiktoken diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts new file mode 100644 index 000000000..5c4cec1fb --- /dev/null +++ b/core/llm/constructMessages.ts @@ -0,0 +1,19 @@ +import { ChatHistory, ChatMessage } from "./types"; + +export function constructMessages(history: ChatHistory): ChatMessage[] { + const msgs: ChatMessage[] = []; + + for (const historyItem of history) { + for (const ctxItem of historyItem.contextItems) { + msgs.push({ + role: historyItem.message.role, + name: ctxItem.name, + content: ctxItem.content, + summary: ctxItem.description, + }); + } + msgs.push(historyItem.message); + } + + return msgs; +} diff --git a/core/llm/index.ts b/core/llm/index.ts index 8ed91d184..a95a7ef1c 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -1,4 +1,4 @@ -import { CONTEXT_LENGTH_FOR_MODEL } from "./constants"; +import { CONTEXT_LENGTH_FOR_MODEL, DEFAULT_ARGS } from "./constants"; import { compileChatMessages, countTokens, @@ -6,14 +6,14 @@ import { } from "./countTokens"; import { CompletionOptions, RequestOptions, ChatMessage } from "./types"; -interface ILLM { +interface LLMOptions { title?: string; - uniqueId?: string; - model: string; + uniqueId: string; + model?: string; systemMessage?: string; - contextLength: number; - completionOptions: CompletionOptions; - requestOptions: RequestOptions; + contextLength?: number; + completionOptions?: CompletionOptions; + requestOptions?: RequestOptions; promptTemplates?: Record; templateMessages?: (messages: ChatMessage[]) => string; writeLog?: (str: string) => Promise; @@ -37,9 +37,9 @@ interface LLMFullCompletionOptions { maxTokens?: number; } -abstract class AbstractLLM implements ILLM { +export abstract class LLM implements LLMOptions { title?: string; - uniqueId?: string; + uniqueId: string; model: string; systemMessage?: string; contextLength: number; @@ -52,7 +52,7 @@ abstract class AbstractLLM implements ILLM { apiKey?: string; apiBase?: string; - constructor(options: ILLM) { + constructor(options: LLMOptions) { this.title = options.title; this.uniqueId = options.uniqueId; this.model = options.model; @@ -251,7 +251,7 @@ abstract class AbstractLLM implements ILLM { completionOptions )) { completion += chunk; - yield chunk; + yield { role: "assistant", content: chunk, summary: chunk }; } } else { for await (const chunk of this._streamChat(messages, completionOptions)) { @@ -263,11 +263,14 @@ abstract class AbstractLLM implements ILLM { this._logTokensGenerated(completionOptions.model, completion); } - private async *_streamComplete(prompt: string, options: CompletionOptions) { + protected async *_streamComplete( + prompt: string, + options: CompletionOptions + ): AsyncGenerator { throw new Error("Not implemented"); } - private async *_streamChat( + protected async *_streamChat( messages: ChatMessage[], options: CompletionOptions ): AsyncGenerator { @@ -285,7 +288,7 @@ abstract class AbstractLLM implements ILLM { } } - private async _complete(prompt: string, options: CompletionOptions) { + protected async _complete(prompt: string, options: CompletionOptions) { let completion = ""; for await (const chunk of this._streamComplete(prompt, options)) { completion += chunk; @@ -296,4 +299,12 @@ abstract class AbstractLLM implements ILLM { countTokens(text: string): number { return countTokens(text, this.model); } + + protected collectArgs(options: CompletionOptions): any { + return { + ...DEFAULT_ARGS, + // model: this.model, + ...options, + }; + } } diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts new file mode 100644 index 000000000..37483c56c --- /dev/null +++ b/core/llm/llms/FreeTrial.ts @@ -0,0 +1,128 @@ +import { LLM } from ".."; +import { ChatMessage, CompletionOptions } from "../types"; +import axios from "axios"; + +// const SERVER_URL = "http://127.0.0.1:8080" +const SERVER_URL = "https://proxy-server-l6vsfbzhba-uw.a.run.app"; + +class FreeTrial extends LLM { + private _getHeaders() { + return { uniqueId: this.uniqueId || "None" }; + } + + protected async _complete( + prompt: string, + options: CompletionOptions + ): Promise { + const args = this.collectArgs(options); + + const response = await axios.post( + `${SERVER_URL}/complete`, + { + messages: [{ role: "user", content: prompt }], + ...args, + }, + { + headers: this._getHeaders(), + // proxy: this.requestOptions.proxy, + } + ); + + if (response.status != 200) { + throw new Error(response.data); + } + + return response.data; + } + + protected async *_streamComplete( + prompt: string, + options: CompletionOptions + ): AsyncGenerator { + const args = this.collectArgs(options); + + const response = await axios.post( + `${SERVER_URL}/stream_complete`, + { + messages: [{ role: "user", content: prompt }], + ...args, + }, + { + headers: this._getHeaders(), + responseType: "stream", + // proxy: this.requestOptions.proxy, + } + ); + + if (response.status != 200) { + throw new Error(await streamToString(response.data)); + } + + for await (const chunk of response.data) { + if (chunk) { + let decodedChunk = chunk.toString("utf-8"); + yield decodedChunk; + } + } + } +} + +async function* streamChat(messages: ChatMessage[], options: any) { + const args = this.collectArgs(options); + + const response = await axios.post( + `${SERVER_URL}/stream_chat`, + { + messages, + ...args, + }, + { + headers: this.getHeaders(), + // proxy: requestOptions.proxy, + responseType: "stream", + } + ); + + if (response.status !== 200) { + throw new Error(await streamToString(response.data)); + } + + for await (const chunk of response.data) { + if (chunk) { + const jsonChunk = chunk.toString("utf-8"); + const chunks = jsonChunk.split("\n"); + + for (const chunk of chunks) { + if (chunk.trim() !== "") { + const loadedChunk = JSON.parse(chunk); + + yield { + role: "assistant", + content: loadedChunk.content || "", + }; + + if (this.model === "gpt-4") { + await delay(0.03); + } else { + await delay(0.01); + } + } + } + } + } +} + +async function delay(seconds: number) { + return new Promise((resolve) => setTimeout(resolve, seconds * 1000)); +} + +async function streamToString(stream: any) { + let decoder = new TextDecoder("utf-8"); + let result = ""; + for await (const chunk of stream) { + result += decoder.decode(chunk); + } + return result; +} + +export default FreeTrial; diff --git a/core/llm/types.d.ts b/core/llm/types.d.ts index 80c29ea2b..b1701a18d 100644 --- a/core/llm/types.d.ts +++ b/core/llm/types.d.ts @@ -27,4 +27,27 @@ interface ChatMessage { summary: string; } -export { CompletionOptions, RequestOptions, ChatMessage, ChatMessageRole }; +interface ContextItem { + content: string; + name: string; + description: string; + providerTitle: string; + itemId: string; +} + +interface ChatHistoryItem { + message: ChatMessage; + contextItems: ContextItem[]; +} + +type ChatHistory = ChatHistoryItem[]; + +export { + CompletionOptions, + RequestOptions, + ChatMessage, + ChatMessageRole, + ChatHistory, + ChatHistoryItem, + ContextItem, +}; diff --git a/core/package-lock.json b/core/package-lock.json new file mode 100644 index 000000000..61640c310 --- /dev/null +++ b/core/package-lock.json @@ -0,0 +1,106 @@ +{ + "name": "core", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "core", + "version": "1.0.0", + "license": "Apache-2.0", + "dependencies": { + "axios": "^1.6.2" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, + "node_modules/axios": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.2.tgz", + "integrity": "sha512-7i24Ri4pmDRfJTR7LDBhsOTtcm+9kjX5WiY1X3wIisx6G9So3pfMkEiU7emUBe46oceVImccTEM3k6C5dbVW8A==", + "dependencies": { + "follow-redirects": "^1.15.0", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/follow-redirects": { + "version": "1.15.3", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.3.tgz", + "integrity": "sha512-1VzOtuEM8pC9SFU1E+8KfTjZyMztRsgEfwQl44z8A25uy13jSzTj6dyK2Df52iV0vgHCfBwLhDWevLn95w5v6Q==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" + } + } +} diff --git a/core/package.json b/core/package.json new file mode 100644 index 000000000..091f60f31 --- /dev/null +++ b/core/package.json @@ -0,0 +1,14 @@ +{ + "name": "core", + "version": "1.0.0", + "description": "The Continue Core contains functionality that can be shared across web, VS Code, or Node.js server. It is written in TypeScript and contains much of the functionality that was previously inside of the legacy Continue Python Server.", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "Nate Sesti and Ty Dunn", + "license": "Apache-2.0", + "dependencies": { + "axios": "^1.6.2" + } +} diff --git a/gui/src/components/gui/StepContainer.tsx b/gui/src/components/gui/StepContainer.tsx index 59f17e102..b24b46223 100644 --- a/gui/src/components/gui/StepContainer.tsx +++ b/gui/src/components/gui/StepContainer.tsx @@ -19,9 +19,10 @@ import { StepDescription } from "../../schema/SessionState"; import { useSelector } from "react-redux"; import { RootStore } from "../../redux/store"; import { GUIClientContext } from "../../App"; +import { ChatHistoryItem } from "../../../../core/llm/types"; interface StepContainerProps { - step: StepDescription; + item: ChatHistoryItem; onReverse: () => void; onUserInput: (input: string) => void; onRetry: () => void; @@ -35,10 +36,6 @@ interface StepContainerProps { // #region styled components -const MainDiv = styled.div<{ - stepDepth: number; -}>``; - const ButtonsDiv = styled.div` display: flex; gap: 2px; @@ -69,7 +66,7 @@ function StepContainer(props: StepContainerProps) { const [isHovered, setIsHovered] = useState(false); const naturalLanguageInputRef = useRef(null); const userInputRef = useRef(null); - const isUserInput = props.step.name === "UserInputStep"; + const isUserInput = props.item.message.role === "user"; const sessionHistory = useSelector( (store: RootStore) => store.sessionState.history ); @@ -96,7 +93,7 @@ function StepContainer(props: StepContainerProps) { const logs = sessionHistory[props.index].logs; if (!logs || logs.length < 1) return; const prompt = logs[0].split("#########\n")[1]; - const completion = props.step.description; + const completion = props.item.message.content; console.log(prompt, completion, client); @@ -104,20 +101,18 @@ function StepContainer(props: StepContainerProps) { }; return ( - { setIsHovered(true); }} onMouseLeave={() => { setIsHovered(false); }} - hidden={props.step.hide as any} >
- {isHovered && (props.step.error || props.noUserInputParent) && ( + {isHovered && (false || props.noUserInputParent) && ( - {props.step.error && + {false && (( - + {(isHovered || typeof feedback !== "undefined") && !active && (
@@ -192,7 +187,7 @@ function StepContainer(props: StepContainerProps) {
)}
-
+ ); } diff --git a/gui/src/components/gui/TimelineItem.tsx b/gui/src/components/gui/TimelineItem.tsx index 4d9bb3d0e..a37a94057 100644 --- a/gui/src/components/gui/TimelineItem.tsx +++ b/gui/src/components/gui/TimelineItem.tsx @@ -4,6 +4,7 @@ import styled from "styled-components"; import { ChatBubbleOvalLeftIcon } from "@heroicons/react/24/outline"; import { getFontSize } from "../../util"; import { StepDescription } from "../../schema/SessionState"; +import { ChatHistoryItem } from "../../../../core/llm/types"; const CollapseButton = styled.div` background-color: ${vscBackground}; @@ -28,7 +29,7 @@ const CollapsedDiv = styled.div<{ fontSize?: number }>` `; interface TimelineItemProps { - step: StepDescription; + item: ChatHistoryItem; open: boolean; onToggle: () => void; children: any; @@ -50,7 +51,8 @@ function TimelineItem(props: TimelineItemProps) { )} - {props.step.error ? props.step.error.title : props.step.name} + {props.item.message.name || props.item.message.summary} + {/* {props.step.error ? props.step.error.title : props.step.name} */} ); diff --git a/gui/src/pages/gui.tsx b/gui/src/pages/gui.tsx index 102004394..d95e954e0 100644 --- a/gui/src/pages/gui.tsx +++ b/gui/src/pages/gui.tsx @@ -57,6 +57,14 @@ import { setTitle, } from "../redux/slices/sessionStateReducer"; import { StepDescription } from "../schema/SessionState"; +import FreeTrial from "../../../core/llm/llms/FreeTrial"; +import { constructMessages } from "../../../core/llm/constructMessages"; +import { + ChatHistory, + ChatHistoryItem, + ChatMessage, +} from "../../../core/llm/types"; +import { streamUpdate, submitMessage } from "../redux/slices/stateSlice"; const TopGuiDiv = styled.div` overflow-y: scroll; @@ -179,9 +187,7 @@ function GUI(props: GUIProps) { // #endregion // #region State - const [waitingForSteps, setWaitingForSteps] = useState(false); const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]); - const [waitingForClient, setWaitingForClient] = useState(true); const [showLoading, setShowLoading] = useState(false); useEffect(() => { @@ -218,6 +224,8 @@ function GUI(props: GUIProps) { const [userScrolledAwayFromBottom, setUserScrolledAwayFromBottom] = useState(false); + const state = useSelector((state: RootStore) => state.state); + useEffect(() => { const handleScroll = () => { // Scroll only if user is within 200 pixels of the bottom of the window. @@ -295,51 +303,25 @@ function GUI(props: GUIProps) { } } - setWaitingForSteps(true); - - // TODO: Sagas or something might be better? - const newHistory = [ - ...sessionState.history, - { - name: "User Input", - description: input, - observations: [], - logs: [], - step_type: "UserInputStep", - params: { - user_input: input, - context_items: sessionState.context_items, - }, - hide: false, - depth: 0, - }, - ]; - const state = { - history: newHistory, - context_items: sessionState.context_items, + const message: ChatMessage = { + role: "user", + content: input, + summary: input, }; - client.runFromState(state); - newHistory.push({ - name: "Generating Response...", - description: " ", - observations: [], - logs: [], - step_type: "SimpleChatStep", - params: {}, - hide: false, - depth: 0, - }); - dispatch(setHistory(newHistory)); - dispatch(setActive(true)); - for (let contextItem of sessionState.context_items) { - dispatch( - addContextItemAtIndex({ - item: contextItem, - index: newHistory.length - 1, - }) - ); - } - dispatch(clearContextItems()); + const historyItem: ChatHistoryItem = { + message, + contextItems: state.contextItems, + }; + + const messages = constructMessages([...state.history, historyItem]); + dispatch(submitMessage(message)); + + const llm = new FreeTrial({ uniqueId: "None" }); + (async () => { + for await (const update of llm.streamChat(messages)) { + dispatch(streamUpdate(update.content)); + } + })(); // Increment localstorage counter for popup const counter = localStorage.getItem("mainTextEntryCounter"); @@ -415,7 +397,13 @@ function GUI(props: GUIProps) { localStorage.setItem("mainTextEntryCounter", "1"); } }, - [client, sessionState.history, sessionState.context_items, defaultModel] + [ + client, + sessionState.history, + sessionState.context_items, + defaultModel, + state, + ] ); const persistSession = useCallback(() => { @@ -591,236 +579,154 @@ function GUI(props: GUIProps) { } }} > - {takenAction && showLoading && typeof client === "undefined" && ( - <> - -

- {serverStatusMessage} -

-
-

- - - Troubleshooting help - - -

-

{ - postToIde("toggleDevTools", {}); - }} - > - View logs -

-

- - - Manually start server - - -

-
- - )} -
- {sessionState?.history?.map( - (step: StepDescription, index: number) => { - if (step.hide) return null; - - return ( - - { - client?.stopSession(); - dispatch(newSession()); - }} - > - {step.name === "User Input" ? ( - step.hide || ( - { - if (value && client) { - client?.stopSession(); - const newHistory = [ - ...sessionState.history.slice(0, index), - { - name: "User Input", - description: value, - observations: [], - logs: [], - step_type: "UserInputStep", - params: { - user_input: value, - context_items: sessionState.context_items, - }, - hide: false, - depth: 0, - }, - ]; - dispatch(setHistory(newHistory)); - dispatch(setActive(true)); - const state = { - history: newHistory, + {state.history.map((item, index: number) => { + return ( + + { + client?.stopSession(); + dispatch(newSession()); + }} + > + {item.message.role === "user" ? ( + { + if (value && client) { + client?.stopSession(); + const newHistory = [ + ...sessionState.history.slice(0, index), + { + name: "User Input", + description: value, + observations: [], + logs: [], + step_type: "UserInputStep", + params: { + user_input: value, context_items: sessionState.context_items, - }; - dispatch(clearContextItems()); + }, + hide: false, + depth: 0, + }, + ]; + dispatch(setHistory(newHistory)); + dispatch(setActive(true)); + const state = { + history: newHistory, + context_items: sessionState.context_items, + }; + dispatch(clearContextItems()); - client.runFromState(state); - } - e?.stopPropagation(); - e?.preventDefault(); + client.runFromState(state); + } + e?.stopPropagation(); + e?.preventDefault(); + }} + groupIndices={getStepsInUserInputGroup(index)} + onToggle={(isOpen: boolean) => { + // Collapse all steps in the section + setStepsOpen((prev) => { + const nextStepsOpen = [...prev]; + getStepsInUserInputGroup(index).forEach((i) => { + nextStepsOpen[i] = isOpen; + }); + return nextStepsOpen; + }); + }} + onToggleAll={(isOpen: boolean) => { + // Collapse _all_ steps + setStepsOpen((prev) => { + return prev.map((_) => isOpen); + }); + }} + isToggleOpen={ + typeof stepsOpen[index] === "undefined" + ? true + : stepsOpen[index]! + } + index={index} + onDelete={() => { + // Delete the input and all steps until the next user input + getStepsInUserInputGroup(index).forEach((i) => { + dispatch(deleteAtIndex(i)); + }); + }} + /> + ) : ( + + ) : false ? ( + + ) : ( + + ) + } + open={ + typeof stepsOpen[index] === "undefined" + ? false + ? false + : true + : stepsOpen[index]! + } + onToggle={() => onToggleAtIndex(index)} + > + {false ? ( // Most of these falses were previously (step.error) + onToggleAtIndex(index)} + error={undefined} + onDelete={() => { + dispatch(deleteAtIndex(index)); }} - groupIndices={getStepsInUserInputGroup(index)} - onToggle={(isOpen: boolean) => { - // Collapse all steps in the section - setStepsOpen((prev) => { - const nextStepsOpen = [...prev]; - getStepsInUserInputGroup(index).forEach((i) => { - nextStepsOpen[i] = isOpen; - }); - return nextStepsOpen; - }); - }} - onToggleAll={(isOpen: boolean) => { - // Collapse _all_ steps - setStepsOpen((prev) => { - return prev.map((_) => isOpen); - }); - }} - isToggleOpen={ + /> + ) : ( + { - // Delete the input and all steps until the next user input - getStepsInUserInputGroup(index).forEach((i) => { - dispatch(deleteAtIndex(i)); - }); + key={index} + onUserInput={(input: string) => { + onStepUserInput(input, index); }} + item={item} + onReverse={() => { + client?.reverseToIndex(index); + }} + onRetry={() => { + client?.retryAtIndex(index); + }} + onDelete={() => { + dispatch(deleteAtIndex(index)); + }} + noUserInputParent={ + getStepsInUserInputGroup(index).length === 0 + } /> - ) - ) : ( - - ) : step.error ? ( - - ) : ( - - ) - } - open={ - typeof stepsOpen[index] === "undefined" - ? step.error - ? false - : true - : stepsOpen[index]! - } - onToggle={() => onToggleAtIndex(index)} - > - {step.error ? ( - onToggleAtIndex(index)} - error={step.error} - onDelete={() => { - dispatch(deleteAtIndex(index)); - }} - /> - ) : ( - { - onStepUserInput(input, index); - }} - step={step} - onReverse={() => { - client?.reverseToIndex(index); - }} - onRetry={() => { - client?.retryAtIndex(index); - setWaitingForSteps(true); - }} - onDelete={() => { - dispatch(deleteAtIndex(index)); - }} - noUserInputParent={ - getStepsInUserInputGroup(index).length === 0 - } - /> - )} - - )} - {/*
*/} -
-
- ); - } - )} + )} + + )} + {/*
*/} +
+
+ ); + })}
diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts new file mode 100644 index 000000000..2ccdcc7e1 --- /dev/null +++ b/gui/src/redux/slices/stateSlice.ts @@ -0,0 +1,67 @@ +import { createSlice } from "@reduxjs/toolkit"; +import { RootStore } from "../store"; + +const initialState: RootStore["state"] = { + history: [], + contextItems: [], + active: false, +}; + +export const stateSlice = createSlice({ + name: "state", + initialState, + reducers: { + addContextItemAtIndex: (state, action) => { + if (action.payload.index < state.history.length) { + state.history[action.payload.index].contextItems.push( + action.payload.contextItem + ); + } + }, + appendMessage: (state, action) => { + state.history.push(action.payload); + }, + addContextItem: (state, action) => { + state.contextItems.push(action.payload); + }, + submitMessage: (state, action) => { + state.history.push({ + message: { + role: "user", + content: action.payload, + summary: action.payload, + }, + contextItems: state.contextItems, + }); + state.history.push({ + message: { + role: "assistant", + content: "", + summary: "", + }, + contextItems: [], + }); + state.contextItems = []; + state.active = true; + }, + setInactive: (state) => { + state.active = false; + }, + streamUpdate: (state, action) => { + if (state.history.length > 0) { + state.history[state.history.length - 1].message.content += + action.payload; + } + }, + }, +}); + +export const { + addContextItemAtIndex, + appendMessage, + addContextItem, + submitMessage, + setInactive, + streamUpdate, +} = stateSlice.actions; +export default stateSlice.reducer; diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 75bcb9e0d..c7366acef 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -3,16 +3,19 @@ import configReducer from "./slices/configSlice"; import miscReducer from "./slices/miscSlice"; import uiStateReducer from "./slices/uiStateSlice"; import serverStateReducer from "./slices/serverStateReducer"; +import stateReducer from "./slices/stateSlice"; import sessionStateReducer, { SessionFullState, } from "./slices/sessionStateReducer"; import { ContinueConfig } from "../schema/ContinueConfig"; -import { ContextItem } from "../schema/ContextItem"; +// import { ContextItem } from "../schema/ContextItem"; +import { ContextItem } from "../../../core/llm/types"; import { ContextProviderDescription } from "../schema/ContextProviderDescription"; import { SlashCommandDescription } from "../schema/SlashCommandDescription"; import storage from "redux-persist/lib/storage"; import { persistReducer, persistStore, createTransform } from "redux-persist"; +import { ChatHistory } from "../../../core/llm/types"; export interface ChatMessage { role: "system" | "user" | "assistant"; @@ -20,6 +23,12 @@ export interface ChatMessage { } export interface RootStore { + state: { + history: ChatHistory; + contextItems: ContextItem[]; + active: boolean; + }; + config: { vscMachineId: string | undefined; }; @@ -39,7 +48,7 @@ export interface RootStore { serverState: { meilisearchUrl: string | undefined; slashCommands: SlashCommandDescription[]; - selectedContextItems: ContextItem[]; + selectedContextItems: any[]; config: ContinueConfig; contextProviders: ContextProviderDescription[]; savedContextGroups: any[]; // TODO: Context groups @@ -48,6 +57,7 @@ export interface RootStore { } const rootReducer = combineReducers({ + state: stateReducer, config: configReducer, misc: miscReducer, uiState: uiStateReducer,