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

代理人代码解释器工具

从本文中,您可以学习如何使用智能代理的代码解释器工具。

代码解释器使代理能够在沙盒执行环境中编写和运行 Python 代码。 启用代码解释器后,代理可以迭代运行代码,以解决更具挑战性的代码、数学和数据分析问题,或者创建图形和图表。 当代理编写未运行的代码时,它可以修改并运行不同的代码,直到代码执行成功。

重要

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

先决条件

注释

某些 区域不提供代码解释器工具。

代码示例

注释

需要最新的预发行版包。 有关详细信息,请参阅 快速入门

import os
import httpx
from dotenv import load_dotenv
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition, CodeInterpreterTool, CodeInterpreterToolAuto

load_dotenv()

# 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")
)

project_client = AIProjectClient(
    endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
    credential=DefaultAzureCredential(),
)

with project_client:
    openai_client = project_client.get_openai_client()

    # Upload the CSV file for the code interpreter to use
    file = openai_client.files.create(purpose="assistants", file=open(asset_file_path, "rb"))
    print(f"File uploaded (id: {file.id})")

    # Create agent with code interpreter tool
    agent = project_client.agents.create_version(
        agent_name="MyAgent",
        definition=PromptAgentDefinition(
            model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
            instructions="You are a helpful assistant.",
            tools=[CodeInterpreterTool(container=CodeInterpreterToolAuto(file_ids=[file.id]))],
        ),
        description="Code interpreter agent for data analysis and visualization.",
    )
    print(f"Agent created (id: {agent.id}, name: {agent.name}, version: {agent.version})")

    # Create a conversation for the agent interaction
    conversation = openai_client.conversations.create()
    print(f"Created conversation (id: {conversation.id})")

    # Send request to create a chart and generate a file
    response = openai_client.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": {"name": agent.name, "type": "agent_reference"}},
    )
    print(f"Response completed (id: {response.id})")

    # 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":
        # Get the last content item (contains the file annotations)
        text_content = last_message.content[-1]  # ResponseOutputText
        if text_content.type == "output_text":
            # Get the last annotation (most recent file)
            if text_content.annotations:
                file_citation = text_content.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})")

    # Download the generated file if available
    if file_id and filename:
        file_content = openai_client.containers.files.content.retrieve(file_id=file_id, container_id=container_id)
        with open(filename, "wb") as f:
            f.write(file_content.read())
            print(f"File {filename} downloaded successfully.")
        print(f"File ready for download: {filename}")
    else:
        print("No file generated in response")
    #uncomment these lines if you want to delete your agent
    #print("\nCleaning up...")
    #project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version)
    #print("Agent deleted")

有关 C# 使用,请参阅 GitHub 上的 .NET Azure SDK 仓库中的 Azure.AI.Projects.OpenAI 示例中关于在代码解释器和文件附件中使用代理的示例

区域限制

Foundry 项目(新)API 的代码解释器工具在以下区域中不可用:

  • 加拿大中部
  • 美国中部
  • 日本东部
  • 美国中南部
  • 东南亚
  • 西班牙中部

支持的文件类型

文件格式 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