你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
代码解释器使 Microsoft Foundry 代理能够在沙盒执行环境中运行Python代码。 代理的 Foundry 模型编写和执行用于数据分析、图表生成和迭代解决问题的任务的代码。
在本文中,你将创建一个代理,该代理使用代码解释器,上传 CSV 文件进行分析,并下载生成的图表。
启用代码解释器时,代理可以迭代编写和运行Python代码,以解决数据分析和数学任务,以及生成图表。
重要
除了与使用 Azure OpenAI 相关的基于令牌的费用之外,代码解释器还有额外的费用。 如果代理在两个不同的会话中同时调用代码解释器,则会创建两个代码解释器会话。 默认情况下,每个会话处于活动状态一小时,空闲超时为 30 分钟。
使用支持
下表显示了 SDK 和设置支持。
| Microsoft Foundry 支持 | Python SDK | C# SDK | JavaScript SDK | Java SDK | REST API | 基本代理设置 | 标准代理设置 |
|---|---|---|---|---|---|---|---|
| ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
先决条件
- 基本或标准代理环境。 有关详细信息,请参阅 代理环境设置 。
- 已为您的语言安装最新的 SDK 包。 .NET SDK 目前为预览版。 请参阅 快速入门以了解安装步骤。
- 项目中已配置的 Azure AI 模型部署。
- 对于文件操作:上传 CSV 或其他受支持的文件以进行分析。
注意
代码解释器在所有区域中都不可用。 请参阅 “检查区域和模型可用性”。
使用代码解释器创建代理
以下示例演示如何创建启用了代码解释器的代理、上传文件进行分析和下载生成的输出。
提示
可以在运行时自定义代码解释器行为,例如,使用 结构化输入指定要包含或调整每个请求的工具参数的文件。
在 Python SDK 中将代理与代码解释器工具配合使用的示例
以下Python示例演示如何将代码解释器工具添加到工具箱、将工具箱附加到代理、上传 CSV 文件进行分析,以及基于数据请求条形图。 选择 Prompt Agents以使用 Azure AI Projects SDK 创建服务器端提示代理,或托管代理使用 Agent Framework FoundryChatClient生成临时进程内代理。
此示例演示了完整的工作流:上传文件、创建启用了代码解释器的代理、请求数据可视化并下载生成的图表。
import os
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition, CodeInterpreterTool, AutoCodeInterpreterToolParam
# Load the CSV file to be processed
asset_file_path = os.path.abspath(
os.path.join(os.path.dirname(__file__), "../assets/synthetic_500_quarterly_results.csv")
)
# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"
# Create clients to call Foundry API
project = AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()
# Upload the CSV file for the code interpreter to use
file = openai.files.create(purpose="assistants", file=open(asset_file_path, "rb"))
# Create agent with code interpreter tool
agent = project.agents.create_version(
agent_name="MyAgent",
definition=PromptAgentDefinition(
model="gpt-5-mini",
instructions="You are a helpful assistant.",
tools=[CodeInterpreterTool(container=AutoCodeInterpreterToolParam(file_ids=[file.id]))],
),
description="Code interpreter agent for data analysis and visualization.",
)
# Create a conversation for the agent interaction
conversation = openai.conversations.create()
# Send request to create a chart and generate a file
response = openai.responses.create(
conversation=conversation.id,
input="Could you please create bar chart in TRANSPORTATION sector for the operating profit from the uploaded csv file and provide file to me?",
extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
)
# Extract file information from response annotations
file_id = ""
filename = ""
container_id = ""
# Get the last message which should contain file citations
last_message = response.output[-1] # ResponseOutputMessage
if (
last_message.type == "message"
and last_message.content
and last_message.content[-1].type == "output_text"
and last_message.content[-1].annotations
):
file_citation = last_message.content[-1].annotations[-1] # AnnotationContainerFileCitation
if file_citation.type == "container_file_citation":
file_id = file_citation.file_id
filename = file_citation.filename
container_id = file_citation.container_id
print(f"Found generated file: {filename} (ID: {file_id})")
# Clean up resources
project.agents.delete_version(agent_name=agent.name, agent_version=agent.version)
# Download the generated file if available
if file_id and filename:
file_content = openai.containers.files.content.retrieve(file_id=file_id, container_id=container_id)
print(f"File ready for download: {filename}")
file_path = os.path.join(os.path.dirname(__file__), filename)
with open(file_path, "wb") as f:
f.write(file_content.read())
print(f"File downloaded successfully: {file_path}")
else:
print("No file generated in response")
预期输出
示例代码生成类似于以下示例的输出:
Found generated file: transportation_operating_profit_bar_chart.png (ID: file-xxxxxxxxxxxxxxxxxxxx)
File ready for download: transportation_operating_profit_bar_chart.png
File downloaded successfully: transportation_operating_profit_bar_chart.png
代理将 CSV 文件上传到Azure存储、创建沙盒Python环境、分析数据以筛选运输部门记录、生成按季度显示营业利润的 PNG 条形图,并将图表下载到本地目录。 响应中的文件注释提供检索生成的图表所需的文件 ID 和容器信息。
在 C 中使用代码解释器创建图表#
以下 C# 示例演示如何将代码解释器工具添加到工具箱、将工具箱附加到代理、上传 CSV 文件进行分析以及下载生成的图表。 选择 Prompt Agents以使用 Azure AI Projects SDK 创建服务器端提示代理,或托管代理使用 Microsoft Agent Framework 生成临时进程内代理。
有关异步用法,请参阅 代码示例,在GitHub上的.NET存储库中找到Azure SDK。
using System;
using System.IO;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;
using OpenAI.Files;
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
var projectEndpoint = "your_project_endpoint";
// Create project client to call Foundry API
AIProjectClient projectClient = new(
endpoint: new Uri(projectEndpoint),
tokenProvider: new DefaultAzureCredential());
// Upload a CSV file for Code Interpreter to analyze
OpenAIFileClient fileClient = projectClient.ProjectOpenAIClient.GetOpenAIFileClient();
OpenAIFile uploadedFile = fileClient.UploadFile(
filePath: "synthetic_500_quarterly_results.csv",
purpose: FileUploadPurpose.Assistants);
Console.WriteLine($"Uploaded file: {uploadedFile.Id}");
// Create an agent with Code Interpreter enabled
DeclarativeAgentDefinition agentDefinition = new(model: "gpt-5-mini")
{
Instructions = "You are a helpful assistant.",
Tools = {
ResponseTool.CreateCodeInterpreterTool(
new CodeInterpreterToolContainer(
CodeInterpreterToolContainerConfiguration.CreateAutomaticContainerConfiguration(
fileIds: [uploadedFile.Id]
)
)
),
}
};
ProjectsAgentVersion agentVersion = projectClient.AgentAdministrationClient.CreateAgentVersion(
agentName: "myChartAgent",
options: new(agentDefinition));
// Request chart generation from the uploaded CSV data
AgentReference agentReference = new(name: agentVersion.Name, version: agentVersion.Version);
ProjectResponsesClient responseClient = projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentReference);
ResponseResult response = responseClient.CreateResponse(
"Could you please create bar chart in TRANSPORTATION sector for the operating profit " +
"from the uploaded csv file and provide file to me?");
Console.WriteLine(response.GetOutputText());
// Extract file information from response annotations
ContainerFileCitationMessageAnnotation containerAnnotation = null;
foreach (ResponseItem item in response.OutputItems)
{
if (item is MessageResponseItem messageItem)
{
foreach (ResponseContentPart content in messageItem.Content)
{
foreach (ResponseMessageAnnotation annotation in content.OutputTextAnnotations)
{
if (annotation is ContainerFileCitationMessageAnnotation cntrAnnotation)
{
containerAnnotation = cntrAnnotation;
}
}
}
}
}
// Download the generated chart if available
if (containerAnnotation is not null)
{
ContainerClient containerClient = projectClient.ProjectOpenAIClient.GetContainerClient();
BinaryData fileData = containerClient.DownloadContainerFile(
containerId: containerAnnotation.ContainerId,
fileId: containerAnnotation.FileId);
File.WriteAllBytes("chart.png", fileData.ToArray());
Console.WriteLine($"Chart downloaded: {Path.GetFullPath("chart.png")}");
}
else
{
Console.WriteLine("No file generated in response");
}
// Clean up resources
projectClient.AgentAdministrationClient.DeleteAgentVersion(
agentName: agentVersion.Name, agentVersion: agentVersion.Version);
预期输出
示例代码生成类似于以下示例的输出:
Uploaded file: file-xxxxxxxxxxxxxxxxxxxx
Here is the bar chart showing operating profit by quarter in the TRANSPORTATION sector...
Chart downloaded: C:\Users\you\chart.png
代理将 CSV 文件上传到Azure存储,创建沙盒Python环境,分析数据以筛选运输扇区记录,并生成 PNG 条形图。 批注分析从响应中提取容器 ID 和文件 ID,用于将图表下载到本地目录。
在 TypeScript SDK 中将代理与代码解释器工具配合使用的示例
以下 TypeScript 示例演示如何将代码解释器工具添加到工具箱、将工具箱附加到代理、上传 CSV 文件进行分析,以及基于数据请求条形图。 有关 JavaScript 版本,请参阅 GitHub 上的 javaScript 存储库Azure SDK中的 JavaScript 示例。
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
import * as fs from "fs";
import * as path from "path";
import { fileURLToPath } from "url";
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
// Helper to resolve asset file path
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export async function main(): Promise<void> {
// Create clients to call Foundry API
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = project.getOpenAIClient();
// Load and upload CSV file
const assetFilePath = path.resolve(
__dirname,
"../assets/synthetic_500_quarterly_results.csv",
);
const fileStream = fs.createReadStream(assetFilePath);
// Upload CSV file
const uploadedFile = await openai.files.create({
file: fileStream,
purpose: "assistants",
});
console.log("Creating a toolbox with the code interpreter tool...");
// 1. Add the code interpreter tool to a toolbox. Using a toolbox is the recommended
// way to give agents tools. See /azure/foundry/agents/concepts/toolbox-overview
const toolbox = await project.toolboxes.createVersion(
"code-interpreter-toolbox",
[
{
type: "code_interpreter",
container: {
type: "auto",
file_ids: [uploadedFile.id],
},
},
],
{ description: "Toolbox with the code interpreter tool" },
);
// 2. The toolbox exposes an MCP-compatible endpoint.
const toolboxMcpUrl =
`${PROJECT_ENDPOINT}/toolboxes/${toolbox.name}` +
`/versions/${toolbox.version}/mcp?api-version=v1`;
// 3. Create a remote-tool project connection that points at the toolbox endpoint.
// Use a user Entra token so the caller's identity is passed through
// (audience https://ai.azure.com). Create the connection once, for example
// with the Azure Developer CLI:
//
// azd ai connection create code-interpreter-toolbox-conn \
// --kind remote-tool \
// --target "<toolboxMcpUrl>" \
// --auth-type user-entra-token \
// --audience https://ai.azure.com
const toolboxConnectionName = "code-interpreter-toolbox-conn";
// 4. Attach the toolbox to a prompt agent as an MCP tool.
const agent = await project.agents.createVersion("MyAgent", {
kind: "prompt",
model: "gpt-5-mini",
instructions: "You are a helpful assistant.",
tools: [
{
type: "mcp",
server_label: "toolbox",
server_url: toolboxMcpUrl,
require_approval: "never",
project_connection_id: toolboxConnectionName,
},
],
});
// Create a conversation
const conversation = await openai.conversations.create();
// Request chart generation
const response = await openai.responses.create(
{
conversation: conversation.id,
input:
"Could you please create bar chart in TRANSPORTATION sector for the operating profit from the uploaded csv file and provide file to me?",
},
{
body: { agent: { name: agent.name, type: "agent_reference" } },
},
);
// Extract file information from response annotations
let fileId = "";
let filename = "";
let containerId = "";
// Get the last message which should contain file citations
const lastMessage = response.output?.[response.output.length - 1];
if (lastMessage && lastMessage.type === "message") {
// Get the last content item
const textContent = lastMessage.content?.[lastMessage.content.length - 1];
if (textContent && textContent.type === "output_text" && textContent.annotations) {
// Get the last annotation (most recent file)
const fileCitation = textContent.annotations[textContent.annotations.length - 1];
if (fileCitation && fileCitation.type === "container_file_citation") {
fileId = fileCitation.file_id;
filename = fileCitation.filename;
containerId = fileCitation.container_id;
console.log(`Found generated file: ${filename} (ID: ${fileId})`);
}
}
}
// Download the generated file if available
if (fileId && filename) {
const safeFilename = path.basename(filename);
const fileContent = await openai.containers.files.content.retrieve({
file_id: fileId,
container_id: containerId,
});
// Read the readable stream into a buffer
const chunks: Buffer[] = [];
for await (const chunk of fileContent.body) {
chunks.push(Buffer.from(chunk));
}
const buffer = Buffer.concat(chunks);
fs.writeFileSync(safeFilename, buffer);
console.log(`File ${safeFilename} downloaded successfully.`);
console.log(`File ready for download: ${safeFilename}`);
} else {
console.log("No file generated in response");
}
// Clean up resources
await project.agents.deleteVersion(agent.name, agent.version);
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
预期输出
示例代码生成类似于以下示例的输出:
Found generated file: transportation_operating_profit_bar_chart.png (ID: file-xxxxxxxxxxxxxxxxxxxx)
File transportation_operating_profit_bar_chart.png downloaded successfully.
File ready for download: transportation_operating_profit_bar_chart.png
代理将 CSV 文件上传到Azure存储、创建沙盒Python环境、分析数据以筛选运输部门记录、生成按季度显示营业利润的 PNG 条形图,并将图表下载到本地目录。 响应中的文件注释提供检索生成的图表所需的文件 ID 和容器信息。
在 Java 中使用代码解释器创建图表
对于大多数代理,请通过 工具箱 添加代码解释器工具,并将工具箱作为 MCP 工具附加到代理。 Java SDK 尚未公开工具箱创建 API,因此请使用当前支持的方法之一(Python、REST API、C#、TypeScript 或 Foundry 门户)创建工具箱。 创建工具箱后,从Java代理引用其 MCP 终结点作为一个 McpTool。 以下示例将代码解释器工具箱 MCP 终结点附加到代理。
将依赖项添加到pom.xml:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-agents</artifactId>
<version>2.2.0</version>
</dependency>
创建代理并生成图表
import com.azure.ai.agents.AgentsClient;
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.ResponsesClient;
import com.azure.ai.agents.models.AgentReference;
import com.azure.ai.agents.models.AgentVersionDetails;
import com.azure.ai.agents.models.AzureCreateResponseOptions;
import com.azure.ai.agents.models.McpTool;
import com.azure.ai.agents.models.PromptAgentDefinition;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import java.util.Collections;
public class CodeInterpreterChartExample {
public static void main(String[] args) {
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
String projectEndpoint = "your_project_endpoint";
String toolboxMcpUrl = projectEndpoint
+ "/toolboxes/code-interpreter-toolbox/versions/1/mcp?api-version=v1";
String toolboxConnectionName = "code-interpreter-toolbox-conn";
AgentsClientBuilder builder = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint);
AgentsClient agentsClient = builder.buildAgentsClient();
ResponsesClient responsesClient = builder.buildResponsesClient();
// The Java SDK doesn't yet expose a toolbox creation API. Create the
// code-interpreter toolbox with Python, REST, C#, TypeScript, or the
// Foundry portal, then attach its MCP endpoint as an MCP tool.
McpTool toolboxTool = new McpTool("toolbox")
.setServerUrl(toolboxMcpUrl)
.setProjectConnectionId(toolboxConnectionName)
.setRequireApproval("never");
// Create agent with the code-interpreter toolbox MCP tool
PromptAgentDefinition agentDefinition = new PromptAgentDefinition("gpt-5-mini")
.setInstructions("You are a data visualization assistant. When asked to create charts, "
+ "write and run Python code using matplotlib to generate them.")
.setTools(Collections.singletonList(toolboxTool));
AgentVersionDetails agent = agentsClient.createAgentVersion("chart-agent", agentDefinition);
// Request a bar chart with inline data
AgentReference agentReference = new AgentReference(agent.getName())
.setVersion(agent.getVersion());
Response response = responsesClient.createAzureResponse(
new AzureCreateResponseOptions().setAgentReference(agentReference),
ResponseCreateParams.builder()
.input("Create a bar chart showing quarterly revenue for 2025: "
+ "Q1=$2.1M, Q2=$2.8M, Q3=$3.2M, Q4=$2.9M. "
+ "Use a blue color scheme, add data labels on each bar, "
+ "and title the chart 'Quarterly Revenue 2025'. "
+ "Save the chart as a PNG file."));
System.out.println("Response: " + response.output());
// Clean up
agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion());
}
}
预期输出
Response: Here is the bar chart showing quarterly revenue for 2025 with Q1 ($2.1M), Q2 ($2.8M), Q3 ($3.2M), and Q4 ($2.9M) displayed in blue with data labels.
代理通过工具箱 MCP 终结点使用代码解释器,使用 matplotlib 编写Python代码来生成图表,并在沙盒环境中执行代码。 有关上传 CSV 文件并下载生成的图表的示例,请从本文顶部的语言选择器中选择 Python 或 TypeScript。 有关更多示例,请参阅 Azure AI 代理Java SDK 示例。
使用 REST API 通过代码解释器创建图表
以下示例演示如何上传 CSV 文件、使用代码解释器创建代理、请求图表以及下载生成的文件。
先决条件
设置以下环境变量:
-
FOUNDRY_PROJECT_ENDPOINT:项目终结点 URL。 -
AGENT_TOKEN:Foundry 的持有者令牌。
获取访问令牌:
export AGENT_TOKEN=$(az account get-access-token --scope "https://ai.azure.com/.default" --query accessToken -o tsv)
在工具箱中使用代码解释器
若要上传供 Code Interpreter 通过工具箱使用的文件,请使用 标头,将文件上传到 POST {account_endpoint}/openai/v1/files Files 端点(x-aml-project-id)。 与提示词代理流程不同,通过项目范围的 Files 端点(/api/projects/{name}/openai/v1/files)上传的文件会收到一个工具箱容器无法验证的 owner_id,因此 tools/call 会因所有权验证错误而失败。
从Azure 资源管理器获取项目 GUID。 使用
properties.amlWorkspace.internalId(带连字符的 UUID 格式),不要使用properties.internalId(无连字符——toolbox 容器不接受这种格式):ARM_TOKEN=$(az account get-access-token --query accessToken -o tsv) PROJECT_GUID=$(curl -s -H "Authorization: ******" \ "https://management.azure.com/subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.CognitiveServices/accounts/{account}/projects/{project}?api-version=2025-06-01" \ | jq -r '.properties.amlWorkspace.internalId')使用
x-aml-project-id标头在帐户(资源)级别上传文件:TOKEN=$(az account get-access-token --resource https://ai.azure.com/.default --query accessToken -o tsv) curl -X POST "https://{account}.services.ai.azure.com/openai/v1/files" \ -H "Authorization: ******" \ -H "x-aml-project-id: $PROJECT_GUID" \ -F "purpose=assistants" \ -F "file=@your-file.csv"
返回的文件 id 就是你在工具配置中为 <FILE_ID> 提供的值。 文件挂载在沙盒中的 /mnt/data/{file-id}-{original-filename}。
重要
当代码解释器通过托管代理中的工具箱使用时, 不支持用户隔离。 同一项目中的所有用户共享相同的容器上下文。
1.上传 CSV 文件
curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/files" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-F "purpose=assistants" \
-F "file=@quarterly_results.csv"
请保存来自响应中的id(例如file-abc123)。
2. 将代码解释器添加到工具箱
通过创建工具箱添加代码解释器,然后将工具箱作为 MCP 工具附加到代理。 有关详细信息,请参阅 什么是工具箱?
创建包含代码解释器工具的工具箱:
curl --request POST \ --url "$FOUNDRY_PROJECT_ENDPOINT/toolboxes/code-interpreter-toolbox/versions?api-version=v1" \ -H "Content-Type: application/json" \ --data '{ "description": "Toolbox with the code interpreter tool", "tools": [ { "type": "code_interpreter", "container": { "type": "auto", "file_ids": ["<FILE_ID>"] } } ] }'工具箱公开了 MCP 兼容的终结点,该终结点
$FOUNDRY_PROJECT_ENDPOINT/toolboxes/code-interpreter-toolbox/versions/<version>/mcp?api-version=v1是<version>上一次调用返回的版本。使用用户 Entra 令牌创建指向工具箱终结点的远程工具项目连接,以便调用方的身份通过(受众
https://ai.azure.com) 传递。azd ai connection create code-interpreter-toolbox-conn \ --kind remote-tool \ --target "$FOUNDRY_PROJECT_ENDPOINT/toolboxes/code-interpreter-toolbox/versions/<version>/mcp?api-version=v1" \ --auth-type user-entra-token \ --audience https://ai.azure.com
3. 使用代码解释器工具箱创建代理
curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/agents?api-version=v1" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-d '{
"name": "chart-agent",
"definition": {
"kind": "prompt",
"model": "<MODEL_DEPLOYMENT>",
"instructions": "You are a data visualization assistant. When asked to create charts, write and run Python code using matplotlib to generate them.",
"tools": [
{
"type": "mcp",
"server_label": "toolbox",
"server_url": "'$FOUNDRY_PROJECT_ENDPOINT'/toolboxes/code-interpreter-toolbox/versions/<version>/mcp?api-version=v1",
"require_approval": "never",
"project_connection_id": "code-interpreter-toolbox-conn"
}
]
}
}'
4. 生成图表
curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-d '{
"agent_reference": {"type": "agent_reference", "name": "chart-agent"},
"input": "Create a bar chart of operating profit by quarter from the uploaded CSV file. Use a blue color scheme and add data labels."
}'
响应包含附有生成的文件详细信息的container_file_citation注释。 保存container_id和file_id值来自批注。
5. 下载生成的图表
curl -X GET "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/containers/<CONTAINER_ID>/files/<FILE_ID>/content" \
-H "Authorization: Bearer $AGENT_TOKEN" \
--output chart.png
6. 清理
curl -X DELETE "$FOUNDRY_PROJECT_ENDPOINT/agents/chart-agent?api-version=v1" \
-H "Authorization: Bearer $AGENT_TOKEN"
检查区域和模型可用性
工具可用性因区域和模型而异。
有关代码解释器的受支持区域和模型的当前列表,请参阅 有关在 Microsoft Foundry 代理服务中使用工具的最佳做法。
支持的文件类型
| 文件格式 | MIME 类型 |
|---|---|
.c |
text/x-c |
.cpp |
text/x-c++ |
.csv |
application/csv |
.docx |
application/vnd.openxmlformats-officedocument.wordprocessingml.document |
.html |
text/html |
.java |
text/x-java |
.json |
application/json |
.md |
text/markdown |
.pdf |
application/pdf |
.php |
text/x-php |
.pptx |
application/vnd.openxmlformats-officedocument.presentationml.presentation |
.py |
text/x-python |
.py |
text/x-script.python |
.rb |
text/x-ruby |
.tex |
text/x-tex |
.txt |
text/plain |
.css |
text/css |
.jpeg |
image/jpeg |
.jpg |
image/jpeg |
.js |
text/javascript |
.gif |
image/gif |
.png |
image/png |
.tar |
application/x-tar |
.ts |
application/typescript |
.xlsx |
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
.xml |
application/xml 或 text/xml |
.zip |
application/zip |
故障 排除
| 问题 | 可能的原因 | 分辨率 |
|---|---|---|
| 代码解释器未运行。 | 工具未启用或模型在你的区域中不支持它。 | 确认代理上已启用代码解释器。 验证模型部署是否支持区域中的工具。 请参阅 “检查区域和模型可用性”。 |
| 未生成任何文件。 | 代理返回了不包含文件注释的仅限文本的响应。 | 检查container_file_citation的响应批注. 如果不存在,代理未生成文件。 重新表述提示,以明确请求文件输出。 |
| 文件上传失败。 | 不支持的文件类型或错误的用途。 | 确认文件类型位于 支持的文件类型 列表中。 使用purpose="assistants"进行上传。 |
| 生成的文件已损坏或为空。 | 代码执行错误或处理不完整。 | 检查智能体响应中的错误消息。 验证输入数据是否有效。 首先尝试更简单的请求。 |
| 会话超时或高延迟。 | 代码解释器会话具有时间限制。 | 会话具有 1 小时的活动超时和 30 分钟的空闲超时。 减少操作的复杂性或拆分为较小的任务。 |
| 意外的计费费用。 | 创建了多个并发会话。 | 每个对话都会创建一个单独的会话。 尽可能监视会话使用情况并合并操作。 |
| Python包不可用。 | 代码解释器有一组固定的包。 | 代码解释器包括常见的数据科学包。 对于自定义包,请使用 自定义代码解释器。 |
| 文件下载失败。 | 容器 ID 或文件 ID 不正确。 | 请验证您是否在响应批注中使用了正确的 container_id 和 file_id。 |
清理资源
不再需要资源来避免持续成本时,请删除此示例中创建的资源:
- 删除代理版本。
- 删除对话。
- 删除上传的文件。
有关聊天和文件清理模式的示例,请参阅代理的 Web 搜索工具和文件搜索工具。
沙盒执行环境
代码解释器在Microsoft管理的沙盒中运行Python代码。 沙盒旨在运行不受信任的代码,并在 Azure 容器应用中使用动态会话(代码解释器会话)。 每个会话都由 Hyper-V 边界隔离。
要规划的主要行为:
- Region:代码解释器沙盒与 Foundry 项目在同一Azure区域中运行。
- 会话生命周期:代码解释器会话最多活跃一小时,并具有空闲超时(请参阅本文开头的“重要信息”说明)。
- 隔离:每个会话在隔离的环境中运行。 如果代理在不同的会话中并发调用代码解释器,则创建单独的会话。
- 网络隔离和 Internet 访问:沙盒不会继承代理子网配置,动态会话无法发出出站网络请求。
- 沙盒中的文件:沙盒Python运行时有权访问附加的文件进行分析。 代码解释器还可以生成文件(如图表),并将它们作为可下载的输出返回。
如果需要对沙盒运行时进行更多控制,或者需要其他隔离模型,请参阅 代理的自定义代码解释器工具。