-
Notifications
You must be signed in to change notification settings - Fork 3k
/
sessions_python_plugin.py
261 lines (211 loc) · 9.79 KB
/
sessions_python_plugin.py
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
# Copyright (c) Microsoft. All rights reserved.
import logging
import os
import re
from collections.abc import Awaitable, Callable
from io import BufferedReader, BytesIO
from typing import Annotated, Any
import httpx
from pydantic import ValidationError, field_validator
from semantic_kernel.connectors.ai.open_ai.const import USER_AGENT
from semantic_kernel.connectors.telemetry import HTTP_USER_AGENT, version_info
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
from semantic_kernel.functions.kernel_function_decorator import kernel_function
from semantic_kernel.kernel_pydantic import KernelBaseModel
logger = logging.getLogger(__name__)
SESSIONS_USER_AGENT = f"{HTTP_USER_AGENT}/{version_info} (Language=Python)"
class SessionsPythonTool(KernelBaseModel):
"""A plugin for running Python code in an Azure Container Apps dynamic sessions code interpreter."""
pool_management_endpoint: str
settings: SessionsPythonSettings | None = None
auth_callback: Callable[..., Awaitable[Any]]
http_client: httpx.AsyncClient | None = None
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."""
if not settings:
settings = SessionsPythonSettings()
if not http_client:
http_client = httpx.AsyncClient()
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: {str(e)}")
raise FunctionExecutionException(f"Failed to load the ACASessionsSettings with message: {str(e)}") from e
endpoint = pool_management_endpoint or aca_settings.pool_management_endpoint
super().__init__(
pool_management_endpoint=endpoint,
auth_callback=auth_callback,
settings=settings,
http_client=http_client,
**kwargs,
)
@field_validator("pool_management_endpoint", mode="before")
@classmethod
def _validate_endpoint(cls, endpoint: str):
endpoint = str(endpoint)
"""Validates the pool management endpoint."""
if "/python/execute" in endpoint:
# Remove '/python/execute/' and ensure the endpoint ends with a '/'
endpoint = endpoint.replace("/python/execute", "").rstrip("/") + "/"
if not endpoint.endswith("/"):
# Ensure the endpoint ends with a '/'
endpoint = endpoint + "/"
return endpoint
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: {str(e)}")
raise FunctionExecutionException(f"Failed to retrieve the client auth token with messages: {str(e)}") 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: 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
code = re.sub(r"(\s|`)*$", "", code)
return code
@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),
}
response = await self.http_client.post(
url=f"{self.pool_management_endpoint}python/execute/",
json=request_body,
)
response.raise_for_status()
result = response.json()
return f"Result:\n{result['result']}Stdout:\n{result['stdout']}Stderr:\n{result['stderr']}" # noqa: E501
@kernel_function(name="upload_file", description="Uploads a file for the current Session ID")
async def upload_file(
self, *, data: BufferedReader = None, remote_file_path: str = None, local_file_path: str = None
) -> SessionsRemoteFileMetadata:
"""Upload a file to the session pool.
Args:
data (BufferedReader): The file data to upload.
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.
"""
if data and local_file_path:
raise ValueError("data and local_file_path cannot be provided together")
if local_file_path:
if not remote_file_path:
remote_file_path = os.path.basename(local_file_path)
data = open(local_file_path, "rb")
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"))]
response = await self.http_client.post(
url=f"{self.pool_management_endpoint}python/uploadFile?identifier={self.settings.session_id}",
json={},
files=files,
)
response.raise_for_status()
response_json = response.json()
return SessionsRemoteFileMetadata.from_dict(response_json)
@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,
}
)
response = await self.http_client.get(
url=f"{self.pool_management_endpoint}python/files?identifier={self.settings.session_id}",
)
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) -> BufferedReader | 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,
}
)
response = await self.http_client.get(
url=f"{self.pool_management_endpoint}python/downloadFile?identifier={self.settings.session_id}&filename={remote_file_path}", # noqa: E501
)
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)