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 Q# Copilot to VS Code Extension #1379

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 5 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"@types/markdown-it": "^13.0.6",
"@types/mocha": "^10.0.2",
"@types/node": "^18.17",
"@types/vscode": "^1.83.0",
"@types/vscode": "^1.88.0",
"@types/vscode-webview": "^1.57.3",
"@typescript-eslint/eslint-plugin": "^7.3.1",
"@typescript-eslint/parser": "^7.3.1",
Expand Down
28 changes: 26 additions & 2 deletions vscode/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
},
"type": "commonjs",
"engines": {
"vscode": "^1.77.0"
"vscode": "^1.88.0"
},
"categories": [
"Programming Languages",
Expand All @@ -27,6 +27,9 @@
"onFileSystem:qsharp-vfs",
"onWebviewPanel:qsharp-webview"
],
"enabledApiProposals": [
"chatParticipant"
],
"contributes": {
"walkthroughs": [
{
Expand Down Expand Up @@ -458,7 +461,28 @@
"[qsharp]": {
"debug.saveBeforeStart": "none"
}
}
},
"extensionDependencies": [
"github.copilot-chat"
],
"chatParticipants": [
{
"id": "quantum.copilot",
"name": "quantum",
"description": "Azure Quantum Copilot",
"isSticky": true,
"commands": [
{
"name": "samples",
"description": "Show Q# samples"
},
{
"name": "quantumNotebook",
"description": "Create an Azure Quantum Jupyter Notebook"
}
]
}
]
},
"scripts": {
"build": "npm run tsc:check && node build.mjs",
Expand Down
Binary file added vscode/resources/copilotIcon.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions vscode/src/azure/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { EndEventProperties } from "./workspaceActions";
export const scopes = {
armMgmt: "https://management.azure.com/user_impersonation",
quantum: "https://quantum.microsoft.com/user_impersonation",
chatApi: "https://api.quantum.microsoft.com/Chat.ReadWrite",
};

export async function getAuthSession(
Expand Down
130 changes: 130 additions & 0 deletions vscode/src/chatParticipant.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

import * as vscode from "vscode";
import { getRandomGuid } from "./utils";
import { log } from "qsharp-lang";
import { getAuthSession, scopes } from "./azure/auth";

const chatUrl = "https://canary.api.quantum.microsoft.com/api/chat/completions";
const chatApp = "652066ed-7ea8-4625-a1e9-5bac6600bf06";

type quantumChatRequest = {
conversationId: string; // GUID
messages: Array<{
role: string; // e.g. "user"
content: string;
}>; // The actual question
additionalContext: any; // ?
};

type QuantumChatResponse = {
role: string; // e.g. "assistant"
content: string; // The actual answer
embeddedData: any; // ?
};

async function chatRequest(
token: string,
question: string,
context?: string,
): Promise<QuantumChatResponse> {
const payload: quantumChatRequest = {
conversationId: getRandomGuid(),
messages: [
{
role: "user",
content: question,
},
],
additionalContext: {
qcomEnvironment: "Desktop",
},
};

if (context) {
payload.messages.unshift({
role: "assistant",
content: context,
});
}

const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(payload),
};
log.debug("About to call ChatAPI with payload: ", payload);

try {
const response = await fetch(chatUrl, options);
log.debug("ChatAPI response status: ", response.statusText);

const json = await response.json();
log.debug("ChatAPI response payload: ", json);
return json;
} catch (error) {
log.error("ChatAPI fetch failed with error: ", error);
throw error;
}
}

const requestHandler: vscode.ChatRequestHandler = async (
request: vscode.ChatRequest,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_context: vscode.ChatContext,
stream: vscode.ChatResponseStream,
token: vscode.CancellationToken,
): Promise<vscode.ChatResult> => {
const msaChatSession = await getAuthSession(
[scopes.chatApi, `VSCODE_TENANT:common`, `VSCODE_CLIENT_ID:${chatApp}`],
getRandomGuid(),
);
if (!msaChatSession) throw Error("Failed to get MSA chat token");

let response: QuantumChatResponse;
if (request.command == "samples") {
if (request.prompt) {
response = await chatRequest(
msaChatSession.accessToken,
"Please show me the Q# code for " + request.prompt,
);
} else {
response = await chatRequest(
msaChatSession.accessToken,
"Can you list the names of the quantum samples you could write if asked?",
"The main samples I know how to write are Bell state, Grovers, QRNG, hidden shift, Bernstein-Vazarani, Deutsch-Jozsa, superdense coding, and teleportation",
);
}
} else if (request.command == "quantumNotebook") {
stream.progress("Opening a new Quantum Notebook...");
await vscode.commands.executeCommand("qsharp-vscode.createNotebook");
return Promise.resolve({});
} else {
response = await chatRequest(msaChatSession.accessToken, request.prompt);
}
if (token.isCancellationRequested) return Promise.reject("Request cancelled");

stream.markdown(response.content);

return Promise.resolve({});
};

export function activateChatParticipant(context: vscode.ExtensionContext) {
const copilot = vscode.chat.createChatParticipant(
"quantum.copilot",
requestHandler,
);

copilot.iconPath = vscode.Uri.joinPath(
context.extensionUri,
"resources",
"copilotIcon.png",
);

// Register a chat agent
context.subscriptions.push(copilot);
}
4 changes: 3 additions & 1 deletion vscode/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import {
} from "./telemetry.js";
import { registerWebViewCommands } from "./webviewPanel.js";
import { initProjectCreator } from "./createProject.js";
import { activateChatParticipant } from "./chatParticipant.js";

export async function activate(
context: vscode.ExtensionContext,
Expand Down Expand Up @@ -90,6 +91,7 @@ export async function activate(
registerWebViewCommands(context);
initFileSystem(context);
initProjectCreator(context);
activateChatParticipant(context);

log.info("Q# extension activated.");

Expand Down Expand Up @@ -394,7 +396,7 @@ export class QsTextDocumentContentProvider
provideTextDocumentContent(
uri: vscode.Uri,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
token: vscode.CancellationToken,
_token: vscode.CancellationToken,
): vscode.ProviderResult<string> {
return getLibrarySourceContent(uri.path);
}
Expand Down