从零开始:开发你的第一个 VS Code AI 插件
从零开始开发你的第一个 VS Code AI 插件一、为什么开发自己的 AI 插件市面上的 AI 插件很多GitHub Copilot、Cursor、Codeium但开发自己的插件有以下优势完全可控- 选择自己的模型、定价、功能定制化- 针对团队或项目特殊需求成本优化- 使用性价比更高的模型 API数据隐私- 代码不会发送到第三方服务二、环境准备2.1 必需工具# 安装 Node.js (v18)brewinstallnode# 安装 Yeoman 和 VS Code 扩展生成器npminstall-gyo generator-code# 安装 VSCE发布工具npminstall-gvscode/vsce2.2 创建插件项目# 生成插件骨架yo code# 按提示选择# - What type of extension? → New Extension (TypeScript)# - Whats the name of your extension? → ai-code-assistant# - Whats the identifier of your extension? → ai-code-assistant# - Whats the description? → AI Code Assistant with LLM integration# - Whats the base editor? → TypeScript# - Initialize a git repo? → Yes# - Which package manager? → npm# - Install dependencies with npm? → Yes2.3 项目结构ai-code-assistant/ ├── src/ │ └── extension.ts # 主入口 ├── package.json # 插件配置 ├── tsconfig.json # TypeScript 配置 └── .vscodeignore # 发布时忽略的文件三、核心功能实现3.1 安装依赖cdai-code-assistantnpminstallopenai axiosnpminstall--save-dev types/node3.2 配置 API Key在package.json中添加配置项{contributes:{configuration:{title:AI Code Assistant,properties:{aiCodeAssistant.apiKey:{type:string,default:,description:Your LLM API Key (e.g., OpenAI, Anthropic, Aliyun)},aiCodeAssistant.model:{type:string,default:qwen-plus,description:Model to use for code generation},aiCodeAssistant.endpoint:{type:string,default:https://dashscope.aliyuncs.com/compatible-mode/v1,description:API endpoint URL}}}}}3.3 实现 AI 服务类创建src/ai-service.tsimportOpenAIfromopenai;import*asvscodefromvscode;exportclassAIService{privateclient:OpenAI;constructor(){constconfigvscode.workspace.getConfiguration(aiCodeAssistant);constapiKeyconfig.get(apiKey,);constendpointconfig.get(endpoint,);if(!apiKey){thrownewError(请先配置 API Key);}this.clientnewOpenAI({apiKey,baseURL:endpoint,});}/** * 代码解释 */asyncexplainCode(code:string,language:string):Promisestring{constresponseawaitthis.client.chat.completions.create({model:qwen-plus,messages:[{role:system,content:你是一位专业的代码讲解助手。请用简洁清晰的语言解释代码的功能、逻辑和关键点。,},{role:user,content:请解释这段${language}代码\n\n\\\${language}\n${code}\n\\\,},],temperature:0.3,max_tokens:1000,});returnresponse.choices[0].message.content||;}/** * 代码生成 */asyncgenerateCode(prompt:string,language:string):Promisestring{constresponseawaitthis.client.chat.completions.create({model:qwen-plus,messages:[{role:system,content:你是一位专业的代码生成助手。请根据用户需求生成高质量、可运行的代码。,},{role:user,content:请生成${language}代码${prompt},},],temperature:0.7,max_tokens:2000,});returnthis.extractCode(response.choices[0].message.content||);}/** * 代码重构 */asyncrefactorCode(code:string,language:string,instruction:string):Promisestring{constresponseawaitthis.client.chat.completions.create({model:qwen-plus,messages:[{role:system,content:你是一位代码重构专家。请在保持功能不变的前提下优化代码结构、性能和可读性。,},{role:user,content:请重构这段${language}代码要求${instruction}\n\n原始代码\n\\\${language}\n${code}\n\\\,},],temperature:0.5,max_tokens:2000,});returnthis.extractCode(response.choices[0].message.content||);}/** * 从响应中提取代码块 */privateextractCode(content:string):string{constcodeBlockRegex/[\w]*\n([\s\S]*?)\n/;constmatchcontent.match(codeBlockRegex);returnmatch?match[1]:content;}}3.4 实现命令处理器创建src/commands.tsimport*asvscodefromvscode;import{AIService}from./ai-service;exportclassCommandHandler{privateaiService:AIService;constructor(){this.aiServicenewAIService();}/** * 解释选中的代码 */asyncexplainSelection(){consteditorvscode.window.activeTextEditor;if(!editor){vscode.window.showErrorMessage(请先打开一个文件);return;}constselectioneditor.selection;if(selection.isEmpty){vscode.window.showErrorMessage(请先选中一段代码);return;}constcodeeditor.document.getText(selection);constlanguageeditor.document.languageId;vscode.window.withProgress({location:vscode.ProgressLocation.Notification,title:AI 正在分析代码...,cancellable:false,},async(){try{constexplanationawaitthis.aiService.explainCode(code,language);// 在输出面板显示constoutputChannelvscode.window.createOutputChannel(AI Code Assistant);outputChannel.appendLine( 代码解释 );outputChannel.appendLine(explanation);outputChannel.show();// 或者显示为 webviewthis.showExplanationWebview(explanation);}catch(error:any){vscode.window.showErrorMessage(AI 解释失败${error.message});}});}/** * 根据提示生成代码 */asyncgenerateFromPrompt(){constpromptawaitvscode.window.showInputBox({prompt:描述你想要生成的代码,placeHolder:例如创建一个函数计算两个数的最大公约数,});if(!prompt){return;}consteditorvscode.window.activeTextEditor;if(!editor){vscode.window.showErrorMessage(请先打开一个文件);return;}constlanguageeditor.document.languageId;vscode.window.withProgress({location:vscode.ProgressLocation.Notification,title:AI 正在生成代码...,cancellable:false,},async(){try{constcodeawaitthis.aiService.generateCode(prompt,language);// 插入到光标位置constpositioneditor.selection.active;awaiteditor.edit(editBuilder{editBuilder.insert(position,code);});vscode.window.showInformationMessage(代码生成成功);}catch(error:any){vscode.window.showErrorMessage(代码生成失败${error.message});}});}/** * 重构选中的代码 */asyncrefactorSelection(){consteditorvscode.window.activeTextEditor;if(!editor){return;}constselectioneditor.selection;if(selection.isEmpty){vscode.window.showErrorMessage(请先选中一段代码);return;}constinstructionawaitvscode.window.showInputBox({prompt:描述重构要求,placeHolder:例如优化性能、提高可读性、添加错误处理,});if(!instruction){return;}constcodeeditor.document.getText(selection);constlanguageeditor.document.languageId;vscode.window.withProgress({location:vscode.ProgressLocation.Notification,title:AI 正在重构代码...,cancellable:false,},async(){try{constnewCodeawaitthis.aiService.refactorCode(code,language,instruction);// 替换选中的代码awaiteditor.edit(editBuilder{editBuilder.replace(selection,newCode);});vscode.window.showInformationMessage(代码重构完成);}catch(error:any){vscode.window.showErrorMessage(重构失败${error.message});}});}privateshowExplanationWebview(content:string){constpanelvscode.window.createWebviewPanel(aiExplanation,AI 代码解释,vscode.ViewColumn.Beside,{});panel.webview.html!DOCTYPE html html head meta charsetUTF-8 style body { font-family: var(--vscode-font-family); padding: 20px; } pre { background: var(--vscode-editor-background); padding: 10px; border-radius: 4px; } /style /head body h2AI 代码解释/h2 div${content.replace(/\n/g,br)}/div /body /html;}}3.5 注册命令修改src/extension.tsimport*asvscodefromvscode;import{CommandHandler}from./commands;exportfunctionactivate(context:vscode.ExtensionContext){console.log(AI Code Assistant 已激活);consthandlernewCommandHandler();// 注册命令context.subscriptions.push(vscode.commands.registerCommand(aiCodeAssistant.explain,(){handler.explainSelection();}));context.subscriptions.push(vscode.commands.registerCommand(aiCodeAssistant.generate,(){handler.generateFromPrompt();}));context.subscriptions.push(vscode.commands.registerCommand(aiCodeAssistant.refactor,(){handler.refactorSelection();}));}exportfunctiondeactivate(){}四、配置快捷键在package.json中添加快捷键绑定{contributes:{keybindings:[{command:aiCodeAssistant.explain,key:ctrlshifte,mac:cmdshifte,when:editorTextSelection},{command:aiCodeAssistant.generate,key:ctrlshiftg,mac:cmdshiftg},{command:aiCodeAssistant.refactor,key:ctrlshiftr,mac:cmdshiftr,when:editorTextSelection}],menus:{editor/context:[{command:aiCodeAssistant.explain,group:ai-assistant,when:editorTextSelection},{command:aiCodeAssistant.refactor,group:ai-assistant,when:editorTextSelection}]}}}五、测试插件5.1 本地调试# 在 VS Code 中按 F5 启动调试# 这会打开一个新的 VS Code 窗口Extension Development Host# 在新窗口中测试插件功能5.2 测试清单配置 API Key 后插件正常工作选中代码后右键菜单显示 AI 命令快捷键触发命令正常代码解释功能正常代码生成功能正常代码重构功能正常错误处理友好API Key 无效、网络错误等六、打包发布6.1 打包# 打包成 .vsix 文件vsce package6.2 发布到 Marketplace# 登录需要 Microsoft 账号vsce loginpublisher-name# 发布vsce publish6.3 本地安装# 安装 .vsix 文件code --install-extension ai-code-assistant-0.0.1.vsix七、进阶功能建议7.1 可以添加的功能上下文感知- 分析整个项目结构提供更准确的建议单元测试生成- 根据代码自动生成测试用例代码审查- 自动检测潜在 bug 和安全问题文档生成- 根据代码生成 API 文档多模型支持- 支持切换不同的大模型对话模式- 在侧边栏实现聊天界面7.2 性能优化流式响应- 实时显示 AI 生成的内容请求缓存- 相同请求返回缓存结果批量处理- 合并多个小请求离线模式- 本地小模型处理简单任务八、总结开发 VS Code AI 插件的核心步骤环境搭建- Yeoman 生成器创建骨架API 集成- 对接大模型服务命令实现- 解释、生成、重构等功能UI 交互- 快捷键、右键菜单、Webview测试发布- 调试、打包、上架关键要点从简单功能开始逐步迭代重视错误处理和用户体验合理配置 API 调用频率和成本收集用户反馈持续优化现在就开始开发你的第一个 VS Code AI 插件吧
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2423232.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!