forked from microsoft/vscode-python
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbaseTool.ts
More file actions
80 lines (75 loc) · 2.99 KB
/
baseTool.ts
File metadata and controls
80 lines (75 loc) · 2.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import {
CancellationToken,
LanguageModelTextPart,
LanguageModelTool,
LanguageModelToolInvocationOptions,
LanguageModelToolInvocationPrepareOptions,
LanguageModelToolResult,
PreparedToolInvocation,
Uri,
workspace,
} from 'vscode';
import { IResourceReference, isCancellationError, resolveFilePath } from './utils';
import { ErrorWithTelemetrySafeReason } from '../common/errors/errorUtils';
import { sendTelemetryEvent } from '../telemetry';
import { EventName } from '../telemetry/constants';
import { StopWatch } from '../common/utils/stopWatch';
export abstract class BaseTool<T extends IResourceReference> implements LanguageModelTool<T> {
protected extraTelemetryProperties: Record<string, string> = {};
constructor(private readonly toolName: string) {}
async invoke(
options: LanguageModelToolInvocationOptions<T>,
token: CancellationToken,
): Promise<LanguageModelToolResult> {
if (!workspace.isTrusted) {
return new LanguageModelToolResult([
new LanguageModelTextPart('Cannot use this tool in an untrusted workspace.'),
]);
}
this.extraTelemetryProperties = {};
let error: Error | undefined;
const resource = resolveFilePath(options.input.resourcePath);
const stopWatch = new StopWatch();
try {
return await this.invokeImpl(options, resource, token);
} catch (ex) {
error = ex as any;
throw ex;
} finally {
const isCancelled = token.isCancellationRequested || (error ? isCancellationError(error) : false);
const failed = !!error || isCancelled;
const failureCategory = isCancelled
? 'cancelled'
: error
? error instanceof ErrorWithTelemetrySafeReason
? error.telemetrySafeReason
: 'error'
: undefined;
sendTelemetryEvent(EventName.INVOKE_TOOL, stopWatch.elapsedTime, {
toolName: this.toolName,
failed,
failureCategory,
...this.extraTelemetryProperties,
});
}
}
protected abstract invokeImpl(
options: LanguageModelToolInvocationOptions<T>,
resource: Uri | undefined,
token: CancellationToken,
): Promise<LanguageModelToolResult>;
async prepareInvocation(
options: LanguageModelToolInvocationPrepareOptions<T>,
token: CancellationToken,
): Promise<PreparedToolInvocation> {
const resource = resolveFilePath(options.input.resourcePath);
return this.prepareInvocationImpl(options, resource, token);
}
protected abstract prepareInvocationImpl(
options: LanguageModelToolInvocationPrepareOptions<T>,
resource: Uri | undefined,
token: CancellationToken,
): Promise<PreparedToolInvocation>;
}