Observação
O acesso a essa página exige autorização. Você pode tentar entrar ou alterar diretórios.
O acesso a essa página exige autorização. Você pode tentar alterar os diretórios.
Use a pesquisa de vetor no Azure DocumentDB com a biblioteca de clientes Python para armazenar e consultar dados de vetor com eficiência.
Este início rápido usa um conjunto de dados de hotel de exemplo em um arquivo JSON com vetores pré-calculados do text-embedding-3-small modelo. O conjunto de dados inclui nomes de hotéis, locais, descrições e inserções de vetor.
Encontre o código de exemplo no GitHub.
Prerequisites
- Uma assinatura do Azure. Caso não tenha uma assinatura do Azure, crie uma conta gratuita.
Um cluster existente do Azure DocumentDB. Se você não tiver um cluster, crie um novo cluster.
-
O domínio personalizado está configurado.
text-embedding-3-smallmodelo é implantado.
Código do Visual Studio. Verifique se você tem a extensão Azure DocumentDB.
Use o ambiente bash em Azure Cloud Shell. Para obter mais informações, confira Introdução ao Azure Cloud Shell.
Se você preferir executar comandos de referência da CLI localmente, instale a CLI do Azure. Se você estiver executando no Windows ou no macOS, considere executar a CLI do Azure em um contêiner do Docker. Para obter mais informações, confira Como executar a CLI do Azure em um contêiner do Docker.
Se você estiver usando uma instalação local, entre na CLI do Azure usando o comando az login . Para concluir o processo de autenticação, siga as etapas exibidas em seu terminal. Para obter outras opções de entrada, consulte Autenticar no Azure usando a CLI do Azure.
Quando solicitado, instale a extensão da CLI do Azure no primeiro uso. Para obter mais informações sobre extensões, confira Usar e gerenciar extensões com a CLI do Azure.
Execute o comando az version para localizar a versão e as bibliotecas dependentes que estão instaladas. Para atualizar para a versão mais recente, execute az upgrade.
Tip
Para personalizar parâmetros de modelo do Azure OpenAI antes da implantação, consulte a seção Personalizar a implantação do Azure OpenAI mais adiante neste artigo.
- Python 3.9 ou posterior.
Criar um arquivo de dados com vetores
Crie um novo diretório de dados para o arquivo de dados de hotéis:
mkdir dataCopie o
Hotels_Vector.jsonarquivo de dados brutos com vetores para o diretóriodata.
Criar um projeto de Python
Crie um novo diretório para seu projeto e abra-o no Visual Studio Code:
mkdir vector-search-quickstart code vector-search-quickstartNo terminal, crie e ative um ambiente virtual:
Para Windows:
python -m venv venv venv\\Scripts\\activatePara macOS/Linux:
python -m venv venv source venv/bin/activateInstale os pacotes necessários:
pip install pymongo azure-identity openai python-dotenv-
pymongo: o driver do MongoDB para Python. -
azure-identity: a biblioteca Azure Identity para autenticação sem senha. -
openai: a biblioteca de clientes OpenAI para criar vetores. -
python-dotenv: o gerenciamento de variáveis de ambiente em arquivos .env.
-
Crie um
.envarquivo para variáveis de ambiente emvector-search-quickstart:# Identity for local developer authentication with Azure CLI AZURE_TOKEN_CREDENTIALS=AzureCliCredential # Azure OpenAI configuration AZURE_OPENAI_EMBEDDING_ENDPOINT= AZURE_OPENAI_EMBEDDING_MODEL=text-embedding-3-small AZURE_OPENAI_EMBEDDING_API_VERSION=2023-05-15 # Azure DocumentDB configuration MONGO_CLUSTER_NAME= # Data Configuration (defaults should work) DATA_FILE_WITH_VECTORS=../data/Hotels_Vector.json EMBEDDED_FIELD=DescriptionVector EMBEDDING_DIMENSIONS=1536 EMBEDDING_SIZE_BATCH=16 LOAD_SIZE_BATCH=50Para a autenticação sem senha usada neste artigo, substitua os valores de espaço reservado no arquivo
.envcom suas próprias informações:-
AZURE_OPENAI_EMBEDDING_ENDPOINT: sua URL do ponto de extremidade de recurso Azure OpenAI. -
MONGO_CLUSTER_NAME: o nome do recurso Azure DocumentDB.
Recomendamos que você use a autenticação sem senha, mas esse tipo de autenticação requer mais etapas de instalação. Para obter mais informações sobre como configurar a identidade gerenciada e toda a gama de opções de autenticação, consulte Autenticar aplicativos Python nos serviços do Azure usando o SDK do Azure para Python.
-
Criar arquivos de código para pesquisa de vetor
Continue o projeto criando arquivos de código para pesquisa de vetor. Quando você terminar, a estrutura do projeto será semelhante a este exemplo:
├── data/
│ ├── Hotels.json # Source hotel data (without vectors)
│ └── Hotels_Vector.json # Hotel data with vector embeddings
└── vector-search-quickstart/
├── src/
│ ├── diskann.py # DiskANN vector search implementation
│ ├── hnsw.py # HNSW vector search implementation
│ ├── ivf.py # IVF vector search implementation
│ └── utils.py # Shared utility functions
├── requirements.txt # Python dependencies
├── .env # Environment variables template
Crie um diretório src para seus arquivos de Python. Adicione dois arquivos diskann.py e utils.py, para a implementação do índice DiskANN.
mkdir src
touch src/diskann.py
touch src/utils.py
Tip
Ao contrário de alguns bancos de dados, Azure DocumentDB permite que você crie e solte índices de vetor a qualquer momento depois de criar um contêiner. Você não precisa definir a política de indexação de vetor no momento em que você cria um contêiner.
Criar o código para pesquisa de vetor
Cole o código a seguir no diskann.py arquivo.
import os
from typing import List, Dict, Any
from utils import get_clients, get_clients_passwordless, read_file_return_json, insert_data, print_search_results, drop_vector_indexes
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
def create_diskann_vector_index(collection, vector_field: str, dimensions: int) -> None:
print(f"Creating DiskANN vector index on field '{vector_field}'...")
# Drop any existing vector indexes on this field first
drop_vector_indexes(collection, vector_field)
# Use the native MongoDB command for DocumentDB vector indexes
index_command = {
"createIndexes": collection.name,
"indexes": [
{
"name": f"diskann_index_{vector_field}",
"key": {
vector_field: "cosmosSearch" # DocumentDB vector search index type
},
"cosmosSearchOptions": {
# DiskANN algorithm configuration
"kind": "vector-diskann",
# Vector dimensions must match the embedding model
"dimensions": dimensions,
# Vector similarity metric - cosine is good for text embeddings
"similarity": "COS",
# Maximum degree: number of edges per node in the graph
# Higher values improve accuracy but increase memory usage
"maxDegree": 20,
# Build parameter: candidates evaluated during index construction
# Higher values improve index quality but increase build time
"lBuild": 10
}
}
]
}
try:
# Execute the createIndexes command directly
result = collection.database.command(index_command)
print("DiskANN vector index created successfully")
except Exception as e:
print(f"Error creating DiskANN vector index: {e}")
# Check if it's a tier limitation and suggest alternatives
if "not enabled for this cluster tier" in str(e):
print("\nDiskANN indexes require a higher cluster tier.")
print("Try one of these alternatives:")
print(" • Upgrade your DocumentDB cluster to a higher tier")
print(" • Use HNSW instead: python src/hnsw.py")
print(" • Use IVF instead: python src/ivf.py")
raise
def perform_diskann_vector_search(collection,
azure_openai_client,
query_text: str,
vector_field: str,
model_name: str,
top_k: int = 5) -> List[Dict[str, Any]]:
print(f"Performing DiskANN vector search for: '{query_text}'")
try:
# Generate embedding for the query text
embedding_response = azure_openai_client.embeddings.create(
input=[query_text],
model=model_name
)
query_embedding = embedding_response.data[0].embedding
# Construct the aggregation pipeline for vector search
# DocumentDB uses $search with cosmosSearch
pipeline = [
{
"$search": {
# Use cosmosSearch for vector operations in DocumentDB
"cosmosSearch": {
# The query vector to search for
"vector": query_embedding,
# Field containing the document vectors to compare against
"path": vector_field,
# Number of final results to return
"k": top_k
}
}
},
{
# Add similarity score to the results
"$project": {
"document": "$$ROOT",
# Add search score from metadata
"score": {"$meta": "searchScore"}
}
}
]
# Execute the aggregation pipeline
results = list(collection.aggregate(pipeline))
return results
except Exception as e:
print(f"Error performing DiskANN vector search: {e}")
raise
def main():
# Load configuration from environment variables
config = {
'cluster_name': os.getenv('MONGO_CLUSTER_NAME'),
'database_name': 'Hotels',
'collection_name': 'hotels_diskann',
'data_file': os.getenv('DATA_FILE_WITH_VECTORS', '../data/Hotels_Vector.json'),
'vector_field': os.getenv('EMBEDDED_FIELD', 'DescriptionVector'),
'model_name': os.getenv('AZURE_OPENAI_EMBEDDING_MODEL', 'text-embedding-3-small'),
'dimensions': int(os.getenv('EMBEDDING_DIMENSIONS', '1536')),
'batch_size': int(os.getenv('LOAD_SIZE_BATCH', '100'))
}
try:
# Initialize clients
print("\nInitializing MongoDB and Azure OpenAI clients...")
mongo_client, azure_openai_client = get_clients_passwordless()
# Get database and collection
database = mongo_client[config['database_name']]
collection = database[config['collection_name']]
# Load data with embeddings
print(f"\nLoading data from {config['data_file']}...")
data = read_file_return_json(config['data_file'])
print(f"Loaded {len(data)} documents")
# Verify embeddings are present
documents_with_embeddings = [doc for doc in data if config['vector_field'] in doc]
if not documents_with_embeddings:
raise ValueError(f"No documents found with embeddings in field '{config['vector_field']}'. "
"Please run create_embeddings.py first.")
# Insert data into collection
print(f"\nInserting data into collection '{config['collection_name']}'...")
# Insert the hotel data
stats = insert_data(
collection,
documents_with_embeddings,
batch_size=config['batch_size']
)
if stats['inserted'] == 0 and not stats.get('skipped'):
raise ValueError("No documents were inserted successfully")
# Create DiskANN vector index (skip if data was already present)
if not stats.get('skipped'):
create_diskann_vector_index(
collection,
config['vector_field'],
config['dimensions']
)
# Wait briefly for index to be ready
import time
print("Waiting for index to be ready...")
time.sleep(2)
# Perform sample vector search
query = "quintessential lodging near running trails, eateries, retail"
results = perform_diskann_vector_search(
collection,
azure_openai_client,
query,
config['vector_field'],
config['model_name'],
top_k=5
)
# Display results
print_search_results(results, max_results=5, show_score=True)
except Exception as e:
print(f"\nError during DiskANN demonstration: {e}")
raise
finally:
# Close the MongoDB client
if 'mongo_client' in locals():
mongo_client.close()
if __name__ == "__main__":
main()
Este módulo principal:
Inclui funções de utilitário.
Cria um objeto de configuração para variáveis de ambiente.
Cria clientes para Azure OpenAI e Azure DocumentDB.
Conecta-se ao MongoDB, cria um banco de dados e uma coleção, insere dados e cria índices padrão.
Cria um índice de vetor que usa IVF, HNSW ou DiskANN.
Cria um embedding para um texto de consulta de exemplo usando o cliente OpenAI. Você pode alterar a consulta na parte superior do arquivo.
Executa uma pesquisa vetorial que usa o embedding e imprime os resultados.
Criar funções utilitárias
Cole o seguinte código em utils.py:
import json
import os
import time
import warnings
from typing import Dict, List, Any, Optional, Tuple
# Suppress the PyMongo CosmosDB cluster detection warning
# Must be set before importing pymongo
warnings.filterwarnings(
"ignore",
message="You appear to be connected to a CosmosDB cluster.*",
)
from pymongo import MongoClient, InsertOne
from pymongo.collection import Collection
from pymongo.errors import BulkWriteError
from azure.identity import DefaultAzureCredential
from pymongo.auth_oidc import OIDCCallback, OIDCCallbackContext, OIDCCallbackResult
from openai import AzureOpenAI
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
class AzureIdentityTokenCallback(OIDCCallback):
def __init__(self, credential):
self.credential = credential
def fetch(self, context: OIDCCallbackContext) -> OIDCCallbackResult:
token = self.credential.get_token(
"https://ossrdbms-aad.database.windows.net/.default").token
return OIDCCallbackResult(access_token=token)
def get_clients() -> Tuple[MongoClient, AzureOpenAI]:
# Get MongoDB connection string - required for DocumentDB access
mongo_connection_string = os.getenv("MONGO_CONNECTION_STRING")
if not mongo_connection_string:
raise ValueError("MONGO_CONNECTION_STRING environment variable is required")
# Create MongoDB client with optimized settings for DocumentDB
mongo_client = MongoClient(
mongo_connection_string,
retryWrites=False,
maxPoolSize=50, # Allow up to 50 connections for better performance
minPoolSize=5, # Keep minimum 5 connections open
maxIdleTimeMS=30000, # Close idle connections after 30 seconds
serverSelectionTimeoutMS=5000, # 5 second timeout for server selection
socketTimeoutMS=20000 # 20 second socket timeout
)
# Get Azure OpenAI configuration
azure_openai_endpoint = os.getenv("AZURE_OPENAI_EMBEDDING_ENDPOINT")
azure_openai_key = os.getenv("AZURE_OPENAI_EMBEDDING_KEY")
if not azure_openai_endpoint or not azure_openai_key:
raise ValueError("Azure OpenAI endpoint and key are required")
# Create Azure OpenAI client for generating embeddings
azure_openai_client = AzureOpenAI(
azure_endpoint=azure_openai_endpoint,
api_key=azure_openai_key,
api_version=os.getenv("AZURE_OPENAI_EMBEDDING_API_VERSION", "2023-05-15")
)
return mongo_client, azure_openai_client
def get_clients_passwordless() -> Tuple[MongoClient, AzureOpenAI]:
# Get MongoDB cluster name for passwordless authentication
cluster_name = os.getenv("MONGO_CLUSTER_NAME")
if not cluster_name:
raise ValueError("MONGO_CLUSTER_NAME environment variable is required")
# Create credential object for Azure authentication
credential = DefaultAzureCredential()
authProperties = {"OIDC_CALLBACK": AzureIdentityTokenCallback(credential)}
# Create MongoDB client with Azure AD token callback
mongo_client = MongoClient(
f"mongodb+srv://{cluster_name}.global.mongocluster.cosmos.azure.com/",
connectTimeoutMS=120000,
tls=True,
retryWrites=False,
authMechanism="MONGODB-OIDC",
authMechanismProperties=authProperties
)
# Get Azure OpenAI endpoint
azure_openai_endpoint = os.getenv("AZURE_OPENAI_EMBEDDING_ENDPOINT")
if not azure_openai_endpoint:
raise ValueError("AZURE_OPENAI_EMBEDDING_ENDPOINT environment variable is required")
# Create Azure OpenAI client with credential-based authentication
azure_openai_client = AzureOpenAI(
azure_endpoint=azure_openai_endpoint,
azure_ad_token_provider=lambda: credential.get_token("https://cognitiveservices.azure.com/.default").token,
api_version=os.getenv("AZURE_OPENAI_EMBEDDING_API_VERSION", "2023-05-15")
)
return mongo_client, azure_openai_client
def azure_identity_token_callback(credential: DefaultAzureCredential) -> str:
# DocumentDB requires this specific scope
token_scope = "https://cosmos.azure.com/.default"
# Get token from Azure AD
token = credential.get_token(token_scope)
return token.token
def read_file_return_json(file_path: str) -> List[Dict[str, Any]]:
try:
with open(file_path, 'r', encoding='utf-8') as file:
return json.load(file)
except FileNotFoundError:
print(f"Error: File '{file_path}' not found")
raise
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON in file '{file_path}': {e}")
raise
def write_file_json(data: List[Dict[str, Any]], file_path: str) -> None:
try:
with open(file_path, 'w', encoding='utf-8') as file:
json.dump(data, file, indent=2, ensure_ascii=False)
print(f"Data successfully written to '{file_path}'")
except IOError as e:
print(f"Error writing to file '{file_path}': {e}")
raise
def insert_data(collection: Collection, data: List[Dict[str, Any]],
batch_size: int = 100, index_fields: Optional[List[str]] = None) -> Dict[str, int]:
total_documents = len(data)
# Check if data already exists in the collection
existing_count = collection.count_documents({})
if existing_count >= total_documents:
print(f"Collection already has {existing_count} documents, skipping insert and index creation")
return {'total': total_documents, 'inserted': 0, 'failed': 0, 'skipped': True}
# Clear existing data if counts don't match to ensure clean state
if existing_count > 0:
print(f"Collection has {existing_count} documents but expected {total_documents}, clearing and re-inserting...")
collection.delete_many({})
inserted_count = 0
failed_count = 0
print(f"Starting batch insertion of {total_documents} documents...")
# Create indexes if specified
if index_fields:
for field in index_fields:
try:
collection.create_index(field)
print(f"Created index on field: {field}")
except Exception as e:
print(f"Warning: Could not create index on {field}: {e}")
# Process data in batches to manage memory and error recovery
for i in range(0, total_documents, batch_size):
batch = data[i:i + batch_size]
batch_num = (i // batch_size) + 1
total_batches = (total_documents + batch_size - 1) // batch_size
try:
# Prepare bulk insert operations
operations = [InsertOne(document) for document in batch]
# Execute bulk insert
result = collection.bulk_write(operations, ordered=False)
inserted_count += result.inserted_count
print(f"Batch {batch_num} completed: {result.inserted_count} documents inserted")
except BulkWriteError as e:
# Handle partial failures in bulk operations
inserted_count += e.details.get('nInserted', 0)
failed_count += len(batch) - e.details.get('nInserted', 0)
print(f"Batch {batch_num} had errors: {e.details.get('nInserted', 0)} inserted, "
f"{failed_count} failed")
# Print specific error details for debugging
for error in e.details.get('writeErrors', []):
print(f" Error: {error.get('errmsg', 'Unknown error')}")
except Exception as e:
# Handle unexpected errors
failed_count += len(batch)
print(f"Batch {batch_num} failed completely: {e}")
# Small delay between batches to avoid overwhelming the database
time.sleep(0.1)
# Return summary statistics
stats = {
'total': total_documents,
'inserted': inserted_count,
'failed': failed_count
}
return stats
def drop_vector_indexes(collection, vector_field: str) -> None:
try:
# Get all indexes for the collection
indexes = list(collection.list_indexes())
# Find vector indexes on the specified field
vector_indexes = []
for index in indexes:
if 'key' in index and vector_field in index['key']:
if index['key'][vector_field] == 'cosmosSearch':
vector_indexes.append(index['name'])
# Drop each vector index found
for index_name in vector_indexes:
print(f"Dropping existing vector index: {index_name}")
collection.drop_index(index_name)
if vector_indexes:
print(f"Dropped {len(vector_indexes)} existing vector index(es)")
else:
print("No existing vector indexes found to drop")
except Exception as e:
print(f"Warning: Could not drop existing vector indexes: {e}")
# Continue anyway - the error might be that no indexes exist
def print_search_resultsx(results: List[Dict[str, Any]],
max_results: int = 5,
show_score: bool = True) -> None:
if not results:
print("No search results found.")
return
print(f"\nSearch Results (showing top {min(len(results), max_results)}):")
print("=" * 80)
for i, result in enumerate(results[:max_results], 1):
# Display hotel name and ID
print(f"HotelName: {result['HotelName']}, Score: {result['score']:.4f}")
def print_search_results(results: List[Dict[str, Any]],
max_results: int = 5,
show_score: bool = True) -> None:
if not results:
print("No search results found.")
return
print(f"\nSearch Results (showing top {min(len(results), max_results)}):")
print("=" * 80)
for i, result in enumerate(results[:max_results], 1):
# Check if results are nested under 'document' (when using $$ROOT)
if 'document' in result:
doc = result['document']
else:
doc = result
# Display hotel name and ID
print(f"HotelName: {doc['HotelName']}, Score: {result['score']:.4f}")
if len(results) > max_results:
print(f"\n... and {len(results) - max_results} more results")
Este módulo do utilitário fornece estes recursos:
get_clients: cria e retorna clientes para Azure OpenAI e Azure DocumentDB.get_clients_passwordless: cria e retorna clientes para Azure OpenAI e Azure DocumentDB usando a autenticação sem senha.AzureIdentityTokenCallback: implementa o retorno de chamada do MongoDB OpenID Connect (OIDC) usado paraget_clients_passwordlesssolicitar um token Microsoft Entra para Azure DocumentDB.read_file_return_json: lê um arquivo JSON e retorna seu conteúdo como uma matriz de objetos.write_file_json: grava um array de objetos em um arquivo JSON.insert_data: insere dados em lotes em uma coleção do MongoDB e cria índices padrão em campos especificados.drop_vector_indexes: descarta índices de vetor existentes no campo de vetor de destino.print_search_results: imprime os resultados da pesquisa de vetor, incluindo pontuação e nome do hotel.
Autenticar com a CLI do Azure
Antes de executar o aplicativo, entre no CLI do Azure para que o aplicativo possa acessar Azure recursos com segurança.
az login
O código usa sua autenticação de desenvolvedor local para acessar o Azure DocumentDB e o Azure OpenAI. Quando você defineAZURE_TOKEN_CREDENTIALS=AzureCliCredential, essa configuração informa à função para usar as credenciais de CLI do Azure para autenticação deterministicamente. A autenticação depende de azure-identity de para localizar suas credenciais do Azure no ambiente. Saiba mais sobre como autenticar aplicativos Python em serviços Azure usando a biblioteca Azure Identity.
Executar o aplicativo
Para executar os scripts do Python:
Você verá os cinco principais hotéis que correspondem à consulta de pesquisa de vetor e suas pontuações de similaridade.
Exibir e gerenciar dados no Visual Studio Code
Selecione a extensão Azure DocumentDB em Visual Studio Code para se conectar à sua conta do DocumentDB Azure.
Exiba os dados e índices no banco de dados Hotels.
Personalizar a implantação do Azure OpenAI (opcional)
A infraestrutura implanta Azure OpenAI com as configurações de modelo e região padrão definidas em infra/main.bicepparam. Antes de executar azd up, você pode personalizar qualquer um desses parâmetros:
| Parameter | Default | Description |
|---|---|---|
AZURE_OPENAI_LOCATION |
O mesmo que AZURE_LOCATION |
Região para implantação do recurso OpenAI |
AZURE_OPENAI_EMBEDDING_MODEL |
text-embedding-3-small |
Nome do modelo de embedding |
AZURE_OPENAI_EMBEDDING_MODEL_VERSION |
1 |
Versão do modelo de embedding |
AZURE_OPENAI_EMBEDDING_MODEL_TYPE |
Standard |
Tipo de implantação (Standard ou GlobalStandard) |
Para substituir uma configuração padrão, use azd env set antes de executar azd up:
# Deploy OpenAI to a different region than your other resources
azd env set AZURE_OPENAI_LOCATION swedencentral
# Switch deployment type from Standard (default) to GlobalStandard
azd env set AZURE_OPENAI_EMBEDDING_MODEL_TYPE GlobalStandard
# Change the embedding model
azd env set AZURE_OPENAI_EMBEDDING_MODEL text-embedding-3-small
azd env set AZURE_OPENAI_EMBEDDING_MODEL_VERSION 1
Note
Nem todos os modelos estão disponíveis em todas as regiões ou com todos os tipos de implantação. Verifique disponibilidade do modelo Azure OpenAI por região para obter combinações com suporte.
Solucionar problemas de falhas de provisionamento do Azure OpenAI
Se azd up falhar ao criar o recurso Azure OpenAI ou implantações de modelo, provavelmente será devido a um dos seguintes problemas:
Disponibilidade da região: o modelo não está disponível na região escolhida. Tente
azd env set AZURE_OPENAI_LOCATION <different-region>(por exemplo,eastus2ouswedencentral).Incompatibilidade de tipo de implantação: o modelo não dá suporte ao tipo de implantação selecionado em sua região. Alternar entre
StandardeGlobalStandardusandoazd env set AZURE_OPENAI_EMBEDDING_MODEL_TYPE GlobalStandard.Limites de cota: sua assinatura atingiu sua cota para a combinação de modelo, região ou tipo de implantação selecionada. Verifique sua cota no portal do Azure, em Azure OpenAI>. Você pode solicitar um aumento de cota ou tentar uma região diferente em que tenha capacidade disponível.
Modelo desativado ou indisponível: Azure OpenAI desativa periodicamente versões de modelo mais antigas. Se a implantação falhar porque uma versão do modelo não está mais disponível, atualize para uma versão com suporte usando
azd env set AZURE_OPENAI_EMBEDDING_MODEL_VERSION <new-version>. Verifique descontinuações de modelos do Azure OpenAI para obter o status atual do ciclo de vida do modelo.
Depois de alterar os parâmetros, execute azd up novamente para tentar novamente a implantação.
Limpar os recursos
Quando você não precisar mais deles, exclua o grupo de recursos, Azure cluster do DocumentDB e Azure recurso OpenAI para evitar custos desnecessários.