Aracılığıyla paylaş


Azure OpenAI Yardımcıları ile çalışmaya başlama (Önizleme)

Azure OpenAI Yardımcıları (Önizleme), özel talimatlar aracılığıyla ihtiyaçlarınıza göre uyarlanmış ve kod yorumlayıcı ve özel işlevler gibi gelişmiş araçlarla güçlendirilmiş yapay zeka yardımcıları oluşturmanıza olanak tanır. Bu makalede, Yardımcılar API'sini kullanmaya başlamaya ilişkin ayrıntılı bir kılavuz sağlıyoruz.

Not

  • Dosya arama , yardımcı başına 10.000'e kadar dosya alabilir - öncekinden 500 kat daha fazla. Hızlıdır, çok iş parçacıklı aramalar aracılığıyla paralel sorguları destekler ve gelişmiş yeniden boyutlandırma ve sorgu yeniden yazma özellikleri sunar.
    • Vektör deposu API'de yeni bir nesnedir. Bir dosya bir vektör deposuna eklendikten sonra otomatik olarak ayrıştırılır, öbeklenip eklenir ve aranmaya hazır hale getirilir. Vektör depoları yardımcılar ve iş parçacıkları arasında kullanılabilir ve bu da dosya yönetimini ve faturalamayı basitleştirir.
  • Belirli bir çalıştırmada tool_choice belirli bir aracın (dosya arama, kod yorumlayıcı veya işlev gibi) kullanılmasını zorlamak için kullanılabilecek parametre desteği ekledik.

Yardımcılar desteği

Bölge ve model desteği

Kod yorumlayıcı, Azure OpenAI Yardımcıları tarafından desteklenen tüm bölgelerde kullanılabilir. Modeller sayfası, Yardımcıların şu anda desteklendiği bölgeler/modeller hakkında en güncel bilgileri içerir.

API Sürümleri

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

Desteklenen dosya türleri

Dosya biçimi MIME Türü Kod Yorumlayıcı
c. metin/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 uygulama/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 metin/x-tex
.txt text/plain
.Css metin/css
.jpeg resim/jpeg
.jpg resim/jpeg
.js text/javascript
.gif resim/gif
.png resim/png
.tar application/x-tar
.Ts application/typescript
.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xml application/xml veya "text/xml"
.zip application/zip

Araçlar

İpucu

Belirli bir çalıştırmada tool_choice belirli bir aracın (, veya functiongibifile_searchcode_interpreter) kullanılmasını zorlamak için kullanılabilecek parametresi için destek ekledik.

Tek bir yardımcı, kod yorumlayıcı ve dosya arama dahil olmak üzere en fazla 128 aracıya erişebilir, ancak işlevler aracılığıyla kendi özel araçlarınızı da tanımlayabilirsiniz.

Dosyalar

Dosyalar Studio aracılığıyla veya program aracılığıyla karşıya yüklenebilir. file_ids parametresi, dosyalara erişim gibi code_interpreter araçlar vermek için gereklidir. Dosya yükleme uç noktasını kullanırken, Yardımcılar API'siyle purpose kullanılacak yardımcılar olarak ayarlanmış olmalıdır.

Yardımcılar oyun alanı

Hızlı başlangıç kılavuzumuzda Asistanlar oyun alanı ile ilgili bir kılavuz sunuyoruz. Bu, yardımcıların özelliklerini test etmek için kod içermeyen bir ortam sağlar.

Yardımcılar bileşenleri

Bileşen Açıklama
Asistan Araçlarla birlikte Azure OpenAI modellerini kullanan özel yapay zeka.
İplik Bir Yardımcı ile kullanıcı arasındaki konuşma oturumu. İş parçacıkları İletileri depolar ve içeriği bir modelin bağlamıyla sığdırmak için kesmeyi otomatik olarak işler.
İleti Bir Yardımcı veya kullanıcı tarafından oluşturulan ileti. İletiler metin, resim ve diğer dosyaları içerebilir. İletiler, İş Parçacığında bir liste olarak depolanır.
Çalıştır İş Parçacığının içeriğine göre çalışmaya başlamak için Bir Yardımcı'nın etkinleştirilmesi. Yardımcı, modelleri ve araçları çağırarak görevleri gerçekleştirmek için yapılandırmasını ve İş Parçacığının İletilerini kullanır. Bir Çalıştırmanın parçası olarak, Yardımcı İletileri İş Parçacığına ekler.
Çalıştırma Adımı Yardımcı'nın Bir Çalıştırmanın parçası olarak gerçekleştirilir adımların ayrıntılı listesi. Bir Yardımcı, çalıştırılırken araçları çağırabilir veya İletiler oluşturabilir. Çalıştırma Adımlarını incelemek, Yardımcı'nın nihai sonuçlarına nasıl varmakta olduğunu anlamanıza olanak tanır.

