🚧 minisearch as alternative to meilisearch

This commit is contained in:
Nate Sesti 2023-12-10 23:29:49 -08:00
parent 40338cd45d
commit 7c045bfe2d
8 changed files with 198 additions and 133 deletions

View file

@ -6,6 +6,7 @@ import {
} from "../commands";
import { ContextProvider } from "../context";
import { contextProviderClassFromName } from "../context/providers";
import FileContextProvider from "../context/providers/FileContextProvider";
import { LLM } from "../llm";
import { llmFromDescription } from "../llm/llms";
@ -30,7 +31,7 @@ function loadSerializedConfig(
slashCommands.push(slashFromCustomCommand(command));
}
const contextProviders: ContextProvider[] = [];
const contextProviders: ContextProvider[] = [new FileContextProvider({})];
for (const provider of initial.contextProviders || []) {
const cls = contextProviderClassFromName(provider.name) as any;
if (!cls) {

View file

@ -0,0 +1,33 @@
import { ContextProvider, ContextProviderDescription } from "..";
import { ExtensionIde } from "../../ide";
import { ContextItem } from "../../llm/types";
class FileContextProvider extends ContextProvider {
static description: ContextProviderDescription = {
title: "file",
displayTitle: "Files",
description: "Type to search",
dynamic: false,
requiresQuery: false,
};
async getContextItems(query: string): Promise<ContextItem[]> {
// Assume the query is a filepath
query = query.trim();
const content = await new ExtensionIde().readFile(query);
return [
{
name: query.split(/[\\/]/).pop() || query,
description: query,
content,
id: {
providerTitle: FileContextProvider.description.title,
itemId: query,
},
},
];
}
async load(): Promise<void> {}
}
export default FileContextProvider;

View file

@ -1,7 +1,7 @@
import { LLM, LLMOptions } from "..";
import { ModelProvider } from "../../config";
import OpenAIClient from "openai";
import { ChatCompletionCreateParamsBase } from "openai/resources/chat/completions";
import { LLM, LLMOptions } from "..";
import { ModelProvider } from "../../config";
import { ChatMessage, CompletionOptions } from "../types";
class OpenAI extends LLM {
static providerName: ModelProvider = "openai";

View file

@ -1,96 +1,96 @@
import * as dotenv from "dotenv";
import { LLM } from "..";
import Together from "../llms/Together";
import { CompletionOptions } from "../types";
// import * as dotenv from "dotenv";
// import { LLM } from "..";
// import Together from "../llms/Together";
// import { CompletionOptions } from "../types";
jest.setTimeout(100_000);
// jest.setTimeout(100_000);
dotenv.config();
// dotenv.config();
const COMPLETION_OPTIONS: Partial<CompletionOptions> = {
temperature: 0.5,
topP: 1,
topK: 40,
presencePenalty: 0,
frequencyPenalty: 0,
// stop: ["\n"],
// maxTokens: 5,
};
// const COMPLETION_OPTIONS: Partial<CompletionOptions> = {
// temperature: 0.5,
// topP: 1,
// topK: 40,
// presencePenalty: 0,
// frequencyPenalty: 0,
// // stop: ["\n"],
// // maxTokens: 5,
// };
function testLLM(llm: LLM) {
beforeAll(() => {
llm.completionOptions = { ...llm.completionOptions, ...COMPLETION_OPTIONS };
});
// function testLLM(llm: LLM) {
// beforeAll(() => {
// llm.completionOptions = { ...llm.completionOptions, ...COMPLETION_OPTIONS };
// });
describe(llm.providerName, () => {
test("Stream Chat works", async () => {
let total = "";
for await (const chunk of llm.streamChat([
{ role: "user", content: "Hello" },
])) {
total += chunk.content;
}
// describe(llm.providerName, () => {
// test("Stream Chat works", async () => {
// let total = "";
// for await (const chunk of llm.streamChat([
// { role: "user", content: "Hello" },
// ])) {
// total += chunk.content;
// }
expect(total.length).toBeGreaterThan(0);
console.log(total);
return;
});
// expect(total.length).toBeGreaterThan(0);
// console.log(total);
// return;
// });
test("Stream Complete works", async () => {
let total = "";
for await (const chunk of llm.streamComplete("Hello")) {
total += chunk;
}
// test("Stream Complete works", async () => {
// let total = "";
// for await (const chunk of llm.streamComplete("Hello")) {
// total += chunk;
// }
expect(total.length).toBeGreaterThan(0);
console.log(total);
return;
});
// expect(total.length).toBeGreaterThan(0);
// console.log(total);
// return;
// });
test("Complete works", async () => {
const completion = await llm.complete("Hello");
// test("Complete works", async () => {
// const completion = await llm.complete("Hello");
expect(completion.length).toBeGreaterThan(0);
console.log(completion);
return;
});
});
}
// expect(completion.length).toBeGreaterThan(0);
// console.log(completion);
// return;
// });
// });
// }
describe("LLM", () => {
// testLLM(
// new FreeTrial({
// model: "gpt-3.5-turbo",
// })
// );
// testLLM(
// new Anthropic({
// model: "claude-2",
// apiKey: process.env.ANTHROPIC_API_KEY,
// })
// );
// testLLM(
// new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "gpt-3.5-turbo" })
// );
// TODO: Fix Replicate
// testLLM(
// new Replicate({
// apiKey: process.env.REPLICATE_API_KEY,
// model: "codellama-7b",
// })
// );
// testLLM(new LMStudio({ model: "codellama-7b" }));
// testLLM(new Ollama({ model: "codellama-7b" }));
testLLM(
new Together({
apiKey: process.env.TOGETHER_API_KEY,
model: "codellama-7b",
})
);
// testLLM(new LlamaCpp({ model: "deepseek-7b" }));
// testLLM(new Llamafile({ model: "mistral-7b" }));
// TODO: Test these
// testLLM(new TextGenWebUI({ model: "codellama-7b" }));
// testLLM(new HuggingFaceTGI({ model: "codellama-7b" }));
// testLLM(new HuggingFaceInferenceAPI({ model: "codellama-7b" }));
});
// describe("LLM", () => {
// // testLLM(
// // new FreeTrial({
// // model: "gpt-3.5-turbo",
// // })
// // );
// // testLLM(
// // new Anthropic({
// // model: "claude-2",
// // apiKey: process.env.ANTHROPIC_API_KEY,
// // })
// // );
// // testLLM(
// // new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "gpt-3.5-turbo" })
// // );
// // TODO: Fix Replicate
// // testLLM(
// // new Replicate({
// // apiKey: process.env.REPLICATE_API_KEY,
// // model: "codellama-7b",
// // })
// // );
// // testLLM(new LMStudio({ model: "codellama-7b" }));
// // testLLM(new Ollama({ model: "codellama-7b" }));
// testLLM(
// new Together({
// apiKey: process.env.TOGETHER_API_KEY,
// model: "codellama-7b",
// })
// );
// // testLLM(new LlamaCpp({ model: "deepseek-7b" }));
// // testLLM(new Llamafile({ model: "mistral-7b" }));
// // TODO: Test these
// // testLLM(new TextGenWebUI({ model: "codellama-7b" }));
// // testLLM(new HuggingFaceTGI({ model: "codellama-7b" }));
// // testLLM(new HuggingFaceInferenceAPI({ model: "codellama-7b" }));
// });

11
gui/package-lock.json generated
View file

@ -19,6 +19,7 @@
"downshift": "^7.6.0",
"lodash": "^4.17.21",
"meilisearch": "^0.33.0",
"minisearch": "^6.3.0",
"node-fetch": "^3.3.2",
"posthog-js": "^1.58.0",
"prismjs": "^1.29.0",
@ -3618,6 +3619,11 @@
"node": "*"
}
},
"node_modules/minisearch": {
"version": "6.3.0",
"resolved": "https://registry.npmjs.org/minisearch/-/minisearch-6.3.0.tgz",
"integrity": "sha512-ihFnidEeU8iXzcVHy74dhkxh/dn8Dc08ERl0xwoMMGqp4+LvRSCgicb+zGqWthVokQKvCSxITlh3P08OzdTYCQ=="
},
"node_modules/monaco-editor": {
"version": "0.44.0",
"resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.44.0.tgz",
@ -7708,6 +7714,11 @@
"brace-expansion": "^1.1.7"
}
},
"minisearch": {
"version": "6.3.0",
"resolved": "https://registry.npmjs.org/minisearch/-/minisearch-6.3.0.tgz",
"integrity": "sha512-ihFnidEeU8iXzcVHy74dhkxh/dn8Dc08ERl0xwoMMGqp4+LvRSCgicb+zGqWthVokQKvCSxITlh3P08OzdTYCQ=="
},
"monaco-editor": {
"version": "0.44.0",
"resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.44.0.tgz",

View file

@ -20,6 +20,7 @@
"downshift": "^7.6.0",
"lodash": "^4.17.21",
"meilisearch": "^0.33.0",
"minisearch": "^6.3.0",
"node-fetch": "^3.3.2",
"posthog-js": "^1.58.0",
"prismjs": "^1.29.0",

View file

@ -1,17 +1,20 @@
import GUI from "./pages/gui";
import History from "./pages/history";
import Help from "./pages/help";
import Layout from "./components/Layout";
import { createContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { RouterProvider, createMemoryRouter } from "react-router-dom";
import ErrorPage from "./pages/error";
import SettingsPage from "./pages/settings";
import Models from "./pages/models";
import HelpPage from "./pages/help";
import ModelConfig from "./pages/modelconfig";
import Layout from "./components/Layout";
import useSetup from "./hooks/useSetup";
import MonacoPage from "./pages/monaco";
import ErrorPage from "./pages/error";
import GUI from "./pages/gui";
import { default as Help, default as HelpPage } from "./pages/help";
import History from "./pages/history";
import MigrationPage from "./pages/migration";
import ModelConfig from "./pages/modelconfig";
import Models from "./pages/models";
import MonacoPage from "./pages/monaco";
import SettingsPage from "./pages/settings";
import { ExtensionIde } from "core/ide";
import MiniSearch from "minisearch";
const router = createMemoryRouter([
{
@ -63,12 +66,43 @@ const router = createMemoryRouter([
},
]);
const miniSearch = new MiniSearch({
fields: ["id", "basename"],
storeFields: ["id", "basename"],
});
export const SearchContext = createContext<[MiniSearch, MiniSearchResult[]]>([
miniSearch,
[],
]);
export interface MiniSearchResult {
id: string;
basename: string;
}
function App() {
const dispatch = useDispatch();
useSetup(dispatch);
return <RouterProvider router={router} />;
const [firstResults, setFirstResults] = useState<MiniSearchResult[]>([]);
useEffect(() => {
(async () => {
const files = await new ExtensionIde().listWorkspaceContents();
const results = files.map((filepath) => {
return { id: filepath, basename: filepath.split(/[\\/]/).pop() };
});
miniSearch.addAll(results);
setFirstResults(results);
})();
}, []);
return (
<SearchContext.Provider value={[miniSearch, firstResults]}>
<RouterProvider router={router} />;
</SearchContext.Provider>
);
}
export default App;

View file

@ -21,9 +21,9 @@ import {
} from "@heroicons/react/24/outline";
import { ContextItem } from "core/llm/types";
import { useCombobox } from "downshift";
import { MeiliSearch } from "meilisearch";
import React, {
useCallback,
useContext,
useEffect,
useImperativeHandle,
useLayoutEffect,
@ -39,6 +39,7 @@ import {
vscBackground,
vscForeground,
} from "..";
import { SearchContext } from "../../App";
import useContextProviders from "../../hooks/useContextProviders";
import useHistory from "../../hooks/useHistory";
import { contextLengthSelector } from "../../redux/selectors/modelSelectors";
@ -372,21 +373,7 @@ interface ComboBoxProps {
}
const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
const meilisearchUrl = useSelector(
(state: RootStore) =>
state.serverState.meilisearchUrl || "http://127.0.0.1:7700"
);
const [searchClient, setSearchClient] = useState<MeiliSearch | undefined>(
undefined
);
useEffect(() => {
const client = new MeiliSearch({
host: meilisearchUrl,
});
setSearchClient(client);
}, [meilisearchUrl]);
const [miniSearch, firstResults] = useContext(SearchContext);
const dispatch = useDispatch();
const workspacePaths = (window as any).workspacePaths || [];
@ -597,25 +584,23 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
provider: string,
query: string
) => {
// Only return context items from the current workspace - the index is currently shared between all sessions
const workspaceFilter =
workspacePaths && workspacePaths.length > 0
? `workspace_dir IN [ ${workspacePaths
.map((path) => `"${path}"`)
.join(", ")} ] AND provider_name = '${provider}'`
: undefined;
try {
const res = await searchClient?.index(SEARCH_INDEX_NAME).search(query, {
filter: workspaceFilter,
let res: any = miniSearch.search(query.trim() === "" ? "/" : query, {
prefix: true,
fuzzy: 3,
});
if (res.length === 0) {
res = firstResults;
}
return (
res?.hits.map((hit) => {
return {
title: hit.name,
description: hit.description,
res?.map((hit) => {
const item: ComboBoxItem = {
title: hit.basename,
description: hit.basename,
id: hit.id,
content: hit.content,
content: hit.id,
};
return item;
}) || []
);
} catch (e) {
@ -784,7 +769,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
if (!newProvider) {
if (nestedContextProvider && newItem.id) {
// Tell server the context item was selected
selectContextItem(newItem.id, "");
selectContextItem("file", newItem.id);
// Clear the input
downshiftProps.setInputValue("");
@ -828,7 +813,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
!selectedNestedContextProvider?.description.dynamic
) {
downshiftProps.setInputValue(`@${newItem.id} `);
setNestedContextProvider(selectedNestedContextProvider);
setNestedContextProvider(selectedNestedContextProvider.description);
} else {
downshiftProps.setInputValue("");
}
@ -844,7 +829,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
return;
}
setNestedContextProvider(newProvider);
setNestedContextProvider(newProvider.description);
downshiftProps.setInputValue(`@${newProvider.description.title} `);
(event.nativeEvent as any).preventDownshiftDefault = true;
event.preventDefault();
@ -1569,7 +1554,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
inputRef.current?.focus();
}}
/>
{nestedContextProvider.display_title} -{" "}
{nestedContextProvider.displayTitle} -{" "}
{nestedContextProvider.description}
</div>
)}