你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

Azure AI 代理服务代码解释器

借助代码解释器,代理可以在沙盒化执行环境中编写和运行 Python 代码。 启用代码解释器后,代理可以迭代运行代码,以解决更具挑战性的代码、数学和数据分析问题。 如果代理编写了无法运行的代码,它可以通过修改并运行不同的代码来循环访问此代码,直到代码执行成功。

重要

除了与使用 Azure OpenAI 相关的基于令牌的费用之外,代码解释器还有额外的费用。 如果代理在两个不同的线程中同时调用代码解释器,则会创建两个代码解释器会话。 默认情况下,每个会话处于活动状态一小时。

支持的模型

模型页包含有关支持代理和代码解释器的区域/模型的最新信息。

建议使用具有最新模型的代理来利用新功能、更大的上下文窗口和更新的训练数据。

使用支持

Azure AI Foundry 支持 Python SDK C# SDK JavaScript SDK REST API 基本代理设置 标准代理设置
✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️

将代码解释器工具与代理配合使用

可以使用本文顶部列出的代码示例或 Azure AI Foundry 门户以编程方式将代码解释器工具添加到代理。 如果要使用门户:

  1. 在代理的“创建和调试”屏幕中,向下滚动右侧的“设置”窗格以转到“操作”。 然后选择“添加”。

    显示 Azure AI Foundry 门户中可用工具类别的屏幕截图。

  2. 选择“代码解释器”,然后按照提示添加该工具。

    显示 Azure AI Foundry 门户中可用的操作工具的屏幕截图。

  3. 可以选择上传文件,以供代理从数据集读取和解释信息、生成代码,以及使用数据创建图形和图表。

    显示代码解释器上传页的屏幕截图。

创建项目客户端

要使用代码解释器,请先添加示例中所示的 import 语句,并创建一个项目客户端,其中包含 AI 项目的连接字符串,并将用于对 API 调用进行身份验证。

import os
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import CodeInterpreterTool
from azure.ai.projects.models import FilePurpose
from azure.identity import DefaultAzureCredential
from pathlib import Path

# Create an Azure AI Client from a connection string, copied from your Azure AI Foundry project.
# At the moment, it should be in the format "<HostName>;<AzureSubscriptionId>;<ResourceGroup>;<HubName>"
# Customer needs to login to Azure subscription via Azure CLI and set the environment variables
project_client = AIProjectClient.from_connection_string(
    credential=DefaultAzureCredential(), conn_str=os.environ["PROJECT_CONNECTION_STRING"]
)

上传文件

使用 upload_and_poll() 函数上传文件,以指定文件路径和 FilePurpose.AGENTS 用途。

# Upload a file and add it to the client 
file = project_client.agents.upload_file_and_poll(
    file_path="nifty_500_quarterly_results.csv", purpose=FilePurpose.AGENTS
)
print(f"Uploaded file, file ID: {file.id}")

使用代码解释器工具创建代理

使用 CodeInterpreterTool() 定义 code_interpreter 工具,并包括所上传文件的文件 ID。 之后,创建将 tools 设为 code_interpreter.definitions,并将 tool_resources 设为 code_interpreter.resources 的代理。


code_interpreter = CodeInterpreterTool(file_ids=[file.id])

# create agent with code interpreter tool and tools_resources
agent = project_client.agents.create_agent(
    model="gpt-4o-mini",
    name="my-agent",
    instructions="You are helpful agent",
    tools=code_interpreter.definitions,
    tool_resources=code_interpreter.resources,
)

创建线程、消息并获取代理响应

接下来,使用 create_thread() 创建线程,并使用将触发代码解释器工具的 create_message() 将消息附加到该线程。 之后,使用 create_and_process_run() 创建并执行运行。 运行完成后,可以使用 delete_file() 从代理中删除该文件,以释放代理中的空间。 最后,打印来自代理的消息。

# create a thread
thread = project_client.agents.create_thread()
print(f"Created thread, thread ID: {thread.id}")

# create a message
message = project_client.agents.create_message(
    thread_id=thread.id,
    role="user",
    content="Could you please create bar chart in the TRANSPORTATION sector for the operating profit from the uploaded csv file and provide file to me?",
)
print(f"Created message, message ID: {message.id}")

# create and execute a run
run = project_client.agents.create_and_process_run(thread_id=thread.id, assistant_id=agent.id)
print(f"Run finished with status: {run.status}")

if run.status == "failed":
    # Check if you got "Rate limit is exceeded.", then you want to get more quota
    print(f"Run failed: {run.last_error}")

# delete the original file from the agent to free up space (note: this does not delete your version of the file)
project_client.agents.delete_file(file.id)
print("Deleted file")

# print the messages from the agent
messages = project_client.agents.list_messages(thread_id=thread.id)
print(f"Messages: {messages}")

# get the most recent message from the assistant
last_msg = messages.get_last_text_message_by_sender("assistant")
if last_msg:
    print(f"Last Message: {last_msg.text.value}")

下载代码解释器生成的文件

可以在代理消息响应中查找代码解释器生成的文件。 可以通过循环访问响应的 image_contents 并使用名称和文件 ID 调用 save_file() 来下载代码解释器生成的映像文件。

# save the newly created file
for image_content in messages.image_contents:
  print(f"Image File ID: {image_content.image_file.file_id}")
  file_name = f"{image_content.image_file.file_id}_image_file.png"
  project_client.agents.save_file(file_id=image_content.image_file.file_id, file_name=file_name)
  print(f"Saved image file to: {Path.cwd() / file_name}") 

支持的文件类型

文件格式 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/xmltext/xml
.zip application/zip

另请参阅