Сохраненные результаты завершений позволяют записывать историю беседы из сеансов завершения чата для использования в качестве наборов данных для оценки и дополнительной настройки.
Поддержка хранимых завершений
поддержка API
Поддержка впервые добавлена в 2024-10-01-preview
, используйте 2025-02-01-preview
или более позднюю версию для доступа к новейшим функциям.
Тип развертывания
Поддержка сохраненных операций завершения осуществляется для всех типов развертывания Azure OpenAI: стандартного, глобального, datazone и заданного.
Доступность модели и региона
Пока вы используете API завершения чата для умозаключений, вы можете воспользоваться сохраненными завершениями. Она поддерживается для всех моделей Azure OpenAI и во всех поддерживаемых регионах (включая глобальные регионы).
Чтобы включить хранимые завершения для развертывания Azure OpenAI, задайте для параметра значение store
True
. Используйте параметр metadata
, чтобы обогатить сохраненный набор данных завершения дополнительными сведениями.
import os
from openai import AzureOpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
)
client = AzureOpenAI(
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
azure_ad_token_provider=token_provider,
api_version="2025-02-01-preview"
)
completion = client.chat.completions.create(
model="gpt-4o", # replace with model deployment name
store= True,
metadata = {
"user": "admin",
"category": "docs-test",
},
messages=[
{"role": "system", "content": "Provide a clear and concise summary of the technical content, highlighting key concepts and their relationships. Focus on the main ideas and practical implications."},
{"role": "user", "content": "Ensemble methods combine multiple machine learning models to create a more robust and accurate predictor. Common techniques include bagging (training models on random subsets of data), boosting (sequentially training models to correct previous errors), and stacking (using a meta-model to combine base model predictions). Random Forests, a popular bagging method, create multiple decision trees using random feature subsets. Gradient Boosting builds trees sequentially, with each tree focusing on correcting the errors of previous trees. These methods often achieve better performance than single models by reducing overfitting and variance while capturing different aspects of the data."}
]
)
print(completion.choices[0].message)
import os
from openai import AzureOpenAI
client = AzureOpenAI(
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
api_version="2025-02-01-preview",
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT")
)
completion = client.chat.completions.create(
model="gpt-4o", # replace with model deployment name
store= True,
metadata = {
"user": "admin",
"category": "docs-test",
},
messages=[
{"role": "system", "content": "Provide a clear and concise summary of the technical content, highlighting key concepts and their relationships. Focus on the main ideas and practical implications."},
{"role": "user", "content": "Ensemble methods combine multiple machine learning models to create a more robust and accurate predictor. Common techniques include bagging (training models on random subsets of data), boosting (sequentially training models to correct previous errors), and stacking (using a meta-model to combine base model predictions). Random Forests, a popular bagging method, create multiple decision trees using random feature subsets. Gradient Boosting builds trees sequentially, with each tree focusing on correcting the errors of previous trees. These methods often achieve better performance than single models by reducing overfitting and variance while capturing different aspects of the data."}
]
)
print(completion.choices[0].message)
Майкрософт Ентра айди
curl $AZURE_OPENAI_ENDPOINT/openai/deployments/gpt-4o/chat/completions?api-version=2025-02-01-preview \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_OPENAI_AUTH_TOKEN" \
-d '{
"model": "gpt-4o",
"store": true,
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Hello!"
}
]
}'
Ключ API
curl $AZURE_OPENAI_ENDPOINT/openai/deployments/gpt-4o/chat/completions?api-version=2025-02-01-preview \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "gpt-4o",
"store": true,
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Hello!"
}
]
}'
{
"id": "chatcmpl-B4eQ716S5wGUyFpGgX2MXnJEC5AW5",
"choices": [
{
"finish_reason": "stop",
"index": 0,
"logprobs": null,
"message": {
"content": "Ensemble methods enhance machine learning performance by combining multiple models to create a more robust and accurate predictor. The key techniques include:\n\n1. **Bagging (Bootstrap Aggregating)**: Involves training multiple models on random subsets of the data to reduce variance and overfitting. A popular method within bagging is Random Forests, which build numerous decision trees using random subsets of features and data samples.\n\n2. **Boosting**: Focuses on sequentially training models, where each new model attempts to correct the errors made by previous ones. Gradient Boosting is a common boosting technique that builds trees sequentially, concentrating on the mistakes of earlier trees to improve accuracy.\n\n3. **Stacking**: Uses a meta-model to combine predictions from various base models, leveraging their strengths to enhance overall predictions.\n\nThese ensemble methods generally outperform individual models because they effectively handle overfitting, reduce variance, and capture diverse aspects of the data. In practical applications, they are valued for their ability to improve model accuracy and stability.",
"refusal": null,
"role": "assistant",
"audio": null,
"function_call": null,
"tool_calls": null
},
"content_filter_results": {
"hate": {
"filtered": false,
"severity": "safe"
},
"protected_material_code": {
"filtered": false,
"detected": false
},
"protected_material_text": {
"filtered": false,
"detected": false
},
"self_harm": {
"filtered": false,
"severity": "safe"
},
"sexual": {
"filtered": false,
"severity": "safe"
},
"violence": {
"filtered": false,
"severity": "safe"
}
}
}
],
"created": 1740448387,
"model": "gpt-4o-2024-08-06",
"object": "chat.completion",
"service_tier": null,
"system_fingerprint": "fp_b705f0c291",
"usage": {
"completion_tokens": 205,
"prompt_tokens": 157,
"total_tokens": 362,
"completion_tokens_details": {
"accepted_prediction_tokens": 0,
"audio_tokens": 0,
"reasoning_tokens": 0,
"rejected_prediction_tokens": 0
},
"prompt_tokens_details": {
"audio_tokens": 0,
"cached_tokens": 0
}
},
"prompt_filter_results": [
{
"prompt_index": 0,
"content_filter_results": {
"hate": {
"filtered": false,
"severity": "safe"
},
"jailbreak": {
"filtered": false,
"detected": false
},
"self_harm": {
"filtered": false,
"severity": "safe"
},
"sexual": {
"filtered": false,
"severity": "safe"
},
"violence": {
"filtered": false,
"severity": "safe"
}
}
}
]
}
После включения сохраненных завершений для Azure OpenAI, они начнут отображаться на портале Azure AI Foundry в разделе "Хранимые завершения".
Перегонка
Дистилляция позволяет преобразовать ваши сохраненные результаты в набор данных для точной настройки. Распространенный вариант использования заключается в использовании хранимых завершений с более крупной более мощной моделью для конкретной задачи, а затем использовать сохраненные завершения для обучения меньшей модели на высококачественных примерах взаимодействия модели.
Дистилляция требует не менее 10 хранимых результатов, хотя рекомендуется предоставить от сотен до тысяч хранимых результатов для достижения наилучших результатов.
В области «Хранимые завершения» на портале Azure AI Foundry используйте параметры фильтра, чтобы выбрать завершения, с которыми вы хотите обучить свою модель.
Чтобы начать дистилляцию, выберите "Дистилля"
Выберите модель, которую вы хотите точно настроить с помощью хранимого набора данных завершения.
Подтвердите, какую версию модели вы хотите откорректировать.
.jsonl
Файл со случайным именем будет создан в качестве обучаемого набора данных из сохраненных завершений. Выберите файл >Далее.
Замечание
Сохраненные файлы обучения по дистилляции завершения не могут быть доступны напрямую и не могут быть экспортированы вовне или скачаны.
Остальные шаги соответствуют типичным шагам по настройке Azure OpenAI. Дополнительные сведения см. в нашем руководстве по началу работы с тонкой настройкой.
Оценка
Оценка крупных языковых моделей является критически важным шагом в измерении их производительности в различных задачах и измерениях. Это особенно важно для точно настроенных моделей, где оценка повышения производительности (или потерь) от обучения имеет решающее значение. Подробные оценки помогут вам понять, как различные версии модели могут повлиять на ваше приложение или сценарий.
Хранимые завершения можно использовать в качестве набора данных для проведения оценок.
В области "Хранимые завершения" на портале Azure AI Foundry используйте параметры фильтра, чтобы выбрать завершения, которые необходимо включить в набор данных оценки.
Чтобы настроить оценку, нажмите кнопку "Оценка"
Откроется панель "Оценки" с предварительно заполненным .jsonl
файлом с случайным образом созданным именем, созданным в качестве набора данных оценки из сохраненных завершений.
Замечание
Сохраненные файлы данных оценки завершения нельзя напрямую получить и нельзя экспортировать/скачать.
Дополнительные сведения об оценке см. в статье "Начало работы с оценками"
API завершений, хранимых в памяти
Чтобы получить доступ к командам API хранимых завершений, может потребоваться обновить версию библиотеки OpenAI.
pip install --upgrade openai
Список сохраненных завершений
Дополнительные параметры:
-
metadata
: фильтрация по паре "ключ-значение" в хранимых завершениях
-
after
: идентификатор последнего сохраненного сообщения о завершении из предыдущего запроса на разбиение на страницы.
-
limit
: Количество хранимых сообщений о завершении для извлечения.
-
order
: порядок результатов по индексу (возрастанию или убыванию).
from openai import AzureOpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
)
client = AzureOpenAI(
azure_endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com",
azure_ad_token_provider=token_provider,
api_version="2025-02-01-preview"
)
response = client.chat.completions.list()
print(response.model_dump_json(indent=2))
from openai import AzureOpenAI
client = AzureOpenAI(
azure_endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com",
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
api_version="2025-02-01-preview"
)
response = client.chat.completions.list()
print(response.model_dump_json(indent=2))
Майкрософт Ентра айди
curl https://YOUR-RESOURCE-NAME.openai.azure.com/openai/chat/completions?api-version=2025-02-01-preview \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_OPENAI_AUTH_TOKEN" \
Ключ API
curl https://YOUR-RESOURCE-NAME.openai.azure.com/openai/chat/completions?api-version=2025-02-01-preview \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
{
"data": [
{
"id": "chatcmpl-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u",
"choices": [
{
"finish_reason": null,
"index": 0,
"logprobs": null,
"message": {
"content": "Ensemble methods enhance machine learning performance by combining multiple models to create a more robust and accurate predictor. The key techniques include:\n\n1. **Bagging (Bootstrap Aggregating):** This involves training models on random subsets of the data to reduce variance and prevent overfitting. Random Forests, a popular bagging method, build multiple decision trees using random feature subsets, leading to robust predictions.\n\n2. **Boosting:** This sequential approach trains models to correct the errors of their predecessors, thereby focusing on difficult-to-predict data points. Gradient Boosting is a common implementation that sequentially builds decision trees, each improving upon the prediction errors of the previous ones.\n\n3. **Stacking:** This technique uses a meta-model to combine the predictions of multiple base models, leveraging their diverse strengths to enhance overall prediction accuracy.\n\nThe practical implications of ensemble methods include achieving superior model performance compared to single models by capturing various data patterns and reducing overfitting and variance. These methods are widely used in applications where high accuracy and model reliability are critical.",
"refusal": null,
"role": "assistant",
"audio": null,
"function_call": null,
"tool_calls": null
}
}
],
"created": 1740447656,
"model": "gpt-4o-2024-08-06",
"object": null,
"service_tier": null,
"system_fingerprint": "fp_b705f0c291",
"usage": {
"completion_tokens": 208,
"prompt_tokens": 157,
"total_tokens": 365,
"completion_tokens_details": null,
"prompt_tokens_details": null
},
"request_id": "0000aaaa-11bb-cccc-dd22-eeeeee333333",
"seed": -430976584126747957,
"top_p": 1,
"temperature": 1,
"presence_penalty": 0,
"frequency_penalty": 0,
"metadata": {
"user": "admin",
"category": "docs-test"
}
}
],
"has_more": false,
"object": "list",
"total": 1,
"first_id": "chatcmpl-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u",
"last_id": "chatcmpl-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u"
}
Получение сохраненного завершения
Получить сохраненное завершение по идентификатору.
from openai import AzureOpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
)
client = AzureOpenAI(
azure_endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/",
azure_ad_token_provider=token_provider,
api_version="2025-02-01-preview"
)
response = client.chat.completions.retrieve("chatcmpl-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u")
print(response.model_dump_json(indent=2))
from openai import AzureOpenAI
client = AzureOpenAI(
azure_endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com",
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
api_version="2025-02-01-preview"
)
response = client.chat.completions.retrieve("chatcmpl-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u")
print(response.model_dump_json(indent=2))
Майкрософт Ентра айди
curl https://YOUR-RESOURCE-NAME.openai.azure.com/openai/chat/completions/chatcmpl-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u?api-version=2025-02-01-preview \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_OPENAI_AUTH_TOKEN" \
Ключ API
curl https://YOUR-RESOURCE-NAME.openai.azure.com/openai/chat/completions/chatcmpl-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u?api-version=2025-02-01-preview \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
{
"id": "chatcmpl-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u",
"choices": [
{
"finish_reason": null,
"index": 0,
"logprobs": null,
"message": {
"content": "Ensemble methods enhance machine learning performance by combining multiple models to create a more robust and accurate predictor. The key techniques include:\n\n1. **Bagging (Bootstrap Aggregating):** This involves training models on random subsets of the data to reduce variance and prevent overfitting. Random Forests, a popular bagging method, build multiple decision trees using random feature subsets, leading to robust predictions.\n\n2. **Boosting:** This sequential approach trains models to correct the errors of their predecessors, thereby focusing on difficult-to-predict data points. Gradient Boosting is a common implementation that sequentially builds decision trees, each improving upon the prediction errors of the previous ones.\n\n3. **Stacking:** This technique uses a meta-model to combine the predictions of multiple base models, leveraging their diverse strengths to enhance overall prediction accuracy.\n\nThe practical implications of ensemble methods include achieving superior model performance compared to single models by capturing various data patterns and reducing overfitting and variance. These methods are widely used in applications where high accuracy and model reliability are critical.",
"refusal": null,
"role": "assistant",
"audio": null,
"function_call": null,
"tool_calls": null
}
}
],
"created": 1740447656,
"model": "gpt-4o-2024-08-06",
"object": "chat.completion",
"service_tier": null,
"system_fingerprint": "fp_b705f0c291",
"usage": {
"completion_tokens": 208,
"prompt_tokens": 157,
"total_tokens": 365,
"completion_tokens_details": null,
"prompt_tokens_details": null
},
"request_id": "0000aaaa-11bb-cccc-dd22-eeeeee333333",
"seed": -430976584126747957,
"top_p": 1,
"temperature": 1,
"presence_penalty": 0,
"frequency_penalty": 0,
"metadata": {
"user": "admin",
"category": "docs-test"
}
}
Получение сохраненных сообщений о завершении чата
Дополнительные параметры:
-
after
: идентификатор последнего сохраненного сообщения о завершении из предыдущего запроса на разбиение на страницы.
-
limit
: Количество хранимых сообщений о завершении для извлечения.
-
order
: порядок результатов по индексу (возрастанию или убыванию).
from openai import AzureOpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
)
client = AzureOpenAI(
azure_endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/",
azure_ad_token_provider=token_provider,
api_version="2025-02-01-preview"
)
response = client.chat.completions.messages.list("chatcmpl-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u", limit=2)
print(response.model_dump_json(indent=2))
from openai import AzureOpenAI
client = AzureOpenAI(
azure_endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com",
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
api_version="2025-02-01-preview"
)
response = client.chat.completions.messages.list("chatcmpl-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u", limit=2)
print(response.model_dump_json(indent=2))
Майкрософт Ентра айди
curl https://YOUR-RESOURCE-NAME.openai.azure.com/openai/chat/completions/chatcmpl-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u/messages?api-version=2025-02-01-preview \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_OPENAI_AUTH_TOKEN" \
Ключ API
curl https://YOUR-RESOURCE-NAME.openai.azure.com/openai/chat/completions/chatcmpl-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u/messages?api-version=2025-02-01-preview \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
{
"data": [
{
"content": "Provide a clear and concise summary of the technical content, highlighting key concepts and their relationships. Focus on the main ideas and practical implications.",
"refusal": null,
"role": "system",
"audio": null,
"function_call": null,
"tool_calls": null,
"id": "chatcmpl-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u-0"
},
{
"content": "Ensemble methods combine multiple machine learning models to create a more robust and accurate predictor. Common techniques include bagging (training models on random subsets of data), boosting (sequentially training models to correct previous errors), and stacking (using a meta-model to combine base model predictions). Random Forests, a popular bagging method, create multiple decision trees using random feature subsets. Gradient Boosting builds trees sequentially, with each tree focusing on correcting the errors of previous trees. These methods often achieve better performance than single models by reducing overfitting and variance while capturing different aspects of the data.",
"refusal": null,
"role": "user",
"audio": null,
"function_call": null,
"tool_calls": null,
"id": "chatcmpl-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u-1"
}
],
"has_more": false,
"object": "list",
"total": 2,
"first_id": "chatcmpl-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u-0",
"last_id": "chatcmpl-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u-1"
}
Обновление сохраненного завершения чата
Добавьте пары "ключ:значение" метаданных в уже существующее сохраненное завершение.
from openai import AzureOpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
)
client = AzureOpenAI(
azure_endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/",
azure_ad_token_provider=token_provider,
api_version="2025-02-01-preview"
)
response = client.chat.completions.update(
"chatcmpl-C2dE3fH4iJ5kL6mN7oP8qR9sT0uV1w",
metadata={"fizz": "buzz"}
)
print(response.model_dump_json(indent=2))
from openai import AzureOpenAI
client = AzureOpenAI(
azure_endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com",
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
api_version="2025-02-01-preview"
)
response = client.chat.completions.update(
"chatcmpl-C2dE3fH4iJ5kL6mN7oP8qR9sT0uV1w",
metadata={"fizz": "buzz"}
)
print(response.model_dump_json(indent=2))
Майкрософт Ентра айди
curl -X https://YOUR-RESOURCE-NAME.openai.azure.com/openai/chat/completions/chatcmpl-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u?api-version=2025-02-01-preview \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_OPENAI_AUTH_TOKEN"
-d '{
"metadata": {
"fizz": "buzz"
}
}'
Ключ API
curl -X https://YOUR-RESOURCE-NAME.openai.azure.com/openai/chat/completions/chatcmpl-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u?api-version=2025-02-01-preview \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY"
-d '{
"metadata": {
"fizz": "buzz"
}
}'
"id": "chatcmpl-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u",
"choices": [
{
"finish_reason": null,
"index": 0,
"logprobs": null,
"message": {
"content": "Ensemble methods enhance machine learning performance by combining multiple models to create a more robust and accurate predictor. The key techniques include:\n\n1. **Bagging (Bootstrap Aggregating):** This involves training models on random subsets of the data to reduce variance and prevent overfitting. Random Forests, a popular bagging method, build multiple decision trees using random feature subsets, leading to robust predictions.\n\n2. **Boosting:** This sequential approach trains models to correct the errors of their predecessors, thereby focusing on difficult-to-predict data points. Gradient Boosting is a common implementation that sequentially builds decision trees, each improving upon the prediction errors of the previous ones.\n\n3. **Stacking:** This technique uses a meta-model to combine the predictions of multiple base models, leveraging their diverse strengths to enhance overall prediction accuracy.\n\nThe practical implications of ensemble methods include achieving superior model performance compared to single models by capturing various data patterns and reducing overfitting and variance. These methods are widely used in applications where high accuracy and model reliability are critical.",
"refusal": null,
"role": "assistant",
"audio": null,
"function_call": null,
"tool_calls": null
}
}
],
"created": 1740447656,
"model": "gpt-4o-2024-08-06",
"object": "chat.completion",
"service_tier": null,
"system_fingerprint": "fp_b705f0c291",
"usage": {
"completion_tokens": 208,
"prompt_tokens": 157,
"total_tokens": 365,
"completion_tokens_details": null,
"prompt_tokens_details": null
},
"request_id": "0000aaaa-11bb-cccc-dd22-eeeeee333333",
"seed": -430976584126747957,
"top_p": 1,
"temperature": 1,
"presence_penalty": 0,
"frequency_penalty": 0,
"metadata": {
"user": "admin",
"category": "docs-test"
"fizz": "buzz"
}
}
Удаление завершения сохраненного чата
Удаление сохраненного завершения по идентификатору завершения.
Майкрософт Ентра айди
from openai import AzureOpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
)
client = AzureOpenAI(
azure_endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/",
azure_ad_token_provider=token_provider,
api_version="2025-02-01-preview"
)
response = client.chat.completions.delete("chatcmpl-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u")
print(response.model_dump_json(indent=2))
from openai import AzureOpenAI
client = AzureOpenAI(
azure_endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com",
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
api_version="2025-02-01-preview"
)
response = client.chat.completions.delete("chatcmpl-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u")
print(response.model_dump_json(indent=2))
curl -X DELETE -D - https://YOUR-RESOURCE-NAME.openai.azure.com/openai/chat/completions/chatcmpl-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u?api-version=2025-02-01-preview \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_OPENAI_AUTH_TOKEN"
Ключ API
curl -X DELETE -D - https://YOUR-RESOURCE-NAME.openai.azure.com/openai/chat/completions/chatcmpl-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u?api-version=2025-02-01-preview \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY"
"id"• "chatcmp1-A1bC2dE3fH4iJ5kL6mN7oP8qR9sT0u",
"deleted": true,
"object": "chat. completion. deleted"
Устранение неполадок
Требуются ли специальные разрешения для использования хранимых завершений?
Доступ к хранимым завершениям контролируется с помощью двух действий DataActions.
Microsoft.CognitiveServices/accounts/OpenAI/stored-completions/read
Microsoft.CognitiveServices/accounts/OpenAI/stored-completions/action
По умолчанию Cognitive Services OpenAI Contributor
имеет доступ к обоим этим разрешениям:
Как удалить сохраненные данные?
Данные можно удалить, удалив связанный ресурс Azure OpenAI. Если вы хотите удалить только сохраненные данные завершения, следует обратиться в службу поддержки клиентов.
Сколько сохраненных данных завершения можно хранить?
Можно хранить не более 10 ГБ данных.
Можно ли не допустить, чтобы сохраненные завершения когда-либо включались в подписке?
Вам потребуется обратиться в службу поддержки клиентов, чтобы отключить сохранённые результаты на уровне подписки.
TypeError: Completions.create() получил непредвиденный аргумент store
Эта ошибка возникает при запуске более старой версии клиентской библиотеки OpenAI, которая предшествует выпуску функции хранимых завершений. Выполните pip install openai --upgrade
.