Bagikan melalui


Mulai menggunakan Asisten Azure OpenAI (Pratinjau)

Asisten Azure OpenAI (Pratinjau) memungkinkan Anda membuat asisten AI yang disesuaikan dengan kebutuhan Anda melalui instruksi kustom dan ditambah oleh alat tingkat lanjut seperti penerjemah kode, dan fungsi kustom. Dalam artikel ini, kami menyediakan panduan mendalam untuk memulai dengan Assistants API.

Catatan

  • Pencarian file dapat menyerap hingga 10.000 file per asisten - 500 kali lebih banyak dari sebelumnya. Ini cepat, mendukung kueri paralel melalui pencarian multi-utas, dan fitur reranking dan penulisan ulang kueri yang ditingkatkan.
    • Penyimpanan vektor adalah objek baru di API. Setelah file ditambahkan ke penyimpanan vektor, file secara otomatis diurai, dipotong, dan disematkan, dibuat siap untuk dicari. Penyimpanan vektor dapat digunakan di seluruh asisten dan utas, menyederhanakan manajemen dan penagihan file.
  • Kami telah menambahkan dukungan untuk tool_choice parameter yang dapat digunakan untuk memaksa penggunaan alat tertentu (seperti pencarian file, penerjemah kode, atau fungsi) dalam eksekusi tertentu.

Dukungan asisten

Dukungan wilayah dan model

Penerjemah kode tersedia di semua wilayah yang didukung oleh Asisten Azure OpenAI. Halaman model berisi informasi terbaru tentang wilayah/model di mana Asisten saat ini didukung.

Versi API

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

Jenis file yang didukung

Format file Jenis MIME Penerjemah Kode
c. text/x-c
.cpp text/x-c++
.csv application/csv
.docx application/vnd.openxmlformats-officedocument.wordprocessingml.documen
.html teks/html
.java text/x-java
.json application/json
.md teks/markdown
.pdf aplikasi/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 gambar/jpeg
.jpg gambar/jpeg
.Js text/javascript
.gif gambar/gif
.png gambar/png
.ter application/x-tar
.ts application/typescript
.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xml application/xml atau "text/xml"
.Zip application/zip

Alat

Tip

Kami telah menambahkan dukungan untuk tool_choice parameter yang dapat digunakan untuk memaksa penggunaan alat tertentu (seperti file_search, code_interpreter, atau ) functiondalam eksekusi tertentu.

Asisten individual dapat mengakses hingga 128 alat termasuk penerjemah kode dan pencarian file, tetapi Anda juga dapat menentukan alat kustom Anda sendiri melalui fungsi.

File

File dapat diunggah melalui Studio, atau secara terprogram. Parameter file_ids diperlukan untuk memberikan alat seperti code_interpreter akses ke file. Saat menggunakan titik akhir Unggahan file, Anda harus mengatur purpose ke asisten yang akan digunakan dengan Assistants API.

Taman bermain asisten

Kami menyediakan panduan tentang taman bermain Asisten dalam panduan mulai cepat kami. Ini menyediakan lingkungan tanpa kode untuk menguji kemampuan asisten.

Komponen asisten

Komponen Keterangan
Asisten AI kustom yang menggunakan model Azure OpenAI bersama dengan alat.
Benang Sesi percakapan antara Asisten dan pengguna. Utas menyimpan Pesan dan secara otomatis menangani pemotongan agar sesuai dengan konten ke dalam konteks model.
Pesan Pesan yang dibuat oleh Asisten atau pengguna. Pesan dapat menyertakan teks, gambar, dan file lainnya. Pesan disimpan sebagai daftar di Utas.
jalankan Aktivasi Asisten untuk mulai berjalan berdasarkan konten Utas. Asisten menggunakan konfigurasinya dan Pesan Utas untuk melakukan tugas dengan memanggil model dan alat. Sebagai bagian dari Eksekusi, Asisten menambahkan Pesan ke Utas.
Jalankan Langkah Daftar terperinci langkah yang diambil Asisten sebagai bagian dari Eksekusi. Asisten dapat memanggil alat atau membuat Pesan selama dijalankan. Memeriksa Langkah Eksekusi memungkinkan Anda memahami bagaimana Asisten mencapai hasil akhirnya.

