> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Azure 容器应用动态会话集成

> 使用 LangChain Python 集成 Azure 容器应用动态会话工具。

Azure 容器应用动态会话提供了一种安全且可扩展的方式，在 Hyper-V 隔离沙箱中运行 Python 代码解释器。这允许您的代理在安全环境中运行可能不受信任的代码。代码解释器环境包含许多流行的 Python 包，例如 NumPy、pandas 和 scikit-learn。有关会话工作原理的更多信息，请参阅 [Azure 容器应用文档](https://learn.microsoft.com/en-us/azure/container-apps/sessions-code-interpreter)。

## 设置

默认情况下，`SessionsPythonREPLTool` 工具使用 `DefaultAzureCredential` 进行 Azure 身份验证。在本地，它将使用您来自 Azure CLI 或 VS Code 的凭据。安装 Azure CLI 并使用 `az login` 登录以进行身份验证。

要使用代码解释器，您还需要创建一个会话池，您可以按照[会话池创建说明](https://learn.microsoft.com/en-us/azure/container-apps/sessions-code-interpreter?tabs=azure-cli#create-a-session-pool-with-azure-cli)进行操作。完成后，您应该会有一个池管理会话端点，您需要在下方设置：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import getpass

POOL_MANAGEMENT_ENDPOINT = getpass.getpass()
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
 ········
```

您还需要安装 `langchain-azure-dynamic-sessions` 包：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -qU langchain-azure-dynamic-sessions langchain-openai langchainhub langchain langchain-community
```

## 使用工具

实例化并使用工具：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_azure_dynamic_sessions import SessionsPythonREPLTool

tool = SessionsPythonREPLTool(pool_management_endpoint=POOL_MANAGEMENT_ENDPOINT)
tool.invoke("6 * 7")
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
'{\n  "result": 42,\n  "stdout": "",\n  "stderr": ""\n}'
```

调用工具将返回一个包含代码结果以及任何标准输出和标准错误输出的 JSON 字符串。要获取原始字典结果，请使用 `execute()` 方法：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
tool.execute("6 * 7")
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{'$id': '2',
 'status': 'Success',
 'stdout': '',
 'stderr': '',
 'result': 42,
 'executionTimeInMilliseconds': 8}
```

## 上传数据

如果我们想对特定数据执行计算，可以使用 `upload_file()` 功能将数据上传到我们的会话。您可以通过 `data: BinaryIO` 参数或 `local_file_path: str` 参数（指向您系统上的本地文件）上传数据。数据会自动上传到会话容器中的 "/mnt/data/" 目录。您可以通过 `upload_file()` 返回的上传元数据获取完整文件路径。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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)
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{'$id': '2',
 'status': 'Success',
 'stdout': '',
 'stderr': '',
 'result': -1530,
 'executionTimeInMilliseconds': 12}
```

## 处理图像结果

动态会话结果可以包含以 base64 编码字符串形式表示的图像输出。在这种情况下，'result' 的值将是一个字典，包含键 "type"（其值将为 "image"）、"format"（图像的格式）和 "base64\_data"。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
code = """
import numpy as np
import matplotlib.pyplot as plt

# Generate values for x from -1 to 1
x = np.linspace(-1, 1, 400)

# Calculate the sine of each x value
y = np.sin(x)

# Create the plot
plt.plot(x, y)

# Add title and labels
plt.title('Plot of sin(x) from -1 to 1')
plt.xlabel('x')
plt.ylabel('sin(x)')

# Show the plot
plt.grid(True)
plt.show()
"""

result = tool.execute(code)
result["result"].keys()
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
dict_keys(['type', 'format', 'base64_data'])
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
result["result"]["type"], result["result"]["format"]
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
('image', 'png')
```

我们可以解码图像数据并显示它：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import base64
import io

from IPython.display import display
from PIL import Image

base64_str = result["result"]["base64_data"]
img = Image.open(io.BytesIO(base64.decodebytes(bytes(base64_str, "utf-8"))))
display(img)
```

> **注意**：此处原有一张截图（内联 base64 图片），因 MDX 解析限制已移除。请参阅原始英文文档以查看截图。
