> ## 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容器应用动态会话集成

> 使用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字符串，包含代码执行结果以及任何stdout和stderr输出。要获取原始的字典结果，请使用`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()`返回的upload metadata获取完整的文件路径。

```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

# 生成从-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()
```

```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"]["

---

<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>
```
