Интерпретатор кода позволяет агентам записывать и запускать код Python в изолированной среде выполнения. С включенным интерпретатором кода агент может выполнять итеративное выполнение кода для решения более сложных проблем с кодом, математикой и анализом данных. Когда агент записывает код, который не выполняется, он может выполнять итерацию по этому коду, изменив и выполнив другой код до тех пор, пока выполнение кода не будет выполнено.
Внимание
Интерпретатор кода требует дополнительных расходов за использование токенов Azure OpenAI. Если агент вызывает интерпретатор кода одновременно в двух разных потоках, создаются два сеанса интерпретатора кода. Каждый сеанс активен по умолчанию в течение одного часа.
Поддерживаемые модели
Страница моделей содержит самые актуальные сведения о регионах и моделях, где поддерживаются агенты и интерпретатор кода.
Мы рекомендуем использовать агенты с последними моделями, чтобы воспользоваться новыми функциями, большими контекстными окнами и более актуальными данными обучения.
Поддержка использования
Поддержка литейных решений Azure AI
Пакет SDK для Python
Пакет SDK для C#
Пакет SDK для JavaScript
REST API
Базовая настройка агента
Настройка стандартного агента
✔️
✔️
✔️
✔️
✔️
✔️
✔️
Использование средства интерпретатора кода с агентом
Вы можете добавить средство интерпретатора кода в агент программно с помощью примеров кода, перечисленных в верхней части этой статьи, или портала Azure AI Foundry. Если вы хотите использовать портал, выполните следующие действия.
На экране создания и отладки агента прокрутите вниз область установки справа от действия. Нажмите кнопку Добавить.
Выберите интерпретатор кода и следуйте инструкциям, чтобы добавить это средство.
Кроме того, вы можете отправить файлы для агента для чтения и интерпретации информации из наборов данных, создания кода и создания графов и диаграмм с помощью данных.
Чтобы использовать интерпретатор кода, сначала добавьте import инструкции, показанные в примере, и создайте клиент проекта, который будет содержать строка подключения в проект ИИ и будет использоваться для проверки подлинности вызовов 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"]
)
Чтобы использовать интерпретатор кода, сначала необходимо создать клиент проекта, который будет содержать строка подключения в проект ИИ и будет использоваться для проверки подлинности вызовов API.
var connectionString = Environment.GetEnvironmentVariable("PROJECT_CONNECTION_STRING");
AgentsClient client = new AgentsClient(connectionString, new DefaultAzureCredential());
Чтобы использовать интерпретатор кода, сначала необходимо создать клиент проекта, который будет содержать строка подключения в проект ИИ и будет использоваться для проверки подлинности вызовов API.
const connectionString =
process.env["AZURE_AI_PROJECTS_CONNECTION_STRING"] || "<project connection string>";
if (!connectionString) {
throw new Error("AZURE_AI_PROJECTS_CONNECTION_STRING must be set.");
}
const client = AIProjectsClient.fromConnectionString(
connectionString || "",
new DefaultAzureCredential(),
);
Следуйте краткому руководству по REST API, чтобы задать правильные значения для переменных AZURE_AI_AGENTS_TOKEN среды и AZURE_AI_AGENTS_ENDPOINT.
Отправьте файл с помощью 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}")
Файлы можно отправлять, а затем ссылаться на агенты или сообщения. Во-первых, используйте обобщенный API отправки с purposeAgents целью сделать идентификатор файла доступным. После отправки идентификатор файла можно предоставить для создания хранилища векторов для него. Затем идентификатор хранилища векторов можно предоставить агенту при создании.
Примечание.
Если вы не создаете векторное хранилище, вам не нужно toolResources предоставлять его.
// Upload a file and wait for it to be processed
Response<AgentFile> uploadAgentFileResponse = await client.UploadFileAsync(
filePath: "sample_file_for_upload.txt",
purpose: AgentFilePurpose.Agents);
AgentFile uploadedAgentFile = uploadAgentFileResponse.Value;
// Create a vector store with the file and wait for it to be processed.
// If you do not specify a vector store, create_message will create a vector store with a default expiration policy of seven days after they were last active
VectorStore vectorStore = await client.CreateVectorStoreAsync(
fileIds: new List<string> { uploadedAgentFile.Id },
name: "my_vector_store");
CodeInterpreterToolResource codeInterpreterToolResource = new CodeInterpreterToolResource();
CodeInterpreterToolResource.VectorStoreIds.Add(vectorStore.Id);
Файлы можно отправлять, а затем ссылаться на агенты или сообщения. После отправки его можно добавить в программу инструментов для ссылки.
Определите code_interpreter средство с CodeInterpreterTool() идентификатором файла, который вы добавили. Затем создайте агент с 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,
)
Response<Agent> agentResponse = await client.CreateAgentAsync(
model: "gpt-4o-mini",
name: "My agent",
instructions: "You are a helpful agent.",
tools: new List<ToolDefinition> { new CodeInterpreterToolDefinition() },
toolResources: new ToolResources() { CodeInterpreter = codeInterpreterToolResource });
Agent agent = agentResponse.Value;
// 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.agents.createAgent("gpt-4o-mini", {
name: "my-agent",
instructions: "You are a helpful agent",
tools: [codeInterpreterTool.definition],
toolResources: codeInterpreterTool.resources,
});
console.log(`Created agent, agent ID: ${agent.id}`);
curl $AZURE_AI_AGENTS_ENDPOINT/assistants?api-version=2024-12-01-preview \
-H "Authorization: Bearer $AZURE_AI_AGENTS_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"]
}
}
}'
Создание потока, сообщения и получение ответа агента
Затем создайте поток с 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}")
Затем создайте поток с CreateThreadAsync() потоком и потоком.CreateMessageAsync() После создания потока вы можете добавить в него сообщения, CreateMessageAsync() что приведет к активации средства интерпретатора кода. Создайте запуск и продолжайте опрос до тех пор, пока не достигнет состояния терминала. Предположим, что выполнение выполнено успешно, анализ ответа агента путем перечисления сообщений.
//Create a thread
Response<AgentThread> threadResponse = await client.CreateThreadAsync();
AgentThread thread = threadResponse.Value;
//With a thread created, messages can be created on it:
Response<ThreadMessage> messageResponse = await client.CreateMessageAsync(
thread.Id,
MessageRole.User,
"I need to solve the equation `3x + 11 = 14`. Can you help me?");
ThreadMessage message = messageResponse.Value;
//A run can then be started that evaluates the thread against an agent:
Response<ThreadRun> runResponse = await client.CreateRunAsync(
thread.Id,
agent.Id,
additionalInstructions: "Please address the user as Jane Doe. The user has a premium account.");
ThreadRun run = runResponse.Value;
//Once the run has started, it should then be polled until it reaches a terminal status:
do
{
await Task.Delay(TimeSpan.FromMilliseconds(500));
runResponse = await client.GetRunAsync(thread.Id, runResponse.Value.Id);
}
while (runResponse.Value.Status == RunStatus.Queued
|| runResponse.Value.Status == RunStatus.InProgress);
//Assuming the run successfully completed, listing messages from the thread that was run will now reflect new information added by the agent:
Response<PageableList<ThreadMessage>> afterRunMessagesResponse
= await client.GetMessagesAsync(thread.Id);
IReadOnlyList<ThreadMessage> messages = afterRunMessagesResponse.Value.Data;
// Note: messages iterate from newest to oldest, with the messages[0] being the most recent
foreach (ThreadMessage threadMessage in messages)
{
Console.Write($"{threadMessage.CreatedAt:yyyy-MM-dd HH:mm:ss} - {threadMessage.Role,10}: ");
foreach (MessageContent contentItem in threadMessage.ContentItems)
{
if (contentItem is MessageTextContent textItem)
{
Console.Write(textItem.Text);
}
else if (contentItem is MessageImageFileContent imageFileItem)
{
Console.Write($"<image from ID: {imageFileItem.FileId}");
}
Console.WriteLine();
}
}
// create a thread
const thread = await client.agents.createThread();
// add a message to thread
await client.agents.createMessage(
thread.id, {
role: "user",
content: "I need to solve the equation `3x + 11 = 14`. Can you help me?",
});
// create a run
const streamEventMessages = await client.agents.createRun(thread.id, agent.id).stream();
for await (const eventMessage of streamEventMessages) {
switch (eventMessage.event) {
case RunStreamEvent.ThreadRunCreated:
break;
case MessageStreamEvent.ThreadMessageDelta:
{
const messageDelta = eventMessage.data;
messageDelta.delta.content.forEach((contentPart) => {
if (contentPart.type === "text") {
const textContent = contentPart;
const textValue = textContent.text?.value || "No text";
}
});
}
break;
case RunStreamEvent.ThreadRunCompleted:
break;
case ErrorEvent.Error:
console.log(`An error occurred. Data ${eventMessage.data}`);
break;
case DoneEvent.Done:
break;
}
}
// Print the messages from the agent
const messages = await client.agents.listMessages(thread.id);
// Messages iterate from oldest to newest
// messages[0] is the most recent
for (let i = messages.data.length - 1; i >= 0; i--) {
const m = messages.data[i];
if (isOutputOfType<MessageTextContentOutput>(m.content[0], "text")) {
const textContent = m.content[0];
console.log(`${textContent.text.value}`);
console.log(`---------------------------------`);
}
}
curl $AZURE_AI_AGENTS_ENDPOINT/threads/thread_abc123/messages?api-version=2024-12-01-preview \
-H "Authorization: Bearer $AZURE_AI_AGENTS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"role": "user",
"content": "I need to solve the equation `3x + 11 = 14`. Can you help me?"
}'
Файлы, созданные интерпретатором кода, можно найти в ответах на сообщения агента. Файл изображения, созданный интерпретатором кода, можно скачать, выполнив итерацию ответа image_contents с именем и 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}")
Файлы, созданные интерпретатором кода, можно найти в ответах на сообщения агента. Файл изображения, созданный интерпретатором кода, можно скачать, выполнив итерацию сообщений ответа и проверив наличие ImageFileId. Если это поле существует, используйте следующий код:
foreach (MessageContent contentItem in message.Content)
{
if (!string.IsNullOrEmpty(contentItem.ImageFileId))
{
OpenAIFileInfo imageInfo = await fileClient.GetFileAsync(contentItem.ImageFileId);
BinaryData imageBytes = await fileClient.DownloadFileAsync(contentItem.ImageFileId);
using FileStream stream = File.OpenWrite($"{imageInfo.Filename}.png");
imageBytes.ToStream().CopyTo(stream);
Console.WriteLine($"<image: {imageInfo.Filename}.png>");
}
}
Файлы, отправленные агентами, не могут быть извлечены обратно. Если ваш вариант использования должен получить доступ к содержимому файла, отправленного агентами, рекомендуется сохранить дополнительную копию, доступную приложению. Однако файлы, созданные агентами getFileContent, извлекаются.
const messages = await client.agents.listMessages(thread.id);
const imageFile = (messages.data[0].content[0] as MessageImageFileContentOutput).imageFile;
const imageFileName = (await client.agents.getFile(imageFile.fileId)).filename;
const fileContent = await (await client.agents.getFileContent(imageFile.fileId).asNodeStream()).body;
if (fileContent) {
const chunks: Buffer[] = [];
for await (const chunk of fileContent) {
chunks.push(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}`);
При создании изображения интерпретатор кода можно найти созданный файл в поле file_id ответа помощника: