Repository navigation
Expand file tree
/
Copy pathsessions_python_plugin.py
More file actions
293 lines (237 loc) · 10.7 KB
/
Copy pathsessions_python_plugin.py
File metadata and controls
293 lines (237 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# Copyright (c) Microsoft. All rights reserved.
import logging
import os
import re
from collections.abc import Awaitable, Callable
from io import BytesIO
from typing import Annotated, Any
import httpx
from pydantic import ValidationError
from semantic_kernel.connectors.telemetry import HTTP_USER_AGENT, version_info
from semantic_kernel.const import USER_AGENT
from semantic_kernel.core_plugins.sessions_python_tool.sessions_python_settings import (
ACASessionsSettings,
SessionsPythonSettings,
)
from semantic_kernel.core_plugins.sessions_python_tool.sessions_remote_file_metadata import SessionsRemoteFileMetadata
from semantic_kernel.exceptions.function_exceptions import FunctionExecutionException, FunctionInitializationError
from semantic_kernel.functions.kernel_function_decorator import kernel_function
from semantic_kernel.kernel_pydantic import HttpsUrl, KernelBaseModel
logger = logging.getLogger(__name__)
SESSIONS_USER_AGENT = f"{HTTP_USER_AGENT}/{version_info} (Language=Python)"
SESSIONS_API_VERSION = "2024-02-02-preview"
class SessionsPythonTool(KernelBaseModel):
"""A plugin for running Python code in an Azure Container Apps dynamic sessions code interpreter."""
pool_management_endpoint: HttpsUrl
settings: SessionsPythonSettings
auth_callback: Callable[..., Awaitable[Any]]
http_client: httpx.AsyncClient
def __init__(
self,
auth_callback: Callable[..., Awaitable[Any]],
pool_management_endpoint: str | None = None,
settings: SessionsPythonSettings | None = None,
http_client: httpx.AsyncClient | None = None,
env_file_path: str | None = None,
**kwargs,
):
"""Initializes a new instance of the SessionsPythonTool class."""
try:
aca_settings = ACASessionsSettings.create(
env_file_path=env_file_path, pool_management_endpoint=pool_management_endpoint
)
except ValidationError as e:
logger.error(f"Failed to load the ACASessionsSettings with message: {e!s}")
raise FunctionInitializationError(f"Failed to load the ACASessionsSettings with message: {e!s}") from e
if not settings:
settings = SessionsPythonSettings()
if not http_client:
http_client = httpx.AsyncClient()
super().__init__(
pool_management_endpoint=aca_settings.pool_management_endpoint,
settings=settings,
auth_callback=auth_callback,
http_client=http_client,
**kwargs,
)
async def _ensure_auth_token(self) -> str:
"""Ensure the auth token is valid."""
try:
auth_token = await self.auth_callback()
except Exception as e:
logger.error(f"Failed to retrieve the client auth token with message: {e!s}")
raise FunctionExecutionException(f"Failed to retrieve the client auth token with messages: {e!s}") from e
return auth_token
def _sanitize_input(self, code: str) -> str:
"""Sanitize input to the python REPL.
Remove whitespace, backtick & python (if llm mistakes python console as terminal).
Args:
code (str): The query to sanitize
Returns:
str: The sanitized query
"""
# Removes `, whitespace & python from start
code = re.sub(r"^(\s|`)*(?i:python)?\s*", "", code)
# Removes whitespace & ` from end
return re.sub(r"(\s|`)*$", "", code)
def _construct_remote_file_path(self, remote_file_path: str) -> str:
"""Construct the remote file path.
Args:
remote_file_path (str): The remote file path.
Returns:
str: The remote file path.
"""
if not remote_file_path.startswith("/mnt/data/"):
remote_file_path = f"/mnt/data/{remote_file_path}"
return remote_file_path
def _build_url_with_version(self, base_url, endpoint, params):
"""Builds a URL with the provided base URL, endpoint, and query parameters."""
params["api-version"] = SESSIONS_API_VERSION
query_string = "&".join([f"{key}={value}" for key, value in params.items()])
return f"{base_url}{endpoint}?{query_string}"
@kernel_function(
description="""Executes the provided Python code.
Start and end the code snippet with double quotes to define it as a string.
Insert \\n within the string wherever a new line should appear.
Add spaces directly after \\n sequences to replicate indentation.
Use \" to include double quotes within the code without ending the string.
Keep everything in a single line; the \\n sequences will represent line breaks
when the string is processed or displayed.
""",
name="execute_code",
)
async def execute_code(self, code: Annotated[str, "The valid Python code to execute"]) -> str:
"""Executes the provided Python code.
Args:
code (str): The valid Python code to execute
Returns:
str: The result of the Python code execution in the form of Result, Stdout, and Stderr
Raises:
FunctionExecutionException: If the provided code is empty.
"""
if not code:
raise FunctionExecutionException("The provided code is empty")
if self.settings.sanitize_input:
code = self._sanitize_input(code)
auth_token = await self._ensure_auth_token()
logger.info(f"Executing Python code: {code}")
self.http_client.headers.update(
{
"Authorization": f"Bearer {auth_token}",
"Content-Type": "application/json",
USER_AGENT: SESSIONS_USER_AGENT,
}
)
self.settings.python_code = code
request_body = {
"properties": self.settings.model_dump(exclude_none=True, exclude={"sanitize_input"}, by_alias=True),
}
url = self._build_url_with_version(
base_url=self.pool_management_endpoint,
endpoint="python/execute/",
params={"identifier": self.settings.session_id},
)
response = await self.http_client.post(
url=url,
json=request_body,
)
response.raise_for_status()
result = response.json()
return f"Result:\n{result['result']}Stdout:\n{result['stdout']}Stderr:\n{result['stderr']}"
@kernel_function(name="upload_file", description="Uploads a file for the current Session ID")
async def upload_file(
self,
*,
local_file_path: Annotated[str, "The path to the local file on the machine"],
remote_file_path: Annotated[
str | None, "The remote path to the file in the session. Defaults to /mnt/data"
] = None,
) -> Annotated[SessionsRemoteFileMetadata, "The metadata of the uploaded file"]:
"""Upload a file to the session pool.
Args:
remote_file_path (str): The path to the file in the session.
local_file_path (str): The path to the file on the local machine.
Returns:
RemoteFileMetadata: The metadata of the uploaded file.
Raises:
FunctionExecutionException: If local_file_path is not provided.
"""
if not local_file_path:
raise FunctionExecutionException("Please provide a local file path to upload.")
remote_file_path = self._construct_remote_file_path(remote_file_path or os.path.basename(local_file_path))
with open(local_file_path, "rb") as data:
auth_token = await self._ensure_auth_token()
self.http_client.headers.update(
{
"Authorization": f"Bearer {auth_token}",
USER_AGENT: SESSIONS_USER_AGENT,
}
)
files = [("file", (remote_file_path, data, "application/octet-stream"))]
url = self._build_url_with_version(
base_url=self.pool_management_endpoint,
endpoint="python/uploadFile",
params={"identifier": self.settings.session_id},
)
response = await self.http_client.post(
url=url,
json={},
files=files, # type: ignore
)
response.raise_for_status()
response_json = response.json()
return SessionsRemoteFileMetadata.from_dict(response_json["$values"][0])
@kernel_function(name="list_files", description="Lists all files in the provided Session ID")
async def list_files(self) -> list[SessionsRemoteFileMetadata]:
"""List the files in the session pool.
Returns:
list[SessionsRemoteFileMetadata]: The metadata for the files in the session pool
"""
auth_token = await self._ensure_auth_token()
self.http_client.headers.update(
{
"Authorization": f"Bearer {auth_token}",
USER_AGENT: SESSIONS_USER_AGENT,
}
)
url = self._build_url_with_version(
base_url=self.pool_management_endpoint,
endpoint="python/files",
params={"identifier": self.settings.session_id},
)
response = await self.http_client.get(
url=url,
)
response.raise_for_status()
response_json = response.json()
return [SessionsRemoteFileMetadata.from_dict(entry) for entry in response_json["$values"]]
async def download_file(self, *, remote_file_path: str, local_file_path: str | None = None) -> BytesIO | None:
"""Download a file from the session pool.
Args:
remote_file_path: The path to download the file from, relative to `/mnt/data`.
local_file_path: The path to save the downloaded file to. If not provided, the
file is returned as a BufferedReader.
Returns:
BufferedReader: The data of the downloaded file.
"""
auth_token = await self.auth_callback()
self.http_client.headers.update(
{
"Authorization": f"Bearer {auth_token}",
USER_AGENT: SESSIONS_USER_AGENT,
}
)
url = self._build_url_with_version(
base_url=self.pool_management_endpoint,
endpoint="python/downloadFile",
params={"identifier": self.settings.session_id, "filename": remote_file_path},
)
response = await self.http_client.get(
url=url,
)
response.raise_for_status()
if local_file_path:
with open(local_file_path, "wb") as f:
f.write(response.content)
return None
return BytesIO(response.content)