Merge pull request #6434 from tingwai/tingwai/at-codebase-experimental-call-tools

@codebase use tool calling (under experimental flag)
This commit is contained in:
Nate Sesti 2025-07-03 18:05:12 -07:00 • committed by GitHub
commit de8db5cdcb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 250 additions and 30 deletions

View file

@ -22,6 +22,7 @@ export const sharedConfigSchema = z
logEditingData: z.boolean(),
optInNextEditFeature: z.boolean(),
enableExperimentalTools: z.boolean(),
codebaseToolCallingOnly: z.boolean(),
// `ui` in `ContinueConfig`
showSessionTabs: z.boolean(),
@ -187,6 +188,10 @@ export function modifyAnyConfigWithSharedConfig<
configCopy.experimental.optInNextEditFeature =
sharedConfig.optInNextEditFeature;
}
if (sharedConfig.codebaseToolCallingOnly !== undefined) {
configCopy.experimental.codebaseToolCallingOnly =
sharedConfig.codebaseToolCallingOnly;
}
return configCopy;
}

View file

@ -1,14 +1,40 @@
// @ts-ignore
import nlp from "wink-nlp-utils";
import { BranchAndDir, Chunk, ContinueConfig, IDE, ILLM } from "../../../";
import {
BranchAndDir,
Chunk,
ContextItem,
ContinueConfig,
IDE,
ILLM,
Tool,
ToolExtras,
} from "../../../";
import { openedFilesLruCache } from "../../../autocomplete/util/openedFilesLruCache";
import { chunkDocument } from "../../../indexing/chunk/chunk";
import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCodebaseIndex";
import { LanceDbIndex } from "../../../indexing/LanceDbIndex";
import { BuiltInToolNames } from "../../../tools/builtIn";
import { callBuiltInTool } from "../../../tools/callTool";
import { globSearchTool } from "../../../tools/definitions/globSearch";
import { grepSearchTool } from "../../../tools/definitions/grepSearch";
import { lsTool } from "../../../tools/definitions/lsTool";
import { readFileTool } from "../../../tools/definitions/readFile";
import { viewRepoMapTool } from "../../../tools/definitions/viewRepoMap";
import { viewSubdirectoryTool } from "../../../tools/definitions/viewSubdirectory";
const DEFAULT_CHUNK_SIZE = 384;
const AVAILABLE_TOOLS: Tool[] = [
globSearchTool,
grepSearchTool,
lsTool,
readFileTool,
viewRepoMapTool,
viewSubdirectoryTool,
];
export interface RetrievalPipelineOptions {
llm: ILLM;
config: ContinueConfig;
@ -155,4 +181,105 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
run(args: RetrievalPipelineRunArguments): Promise<Chunk[]> {
throw new Error("Not implemented");
}
protected async retrieveWithTools(input: string): Promise<Chunk[]> {
const toolSelectionPrompt = `Given the following user input: "${input}"
Available tools:
${AVAILABLE_TOOLS.map((tool) => {
const requiredParams = tool.function.parameters?.required || [];
const properties = tool.function.parameters?.properties || {};
const paramDescriptions = requiredParams
.map(
(param: any) => `${param}: ${properties[param]?.description || "string"}`,
)
.join(", ");
return `- ${tool.function.name}: ${tool.function.description}
Required arguments: ${paramDescriptions || "none"}`;
}).join("\n")}
Determine which tools should be used to answer this query. You should feel free to use multiple tools when they would be helpful for comprehensive results. Respond ONLY a JSON object containing the following and nothing else:
{
"tools": [
{
"name": "<tool_name>",
"args": { "<required_parameter_name>": "<required_parameter_value>" }
}
]
}`;
// Get LLM response for tool selection
const toolSelectionResponse = await this.options.llm.chat(
[{ role: "user", content: toolSelectionPrompt }],
new AbortController().signal,
);
let toolCalls: { name: string; args: any }[] = [];
try {
const responseContent =
typeof toolSelectionResponse.content === "string"
? toolSelectionResponse.content
: toolSelectionResponse.content
.map((part) => (part.type === "text" ? part.text : ""))
.join("");
const parsed = JSON.parse(responseContent);
toolCalls = parsed.tools || [];
console.log("retrieveWithTools", toolCalls);
} catch (e) {
console.log("Failed to parse tool selection response", e);
return [];
}
// Execute tools and collect results
const allContextItems: ContextItem[] = [];
const toolExtras: ToolExtras = {
ide: this.options.ide,
llm: this.options.llm,
fetch: fetch,
tool: grepSearchTool,
config: this.options.config,
};
for (const toolCall of toolCalls) {
const tool = AVAILABLE_TOOLS.find(
(t) => t.function.name === toolCall.name,
)!;
const args = toolCall.args;
if (toolCall.name === BuiltInToolNames.GrepSearch) {
args.splitByFile = true;
}
toolExtras.tool = tool;
const contextItems = await callBuiltInTool(
toolCall.name,
args,
toolExtras,
);
allContextItems.push(...contextItems);
}
const chunks: Chunk[] = [];
// Transform ContextItem[] to Chunk[]
for (let i = 0; i < allContextItems.length; i++) {
const contextItem = allContextItems[i];
const filepath = contextItem.uri?.value || contextItem.name || "unknown";
const cleanedFilepath = filepath.replace(/^file:\/\/\//, "");
chunks.push({
content: contextItem.content,
startLine: -1,
endLine: -1,
digest: `file:///${cleanedFilepath}`,
filepath: `file:///${cleanedFilepath}`,
index: i,
});
}
console.log("retrieveWithTools chunks", chunks);
return chunks;
}
}

View file

@ -64,12 +64,22 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
console.error("Error retrieving repo map chunks:", error);
}
retrievalResults.push(
...recentlyEditedFilesChunks,
...ftsChunks,
...embeddingsChunks,
...repoMapChunks,
);
if (this.options.config.experimental?.codebaseToolCallingOnly) {
let toolBasedChunks: Chunk[] = [];
try {
toolBasedChunks = await this.retrieveWithTools(input);
} catch (error) {
console.error("Error retrieving tool based chunks:", error);
}
retrievalResults.push(...toolBasedChunks);
} else {
retrievalResults.push(
...recentlyEditedFilesChunks,
...ftsChunks,
...embeddingsChunks,
...repoMapChunks,
);
}
if (filterDirectory) {
// Backup if the individual retrieval methods don't listen

View file

@ -58,12 +58,22 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
console.error("Error retrieving repo map chunks:", error);
}
retrievalResults.push(
...recentlyEditedFilesChunks,
...ftsChunks,
...embeddingsChunks,
...repoMapChunks,
);
if (config.experimental?.codebaseToolCallingOnly) {
let toolBasedChunks: Chunk[] = [];
try {
toolBasedChunks = await this.retrieveWithTools(input);
} catch (error) {
console.error("Error retrieving tool based chunks:", error);
}
retrievalResults.push(...toolBasedChunks);
} else {
retrievalResults.push(
...recentlyEditedFilesChunks,
...ftsChunks,
...embeddingsChunks,
...repoMapChunks,
);
}
if (filterDirectory) {
// Backup if the individual retrieval methods don't listen

View file

@ -108,7 +108,11 @@ export async function retrieveContextItemsFromEmbeddings(
}
return {
name: `${baseName} (${r.startLine + 1}-${r.endLine + 1})`,
// Don't show line numbers for tool calls where startLine = -1
name:
r.startLine === -1
? baseName
: `${baseName} (${r.startLine + 1}-${r.endLine + 1})`,
description: last2Parts,
content: `\`\`\`${relativePathOrBasename}\n${r.content}\n\`\`\``,
uri: {

View file

@ -45,7 +45,6 @@ import {
RangeInFile,
ToolCall,
type ContextItem,
type ContextItemId,
type IDE,
} from ".";
@ -1101,11 +1100,6 @@ export class Core {
}
try {
const id: ContextItemId = {
providerTitle: provider.description.title,
itemId: uuidv4(),
};
void Telemetry.capture("context_provider_get_context_items", {
name: provider.description.title,
});
@ -1132,7 +1126,10 @@ export class Core {
return items.map((item) => ({
...item,
id,
id: {
providerTitle: provider.description.title,
itemId: item.uri?.value ?? uuidv4(),
},
}));
} catch (e) {
let knownError = false;

6
core/index.d.ts vendored
View file

@ -1422,6 +1422,12 @@ export interface ExperimentalConfig {
* If enabled, will enable next edit in place of autocomplete
*/
optInNextEditFeature?: boolean;
/**
* If enabled, @codebase will only use tool calling
* instead of embeddings, FTS, recently edited files, etc.
*/
codebaseToolCallingOnly?: boolean;
}
export interface AnalyticsConfig {

View file

@ -16,6 +16,8 @@ import { requestRuleImpl } from "./implementations/requestRule";
import { runTerminalCommandImpl } from "./implementations/runTerminalCommand";
import { searchWebImpl } from "./implementations/searchWeb";
import { viewDiffImpl } from "./implementations/viewDiff";
import { viewRepoMapImpl } from "./implementations/viewRepoMap";
import { viewSubdirectoryImpl } from "./implementations/viewSubdirectory";
import { safeParseToolCallArgs } from "./parseArgs";
async function callHttpTool(
@ -135,7 +137,7 @@ async function callToolFromUri(
}
}
async function callBuiltInTool(
export async function callBuiltInTool(
functionName: string,
args: any,
extras: ToolExtras,
@ -167,6 +169,10 @@ async function callBuiltInTool(
return await requestRuleImpl(args, extras);
case BuiltInToolNames.CodebaseTool:
return await codebaseToolImpl(args, extras);
case BuiltInToolNames.ViewRepoMap:
return await viewRepoMapImpl(args, extras);
case BuiltInToolNames.ViewSubdirectory:
return await viewSubdirectoryImpl(args, extras);
default:
throw new Error(`Tool "${functionName}" not found`);
}

View file

@ -13,7 +13,7 @@ export const globSearchTool: Tool = {
function: {
name: BuiltInToolNames.FileGlobSearch,
description:
"Search for files in the project. Output may be truncated; use targeted patterns",
"Search for files recursively in the project using glob patterns. Supports ** for recursive directory search. Output may be truncated; use targeted patterns",
parameters: {
type: "object",
required: ["pattern"],

View file

@ -5,6 +5,41 @@ import { formatGrepSearchResults } from "../../util/grepSearch";
const DEFAULT_GREP_SEARCH_RESULTS_LIMIT = 100;
const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 5000; // ~1000 tokens, will keep truncation simply for now
function splitGrepResultsByFile(content: string): ContextItem[] {
const matches = [...content.matchAll(/^\.\/([^\n]+)$/gm)];
if (matches.length === 0) {
return [];
}
const contextItems: ContextItem[] = [];
for (let i = 0; i < matches.length; i++) {
const match = matches[i];
const filepath = match[1];
const startIndex = match.index!;
const endIndex =
i < matches.length - 1 ? matches[i + 1].index! : content.length;
// Extract grepped content for this file
const fileContent = content
.substring(startIndex, endIndex)
.replace(/^\.\/[^\n]+\n/, "") // remove the line with file path
.trim();
if (fileContent) {
contextItems.push({
name: `Search results in ${filepath}`,
description: `Grep search results from ${filepath}`,
content: fileContent,
uri: { type: "file", value: filepath },
});
}
}
return contextItems;
}
export const grepSearchImpl: ToolImpl = async (args, extras) => {
const results = await extras.ide.getSearchResults(
args.query,
@ -26,13 +61,21 @@ export const grepSearchImpl: ToolImpl = async (args, extras) => {
);
}
const contextItems: ContextItem[] = [
{
name: "Search results",
description: "Results from grep search",
content: formatted,
},
];
let contextItems: ContextItem[] = [];
const splitByFile: boolean = args.splitByFile || false;
if (splitByFile) {
contextItems = splitGrepResultsByFile(formatted);
} else {
contextItems = [
{
name: "Search results",
description: "Results from grep search",
content: formatted,
},
];
}
if (truncationReasons.length > 0) {
contextItems.push({
name: "Search truncation warning",

View file

@ -95,6 +95,8 @@ export function UserSettingsForm() {
config.experimental?.enableExperimentalTools ?? false;
const optInNextEditFeature =
config.experimental?.optInNextEditFeature ?? false;
const codebaseToolCallingOnly =
config.experimental?.codebaseToolCallingOnly ?? false;
const allowAnonymousTelemetry = config.allowAnonymousTelemetry ?? true;
const disableIndexing = config.disableIndexing ?? false;
@ -422,6 +424,16 @@ export function UserSettingsForm() {
text="Enable experimental tools"
/>
<ToggleSwitch
isToggled={codebaseToolCallingOnly}
onToggle={() =>
handleUpdate({
codebaseToolCallingOnly: !codebaseToolCallingOnly,
})
}
text="@Codebase: use tool calling only"
/>
{hasContinueEmail && (
<ContinueFeaturesMenu
logEditingData={logEditingData}