Compartir vía


Intérprete de código del servicio del agente de Azure AI

El intérprete de código permite que los agentes escriban y ejecuten código de Python en un entorno de ejecución de espacio aislado. Con el intérprete de código habilitado, el agente puede ejecutar código de forma iterativa para resolver problemas de análisis de datos, matemáticas y código más complicados. Cuando el agente escribe un código que no se puede ejecutar, puede iterar en este código modificando y ejecutar un código diferente hasta que la ejecución del código se realice correctamente.

Importante

El intérprete de código tiene cargos adicionales más allá de las tarifas basadas en tokens para el uso de Azure OpenAI. Si su agente llama al intérprete de código simultáneamente en dos subprocesos diferentes, se crean dos sesiones de intérprete de código. Cada sesión está activa de forma predeterminada durante una hora.

Modelos admitidos

La página de modelos contiene la información más actualizada sobre regiones o modelos en los que se admiten agentes e intérpretes de código.

Se recomienda usar agentes con los modelos más recientes para aprovechar las nuevas características, las ventanas de contexto más grandes y los datos de entrenamiento más actualizados.

Definición de importaciones y creación de un cliente de proyecto

Para usar el intérprete de código, agregue primero las instrucciones de import que se muestran en el ejemplo y cree un cliente de proyecto, que contendrá una cadena de conexión al proyecto de IA y se usará para autenticar llamadas 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"]
)

Carga de un archivo

Cargue el archivo mediante la función upload_and_poll(), especificando la ruta de acceso del archivo y el propósito 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}")

Creación de un agente con la herramienta de intérprete de código

Defina la herramienta code_interpreter con CodeInterpreterTool() e incluya el identificador de archivo del archivo que había cargado. Después, cree el agente con tools establecido en code_interpreter.definitions y tool_resources establecido en 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,
)

Crear un subproceso y un mensaje y obtener la respuesta del agente

A continuación, cree un subproceso con create_thread() y adjunte un mensaje mediante create_message() que desencadenará la herramienta de intérprete de código. Después, cree y ejecute con create_and_process_run(). Una vez finalizada la ejecución, puede eliminar el archivo del agente con delete_file() para liberar espacio en el agente. Por último, imprima los mensajes del agente.

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

Descarga de archivos generados por el intérprete de código

Los archivos generados por el intérprete de código se pueden encontrar en las respuestas de mensajes del agente. Puede descargar el archivo de imagen generado por el intérprete de código, iterando por el image_contents de la respuesta y llamando a save_file() con un nombre y el identificador de archivo.

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

Tipos de archivo compatibles

Formato de archivo Tipo 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 o text/xml
.zip application/zip

Consulte también

  • Obtenga más información sobre los agentes.