Udostępnij za pośrednictwem


Jak używać narzędzia interpretera kodu

Usługa Azure AI Agents obsługuje korzystanie z narzędzia Code Interpreter, które umożliwia agentowi pisanie i uruchamianie kodu w bezpiecznym środowisku wykonawczym w trybie piaskownicy. Dzięki temu agent może wykonywać zadania, takie jak analiza danych, obliczenia matematyczne lub manipulowanie plikami na podstawie żądań użytkowników. Ten artykuł zawiera instrukcje krok po kroku i przykłady kodu umożliwiające włączanie i używanie narzędzia interpretera kodu za pomocą agenta usługi Azure AI.

Używanie narzędzia interpretera kodu z agentem

Narzędzie interpretera kodu można dodać do agenta programowo przy użyciu przykładów kodu wymienionych w górnej części tego artykułu lub portalu Azure AI Foundry. Jeśli chcesz użyć portalu:

  1. Na ekranie Agent dla Twojego agenta, przewiń w dół okienko Ustawienia po prawej stronie do akcje. Następnie wybierz pozycję Dodaj.

    Zrzut ekranu przedstawiający dostępne kategorie narzędzi w portalu usługi Azure AI Foundry.

  2. Wybierz pozycję Interpreter kodu i postępuj zgodnie z monitami, aby dodać narzędzie.

    Zrzut ekranu przedstawiający dostępne narzędzia akcji w portalu usługi Azure AI Foundry.

  3. Opcjonalnie możesz przekazać pliki agenta, aby odczytywać i interpretować informacje z zestawów danych, generować kod oraz tworzyć grafy i wykresy przy użyciu danych.

    Zrzut ekranu przedstawiający stronę przekazywania interpretera kodu.

Inicjalizacja

Kod rozpoczyna się od skonfigurowania niezbędnych importów i zainicjowania klienta projektu sztucznej inteligencji:

import os
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
from azure.ai.agents.models import CodeInterpreterTool


# Create an Azure AI Client from an endpoint, copied from your Azure AI Foundry project.
# You need to login to Azure subscription via Azure CLI and set the environment variables
project_endpoint = os.environ["PROJECT_ENDPOINT"]  # Ensure the PROJECT_ENDPOINT environment variable is set

# Create an AIProjectClient instance
project_client = AIProjectClient(
    endpoint=project_endpoint,
    credential=DefaultAzureCredential(),  # Use Azure Default Credential for authentication
)

Przekazywanie plików

Przykład uploaduje plik danych do analizy:

file = project_client.agents.upload_file_and_poll(
    file_path="nifty_500_quarterly_results.csv", 
    purpose=FilePurpose.AGENTS
)

Konfiguracja interpretera kodu

Narzędzie Interpreter kodu jest inicjowane za pomocą przekazanego pliku:

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

Tworzenie agenta

Agent jest tworzony za pomocą funkcji interpretera kodu:

agent = project_client.agents.create_agent(
    model=os.environ["MODEL_DEPLOYMENT_NAME"],
    name="my-agent",
    instructions="You are helpful agent",
    tools=code_interpreter.definitions,
    tool_resources=code_interpreter.resources,
)

Zarządzanie wątkami

Kod tworzy wątek konwersacji i początkową wiadomość:

thread = project_client.agents.threads.create()
message = project_client.agents.messages.create(
    thread_id=thread.id,
    role=MessageRole.USER,
    content="Could you please create bar chart in TRANSPORTATION sector for the operating profit from the uploaded csv file and provide file to me?",
)

Przetwarzanie komunikatów

Zostanie utworzony przebieg w celu przetworzenia komunikatu i wykonania kodu:

run = project_client.agents.runs.create_and_process(thread_id=thread.id, agent_id=agent.id)

Obsługa plików

Kod obsługuje pliki wyjściowe i adnotacje:

messages = project_client.agents.messages.list(thread_id=thread.id)

# Save generated image files
for image_content in messages.image_contents:
    file_id = image_content.image_file.file_id
    file_name = f"{file_id}_image_file.png"
    project_client.agents.save_file(file_id=file_id, file_name=file_name)

# Process file path annotations
for file_path_annotation in messages.file_path_annotations:
    print(f"File Paths:")
    print(f"Type: {file_path_annotation.type}")
    print(f"Text: {file_path_annotation.text}")
    print(f"File ID: {file_path_annotation.file_path.file_id}")

Sprzątanie

Po zakończeniu interakcji kod prawidłowo czyści zasoby:

project_client.agents.delete_file(file.id)
project_client.agents.delete_agent(agent.id)

Zapewnia to właściwe zarządzanie zasobami i zapobiega niepotrzebnemu użyciu zasobów.

Tworzenie klienta i agenta

Najpierw skonfiguruj system za pomocą appsettings.json, utwórz element PersistentAgentsClient, a następnie utwórz element PersistentAgent z włączoną opcją interpretera kodu.

using Azure;
using Azure.AI.Agents.Persistent;
using Azure.Identity;
using Microsoft.Extensions.Configuration;
using System.Diagnostics;

