Skip to content
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

Add C++ configuration as a language model tool #12577

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion Extension/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@
"Snippets"
],
"enabledApiProposals": [
"terminalDataWriteEvent"
"terminalDataWriteEvent",
"lmTools"
],
"capabilities": {
"untrustedWorkspaces": {
Expand Down Expand Up @@ -6458,6 +6459,18 @@
"description": "%c_cpp.codeActions.refactor.extract.function.description%"
}
}
],
"languageModelTools": [
{
"id": "cpptools-lmtool-configuration",
"name": "cpp",
"displayName": "C/C++ configuration",
"canBeInvokedManually": true,
"userDescription": "Configuration of the active C or C++ file, like language standard version and target platform.",
benmcmorran marked this conversation as resolved.
Show resolved Hide resolved
"modelDescription": "For the active C or C++ file, this tool provides: the language (C, C++, or CUDA), the language standard version (such as C++11, C++14, C++17, or C++20), the compiler (such as GCC, Clang, or MSVC), the target platform (such as x86, x64, or ARM), and the target architecture (such as 32-bit or 64-bit).",
"icon": "$(file-code)",
"parametersSchema": {}
}
]
},
"scripts": {
Expand Down
16 changes: 16 additions & 0 deletions Extension/src/LanguageServer/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,14 @@ interface GetIncludesResult {
includedFiles: string[];
}

export interface ChatContextResult {
language: string;
standardVersion: string;
compiler: string;
targetPlatform: string;
targetArchitecture: string;
}

// Requests
const PreInitializationRequest: RequestType<void, string, void> = new RequestType<void, string, void>('cpptools/preinitialize');
const InitializationRequest: RequestType<CppInitializationParams, void, void> = new RequestType<CppInitializationParams, void, void>('cpptools/initialize');
Expand All @@ -560,6 +568,7 @@ const GoToDirectiveInGroupRequest: RequestType<GoToDirectiveInGroupParams, Posit
const GenerateDoxygenCommentRequest: RequestType<GenerateDoxygenCommentParams, GenerateDoxygenCommentResult | undefined, void> = new RequestType<GenerateDoxygenCommentParams, GenerateDoxygenCommentResult, void>('cpptools/generateDoxygenComment');
const ChangeCppPropertiesRequest: RequestType<CppPropertiesParams, void, void> = new RequestType<CppPropertiesParams, void, void>('cpptools/didChangeCppProperties');
const IncludesRequest: RequestType<GetIncludesParams, GetIncludesResult, void> = new RequestType<GetIncludesParams, GetIncludesResult, void>('cpptools/getIncludes');
const CppContextRequest: RequestType<void, ChatContextResult, void> = new RequestType<void, ChatContextResult, void>('cpptools/getChatContext');

// Notifications to the server
const DidOpenNotification: NotificationType<DidOpenTextDocumentParams> = new NotificationType<DidOpenTextDocumentParams>('textDocument/didOpen');
Expand Down Expand Up @@ -790,6 +799,7 @@ export interface Client {
setShowConfigureIntelliSenseButton(show: boolean): void;
addTrustedCompiler(path: string): Promise<void>;
getIncludes(maxDepth: number): Promise<GetIncludesResult>;
getChatContext(): Promise<ChatContextResult | undefined>;
}

export function createClient(workspaceFolder?: vscode.WorkspaceFolder): Client {
Expand Down Expand Up @@ -2204,6 +2214,11 @@ export class DefaultClient implements Client {
return this.languageClient.sendRequest(IncludesRequest, params);
}

public async getChatContext(): Promise<ChatContextResult | undefined> {
await this.ready;
return this.languageClient.sendRequest(CppContextRequest, null);
benmcmorran marked this conversation as resolved.
Show resolved Hide resolved
}

/**
* a Promise that can be awaited to know when it's ok to proceed.
*
Expand Down Expand Up @@ -4084,4 +4099,5 @@ class NullClient implements Client {
setShowConfigureIntelliSenseButton(show: boolean): void { }
addTrustedCompiler(path: string): Promise<void> { return Promise.resolve(); }
getIncludes(): Promise<GetIncludesResult> { return Promise.resolve({} as GetIncludesResult); }
getChatContext(): Promise<ChatContextResult> { return Promise.resolve({} as ChatContextResult); }
}
6 changes: 6 additions & 0 deletions Extension/src/LanguageServer/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { CodeActionDiagnosticInfo, CodeAnalysisDiagnosticIdentifiersAndUri, code
import { CppBuildTaskProvider } from './cppBuildTaskProvider';
import { getCustomConfigProviders } from './customProviders';
import { getLanguageConfig } from './languageConfig';
import { CppConfigurationLanguageModelTool } from './lmTool';
import { PersistentState } from './persistentState';
import { NodeType, TreeNode } from './referencesModel';
import { CppSettings } from './settings';
Expand Down Expand Up @@ -248,6 +249,11 @@ export async function activate(): Promise<void> {
clients.timeTelemetryCollector.setFirstFile(activeEditor.document.uri);
activeDocument = activeEditor.document;
}

if (util.extensionContext) {
const tool = vscode.lm.registerTool('cpptools-lmtool-configuration', new CppConfigurationLanguageModelTool(clients));
benmcmorran marked this conversation as resolved.
Show resolved Hide resolved
disposables.push(tool);
}
}

export function updateLanguageConfigurations(): void {
Expand Down
90 changes: 90 additions & 0 deletions Extension/src/LanguageServer/lmTool.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved.
* See 'LICENSE' in the project root for license information.
* ------------------------------------------------------------------------------------------ */
'use strict';

import * as vscode from 'vscode';
import * as util from '../common';
import * as telemetry from '../telemetry';
import { ChatContextResult } from './client';
import { ClientCollection } from './clientCollection';

const knownValues: { [Property in keyof ChatContextResult]?: { [id: string]: string } } = {
language: {
'c': 'C',
'cpp': 'C++',
'cuda-cpp': 'CUDA C++'
},
compiler: {
'msvc': 'MSVC',
'clang': 'Clang',
'gcc': 'GCC'
},
standardVersion: {
'c++98': 'C++98',
'c++03': 'C++03',
'c++11': 'C++11',
'c++14': 'C++14',
'c++17': 'C++17',
'c++20': 'C++20',
'c++23': 'C++23',
'c90': "C90",
'c99': "C99",
'c11': "C11",
'c17': "C17",
'c23': "C23"
},
targetPlatform: {
'windows': 'Windows',
'Linux': 'Linux',
'macos': 'macOS'
}
};

class StringLanguageModelToolResult implements vscode.LanguageModelToolResult
{
public constructor(public readonly value: string) {}
public toString(): string { return this.value; }
}

export class CppConfigurationLanguageModelTool implements vscode.LanguageModelTool
{
public constructor(private readonly clients: ClientCollection) {}

public async invoke(_parameters: any, _token: vscode.CancellationToken): Promise<vscode.LanguageModelToolResult> {
return new StringLanguageModelToolResult(await this.getContext());
}

private async getContext(): Promise<string> {
const currentDoc = vscode.window.activeTextEditor?.document;
if (!currentDoc || (!util.isCpp(currentDoc) && !util.isHeaderFile(currentDoc.uri))) {
return 'The active document is not a C, C++, or CUDA file.';
}

const chatContext: ChatContextResult | undefined = await (this.clients?.ActiveClient?.getChatContext() ?? undefined);
if (!chatContext) {
return 'No configuration information is available for the active document.';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is actual content reporting absence of information needed? Could this be just an empty string?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good

}

telemetry.logLanguageModelToolEvent(
'cpp',
{
"language": chatContext.language,
"compiler": chatContext.compiler,
"standardVersion": chatContext.standardVersion,
"targetPlatform": chatContext.targetPlatform,
"targetArchitecture": chatContext.targetArchitecture
});

for (const key in knownValues) {
const knownKey = key as keyof ChatContextResult;
if (knownValues[knownKey] && chatContext[knownKey])
{
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you run the formatter on this document? The if has { on a separate line.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sean-mcmanus FYI the formatted is happy with { on the next line. I had to move this manually. The formatter used is "dbaeumer.vscode-eslint" as configured in settings.json.

@sean-mcmanus @Colengms @benmcmorran I addressed this comment in this other PR (topmost commit): #12685

I have no access to vscode-cpptools, hence I cant push on this PR.

chatContext[knownKey] = knownValues[knownKey][chatContext[knownKey]] || chatContext[knownKey];
}
}

return `The user is working on a ${chatContext.language} project. The project uses language version ${chatContext.standardVersion}, compiles using the ${chatContext.compiler} compiler, targets the ${chatContext.targetPlatform} platform, and targets the ${chatContext.targetArchitecture} architecture.`;
}
}
14 changes: 14 additions & 0 deletions Extension/src/telemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,20 @@ export function logLanguageServerEvent(eventName: string, properties?: Record<st
sendTelemetry();
}

export function logLanguageModelToolEvent(eventName: string, properties?: Record<string, string>, metrics?: Record<string, number>): void {
const sendTelemetry = () => {
if (experimentationTelemetry) {
const eventNamePrefix: string = "C_Cpp/Copilot/Chat/Tool/";
experimentationTelemetry.sendTelemetryEvent(eventNamePrefix + eventName, properties, metrics);
}
};

if (is.promise(initializationPromise)) {
return void initializationPromise.catch(logAndReturn.undefined).then(sendTelemetry).catch(logAndReturn.undefined);
}
sendTelemetry();
}

function getPackageInfo(): IPackageInfo {
return {
name: util.packageJson.publisher + "." + util.packageJson.name,
Expand Down
Loading