|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +import { |
| 5 | + CancellationError, |
| 6 | + CancellationToken, |
| 7 | + l10n, |
| 8 | + LanguageModelTextPart, |
| 9 | + LanguageModelTool, |
| 10 | + LanguageModelToolInvocationOptions, |
| 11 | + LanguageModelToolInvocationPrepareOptions, |
| 12 | + LanguageModelToolResult, |
| 13 | + PreparedToolInvocation, |
| 14 | + Uri, |
| 15 | +} from 'vscode'; |
| 16 | +import { PythonExtension, ResolvedEnvironment } from '../api/types'; |
| 17 | +import { IServiceContainer } from '../ioc/types'; |
| 18 | +import { ICodeExecutionService } from '../terminals/types'; |
| 19 | +import { TerminalCodeExecutionProvider } from '../terminals/codeExecution/terminalCodeExecution'; |
| 20 | +import { IProcessService, IProcessServiceFactory, IPythonExecutionFactory } from '../common/process/types'; |
| 21 | +import { raceCancellationError } from './utils'; |
| 22 | +import { resolveFilePath } from './utils'; |
| 23 | +import { parsePipList } from './pipListUtils'; |
| 24 | +import { Conda } from '../pythonEnvironments/common/environmentManagers/conda'; |
| 25 | +import { traceError } from '../logging'; |
| 26 | + |
| 27 | +export interface IResourceReference { |
| 28 | + resourcePath: string; |
| 29 | +} |
| 30 | + |
| 31 | +interface EnvironmentInfo { |
| 32 | + type: string; // e.g. conda, venv, virtualenv, sys |
| 33 | + version: string; |
| 34 | + runCommand: string; |
| 35 | + packages: string[] | string; //include versions too |
| 36 | +} |
| 37 | + |
| 38 | +/** |
| 39 | + * A tool to get the information about the Python environment. |
| 40 | + */ |
| 41 | +export class GetEnvironmentInfoTool implements LanguageModelTool<IResourceReference> { |
| 42 | + private readonly terminalExecutionService: TerminalCodeExecutionProvider; |
| 43 | + private readonly pythonExecFactory: IPythonExecutionFactory; |
| 44 | + private readonly processServiceFactory: IProcessServiceFactory; |
| 45 | + public static readonly toolName = 'python_environment'; |
| 46 | + constructor( |
| 47 | + private readonly api: PythonExtension['environments'], |
| 48 | + private readonly serviceContainer: IServiceContainer, |
| 49 | + ) { |
| 50 | + this.terminalExecutionService = this.serviceContainer.get<TerminalCodeExecutionProvider>( |
| 51 | + ICodeExecutionService, |
| 52 | + 'standard', |
| 53 | + ); |
| 54 | + this.pythonExecFactory = this.serviceContainer.get<IPythonExecutionFactory>(IPythonExecutionFactory); |
| 55 | + this.processServiceFactory = this.serviceContainer.get<IProcessServiceFactory>(IProcessServiceFactory); |
| 56 | + } |
| 57 | + /** |
| 58 | + * Invokes the tool to get the information about the Python environment. |
| 59 | + * @param options - The invocation options containing the file path. |
| 60 | + * @param token - The cancellation token. |
| 61 | + * @returns The result containing the information about the Python environment or an error message. |
| 62 | + */ |
| 63 | + async invoke( |
| 64 | + options: LanguageModelToolInvocationOptions<IResourceReference>, |
| 65 | + token: CancellationToken, |
| 66 | + ): Promise<LanguageModelToolResult> { |
| 67 | + const resourcePath = resolveFilePath(options.input.resourcePath); |
| 68 | + |
| 69 | + // environment info set to default values |
| 70 | + const envInfo: EnvironmentInfo = { |
| 71 | + type: 'no type found', |
| 72 | + version: 'no version found', |
| 73 | + packages: 'no packages found', |
| 74 | + runCommand: 'no run command found', |
| 75 | + }; |
| 76 | + |
| 77 | + try { |
| 78 | + // environment |
| 79 | + const envPath = this.api.getActiveEnvironmentPath(resourcePath); |
| 80 | + const environment = await raceCancellationError(this.api.resolveEnvironment(envPath), token); |
| 81 | + if (!environment || !environment.version) { |
| 82 | + throw new Error('No environment found for the provided resource path: ' + resourcePath.fsPath); |
| 83 | + } |
| 84 | + const cmd = await raceCancellationError( |
| 85 | + this.terminalExecutionService.getExecutableInfo(resourcePath), |
| 86 | + token, |
| 87 | + ); |
| 88 | + const executable = cmd.pythonExecutable; |
| 89 | + envInfo.runCommand = cmd.args.length > 0 ? `${cmd.command} ${cmd.args.join(' ')}` : executable; |
| 90 | + envInfo.version = environment.version.sysVersion; |
| 91 | + |
| 92 | + const isConda = (environment.environment?.type || '').toLowerCase() === 'conda'; |
| 93 | + envInfo.packages = isConda |
| 94 | + ? await raceCancellationError( |
| 95 | + listCondaPackages( |
| 96 | + this.pythonExecFactory, |
| 97 | + environment, |
| 98 | + resourcePath, |
| 99 | + await raceCancellationError(this.processServiceFactory.create(resourcePath), token), |
| 100 | + ), |
| 101 | + token, |
| 102 | + ) |
| 103 | + : await raceCancellationError(listPipPackages(this.pythonExecFactory, resourcePath), token); |
| 104 | + |
| 105 | + // format and return |
| 106 | + return new LanguageModelToolResult([BuildEnvironmentInfoContent(envInfo)]); |
| 107 | + } catch (error) { |
| 108 | + if (error instanceof CancellationError) { |
| 109 | + throw error; |
| 110 | + } |
| 111 | + const errorMessage: string = `An error occurred while fetching environment information: ${error}`; |
| 112 | + const partialContent = BuildEnvironmentInfoContent(envInfo); |
| 113 | + return new LanguageModelToolResult([ |
| 114 | + new LanguageModelTextPart(`${errorMessage}\n\n${partialContent.value}`), |
| 115 | + ]); |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + async prepareInvocation?( |
| 120 | + _options: LanguageModelToolInvocationPrepareOptions<IResourceReference>, |
| 121 | + _token: CancellationToken, |
| 122 | + ): Promise<PreparedToolInvocation> { |
| 123 | + return { |
| 124 | + invocationMessage: l10n.t('Fetching Python environment information'), |
| 125 | + }; |
| 126 | + } |
| 127 | +} |
| 128 | + |
| 129 | +function BuildEnvironmentInfoContent(envInfo: EnvironmentInfo): LanguageModelTextPart { |
| 130 | + // Create a formatted string that looks like JSON but preserves comments |
| 131 | + let envTypeDescriptor: string = `This environment is managed by ${envInfo.type} environment manager. Use the install tool to install packages into this environment.`; |
| 132 | + |
| 133 | + // TODO: If this is setup as python.defaultInterpreterPath, then do not include this message. |
| 134 | + if (envInfo.type === 'system') { |
| 135 | + envTypeDescriptor = |
| 136 | + 'System pythons are pythons that ship with the OS or are installed globally. These python installs may be used by the OS for running services and core functionality. Confirm with the user before installing packages into this environment, as it can lead to issues with any services on the OS.'; |
| 137 | + } |
| 138 | + const content = `{ |
| 139 | + // ${JSON.stringify(envTypeDescriptor)} |
| 140 | + "environmentType": ${JSON.stringify(envInfo.type)}, |
| 141 | + // Python version of the environment |
| 142 | + "pythonVersion": ${JSON.stringify(envInfo.version)}, |
| 143 | + // Use this command to run Python script or code in the terminal. |
| 144 | + "runCommand": ${JSON.stringify(envInfo.runCommand)}, |
| 145 | + // Installed Python packages, each in the format <name> or <name> (<version>). The version may be omitted if unknown. Returns an empty array if no packages are installed. |
| 146 | + "packages": ${JSON.stringify(Array.isArray(envInfo.packages) ? envInfo.packages : envInfo.packages, null, 2)} |
| 147 | +}`; |
| 148 | + |
| 149 | + return new LanguageModelTextPart(content); |
| 150 | +} |
| 151 | + |
| 152 | +async function listPipPackages(execFactory: IPythonExecutionFactory, resource: Uri) { |
| 153 | + // Add option --format to subcommand list of pip cache, with abspath choice to output the full path of a wheel file. (#8355) |
| 154 | + // Added in 202. Thats almost 5 years ago. When Python 3.8 was released. |
| 155 | + const exec = await execFactory.createActivatedEnvironment({ allowEnvironmentFetchExceptions: true, resource }); |
| 156 | + const output = await exec.execModule('pip', ['list'], { throwOnStdErr: false, encoding: 'utf8' }); |
| 157 | + return parsePipList(output.stdout).map((pkg) => (pkg.version ? `${pkg.name} (${pkg.version})` : pkg.name)); |
| 158 | +} |
| 159 | + |
| 160 | +async function listCondaPackages( |
| 161 | + execFactory: IPythonExecutionFactory, |
| 162 | + env: ResolvedEnvironment, |
| 163 | + resource: Uri, |
| 164 | + processService: IProcessService, |
| 165 | +) { |
| 166 | + const conda = await Conda.getConda(); |
| 167 | + if (!conda) { |
| 168 | + traceError('Conda is not installed, falling back to pip packages'); |
| 169 | + return listPipPackages(execFactory, resource); |
| 170 | + } |
| 171 | + if (!env.executable.uri) { |
| 172 | + traceError('Conda environment executable not found, falling back to pip packages'); |
| 173 | + return listPipPackages(execFactory, resource); |
| 174 | + } |
| 175 | + const condaEnv = await conda.getCondaEnvironment(env.executable.uri.fsPath); |
| 176 | + if (!condaEnv) { |
| 177 | + traceError('Conda environment not found, falling back to pip packages'); |
| 178 | + return listPipPackages(execFactory, resource); |
| 179 | + } |
| 180 | + const cmd = await conda.getListPythonPackagesArgs(condaEnv, true); |
| 181 | + if (!cmd) { |
| 182 | + traceError('Conda list command not found, falling back to pip packages'); |
| 183 | + return listPipPackages(execFactory, resource); |
| 184 | + } |
| 185 | + const output = await processService.exec(cmd[0], cmd.slice(1), { shell: true }); |
| 186 | + if (!output.stdout) { |
| 187 | + traceError('Unable to get conda packages, falling back to pip packages'); |
| 188 | + return listPipPackages(execFactory, resource); |
| 189 | + } |
| 190 | + const content = output.stdout.split(/\r?\n/).filter((l) => !l.startsWith('#')); |
| 191 | + const packages: string[] = []; |
| 192 | + content.forEach((l) => { |
| 193 | + const parts = l.split(' ').filter((p) => p.length > 0); |
| 194 | + if (parts.length === 3) { |
| 195 | + packages.push(`${parts[0]} (${parts[1]})`); |
| 196 | + } |
| 197 | + }); |
| 198 | + return packages; |
| 199 | +} |
0 commit comments