IConfigurationRoot configuration = new ConfigurationBuilder()
    .SetBasePath(AppContext.BaseDirectory)
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .Build();

var projectEndpoint = configuration["ProjectEndpoint"];
var modelDeploymentName = configuration["ModelDeploymentName"];

PersistentAgentsClient client = new(projectEndpoint, new DefaultAzureCredential());

PersistentAgent agent = client.Administration.CreateAgent(
    model: modelDeploymentName,
    name: "My Friendly Test Agent",
    instructions: "You politely help with math questions. Use the code interpreter tool when asked to visualize numbers.",
    tools: [new CodeInterpreterToolDefinition()]
);

Tworzenie wątku i dodawanie komunikatu

Następnie utwórz PersistentAgentThread element dla konwersacji i dodaj początkową wiadomość użytkownika.

PersistentAgentThread thread = client.Threads.CreateThread();

client.Messages.CreateMessage(
    thread.Id,
    MessageRole.User,
    "Hi, Agent! Draw a graph for a line with a slope of 4 and y-intercept of 9.");

Tworzenie i monitorowanie przebiegu

Następnie utwórz element ThreadRun dla wątku i agenta. Sonduj stan przebiegu, dopóki nie zostanie ukończony lub wymaga akcji.

ThreadRun run = client.Runs.CreateRun(
    thread.Id,
    agent.Id,
    additionalInstructions: "Please address the user as Jane Doe. The user has a premium account.");

do
{
    Thread.Sleep(TimeSpan.FromMilliseconds(500));
    run = client.Runs.GetRun(thread.Id, run.Id);
}
while (run.Status == RunStatus.Queued
    || run.Status == RunStatus.InProgress
    || run.Status == RunStatus.RequiresAction);

Przetwarzanie wyników i obsługa plików

Po zakończeniu przebiegu pobierz wszystkie komunikaty z wątku. Iteruj przez komunikaty w celu wyświetlenia zawartości tekstowej i obsłuż wszystkie wygenerowane pliki obrazów, zapisując je lokalnie i otwierając je.

Pageable<PersistentThreadMessage> messages = client.Messages.GetMessages(
    threadId: thread.Id,
    order: ListSortOrder.Ascending);

foreach (PersistentThreadMessage threadMessage in messages)
{
    foreach (MessageContent content in threadMessage.ContentItems)
    {
        switch (content)
        {
            case MessageTextContent textItem:
                Console.WriteLine($"[{threadMessage.Role}]: {textItem.Text}");
                break;
            case MessageImageFileContent imageFileContent:
                Console.WriteLine($"[{threadMessage.Role}]: Image content file ID = {imageFileContent.FileId}");
                BinaryData imageContent = client.Files.GetFileContent(imageFileContent.FileId);
                string tempFilePath = Path.Combine(AppContext.BaseDirectory, $"{Guid.NewGuid()}.png");
                File.WriteAllBytes(tempFilePath, imageContent.ToArray());
                client.Files.DeleteFile(imageFileContent.FileId);

                ProcessStartInfo psi = new()
                {
                    FileName = tempFilePath,
                    UseShellExecute = true
                };
                Process.Start(psi);
                break;
        }
    }
}

Uprzątnij zasoby

Na koniec usuń wątek i agenta, aby wyczyścić zasoby utworzone w tym przykładzie.

    client.Threads.DeleteThread(threadId: thread.Id);
    client.Administration.DeleteAgent(agentId: agent.Id);

Tworzenie klienta projektu

Aby użyć interpretera kodu, najpierw należy utworzyć klienta projektu, który będzie zawierać punkt końcowy w projekcie sztucznej inteligencji i będzie używany do uwierzytelniania wywołań interfejsu API.

const { AgentsClient, isOutputOfType, ToolUtility } = require("@azure/ai-agents");
const { delay } = require("@azure/core-util");
const { DefaultAzureCredential } = require("@azure/identity");
const fs = require("fs");
const path = require("node:path");
require("dotenv/config");

const projectEndpoint = process.env["PROJECT_ENDPOINT"];

// Create an Azure AI Client
const client = new AgentsClient(projectEndpoint, new DefaultAzureCredential());

Przekazywanie pliku

Pliki mogą być przekazywane, a następnie przywoływane przez agentów lub komunikaty. Po przekazaniu można go dodać do narzędzia narzędziowego w celu odwoływania się.

// Upload file and wait for it to be processed
const filePath = "./data/nifty500QuarterlyResults.csv";
const localFileStream = fs.createReadStream(filePath);
const localFile = await client.files.upload(localFileStream, "assistants", {
  fileName: "localFile",
});

console.log(`Uploaded local file, file ID : ${localFile.id}`);

Tworzenie agenta za pomocą narzędzia interpretera kodu

// Create code interpreter tool
const codeInterpreterTool = ToolUtility.createCodeInterpreterTool([localFile.id]);

// Notice that CodeInterpreter must be enabled in the agent creation, otherwise the agent will not be able to see the file attachment
const agent = await client.createAgent("gpt-4o", {
  name: "my-agent",
  instructions: "You are a helpful agent",
  tools: [codeInterpreterTool.definition],
  toolResources: codeInterpreterTool.resources,
});
console.log(`Created agent, agent ID: ${agent.id}`);

