Comparteix a través de


Introducción a Azure OpenAI Assistants (versión preliminar)

Azure OpenAI Assistants (versión preliminar) permite crear asistentes de IA adaptados a sus necesidades mediante instrucciones personalizadas y aumentadas por herramientas avanzadas como el intérprete de código y las funciones personalizadas. En este artículo, se proporciona un tutorial detallado sobre cómo empezar a trabajar con la API de asistentes.

Nota:

  • La búsqueda de archivos puede ingerir hasta 10 000 archivos por asistente, 500 veces más que antes. Es rápida, compatible con consultas paralelas a través de búsquedas multiproceso y presenta características mejoradas de reordenación y reescritura de consultas.
    • El almacén de vectores es un nuevo objeto de la API. Una vez que un archivo se agrega a un almacén de vectores, se analiza automáticamente, se divide en fragmentos y se inserta, quedando listo para su búsqueda. Los almacenes de vectores se pueden usar entre asistentes y subprocesos, lo que simplifica la administración de archivos y la facturación.
  • Hemos agregado compatibilidad con el parámetro tool_choice que se puede usar para forzar el uso de una herramienta específica (como la búsqueda de archivos, el intérprete de código o una función) en una ejecución determinada.

Compatibilidad con asistentes

Compatibilidad con regiones y modelos

El intérprete de código está disponible en todas las regiones compatibles con los asistentes de Azure OpenAI. La página de modelos contiene la información más actualizada sobre regiones o modelos en los que se admiten actualmente los asistentes.

Versiones de API

  • 2024-02-15-preview
  • 2024-05-01-preview

Tipos de archivo compatibles

Formato de archivo Tipo MIME Intérprete de código
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

Herramientas

Sugerencia

Hemos agregado compatibilidad con el parámetro tool_choice que se puede usar para forzar el uso de una herramienta específica (como file_search, code_interpreter o un function) en una ejecución determinada.

Un asistente individual puede acceder a hasta 128 herramientas, como intérprete de código y búsqueda de archivos, pero también puede definir sus propias herramientas personalizadas mediante funciones.

Archivos

Los archivos se pueden cargar a través de Studio o mediante programación. El parámetro file_ids es necesario para que herramientas como code_interpreter puedan acceder a los archivos. Al usar el punto de conexión de carga de archivos, debe tener el purpose configurado en asistentes para poder usarlo con la API de asistentes.

Área de juegos de asistentes

Proporcionamos un tutorial del área de juegos de asistentes en nuestra guía de inicio rápido. Esto proporciona un entorno sin código para probar las funcionalidades de los asistentes.

Componentes de asistentes

Componente Descripción
Asistente Inteligencia artificial personalizada que usa modelos de Azure OpenAI junto con herramientas.
Subproceso Una sesión de conversación entre un asistente y un usuario. Los subprocesos almacenan mensajes y controlan automáticamente el truncamiento para ajustar el contenido a un contexto del modelo.
Mensaje Mensaje creado por un asistente o un usuario. Los mensajes pueden incluir texto, imágenes y otros archivos. Los mensajes se almacenan como una lista en el subproceso.
Ejecutar Activación de un asistente para empezar a ejecutarse en función del contenido del subproceso. El asistente usa su configuración y los mensajes del subproceso para realizar tareas llamando a modelos y herramientas. Como parte de una ejecución, el asistente anexa mensajes al subproceso.
Paso de ejecución Una lista detallada de los pasos que tomó el asistente como parte de una ejecución. Un asistente puede llamar a herramientas o crear mensajes durante su ejecución. Examinar los pasos de ejecución le permite comprender cómo el asistente obtiene sus resultados finales.

Configuración del primer asistente

Creación de un asistente

En este ejemplo, crearemos un asistente que escriba código para generar visualizaciones mediante las funcionalidades de la herramienta code_interpreter. Los siguientes ejemplos están diseñados para ejecutarse secuencialmente en un entorno como Jupyter Notebooks.

import os
import json
from openai import AzureOpenAI
    
client = AzureOpenAI(
    api_key=os.getenv("AZURE_OPENAI_API_KEY"),  
    api_version="2024-05-01-preview",
    azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT")
    )

