Merge branch 'preview' of https://github.com/continuedev/continue into preview

This commit is contained in:
Nate Sesti 2023-11-02 23:28:23 -07:00
commit 869764cf23
68 changed files with 5433 additions and 1806 deletions

20
.vscode/launch.json vendored
View file

@ -76,6 +76,24 @@
"justMyCode": false,
"subProcess": false
},
{
"name": "Index",
"type": "python",
"request": "launch",
"module": "server.continuedev",
"args": ["index", "server/continuedev"],
"justMyCode": false,
"subProcess": false
},
{
"name": "Query",
"type": "python",
"request": "launch",
"module": "server.continuedev",
"args": ["search", "--directory", "server/continuedev", "Ollama"],
"justMyCode": false,
"subProcess": false
},
{
"name": "Extension (VSCode)",
"type": "extensionHost",
@ -83,7 +101,7 @@
"cwd": "${workspaceFolder}/extensions/vscode",
"args": [
// Pass a directory to manually test in
"${workspaceFolder}/extensions/vscode/manual-testing-sandbox",
"${workspaceFolder}/extensions/vscode",
"${workspaceFolder}/extensions/vscode/manual-testing-sandbox/example.ts",
"--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode"
],

View file

@ -1,3 +1,4 @@
{
"python.defaultInterpreterPath": "${workspaceFolder}/server/.venv/bin/python3"
"python.defaultInterpreterPath": "${workspaceFolder}/server/.venv/bin/python3",
"continue.showInlineTip": false
}

View file

@ -36,7 +36,7 @@ fun getDiffDirectory(): File {
return diffDir
}
fun escapeFilepath(filepath: String): String {
return filepath.replace("/", "\$f\$").replace("\\", "\$b\$")
return filepath.replace("/", "_f_").replace("\\", "_b_")
}
interface DiffInfo {
@ -175,7 +175,7 @@ class DiffManager(private val project: Project): DumbAware {
override fun createActions(): Array<Action> {
val okAction = getOKAction()
val cmdCtrl = if (System.getProperty("os.name").toLowerCase().contains("mac")) "⌘" else "⌃"
okAction.putValue(Action.NAME, "Accept ($cmdCtrl ⇧ ↵)")
okAction.putValue(Action.NAME, "Accept ($cmdCtrl ⇧ ⏎)")
val cancelAction = getCancelAction()
cancelAction.putValue(Action.NAME, "Reject ($cmdCtrl ⇧ ⌫)")

View file

@ -62,6 +62,6 @@ select the code and toggle the /edit slash command"""
# e.g.) write comments
"""Step 4: Use keyboard shortcuts to
accept [⌘ ⇧ ↵] or reject [⌘ ⇧ ⌫] the edit"""
accept [⌘ ⇧ ⏎] or reject [⌘ ⇧ ⌫] the edit"""
# endregion

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -64,7 +64,7 @@ select the code and toggle the /edit slash command"""
"""Step 3: Request an edit and press Enter"""
"""Step 4: Use keyboard shortcuts to
accept [⌘ ⇧ ↵] or reject [⌘ ⇧ ⌫] the edit"""
accept [⌘ ⇧ ⏎] or reject [⌘ ⇧ ⌫] the edit"""
# endregion

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -63,7 +63,7 @@ class DiffManager {
}
private escapeFilepath(filepath: string): string {
return filepath.replace(/\//g, "$f$").replace(/\\/g, "$b$");
return filepath.replace(/\//g, "_f_").replace(/\\/g, "_b_");
}
private remoteTmpDir: string = "/tmp/continue";

View file

@ -0,0 +1,148 @@
import React from "react";
import { defaultBorderRadius, lightGray, secondaryDark } from ".";
import styled from "styled-components";
import { getFontSize, getMarkdownLanguageTagForFile } from "../util";
import FileIcon from "./FileIcon";
import HeaderButtonWithText from "./HeaderButtonWithText";
import { ContextItem } from "../schema/ContextItem";
import { postToIde } from "../vscode";
import {
ArrowUpLeftIcon,
ChevronDownIcon,
ChevronUpIcon,
TrashIcon,
} from "@heroicons/react/24/outline";
import { deleteContextWithIds } from "../redux/slices/sessionStateReducer";
import { useDispatch } from "react-redux";
import StyledMarkdownPreview from "./StyledMarkdownPreview";
const PreviewMarkdownDiv = styled.div<{ scroll: boolean }>`
padding: 0px;
background-color: ${secondaryDark};
border-radius: ${defaultBorderRadius};
margin: 8px;
overflow: hidden;
position: relative;
& div {
background-color: ${secondaryDark};
}
& code {
overflow: ${(props) => (props.scroll ? "scroll" : "hidden")} !important;
}
`;
const PreviewMarkdownHeader = styled.p`
margin: 0;
padding: 4px 8px;
border-bottom: 1px solid ${lightGray};
word-break: break-all;
font-size: ${getFontSize()}px;
display: flex;
align-items: center;
`;
interface CodeSnippetPreviewProps {
item: ContextItem;
index: number;
}
function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
const dispatch = useDispatch();
const [scrollLocked, setScrollLocked] = React.useState(true);
const [hovered, setHovered] = React.useState(false);
return (
<PreviewMarkdownDiv
scroll={!scrollLocked}
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
>
<PreviewMarkdownHeader className="flex justify-between">
<div className="flex items-center">
<FileIcon
height="20px"
width="20px"
filename={props.item.description.name}
></FileIcon>
{props.item.description.name}
</div>
<div className="flex items-center">
<HeaderButtonWithText
text="View"
onClick={() => {
if (props.item.description.id.provider_title === "file") {
postToIde("showFile", {
filepath: props.item.description.description,
});
} else if (props.item.description.id.provider_title === "code") {
const lines = props.item.description.name
.split("(")[1]
.split(")")[0]
.split("-");
postToIde("showLines", {
filepath: props.item.description.description,
start: parseInt(lines[0]) - 1,
end: parseInt(lines[1]) - 1,
});
} else {
postToIde("showVirtualFile", {
name: props.item.description.name,
content: props.item.content,
});
}
}}
>
<ArrowUpLeftIcon width="1.2em" height="1.2em" />
</HeaderButtonWithText>
<HeaderButtonWithText
text="Delete"
onClick={() => {
dispatch(
deleteContextWithIds({
ids: [props.item.description.id],
index: props.index,
})
);
}}
>
<TrashIcon width="1.2em" height="1.2em" />
</HeaderButtonWithText>
</div>
</PreviewMarkdownHeader>
<pre className="m-0">
<StyledMarkdownPreview
source={`\`\`\`${getMarkdownLanguageTagForFile(
props.item.description.description
)}\n${props.item.content}\n\`\`\``}
maxHeight={200}
/>
</pre>
{hovered && (
<HeaderButtonWithText
className="bottom-1 right-1 absolute"
text={scrollLocked ? "Scroll" : "Lock Scroll"}
>
{scrollLocked ? (
<ChevronUpIcon
width="1.2em"
height="1.2em"
onClick={() => setScrollLocked(false)}
/>
) : (
<ChevronDownIcon
width="1.2em"
height="1.2em"
onClick={() => setScrollLocked(true)}
/>
)}
</HeaderButtonWithText>
)}
</PreviewMarkdownDiv>
);
}
export default CodeSnippetPreview;

View file

@ -22,8 +22,19 @@ import {
ArrowLeftIcon,
ArrowRightIcon,
ArrowUpLeftIcon,
ArrowUpOnSquareIcon,
BeakerIcon,
ChevronDownIcon,
ChevronRightIcon,
Cog6ToothIcon,
CommandLineIcon,
FolderIcon,
GlobeAltIcon,
HashtagIcon,
MagnifyingGlassIcon,
PaintBrushIcon,
PlusIcon,
SparklesIcon,
TrashIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
@ -39,6 +50,7 @@ import {
getMarkdownLanguageTagForFile,
getMetaKeyLabel,
getPlatform,
isMetaEquivalentKeyPressed,
} from "../util";
import StyledMarkdownPreview from "./StyledMarkdownPreview";
import { setTakenActionTrue } from "../redux/slices/miscSlice";
@ -55,9 +67,35 @@ import {
newSession,
setActive,
} from "../redux/slices/sessionStateReducer";
import RingLoader from "./RingLoader";
import CodeSnippetPreview from "./CodeSnippetPreview";
const SEARCH_INDEX_NAME = "continue_context_items";
const ICONS_FOR_DROPDOWN: { [key: string]: any } = {
file: FolderIcon,
terminal: CommandLineIcon,
diff: PlusIcon,
search: MagnifyingGlassIcon,
url: GlobeAltIcon,
"/edit": PaintBrushIcon,
"/clear": TrashIcon,
"/test": BeakerIcon,
"/config": Cog6ToothIcon,
"/comment": HashtagIcon,
"/share": ArrowUpOnSquareIcon,
"/cmd": CommandLineIcon,
"/codebase": SparklesIcon,
};
function DropdownIcon(props: { provider: string; className?: string }) {
const Icon = ICONS_FOR_DROPDOWN[props.provider];
if (!Icon) {
return null;
}
return <Icon className={props.className} height="1.2em" width="1.2em" />;
}
// #region styled components
const gradient = keyframes`
@ -100,8 +138,8 @@ const GradientBorder = styled.div<{
margin-top: 8px;
`;
const HiddenHeaderButtonWithText = styled.button`
opacity: 0;
const HiddenHeaderButtonWithText = styled.button<{ pinVisible: boolean }>`
opacity: ${({ pinVisible }) => (pinVisible ? 1 : 0)};
background-color: transparent;
border: none;
outline: none;
@ -128,28 +166,6 @@ const HiddenHeaderButtonWithText = styled.button`
const mainInputFontSize = getFontSize();
const PreviewMarkdownDiv = styled.div`
padding: 0px;
background-color: ${secondaryDark};
border-radius: ${defaultBorderRadius};
margin: 8px;
overflow: hidden;
& div {
background-color: ${secondaryDark};
}
`;
const PreviewMarkdownHeader = styled.p`
margin: 0;
padding: 4px 8px;
border-bottom: 1px solid ${lightGray};
word-break: break-all;
font-size: ${getFontSize()}px;
display: flex;
align-items: center;
`;
const MainTextInput = styled.textarea<{
inQueryForDynamicProvider: boolean;
fontSize?: number;
@ -224,7 +240,10 @@ const Ul = styled.ul<{
6
}px);`}
position: absolute;
background: ${vscBackground};
/* background: ${vscBackground}; */
background-color: transparent;
backdrop-filter: blur(12px);
color: ${vscForeground};
max-height: ${UlMaxHeight}px;
margin-left: 1px;
@ -253,7 +272,7 @@ const Li = styled.li<{
isLastItem: boolean;
}>`
background-color: ${({ highlighted }) =>
highlighted ? buttonColor + "66" : secondaryDark};
highlighted ? buttonColor + "66" : "transparent"};
${({ selected }) => selected && "font-weight: bold;"}
padding: 0.5rem 0.5rem;
display: flex;
@ -400,7 +419,13 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
const selectContextItem = useCallback(
async (id: string, query: string) => {
const timeout = setTimeout(() => {
setWaitingForContextItem(true);
}, 0.1);
const contextItem = await client?.getContextItem(id, query);
clearTimeout(timeout);
setWaitingForContextItem(false);
if (!contextItem) return;
if (props.isMainInput) {
dispatch(addContextItem(contextItem));
} else if (typeof props.index !== "undefined") {
@ -552,6 +577,8 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
},
});
const [waitingForContextItem, setWaitingForContextItem] = useState(false);
useEffect(() => {
if (downshiftProps.highlightedIndex < 0) {
downshiftProps.setHighlightedIndex(0);
@ -817,10 +844,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
>
+ Add Context
</span>
{(downshiftProps.inputValue?.startsWith("/edit") ||
(inputFocused &&
metaKeyPressed &&
downshiftProps.inputValue?.length > 0)) && (
{downshiftProps.inputValue?.startsWith("/edit") && (
<span className="float-right">Inserting at cursor</span>
)}
</div>
@ -854,6 +878,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
)}
<HiddenHeaderButtonWithText
pinVisible={selectedContextItems.length >= 8}
className={
selectedContextItems.length > 0
? `pill-button-${props.index || "main"}`
@ -886,103 +911,143 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
}
}}
>
<TrashIcon width="1.4em" height="1.4em" />
<TrashIcon width="1.2em" height="1.2em" />
</HiddenHeaderButtonWithText>
{selectedContextItems.map((item, idx) => {
return (
<PillButton
inputIndex={props.index}
areMultipleItems={selectedContextItems.length > 1}
key={`${item.description.id.item_id}${idx}`}
item={item}
editing={
item.editing &&
(inputRef.current as any)?.value?.startsWith("/edit")
}
editingAny={(inputRef.current as any)?.value?.startsWith(
"/edit"
)}
stepIndex={props.index}
index={idx}
onDelete={() => {
dispatch(
deleteContextWithIds({
ids: [item.description.id],
index: props.index,
})
);
inputRef.current?.focus();
if (
(item.description.id.item_id ===
focusedContextItem?.description.id.item_id &&
focusedContextItem?.description.id.provider_name ===
item.description.id.provider_name) ||
(item.description.id.item_id ===
previewingContextItem?.description.id.item_id &&
previewingContextItem?.description.id.provider_name ===
item.description.id.provider_name)
) {
setPreviewingContextItem(undefined);
setFocusedContextItem(undefined);
}
}}
onClick={(e) => {
if (
item.description.id.item_id ===
focusedContextItem?.description.id.item_id &&
focusedContextItem?.description.id.provider_name ===
item.description.id.provider_name
) {
setFocusedContextItem(undefined);
} else {
setFocusedContextItem(item);
}
}}
onBlur={() => {
setFocusedContextItem(undefined);
}}
toggleViewContent={() => {
setPreviewingContextItem((prev) => {
if (!prev) return item;
if (
prev.description.id.item_id ===
item.description.id.item_id &&
prev.description.id.provider_name ===
item.description.id.provider_name
) {
return undefined;
} else {
return item;
{selectedContextItems.length < 8 ? (
<>
{selectedContextItems.map((item, idx) => {
return (
<PillButton
inputIndex={props.index}
areMultipleItems={selectedContextItems.length > 1}
key={`${item.description.id.item_id}${idx}`}
item={item}
editing={
item.editing &&
(inputRef.current as any)?.value?.startsWith("/edit")
}
});
}}
previewing={
item.description.id.item_id ===
previewingContextItem?.description.id.item_id &&
previewingContextItem?.description.id.provider_name ===
item.description.id.provider_name
}
focusing={
item.description.id.item_id ===
focusedContextItem?.description.id.item_id &&
focusedContextItem?.description.id.provider_name ===
item.description.id.provider_name
}
prefixInputWithEdit={(should) => {
if (!should && inputRef.current?.value.startsWith("/edit")) {
downshiftProps.setInputValue(
inputRef.current?.value.replace("/edit ", "")
);
}
if (downshiftProps.inputValue.startsWith("/edit")) return;
downshiftProps.setInputValue(
`/edit ${downshiftProps.inputValue}`
);
editingAny={(inputRef.current as any)?.value?.startsWith(
"/edit"
)}
stepIndex={props.index}
index={idx}
onDelete={() => {
dispatch(
deleteContextWithIds({
ids: [item.description.id],
index: props.index,
})
);
inputRef.current?.focus();
if (
(item.description.id.item_id ===
focusedContextItem?.description.id.item_id &&
focusedContextItem?.description.id.provider_name ===
item.description.id.provider_name) ||
(item.description.id.item_id ===
previewingContextItem?.description.id.item_id &&
previewingContextItem?.description.id
.provider_name ===
item.description.id.provider_name)
) {
setPreviewingContextItem(undefined);
setFocusedContextItem(undefined);
}
}}
onClick={(e) => {
if (
item.description.id.item_id ===
focusedContextItem?.description.id.item_id &&
focusedContextItem?.description.id.provider_name ===
item.description.id.provider_name
) {
setFocusedContextItem(undefined);
} else {
setFocusedContextItem(item);
}
}}
onBlur={() => {
setFocusedContextItem(undefined);
}}
toggleViewContent={() => {
setPreviewingContextItem((prev) => {
if (!prev) return item;
if (
prev.description.id.item_id ===
item.description.id.item_id &&
prev.description.id.provider_name ===
item.description.id.provider_name
) {
return undefined;
} else {
return item;
}
});
}}
previewing={
item.description.id.item_id ===
previewingContextItem?.description.id.item_id &&
previewingContextItem?.description.id.provider_name ===
item.description.id.provider_name
}
focusing={
item.description.id.item_id ===
focusedContextItem?.description.id.item_id &&
focusedContextItem?.description.id.provider_name ===
item.description.id.provider_name
}
prefixInputWithEdit={(should) => {
if (
!should &&
inputRef.current?.value.startsWith("/edit")
) {
downshiftProps.setInputValue(
inputRef.current?.value.replace("/edit ", "")
);
}
if (downshiftProps.inputValue.startsWith("/edit")) return;
downshiftProps.setInputValue(
`/edit ${downshiftProps.inputValue}`
);
inputRef.current?.focus();
}}
/>
);
})}
{waitingForContextItem && (
<RingLoader
period={1.5}
className="ml-0 mt-1 mb-0"
width="1.0em"
height="1.0em"
size={32}
wFull={false}
></RingLoader>
)}
</>
) : (
<div
onClick={() => {
if (props.isMainInput) {
setShowContextToggleOn((prev) => !prev);
} else {
inputRef.current?.focus();
}}
/>
);
})}
setShowContextItemsIfNotMain(true);
}
}}
style={{
color: lightGray,
backgroundColor: vscBackground,
fontSize: "12px",
alignItems: "center",
display: "flex",
height: "100%",
cursor: "pointer",
}}
>
{selectedContextItems.length} snippets selected
</div>
)}
{/* {selectedContextItems.length > 0 && (
<HeaderButtonWithText
onClick={() => {
@ -1030,24 +1095,10 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
{showContextToggleOn && (
<div>
{selectedContextItems.map((item) => (
<PreviewMarkdownDiv>
<PreviewMarkdownHeader>
<FileIcon
height="20px"
width="20px"
filename={item.description.name}
></FileIcon>
{item.description.name}
</PreviewMarkdownHeader>
<pre className="m-0">
<StyledMarkdownPreview
source={`\`\`\`${getMarkdownLanguageTagForFile(
item.description.description
)}\n${item.content}\n\`\`\``}
maxHeight={200}
/>
</pre>
</PreviewMarkdownDiv>
<CodeSnippetPreview
index={props.index}
item={item}
></CodeSnippetPreview>
))}
</div>
)}
@ -1111,7 +1162,6 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
if (isComposing) {
return;
}
dispatch(setBottomMessage(undefined));
if (event.key === "Enter" && event.shiftKey) {
// Prevent Downshift's default 'Enter' behavior.
@ -1380,15 +1430,18 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
filename={item.name}
></FileIcon>
)}
<DropdownIcon provider={item.name} className="mr-2" />
<DropdownIcon provider={item.id} className="mr-2" />
{item.name}
{" "}
</div>
<span
style={{
color: lightGray,
color: vscForeground,
float: "right",
textAlign: "right",
}}
hidden={downshiftProps.highlightedIndex !== index}
>
{item.description}
</span>
@ -1401,7 +1454,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
<ArrowRightIcon
width="1.2em"
height="1.2em"
color={lightGray}
color={vscForeground}
className="ml-2 flex-shrink-0"
/>
)}
@ -1431,6 +1484,41 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
</Ul>
</div>
{props.isMainInput && (
<>
<div
style={{
color: lightGray,
fontSize: "10px",
backgroundColor: vscBackground,
width: "calc(100% - 16px)",
height: "0",
marginTop: "4px",
}}
>
<span
onClick={() => {
const inputValue = downshiftProps.inputValue;
if (inputValue.startsWith("/codebase")) {
downshiftProps.setInputValue(
inputValue.replace("/codebase ", "")
);
} else {
downshiftProps.setInputValue("/codebase " + inputValue);
}
inputRef.current?.focus();
}}
className={"hover:underline cursor-pointer float-right"}
>
{downshiftProps.inputValue.startsWith("/codebase")
? "Using codebase"
: "⌘ ⏎ Use codebase"}
</span>
</div>
<br />
</>
)}
{props.isMainInput && (
<ContinueButton
disabled={

View file

@ -0,0 +1,64 @@
import React from "react";
import styled from "styled-components";
import { StyledTooltip, lightGray, vscForeground } from ".";
const ProgressBarWrapper = styled.div`
width: 100px;
height: 6px;
border-radius: 6px;
border: 0.5px solid ${lightGray};
margin-top: 6px;
`;
const ProgressBarFill = styled.div<{ completed: number; color?: string }>`
height: 100%;
background-color: ${(props) => props.color || vscForeground};
border-radius: inherit;
transition: width 0.2s ease-in-out;
width: ${(props) => props.completed}%;
`;
const GridDiv = styled.div`
display: grid;
grid-template-rows: 1fr auto;
align-items: center;
justify-items: center;
`;
const P = styled.p`
margin: 0;
margin-top: 2px;
font-size: 11.5px;
color: ${lightGray};
text-align: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
`;
interface ProgressBarProps {
completed: number;
total: number;
}
const IndexingProgressBar = ({ completed, total }: ProgressBarProps) => {
const fillPercentage = Math.min(100, Math.max(0, (completed / total) * 100));
return (
<>
<GridDiv data-tooltip-id="usage_progress_bar">
<ProgressBarWrapper>
<ProgressBarFill completed={fillPercentage} />
</ProgressBarWrapper>
<P>Indexing ({Math.trunc((completed / total) * 100)}%)</P>
</GridDiv>
<StyledTooltip id="usage_progress_bar" place="bottom">
{
"Continue is indexing your codebase locally. You can find the index in ~/.continue/embeddings."
}
</StyledTooltip>
</>
);
};
export default IndexingProgressBar;

View file

@ -3,7 +3,7 @@ import { StyledTooltip } from ".";
import ReactDOM from "react-dom";
const InfoHover = ({ msg }: { msg: string }) => {
const id = "info-hover";
const id = `info-hover-${encodeURIComponent(msg)}`;
const tooltipPortalDiv = document.getElementById("tooltip-portal-div");

View file

@ -22,6 +22,7 @@ import ModelSelect from "./ModelSelect";
import ProgressBar from "./ProgressBar";
import { newSession } from "../redux/slices/sessionStateReducer";
import { getFontSize } from "../util";
import IndexingProgressBar from "./IndexingProgressBar";
// #region Styled Components
const FOOTER_HEIGHT = "1.8em";
@ -73,6 +74,8 @@ const Footer = styled.footer`
align-items: center;
width: calc(100% - 16px);
height: ${FOOTER_HEIGHT};
background-color: transparent;
backdrop-filter: blur(12px);
overflow: hidden;
`;
@ -105,6 +108,9 @@ const Layout = () => {
const showDialog = useSelector(
(state: RootStore) => state.uiState.showDialog
);
const indexingProgress = useSelector(
(state: RootStore) => state.serverState.indexingProgress
);
const defaultModel = useSelector(
(state: RootStore) => (state.serverState.config as any).models?.default
@ -217,7 +223,8 @@ const Layout = () => {
/>
)}
<ModelSelect />
{defaultModel?.class_name === "OpenAIFreeTrial" &&
{indexingProgress >= 1 && // Would take up too much space together with indexing progress
defaultModel?.class_name === "OpenAIFreeTrial" &&
defaultModel?.api_key === "" &&
(location.pathname === "/settings" ||
parseInt(localStorage.getItem("ftc") || "0") >= 125) && (
@ -226,6 +233,13 @@ const Layout = () => {
total={250}
/>
)}
{indexingProgress < 1 && (
<IndexingProgressBar
completed={indexingProgress * 100}
total={100}
/>
)}
</div>
<HeaderButtonWithText
text="Help"

View file

@ -0,0 +1,65 @@
import React, { useCallback, useEffect, useState } from "react";
import styled from "styled-components";
import { defaultBorderRadius, secondaryDark } from ".";
import { useDispatch, useSelector } from "react-redux";
import { RootStore } from "../redux/store";
import { postToIde } from "../vscode";
const StyledCode = styled.code<{ link: boolean }>`
color: ${(props) => (props.link ? "#ff43433" : "#f78383")};
word-wrap: break-word;
border-radius: ${defaultBorderRadius};
background-color: ${secondaryDark};
${(props) => props.link && "cursor: pointer;"}
&:hover {
${(props) => props.link && "text-decoration: underline;"}
}
`;
function LinkableCode(props: any) {
const contextItems = useSelector(
(store: RootStore) => store.sessionState.context_items
);
const [linkingDone, setLinkingDone] = useState(false);
const [isLink, setIsLink] = useState(false);
const [filepath, setFilepath] = useState("");
useEffect(() => {
if (linkingDone) return;
// Get filename from props.children
let filename: string | undefined = undefined;
if (typeof props.children === "string") {
filename = props.children;
} else if (
Array.isArray(props.children) &&
props.children.length > 0 &&
typeof props.children[0] === "string"
) {
filename = props.children[0];
}
if (!filename) return;
// Check if matches any context item's filepath
let link = false;
for (let contextItem of contextItems) {
if (contextItem.description.description.endsWith(filename)) {
link = true;
setFilepath(contextItem.description.description);
break;
}
}
setIsLink(link);
setLinkingDone(true);
}, [linkingDone, contextItems]);
const onClick = () => {
postToIde("showFile", { filepath });
};
return <StyledCode {...props} onClick={onClick} link={isLink} />;
}
export default LinkableCode;

View file

@ -27,9 +27,9 @@ const Button = styled.button<{ fontSize?: number }>`
color: ${vscForeground};
background-color: ${secondaryDark};
border-radius: ${defaultBorderRadius};
padding: 4px;
padding-left: 8px;
padding-right: 8px;
padding: 3.5px;
padding-left: 3px;
padding-right: 5px;
overflow: hidden;
font-size: ${(props) => props.fontSize || getFontSize()}px;
@ -186,7 +186,7 @@ const PillButton = (props: PillButtonProps) => {
<div style={{ position: "relative" }}>
<Container previewing={props.previewing} ref={pillContainerRef}>
<StyledButton
fontSize={getFontSize()}
fontSize={getFontSize() - 1}
borderColor={
props.editing ? (warning ? "red" : undefined) : undefined
}

View file

@ -1,6 +1,6 @@
import React from "react";
import styled, { keyframes } from "styled-components";
import { buttonColor, vscBackground, vscForeground } from ".";
import { vscForeground } from ".";
const rotate = keyframes`
0% {
@ -11,10 +11,14 @@ const rotate = keyframes`
}
`;
const LoaderSvg = styled.svg`
const LoaderSvg = styled.svg<{
width?: string;
height?: string;
period?: number;
}>`
transform: rotate(-90deg);
width: 40px;
height: 40px;
width: ${(props) => props.width || "40px"};
height: ${(props) => props.height || "40px"};
opacity: 50%;
circle {
@ -23,17 +27,41 @@ const LoaderSvg = styled.svg`
stroke-width: 2;
stroke-dasharray: 100;
stroke-dashoffset: 0;
animation: ${rotate} 6s ease-out infinite;
animation: ${rotate} ${(props) => props.period || 6}s ease-out infinite;
stroke-linecap: round;
}
`;
const RingLoader = () => (
<div className="m-auto w-full text-center mt-2">
<LoaderSvg viewBox="0 0 32 32">
<circle cx="16" cy="16" r="14" />
</LoaderSvg>
</div>
);
const RingLoader = (props: {
size: number;
wFull?: boolean;
className?: string;
width?: string;
height?: string;
period?: number;
}) => {
const viewBox = `0 0 ${props.size} ${props.size}`;
const size = (props.size / 2).toString();
const r = "14"; //(props.size / 2 - 2).toString();
return (
<div
className={
"m-auto text-center mt-2" +
(props.wFull === false ? "" : " w-full") +
" " +
props.className
}
>
<LoaderSvg
period={props.period}
width={props.width}
height={props.height}
viewBox={viewBox}
>
<circle cx={size} cy={size} r={r} />
</LoaderSvg>
</div>
);
};
export default RingLoader;

View file

@ -8,6 +8,7 @@ import {
} from ".";
import MarkdownPreview from "@uiw/react-markdown-preview";
import { getFontSize } from "../util";
import LinkableCode from "./LinkableCode";
const StyledMarkdownPreviewComponent = styled(MarkdownPreview)<{
light?: boolean;
@ -71,6 +72,10 @@ function StyledMarkdownPreview(props: StyledMarkdownPreviewProps) {
</a>
);
},
code: ({ node, ...props }) => {
console.log(node, props);
return <LinkableCode {...props}></LinkableCode>;
},
}}
className={props.className}
maxHeight={props.maxHeight}

View file

@ -71,8 +71,8 @@ const vscodeShortcuts: KeyboardShortcutProps[] = [
description: "Edit Highlighted Code",
},
{
mac: "⌘ ⇧ ↵",
windows: "⌃ ⇧ ↵",
mac: "⌘ ⇧ ⏎",
windows: "⌃ ⇧ ⏎",
description: "Accept Diff",
},
{
@ -105,6 +105,11 @@ const vscodeShortcuts: KeyboardShortcutProps[] = [
windows: "⌃ ⌫",
description: "Stop Active Step",
},
{
mac: "Tab",
windows: "Tab",
description: "Toggle between context items",
},
];
const jetbrainsShortcuts: KeyboardShortcutProps[] = [
@ -119,8 +124,8 @@ const jetbrainsShortcuts: KeyboardShortcutProps[] = [
description: "Edit Highlighted Code",
},
{
mac: "⌘ ⇧ ↵",
windows: "⌃ ⇧ ↵",
mac: "⌘ ⇧ ⏎",
windows: "⌃ ⇧ ⏎",
description: "Accept Diff",
},
{
@ -148,6 +153,11 @@ const jetbrainsShortcuts: KeyboardShortcutProps[] = [
windows: "⌃ ⌫",
description: "Stop Active Step",
},
{
mac: "Tab",
windows: "Tab",
description: "Toggle between context items",
},
];
function KeyboardShortcutsDialog() {

View file

@ -120,6 +120,12 @@ class ContinueGUIClientProtocol extends AbstractContinueGUIClientProtocol {
});
}
onIndexingProgress(callback: (progress: number) => void) {
this.messenger?.onMessageType("indexing_progress", (data: any) => {
callback(data.progress);
});
}
onConfigUpdate(callback: (config: ContinueConfig) => void) {
this.messenger?.onMessageType("config_update", (data: any) => {
callback(data);

View file

@ -15,6 +15,7 @@ import { RootStore } from "../redux/store";
import {
setConfig,
setContextProviders,
setIndexingProgress,
setSlashCommands,
} from "../redux/slices/serverStateReducer";
import {
@ -68,6 +69,10 @@ function useSetup(
dispatch(processSessionUpdate(update));
});
client.onIndexingProgress((progress) => {
dispatch(setIndexingProgress(progress));
});
client.onAddContextItem((item) => {
dispatch(addContextItem(item));
});

View file

@ -76,6 +76,7 @@ const TitleTextInput = styled(Input)`
margin-right: 8px;
padding-top: 6px;
padding-bottom: 6px;
background-color: transparent;
&:focus {
outline: none;
@ -120,7 +121,8 @@ const GUIHeaderDiv = styled.div`
position: sticky;
top: 0;
z-index: 100;
background-color: ${vscBackground};
background-color: transparent;
backdrop-filter: blur(12px);
`;
function fallbackRender({ error, resetErrorBoundary }) {
@ -426,7 +428,7 @@ function GUI(props: GUIProps) {
// cmd+enter to /codebase
if (event && isMetaEquivalentKeyPressed(event)) {
input = `/edit ${input}`;
input = `/codebase ${input}`;
}
(mainTextInputRef.current as any).setInputValue("");
@ -591,7 +593,7 @@ function GUI(props: GUIProps) {
</GUIHeaderDiv>
{takenAction && showLoading && typeof client === "undefined" && (
<>
<RingLoader />
<RingLoader size={32} />
<p
style={{
textAlign: "center",

View file

@ -2,48 +2,6 @@ import { createSlice } from "@reduxjs/toolkit";
import { ContextItem } from "../../schema/ContextItem";
import { RootStore } from "../store";
const TEST_TIMELINE = [
{
description: "Hi, please write bubble sort in python",
name: "User Input",
},
{
description: `\`\`\`python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
\`\`\``,
name: "Bubble Sort in Python",
},
{
description: "Now write it in Rust",
name: "User Input",
},
{
description: "Hello! This is a test...\n\n1, 2, 3, testing...",
name: "Testing",
},
{
description: `Sure, here's bubble sort written in rust: \n\`\`\`rust
fn bubble_sort<T: Ord>(values: &mut[T]) {
let len = values.len();
for i in 0..len {
for j in 0..(len - i - 1) {
if values[j] > values[j + 1] {
values.swap(j, j + 1);
}
}
}
}
\`\`\`\nIs there anything else I can answer?`,
name: "Rust Bubble Sort",
},
];
const TEST_SLASH_COMMANDS = [
{
name: "edit",
@ -59,31 +17,6 @@ const TEST_SLASH_COMMANDS = [
},
];
const TEST_CONTEXT_ITEMS: ContextItem[] = [
{
content: "def add(a, b):\n return a + b",
description: {
description: "test.py",
name: "test.py",
id: {
item_id: "test.py",
provider_title: "file",
},
},
},
{
content: "function add(a, b) {\n return a + b\n}",
description: {
description: "test.js",
name: "test.js",
id: {
item_id: "test.js",
provider_title: "file",
},
},
},
];
const initialState: RootStore["serverState"] = {
meilisearchUrl: undefined,
slashCommands: [],
@ -94,6 +27,7 @@ const initialState: RootStore["serverState"] = {
},
contextProviders: [],
savedContextGroups: [],
indexingProgress: 1.0,
};
export const serverStateSlice = createSlice({
@ -103,7 +37,10 @@ export const serverStateSlice = createSlice({
setSlashCommands: (state, action) => {
return {
...state,
slashCommands: action.payload,
slashCommands: [
...action.payload,
{ name: "codebase", description: "Retrieve codebase context" },
],
};
},
setContextProviders: (state, action) => {
@ -118,9 +55,19 @@ export const serverStateSlice = createSlice({
config: action.payload,
};
},
setIndexingProgress: (state, { payload }: { payload: number }) => {
return {
...state,
indexingProgress: payload,
};
},
},
});
export const { setContextProviders, setSlashCommands, setConfig } =
serverStateSlice.actions;
export const {
setContextProviders,
setSlashCommands,
setConfig,
setIndexingProgress,
} = serverStateSlice.actions;
export default serverStateSlice.reducer;

View file

@ -6,6 +6,73 @@ import { PersistedSessionInfo } from "../../schema/PersistedSessionInfo";
import { v4 } from "uuid";
import { ContextItemId } from "../../schema/ContextItemId";
const TEST_TIMELINE = [
{
description: "Hi, please write bubble sort in python",
name: "User Input",
},
{
description: `\`\`\`python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
\`\`\``,
name: "Bubble Sort in Python",
},
{
description: "Now write it in Rust",
name: "User Input",
},
{
description: "Hello! This is a test...\n\n1, 2, 3, testing...",
name: "Testing",
},
{
description: `Sure, here's bubble sort written in rust: \n\`\`\`rust
fn bubble_sort<T: Ord>(values: &mut[T]) {
let len = values.len();
for i in 0..len {
for j in 0..(len - i - 1) {
if values[j] > values[j + 1] {
values.swap(j, j + 1);
}
}
}
}
\`\`\`\nIs there anything else I can answer?`,
name: "Rust Bubble Sort",
},
];
const TEST_CONTEXT_ITEMS: ContextItem[] = [
{
content: "def add(a, b):\n return a + b",
description: {
description: "test.py",
name: "test.py",
id: {
item_id: "test.py",
provider_title: "file",
},
},
},
{
content: "function add(a, b) {\n return a + b\n}",
description: {
description: "test.js",
name: "test.js",
id: {
item_id: "test.js",
provider_title: "file",
},
},
},
];
export interface SessionFullState {
history: StepDescription[];
contextItemsAtIndex: { [index: number]: ContextItem[] };

View file

@ -45,6 +45,7 @@ export interface RootStore {
config: ContinueConfig;
contextProviders: ContextProviderDescription[];
savedContextGroups: any[]; // TODO: Context groups
indexingProgress: number;
};
}

View file

@ -461,7 +461,7 @@ export const MODEL_INFO: { [key: string]: ModelInfo } = {
icon: "ollama.png",
tags: [ModelProviderTag["Local"], ModelProviderTag["Open-Source"]],
packages: osModels,
collectInputFor: [...completionParamsInputs],
collectInputFor: [...completionParamsInputs, serverUrlInput],
},
together: {
title: "TogetherAI",
@ -745,7 +745,10 @@ After it's up and running, you can start using Continue.`,
'New users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.py where it says `api_key=""` or select another model provider.',
icon: "openai.png",
tags: [ModelProviderTag.Free],
packages: [gpt4, gpt35turbo],
packages: [
{ ...gpt4, title: "GPT-4 (trial)" },
{ ...gpt35turbo, title: "GPT-3.5-Turbo (trial)" },
],
collectInputFor: [...completionParamsInputs],
},
};

View file

@ -1,11 +1,28 @@
import asyncio
import os
from typing import Optional
from tqdm import tqdm
from .core.config import ContinueConfig
from .headless.headless_ide import LocalIdeProtocol
from .libs.index.build_index import build_index
from .libs.util.ext_to_lang import ext_to_lang
from .libs.index.chunkers.chunk import Chunk
from dotenv import load_dotenv
from rich.console import Console
from rich.markdown import Markdown
import typer
from . import run
from .server.main import run_server
from .headless import get_headless_autopilot
from .libs.index.pipelines.main import main_retrieval_pipeline
app = typer.Typer()
load_dotenv()
app = typer.Typer(invoke_without_command=True)
console = Console()
CONTINUE_ASCII = r"""
@ -19,13 +36,15 @@ _ / _ __ \__ __ \_ __/__ / __ __ \_ / / /_ _ \
"""
@app.command()
def main(
def main_command(
port: int = typer.Option(65432, help="server port"),
host: str = typer.Option("127.0.0.1", help="server host"),
meilisearch_url: Optional[str] = typer.Option(
None, help="The URL of the MeiliSearch server if running manually"
),
disable_meilisearch: bool = typer.Option(
False, help="Disable the MeiliSearch server"
),
config: Optional[str] = typer.Option(
None, help="The path to the configuration file"
),
@ -35,7 +54,119 @@ def main(
run(config)
else:
print(CONTINUE_ASCII)
run_server(port=port, host=host, meilisearch_url=meilisearch_url)
run_server(
port=port,
host=host,
meilisearch_url=meilisearch_url,
disable_meilisearch=disable_meilisearch,
)
@app.callback()
def main(
ctx: typer.Context,
port: int = typer.Option(65432, help="server port"),
host: str = typer.Option("127.0.0.1", help="server host"),
meilisearch_url: Optional[str] = typer.Option(
None, help="The URL of the MeiliSearch server if running manually"
),
disable_meilisearch: bool = typer.Option(
False, help="Disable the MeiliSearch server"
),
config: Optional[str] = typer.Option(
None, help="The path to the configuration file"
),
headless: bool = typer.Option(False, help="Run in headless mode"),
):
if ctx.invoked_subcommand is None:
main_command(
port=port,
host=host,
meilisearch_url=meilisearch_url,
config=config,
headless=headless,
disable_meilisearch=disable_meilisearch,
)
def print_chunk(chunk: Chunk):
# A nice colored representation of the piece of the file
language = ext_to_lang(chunk.document_id.split(".")[-1])
console.print(
Markdown(
f"\n**{chunk.document_id}**\n\n```{language}\n{chunk.content}\n```\n---\n"
)
)
@app.command()
def search(
query: str = typer.Argument(..., help="The query to search for"),
config: Optional[str] = typer.Option(
None, "--config", help="The path to the configuration file"
),
directory: str = typer.Option(None, "--directory", help="The directory to index"),
):
if directory is None:
directory = "."
print(f"Searching {directory}...")
# Make absolute
directory = os.path.abspath(directory)
async def run():
autopilot = await get_headless_autopilot(config=config, directory=directory)
results = await main_retrieval_pipeline(
query,
autopilot.sdk,
openai_api_key=None, # os.environ.get("OPENAI_API_KEY"),
)
console.print(Markdown(f"## Results for `{query}`"))
for result in results:
print_chunk(result)
asyncio.run(run())
@app.command()
def index(
directory: str = typer.Argument(None, help="The directory to index"),
config: Optional[str] = typer.Option(
None, help="The path to the configuration file"
),
openai_api_key: Optional[str] = typer.Option(
None, help="The OpenAI API key to use for indexing"
),
):
if directory is None:
directory = "."
# Make absolute
directory = os.path.abspath(directory)
print(f"Indexing {directory}...")
async def run():
nonlocal config
if config is None:
config = ContinueConfig.load_default()
else:
config = ContinueConfig.from_filepath(config)
config.retrieval_settings.openai_api_key = openai_api_key
pbar = tqdm(total=100)
async for progress in build_index(
ide=LocalIdeProtocol(workspace_directory=directory), config=config
):
pbar.update(int(progress * 100) - pbar.n)
pbar.close()
print("Indexing complete")
asyncio.run(run())
if __name__ == "__main__":

View file

@ -50,6 +50,32 @@ class CustomCommand(BaseModel):
)
class RetrievalSettings(BaseModel):
n_retrieve: Optional[int] = Field(
50, description="Number of results to initially retrieve from vector database"
)
n_final: Optional[int] = Field(
10, description="Final number of results to use after re-ranking"
)
use_reranking: bool = Field(
True,
description="Whether to use re-ranking, which will allow initial selection of n_retrieve results, then will use an LLM to select the top n_final results",
)
rerank_group_size: int = Field(
5,
description="Number of results to group together when re-ranking. Each group will be processed in parallel.",
)
ignore_files: List[str] = Field(
[],
description="Files to ignore when indexing the codebase. You can use glob patterns, such as **/*.py. This is useful for directories that contain generated code, or other directories that are not relevant to the codebase.",
)
openai_api_key: Optional[str] = Field(None, description="OpenAI API key")
api_base: Optional[str] = Field(None, description="OpenAI API base URL")
api_type: Optional[str] = Field(None, description="OpenAI API type")
api_version: Optional[str] = Field(None, description="OpenAI API version")
organization_id: Optional[str] = Field(None, description="OpenAI organization ID")
class ContinueConfig(BaseModel):
"""
Continue can be deeply customized by editing the `ContinueConfig` object in `~/.continue/config.py` (`%userprofile%\.continue\config.py` for Windows) on your machine. This class is instantiated from the config file for every new session.
@ -118,6 +144,10 @@ class ContinueConfig(BaseModel):
False,
description="If set to `True`, Continue will not generate summaries for each Step. This can be useful if you want to save on compute.",
)
retrieval_settings: Optional[RetrievalSettings] = Field(
RetrievalSettings(),
description="Settings for the retrieval system. Read more about the retrieval system in the documentation.",
)
@classmethod
def schema(cls, *args, **kwargs):

View file

@ -1,7 +1,7 @@
import asyncio
import time
from abc import abstractmethod
from typing import Any, Awaitable, Callable, Dict, List, Optional
from typing import Any, Awaitable, Callable, List, Optional
from ..server.protocols.ide_protocol import AbstractIdeProtocolServer
from meilisearch_python_async import Client
@ -398,8 +398,8 @@ class ContextManager:
except Exception as e:
logger.debug(f"Error loading meilisearch index: {e}")
if should_retry:
await restart_meilisearch()
try:
await restart_meilisearch()
await asyncio.wait_for(poll_meilisearch_running(), timeout=20)
except asyncio.TimeoutError:
logger.warning(

View file

@ -200,6 +200,7 @@ class ContinueSDK:
)
async def add_context_item(self, item: ContextItem):
self.__autopilot.session_state.context_items.append(item)
await self.gui.add_context_item(item)
def set_loading_message(self, message: str):

View file

@ -0,0 +1,634 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/natesesti/Desktop/continue/server/.venv/lib/python3.11/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
" from .autonotebook import tqdm as notebook_tqdm\n",
"[2023-10-24 23:31:12,190] [DEBUG] New session: None\n",
"[2023-10-24 23:31:12,195] [DEBUG] Loaded Continue config file from /Users/natesesti/.continue/config.py\n",
"Unclosed client session\n",
"client_session: <aiohttp.client.ClientSession object at 0x127737d10>\n",
"[2023-10-24 23:31:12,266] [DEBUG] Starting context manager\n"
]
}
],
"source": [
"import json\n",
"import os\n",
"from typing import List\n",
"import asyncio\n",
"\n",
"from continuedev.core.sdk import ContinueSDK\n",
"from continuedev.libs.index.chunkers import Chunk\n",
"from continuedev.headless import start_headless_session\n",
"from continuedev.libs.index.pipelines.main import main_retrieval_pipeline, retrieval_step\n",
"from continuedev.libs.index.hyde import code_hyde\n",
"from continuedev.libs.index.rerankers.single_token import single_token_reranker_parallel\n",
"\n",
"session = await start_headless_session(directory=\"/Users/natesesti/Desktop/continue/server/continuedev\")\n",
"sdk: ContinueSDK = session.autopilot.continue_sdk"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"async def f(q: str):\n",
" return await main_retrieval_pipeline(q, sdk)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'basePath': '/Users/natesesti/Desktop/continue/server/continuedev', 'questions': [{'q': 'How does the Continue FastAPI server work?', 'files': ['server/main.py', 'server/gui.py', 'server/ide.py']}, {'q': 'Where is logic for pruning the prompt tokens?', 'files': ['libs/util/count_tokens.py', 'libs/llm/base.py']}, {'q': 'Where does codebase indexing happen?', 'files': ['plugins/steps/chroma.py', 'libs/index/indices/chroma_index.py', 'libs/index/indices/meilisearch_index.py', 'libs/index/indices/base.py', 'core/context.py']}, {'q': 'How is meilisearch used?', 'files': ['plugins/steps/chroma.py', 'libs/index/indices/meilisearch_index.py', 'libs/index/indices/base.py', 'core/context.py', 'server/meilisearch_server.py']}, {'q': 'I want to update Ollama integration', 'files': ['libs/llm/ollama.py']}, {'q': 'How does Continue chunk code?', 'files': ['libs/index/chunkers/basic.py', 'libs/index/chunkers/chunk_directory.py', 'libs/index/chunkers/chunk.py', 'libs/index/chunkers/code.py']}]}\n"
]
}
],
"source": [
"with open(\"y.json\", \"r\") as file:\n",
" data = json.load(file)\n",
"\n",
"print(data)\n",
"questions = data[\"questions\"]\n",
"base_path = data[\"basePath\"]\n",
"\n",
"def abs_paths(question):\n",
" return list(map(\n",
" lambda x: os.path.join(base_path, x),\n",
" question[\"files\"]\n",
" ))\n",
"\n",
"def in_y(chunk: Chunk, question):\n",
" return chunk.document_id in abs_paths(question)\n",
"\n",
"def f1_score(chunks: List[Chunk], question) -> float:\n",
" chosen_files = list(set(map(lambda c: c.document_id, chunks)))\n",
" actual_files = abs_paths(question)\n",
" tp = len(list(filter(lambda x: x in actual_files, chosen_files)))\n",
" fp = len(chosen_files) - tp\n",
" fn = len(actual_files) - tp\n",
" if tp == 0:\n",
" return 0\n",
"\n",
" return 2 * tp / (2 * tp + fp + fn)\n",
"\n",
"def get_recall(chunks: List[Chunk], question) -> float:\n",
" chosen_files = list(set(map(lambda c: c.document_id, chunks)))\n",
" actual_files = abs_paths(question)\n",
" tp = len(list(filter(lambda x: x in actual_files, chosen_files)))\n",
" fn = len(actual_files) - tp\n",
" if tp == 0:\n",
" return 0\n",
"\n",
" return tp / (tp + fn)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"# scores = []\n",
"# for question in questions:\n",
"# chunks = await f(question[\"q\"])\n",
"# score = f1_score(chunks, question)\n",
"# print(score)\n",
"# scores.append(score)\n",
"\n",
"# print(scores)\n",
"# print(sum(scores) / len(scores))"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"[2023-10-24 23:31:12,418] [DEBUG] Loading Meilisearch index...\n",
"[2023-10-24 23:31:12,639] [DEBUG] Loaded 0 documents into meilisearch in 0.018690824508666992 seconds for context provider code\n",
"[2023-10-24 23:31:12,645] [DEBUG] Loaded 1 documents into meilisearch in 0.02457594871520996 seconds for context provider search\n",
"[2023-10-24 23:31:12,661] [DEBUG] Loaded 1 documents into meilisearch in 0.040534019470214844 seconds for context provider terminal\n",
"[2023-10-24 23:31:12,662] [DEBUG] Loaded 1 documents into meilisearch in 0.041803836822509766 seconds for context provider url\n",
"[2023-10-24 23:31:12,663] [DEBUG] Loaded 1 documents into meilisearch in 0.042099952697753906 seconds for context provider diff\n",
"[2023-10-24 23:31:12,664] [DEBUG] Loaded 152 documents into meilisearch in 0.04308819770812988 seconds for context provider file\n",
"[2023-10-24 23:31:12,664] [DEBUG] Loaded Meilisearch index\n"
]
}
],
"source": [
"hyde_mapping = {}\n",
"hydes = await asyncio.gather(*[code_hyde(question[\"q\"], \"python\", sdk) for question in questions])\n",
"for i, hyde in enumerate(hydes):\n",
" hyde_mapping[questions[i][\"q\"]] = hyde"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Unclosed client session\n",
"client_session: <aiohttp.client.ClientSession object at 0x147c077d0>\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"1.0\n",
"1.0\n",
"1.0\n",
"0.6\n",
"1.0\n",
"0.8\n",
"[1.0, 1.0, 0.6, 0.8, 1.0, 1.0]\n",
"0.9\n"
]
}
],
"source": [
"async def get_score(question):\n",
" chunks = await retrieval_step(hyde_mapping[question[\"q\"]], sdk, n_retrieve=50)\n",
" score = get_recall(chunks, question)\n",
" print(score)\n",
" return score\n",
"\n",
"scores = await asyncio.gather(*map(get_score, questions))\n",
"\n",
"print(scores)\n",
"print(sum(scores) / len(scores))"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"25\n",
"25\n",
"25\n",
"25\n",
"25\n",
"25\n",
"10\n",
"1.0\n",
"MISSED BY RERANK: \n",
"\n",
"\n",
"10\n",
"0.7499999999999999\n",
"MISSED BY RERANK: \n",
"\n",
"\n",
"/Users/natesesti/Desktop/continue/server/continuedev/plugins/steps/chroma.py\n",
"class AnswerQuestionChroma(Step):\n",
" ...\n",
"\n",
" async def run(self, sdk: ContinueSDK) -> Coroutine[Observation, None, None]:\n",
" chroma_index = ChromaCodebaseIndex(\n",
" sdk.ide.workspace_directory, openai_api_key=self.openai_api_key\n",
" )\n",
" meilisearch_index = MeilisearchCodebaseIndex(sdk.ide.workspace_directory)\n",
"\n",
" self.hide = False\n",
" self.description = f\"Scanning {self.n_retrieve} files...\"\n",
" await sdk.update_ui()\n",
"\n",
" # Get top chunks from index\n",
" to_retrieve_from_each = (\n",
" self.n_retrieve if self.use_reranking else self.n_final\n",
" ) // 2\n",
" chroma_chunks = await chroma_index.query(\n",
" self.user_input, n=to_retrieve_from_each\n",
" )\n",
" meilisearch_chunks = await meilisearch_index.query(\n",
" self.user_input, n=to_retrieve_from_each\n",
" )\n",
" chunk_ids = set()\n",
" chunks = []\n",
" for chunk in chroma_chunks + meilisearch_chunks:\n",
" if chunk.id not in chunk_ids:\n",
" chunk_ids.add(chunk.id)\n",
" chunks.append(chunk)\n",
"\n",
" # Rerank to select top results\n",
" self.description = f\"Selecting most important files...\"\n",
" await sdk.update_ui()\n",
"\n",
" if self.use_reranking:\n",
" chunks = await default_reranker_parallel(\n",
" chunks,\n",
" self.user_input,\n",
" self.n_final,\n",
" sdk,\n",
" group_size=self.rerank_group_size,\n",
" )\n",
"\n",
" # Add context items\n",
" context_items: List[ContextItem] = []\n",
" for chunk in chunks:\n",
" # Can we select the context item through the normal means so that the name is disambiguated?\n",
" # Also so you don't have to understand the internals of the context provider\n",
" # OR have a chunk context provider??? Nice short-term, but I don't like it for long-term\n",
" ctx_item = ContextItem(\n",
" content=chunk.content,\n",
" description=ContextItemDescription(\n",
" name=f\"{os.path.basename(chunk.document_id)} ({chunk.start_line}-{chunk.end_line})\",\n",
" description=chunk.document_id,\n",
" id=ContextItemId(\n",
" provider_title=\"file\",\n",
" item_id=remove_meilisearch_disallowed_chars(chunk.document_id),\n",
" ),\n",
" ),\n",
" ) # Should be 'code' not file! And eventually should be able to embed all context providers automatically!\n",
"\n",
" context_items.append(ctx_item)\n",
" await sdk.add_context_item(ctx_item)\n",
"\n",
" self.hide = True\n",
" model = sdk.models.chat.model\n",
" # if model == \"gpt-4\":\n",
" # model = \"gpt-4-32k\" # Not publicly available yet?\n",
" if model == \"gpt-3.5-turbo\":\n",
" model = \"gpt-3.5-turbo-16k\"\n",
"\n",
" await sdk.run_step(\n",
" SimpleChatStep(\n",
" name=\"Answer Question\",\n",
" description=f\"Reading from {len(context_items)} files...\",\n",
" completion_options=CompletionOptions(model=model),\n",
" )\n",
" )\n",
"\n",
" # for ctx_item in context_items:\n",
" # await sdk.delete_context_item(ctx_item.description.id)\n",
"\n",
"\n",
"-----------------------------\n",
"\n",
"\n",
"/Users/natesesti/Desktop/continue/server/continuedev/plugins/steps/chroma.py\n",
"async def run(self, sdk: ContinueSDK) -> Coroutine[Observation, None, None]:\n",
" chroma_index = ChromaCodebaseIndex(\n",
" sdk.ide.workspace_directory,\n",
" openai_api_key=self.openai_api_key,\n",
" api_base=self.api_base,\n",
" api_type=self.api_type,\n",
" api_version=self.api_version,\n",
" organization_id=self.organization_id,\n",
" )\n",
" meilisearch_index = MeilisearchCodebaseIndex(sdk.ide.workspace_directory)\n",
"\n",
" indices_to_build = 0\n",
" chroma_exists = await chroma_index.exists()\n",
" meilisearch_exists = await meilisearch_index.exists()\n",
" if not chroma_exists:\n",
" indices_to_build += 1\n",
" if not meilisearch_exists:\n",
" indices_to_build += 1\n",
"\n",
" if indices_to_build == 0:\n",
" return\n",
"\n",
" self.hide = False\n",
"\n",
" chunks = await chunk_directory(sdk, MAX_CHUNK_SIZE)\n",
"\n",
" total_progress = 0\n",
" if not chroma_exists:\n",
" async for progress in chroma_index.build(\n",
" sdk, ignore_files=self.ignore_files, chunks=chunks\n",
" ):\n",
" self.description = f\"Generating codebase embeddings... {int(progress*100 / indices_to_build)}%\"\n",
" print(self.description, flush=True)\n",
" await sdk.update_ui()\n",
"\n",
" total_progress += 50\n",
"\n",
" if not meilisearch_exists:\n",
" async for progress in meilisearch_index.build(\n",
" sdk, ignore_files=self.ignore_files, chunks=chunks\n",
" ):\n",
" self.description = f\"Generating codebase embeddings... {int(progress*100 / indices_to_build + total_progress)}%\"\n",
" print(self.description, flush=True)\n",
" await sdk.update_ui()\n",
"\n",
" await asyncio.sleep(1)\n",
" self.hide = True\n",
"\n",
"\n",
"-----------------------------\n",
"\n",
"\n",
"10\n",
"1.0\n",
"MISSED BY RERANK: \n",
"\n",
"\n",
"10\n",
"0.6666666666666667\n",
"MISSED BY RERANK: \n",
"\n",
"\n",
"/Users/natesesti/Desktop/continue/server/continuedev/plugins/steps/chroma.py\n",
"class CreateCodebaseIndexChroma(Step):\n",
" name: str = \"Create Codebase Index\"\n",
" hide: bool = True\n",
" description: str = \"Generating codebase embeddings... 1%\"\n",
" openai_api_key: Optional[str] = Field(None, description=\"OpenAI API key\")\n",
" api_base: Optional[str] = Field(None, description=\"OpenAI API base URL\")\n",
" api_type: Optional[str] = Field(None, description=\"OpenAI API type\")\n",
" api_version: Optional[str] = Field(None, description=\"OpenAI API version\")\n",
" organization_id: Optional[str] = Field(None, description=\"OpenAI organization ID\")\n",
"\n",
" ignore_files: List[str] = Field(\n",
" [],\n",
" description=\"Files to ignore when indexing the codebase. You can use glob patterns, such as **/*.py. This is useful for directories that contain generated code, or other directories that are not relevant to the codebase.\",\n",
" )\n",
"\n",
" async def describe(self, models) -> Coroutine[str, None, None]:\n",
" ...\n",
"\n",
" async def run(self, sdk: ContinueSDK) -> Coroutine[Observation, None, None]:\n",
" ...\n",
"\n",
"\n",
"-----------------------------\n",
"\n",
"\n",
"10\n",
"1.0\n",
"MISSED BY RERANK: \n",
"\n",
"\n"
]
}
],
"source": [
"async def get_rerank_score(question):\n",
" initial_chunks = await retrieval_step(hyde_mapping[question[\"q\"]], sdk, n_retrieve=50)\n",
" initial_recall = get_recall(initial_chunks, question)\n",
" print(len(initial_chunks))\n",
" chunks = await single_token_reranker_parallel(initial_chunks, question[\"q\"], 10, sdk)\n",
" print(len(chunks))\n",
" score = get_recall(chunks, question) / initial_recall\n",
" print(score)\n",
"\n",
" missed_by_rerank = [chunk for chunk in initial_chunks if in_y(chunk, question) and chunk.document_id not in [c.document_id for c in chunks]]\n",
" print(\"MISSED BY RERANK: \\n\\n\")\n",
" for chunk in missed_by_rerank:\n",
" print(chunk.document_id)\n",
" print(chunk.content)\n",
" print(\"\\n\\n-----------------------------\\n\\n\")\n",
"\n",
" return score\n",
"\n",
"scores = await asyncio.gather(*map(get_rerank_score, questions))\n",
"\n",
"print(scores)\n",
"print(sum(scores) / len(scores))"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"PROMPT = \"\"\"\n",
"You are an expert software developer responsible for helping detect whether the retrieved snippet of code is relevant to the query. For a given input, you need to output a single word: \"Yes\" or \"No\" indicating the retrieved snippet is relevant to the query.\n",
"\n",
"Query: Where is the FastAPI server?\n",
"Snippet:\n",
"```/Users/andrew/Desktop/server/main.py\n",
"from fastapi import FastAPI\n",
"app = FastAPI()\n",
"@app.get(\"/\")\n",
"def read_root():\n",
" return {\"Hello\": \"World\"}\n",
"```\n",
"Relevant: Yes\n",
"\n",
"Query: Where in the documentation does it talk about the UI?\n",
"Snippet:\n",
"```/Users/andrew/Projects/bubble_sort/src/lib.rs\n",
"fn bubble_sort<T: Ord>(arr: &mut [T]) {\n",
" for i in 0..arr.len() {\n",
" for j in 1..arr.len() - i {\n",
" if arr[j - 1] > arr[j] {\n",
" arr.swap(j - 1, j);\n",
" }\n",
" }\n",
" }\n",
"}\n",
"```\n",
"Relevant: No\n",
"\n",
"Query: Where does codebase indexing happen?\n",
"Snippet:\n",
"```/Users/natesesti/Desktop/continue/server/continuedev/plugins/steps/chroma.py\n",
"class AnswerQuestionChroma(Step):\n",
" ...\n",
"\n",
" async def run(self, sdk: ContinueSDK) -> Coroutine[Observation, None, None]:\n",
" chroma_index = ChromaCodebaseIndex(\n",
" sdk.ide.workspace_directory, openai_api_key=self.openai_api_key\n",
" )\n",
" meilisearch_index = MeilisearchCodebaseIndex(sdk.ide.workspace_directory)\n",
"\n",
" self.hide = False\n",
" self.description = f\"Scanning {self.n_retrieve} files...\"\n",
" await sdk.update_ui()\n",
"\n",
" # Get top chunks from index\n",
" to_retrieve_from_each = (\n",
" self.n_retrieve if self.use_reranking else self.n_final\n",
" ) // 2\n",
" chroma_chunks = await chroma_index.query(\n",
" self.user_input, n=to_retrieve_from_each\n",
" )\n",
" meilisearch_chunks = await meilisearch_index.query(\n",
" self.user_input, n=to_retrieve_from_each\n",
" )\n",
" chunk_ids = set()\n",
" chunks = []\n",
" for chunk in chroma_chunks + meilisearch_chunks:\n",
" if chunk.id not in chunk_ids:\n",
" chunk_ids.add(chunk.id)\n",
" chunks.append(chunk)\n",
"\n",
" # Rerank to select top results\n",
" self.description = f\"Selecting most important files...\"\n",
" await sdk.update_ui()\n",
"\n",
" if self.use_reranking:\n",
" chunks = await default_reranker_parallel(\n",
" chunks,\n",
" self.user_input,\n",
" self.n_final,\n",
" sdk,\n",
" group_size=self.rerank_group_size,\n",
" )\n",
"\n",
" # Add context items\n",
" context_items: List[ContextItem] = []\n",
" for chunk in chunks:\n",
" # Can we select the context item through the normal means so that the name is disambiguated?\n",
" # Also so you don't have to understand the internals of the context provider\n",
" # OR have a chunk context provider??? Nice short-term, but I don't like it for long-term\n",
" ctx_item = ContextItem(\n",
" content=chunk.content,\n",
" description=ContextItemDescription(\n",
" name=f\"{os.path.basename(chunk.document_id)} ({chunk.start_line}-{chunk.end_line})\",\n",
" description=chunk.document_id,\n",
" id=ContextItemId(\n",
" provider_title=\"file\",\n",
" item_id=remove_meilisearch_disallowed_chars(chunk.document_id),\n",
" ),\n",
" ),\n",
" ) # Should be 'code' not file! And eventually should be able to embed all context providers automatically!\n",
"\n",
" context_items.append(ctx_item)\n",
" await sdk.add_context_item(ctx_item)\n",
"\n",
" self.hide = True\n",
" model = sdk.models.chat.model\n",
" # if model == \"gpt-4\":\n",
" # model = \"gpt-4-32k\" # Not publicly available yet?\n",
" if model == \"gpt-3.5-turbo\":\n",
" model = \"gpt-3.5-turbo-16k\"\n",
"\n",
" await sdk.run_step(\n",
" SimpleChatStep(\n",
" name=\"Answer Question\",\n",
" description=f\"Reading from {len(context_items)} files...\",\n",
" completion_options=CompletionOptions(model=model),\n",
" )\n",
" )\n",
"\n",
" # for ctx_item in context_items:\n",
" # await sdk.delete_context_item(ctx_item.description.id)\n",
"```\n",
"Relevant: \"\"\""
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<OpenAIObject at 0x11377c6b0> JSON: {\n",
" \"tokens\": [\n",
" \" No\"\n",
" ],\n",
" \"token_logprobs\": [\n",
" -0.0012104723\n",
" ],\n",
" \"top_logprobs\": [\n",
" {\n",
" \" No\": -0.0012104723,\n",
" \"\\n\": -6.8743377,\n",
" \"No\": -8.752341,\n",
" \"\\u00a0\": -11.196322,\n",
" \"<|endoftext|>\": -13.671831\n",
" }\n",
" ],\n",
" \"text_offset\": [\n",
" 4147\n",
" ]\n",
"}"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import openai\n",
"openai.api_key = \"\"\n",
"response = openai.Completion.create(\n",
" model=\"text-davinci-003\",\n",
" prompt=PROMPT,\n",
" max_tokens=1,\n",
" temperature=0.0,\n",
" stop=[\"```\"],\n",
" logit_bias={3363: 1, 1400: 1},\n",
" logprobs=10,\n",
")\n",
"response[\"choices\"][0][\"logprobs\"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.6"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View file

@ -0,0 +1,46 @@
{
"basePath": "/Users/natesesti/Desktop/continue/server/continuedev",
"questions": [
{
"q": "How does the Continue FastAPI server work?",
"files": ["server/main.py", "server/gui.py", "server/ide.py"]
},
{
"q": "Where is logic for pruning the prompt tokens?",
"files": ["libs/util/count_tokens.py", "libs/llm/base.py"]
},
{
"q": "Where does codebase indexing happen?",
"files": [
"plugins/steps/chroma.py",
"libs/index/indices/chroma_index.py",
"libs/index/indices/meilisearch_index.py",
"libs/index/indices/base.py",
"core/context.py"
]
},
{
"q": "How is meilisearch used?",
"files": [
"plugins/steps/chroma.py",
"libs/index/indices/meilisearch_index.py",
"libs/index/indices/base.py",
"core/context.py",
"server/meilisearch_server.py"
]
},
{
"q": "I want to update Ollama integration",
"files": ["libs/llm/ollama.py"]
},
{
"q": "How does Continue chunk code?",
"files": [
"libs/index/chunkers/basic.py",
"libs/index/chunkers/chunk_directory.py",
"libs/index/chunkers/chunk.py",
"libs/index/chunkers/code.py"
]
}
]
}

View file

@ -1,21 +1,35 @@
from typing import Optional, Union
from typing import List, Optional, Union
import typer
from ..server.protocols.cli_gui import CommandLineGUI
from ..core.context import ContextManager, ContextProvider
from ..core.main import SessionState
from ..core.autopilot import Autopilot
from .headless_ide import LocalIdeProtocol
from ..core.config import ContinueConfig
# from ..server.session_manager import Session, session_manager
# from .headless_ide import LocalIdeProtocol
# app = typer.Typer()
async def get_headless_autopilot(
directory: Optional[str] = ".",
state: Optional[SessionState] = None,
config: Optional[Union[str, ContinueConfig]] = None,
context_providers: List[ContextProvider] = [],
) -> Autopilot:
if config is not None:
if isinstance(config, str):
config: ContinueConfig = ContinueConfig.from_filepath(config)
else:
config = ContinueConfig.load_default()
ide = LocalIdeProtocol(workspace_directory=directory)
context_manager = ContextManager()
# await context_manager.start(context_providers=context_providers, ide=ide)
await config.models.start("HEADLESS", config.system_message, config.temperature)
# async def start_headless_session(
# config: Optional[Union[str, ContinueConfig]] = None
# ) -> Session:
# if config is not None:
# if isinstance(config, str):
# config: ContinueConfig = ContinueConfig.from_filepath(config)
# ide = LocalIdeProtocol()
# return await session_manager.new_session(ide, config=config)
return Autopilot(
session_state=state,
ide=ide,
gui=CommandLineGUI(),
config=config,
context_manager=context_manager,
)

View file

@ -13,7 +13,7 @@ from ..models.filesystem import (
RealFileSystem,
)
from ..models.filesystem_edit import EditDiff, FileEdit, FileSystemEdit
from ..server.ide_protocol import AbstractIdeProtocolServer
from ..server.protocols.ide_protocol import AbstractIdeProtocolServer
load_dotenv()
@ -32,6 +32,10 @@ class LocalIdeProtocol(AbstractIdeProtocolServer):
filesystem: FileSystem = RealFileSystem()
def __init__(self, workspace_directory: str = None):
if workspace_directory:
self.workspace_directory = workspace_directory
async def handle_json(self, data: Any):
"""Handle a json message"""
pass
@ -90,7 +94,10 @@ class LocalIdeProtocol(AbstractIdeProtocolServer):
async def readFile(self, filepath: str) -> str:
"""Read a file"""
return self.filesystem.read(filepath)
try:
return self.filesystem.read(filepath)
except UnicodeDecodeError:
return ""
async def readRangeInFile(self, range_in_file: RangeInFile) -> str:
"""Read a range in a file"""

View file

@ -0,0 +1,51 @@
from typing import AsyncGenerator
from ...core.config import ContinueConfig
from ...server.protocols.ide_protocol import AbstractIdeProtocolServer
from ...libs.index.chunkers.chunk_directory import chunk_directory
from ...libs.index.indices.meilisearch_index import MeilisearchCodebaseIndex
from ...libs.index.indices.chroma_index import MAX_CHUNK_SIZE, ChromaCodebaseIndex
async def build_index(
ide: AbstractIdeProtocolServer, config: ContinueConfig
) -> AsyncGenerator[float, None]:
settings = config.retrieval_settings
chroma_index = ChromaCodebaseIndex(
ide.workspace_directory,
openai_api_key=settings.openai_api_key,
api_base=settings.api_base,
api_type=settings.api_type,
api_version=settings.api_version,
organization_id=settings.organization_id,
)
meilisearch_index = MeilisearchCodebaseIndex(ide.workspace_directory)
indices_to_build = 0
chroma_exists = await chroma_index.exists()
# meilisearch_exists = await meilisearch_index.exists()
meilisearch_exists = chroma_exists
if not chroma_exists:
indices_to_build += 1
if not meilisearch_exists:
indices_to_build += 1
if indices_to_build == 0:
yield 1
return
chunks = await chunk_directory(ide, MAX_CHUNK_SIZE)
total_progress = 0
if not chroma_exists:
async for progress in chroma_index.build(
ide, ignore_files=settings.ignore_files, chunks=chunks
):
yield progress / indices_to_build
total_progress += 50
if not meilisearch_exists:
async for progress in meilisearch_index.build(
ide, ignore_files=settings.ignore_files, chunks=chunks
):
yield progress / indices_to_build + total_progress / 100

View file

@ -0,0 +1,136 @@
import asyncio
import os
from typing import Dict, List
from ....server.protocols.ide_protocol import AbstractIdeProtocolServer
from ...util.filter_files import DEFAULT_IGNORE_PATTERNS, should_filter_path
from .chunk import Chunk
from . import chunk_document
FILE_IGNORE_PATTERNS = [
# File Names
"**/.DS_Store",
"**/package-lock.json",
"**/yarn.lock",
# File Types
"*.log",
"*.ttf",
"*.png",
"*.jpg",
"*.jpeg",
"*.gif",
"*.mp4",
"*.svg",
"*.ico",
"*.pdf",
"*.zip",
"*.gz",
"*.tar",
"*.tgz",
"*.rar",
"*.7z",
"*.exe",
"*.dll",
"*.obj",
"*.o",
"*.a",
"*.lib",
"*.so",
"*.dylib",
"*.ncb",
"*.sdf",
]
MAX_SIZE_IN_CHARS = 50_000
async def get_file_contents(filepath: str, ide: AbstractIdeProtocolServer) -> str:
try:
return (await ide.readFile(filepath))[:MAX_SIZE_IN_CHARS]
except Exception as _:
return None
async def get_contents_of_files(
files: List[str], ide: AbstractIdeProtocolServer, ignore_files: List[str] = []
) -> List[str]:
# Get file contents for all at once
return await asyncio.gather(*[ide.readFile(file) for file in files])
def gi_basename(path: str) -> str:
return path[: path.index(".gitignore")]
async def get_all_file_contents(
ide: AbstractIdeProtocolServer, ignore_files: List[str] = [], group_size: int = 100
) -> Dict[str, str]:
# Get list of filenames to index
files = await ide.listDirectoryContents(ide.workspace_directory, True)
# Get all .gitignores first
gitignore_paths = list(
filter(
lambda file: file.endswith(".gitignore")
or file.endswith(".continueignore"),
files,
)
)
gitignore_contents = await get_contents_of_files(gitignore_paths, ide)
gitignores = {
path: content for path, content in zip(gitignore_paths, gitignore_contents)
}
def gitignore_patterns_for_file(filepath: str) -> List[str]:
paths = list(
filter(
lambda gitignore_path: filepath.startswith(gi_basename(gitignore_path)),
gitignore_paths,
)
)
patterns = []
for path in paths:
base = gi_basename(path)
for pattern in gitignores[path].split("\n"):
if pattern.strip() != "":
patterns.append(os.path.join(base, pattern.strip()))
return patterns
# Filter from ignore_directories
files = list(
filter(
lambda file: not should_filter_path(
file,
ignore_files
+ DEFAULT_IGNORE_PATTERNS
+ FILE_IGNORE_PATTERNS
+ gitignore_patterns_for_file(file),
),
files,
)
)
items = []
i = 0
# Don't want to flood with too many requests
while i < len(files):
items += await get_contents_of_files(files[i : i + group_size], ide)
i += group_size
await asyncio.sleep(0.1)
return dict(filter(lambda tup: tup[1] is not None, zip(files, items)))
async def chunk_directory(
ide: AbstractIdeProtocolServer, max_chunk_size: int
) -> List[Chunk]:
file_contents = await get_all_file_contents(ide)
chunks = []
for filepath, contents in file_contents.items():
chunks += chunk_document(filepath, contents, max_chunk_size)
return chunks

View file

@ -0,0 +1,50 @@
# Hypothetical Document Embeddings (HyDE) - Prompts
from ..llm.base import LLM
CODE_PROMPT = """\
Generate a hypothetical snippet of code that would be relevant in answering the user's question.
It can be either a function, a class, or more than one of these. It should be roughly 10-20 lines of code and must be valid {language} code.
User question: {user_input}
Write your code in the block below:
```{language}
"""
async def code_hyde(user_input, language: str, model: LLM):
prompt = CODE_PROMPT.format(user_input=user_input, language=language)
completion = await model.complete(
prompt, log=False, max_tokens=100, temperature=0.0, stop=["```"]
)
return completion
KEYWORDS_PROMPT = """\
For each user question, generate keywords or file names that would be useful to search for in the codebase. Don't repeat or include similar keywords more than once. Try to include specific keywords or snippets of code that might exist in a codebase, not just general terms. Separate the keywords with a comma.
User question: Where should I add unit tests for this Python project?
Keywords: import pytest, test, import unittest, pytest-cov, coverage, coverage.py, assert, fixture, pytest.mark.parametrize
User: How to add a new command to this VS Code extension?
Keywords: vscode, command, package.json, vscode.commands.registerCommand
User: How to add a new endpoint to this Spring Boot application?
Keywords: spring, boot, endpoint, controller, request mapping, mapping, requestbody, requestparam, pathvariable, req
User question: {user_input}
Keywords:
"""
async def generate_keywords(user_input, model: LLM):
completion = await model.complete(
KEYWORDS_PROMPT.format(user_input=user_input),
log=False,
max_tokens=80,
temperature=0.0,
stop=["\n"],
)
return completion.strip().replace("'", "").replace('"', "").split(", ")

View file

@ -0,0 +1,39 @@
from abc import ABC, abstractmethod
from typing import AsyncGenerator, List, Optional
from ....server.protocols.ide_protocol import AbstractIdeProtocolServer
from ....core.sdk import ContinueSDK
from ..chunkers import Chunk
class CodebaseIndex(ABC):
directory: str
def __init__(self, directory: str):
self.directory = directory
@abstractmethod
async def exists(self) -> bool:
"""Returns whether the index exists (has been built)"""
raise NotImplementedError()
@abstractmethod
async def build(
self,
ide: AbstractIdeProtocolServer,
ignore_files: List[str] = [],
chunks: Optional[List[Chunk]] = None,
) -> AsyncGenerator[float, None]:
"""Builds the index, yielding progress as a float between 0 and 1. Optionally takes a list of chunks, otherwise builds its own"""
raise NotImplementedError()
@abstractmethod
async def update(self) -> AsyncGenerator[float, None]:
"""Updates the index, yielding progress as a float between 0 and 1"""
raise NotImplementedError()
@abstractmethod
async def query(self, query: str, n: int = 4) -> List[Chunk]:
"""Queries the index, returning the top n results"""
raise NotImplementedError()

View file

@ -8,54 +8,19 @@ from typing import AsyncGenerator, Dict, List, Literal, Optional
import chromadb
from chromadb.config import Settings
from chromadb.utils import embedding_functions
from ....server.protocols.ide_protocol import AbstractIdeProtocolServer
from .base import CodebaseIndex
from dotenv import load_dotenv
from openai.error import RateLimitError
from pydantic import BaseModel
from .chunkers.chunk import Chunk
from ...libs.index.git import GitProject
from ...core.sdk import ContinueSDK
from ..util.filter_files import DEFAULT_IGNORE_PATTERNS, should_filter_path
from ..util.logging import logger
from ..util.paths import getEmbeddingsPathForBranch
from .chunkers import chunk_document
from ..chunkers.chunk import Chunk
from ..git import GitProject
from ...util.logging import logger
from ...util.paths import getEmbeddingsPathForBranch
load_dotenv()
IGNORE_PATTERNS_FOR_CHROMA = [
# File Names
"**/.DS_Store",
"**/package-lock.json",
"**/yarn.lock",
# File Types
"*.log",
"*.ttf",
"*.png",
"*.jpg",
"*.jpeg",
"*.gif",
"*.mp4",
"*.svg",
"*.ico",
"*.pdf",
"*.zip",
"*.gz",
"*.tar",
"*.tgz",
"*.rar",
"*.7z",
"*.exe",
"*.dll",
"*.obj",
"*.o",
"*.a",
"*.lib",
"*.so",
"*.dylib",
"*.ncb",
"*.sdf",
]
# Mapping of workspace_dir to chromadb collection
collections = {}
@ -70,7 +35,7 @@ class CodebaseIndexMetadata(BaseModel):
chunks: Dict[str, int]
class ChromaCodebaseIndex:
class ChromaCodebaseIndex(CodebaseIndex):
directory: str
client: chromadb.Client
openai_api_key: str = None
@ -130,7 +95,7 @@ class ChromaCodebaseIndex:
def metadata_path(self) -> str:
return os.path.join(self.index_dir, "metadata.json")
def exists(self):
async def exists(self):
"""Check whether the codebase index has already been built and saved on disk"""
return os.path.exists(self.metadata_path)
@ -185,57 +150,32 @@ class ChromaCodebaseIndex:
return collection
async def build(
self, sdk: ContinueSDK, ignore_files: List[str] = []
self,
ide: AbstractIdeProtocolServer,
ignore_files: List[str] = [],
chunks: Optional[List[Chunk]] = None,
) -> AsyncGenerator[float, None]:
"""Create a new index for the current branch."""
if self.exists():
if await self.exists():
return
# Get list of filenames to index
files = await sdk.ide.listDirectoryContents(sdk.ide.workspace_directory, True)
if chunks is None:
raise Exception("Chunks must be passed in to build Chroma index")
# Filter from ignore_directories
files = list(
# Construct list of chunks for each file
chunks = list(
filter(
lambda file: not should_filter_path(
file,
ignore_files + DEFAULT_IGNORE_PATTERNS + IGNORE_PATTERNS_FOR_CHROMA,
),
files,
lambda c: len(c.content.strip()) > 0,
chunks,
)
)
# Get file contents for all at once
tasks = []
async def readFile(filepath: str) -> Optional[str]:
to = 0.1
while True:
try:
return await sdk.ide.readFile(filepath)
except Exception as e:
if to > 4:
return None
await asyncio.sleep(to)
to *= 2
for file in files:
tasks.append(readFile(file))
file_contents = await asyncio.gather(*tasks)
# Construct list of chunks for each file
chunks: List[Chunk] = []
num_chunks_per_file = {}
for i in range(len(files)):
document_chunks = [
c
for c in chunk_document(files[i], file_contents[i], MAX_CHUNK_SIZE)
if len(c.content.strip()) > 0
]
num_chunks_per_file[files[i]] = len(document_chunks)
chunks.extend(document_chunks)
for chunk in chunks:
num_chunks_per_file[chunk.document_id] = (
num_chunks_per_file.get(chunk.document_id, 0) + 1
)
# Flatten chunks, metadata, and ids for insertion to Chroma
documents = []
@ -285,12 +225,10 @@ class ChromaCodebaseIndex:
indent=4,
)
logger.debug("Codebase index created")
async def update(self):
"""Update the index with a list of files."""
if not self.exists():
if not await self.exists():
self.build()
else:
metadata = self.get_metadata()
@ -334,9 +272,9 @@ class ChromaCodebaseIndex:
logger.debug("Codebase index updated")
def query(self, query: str, n: int = 4) -> List[Chunk]:
async def query(self, query: str, n: int = 4) -> List[Chunk]:
"""Query the codebase index for top n results"""
if not self.exists():
if not await self.exists():
logger.warning(f"No index found for the codebase at {self.index_dir}")
return []

View file

@ -0,0 +1,151 @@
import asyncio
from functools import cached_property
from ....server.protocols.ide_protocol import AbstractIdeProtocolServer
from meilisearch_python_async import Client
from meilisearch_python_async.errors import MeilisearchApiError
from ....server.meilisearch_server import get_meilisearch_url
from .base import CodebaseIndex
from ..chunkers import Chunk
from typing import Any, AsyncGenerator, Dict, List, Optional
from ....server.meilisearch_server import remove_meilisearch_disallowed_chars
from ...util.logging import logger
class MeilisearchCodebaseIndex(CodebaseIndex):
directory: str
def __init__(self, directory: str):
self.directory = directory
@cached_property
def index_name(self) -> str:
return remove_meilisearch_disallowed_chars(self.directory)
async def exists(self) -> bool:
"""Returns whether the index exists (has been built)"""
async with Client(get_meilisearch_url()) as search_client:
try:
index = await search_client.get_index(self.index_name)
return index is not None
except MeilisearchApiError as e:
return False
except Exception as e:
logger.warning(f"Error while checking if meilisearch index exists: {e}")
return False
def chunk_to_meilisearch_document(self, chunk: Chunk, index: int) -> Dict[str, Any]:
return {
"id": str(index),
"content": chunk.content,
"document_id": chunk.document_id,
**chunk.other_metadata,
"metadata": {
"start_line": chunk.start_line,
"end_line": chunk.end_line,
"index": chunk.index,
},
}
def meilisearch_document_to_chunk(self, document: Dict[str, Any]) -> Chunk:
other_metadata = document.copy()
del other_metadata["content"]
del other_metadata["metadata"]
del other_metadata["document_id"]
del other_metadata["id"]
return Chunk(
content=document["content"],
start_line=document["metadata"]["start_line"],
end_line=document["metadata"]["end_line"],
index=document["metadata"]["index"],
document_id=document["document_id"],
other_metadata=other_metadata,
)
async def build(
self,
ide: AbstractIdeProtocolServer,
ignore_files: List[str] = [],
chunks: Optional[List[Chunk]] = None,
) -> AsyncGenerator[float, None]:
"""Builds the index, yielding progress as a float between 0 and 1"""
if chunks is None:
logger.warning("Meilisearch index requires chunks to be passed in")
yield 1
async with Client(get_meilisearch_url()) as search_client:
try:
await search_client.create_index(self.index_name)
index = await search_client.get_index(self.index_name)
# await index.update_ranking_rules(
# ["attribute", "words", "typo", "proximity", "sort", "exactness"]
# )
await index.update_searchable_attributes(["content", "document_id"])
i = 0
GROUP_SIZE = 100
while i < len(chunks):
await index.add_documents(
[
self.chunk_to_meilisearch_document(chunk, j)
for j, chunk in enumerate(chunks[i : i + GROUP_SIZE])
]
)
i += GROUP_SIZE
yield i / len(chunks)
await asyncio.sleep(0.1)
except Exception as e:
logger.warning(f"Error while building meilisearch index: {e}")
yield 1
async def update(self) -> AsyncGenerator[float, None]:
"""Updates the index, yielding progress as a float between 0 and 1"""
raise NotImplementedError()
async def _query(self, query: str, n: int = 4) -> List[Chunk]:
async with Client(get_meilisearch_url()) as search_client:
try:
results = await search_client.index(self.index_name).search(
query, limit=n
)
return [
self.meilisearch_document_to_chunk(result)
for result in results.hits
]
except Exception as e:
logger.warning(f"Error while retrieving document from meilisearch: {e}")
return []
async def query(self, query: str, n: int = 4) -> List[Chunk]:
"""Queries the index, returning the top n results"""
return await self._query(query, n=n)
async def query_keywords(self, keywords: List[str], n: int = 4) -> List[Chunk]:
count_per_chunk = {}
id_to_chunk = {}
for keyword in keywords:
chunks = await self._query(keyword, n=n)
for chunk in chunks:
if chunk.id not in count_per_chunk:
count_per_chunk[chunk.id] = 0
id_to_chunk[chunk.id] = chunk
count_per_chunk[chunk.id] += 1
# Sort by count
sorted_chunks = sorted(
count_per_chunk.items(), key=lambda item: item[1], reverse=True
)
# Get top n
chunks = []
for chunk_id, count in sorted_chunks[:n]:
chunks.append(id_to_chunk[chunk_id])
return chunks

View file

@ -0,0 +1,56 @@
from meilisearch_python_async import Client
async def add_docs():
async with Client("http://localhost:7700") as search_client:
index = await search_client.create_index("UsersnatesestiDesktopcontinueguisrc")
await index.delete_all_documents()
return
await index.add_documents(
[
{
"id": 0,
"content": 'import GUI from "./pages/gui";\nimport History from "./pages/history";\nimport Help from "./pages/help";\nimport Layout from "./components/Layout";\nimport { createContext, useEffect } from "react";\nimport useContinueGUIProtocol from "./hooks/useWebsocket";\nimport ContinueGUIClientProtocol from "./hooks/ContinueGUIClientProtocol";\nimport { useDispatch } from "react-redux";\nimport {\n setApiUrl,\n setVscMachineId,\n setSessionId,\n setVscMediaUrl,\n setDataSwitchOn,\n setWorkspacePaths,\n} from "./redux/slices/configSlice";\nimport {\n setHighlightedCode,\n setServerStatusMessage,\n} from "./redux/slices/miscSlice";\nimport { postVscMessage } from "./vscode";\nimport { RouterProvider, createMemoryRouter } from "react-router-dom";\nimport ErrorPage from "./pages/error";\nimport SettingsPage from "./pages/settings";\nimport Models from "./pages/models";\nimport HelpPage from "./pages/help";\nimport ModelConfig from "./pages/modelconfig";\nimport { usePostHog } from "posthog-js/react";\n\nconst router = createMemoryRouter([\n {\n path: "/",\n element: <Layout />,\n errorElement: <ErrorPage />,\n children: [\n {\n path: "/index.html",\n element: <GUI />,\n },\n {\n path: "/",\n element: <GUI />,\n },\n {\n path: "/history",\n element: <History />,\n },\n {\n path: "/help",\n element: <Help />,\n },\n {\n path: "/settings",\n element: <SettingsPage />,\n },\n {\n path: "/models",\n element: <Models />,\n },\n {\n path: "/help",\n element: <HelpPage />,\n },\n {\n path: "/modelconfig/:modelName",\n element: <ModelConfig />,\n },\n ],\n },\n]);\n\nexport const GUIClientContext = createContext<\n ContinueGUIClientProtocol | undefined\n>(undefined);\n\nfunction App() {\n const client = useContinueGUIProtocol(false);\n const posthog = usePostHog();\n\n const dispatch = useDispatch();\n useEffect(() => {\n const eventListener = (event: any) => {\n switch (event.data.type) {\n case "onLoad":\n dispatch(setApiUrl(event.data.apiUrl));\n dispatch(setVscMachineId(event.data.vscMachineId));\n dispatch(setSessionId(event.data.sessionId));\n',
"document_id": "/Users/natesesti/Desktop/continue/gui/src/App.tsx",
"metadata": {"start_pos": 0, "end_pos": 10, "index": 0},
},
{
"id": 1,
"content": ' dispatch(setVscMediaUrl(event.data.vscMediaUrl));\n dispatch(setDataSwitchOn(event.data.dataSwitchOn));\n if (event.data.uniqueId) {\n posthog?.identify(event.data.vscMachineId);\n }\n dispatch(setWorkspacePaths(event.data.workspacePaths));\n break;\n case "highlightedCode":\n dispatch(setHighlightedCode(event.data.rangeInFile));\n break;\n case "serverStatus":\n dispatch(setServerStatusMessage(event.data.message));\n break;\n }\n };\n window.addEventListener("message", eventListener);\n postVscMessage("onLoad", {});\n return () => window.removeEventListener("message", eventListener);\n }, []);\n\n useEffect(() => {\n if (document.body.style.getPropertyValue("--vscode-editor-foreground")) {\n localStorage.setItem(\n "--vscode-editor-foreground",\n document.body.style.getPropertyValue("--vscode-editor-foreground")\n );\n }\n if (document.body.style.getPropertyValue("--vscode-editor-background")) {\n localStorage.setItem(\n "--vscode-editor-background",\n document.body.style.getPropertyValue("--vscode-editor-background")\n );\n }\n if (document.body.style.getPropertyValue("--vscode-list-hoverBackground")) {\n localStorage.setItem(\n "--vscode-list-hoverBackground",\n document.body.style.getPropertyValue("--vscode-list-hoverBackground")\n );\n }\n }, []);\n\n return (\n <GUIClientContext.Provider value={client}>\n <RouterProvider router={router} />\n </GUIClientContext.Provider>\n );\n}\n\nexport default App;\n\n',
"document_id": "/Users/natesesti/Desktop/continue/gui/src/App.tsx",
# "metadata": {...},
},
{
"id": 2,
"content": '@tailwind base;\n@tailwind components;\n@tailwind utilities;\n\n:root {\n --secondary-dark: rgb(37, 37, 38);\n --vsc-background: rgb(30, 30, 30);\n --button-color: rgb(113, 28, 59);\n --button-color-hover: rgba(113, 28, 59, 0.667);\n --def-border-radius: 5px;\n\n --vscode-editor-background: rgb(30, 30, 30);\n --vscode-editor-foreground: rgb(197, 200, 198);\n --vscode-textBlockQuote-background: rgba(255, 255, 255, 1);\n}\n\nhtml,\nbody,\n#root {\n height: 100%;\n background-color: var(--vscode-editor-background);\n font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,\n Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;\n}\n\nbody {\n padding: 0;\n color: var(--vscode-editor-foreground);\n padding: 0px;\n margin: 0px;\n height: 100%;\n}\n\n.press-start-2p {\n font-family: "Press Start 2P", sans-serif;\n}\n\na:focus {\n outline: none;\n}\n\n',
"document_id": "/Users/natesesti/Desktop/continue/gui/src/index.css",
# "metadata": {...},
},
{
"id": 3,
"content": 'import React from "react";\nimport ReactDOM from "react-dom/client";\nimport App from "./App";\nimport { Provider } from "react-redux";\nimport store from "./redux/store";\nimport "./index.css";\n\nimport CustomPostHogProvider from "./hooks/CustomPostHogProvider";\n\nReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(\n <React.StrictMode>\n <Provider store={store}>\n <CustomPostHogProvider>\n <App />\n </CustomPostHogProvider>\n </Provider>\n </React.StrictMode>\n);\n\n',
"document_id": "/Users/natesesti/Desktop/continue/gui/src/main.tsx",
# "metadata": {...},
},
]
)
async def query(query: str):
async with Client("http://localhost:7700") as search_client:
results = await search_client.index(
"UsersnatesestiDesktopcontinueguisrc"
).search(query, limit=4)
return results
async def main():
await add_docs()
results = await query("import")
print(results)
if __name__ == "__main__":
import asyncio
asyncio.run(main())

View file

@ -0,0 +1,72 @@
from typing import List, Optional
from ..hyde import code_hyde
from ..rerankers.default import default_reranker_parallel
from ..rerankers.single_token import single_token_reranker_parallel
from ..indices.meilisearch_index import MeilisearchCodebaseIndex
from ....core.sdk import ContinueSDK
from ..indices.chroma_index import ChromaCodebaseIndex
from ..chunkers.chunk import Chunk
async def retrieval_step(
query: str,
sdk: ContinueSDK,
n_retrieve: int = 50,
n_final: int = 10,
use_reranking: bool = True,
openai_api_key: Optional[str] = None,
) -> List[Chunk]:
chroma_index = ChromaCodebaseIndex(
sdk.ide.workspace_directory, openai_api_key=openai_api_key
)
meilisearch_index = MeilisearchCodebaseIndex(sdk.ide.workspace_directory)
print(f"Scanning {n_retrieve} files...")
# Get top chunks from index
to_retrieve_from_each = (n_retrieve if use_reranking else n_final) // 2
hyde = await code_hyde(query, "", sdk)
chroma_chunks = await chroma_index.query(hyde, n=to_retrieve_from_each)
meilisearch_chunks = await meilisearch_index.query(query, n=to_retrieve_from_each)
# De-duplicate
chunk_ids = set()
chunks = []
for chunk in chroma_chunks + meilisearch_chunks:
if chunk.id not in chunk_ids:
chunk_ids.add(chunk.id)
chunks.append(chunk)
return chunks
async def main_retrieval_pipeline(
query: str,
sdk: ContinueSDK,
openai_api_key: Optional[str] = None,
n_retrieve: int = 50,
use_reranking: bool = True,
n_final: int = 10,
rerank_group_size: int = 5,
) -> List[Chunk]:
chunks = await retrieval_step(
query,
sdk,
n_retrieve=n_retrieve,
use_reranking=use_reranking,
openai_api_key=openai_api_key,
n_final=n_final,
)
# Rerank to select top results
if use_reranking:
print(f"Selecting most important files...")
chunks = await single_token_reranker_parallel(
chunks,
query,
n_final,
sdk,
)
return chunks

View file

@ -2,13 +2,12 @@ import asyncio
import os
from typing import Dict, List
from ...llm.base import LLM
from ..chunkers.chunk import Chunk
from continuedev.core.sdk import ContinueSDK
async def decide_include_remove(
chunks: List[Chunk], user_input: str, n: int, sdk: ContinueSDK
chunks: List[Chunk], user_input: str, n: int, model: LLM
) -> Dict[str, str]:
"""
Reranks the results from the codebase index based on the user input.
@ -88,15 +87,15 @@ Now for the real task, here are the top {len(chunks)} results from the codebase
List the results that are not useful in answering the request, using in the same format from the example. Only choose those that are completely unrelated, and no more than {n // 2}:"""
include = sdk.models.summarize.complete(include_prompt, log=False)
remove = sdk.models.summarize.complete(remove_prompt, log=False)
include = model.complete(include_prompt, log=False)
remove = model.complete(remove_prompt, log=False)
include_completion, remove_completion = await asyncio.gather(include, remove)
return include_completion.split("\n"), remove_completion.split("\n")
async def default_reranker_parallel(
chunks: List[Chunk], user_input: str, n: int, sdk: ContinueSDK
chunks: List[Chunk], user_input: str, n: int, model: LLM, group_size: int = 10
) -> List[Chunk]:
"""
A reranker, given a mapping from id to contents, returns the subset of the mapping that is most relevant to the user_input
@ -106,7 +105,7 @@ async def default_reranker_parallel(
group = []
for chunk in chunks:
group.append(chunk)
if len(group) == 10:
if len(group) == group_size:
groups.append(group)
group = []
@ -119,7 +118,7 @@ async def default_reranker_parallel(
tasks = []
for group in groups:
tasks.append(decide_include_remove(group, user_input, n, sdk))
tasks.append(decide_include_remove(group, user_input, n, model))
reranking_results = await asyncio.gather(*tasks)
for rr in reranking_results:

View file

@ -0,0 +1,91 @@
import asyncio
from typing import List
from ...llm.base import LLM
import openai
from ..chunkers.chunk import Chunk
from ...util.logging import logger
PROMPT = """
You are an expert software developer responsible for helping detect whether the retrieved snippet of code is relevant to the query. For a given input, you need to output a single word: "Yes" or "No" indicating the retrieved snippet is relevant to the query.
Query: Where is the FastAPI server?
Snippet:
```/Users/andrew/Desktop/server/main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {{"Hello": "World"}}
```
Relevant: Yes
Query: Where in the documentation does it talk about the UI?
Snippet:
```/Users/andrew/Projects/bubble_sort/src/lib.rs
fn bubble_sort<T: Ord>(arr: &mut [T]) {{
for i in 0..arr.len() {{
for j in 1..arr.len() - i {{
if arr[j - 1] > arr[j] {{
arr.swap(j - 1, j);
}}
}}
}}
}}
```
Relevant: No
Query: {query}
Snippet:
```{document_id}
{document}
```
Relevant:
"""
async def single_token_reranker(chunk: Chunk, user_input: str, model: LLM) -> float:
compiled_prompt = PROMPT.format(
query=user_input, document=chunk.content, document_id=chunk.document_id
)
if False:
# TODO: Continuous ranking with logits
# openai.api_key = openai_api_key
response = openai.Completion.create(
model="gpt-3.5-turbo",
prompt=compiled_prompt,
max_tokens=1,
temperature=0.0,
stop=["```"],
logit_bias={3363: 1, 1400: 1},
logprobs=1,
)
return response["choices"][0]["logprobs"]["token_logprobs"][0]
else:
try:
completion = await model.complete(
compiled_prompt, log=False, max_tokens=1, temperature=0.0
)
except Exception:
return 0.5
answer = completion.strip().lower().replace('"', "").replace("'", "")
if answer == "yes":
return 1.0
elif answer == "no":
return 0.0
else:
logger.warning(f"Unexpected response from single token reranker: {answer}")
return 0.0
async def single_token_reranker_parallel(
chunks: List[Chunk], user_input: str, n: int, model: LLM
) -> List[Chunk]:
tasks = [single_token_reranker(chunk, user_input, model) for chunk in chunks]
results = await asyncio.gather(*tasks)
# Sort by results, return top n
sorted_chunks = sorted(zip(chunks, results), key=lambda x: x[1], reverse=True)
return [chunk for chunk, _ in sorted_chunks[:n]]

View file

@ -3,8 +3,10 @@ from typing import List, Literal, Optional
import certifi
from ..util.count_tokens import MAX_TOKENS_FOR_MODEL
from ..util.logging import logger
from .prompts.chat import template_alpaca_messages
import openai
from openai.error import RateLimitError
from pydantic import Field
from ...core.main import ChatMessage
@ -164,7 +166,10 @@ class OpenAI(LLM):
if self.api_type == "azure":
# To smooth out the response streaming, which typically comes in bursts
await asyncio.sleep(0.01)
if self.model == "gpt-4":
await asyncio.sleep(0.03)
else:
await asyncio.sleep(0.01)
yield chunk.choices[0].delta
else:
@ -187,12 +192,21 @@ class OpenAI(LLM):
args["model"] not in NON_CHAT_MODELS
and not self.use_legacy_completions_endpoint
):
resp = await openai.ChatCompletion.acreate(
messages=[{"role": "user", "content": prompt}],
**args,
headers=self.headers,
)
return resp.choices[0].message.content
wait_time = 0.2
while True:
try:
resp = await openai.ChatCompletion.acreate(
messages=[{"role": "user", "content": prompt}],
**args,
headers=self.headers,
)
return resp.choices[0].message.content
except RateLimitError as e:
logger.debug(f"Rate limit exceeded, waiting {wait_time} seconds")
await asyncio.sleep(wait_time)
wait_time *= 2
if wait_time > 2**10:
raise e
else:
return (
(

View file

@ -73,6 +73,11 @@ class ProxyServer(LLM):
yield loaded_chunk
await asyncio.sleep(0.01)
if self.model == "gpt-4":
await asyncio.sleep(0.03)
else:
await asyncio.sleep(0.01)
except Exception as e:
posthog_logger.capture_event(
"proxy_server_parse_error",

View file

@ -0,0 +1,29 @@
ext_dict = {
"py": "python",
"js": "javascript",
"ts": "typescript",
"java": "java",
"go": "go",
"rb": "ruby",
"rs": "rust",
"c": "c",
"cpp": "cpp",
"cs": "csharp",
"php": "php",
"scala": "scala",
"swift": "swift",
"kt": "kotlin",
"md": "markdown",
"json": "json",
"html": "html",
"css": "css",
"sh": "shell",
"yaml": "yaml",
"toml": "toml",
"tex": "latex",
"sql": "sql",
}
def ext_to_lang(ext: str) -> str:
return ext_dict.get(ext, "plaintext")

View file

@ -1,5 +1,6 @@
import fnmatch
# import fnmatch
from typing import List
import pathspec
DEFAULT_IGNORE_DIRS = [
".git",
@ -30,4 +31,8 @@ def should_filter_path(
path: str, ignore_patterns: List[str] = DEFAULT_IGNORE_PATTERNS
) -> bool:
"""Returns whether a file should be filtered"""
return any(fnmatch.fnmatch(path, pattern) for pattern in ignore_patterns)
spec = pathspec.PathSpec.from_lines(
pathspec.patterns.GitWildMatchPattern, ignore_patterns
)
return spec.match_file(path)
# return any(fnmatch.fnmatch(path, pattern) for pattern in ignore_patterns)

View file

@ -55,14 +55,14 @@ def decode_escaped_path(path: str) -> str:
"""We use a custom escaping scheme to record the full path of a file as a
corresponding basename, but withut URL encoding, because then the URI just gets
interpreted as a full path again."""
return path.replace("$f$", "/").replace("$b$", "\\")
return path.replace("_f_", "/").replace("_b_", "\\")
def encode_escaped_path(path: str) -> str:
"""We use a custom escaping scheme to record the full path of a file as a
corresponding basename, but withut URL encoding, because then the URI just gets
interpreted as a full path again."""
return path.replace("/", "$f$").replace("\\", "$b$")
return path.replace("/", "_f_").replace("\\", "_b_")
def getEmbeddingsPathForBranch(workspace_dir: str, branch_name: str):
@ -114,6 +114,7 @@ def migrateConfigFile(existing: str) -> Optional[str]:
.replace("medium=", "summarize=")
.replace("TextGenUI", "TextGenWebUI")
.replace("text_gen_interface", "text_gen_webui")
.replace(".steps.chroma", ".steps.codebase")
)
if migrated != existing:
return migrated

View file

@ -4,6 +4,7 @@ from typing import Dict, List, Tuple
from pydantic import BaseModel
from ..libs.util.filter_files import should_filter_path
from ..models.main import AbstractModel, Position, Range
from .filesystem_edit import (
AddDirectory,
@ -332,6 +333,7 @@ class RealFileSystem(FileSystem):
# Walk
paths = []
for root, dirs, files in os.walk(path):
dirs[:] = list(filter(lambda p: not should_filter_path(p), dirs))
for f in files:
paths.append(os.path.join(root, f))

View file

@ -6,7 +6,7 @@ from pydantic import BaseModel
from ...core.context import ContextProvider
from ...core.main import ContextItem, ContextItemDescription, ContextItemId
from ...libs.index.codebase_index import ChromaIndexManager
from ...libs.index.indices.chroma_index import ChromaIndexManager
class EmbeddingResult(BaseModel):

View file

@ -8,7 +8,7 @@ from ...core.context import ContextProvider
from ...core.main import ChatMessage, ContextItem, ContextItemDescription, ContextItemId
from ...libs.util.filter_files import DEFAULT_IGNORE_PATTERNS
from ...libs.util.logging import logger
from .util import remove_meilisearch_disallowed_chars
from ...server.meilisearch_server import remove_meilisearch_disallowed_chars
MAX_SIZE_IN_CHARS = 50_000

View file

@ -6,7 +6,7 @@ from pydantic import Field
from ...core.context import ContextProvider
from ...core.main import ContextItem, ContextItemDescription, ContextItemId
from .util import remove_meilisearch_disallowed_chars
from ...server.meilisearch_server import remove_meilisearch_disallowed_chars
class GoogleContextProvider(ContextProvider):

View file

@ -15,7 +15,7 @@ class SearchContextProvider(ContextProvider):
title = "search"
display_title = "Search"
description = "Search workspace for matches of an exact string"
description = "Search workspace for exact matches"
dynamic = True
requires_query = True

View file

@ -3,7 +3,7 @@ from typing import Type, Union
from ..steps.clear_history import ClearHistoryStep
from ..steps.comment_code import CommentCodeStep
from ..steps.share_session import ShareSessionStep
from ..steps.chroma import AnswerQuestionChroma
from ..steps.codebase import AnswerQuestionChroma
from ...core.config import ContinueConfig
from ...core.main import Policy, SessionState, Step
from ..steps.chat import SimpleChatStep
@ -100,4 +100,7 @@ class DefaultPolicy(Policy):
if user_input.startswith("/edit"):
return EditHighlightedCodeStep(user_input=user_input[5:])
if user_input.startswith("/codebase "):
return AnswerQuestionChroma(user_input=user_input[len("/codebase ") :])
return self.default_step(**self.default_params)

View file

@ -1,6 +1,5 @@
# from .chroma import (
# AnswerQuestionChroma, # noqa: F401
# CreateCodebaseIndexChroma, # noqa: F401
# EditFileChroma, # noqa: F401
# )
from .clear_history import ClearHistoryStep # noqa: F401

View file

@ -23,15 +23,11 @@ class SimpleChatStep(Step):
manage_own_chat_context: bool = True
description: str = ""
messages: List[ChatMessage] = None
prompt: Optional[str] = None
completion_options: Optional[CompletionOptions] = None
async def run(self, sdk: ContinueSDK):
messages = self.messages or await sdk.get_chat_context()
kwargs = self.completion_options.dict() if self.completion_options else {}
generator = sdk.models.chat.stream_chat(messages, **kwargs)
posthog_logger.capture_event(
"model_use",
{
@ -47,6 +43,15 @@ class SimpleChatStep(Step):
},
)
messages = self.messages or await sdk.get_chat_context()
if self.prompt and messages:
messages[-1].content = self.prompt
kwargs = self.completion_options.dict() if self.completion_options else {}
generator = sdk.models.chat.stream_chat(messages, **kwargs)
yield SetStep(description="")
async for chunk in generator:
if "content" in chunk:
yield chunk["content"]

View file

@ -1,161 +0,0 @@
import os
from typing import Coroutine, List, Optional, Union
from ...libs.llm.base import CompletionOptions
from ...libs.index.rerankers.default import default_reranker_parallel
from pydantic import Field
from ...core.main import (
ContextItem,
ContextItemDescription,
ContextItemId,
DeltaStep,
SetStep,
Step,
)
from ...core.sdk import ContinueSDK
from ...core.steps import EditFileStep
from ...libs.index.codebase_index import ChromaCodebaseIndex
from ..context_providers.util import remove_meilisearch_disallowed_chars
from .chat import SimpleChatStep
class CreateCodebaseIndexChroma(Step):
name: str = "Create Codebase Index"
hide: bool = True
description: str = "Generating codebase embeddings... 1%"
openai_api_key: Optional[str] = Field(None, description="OpenAI API key")
api_base: Optional[str] = Field(None, description="OpenAI API base URL")
api_type: Optional[str] = Field(None, description="OpenAI API type")
api_version: Optional[str] = Field(None, description="OpenAI API version")
organization_id: Optional[str] = Field(None, description="OpenAI organization ID")
ignore_files: List[str] = Field(
[],
description="Files to ignore when indexing the codebase. You can use glob patterns, such as **/*.py. This is useful for directories that contain generated code, or other directories that are not relevant to the codebase.",
)
async def describe(self, models) -> Coroutine[str, None, None]:
return "Generated codebase embeddings."
async def run(self, sdk: ContinueSDK):
index = ChromaCodebaseIndex(
sdk.ide.workspace_directory,
openai_api_key=self.openai_api_key,
api_base=self.api_base,
api_type=self.api_type,
api_version=self.api_version,
organization_id=self.organization_id,
)
if index.exists():
return
yield SetStep(hide=False)
async for progress in index.build(sdk, ignore_files=self.ignore_files):
yield SetStep(
description=f"Generating codebase embeddings... {int(progress*100)}%",
)
class AnswerQuestionChroma(Step):
user_input: str
_answer: Union[str, None] = None
name: str = "Answer Question"
n_retrieve: Optional[int] = Field(
20, description="Number of results to initially retrieve from vector database"
)
n_final: Optional[int] = Field(
10, description="Final number of results to use after re-ranking"
)
use_reranking: bool = Field(
True,
description="Whether to use re-ranking, which will allow initial selection of n_retrieve results, then will use an LLM to select the top n_final results",
)
hide: bool = True
async def describe(self, llm) -> Coroutine[str, None, None]:
if self._answer is None:
return f"Answering the question: {self.user_input}"
else:
return self._answer
async def run(self, sdk: ContinueSDK):
index = ChromaCodebaseIndex(sdk.ide.workspace_directory)
yield SetStep(hide=False, description="Scanning codebase...")
# Get top chunks from index
chunks = index.query(
self.user_input, n=self.n_retrieve if self.use_reranking else self.n_final
)
# Rerank to select top results
yield SetStep(description="Selecting most important files...")
if self.use_reranking:
chunks = await default_reranker_parallel(
chunks, self.user_input, self.n_final, sdk
)
# Add context items
context_items: List[ContextItem] = []
for chunk in chunks:
# Can we select the context item through the normal means so that the name is disambiguated?
# Also so you don't have to understand the internals of the context provider
# OR have a chunk context provider??? Nice short-term, but I don't like it for long-term
ctx_item = ContextItem(
content=chunk.content,
description=ContextItemDescription(
name=f"{os.path.basename(chunk.document_id)} ({chunk.start_line}-{chunk.end_line})",
description=chunk.document_id,
id=ContextItemId(
provider_title="file",
item_id=remove_meilisearch_disallowed_chars(chunk.document_id),
),
),
) # Should be 'code' not file! And eventually should be able to embed all context providers automatically!
context_items.append(ctx_item)
await sdk.add_context_item(ctx_item)
yield SetStep(hide=True)
model = sdk.models.chat.model
# if model == "gpt-4":
# model = "gpt-4-32k" # Not publicly available yet?
if model == "gpt-3.5-turbo":
model = "gpt-3.5-turbo-16k"
await sdk.run_step(
SimpleChatStep(
name="Answer Question",
description=f"Reading from {len(context_items)} files...",
completion_options=CompletionOptions(model=model),
)
)
# for ctx_item in context_items:
# await sdk.delete_context_item(ctx_item.description.id)
class EditFileChroma(Step):
user_input: str
hide: bool = True
async def run(self, sdk: ContinueSDK):
index = ChromaCodebaseIndex(sdk.ide.workspace_directory)
results = index.query_codebase_index(self.user_input)
resource_name = list(results.source_nodes[0].node.relationships.values())[0]
filepath = resource_name[: resource_name.index("::")]
await sdk.run_step(
EditFileStep(
filepath=filepath,
prompt=f"Here is the code:\n\n{{code}}\n\nHere is the user request:\n\n{self.user_input}\n\nHere is the code after making the requested changes:\n",
)
)

View file

@ -0,0 +1,196 @@
import asyncio
import os
from typing import Coroutine, List, Optional, Union
from ...libs.index.hyde import code_hyde, generate_keywords
from ...libs.index.indices.meilisearch_index import MeilisearchCodebaseIndex
from ...libs.llm.base import LLM, CompletionOptions
from ...libs.index.rerankers.single_token import single_token_reranker_parallel
from ...core.main import (
ContextItem,
ContextItemDescription,
ContextItemId,
SetStep,
Step,
)
from ...core.sdk import ContinueSDK
from ...core.steps import EditFileStep
from ...libs.index.indices.chroma_index import ChromaCodebaseIndex
from ...server.meilisearch_server import remove_meilisearch_disallowed_chars
from .chat import SimpleChatStep
PROMPT = """Use the above code to answer the following question. You should not reference any files outside of what is shown, unless they are commonly known files, like a .gitignore or package.json. Reference the filenames whenever possible. If there isn't enough information to answer the question, suggest where the user might look to learn more. Here is the question: '{user_input}'. Response: """
async def get_faster_model(sdk: ContinueSDK) -> Optional[LLM]:
# First, check for GPT-3/3.5
models = sdk.config.models.all_models
if gpt3_model := next(filter(lambda m: "gpt-3" in m.model, models), None):
return gpt3_model
# Then, check for OpenAIFreeTrial
if openai_free_trial_model := next(
filter(lambda m: m.__class__.__name__ == "OpenAIFreeTrial", models), None
):
new_model = openai_free_trial_model.copy()
new_model.model = "gpt-3.5-turbo"
await new_model.start(sdk.ide.window_info.unique_id)
return new_model
# Then, check for an API Key
if openai_model := next(
filter(
lambda m: hasattr(m, "api_key")
and m.api_key is not None
and m.api_key.startswith("sk-"),
models,
),
None,
):
new_model = openai_model.copy()
new_model.model = "gpt-3.5-turbo"
await new_model.start(sdk.ide.window_info.unique_id)
return new_model
# Return None, so re-ranking probably shouldn't happen
return None
class AnswerQuestionChroma(Step):
user_input: str
_answer: Union[str, None] = None
name: str = "Answer Question"
hide: bool = True
async def describe(self, llm) -> Coroutine[str, None, None]:
if self._answer is None:
return f"Answering the question: {self.user_input}"
else:
return self._answer
async def run(self, sdk: ContinueSDK):
settings = sdk.config.retrieval_settings
faster_model = await get_faster_model(sdk)
use_reranking = settings.use_reranking and faster_model is not None
chroma_index = ChromaCodebaseIndex(
sdk.ide.workspace_directory, openai_api_key=settings.openai_api_key
)
meilisearch_index = MeilisearchCodebaseIndex(sdk.ide.workspace_directory)
yield SetStep(hide=False, description="Scanning codebase...")
# Get top chunks from index
to_retrieve_from_each = (
settings.n_retrieve if use_reranking else settings.n_final
) // 2
# Use HyDE only if a faster model is available
query = self.user_input
keywords = None
if faster_model is not None:
resps = await asyncio.gather(
*[
code_hyde(self.user_input, "", faster_model),
generate_keywords(self.user_input, faster_model),
]
)
query = resps[0]
keywords = resps[1]
# Get meilisearch chunks first, fill in the rest with chroma
if keywords is None:
meilisearch_chunks = await meilisearch_index.query(
self.user_input, n=to_retrieve_from_each
)
else:
meilisearch_chunks = await meilisearch_index.query_keywords(
keywords, n=to_retrieve_from_each
)
chroma_chunks = await chroma_index.query(
query, n=2 * to_retrieve_from_each - len(meilisearch_chunks)
)
chunk_ids = set()
chunks = []
for chunk in chroma_chunks + meilisearch_chunks:
if chunk.id not in chunk_ids:
chunk_ids.add(chunk.id)
chunks.append(chunk)
# Rerank to select top results
yield SetStep(description="Selecting most important files...")
if use_reranking:
chunks = await single_token_reranker_parallel(
chunks,
self.user_input,
settings.n_final,
faster_model,
# group_size=settings.rerank_group_size,
)
# Add context items
context_items: List[ContextItem] = []
i = 0
for chunk in chunks:
# Can we select the context item through the normal means so that the name is disambiguated?
# Also so you don't have to understand the internals of the context provider
# OR have a chunk context provider??? Nice short-term, but I don't like it for long-term
ctx_item = ContextItem(
content=chunk.content,
description=ContextItemDescription(
name=f"{os.path.basename(chunk.document_id)} ({chunk.start_line}-{chunk.end_line})",
description=chunk.document_id,
id=ContextItemId(
provider_title="file",
item_id=remove_meilisearch_disallowed_chars(chunk.document_id),
),
),
) # Should be 'code' not file! And eventually should be able to embed all context providers automatically!
context_items.append(ctx_item)
await sdk.add_context_item(ctx_item)
if i < 8:
await asyncio.sleep(0.06)
i += 1
yield SetStep(hide=True)
model = sdk.models.chat.model
# if model == "gpt-4":
# model = "gpt-4-32k" # Not publicly available yet?
if model == "gpt-3.5-turbo":
model = "gpt-3.5-turbo-16k"
await sdk.run_step(
SimpleChatStep(
name="Answer Question",
description=f"Reading from {len(context_items)} files...",
completion_options=CompletionOptions(model=model),
prompt=PROMPT.format(user_input=self.user_input),
)
)
# for ctx_item in context_items:
# await sdk.delete_context_item(ctx_item.description.id)
class EditFileChroma(Step):
user_input: str
hide: bool = True
async def run(self, sdk: ContinueSDK):
index = ChromaCodebaseIndex(sdk.ide.workspace_directory)
results = index.query_codebase_index(self.user_input)
resource_name = list(results.source_nodes[0].node.relationships.values())[0]
filepath = resource_name[: resource_name.index("::")]
await sdk.run_step(
EditFileStep(
filepath=filepath,
prompt=f"Here is the code:\n\n{{code}}\n\nHere is the user request:\n\n{self.user_input}\n\nHere is the code after making the requested changes:\n",
)
)

View file

@ -4,5 +4,7 @@ from pydantic import BaseModel
class GlobalConfig(BaseModel):
meilisearch_url: Optional[str] = None
disable_meilisearch: bool = False
global_config = GlobalConfig()
global_config = GlobalConfig()

View file

@ -77,12 +77,29 @@ def health():
# endregion
async def cleanup_coroutine():
logger.debug("------ End logs ------")
def cleanup():
loop = asyncio.new_event_loop()
loop.run_until_complete(cleanup_coroutine())
loop.close()
def run_server(
port: int = 65432, host: str = "127.0.0.1", meilisearch_url: Optional[str] = None
port: int = 65432,
host: str = "127.0.0.1",
meilisearch_url: Optional[str] = None,
disable_meilisearch: bool = False,
):
try:
global global_config
global_config.meilisearch_url = meilisearch_url
global_config.disable_meilisearch = disable_meilisearch
logger.debug("------ Begin Logs ------")
atexit.register(cleanup)
config = uvicorn.Config(app, host=host, port=port)
server = uvicorn.Server(config)
@ -101,18 +118,6 @@ def run_server(
raise e
async def cleanup_coroutine():
logger.debug("------ End logs ------")
def cleanup():
loop = asyncio.new_event_loop()
loop.run_until_complete(cleanup_coroutine())
loop.close()
atexit.register(cleanup)
if __name__ == "__main__":
try:
# add cli arg for server port

View file

@ -1,6 +1,7 @@
import asyncio
import os
import shutil
import re
import subprocess
from typing import Optional
@ -82,7 +83,10 @@ async def ensure_meilisearch_installed() -> bool:
pass
existing_paths.remove(meilisearchPath)
await download_meilisearch()
try:
await asyncio.wait_for(download_meilisearch(), timeout=60)
except asyncio.TimeoutError:
logger.critical("Timed out trying to download MeiliSearch")
# Clear the existing directories
for p in existing_paths:
@ -141,6 +145,10 @@ async def start_meilisearch(url: Optional[str] = None):
meilisearch_url = url
return
if global_config.disable_meilisearch:
logger.debug("MeiliSearch disabled")
return
serverPath = getServerFolderPath()
# Check if MeiliSearch is installed, if not download
@ -195,3 +203,7 @@ async def restart_meilisearch():
stop_meilisearch()
kill_proc(7700)
await start_meilisearch(url=global_config.meilisearch_url)
def remove_meilisearch_disallowed_chars(id: str) -> str:
return re.sub(r"[^0-9a-zA-Z_-]", "", id)

View file

@ -0,0 +1,10 @@
from ...core.main import SessionUpdate
class CommandLineGUI:
async def send_session_update(self, session_update: SessionUpdate):
if hasattr(session_update.update, "description"):
print(session_update.update.description)
async def send_indexing_progress(self, progress: float):
print(f"Indexing... {int(progress*100)}%")

View file

@ -310,6 +310,9 @@ class GUIProtocolServer:
async def send_session_update(self, session_update: SessionUpdate):
await self.messenger.send("session_update", session_update.dict())
async def send_indexing_progress(self, progress: float):
await self.messenger.send("indexing_progress", {"progress": progress})
async def get_session_state(self) -> SessionState:
return await self.messenger.send_and_receive(
{}, SessionState, "get_session_state"

View file

@ -1,6 +1,10 @@
import traceback
from typing import Dict, Optional
from ..libs.util.create_async_task import create_async_task
from ..libs.index.build_index import build_index
from ..plugins.steps.on_traceback import DefaultOnTracebackStep
from ..core.context import ContextManager
@ -89,6 +93,12 @@ class Window:
if self._error_loading_config is not None:
await self.ide.setFileOpen(getConfigFilePath())
async def index():
async for progress in build_index(self.ide, self.config):
await self.gui.send_indexing_progress(progress)
create_async_task(index(), on_error=self.ide.on_error)
# Start models
await self.config.models.start(
self.ide.window_info.unique_id,

2707
server/poetry.lock generated

File diff suppressed because it is too large Load diff

View file

@ -37,7 +37,10 @@ chromadb = "^0.4.12"
fastapi = "0.95.2"
tree-sitter = "^0.20.2"
tree-sitter-languages = "^1.7.0"
rich = "^13.6.0"
python-socketio = "^5.10.0"
pathspec = "^0.11.2"
tqdm = "^4.66.1"
[tool.poetry.scripts]
typegen = "continuedev.models.generate_json_schema:main"
@ -45,6 +48,7 @@ typegen = "continuedev.models.generate_json_schema:main"
[tool.poetry.group.dev.dependencies]
pytest = "^7.4.1"
pytest-asyncio = "^0.21.1"
ipykernel = "^6.26.0"
[build-system]
requires = ["poetry-core"]