Skip to content

Commit 4367614

Browse files
authored
Port Python Env Tools (#25066)
* Tested with .venv, global conda, local conda and global Python * Tested both tools ![Screenshot 2025-05-14 at 11 54 44](https://github.com/user-attachments/assets/dab561f7-a66d-4157-8e04-86be433fb0eb) ![Screenshot 2025-05-14 at 11 57 39](https://github.com/user-attachments/assets/ce727718-56fb-4948-9764-bc8df3dda565) ![Screenshot 2025-05-14 at 11 57 49](https://github.com/user-attachments/assets/f1a5c643-b079-4306-be89-654a2043e8b4)
1 parent e709012 commit 4367614

File tree

9 files changed

+511
-1
lines changed

9 files changed

+511
-1
lines changed

package.json

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1462,6 +1462,66 @@
14621462
"fileMatch": "meta.yaml",
14631463
"url": "./schemas/conda-meta.json"
14641464
}
1465+
],
1466+
"languageModelTools": [
1467+
{
1468+
"name": "python_environment",
1469+
"displayName": "Get Python Environment Information",
1470+
"userDescription": "%python.languageModelTools.python_environment.userDescription%",
1471+
"modelDescription": "Provides details about the Python environment for a specified file or workspace, including environment type, Python version, run command, and installed packages with their versions. Use this tool to determine the correct command for executing Python code in this workspace.",
1472+
"toolReferenceName": "pythonGetEnvironmentInfo",
1473+
"tags": [
1474+
"ms-python.python"
1475+
],
1476+
"icon": "$(files)",
1477+
"canBeReferencedInPrompt": true,
1478+
"inputSchema": {
1479+
"type": "object",
1480+
"properties": {
1481+
"resourcePath": {
1482+
"type": "string"
1483+
}
1484+
},
1485+
"description": "The path to the Python file or workspace to get the environment information for.",
1486+
"required": [
1487+
"resourcePath"
1488+
]
1489+
},
1490+
"when": "!pythonEnvExtensionInstalled"
1491+
},
1492+
{
1493+
"name": "python_install_package",
1494+
"displayName": "Install Python Package",
1495+
"userDescription": "%python.languageModelTools.python_install_package.userDescription%",
1496+
"modelDescription": "Installs Python packages in the given workspace. Use this tool to install packages in the user's chosen environment.",
1497+
"toolReferenceName": "pythonInstallPackage",
1498+
"tags": [
1499+
"ms-python.python"
1500+
],
1501+
"icon": "$(package)",
1502+
"canBeReferencedInPrompt": true,
1503+
"inputSchema": {
1504+
"type": "object",
1505+
"properties": {
1506+
"packageList": {
1507+
"type": "array",
1508+
"items": {
1509+
"type": "string"
1510+
},
1511+
"description": "The list of packages to install."
1512+
},
1513+
"resourcePath": {
1514+
"type": "string",
1515+
"description": "The path to the Python file or workspace to get the environment information for."
1516+
}
1517+
},
1518+
"required": [
1519+
"packageList",
1520+
"resourcePath"
1521+
]
1522+
},
1523+
"when": "!pythonEnvExtensionInstalled"
1524+
}
14651525
]
14661526
},
14671527
"copilot": {

package.nls.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
{
22
"python.command.python.startTerminalREPL.title": "Start Terminal REPL",
3+
"python.languageModelTools.python_environment.userDescription": "Get Python environment info for a file or path, including version, packages, and the command to run it.",
4+
"python.languageModelTools.python_install_package.userDescription": "Installs Python packages in the given workspace.",
35
"python.command.python.startNativeREPL.title": "Start Native Python REPL",
46
"python.command.python.createEnvironment.title": "Create Environment...",
57
"python.command.python.createNewFile.title": "New Python File",
68
"python.command.python.createTerminal.title": "Create Terminal",
79
"python.command.python.execInTerminal.title": "Run Python File in Terminal",
810
"python.command.python.execInTerminalIcon.title": "Run Python File",
9-
"python.command.python.execInDedicatedTerminal.title": "Run Python File in Dedicated Terminal",
11+
"python.command.python.execInDedicatedTerminal.title": "Run Python File in Dedicated Terminal",
1012
"python.command.python.setInterpreter.title": "Select Interpreter",
1113
"python.command.python.clearWorkspaceInterpreter.title": "Clear Workspace Interpreter Setting",
1214
"python.command.python.viewOutput.title": "Show Output",

src/client/chat/getPythonEnvTool.ts

Lines changed: 199 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,199 @@
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+
}

src/client/chat/index.ts

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT License.
3+
4+
import { commands, extensions, lm } from 'vscode';
5+
import { PythonExtension } from '../api/types';
6+
import { IServiceContainer } from '../ioc/types';
7+
import { GetEnvironmentInfoTool } from './getPythonEnvTool';
8+
import { InstallPackagesTool } from './installPackagesTool';
9+
import { IExtensionContext } from '../common/types';
10+
import { DisposableStore } from '../common/utils/resourceLifecycle';
11+
import { ENVS_EXTENSION_ID } from '../envExt/api.internal';
12+
import { IDiscoveryAPI } from '../pythonEnvironments/base/locator';
13+
14+
export function registerTools(
15+
context: IExtensionContext,
16+
discoverApi: IDiscoveryAPI,
17+
environmentsApi: PythonExtension['environments'],
18+
serviceContainer: IServiceContainer,
19+
) {
20+
if (extensions.getExtension(ENVS_EXTENSION_ID)) {
21+
return;
22+
}
23+
const contextKey = 'pythonEnvExtensionInstalled';
24+
commands.executeCommand('setContext', contextKey, false);
25+
const ourTools = new DisposableStore();
26+
context.subscriptions.push(ourTools);
27+
28+
ourTools.add(
29+
lm.registerTool(GetEnvironmentInfoTool.toolName, new GetEnvironmentInfoTool(environmentsApi, serviceContainer)),
30+
);
31+
ourTools.add(
32+
lm.registerTool(
33+
InstallPackagesTool.toolName,
34+
new InstallPackagesTool(environmentsApi, serviceContainer, discoverApi),
35+
),
36+
);
37+
ourTools.add(
38+
extensions.onDidChange(() => {
39+
const envExtension = extensions.getExtension(ENVS_EXTENSION_ID);
40+
if (envExtension) {
41+
envExtension.activate();
42+
commands.executeCommand('setContext', contextKey, true);
43+
ourTools.dispose();
44+
}
45+
}),
46+
);
47+
}

0 commit comments

Comments
 (0)