# Create an assistant
assistant = client.beta.assistants.create(
    name="Data Visualization",
    instructions=f"You are a helpful AI assistant who makes interesting visualizations based on data." 
    f"You have access to a sandboxed environment for writing and testing code."
    f"When you are asked to create a visualization you should follow these steps:"
    f"1. Write the code."
    f"2. Anytime you write new code display a preview of the code to show your work."
    f"3. Run the code to confirm that it runs."
    f"4. If the code is successful display the visualization."
    f"5. If the code is unsuccessful display the error message and try to revise the code and rerun going through the steps from above again.",
    tools=[{"type": "code_interpreter"}],
    model="gpt-4-1106-preview" #You must replace this value with the deployment name for your model.
)

Hay algunos detalles que debe tener en cuenta de la configuración anterior:

  • Habilitamos a este asistente para que acceda al intérprete de código con la línea tools=[{"type": "code_interpreter"}],. Esto proporciona al modelo acceso a un entorno de caja de arena de Python para ejecutar código para ayudar a formular respuestas a la pregunta de un usuario.
  • En las instrucciones recordamos al modelo que puede ejecutar código. A veces, el modelo necesita ayuda para guiarse hacia la herramienta correcta para resolver una consulta determinada. Si sabe que quiere usar una biblioteca concreta para generar una respuesta determinada que sabe que forma parte del intérprete de código, este puede ayudar a proporcionar instrucciones diciendo algo como "Usar Matplotlib para hacer x".
  • Dado que se trata de Azure OpenAI, el valor que escriba para model=debe coincidir con el nombre de implementación.

A continuación, vamos a imprimir el contenido del asistente que acabamos de crear para confirmar que la creación se ha realizado correctamente:

print(assistant.model_dump_json(indent=2))
{
  "id": "asst_7AZSrv5I3XzjUqWS40X5UgRr",
  "created_at": 1705972454,
  "description": null,
  "file_ids": [],
  "instructions": "You are a helpful AI assistant who makes interesting visualizations based on data.You have access to a sandboxed environment for writing and testing code.When you are asked to create a visualization you should follow these steps:1. Write the code.2. Anytime you write new code display a preview of the code to show your work.3. Run the code to confirm that it runs.4. If the code is successful display the visualization.5. If the code is unsuccessful display the error message and try to revise the code and rerun going through the steps from above again.",
  "metadata": {},
  "model": "gpt-4-1106-preview",
  "name": "Data Visualization",
  "object": "assistant",
  "tools": [
    {
      "type": "code_interpreter"
    }
  ]
}

Creación de un subproceso

Ahora vamos a crear un subproceso.

# Create a thread
thread = client.beta.threads.create()
print(thread)
Thread(id='thread_6bunpoBRZwNhovwzYo7fhNVd', created_at=1705972465, metadata={}, object='thread')

Un subproceso es esencialmente el registro de la sesión de conversación entre el asistente y el usuario. Es similar a la matriz o lista de mensajes de una llamada API típica de finalizaciones de chat. Una de las principales diferencias es que, a diferencia de una matriz de mensajes de finalizaciones de chat, no es necesario realizar un seguimiento de los tokens con cada llamada para asegurarse de que permanece por debajo de la longitud de contexto del modelo. Los subprocesos abstraen este detalle de administración y comprimen el historial de subprocesos según sea necesario para permitir que la conversación continúe. La capacidad de los subprocesos para lograr esto con conversaciones más grandes se mejora al usar los modelos más recientes, que tienen longitudes de contexto más grandes, así como compatibilidad con las características más recientes.

A continuación, cree la primera pregunta del usuario que se va a agregar al subproceso.

# Add a user question to the thread
message = client.beta.threads.messages.create(
    thread_id=thread.id,
    role="user",
    content="Create a visualization of a sinewave"
)

Enumeración de mensajes de subproceso