Menyiapkan Asisten pertama Anda

Membuat asisten

Untuk contoh ini, kita akan membuat asisten yang menulis kode untuk menghasilkan visualisasi menggunakan kemampuan code_interpreter alat. Contoh di bawah ini dimaksudkan untuk dijalankan secara berurutan di lingkungan seperti 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.
)

Ada beberapa detail yang harus Anda catat dari konfigurasi di atas:

  • Kami memungkinkan asisten ini untuk mengakses penerjemah kode dengan baris tools=[{"type": "code_interpreter"}],. Ini memberi model akses ke lingkungan python berkotak pasir untuk menjalankan dan menjalankan kode untuk membantu merumuskan respons terhadap pertanyaan pengguna.
  • Dalam instruksi, kami mengingatkan model bahwa model dapat menjalankan kode. Terkadang model membutuhkan bantuan memandunya menuju alat yang tepat untuk menyelesaikan kueri tertentu. Jika Anda tahu ingin menggunakan pustaka tertentu untuk menghasilkan respons tertentu yang Anda ketahui adalah bagian dari penerjemah kode, itu dapat membantu memberikan panduan dengan mengatakan sesuatu seperti "Gunakan Matplotlib untuk melakukan x."
  • Karena ini adalah Azure OpenAI, nilai yang Anda masukkan model= harus cocok dengan nama penyebaran.

Selanjutnya kita akan mencetak konten asisten yang baru saja kita buat untuk mengonfirmasi bahwa pembuatan berhasil:

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"
    }
  ]
}

Membuat utas

Sekarang mari kita buat utas.

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

Utas pada dasarnya adalah catatan sesi percakapan antara asisten dan pengguna. Ini mirip dengan array/daftar pesan dalam panggilan API penyelesaian obrolan biasa. Salah satu perbedaan utama, tidak seperti array pesan penyelesaian obrolan, Anda tidak perlu melacak token dengan setiap panggilan untuk memastikan bahwa Anda tetap berada di bawah panjang konteks model. Utas mengabstraksi detail manajemen ini dan akan memadatkan riwayat utas sesuai kebutuhan untuk memungkinkan percakapan berlanjut. Kemampuan untuk utas untuk menyelesaikan ini dengan percakapan yang lebih besar ditingkatkan saat menggunakan model terbaru, yang memiliki panjang konteks dan dukungan yang lebih besar untuk fitur terbaru.

Selanjutnya buat pertanyaan pengguna pertama untuk ditambahkan ke utas.

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

Mencantumkan pesan utas

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
}

Jalankan utas

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
)

Kami juga dapat meneruskan instructions parameter di sini, tetapi ini akan mengambil alih instruksi yang ada yang telah kami berikan untuk asisten.

Mengambil status utas

# 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

Bergantung pada kompleksitas kueri yang Anda jalankan, utas bisa memakan waktu lebih lama untuk dijalankan. Dalam hal ini Anda dapat membuat perulangan untuk memantau status eksekusi utas dengan kode seperti contoh di bawah ini:

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

Saat Eksekusi atau in_progress dalam status nonterminal lainnya, utas dikunci. Saat utas dikunci, pesan baru tidak dapat ditambahkan, dan eksekusi baru tidak dapat dibuat.

Mencantumkan postingan pesan utas yang dijalankan

Setelah status eksekusi menunjukkan keberhasilan penyelesaian, Anda dapat mencantumkan konten utas lagi untuk mengambil respons model dan alat apa pun:

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
}

Mengambil ID file

Kami telah meminta agar model menghasilkan gambar gelombang sinus. Untuk mengunduh gambar, pertama-tama kita perlu mengambil ID file gambar.

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

Unduh citra

content = client.files.content(image_file_id)

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

Buka gambar secara lokal setelah diunduh:

from PIL import Image

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

Cuplikan layar penerjemah kode menghasilkan gelombang sinus.

Ajukan pertanyaan tindak lanjut pada utas

Karena asisten tidak cukup mengikuti instruksi kami dan menyertakan kode yang dijalankan dalam bagian teks responsnya memungkinkan untuk secara eksplisit meminta informasi tersebut.

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

