🚸 keep context items in the history

This commit is contained in:
Nate Sesti 2023-11-18 22:22:24 -08:00
parent eb7d2c6172
commit e5cc0c9bf2
8 changed files with 119 additions and 67 deletions

View file

@ -372,7 +372,8 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
);
const selectedContextItems = useSelector((state: RootStore) => {
if (typeof props.index !== "undefined") {
return state.sessionState.contextItemsAtIndex[props.index] || [];
return (state.sessionState.history[props.index].params["context_items"] ||
[]) as ContextItem[];
} else {
return state.sessionState.context_items || [];
}

View file

@ -49,6 +49,7 @@ import { useNavigate } from "react-router-dom";
import { setTakenActionTrue } from "../redux/slices/miscSlice";
import {
addContextItemAtIndex,
clearContextItems,
deleteAtIndex,
newSession,
setActive,
@ -305,7 +306,10 @@ function GUI(props: GUIProps) {
observations: [],
logs: [],
step_type: "UserInputStep",
params: { user_input: input },
params: {
user_input: input,
context_items: sessionState.context_items,
},
hide: false,
depth: 0,
},
@ -314,14 +318,6 @@ function GUI(props: GUIProps) {
history: newHistory,
context_items: sessionState.context_items,
};
for (let contextItem of sessionState.context_items) {
dispatch(
addContextItemAtIndex({
item: contextItem,
index: newHistory.length - 1,
})
);
}
client.runFromState(state);
newHistory.push({
name: "Generating Response...",
@ -335,6 +331,15 @@ function GUI(props: GUIProps) {
});
dispatch(setHistory(newHistory));
dispatch(setActive(true));
for (let contextItem of sessionState.context_items) {
dispatch(
addContextItemAtIndex({
item: contextItem,
index: newHistory.length - 1,
})
);
}
dispatch(clearContextItems());
// Increment localstorage counter for popup
const counter = localStorage.getItem("mainTextEntryCounter");
@ -742,7 +747,10 @@ function GUI(props: GUIProps) {
observations: [],
logs: [],
step_type: "UserInputStep",
params: { user_input: value },
params: {
user_input: value,
context_items: sessionState.context_items,
},
hide: false,
depth: 0,
},
@ -753,6 +761,7 @@ function GUI(props: GUIProps) {
history: newHistory,
context_items: sessionState.context_items,
};
dispatch(clearContextItems());
client.runFromState(state);
}

View file

@ -75,7 +75,6 @@ const TEST_CONTEXT_ITEMS: ContextItem[] = [
export interface SessionFullState {
history: StepDescription[];
contextItemsAtIndex: { [index: number]: ContextItem[] };
context_items: ContextItem[];
active: boolean;
title: string;
@ -89,7 +88,6 @@ export const sessionStateSlice = createSlice({
context_items: [],
active: false,
title: "New Session",
contextItemsAtIndex: {},
session_id: v4(),
},
reducers: {
@ -223,16 +221,22 @@ export const sessionStateSlice = createSlice({
state: SessionFullState,
{ payload }: { payload: { item: ContextItem; index: number } }
) => {
return {
...state,
contextItemsAtIndex: {
...state.contextItemsAtIndex,
[payload.index]: [
...(state.contextItemsAtIndex[payload.index] ?? []),
let history = [...state.history];
history[payload.index] = {
...history[payload.index],
params: {
...history[payload.index].params,
context_items: [
...((history[payload.index].params?.context_items as any) || []),
payload.item,
],
},
};
return {
...state,
history,
};
},
addHighlightedCode: (
state: SessionFullState,
@ -327,20 +331,32 @@ export const sessionStateSlice = createSlice({
} else {
return {
...state,
contextItemsAtIndex: {
...state.contextItemsAtIndex,
[payload.index]: (
state.contextItemsAtIndex[payload.index] ?? []
).filter(
(item) =>
!ids.includes(
`${item.description.id.provider_title}-${item.description.id.item_id}`
)
),
},
history: state.history.map((step, i) => {
if (i === payload.index) {
return {
...step,
params: {
...step.params,
context_items: (step.params?.context_items as any).filter(
(item: ContextItem) =>
!ids.includes(
`${item.description.id.provider_title}-${item.description.id.item_id}`
)
),
},
};
}
return step;
}),
};
}
},
clearContextItems: (state: SessionFullState) => {
return {
...state,
context_items: [],
};
},
setEditingAtIds: (
state: SessionFullState,
{
@ -362,17 +378,25 @@ export const sessionStateSlice = createSlice({
} else {
return {
...state,
contextItemsAtIndex: {
...state.contextItemsAtIndex,
[payload.index]: (
state.contextItemsAtIndex[payload.index] ?? []
).map((item) => {
history: state.history.map((step, i) => {
if (i === payload.index) {
return {
...item,
editing: ids.includes(item.description.id.item_id),
...step,
params: {
...step.params,
context_items: (step.params?.context_items as any).map(
(item: ContextItem) => {
return {
...item,
editing: ids.includes(item.description.id.item_id),
};
}
),
},
};
}),
},
}
return step;
}),
};
}
},
@ -391,5 +415,6 @@ export const {
deleteContextWithIds,
setTitle,
setEditingAtIds,
clearContextItems,
} = sessionStateSlice.actions;
export default sessionStateSlice.reducer;

View file

@ -216,9 +216,10 @@ class Autopilot:
elif inspect.isasyncgenfunction(step.run):
async for update in step.run(self.sdk): # type: ignore (stub type)
if self.stopped:
for update in step.on_stop(self.sdk): # type: ignore (stub type)
if handled := handle_step_update(update):
yield handled
if stop_generator := step.on_stop(self.sdk): # type: ignore (stub type)
for update in stop_generator: # type: ignore
if handled := handle_step_update(update): # type: ignore
yield handled
return
if handled := handle_step_update(update):
@ -329,9 +330,7 @@ class Autopilot:
if self.sdk.config.disable_summaries:
return "New Session"
else:
chat_history = list(
map(lambda x: x.dict(), await self.sdk.get_chat_context())
)
chat_history = await self.sdk.get_chat_context()
chat_history_str = template_alpaca_messages(chat_history)
if self.sdk.models.summarize is None:
return "New Session"

View file

@ -340,7 +340,7 @@ class Step(ContinueBaseModel):
return "Running step: " + self.name
def on_stop(self, sdk: ContinueSDK) -> Optional[StepGenerator]:
pass
return None
def dict(self, *args, **kwargs):
d = super().dict(*args, **kwargs)

View file

@ -215,27 +215,28 @@ class ContinueSDK(AbstractContinueSDK):
raise ContinueCustomException(message, title, with_step)
async def get_chat_context(self) -> List[ChatMessage]:
history_context = list(
map(
lambda step: ChatMessage(
role="user" if step.step_type == "UserInputStep" else "assistant",
msgs = []
for step in filter(lambda x: x.hide is False, self.history):
role = "assistant"
if step.step_type == "UserInputStep":
role = "user"
msgs.extend(
await self.__autopilot.context_manager.get_chat_messages(
[ContextItem(**itm) for itm in step.params["context_items"]]
)
)
msgs.append(
ChatMessage(
role=role,
name=step.step_type,
content=step.description or f"Ran function {step.name}",
summary=f"Called function {step.name}",
),
filter(lambda x: x.hide is False, self.history[:-1]),
)
)
)
context_messages: List[
ChatMessage
] = await self.__autopilot.context_manager.get_chat_messages(self.context_items)
# Insert at the end, but don't insert after latest user message or function call
for msg in context_messages:
history_context.insert(-1, msg)
return history_context
return msgs
async def get_context_item_chat_messages(
self, exclude: Optional[str] = None

View file

@ -3,7 +3,7 @@ import difflib
import subprocess
import time
from textwrap import dedent
from typing import Any, Dict, List, Optional, Union
from typing import Any, AsyncGenerator, Dict, List, Optional, Union
from pydantic import Field
@ -20,7 +20,15 @@ from ..libs.util.templating import render_prompt_template
from ..models.filesystem import FileSystem, RangeInFile, RangeInFileWithContents
from ..models.filesystem_edit import EditDiff, FileEditWithFullContents, FileSystemEdit
from .abstract_sdk import AbstractContinueSDK
from .main import ChatMessage, ContinueCustomException, SessionUpdate, SetStep, Step
from .main import (
ChatMessage,
ContextItem,
ContinueCustomException,
DeltaStep,
SessionUpdate,
SetStep,
Step,
)
from .observation import TextObservation, UserInputObservation
@ -373,7 +381,9 @@ Please output the code to be inserted at the cursor in order to fulfill the user
or "<code_to_edit>" in line
)
async def stream_rif(self, rif: RangeInFileWithContents, sdk: AbstractContinueSDK):
async def stream_rif(
self, rif: RangeInFileWithContents, sdk: AbstractContinueSDK
) -> AsyncGenerator[SetStep, None]:
await sdk.ide.saveFile(rif.filepath)
full_file_contents = await sdk.ide.readFile(rif.filepath)
@ -640,6 +650,10 @@ Please output the code to be inserted at the cursor in order to fulfill the user
try:
last_task_time = time.time()
async for chunk in generator:
yield SetStep(
hide=False
) # Doing this so that there are breakpoints for cancellation
# Stop early if it is repeating the file_suffix or the step was deleted
if repeating_file_suffix:
break
@ -754,7 +768,8 @@ Please output the code to be inserted at the cursor in order to fulfill the user
for rif in rif_with_contents:
await sdk.ide.setSuggestionsLocked(rif.filepath, True)
await self.stream_rif(rif, sdk)
async for update in self.stream_rif(rif, sdk):
yield update
await sdk.ide.setSuggestionsLocked(rif.filepath, False)
changes = "\n".join(
@ -854,6 +869,7 @@ class ManualEditStep(ReversibleStep):
class UserInputStep(Step):
user_input: str
context_items: List[ContextItem] = []
name: str = "User Input"
hide: bool = False

View file

@ -4,7 +4,7 @@ from typing import List, Optional, Union
from pydantic import BaseModel, Field
from ...core.main import ContinueCustomException, SetStep, Step
from ...core.main import ContextItem, ContinueCustomException, SetStep, Step
from ...core.sdk import ContinueSDK, Models
from ...core.steps import DefaultModelEditCodeStep
from ...libs.llm.base import LLM
@ -371,6 +371,7 @@ class EditHighlightedCodeStep(Step):
class UserInputStep(Step):
user_input: str
context_items: List[ContextItem] = []
class SolveTracebackStep(Step):