İlk Yardımcınızı ayarlama

Yardımcı oluşturma

Bu örnekte, aracın özelliklerini code_interpreter kullanarak görselleştirmeler oluşturmak için kod yazan bir yardımcı oluşturacağız. Aşağıdaki örneklerin Jupyter Notebooks gibi bir ortamda sıralı olarak çalıştırılması amaçlanmıştır.

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

Yukarıdaki yapılandırmada dikkate alınması gereken birkaç ayrıntı vardır:

  • Bu yardımcının satırıyla tools=[{"type": "code_interpreter"}],kod yorumlayıcıya erişmesini sağlarız. Bu, modelin kullanıcının sorusuna yanıtlar formüle etmeye yardımcı olmak için kod çalıştırması ve yürütmesi için kum kutulu python ortamına erişmesini sağlar.
  • Yönergelerde modele kodu yürütebileceğini anımsatacağız. Bazen modelin belirli bir sorguyu çözmek için doğru ara aracı yönlendirme konusunda yardıma ihtiyacı vardır. Kod yorumlayıcının bir parçası olduğunu bildiğiniz belirli bir yanıt oluşturmak için belirli bir kitaplığı kullanmak istediğinizi biliyorsanız, "x yapmak için Matplotlib'i kullanma" gibi bir şey söyleyerek rehberlik sağlamaya yardımcı olabilir.
  • Bu Azure OpenAI olduğundan, girdiğiniz model= değerin dağıtım adıyla eşleşmesi gerekir.

Şimdi oluşturma işleminin başarılı olduğunu onaylamak için yeni oluşturduğumuz yardımcının içeriğini yazdıracağız:

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

İş parçacığı oluşturma

Şimdi bir iş parçacığı oluşturalım.

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

İş parçacığı temelde yardımcı ile kullanıcı arasındaki konuşma oturumunun kaydıdır. Bu, tipik bir sohbet tamamlama API çağrısındaki dizi/liste iletilerine benzer. Önemli farklardan biri, sohbet tamamlama iletileri dizisinin aksine, modelin bağlam uzunluğunun altında kaldığınıza emin olmak için her çağrıyla belirteçleri izlemeniz gerekmez. İş parçacıkları bu yönetim ayrıntılarını soyutlar ve konuşmanın devam edebilmesi için iş parçacığı geçmişini gerektiği gibi sıkıştırır. İş parçacıklarının bunu daha büyük konuşmalarla gerçekleştirme özelliği, bağlam uzunlukları ve en son özellikler için daha büyük destek içeren en son modeller kullanılırken geliştirilmiştir.

Ardından, iş parçacığına eklenecek ilk kullanıcı sorusunu oluşturun.

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

İş parçacığı iletilerini listeleme

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
}

İş parçacığını çalıştırma

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
)

Burada bir instructions parametre de geçirebiliriz, ancak bu, yardımcı için önceden sağladığımız mevcut yönergeleri geçersiz kılabilir.

İş parçacığı durumunu alma

# 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

Çalıştırdığınız sorgunun karmaşıklık düzeyine bağlı olarak, iş parçacığının yürütülmesi daha uzun sürebilir. Bu durumda aşağıdaki örnekte olduğu gibi kodla iş parçacığının çalışma durumunu izlemek için bir döngü oluşturabilirsiniz:

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

Bir Çalıştırma olduğunda in_progress veya diğer terim dışı durumlarda iş parçacığı kilitlenir. İş parçacığı kilitli olduğunda yeni iletiler eklenemez ve yeni çalıştırmalar oluşturulamaz.

Çalıştırma sonrasında iş parçacığı iletilerini listeleme

Çalıştırma durumu başarılı tamamlandı ifadesini gösterdiğinde, modelin ve herhangi bir araç yanıtını almak için iş parçacığının içeriğini yeniden listeleyebilirsiniz:

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
}

Dosya kimliğini alma

Modelin sinüs dalgasının görüntüsünü oluşturmasını istemiştik. Görüntüyü indirmek için önce görüntüler dosya kimliğini almalıyız.

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

Görüntüyü indirin

content = client.files.content(image_file_id)

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

İndirildikten sonra resmi yerel olarak açın:

from PIL import Image

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

Kod yorumlayıcı tarafından oluşturulan sinüs dalgasının ekran görüntüsü.

yazışmada bir takip sorusu sorun

Yardımcı yönergelerimizi tam olarak izlemediğinden ve yanıtının metin bölümüne çalıştırılan kodu eklediğinden, bu bilgileri açıkça isteyebilir.

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