Tworzenie wątku, komunikatu i uzyskiwanie odpowiedzi agenta

// Create a thread
const thread = await client.threads.create();
console.log(`Created thread, thread ID: ${thread.id}`);

// Create a message
const message = await client.messages.create(
  thread.id,
  "user",
  "Could you please create a bar chart in the TRANSPORTATION sector for the operating profit from the uploaded CSV file and provide the file to me?",
  {
    attachments: [
      {
        fileId: localFile.id,
        tools: [codeInterpreterTool.definition],
      },
    ],
  },
);

console.log(`Created message, message ID: ${message.id}`);

// Create and execute a run
let run = await client.runs.create(thread.id, agent.id);
while (run.status === "queued" || run.status === "in_progress") {
  await delay(1000);
  run = await client.runs.get(thread.id, run.id);
}
if (run.status === "failed") {
  // Check if you got "Rate limit is exceeded.", then you want to get more quota
  console.log(`Run failed: ${run.lastError}`);
}
console.log(`Run finished with status: ${run.status}`);

// Delete the original file from the agent to free up space (note: this does not delete your version of the file)
await client.files.delete(localFile.id);
console.log(`Deleted file, file ID: ${localFile.id}`);

// Print the messages from the agent
const messagesIterator = client.messages.list(thread.id);
const allMessages = [];
for await (const m of messagesIterator) {
  allMessages.push(m);
}
console.log("Messages:", allMessages);

// Get most recent message from the assistant
const assistantMessage = allMessages.find((msg) => msg.role === "assistant");
if (assistantMessage) {
  const textContent = assistantMessage.content.find((content) => isOutputOfType(content, "text"));
  if (textContent) {
    console.log(`Last message: ${textContent.text.value}`);
  }
}

// Save the newly created file
console.log(`Saving new files...`);
const imageFile = allMessages[0].content[0].imageFile;
console.log(`Image file ID : ${imageFile.fileId}`);
const imageFileName = path.resolve(
  "./data/" + (await client.files.get(imageFile.fileId)).filename + "ImageFile.png",
);

const fileContent = await (await client.files.getContent(imageFile.fileId).asNodeStream()).body;
if (fileContent) {
  const chunks = [];
  for await (const chunk of fileContent) {
    chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  }
  const buffer = Buffer.concat(chunks);
  fs.writeFileSync(imageFileName, buffer);
} else {
  console.error("Failed to retrieve file content: fileContent is undefined");
}
console.log(`Saved image file to: ${imageFileName}`);

// Iterate through messages and print details for each annotation
console.log(`Message Details:`);
allMessages.forEach((m) => {
  console.log(`File Paths:`);
  console.log(`Type: ${m.content[0].type}`);
  if (isOutputOfType(m.content[0], "text")) {
    const textContent = m.content[0];
    console.log(`Text: ${textContent.text.value}`);
  }
  console.log(`File ID: ${m.id}`);
});

// Delete the agent once done
await client.deleteAgent(agent.id);
console.log(`Deleted agent, agent ID: ${agent.id}`);

Postępuj zgodnie z przewodnikiem Szybki start dotyczącym interfejsu API REST , aby ustawić odpowiednie wartości zmiennych środowiskowych AGENT_TOKENi AZURE_AI_FOUNDRY_PROJECT_ENDPOINTAPI_VERSION.

Przekazywanie pliku

curl --request POST \
  --url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/files?api-version=$API_VERSION \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -F purpose="assistants" \
  -F file="@c:\\path_to_file\\file.csv"

Tworzenie agenta za pomocą narzędzia interpretera kodu

curl --request POST \
  --url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/assistants?api-version=$API_VERSION \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "instructions": "You are an AI assistant that can write code to help answer math questions.",
    "tools": [
      { "type": "code_interpreter" }
    ],
    "model": "gpt-4o-mini",
    "tool_resources"{
      "code interpreter": {
          "file_ids": ["assistant-1234"]
      }
    }
  }'

Tworzenie wątku

curl --request POST \
  --url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads?api-version=$API_VERSION \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -H "Content-Type: application/json" \
  -d ''

Dodawanie pytania użytkownika do wątku

curl --request POST \
  --url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads/thread_abc123/messages?api-version=$API_VERSION \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
      "role": "user",
      "content": "I need to solve the equation `3x + 11 = 14`. Can you help me?"
    }'

Uruchom wątek

curl --request POST \
  --url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads/thread_abc123/runs?api-version=$API_VERSION \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "assistant_id": "asst_abc123",
  }'

Pobierz status przebiegu

curl --request GET \
  --url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads/thread_abc123/runs/run_abc123?api-version=$API_VERSION \
  -H "Authorization: Bearer $AGENT_TOKEN"

Pobieranie odpowiedzi agenta

curl --request GET \
  --url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads/thread_abc123/messages?api-version=$API_VERSION \
  -H "Authorization: Bearer $AGENT_TOKEN"