Elffuss BraidHub

kikocis/continue public

99fe51849b68 · 5.2 KiBRawPermalink
1import { Position } from "../..";
2import { ContextRetrievalService } from "../../autocomplete/context/ContextRetrievalService";
3import { getAllSnippetsWithoutRace } from "../../autocomplete/snippets/getAllSnippets";
4import { AutocompleteCodeSnippet } from "../../autocomplete/snippets/types";
5import { renderPrompt } from "../../autocomplete/templating";
6import { GetLspDefinitionsFunction } from "../../autocomplete/types";
7import { HelperVars } from "../../autocomplete/util/HelperVars";
8import {
9 AutocompleteInput,
10 RecentlyEditedRange,
11} from "../../autocomplete/util/types";
12import { ConfigHandler } from "../../config/ConfigHandler";
13import { IDE, ILLM } from "../../index";
14import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../util/parameters";
15
16/**
17 * Gets the formatted autocomplete context string that would be used for autocomplete at the given position.
18 * This function mimics the context generation pipeline from the autocomplete system without triggering
19 * an actual completion.
20 *
21 * @param filepath - The file path where context is being requested
22 * @param pos - The position in the file where context is being requested
23 * @param ide - The IDE interface for file system operations
24 * @param configHandler - The config handler to load user configuration
25 * @param getDefinitionsFromLsp - Function to get LSP definitions (can be a no-op function if not needed)
26 * @param autocompleteModel - Optional autocomplete model to use (if not provided, uses configured autocomplete model)
27 * @param recentlyEditedRanges - Recently edited ranges (defaults to empty array)
28 * @param recentlyVisitedRanges - Recently visited ranges (if not provided, will fetch current live data like real autocomplete)
29 * @param maxPromptTokens - Optional override for maximum number of tokens (if not provided, uses config)
30 * @param manuallyPassFileContents - Optional file contents to use instead of reading from disk (should match current editor state)
31 * @returns Promise that resolves to the formatted context string
32 */
33export const getAutocompleteContext = async (
34 filepath: string,
35 pos: Position,
36 ide: IDE,
37 configHandler: ConfigHandler,
38 getDefinitionsFromLsp: GetLspDefinitionsFunction = async () => [],
39 recentlyEditedRanges: RecentlyEditedRange[],
40 recentlyVisitedRanges: AutocompleteCodeSnippet[],
41 maxPromptTokens: number,
42 manuallyPassFileContents: string,
43 autocompleteModel?: ILLM | string,
44 // eslint-disable-next-line max-params
45): Promise<string> => {
46 if (!recentlyEditedRanges) recentlyEditedRanges = [];
47 if (!recentlyVisitedRanges) recentlyVisitedRanges = [];
48
49 const input: AutocompleteInput = {
50 isUntitledFile: false,
51 completionId: `context-fetch-${Date.now()}`,
52 filepath,
53 pos,
54 recentlyVisitedRanges,
55 recentlyEditedRanges,
56 manuallyPassFileContents,
57 };
58
59 const { config } = await configHandler.loadConfig();
60 if (!config) {
61 throw new Error("No config available");
62 }
63
64 // Use provided autocomplete model or fall back to configured autocomplete model
65 let finalModel: ILLM;
66 let modelNameForTemplating: string;
67
68 if (autocompleteModel) {
69 if (typeof autocompleteModel === "string") {
70 // Try to find the model in config first
71 const foundModel = config.modelsByRole.autocomplete.find(
72 (m) => m.title === autocompleteModel,
73 );
74 if (foundModel) {
75 finalModel = foundModel;
76 modelNameForTemplating = foundModel.model;
77 } else {
78 // Model not found in config, but we can still use it for template selection
79 const configuredModel = config.selectedModelByRole.autocomplete;
80 if (!configuredModel) {
81 throw new Error(
82 "No autocomplete model configured and provided model not found in config",
83 );
84 }
85 finalModel = configuredModel;
86 modelNameForTemplating = autocompleteModel; // Use the provided string for template selection
87 }
88 } else {
89 finalModel = autocompleteModel;
90 modelNameForTemplating = autocompleteModel.model;
91 }
92 } else {
93 const configuredModel = config.selectedModelByRole.autocomplete;
94 if (!configuredModel) {
95 throw new Error("No autocomplete model configured and no model provided");
96 }
97 finalModel = configuredModel;
98 modelNameForTemplating = configuredModel.model;
99 }
100
101 const options = {
102 ...DEFAULT_AUTOCOMPLETE_OPTS,
103 ...config.tabAutocompleteOptions,
104 ...finalModel.autocompleteOptions,
105 ...(maxPromptTokens && { maxPromptTokens }),
106 };
107
108 if (finalModel.promptTemplates?.autocomplete) {
109 options.template = finalModel.promptTemplates.autocomplete as string;
110 }
111
112 const helper = await HelperVars.create(
113 input,
114 options,
115 modelNameForTemplating,
116 ide,
117 );
118
119 const contextRetrievalService = new ContextRetrievalService(ide);
120
121 await contextRetrievalService.initializeForFile(filepath);
122
123 const [snippetPayload, workspaceDirs] = await Promise.all([
124 getAllSnippetsWithoutRace({
125 helper,
126 ide: ide,
127 getDefinitionsFromLsp: getDefinitionsFromLsp,
128 contextRetrievalService: contextRetrievalService,
129 }),
130 ide.getWorkspaceDirs(),
131 ]);
132
133 const { prompt, prefix, suffix, completionOptions } = renderPrompt({
134 snippetPayload,
135 workspaceDirs,
136 helper,
137 });
138
139 return prefix;
140};