Yine iş parçacığının durumunu çalıştırmamız ve almanız gerekir:

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

Çalıştırma durumu tamamlandıktan sonra, iş parçacığındaki iletileri yeniden listeleyeceğiz ve bu da en son sorumuzun yanıtını içermelidir.

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
}

Yalnızca en son sorumuzun yanıtını ayıklamak için:

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

Sinüs dalga görselleştirmesini oluşturmak için kullandığım kod şudur:

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

Koyu mod

Kod yorumlayıcının grafiği bizim için koyu moda değiştirip değiştiremediğini görmek için yazışmaya son bir soru ekleyelim.

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

Yeni görüntü dosyası kimliğini ayıklayın ve görüntüyü indirip görüntüleyin:

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

Koyu modda kod yorumlayıcı tarafından oluşturulan sinüs dalgasının ekran görüntüsü.

Ek başvurular

Durum tanımlarını çalıştırma

Durum Tanım
queued Çalıştırmalar ilk oluşturulduğunda veya required_action tamamladığınızda, bunlar kuyruğa alınmış duruma taşınır. Hemen in_progress geçmeleri gerekir.
in_progress in_progress, Yardımcı adımları gerçekleştirmek için modeli ve araçları kullanır. Çalıştırma Adımları'nı inceleyerek Çalıştır tarafından ilerleme durumunu görüntüleyebilirsiniz.
completed Çalıştırma başarıyla tamamlandı! Artık Yardımcı'nın İş Parçacığına eklediği tüm İletileri ve Çalıştırma'nın uyguladığı tüm adımları görüntüleyebilirsiniz. İş Parçacığına daha fazla kullanıcı İletisi ekleyerek ve başka bir Çalıştırma oluşturarak da konuşmaya devam edebilirsiniz.
requires_action İşlev çağırma aracını kullanırken, model çağrılacak işlevlerin adlarını ve bağımsız değişkenlerini belirledikten sonra Çalıştır required_action durumuna geçer. Ardından bu işlevleri çalıştırmanız ve çalıştırma devam etmeden önce çıkışları göndermeniz gerekir. Çıkışlar expires_at zaman damgası geçilmeden önce sağlanmazsa (oluşturma işleminden yaklaşık 10 dakika sonra), çalıştırma süresi dolmuş duruma geçer.
expired İşlev çağrısı çıkışları expires_at önce gönderilmediğinde ve çalıştırmanın süresi dolduğunda bu durum ortaya çıkar. Buna ek olarak, çalıştırmaların yürütülmesi çok uzun sürerse ve expires_at belirtilen sürenin ötesine geçerse sistemlerimiz çalıştırmanın süresi dolar.
cancelling Çalıştırmayı İptal Et uç noktasını kullanarak bir in_progress çalıştırmasını iptal etmeye çalışabilirsiniz. İptal etme girişimi başarılı olduktan sonra Çalıştır'ın durumu iptal edildi olarak taşınır. İptal denendi ancak garanti edilemedi.
cancelled Çalıştırma başarıyla iptal edildi.
failed Çalıştır'daki nesneye bakarak hatanın last_error nedenini görüntüleyebilirsiniz. Hatanın zaman damgası failed_at altına kaydedilir.

İleti ek açıklamaları

Yardımcı ileti ek açıklamaları, tamamlanma ve sohbet tamamlama API'sinin yanıtlarında bulunan içerik filtreleme ek açıklamalarından farklıdır. Yardımcı ek açıklamaları, nesnenin içerik dizisi içinde oluşabilir. Ek açıklamalar, kullanıcıya verilen yanıtlardaki metne nasıl açıklama ek açıklama ekliydiğiniz hakkında bilgi sağlar.

İleti içeriği dizisinde ek açıklamalar mevcut olduğunda, metinde doğru ek açıklamalarla değiştirmeniz gereken model tarafından oluşturulan okunamaz alt dizeler görürsünüz. Bu dizeler veya sandbox:/mnt/data/file.csvgibi 【13†source】 görünebilir. Bu dizeleri ek açıklamalarda bulunan bilgilerle değiştiren OpenAI'den bir Python kod parçacığı aşağıdadır.


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)

İleti ek açıklaması Açıklama
file_citation Dosya alıntıları alma aracı tarafından oluşturulur ve yanıt oluşturmak için Yardımcı tarafından yüklenen ve kullanılan belirli bir dosyada belirli bir teklife başvurular tanımlar.
file_path Dosya yolu ek açıklamaları code_interpreter aracı tarafından oluşturulur ve araç tarafından oluşturulan dosyalara başvurular içerir.

Ayrıca bkz.