Sekali lagi kita harus menjalankan dan mengambil status utas:

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

Setelah status eksekusi selesai, kita akan mencantumkan pesan di utas lagi yang sekarang harus menyertakan respons terhadap pertanyaan terbaru kita.

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
}

Untuk mengekstrak hanya respons terhadap pertanyaan terbaru kami:

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

Tentu saja, berikut adalah kode yang saya gunakan untuk menghasilkan visualisasi gelombang sinus:

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()

Mode gelap

Mari kita tambahkan satu pertanyaan terakhir ke utas untuk melihat apakah penerjemah kode dapat menukar bagan ke mode gelap bagi kita.

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

Ekstrak ID file gambar baru dan unduh dan tampilkan gambar:

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()

Cuplikan layar penerjemah kode menghasilkan gelombang sinus dalam mode gelap.

Referensi tambahan

Menjalankan definisi status

Status Definisi
queued Saat Eksekusi pertama kali dibuat atau saat Anda menyelesaikan required_action, Eksekusi dipindahkan ke status antrean. Mereka harus segera pindah ke in_progress.
in_progress Saat in_progress, Asisten menggunakan model dan alat untuk melakukan langkah-langkah. Anda dapat melihat kemajuan yang dibuat oleh Jalankan dengan memeriksa Langkah Eksekusi.
completed Eksekusi berhasil diselesaikan! Sekarang Anda dapat melihat semua Pesan yang ditambahkan Asisten ke Utas, dan semua langkah yang diambil Eksekusi. Anda juga dapat melanjutkan percakapan dengan menambahkan lebih banyak Pesan pengguna ke Utas dan membuat Eksekusi lain.
requires_action Saat menggunakan alat panggilan Fungsi, Jalankan akan berpindah ke status required_action setelah model menentukan nama dan argumen fungsi yang akan dipanggil. Anda kemudian harus menjalankan fungsi-fungsi tersebut dan mengirimkan output sebelum proses berlangsung. Jika output tidak disediakan sebelum tanda waktu expires_at berlalu (kira-kira 10 menit sebelumnya pembuatan), eksekusi akan berpindah ke status kedaluwarsa.
expired Ini terjadi ketika output panggilan fungsi tidak dikirimkan sebelum expires_at dan eksekusi kedaluwarsa. Selain itu, jika eksekusi membutuhkan waktu terlalu lama untuk dijalankan dan melampaui waktu yang dinyatakan dalam expires_at, sistem kami akan kedaluwarsa eksekusi.
cancelling Anda dapat mencoba membatalkan eksekusi in_progress menggunakan titik akhir Batalkan Eksekusi. Setelah upaya untuk membatalkan berhasil, status Jalankan berpindah ke dibatalkan. Pembatalan dicoba tetapi tidak dijamin.
cancelled Eksekusi berhasil dibatalkan.
failed Anda dapat melihat alasan kegagalan dengan melihat last_error objek di Jalankan. Tanda waktu untuk kegagalan akan dicatat di bawah failed_at.

Anotasi pesan

Anotasi pesan asisten berbeda dari anotasi pemfilteran konten yang ada dalam respons API penyelesaian dan penyelesaian obrolan. Anotasi asisten dapat terjadi dalam array konten objek. Anotasi memberikan informasi tentang bagaimana Anda harus membuat anotasi teks dalam respons kepada pengguna.

Saat anotasi ada di array konten Pesan, Anda akan melihat substring yang dihasilkan model yang tidak dapat dilepaskan dalam teks yang perlu Anda ganti dengan anotasi yang benar. String ini mungkin terlihat seperti 【13†source】 atau sandbox:/mnt/data/file.csv. Berikut adalah cuplikan kode Python dari OpenAI yang mengganti string ini dengan informasi yang ada dalam anotasi.


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)

Anotasi pesan Deskripsi
file_citation Kutipan file dibuat oleh alat pengambilan dan menentukan referensi ke kutipan tertentu dalam file tertentu yang diunggah dan digunakan oleh Asisten untuk menghasilkan respons.
file_path Anotasi jalur file dibuat oleh alat code_interpreter dan berisi referensi ke file yang dihasilkan oleh alat.

Lihat juga