Skip to content

Commit

Permalink
cleanup some functions, add prompt by instruct template command
Browse files Browse the repository at this point in the history
  • Loading branch information
ili16 committed Mar 11, 2024
1 parent f6106b8 commit c76c4e7
Show file tree
Hide file tree
Showing 3 changed files with 162 additions and 74 deletions.
17 changes: 14 additions & 3 deletions extension/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,20 @@
"name": "modernizer-vscode",
"displayName": "Modernizer",
"description": "A VSCode extension for displaying and ranking most frequently asked prompts",
"version": "1.1.0",
"version": "1.2.0",
"publisher": "IlijaKovacevic",
"author": "Ilija Kovacevic",
"icon": "resources/modernizer-logo.jpg",
"homepage": "https://github.com/rwth-acis/modernizer#readme",
"repository": {
"type": "git",
"url": "github:rwth-acis/modernizer.git"
"url": "https://github.com/rwth-acis/modernizer"
},
"engines": {
"vscode": "^1.73.0"
},
"categories": [
"Other"
"Education"
],
"activationEvents": [
"onStartup"
Expand Down Expand Up @@ -49,6 +49,11 @@
"command": "modernizer-vscode.customPrompt",
"group": "navigation",
"when": "editorHasSelection && resourceScheme == 'file'"
},
{
"command": "modernizer-vscode.PromptByList",
"group": "navigation",
"when": "editorHasSelection && resourceScheme == 'file'"
}
],
"editor/context": [
Expand Down Expand Up @@ -98,6 +103,12 @@
"command": "modernizer-vscode.gitURL",
"category": "Modernizer",
"group": "Modernizer"
},
{
"title": "Generate Prompt by List",
"command": "modernizer-vscode.PromptByList",
"category": "Modernizer",
"group": "Modernizer"
}
],
"configuration": {
Expand Down
32 changes: 18 additions & 14 deletions extension/src/CodelensProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export class CodelensProvider implements vscode.CodeLensProvider {


constructor() {
this.regex = /\b(?:func|type|var|const)\b\s+([a-zA-Z_]\w*)/g;
this.regex = /\b(?:func|type|var|const|def|public\s+class|function)\b\s+([a-zA-Z_]\w*)|\bfunc\s*\(\s*\*\s*[a-zA-Z_]\w*\s*\)\s*([a-zA-Z_]\w*)|function\s+([a-zA-Z_]\w*)/g;

vscode.workspace.onDidChangeConfiguration(() => {
this._onDidChangeCodeLenses.fire();
Expand Down Expand Up @@ -43,7 +43,7 @@ export class CodelensProvider implements vscode.CodeLensProvider {
const line = document.lineAt(document.positionAt(matches.index).line);
const indexOf = line.text.indexOf(matches[0]);
const position = new vscode.Position(line.lineNumber, indexOf);
const range = document.getWordRangeAtPosition(position, /\b(?:func|type|var|const)\b\s+([a-zA-Z_]\w*)/);
const range = document.getWordRangeAtPosition(position, this.regex);

if (range) {
const codeLens = new vscode.CodeLens(range);
Expand Down Expand Up @@ -87,22 +87,26 @@ export class CodelensProvider implements vscode.CodeLensProvider {
const line = document.lineAt(document.positionAt(match.index).line);
const position = new vscode.Position(line.lineNumber, match.index);
const range = new vscode.Range(position, position.with(undefined, match.index + match[0].length));

const codeLens = new vscode.CodeLens(range, {
title: "Show next Prompt ⮞",
tooltip: "Show next Prompt",
command: "modernizer-vscode.showNextResponse"
});


const gitURL = await getGitURLByID(remainingResponseList[0]);

const codeLens2 = new vscode.CodeLens(range, {
title: "Open GitHub Repository",
command: "modernizer-vscode.openGitHubRepo",
arguments: [gitURL]
});

codeLenses.push(codeLens, codeLens2);

codeLenses.push(codeLens2);

if (remainingResponseList.length > 1) {
const codeLens = new vscode.CodeLens(range, {
title: "Show next Prompt ⮞",
tooltip: "Show next Prompt",
command: "modernizer-vscode.showNextResponse"
});

codeLenses.push(codeLens);
}
}

return codeLenses;
Expand Down Expand Up @@ -234,7 +238,7 @@ async function showResponse(isBestResponse:boolean) {
outputWindow.append("The instruct used for this prompt: " + responseText.instruct + "\n\n");
outputWindow.append(responseText.hasResponse);

remainingResponseList = responseList.slice(1);
remainingResponseList = responseList;

const options = [
{ title: `👍 Upvote` },
Expand All @@ -260,9 +264,9 @@ async function showResponse(isBestResponse:boolean) {
}

let disposableNextResponse = vscode.commands.registerCommand('modernizer-vscode.showNextResponse', async () => {
await showNextResponse(remainingResponseList);

remainingResponseList = remainingResponseList.slice(1);
await showNextResponse(remainingResponseList);
});

let disposableBest = vscode.commands.registerCommand('modernizer-vscode.showBestResponse', async () => {
Expand Down
187 changes: 130 additions & 57 deletions extension/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ export function activate(context: ExtensionContext) {

const codelensProvider = new CodelensProvider();

context.subscriptions.push(disposableUserInput);
context.subscriptions.push(disposableGetGitURL);

languages.registerCodeLensProvider("*", codelensProvider);
Expand All @@ -32,6 +31,7 @@ export function activate(context: ExtensionContext) {

context.subscriptions.push(disposableCustomPrompt);
context.subscriptions.push(disposableRandomPrompt);
context.subscriptions.push(disposableCustomPromptbyList);
}


Expand Down Expand Up @@ -75,25 +75,6 @@ export function getSelectedFunctionRange(editor: vscode.TextEditor): vscode.Rang
}
}

let disposableUserInput = vscode.commands.registerCommand('modernizer-vscode.customPrompt2', async () => {
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showErrorMessage("No text selected.");
return;
}

const userInput = await vscode.window.showInputBox({
prompt: "Enter instruct to use in prompt"
});

if (!userInput) {
vscode.window.showErrorMessage("No input provided.");
return;
}

vscode.window.showInformationMessage(`Notification: ${userInput}`);
});

let disposableRandomPrompt = vscode.commands.registerCommand('modernizer-vscode.randomPrompt', async () => {
try {
await generateRandomPrompt();
Expand All @@ -119,6 +100,14 @@ let disposableGetGitURL = vscode.commands.registerCommand('modernizer-vscode.git
}
});

let disposableCustomPromptbyList = vscode.commands.registerCommand('modernizer-vscode.PromptByList', async () => {
try {
await generateCustomPromptbyList();
} catch (error: any) {
vscode.window.showErrorMessage(`Error: ${error.message}`);
}
});

async function generateRandomPrompt() {
const activeEditor = vscode.window.activeTextEditor;
if (!activeEditor) {
Expand All @@ -143,7 +132,7 @@ async function generateRandomPrompt() {
const url: string = `${baseUrl}${generateRoute}`;

const promptData = {
model: 'codellama:13b-instruct',
model: 'codellama:34b-instruct',
prompt: `${functionCode}`,
gitURL: gitURL,
};
Expand Down Expand Up @@ -179,7 +168,7 @@ async function generateCustomPrompt() {
const url: string = `${baseUrl}${generateRoute}`;

const promptData = {
model: "codellama:13b-instruct",
model: "codellama:34b-instruct",
prompt: `${functionCode}`,
instruct: userInput,
gitURL: gitURL,
Expand All @@ -188,45 +177,129 @@ async function generateCustomPrompt() {
await sendPromptToAPI(url, promptData);
}

async function generateCustomPromptbyList() {
const activeEditor = vscode.window.activeTextEditor;
if (!activeEditor) {
vscode.window.showErrorMessage("No text selected.");
return;
}

const gitURL = await calculateURL();

const selectedFunctionRange = getSelectedFunctionRange(activeEditor);
if (!selectedFunctionRange) {
vscode.window.showWarningMessage('No function selected. Please select a function to generate a prompt.');
return;
}

const functionCode = activeEditor.document.getText(selectedFunctionRange);


const selectedInstruct = await showInstructTemplates();

if (!selectedInstruct) return; // User canceled input

const baseUrl: string = vscode.workspace.getConfiguration("modernizer-vscode").get("baseURL", "https://modernizer.milki-psy.dbis.rwth-aachen.de");
const generateRoute: string = "/generate";
const url: string = `${baseUrl}${generateRoute}`;

const promptData = {
model: "codellama:34b-instruct",
prompt: `${functionCode}`,
instruct: selectedInstruct,
gitURL: gitURL,

};

await sendPromptToAPI(url, promptData);
}

async function sendPromptToAPI(url: string, promptData: any) {
try {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(promptData)
});
return vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: 'Sending prompt to API...',
cancellable: false
}, async (progress, token) => {
try {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(promptData)
});

if (!response.ok) {
throw new Error(`Failed to make request: ${response.statusText}`);
}

if (response.ok) {
try {
const contentType = response.headers.get("content-type");
if (contentType && contentType.includes("application/json")) {
// Parse and display the Ollama response
const responseBody = await response.json();
const responseText = responseBody.response || "No response field found";

const outputWindow = vscode.window.createOutputChannel("Ollama Response");
outputWindow.show(true);

outputWindow.append(`Generated new response with the instruct: ${responseBody.instruct}\n\n`);
outputWindow.append(responseText + "\n");

if (responseBody.promptID) {
DisplayVoting(responseBody.promptID);
} else {
vscode.window.showWarningMessage("No promptId field found");
}
} else {
vscode.window.showWarningMessage("Received non-JSON response. Check the API for possible errors.");
}
} catch (jsonError: any) {
vscode.window.showErrorMessage(`Failed to parse JSON response: ${jsonError.message}`);
const contentType = response.headers.get("content-type");
if (!contentType || !contentType.includes("application/json")) {
throw new Error("Received non-JSON response. Check the API for possible errors.");
}
} else {
vscode.window.showErrorMessage(`Failed to make request: ${response.statusText}`);

const responseBody = await response.json();
const responseText = responseBody.response || "No response field found";

const outputWindow = vscode.window.createOutputChannel("Ollama Response");
outputWindow.show(true);

outputWindow.append(`Generated new response with the instruct: ${responseBody.instruct}\n\n`);
outputWindow.append(responseText + "\n");

if (responseBody.promptID) {
DisplayVoting(responseBody.promptID);
} else {
vscode.window.showWarningMessage("No promptId field found");
}
} catch (error: any) {
vscode.window.showErrorMessage(`Error: ${error.message}`);
}
});
}



async function showInstructTemplates(): Promise<string | undefined> {
let baseUrl: string = vscode.workspace.getConfiguration("modernizer-vscode").get("baseURL", "https://modernizer.milki-psy.dbis.rwth-aachen.de");
let responseListPath: string = '/get-all-sets';
let url: string = `${baseUrl}${responseListPath}`;
let result: string | undefined;

try {
const response = await fetch(url);
const sets = await response.json();

result = await vscode.window.showQuickPick(sets, {
placeHolder: 'Select a set',
});
} catch (error: any) {
vscode.window.showErrorMessage(`Error: ${error.message}`);
return ''; // Return an empty string in case of an error
}

baseUrl = vscode.workspace.getConfiguration("modernizer-vscode").get("baseURL", "https://modernizer.milki-psy.dbis.rwth-aachen.de");
responseListPath = '/get-instruct';
url = `${baseUrl}${responseListPath}`;

let queryParams = new URLSearchParams(result ? { set: result } : {});
let urlQuery = `${url}?${queryParams.toString()}&all=true`;

const response = await fetch(urlQuery);
if (!response.ok) {
vscode.window.showErrorMessage(`Error: ${response.statusText}`);
return '';
}
}

try {
const instructs = await response.json();
result = await vscode.window.showQuickPick(instructs.result, {
placeHolder: 'Select an instruct',
});

return result;
} catch (error) {
console.error("Error parsing response data:", error);
return "";
}
}

0 comments on commit c76c4e7

Please sign in to comment.