basic-ai/extension.js

206 lines
6.1 KiB
JavaScript

const vscode = require('vscode');
class ApiResponseViewProvider {
constructor() {
this._view = undefined;
this._response = '';
}
resolveWebviewView(webviewView) {
this._view = webviewView;
webviewView.webview.options = {
enableScripts: true
};
this.updateContent();
}
updateResponse(response) {
this._response = response;
this.updateContent();
}
getResponse() {
return this._response;
}
updateContent() {
if (this._view) {
this._view.webview.html = `
<!DOCTYPE html>
<html>
<body>
<pre>${this._response}</pre>
</body>
</html>
`;
}
}
}
const prompt_docscting = `
You are a specialized Python documentation assistant. When given Python code, generate a comprehensive docstring following this specific format:
1. First line: Brief, clear description of what the function/class does
2. Empty line after description
3. Args section (if there are parameters):
- Each parameter on a new line
- Format: parameter_name (type): description
- Include type hints in parentheses
- Detailed description of parameter purpose and constraints
4. Returns section (if the function returns something):
- Detailed description of return value(s)
- For complex return types, include full type annotation
- For multiple return values, list each component
5. Raises section (if applicable):
- List exceptions that may be raised
- Include when and why they occur
Rules for writing:
- Always use triple double quotes (""")
- Keep first line concise but informative
- Be specific about types, including nested types (List[Dict], Tuple[str, int], etc.)
- For complex return types, break them down with bullet points
- Indentation should match the function's indentation level
- Use consistent capitalization (start each section with capital letter)
- Don't include implementation details, focus on interface
- Be explicit about optional parameters and default values
- For collections, specify the structure of contained elements
Example Format:
"""
Brief description of function purpose.
Args:
param1 (type): Description of first parameter.
param2 (type): Description of second parameter.
Returns:
type: Description of return value.
- bullet points for complex returns
- explaining each component
Raises:
ExceptionType: Description of when/why exception occurs.
"""
Focus on:
- Accuracy of type annotations
- Clarity of descriptions
- Completeness of information
- Consistency in formatting
- Technical precision
You will receive Python code and should respond with only the appropriate docstring, maintaining exact indentation and following all format rules above.
`;
function formatApiResponse(apiResponse) {
// Extraer el contenido de la respuesta
const rawContent = apiResponse.content;
// El contenido viene con comillas y barras invertidas adicionales
// Primero eliminamos las comillas al inicio y final
let cleanContent = rawContent.replace('\\', '###');
// Luego reemplazamos los caracteres de escape de las comillas triples
//cleanContent = cleanContent.replace(/\\"\\"\\"/g, '########');
// Eliminamos cualquier barra invertida adicional que esté escapando caracteres
//cleanContent = cleanContent.replace(/\\\\/g, '\\');
//cleanContent = cleanContent.replace(/\\n/g, '\n');
return cleanContent;
}
function activate(context) {
const apiResponseProvider = new ApiResponseViewProvider();
context.subscriptions.push(
vscode.window.registerWebviewViewProvider('apiResponseView', apiResponseProvider)
);
// Comando para enviar código a la API
let sendToApiCommand = vscode.commands.registerCommand('code-api-integration.sendToApi', async () => {
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showErrorMessage('No hay editor activo');
return;
}
const selection = editor.selection;
const selectedText = editor.document.getText(selection);
if (!selectedText) {
vscode.window.showErrorMessage('No hay texto seleccionado');
return;
}
try {
// Mostrar indicador de progreso
vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: "Enviando código a la API...",
cancellable: false
}, async (progress) => {
const response = await fetch('https://allapi.desarrollo.ciditel.net/api/v2/text/text', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(
{"server":"groq",
"model":"llama3.3-70b-it",
"system":prompt_docscting,
"content":selectedText,
"password": "1223Aer*",
"userid": "Anon"}
)
});
if (!response.ok) {
throw new Error(`Error en la API: ${response.statusText}`);
}
const data = await response.json();
const data2 = formatApiResponse(data);
apiResponseProvider.updateResponse(JSON.stringify(data2, null, 2));
// Notificar que la respuesta está lista para usar
vscode.window.showInformationMessage('Respuesta de API guardada - usa el botón derecho para pegarla');
});
} catch (error) {
vscode.window.showErrorMessage(`Error: ${error.message}`);
}
});
// Comando para pegar la última respuesta
let pasteResponseCommand = vscode.commands.registerCommand('code-api-integration.pasteLastResponse', async () => {
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showErrorMessage('No hay editor activo');
return;
}
const response = apiResponseProvider.getResponse();
if (!response) {
vscode.window.showWarningMessage('No hay respuesta guardada de la API');
return;
}
editor.edit(editBuilder => {
editBuilder.insert(editor.selection.active, response);
});
});
context.subscriptions.push(sendToApiCommand, pasteResponseCommand);
}
function deactivate() {}
module.exports = {
activate,
deactivate
}