thread_messages = client.beta.threads.messages.list(thread.id)
print(thread_messages.model_dump_json(indent=2))
{
  "data": [
    {
      "id": "msg_JnkmWPo805Ft8NQ0gZF6vA2W",
      "assistant_id": null,
      "content": [
        {
          "text": {
            "annotations": [],
            "value": "Create a visualization of a sinewave"
          },
          "type": "text"
        }
      ],
      "created_at": 1705972476,
      "file_ids": [],
      "metadata": {},
      "object": "thread.message",
      "role": "user",
      "run_id": null,
      "thread_id": "thread_6bunpoBRZwNhovwzYo7fhNVd"
    }
  ],
  "object": "list",
  "first_id": "msg_JnkmWPo805Ft8NQ0gZF6vA2W",
  "last_id": "msg_JnkmWPo805Ft8NQ0gZF6vA2W",
  "has_more": false
}

Ejecución de subprocesos

run = client.beta.threads.runs.create(
  thread_id=thread.id,
  assistant_id=assistant.id,
  #instructions="New instructions" #You can optionally provide new instructions but these will override the default instructions
)

También podríamos pasar un parámetro instructions aquí, pero esto invalidaría las instrucciones existentes que ya hemos proporcionado para el asistente.

Recuperación del estado del subproceso

# Retrieve the status of the run
run = client.beta.threads.runs.retrieve(
  thread_id=thread.id,
  run_id=run.id
)

status = run.status
print(status)
completed

En función de la complejidad de la consulta que ejecute, el subproceso podría tardar más tiempo en ejecutarse. En ese caso, puede crear un bucle para supervisar el estado de ejecución del subproceso con código como en el siguiente ejemplo:

import time
from IPython.display import clear_output

start_time = time.time()

status = run.status

