Skip to main content

Documentation Index

Fetch the complete documentation index at: https://langchain-zh.cn/llms.txt

Use this file to discover all available pages before exploring further.

Azure容器应用动态会话提供了在Hyper-V隔离沙盒中安全、可扩展地运行Python代码解释器的方式。这使您的代理能够在安全环境中运行可能不受信任的代码。代码解释器环境包含许多流行的Python包,如NumPy、pandas和scikit-learn。有关会话工作原理的详细信息,请参阅Azure容器应用文档

设置

默认情况下,SessionsPythonREPLTool工具使用DefaultAzureCredential来与Azure进行身份验证。本地运行时,它将使用您在Azure CLI或VS Code中的凭据进行身份验证。安装Azure CLI并使用az login登录以进行身份验证。 要使用代码解释器,您还需要创建一个会话池,您可以按照会话池创建说明进行操作。完成后,您将获得一个池管理会话端点,您需要在下面设置此端点:
import getpass

POOL_MANAGEMENT_ENDPOINT = getpass.getpass()
 ········
您还需要安装langchain-azure-dynamic-sessions包:
pip install -qU langchain-azure-dynamic-sessions langchain-openai langchainhub langchain langchain-community

使用工具

实例化并使用工具:
from langchain_azure_dynamic_sessions import SessionsPythonREPLTool

tool = SessionsPythonREPLTool(pool_management_endpoint=POOL_MANAGEMENT_ENDPOINT)
tool.invoke("6 * 7")
'{\n  "result": 42,\n  "stdout": "",\n  "stderr": ""\n}'
调用该工具将返回一个json字符串,包含代码执行结果以及任何stdout和stderr输出。要获取原始的字典结果,请使用execute()方法:
tool.execute("6 * 7")
{'$id': '2',
 'status': 'Success',
 'stdout': '',
 'stderr': '',
 'result': 42,
 'executionTimeInMilliseconds': 8}

上传数据

如果我们希望对特定数据进行计算,可以使用upload_file()功能将数据上传到我们的会话。您可以通过data: BinaryIO参数或local_file_path: str参数(指向您系统上的本地文件)上传数据。数据会自动上传到会话容器的”/mnt/data/“目录中。您可以通过upload_file()返回的upload metadata获取完整的文件路径。
import io
import json

data = {"important_data": [1, 10, -1541]}
binary_io = io.BytesIO(json.dumps(data).encode("ascii"))

upload_metadata = tool.upload_file(
    data=binary_io, remote_file_path="important_data.json"
)

code = f"""
import json

with open("{upload_metadata.full_path}") as f:
    data = json.load(f)

sum(data['important_data'])
"""
tool.execute(code)
{'$id': '2',
 'status': 'Success',
 'stdout': '',
 'stderr': '',
 'result': -1530,
 'executionTimeInMilliseconds': 12}

处理图像结果

动态会话的结果可以包含作为base64编码字符串的图像输出。在这种情况下,‘result’的值将是一个字典,包含键”type”(将为”image”)、“format”(图像的格式)和”base64_data”。
code = """
import numpy as np
import matplotlib.pyplot as plt

# 生成从-1到1的x值
x = np.linspace(-1, 1, 400)

# 计算每个x值的正弦值
y = np.sin(x)

# 创建绘图
plt.plot(x, y)

# 添加标题和标签
plt.title('Plot of sin(x) from -1 to 1')
plt.xlabel('x')
plt.ylabel('sin(x)')

# 显示绘图
plt.grid(True)
plt.show()
"""

result = tool.execute(code)
result["result"].keys()
dict_keys(['type', 'format', 'base64_data'])
result["result"]["type"], result["result"]["format"]
('image', 'png')
我们可以解码图像数据并显示它:
import base64
import io

from IPython.display import display
from PIL import Image

base64_str = result["result"]["

---

<div className="source-links">
<Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\oss\python\integrations\tools\azure_dynamic_sessions.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
</Callout>
<Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
</Callout>
</div>