implement read file output limits

This commit is contained in:
Dallin Romney 2025-07-03 15:43:58 -07:00
parent 7f756d7590
commit 03fc5f51e4
3 changed files with 56 additions and 17 deletions

View file

@ -1,28 +1,41 @@
import { getUriDescription } from "../../util/uri";
import { ToolImpl } from ".";
import { throwIfFileExceedsHalfOfContext } from "./readFileLimit";
export const readCurrentlyOpenFileImpl: ToolImpl = async (args, extras) => {
const result = await extras.ide.getCurrentFile();
if (!result) {
return [];
}
if (result) {
await throwIfFileExceedsHalfOfContext(
result.path,
result.contents,
extras.config.selectedModelByRole.chat,
);
const { relativePathOrBasename, last2Parts, baseName } = getUriDescription(
result.path,
await extras.ide.getWorkspaceDirs(),
);
const { relativePathOrBasename, last2Parts, baseName } = getUriDescription(
result.path,
await extras.ide.getWorkspaceDirs(),
);
return [
{
name: `Current file: ${baseName}`,
description: last2Parts,
content: `\`\`\`${relativePathOrBasename}\n${result.contents}\n\`\`\``,
uri: {
type: "file",
value: result.path,
return [
{
name: `Current file: ${baseName}`,
description: last2Parts,
content: `\`\`\`${relativePathOrBasename}\n${result.contents}\n\`\`\``,
uri: {
type: "file",
value: result.path,
},
},
},
];
];
} else {
return [
{
name: `No Current File`,
description: "",
content: "There are no files currently open.",
},
];
}
};

View file

@ -2,6 +2,7 @@ import { resolveRelativePathInDir } from "../../util/ideUtils";
import { getUriPathBasename } from "../../util/uri";
import { ToolImpl } from ".";
import { throwIfFileExceedsHalfOfContext } from "./readFileLimit";
export const readFileImpl: ToolImpl = async (args, extras) => {
const firstUriMatch = await resolveRelativePathInDir(
@ -12,6 +13,13 @@ export const readFileImpl: ToolImpl = async (args, extras) => {
throw new Error(`Could not find file ${args.filepath}`);
}
const content = await extras.ide.readFile(firstUriMatch);
await throwIfFileExceedsHalfOfContext(
args.filepath,
content,
extras.config.selectedModelByRole.chat,
);
return [
{
name: getUriPathBasename(args.filepath),

View file

@ -0,0 +1,18 @@
import { ILLM } from "../..";
import { countTokensAsync } from "../../llm/countTokens";
export async function throwIfFileExceedsHalfOfContext(
filepath: string,
content: string,
model: ILLM | null,
) {
if (model) {
const tokens = await countTokensAsync(content, model.title);
const tokenLimit = model.contextLength / 2;
if (tokens > tokenLimit) {
throw new Error(
`File ${filepath} is too large (${tokens} tokens vs ${tokenLimit} token limit). Try another approach`,
);
}
}
}