-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Compress tool output to reduce token usage #5106
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
meganrogge
wants to merge
3
commits into
main
Choose a base branch
from
merogge/tool-output-compression
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
136 changes: 136 additions & 0 deletions
136
src/extension/tools/common/test/toolResultCompressor.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| /*--------------------------------------------------------------------------------------------- | ||
| * Copyright (c) Microsoft Corporation. All rights reserved. | ||
| * Licensed under the MIT License. See License.txt in the project root for license information. | ||
| *--------------------------------------------------------------------------------------------*/ | ||
|
|
||
| import { describe, expect, it } from 'vitest'; | ||
| import type { IConfigurationService } from '../../../../platform/configuration/common/configurationService'; | ||
| import type { ILogService } from '../../../../platform/log/common/logService'; | ||
| import type { ITelemetryService } from '../../../../platform/telemetry/common/telemetry'; | ||
| import { | ||
| LanguageModelDataPart, | ||
| LanguageModelPartAudience, | ||
| LanguageModelTextPart, | ||
| LanguageModelTextPart2, | ||
| LanguageModelToolResult, | ||
| } from '../../../../vscodeTypes'; | ||
| import { IToolResultFilter, ToolResultCompressorService } from '../toolResultCompressor'; | ||
|
|
||
| const TOOL = 'run_in_terminal'; | ||
|
|
||
| function makeService(opts: { | ||
| enabled: boolean; | ||
| warnings?: string[]; | ||
| }): ToolResultCompressorService { | ||
| const config = { | ||
| getConfig: (_key: unknown) => opts.enabled, | ||
| } as unknown as IConfigurationService; | ||
| const telemetry = { | ||
| sendMSFTTelemetryEvent: () => { /* noop */ }, | ||
| } as unknown as ITelemetryService; | ||
| const log = { | ||
| warn: (msg: string) => { opts.warnings?.push(msg); }, | ||
| } as unknown as ILogService; | ||
| return new ToolResultCompressorService(config, telemetry, log); | ||
| } | ||
|
|
||
| function longText(prefix: string): string { | ||
| // Must exceed MIN_COMPRESSIBLE_LENGTH (80) so filters get a chance to run. | ||
| return prefix + ' ' + 'x'.repeat(200); | ||
| } | ||
|
|
||
| const replaceWithFooFilter: IToolResultFilter = { | ||
| id: 'test.replaceWithFoo', | ||
| toolNames: [TOOL], | ||
| matches: () => true, | ||
| apply: () => ({ text: 'foo', compressed: true }), | ||
| }; | ||
|
|
||
| describe('ToolResultCompressorService', () => { | ||
| it('returns undefined when disabled', () => { | ||
| const svc = makeService({ enabled: false }); | ||
| svc.registerFilter(replaceWithFooFilter); | ||
| const result = new LanguageModelToolResult([new LanguageModelTextPart(longText('hello'))]); | ||
| expect(svc.maybeCompress(TOOL, {}, result)).toBeUndefined(); | ||
| }); | ||
|
|
||
| it('returns undefined when no filters registered', () => { | ||
| const svc = makeService({ enabled: true }); | ||
| const result = new LanguageModelToolResult([new LanguageModelTextPart(longText('hello'))]); | ||
| expect(svc.maybeCompress(TOOL, {}, result)).toBeUndefined(); | ||
| }); | ||
|
|
||
| it('returns undefined when no filters match', () => { | ||
| const svc = makeService({ enabled: true }); | ||
| svc.registerFilter({ | ||
| id: 'no-match', | ||
| toolNames: [TOOL], | ||
| matches: () => false, | ||
| apply: () => ({ text: 'foo', compressed: true }), | ||
| }); | ||
| const result = new LanguageModelToolResult([new LanguageModelTextPart(longText('hello'))]); | ||
| expect(svc.maybeCompress(TOOL, {}, result)).toBeUndefined(); | ||
| }); | ||
|
|
||
| it('disables a throwing filter for the rest of the pass and warns once', () => { | ||
| const warnings: string[] = []; | ||
| const svc = makeService({ enabled: true, warnings }); | ||
| let calls = 0; | ||
| svc.registerFilter({ | ||
| id: 'thrower', | ||
| toolNames: [TOOL], | ||
| matches: () => true, | ||
| apply: () => { calls++; throw new Error('boom'); }, | ||
| }); | ||
| svc.registerFilter(replaceWithFooFilter); | ||
| const result = new LanguageModelToolResult([ | ||
| new LanguageModelTextPart(longText('a')), | ||
| new LanguageModelTextPart(longText('b')), | ||
| new LanguageModelTextPart(longText('c')), | ||
| ]); | ||
| const out = svc.maybeCompress(TOOL, {}, result)!; | ||
| expect(out).toBeDefined(); | ||
| // Throwing filter is invoked exactly once on the first text part, then disabled. | ||
| expect(calls).toBe(1); | ||
| expect(warnings.length).toBe(1); | ||
| expect(warnings[0]).toContain('thrower'); | ||
| // The other filter still rewrites every text part. | ||
| for (const part of out.content) { | ||
| expect(part).toBeInstanceOf(LanguageModelTextPart); | ||
| expect((part as LanguageModelTextPart).value).toBe('foo'); | ||
| } | ||
| }); | ||
|
|
||
| it('preserves non-text parts unchanged', () => { | ||
| const svc = makeService({ enabled: true }); | ||
| svc.registerFilter(replaceWithFooFilter); | ||
| const dataPart = new LanguageModelDataPart(new Uint8Array([1, 2, 3]), 'application/octet-stream'); | ||
| const textPart = new LanguageModelTextPart(longText('hello')); | ||
| const result = new LanguageModelToolResult([dataPart, textPart]); | ||
| const out = svc.maybeCompress(TOOL, {}, result)!; | ||
| expect(out.content[0]).toBe(dataPart); | ||
| expect(out.content[1]).toBeInstanceOf(LanguageModelTextPart); | ||
| expect((out.content[1] as LanguageModelTextPart).value).toBe('foo'); | ||
| }); | ||
|
|
||
| it('preserves LanguageModelTextPart2 audience metadata when rewriting', () => { | ||
| const svc = makeService({ enabled: true }); | ||
| svc.registerFilter(replaceWithFooFilter); | ||
| const audience = [LanguageModelPartAudience.Assistant, LanguageModelPartAudience.User]; | ||
| const part = new LanguageModelTextPart2(longText('hello'), audience); | ||
| const result = new LanguageModelToolResult([part]); | ||
| const out = svc.maybeCompress(TOOL, {}, result)!; | ||
| expect(out.content[0]).toBeInstanceOf(LanguageModelTextPart2); | ||
| const rewritten = out.content[0] as LanguageModelTextPart2; | ||
| expect(rewritten.value).toBe('foo'); | ||
| expect(rewritten.audience).toEqual(audience); | ||
| }); | ||
|
|
||
| it('skips text parts shorter than the minimum compressible length', () => { | ||
| const svc = makeService({ enabled: true }); | ||
| svc.registerFilter(replaceWithFooFilter); | ||
| const result = new LanguageModelToolResult([new LanguageModelTextPart('tiny')]); | ||
| // Nothing was compressed because the part was below the threshold. | ||
| expect(svc.maybeCompress(TOOL, {}, result)).toBeUndefined(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,183 @@ | ||
| /*--------------------------------------------------------------------------------------------- | ||
| * Copyright (c) Microsoft Corporation. All rights reserved. | ||
| * Licensed under the MIT License. See License.txt in the project root for license information. | ||
| *--------------------------------------------------------------------------------------------*/ | ||
|
|
||
| import type * as vscode from 'vscode'; | ||
| import { ConfigKey, IConfigurationService } from '../../../platform/configuration/common/configurationService'; | ||
| import { ILogService } from '../../../platform/log/common/logService'; | ||
| import { ITelemetryService } from '../../../platform/telemetry/common/telemetry'; | ||
| import { createServiceIdentifier } from '../../../util/common/services'; | ||
| import { LanguageModelTextPart, LanguageModelTextPart2 } from '../../../vscodeTypes'; | ||
|
|
||
| export const IToolResultCompressor = createServiceIdentifier<IToolResultCompressor>('IToolResultCompressor'); | ||
|
|
||
| /** | ||
| * Result of running a {@link IToolResultFilter}. | ||
| * | ||
| * `text` is the new text to substitute back into the corresponding text part. | ||
| * `compressed` is `true` if any compression actually happened — used purely | ||
| * for telemetry / accounting. | ||
| */ | ||
| export interface IToolResultFilterOutput { | ||
| readonly text: string; | ||
| readonly compressed: boolean; | ||
| } | ||
|
|
||
| /** | ||
| * A pure function that compresses a single text part of a tool result. | ||
| * | ||
| * Implementations MUST never make output worse than the input. If a filter | ||
| * cannot improve a piece of text, it should return the original `text` and | ||
| * `compressed: false`. | ||
| */ | ||
| export interface IToolResultFilter { | ||
| readonly id: string; | ||
| /** Tool names this filter applies to. */ | ||
| readonly toolNames: readonly string[]; | ||
| /** | ||
| * Decide whether this filter wants to handle the result. May inspect tool | ||
| * input (e.g. for `run_in_terminal`, the command being run). | ||
| */ | ||
| matches(toolName: string, input: unknown): boolean; | ||
| apply(text: string, input: unknown): IToolResultFilterOutput; | ||
| } | ||
|
|
||
| export interface IToolResultCompressor { | ||
| readonly _serviceBrand: undefined; | ||
| registerFilter(filter: IToolResultFilter): void; | ||
| /** | ||
| * Returns a possibly-compressed copy of `result`, or `undefined` if no | ||
| * compression was applied (caller should pass through the original). | ||
| */ | ||
| maybeCompress(toolName: string, input: unknown, result: vscode.LanguageModelToolResult | vscode.LanguageModelToolResult2): vscode.LanguageModelToolResult | undefined; | ||
| } | ||
|
|
||
| /** | ||
| * Outputs at or below this many characters (UTF-16 code units, i.e. | ||
| * `string.length`) are not worth compressing. Mirrors ztk's 80-character | ||
| * minimum. | ||
| */ | ||
| const MIN_COMPRESSIBLE_LENGTH = 80; | ||
|
|
||
| export class ToolResultCompressorService implements IToolResultCompressor { | ||
| declare readonly _serviceBrand: undefined; | ||
|
|
||
| private readonly _filters = new Map<string, IToolResultFilter[]>(); | ||
|
|
||
| constructor( | ||
| @IConfigurationService private readonly _configurationService: IConfigurationService, | ||
| @ITelemetryService private readonly _telemetryService: ITelemetryService, | ||
| @ILogService private readonly _logService: ILogService, | ||
| ) { } | ||
|
|
||
| registerFilter(filter: IToolResultFilter): void { | ||
| for (const name of filter.toolNames) { | ||
| let bucket = this._filters.get(name); | ||
| if (!bucket) { | ||
| bucket = []; | ||
| this._filters.set(name, bucket); | ||
| } | ||
| bucket.push(filter); | ||
| } | ||
| } | ||
|
|
||
| maybeCompress(toolName: string, input: unknown, result: vscode.LanguageModelToolResult | vscode.LanguageModelToolResult2): vscode.LanguageModelToolResult | undefined { | ||
| if (!this._configurationService.getConfig(ConfigKey.ToolResultCompressionEnabled)) { | ||
| return undefined; | ||
| } | ||
|
|
||
| const filters = this._filters.get(toolName); | ||
| if (!filters || filters.length === 0) { | ||
| return undefined; | ||
| } | ||
|
|
||
| const matchingFilters = filters.filter(f => f.matches(toolName, input)); | ||
| if (matchingFilters.length === 0) { | ||
| return undefined; | ||
| } | ||
|
|
||
| // Mutable copy: filters that throw get spliced out so we don't repeatedly | ||
| // invoke a broken filter on every subsequent text part in this pass. | ||
| const activeFilters = matchingFilters.slice(); | ||
| const disabledFilterIds = new Set<string>(); | ||
|
|
||
| let totalBefore = 0; | ||
| let totalAfter = 0; | ||
| let anyCompressed = false; | ||
| const usedFilterIds = new Set<string>(); | ||
|
|
||
| const newContent = result.content.map(part => { | ||
| if (!(part instanceof LanguageModelTextPart)) { | ||
| return part; | ||
| } | ||
| const original = part.value; | ||
| if (original.length < MIN_COMPRESSIBLE_LENGTH) { | ||
| return part; | ||
| } | ||
|
|
||
| let current = original; | ||
| for (let i = 0; i < activeFilters.length; /* manual increment */) { | ||
| const filter = activeFilters[i]; | ||
| try { | ||
| const out = filter.apply(current, input); | ||
| if (out.compressed && out.text.length < current.length) { | ||
| current = out.text; | ||
| usedFilterIds.add(filter.id); | ||
| } | ||
| i++; | ||
| } catch (err) { | ||
| // "Never make it worse." Disable the filter for the rest of this | ||
| // compression pass so it can't repeatedly throw on later text parts, | ||
| // and warn at most once per filter. | ||
| activeFilters.splice(i, 1); | ||
| if (!disabledFilterIds.has(filter.id)) { | ||
| disabledFilterIds.add(filter.id); | ||
| this._logService.warn(`[ToolResultCompressor] filter ${filter.id} threw on tool ${toolName}; disabled for this pass: ${err}`); | ||
| } | ||
| } | ||
|
meganrogge marked this conversation as resolved.
|
||
| } | ||
|
|
||
| totalBefore += original.length; | ||
| totalAfter += current.length; | ||
| if (current !== original) { | ||
| anyCompressed = true; | ||
| // Preserve LanguageModelTextPart2 audience metadata if present. | ||
| if (part instanceof LanguageModelTextPart2) { | ||
| return new LanguageModelTextPart2(current, part.audience); | ||
| } | ||
| return new LanguageModelTextPart(current); | ||
| } | ||
| return part; | ||
|
meganrogge marked this conversation as resolved.
|
||
| }); | ||
|
|
||
| if (!anyCompressed) { | ||
| return undefined; | ||
| } | ||
|
|
||
| this._sendTelemetry(toolName, [...usedFilterIds], totalBefore, totalAfter); | ||
|
|
||
| // Preserve `toolResultMessage`/`toolResultDetails` if present (ExtendedLanguageModelToolResult shape). | ||
| const compressed: vscode.LanguageModelToolResult & { toolResultMessage?: unknown; toolResultDetails?: unknown } = | ||
| Object.assign(Object.create(Object.getPrototypeOf(result)), result, { content: newContent }); | ||
| return compressed as vscode.LanguageModelToolResult; | ||
| } | ||
|
meganrogge marked this conversation as resolved.
|
||
|
|
||
| private _sendTelemetry(toolName: string, filterIds: string[], beforeChars: number, afterChars: number) { | ||
| /* __GDPR__ | ||
| "toolResultCompressed" : { | ||
| "owner": "meganrogge", | ||
| "comment": "Reports tool output compression savings.", | ||
| "toolName": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The tool whose output was compressed." }, | ||
| "filters": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "Comma-separated filter ids that fired." }, | ||
| "beforeChars": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true, "comment": "Total text part length in UTF-16 code units before compression." }, | ||
| "afterChars": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true, "comment": "Total text part length in UTF-16 code units after compression." } | ||
| } | ||
| */ | ||
| this._telemetryService.sendMSFTTelemetryEvent( | ||
| 'toolResultCompressed', | ||
| { toolName, filters: filterIds.join(',') }, | ||
| { beforeChars, afterChars }, | ||
| ); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.