while status not in ["completed", "cancelled", "expired", "failed"]:
    time.sleep(5)
    run = client.beta.threads.runs.retrieve(thread_id=thread.id,run_id=run.id)
    print("Elapsed time: {} minutes {} seconds".format(int((time.time() - start_time) // 60), int((time.time() - start_time) % 60)))
    status = run.status
    print(f'Status: {status}')
    clear_output(wait=True)

messages = client.beta.threads.messages.list(
  thread_id=thread.id
) 

print(f'Status: {status}')
print("Elapsed time: {} minutes {} seconds".format(int((time.time() - start_time) // 60), int((time.time() - start_time) % 60)))
print(messages.model_dump_json(indent=2))

Cuando una ejecución está en in_progress o en otros estados no predeterminados, el subproceso está bloqueado. Cuando un subproceso está bloqueado, no se pueden agregar nuevos mensajes y no se pueden crear nuevas ejecuciones.

Enumeración de mensajes de subprocesos después de la ejecución

Una vez que el estado de ejecución indica la finalización correcta, puede volver a enumerar el contenido del subproceso para recuperar el modelo y cualquier respuesta de herramientas:

messages = client.beta.threads.messages.list(
  thread_id=thread.id
)

print(messages.model_dump_json(indent=2))
{
  "data": [
    {
      "id": "msg_M5pz73YFsJPNBbWvtVs5ZY3U",
      "assistant_id": "asst_eHwhP4Xnad0bZdJrjHO2hfB4",
      "content": [
        {
          "text": {
            "annotations": [],
            "value": "Is there anything else you would like to visualize or any additional features you'd like to add to the sine wave plot?"
          },
          "type": "text"
        }
      ],
      "created_at": 1705967782,
      "file_ids": [],
      "metadata": {},
      "object": "thread.message",
      "role": "assistant",
      "run_id": "run_AGQHJrrfV3eM0eI9T3arKgYY",
      "thread_id": "thread_ow1Yv29ptyVtv7ixbiKZRrHd"
    },
    {
      "id": "msg_oJbUanImBRpRran5HSa4Duy4",
      "assistant_id": "asst_eHwhP4Xnad0bZdJrjHO2hfB4",
      "content": [
        {
          "image_file": {
            "file_id": "assistant-1YGVTvNzc2JXajI5JU9F0HMD"
          },
          "type": "image_file"
        },
        {
          "text": {
            "annotations": [],
            "value": "Here is the visualization of a sine wave: \n\nThe wave is plotted using values from 0 to \\( 4\\pi \\) on the x-axis, and the corresponding sine values on the y-axis. I've also added grid lines for easier reading of the plot."
          },
          "type": "text"
        }
      ],
      "created_at": 1705967044,
      "file_ids": [],
      "metadata": {},
      "object": "thread.message",
      "role": "assistant",
      "run_id": "run_8PsweDFn6gftUd91H87K0Yts",
      "thread_id": "thread_ow1Yv29ptyVtv7ixbiKZRrHd"
    },
    {
      "id": "msg_Pu3eHjM10XIBkwqh7IhnKKdG",
      "assistant_id": null,
      "content": [
        {
          "text": {
            "annotations": [],
            "value": "Create a visualization of a sinewave"
          },
          "type": "text"
        }
      ],
      "created_at": 1705966634,
      "file_ids": [],
      "metadata": {},
      "object": "thread.message",
      "role": "user",
      "run_id": null,
      "thread_id": "thread_ow1Yv29ptyVtv7ixbiKZRrHd"
    }
  ],
  "object": "list",
  "first_id": "msg_M5pz73YFsJPNBbWvtVs5ZY3U",
  "last_id": "msg_Pu3eHjM10XIBkwqh7IhnKKdG",
  "has_more": false
}

Recuperación del identificador de archivo

Hemos solicitado que el modelo genere una imagen de una onda sinusoidal. Para descargar la imagen, primero es necesario recuperar el identificador de archivo de imágenes.

data = json.loads(messages.model_dump_json(indent=2))  # Load JSON data into a Python object
image_file_id = data['data'][0]['content'][0]['image_file']['file_id']

print(image_file_id)  # Outputs: assistant-1YGVTvNzc2JXajI5JU9F0HMD

Descarga de la imagen

content = client.files.content(image_file_id)

image= content.write_to_file("sinewave.png")

Abra la imagen localmente una vez que se descargue:

from PIL import Image

# Display the image in the default image viewer
image = Image.open("sinewave.png")
image.show()

Captura de pantalla del intérprete de código generado por la onda sinodal.

Formulación de una pregunta de seguimiento en el subproceso

Dado que el asistente no siguió nuestras instrucciones e incluyó el código que se ejecutó en la parte de texto de su respuesta, vamos a pedirle explícitamente esa información.

# Add a new user question to the thread
message = client.beta.threads.messages.create(
    thread_id=thread.id,
    role="user",
    content="Show me the code you used to generate the sinewave"
)

De nuevo, tendremos que ejecutar y recuperar el estado del subproceso:

run = client.beta.threads.runs.create(
  thread_id=thread.id,
  assistant_id=assistant.id,
  #instructions="New instructions" #You can optionally provide new instructions  but these will override the default instructions
)

# Retrieve the status of the run
run = client.beta.threads.runs.retrieve(
  thread_id=thread.id,
  run_id=run.id
)

status = run.status
print(status)

completed

Una vez que el estado de ejecución llegue a completado, volveremos a listar los mensajes en el subproceso que ahora debería incluir la respuesta a nuestra última pregunta.

messages = client.beta.threads.messages.list(
  thread_id=thread.id
)

print(messages.model_dump_json(indent=2))
{
  "data": [
    {
      "id": "msg_oaF1PUeozAvj3KrNnbKSy4LQ",
      "assistant_id": "asst_eHwhP4Xnad0bZdJrjHO2hfB4",
      "content": [
        {
          "text": {
            "annotations": [],
            "value": "Certainly, here is the code I used to generate the sine wave visualization:\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Generating data for the sinewave\nx = np.linspace(0, 4 * np.pi, 1000)  # Generate values from 0 to 4*pi\ny = np.sin(x)  # Compute the sine of these values\n\n# Plotting the sine wave\nplt.plot(x, y)\nplt.title('Sine Wave')\nplt.xlabel('x')\nplt.ylabel('sin(x)')\nplt.grid(True)\nplt.show()\n```\n\nThis code snippet uses `numpy` to generate an array of x values and then computes the sine for each x value. It then uses `matplotlib` to plot these values and display the resulting graph."
          },
          "type": "text"
        }
      ],
      "created_at": 1705969710,
      "file_ids": [],
      "metadata": {},
      "object": "thread.message",
      "role": "assistant",
      "run_id": "run_oDS3fH7NorCUVwROTZejKcZN",
      "thread_id": "thread_ow1Yv29ptyVtv7ixbiKZRrHd"
    },
    {
      "id": "msg_moYE3aNwFYuRq2aXpxpt2Wb0",
      "assistant_id": null,
      "content": [
        {
          "text": {
            "annotations": [],
            "value": "Show me the code you used to generate the sinewave"
          },
          "type": "text"
        }
      ],
      "created_at": 1705969678,
      "file_ids": [],
      "metadata": {},
      "object": "thread.message",
      "role": "user",
      "run_id": null,
      "thread_id": "thread_ow1Yv29ptyVtv7ixbiKZRrHd"
    },
    {
      "id": "msg_M5pz73YFsJPNBbWvtVs5ZY3U",
      "assistant_id": "asst_eHwhP4Xnad0bZdJrjHO2hfB4",
      "content": [
        {
          "text": {
            "annotations": [],
            "value": "Is there anything else you would like to visualize or any additional features you'd like to add to the sine wave plot?"
          },
          "type": "text"
        }
      ],
      "created_at": 1705967782,
      "file_ids": [],
      "metadata": {},
      "object": "thread.message",
      "role": "assistant",
      "run_id": "run_AGQHJrrfV3eM0eI9T3arKgYY",
      "thread_id": "thread_ow1Yv29ptyVtv7ixbiKZRrHd"
    },
    {
      "id": "msg_oJbUanImBRpRran5HSa4Duy4",
      "assistant_id": "asst_eHwhP4Xnad0bZdJrjHO2hfB4",
      "content": [
        {
          "image_file": {
            "file_id": "assistant-1YGVTvNzc2JXajI5JU9F0HMD"
          },
          "type": "image_file"
        },
        {
          "text": {
            "annotations": [],
            "value": "Here is the visualization of a sine wave: \n\nThe wave is plotted using values from 0 to \\( 4\\pi \\) on the x-axis, and the corresponding sine values on the y-axis. I've also added grid lines for easier reading of the plot."
          },
          "type": "text"
        }
      ],
      "created_at": 1705967044,
      "file_ids": [],
      "metadata": {},
      "object": "thread.message",
      "role": "assistant",
      "run_id": "run_8PsweDFn6gftUd91H87K0Yts",
      "thread_id": "thread_ow1Yv29ptyVtv7ixbiKZRrHd"
    },
    {
      "id": "msg_Pu3eHjM10XIBkwqh7IhnKKdG",
      "assistant_id": null,
      "content": [
        {
          "text": {
            "annotations": [],
            "value": "Create a visualization of a sinewave"
          },
          "type": "text"
        }
      ],
      "created_at": 1705966634,
      "file_ids": [],
      "metadata": {},
      "object": "thread.message",
      "role": "user",
      "run_id": null,
      "thread_id": "thread_ow1Yv29ptyVtv7ixbiKZRrHd"
    }
  ],
  "object": "list",
  "first_id": "msg_oaF1PUeozAvj3KrNnbKSy4LQ",
  "last_id": "msg_Pu3eHjM10XIBkwqh7IhnKKdG",
  "has_more": false
}

Para extraer solo la respuesta a nuestra pregunta más reciente:

data = json.loads(messages.model_dump_json(indent=2))
code = data['data'][0]['content'][0]['text']['value']
print(code)

Ciertamente, este es el código que he usado para generar la visualización de onda sinusoidal:

import numpy as np
import matplotlib.pyplot as plt

# Generating data for the sinewave
x = np.linspace(0, 4 * np.pi, 1000)  # Generate values from 0 to 4*pi
y = np.sin(x)  # Compute the sine of these values

# Plotting the sine wave
plt.plot(x, y)
plt.title('Sine Wave')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.grid(True)
plt.show()

Modo oscuro

Agreguemos una última pregunta al hilo para ver si el intérprete de código puede cambiar el gráfico a modo oscuro por nosotros.

# Add a user question to the thread
message = client.beta.threads.messages.create(
    thread_id=thread.id,
    role="user",
    content="I prefer visualizations in darkmode can you change the colors to make a darkmode version of this visualization."
)

# Run the thread
run = client.beta.threads.runs.create(
  thread_id=thread.id,
  assistant_id=assistant.id,
)

# Retrieve the status of the run
run = client.beta.threads.runs.retrieve(
  thread_id=thread.id,
  run_id=run.id
)

status = run.status
print(status)
completed
messages = client.beta.threads.messages.list(
  thread_id=thread.id
)

print(messages.model_dump_json(indent=2))
{
  "data": [
    {
      "id": "msg_KKzOHCArWGvGpuPo0pVZTHgV",
      "assistant_id": "asst_eHwhP4Xnad0bZdJrjHO2hfB4",
      "content": [
        {
          "text": {
            "annotations": [],
            "value": "You're viewing the dark mode version of the sine wave visualization in the image above. The plot is set against a dark background with a cyan colored sine wave for better contrast and visibility. If there's anything else you'd like to adjust or any other assistance you need, feel free to let me know!"
          },
          "type": "text"
        }
      ],
      "created_at": 1705971199,
      "file_ids": [],
      "metadata": {},
      "object": "thread.message",
      "role": "assistant",
      "run_id": "run_izZFyTVB1AlFM1VVMItggRn4",
      "thread_id": "thread_ow1Yv29ptyVtv7ixbiKZRrHd"
    },
    {
      "id": "msg_30pXFVYNgP38qNEMS4Zbozfk",
      "assistant_id": null,
      "content": [
        {
          "text": {
            "annotations": [],
            "value": "I prefer visualizations in darkmode can you change the colors to make a darkmode version of this visualization."
          },
          "type": "text"
        }
      ],
      "created_at": 1705971194,
      "file_ids": [],
      "metadata": {},
      "object": "thread.message",
      "role": "user",
      "run_id": null,
      "thread_id": "thread_ow1Yv29ptyVtv7ixbiKZRrHd"
    },
    {
      "id": "msg_3j31M0PaJLqO612HLKVsRhlw",
      "assistant_id": "asst_eHwhP4Xnad0bZdJrjHO2hfB4",
      "content": [
        {
          "image_file": {
            "file_id": "assistant-kfqzMAKN1KivQXaEJuU0u9YS"
          },
          "type": "image_file"
        },
        {
          "text": {
            "annotations": [],
            "value": "Here is the dark mode version of the sine wave visualization. I've used the 'dark_background' style in Matplotlib and chosen a cyan color for the plot line to ensure it stands out against the dark background."
          },
          "type": "text"
        }
      ],
      "created_at": 1705971123,
      "file_ids": [],
      "metadata": {},
      "object": "thread.message",
      "role": "assistant",
      "run_id": "run_B91erEPWro4bZIfryQeIDDlx",
      "thread_id": "thread_ow1Yv29ptyVtv7ixbiKZRrHd"
    },
    {
      "id": "msg_FgDZhBvvM1CLTTFXwgeJLdua",
      "assistant_id": null,
      "content": [
        {
          "text": {
            "annotations": [],
            "value": "I prefer visualizations in darkmode can you change the colors to make a darkmode version of this visualization."
          },
          "type": "text"
        }
      ],
      "created_at": 1705971052,
      "file_ids": [],
      "metadata": {},
      "object": "thread.message",
      "role": "user",
      "run_id": null,
      "thread_id": "thread_ow1Yv29ptyVtv7ixbiKZRrHd"
    },
    {
      "id": "msg_oaF1PUeozAvj3KrNnbKSy4LQ",
      "assistant_id": "asst_eHwhP4Xnad0bZdJrjHO2hfB4",
      "content": [
        {
          "text": {
            "annotations": [],
            "value": "Certainly, here is the code I used to generate the sine wave visualization:\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Generating data for the sinewave\nx = np.linspace(0, 4 * np.pi, 1000)  # Generate values from 0 to 4*pi\ny = np.sin(x)  # Compute the sine of these values\n\n# Plotting the sine wave\nplt.plot(x, y)\nplt.title('Sine Wave')\nplt.xlabel('x')\nplt.ylabel('sin(x)')\nplt.grid(True)\nplt.show()\n```\n\nThis code snippet uses `numpy` to generate an array of x values and then computes the sine for each x value. It then uses `matplotlib` to plot these values and display the resulting graph."
          },
          "type": "text"
        }
      ],
      "created_at": 1705969710,
      "file_ids": [],
      "metadata": {},
      "object": "thread.message",
      "role": "assistant",
      "run_id": "run_oDS3fH7NorCUVwROTZejKcZN",
      "thread_id": "thread_ow1Yv29ptyVtv7ixbiKZRrHd"
    },
    {
      "id": "msg_moYE3aNwFYuRq2aXpxpt2Wb0",
      "assistant_id": null,
      "content": [
        {
          "text": {
            "annotations": [],
            "value": "Show me the code you used to generate the sinewave"
          },
          "type": "text"
        }
      ],
      "created_at": 1705969678,
      "file_ids": [],
      "metadata": {},
      "object": "thread.message",
      "role": "user",
      "run_id": null,
      "thread_id": "thread_ow1Yv29ptyVtv7ixbiKZRrHd"
    },
    {
      "id": "msg_M5pz73YFsJPNBbWvtVs5ZY3U",
      "assistant_id": "asst_eHwhP4Xnad0bZdJrjHO2hfB4",
      "content": [
        {
          "text": {
            "annotations": [],
            "value": "Is there anything else you would like to visualize or any additional features you'd like to add to the sine wave plot?"
          },
          "type": "text"
        }
      ],
      "created_at": 1705967782,
      "file_ids": [],
      "metadata": {},
      "object": "thread.message",
      "role": "assistant",
      "run_id": "run_AGQHJrrfV3eM0eI9T3arKgYY",
      "thread_id": "thread_ow1Yv29ptyVtv7ixbiKZRrHd"
    },
    {
      "id": "msg_oJbUanImBRpRran5HSa4Duy4",
      "assistant_id": "asst_eHwhP4Xnad0bZdJrjHO2hfB4",
      "content": [
        {
          "image_file": {
            "file_id": "assistant-1YGVTvNzc2JXajI5JU9F0HMD"
          },
          "type": "image_file"
        },
        {
          "text": {
            "annotations": [],
            "value": "Here is the visualization of a sine wave: \n\nThe wave is plotted using values from 0 to \\( 4\\pi \\) on the x-axis, and the corresponding sine values on the y-axis. I've also added grid lines for easier reading of the plot."
          },
          "type": "text"
        }
      ],
      "created_at": 1705967044,
      "file_ids": [],
      "metadata": {},
      "object": "thread.message",
      "role": "assistant",
      "run_id": "run_8PsweDFn6gftUd91H87K0Yts",
      "thread_id": "thread_ow1Yv29ptyVtv7ixbiKZRrHd"
    },
    {
      "id": "msg_Pu3eHjM10XIBkwqh7IhnKKdG",
      "assistant_id": null,
      "content": [
        {
          "text": {
            "annotations": [],
            "value": "Create a visualization of a sinewave"
          },
          "type": "text"
        }
      ],
      "created_at": 1705966634,
      "file_ids": [],
      "metadata": {},
      "object": "thread.message",
      "role": "user",
      "run_id": null,
      "thread_id": "thread_ow1Yv29ptyVtv7ixbiKZRrHd"
    }
  ],
  "object": "list",
  "first_id": "msg_KKzOHCArWGvGpuPo0pVZTHgV",
  "last_id": "msg_Pu3eHjM10XIBkwqh7IhnKKdG",
  "has_more": false
}

Extraiga el nuevo identificador de archivo de imagen y descargue y muestre la imagen:

data = json.loads(messages.model_dump_json(indent=2))  # Load JSON data into a Python object
image_file_id = data['data'][0]['content'][0]['image_file']['file_id'] # index numbers can vary if you have had a different conversation over the course of the thread.

print(image_file_id)

content = client.files.content(image_file_id)
image= content.write_to_file("dark_sine.png")

# Display the image in the default image viewer
image = Image.open("dark_sine.png")
image.show()

Captura de pantalla del intérprete de código generado por la onda sinodal en modo oscuro.

Referencia adicional

Ejecución de definiciones de estado

Estado Definición
queued Cuando las ejecuciones se crean por primera vez o cuando se completa la required_action, se mueven a un estado en cola. Deberían pasar casi inmediatamente a in_progress.
in_progress Mientras está en in_progress, el asistente utiliza el modelo y las herramientas para realizar los pasos. Para ver el progreso que realiza la ejecución, examine los pasos de ejecución.
completed La ejecución se completó correctamente. Ahora puede ver todos los mensajes que el asistente ha agregado al subproceso y todos los pasos que ha llevado a cabo la ejecución. También puede continuar la conversación agregando más mensajes de usuario al subproceso y creando otra ejecución.
requires_action Al usar la herramienta de llamada de función, la ejecución pasará a un estado de required_action una vez que el modelo determine los nombres y argumentos de las funciones a las que se va a llamar. A continuación, debe ejecutar esas funciones y enviar las salidas antes de que continúe la ejecución. Si las salidas no se proporcionan antes de que pase la marca de tiempo expires_at (aproximadamente 10 minutos después de la creación), la ejecución expirará.
expired Esto ocurre cuando las salidas que llaman a la función no fueron enviadas antes de expires_at y la ejecución expira. Además, si las ejecuciones tardan demasiado tiempo en ejecutarse y exceden el tiempo indicado en expires_at, nuestros sistemas expirarán la ejecución.
cancelling Puede intentar cancelar una ejecución que esté en in_progress mediante el punto de conexión Cancelar ejecución. Una vez que el intento de cancelación se realiza correctamente, el estado de la ejecución pasa a cancelado. La cancelación se intenta pero no se garantiza.
cancelled La ejecución se ha cancelado correctamente.
failed Puede ver el motivo del error examinando el objeto last_error en la ejecución. La marca de tiempo del error se registrará con failed_at.

Anotaciones del mensaje

Las anotaciones de mensajes del asistente son diferentes de las anotaciones de filtrado de contenido que están presentes en las respuestas de la API de finalización y finalización de chat. Las anotaciones del asistente pueden producirse dentro de la matriz de contenido del objeto. Las anotaciones proporcionan información sobre cómo debe anotar el texto en las respuestas al usuario.

Cuando las anotaciones estén presentes en la matriz de contenido de mensajes, verá substrings generadas por modelos ilegibles en el texto que necesita reemplazar por las anotaciones correctas. Estas cadenas pueden tener un aspecto similar a 【13†source】 o sandbox:/mnt/data/file.csv. Este es un fragmento de código de Python de OpenAI que reemplaza estas cadenas por la información presente en las anotaciones.


from openai import AzureOpenAI
    
client = AzureOpenAI(
    api_key=os.getenv("AZURE_OPENAI_API_KEY"),  
    api_version="2024-05-01-preview",
    azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT")
    )

# Retrieve the message object
message = client.beta.threads.messages.retrieve(
  thread_id="...",
  message_id="..."
)

# Extract the message content
message_content = message.content[0].text
annotations = message_content.annotations
citations = []

# Iterate over the annotations and add footnotes
for index, annotation in enumerate(annotations):
    # Replace the text with a footnote
    message_content.value = message_content.value.replace(annotation.text, f' [{index}]')

    # Gather citations based on annotation attributes
    if (file_citation := getattr(annotation, 'file_citation', None)):
        cited_file = client.files.retrieve(file_citation.file_id)
        citations.append(f'[{index}] {file_citation.quote} from {cited_file.filename}')
    elif (file_path := getattr(annotation, 'file_path', None)):
        cited_file = client.files.retrieve(file_path.file_id)
        citations.append(f'[{index}] Click <here> to download {cited_file.filename}')
        # Note: File download functionality not implemented above for brevity

# Add footnotes to the end of the message before displaying to user
message_content.value += '\n' + '\n'.join(citations)

Anotación de mensaje Descripción
file_citation La herramienta de recuperación crea citas de archivo y define referencias a una cita específica en un archivo específico cargado y usado por el asistente para generar la respuesta.
file_path La herramienta code_interpreter crea anotaciones de ruta de acceso de archivo y contiene referencias a los archivos generados por la herramienta.

Consulte también