Condividi tramite


AI_GENERATE_EMBEDDINGS (Transact-SQL)

Si applica a: Anteprima di SQL Server 2025 (17.x)

AI_GENERATE_EMBEDDINGS è una funzione predefinita che crea incorporamenti (matrici vettoriali) usando una definizione del modello di intelligenza artificiale precreata archiviata nel database.

Sintassi

Convenzioni relative alla sintassi Transact-SQL

AI_GENERATE_EMBEDDINGS ( source USE MODEL model_identifier [ PARAMETERS optional_json_request_body_parameters ] )

Argomenti

origine

Espressione di qualsiasi tipo di carattere, ad esempio nvarchar, varchar, nchar o char.

model_identifier

Nome di un MODELLO ESTERNO definito come EMBEDDING tipo utilizzato per creare la matrice vettoriale di incorporamenti.

Per altre informazioni, vedere CREATE EXTERNAL MODEL.

optional_json_request_body_parameters

Elenco di parametri aggiuntivi in formato JSON valido. Questi parametri vengono aggiunti al corpo del messaggio della richiesta REST prima di essere inviati al EXTERNAL MODELpercorso dell'endpoint. Questi parametri sono depenanti in base a ciò che l'endpoint EXTERNAL MODELsupporta e accetta.

Tipi restituiti

AI_GENERATE_EMBEDDINGS restituisce una tabella a colonna singola le cui righe sono le matrici di vettori di incorporamento generate restituite come JSON.

Formato restituito

Il formato del codice JSON restituito è il seguente:

[
    0.0023929428,
    0.00034713413,
    -0.0023142276,
    -0.025654867,
    -0.011492423,
    0.0010358924,
    -0.014836246,
    0.0035484824,
    0.000045630233,
    -0.027581815,
    0.023816079,
    0.005012586,
    -0.027732948,
    -0.010088143,
    ...
    -0.014571763
]

Osservazioni:

Prerequisiti

Per usare AI_GENERATE_EMBEDDINGSè necessario soddisfare due prerequisiti:

  • sp_invoke_external_endpoint deve essere abilitato nel database utilizzando sp_configure.

  • un MODELLO ESTERNO del EMBEDDINGS tipo, accessibile tramite le concessioni, i ruoli e/o le autorizzazioni corrette.

Parametri facoltativi

Il parametro optional_json_request_body_parameters in AI_GENERATE_EMBEDDINGS viene usato quando è necessario aggiungere un parametro endpoint al corpo del messaggio di richiesta di incorporamento. L'aggiunta di un parametro facoltativo sostituisce il valore in fase di esecuzione se tale parametro è definito nella definizione del modello.

Ad esempio, se EXTERNAL MODEL contiene il parametro per dimensions impostato su 1536, passando tale parametro in optional_json_request_body_parameters fase di esecuzione con un nuovo valore come illustrato di seguito: json_object('dimensions':755), il dimensions parametro nel modello viene sottoposto a override.

Il valore passato in optional_json_request_body_parameters deve essere JSON valido.

Creare endpoint di incorporamento

Per altre informazioni sulla creazione di endpoint di incorporamento, vedere il processo per Azure OpenAI, OpenAI o Ollama.

Eventi estesi (XEvent)

AI_GENERATE_EMBEDDINGS ha un evento esteso (ai_generate_embeddings_summary) che può essere abilitato per la risoluzione dei problemi. Contiene informazioni sulla richiesta REST e sulla risposta, ad esempio il codice di stato, gli eventuali errori rilevati, il nome del modello usato e i conteggi dei token usati dall'endpoint di incorporamento. L'evento external_rest_endpoint_summary esteso contiene informazioni aggiuntive che possono essere per la risoluzione dei problemi e il debug delle richieste REST.

Esempi

Un. Creare incorporamenti con un'istruzione SELECT

Nell'esempio seguente viene illustrato come usare la AI_GENERATE_EMBEDDINGS funzione con un'istruzione select che restituisce i risultati della matrice vettoriale.

SELECT id,
       AI_GENERATE_EMBEDDINGS(large_text USE MODEL MyAzureOpenAIModel)
FROM myTable;

B. Creare incorporamenti con un'istruzione SELECT usando AI_GENERATE_CHUNKS

Nell'esempio seguente viene illustrato come usare la funzione con la AI_GENERATE_EMBEDDINGSAI_GENERATE_CHUNKS funzione per passare il testo suddiviso in blocchi specificati con un'istruzione select che restituisce i risultati della matrice vettoriale.

SELECT
    id,
    title,
    large_text,
    AI_GENERATE_EMBEDDINGS(c.chunk_text USE MODEL MyAzureOpenAiModel)
FROM
    myTable
CROSS APPLY
    AI_GENERATE_CHUNKS(source = large_text, chunk_type = N'FIXED' , chunk_size = 10) c;

C. Creare incorporamenti con un aggiornamento della tabella

Nell'esempio seguente viene illustrato come usare la AI_GENERATE_EMBEDDINGS funzione con un'istruzione di aggiornamento della tabella per restituire i risultati della matrice vettoriale in una colonna di tipo di dati vettoriale.

UPDATE t
    SET myEmbeddings = AI_GENERATE_EMBEDDINGS(t.text USE MODEL MyAzureOpenAiModel)
FROM myTable AS t;

D. Creare incorporamenti con un'istruzione SELECT e PARAMETERS

Nell'esempio seguente viene illustrato come usare la AI_GENERATE_EMBEDDINGS funzione con un'istruzione select e passare parametri facoltativi all'endpoint, che restituisce i risultati della matrice vettoriale.

SELECT id,
       AI_GENERATE_EMBEDDINGS(large_text USE MODEL MyAzureOpenAIModel PARAMETERS '{"dimensions" : 768 }')
FROM myTable;

E. Esempio completo con suddivisione in blocchi, AI_GENERATE_EMBEDDINGS e creazione di modelli

Questo esempio è un flusso completo dalla creazione di CREATE EXTERNAL MODEL, usando e usando AI_GENERATE_EMBEDDINGSAI_GENERATE_CHUNKS per inserire i risultati in una tabella con un tipo di dati vector. Ricordarsi di sostituire <password> con una password valida.

-- Turn external REST endpoint invocation ON in the database
EXECUTE sp_configure 'external rest endpoint enabled', 1;
RECONFIGURE WITH OVERRIDE;
GO

-- Create a master key for the database
IF NOT EXISTS (SELECT *
               FROM sys.symmetric_keys
               WHERE [name] = '##MS_DatabaseMasterKey##')
    BEGIN
        CREATE MASTER KEY ENCRYPTION BY PASSWORD = N'<password>';
    END
GO

-- Create access credentials to Azure OpenAI using a key:
CREATE DATABASE SCOPED CREDENTIAL [https://my-azure-openai-endpoint.openai.azure.com/]
    WITH IDENTITY = 'HTTPEndpointHeaders', secret = '{"api-key":"YOUR_AZURE_OPENAI_KEY"}';
GO

-- Create an external model to call the Azure OpenAI embeddings REST endpoint
CREATE EXTERNAL MODEL MyAzureOpenAiModel
WITH (
      LOCATION = 'https://my-azure-openai-endpoint.openai.azure.com/openai/deployments/text-embedding-ada-002/embeddings?api-version=2023-05-15',
      API_FORMAT = 'Azure OpenAI',
      MODEL_TYPE = EMBEDDINGS,
      MODEL = 'text-embedding-ada-002',
      CREDENTIAL = [https://my-azure-openai-endpoint.openai.azure.com/]
);

-- Create a table with text to chunk and insert data
CREATE TABLE textchunk
(
    text_id INT IDENTITY (1, 1) PRIMARY KEY,
    text_to_chunk NVARCHAR (MAX)
);
GO

INSERT INTO textchunk (text_to_chunk)
VALUES
('All day long we seemed to dawdle through a country which was full of beauty of every kind. Sometimes we saw little towns or castles on the top of steep hills such as we see in old missals; sometimes we ran by rivers and streams which seemed from the wide stony margin on each side of them to be subject to great floods.'),
('My Friend, Welcome to the Carpathians. I am anxiously expecting you. Sleep well to-night. At three to-morrow the diligence will start for Bukovina; a place on it is kept for you. At the Borgo Pass my carriage will await you and will bring you to me. I trust that your journey from London has been a happy one, and that you will enjoy your stay in my beautiful land. Your friend, DRACULA')
GO

-- Create a new table to hold the chunked text and vector embeddings
CREATE TABLE text_embeddings
(
    embeddings_id INT IDENTITY (1, 1) PRIMARY KEY,
    chunked_text NVARCHAR (MAX),
    vector_embeddings VECTOR (1536)
);

-- Insert the chunked text and vector embeddings into the text_embeddings table using AI_GENERATE_CHUNKS and AI_GENERATE_EMBEDDINGS
INSERT INTO text_embeddings (chunked_text, vector_embeddings)
SELECT c.chunk, AI_GENERATE_EMBEDDINGS(c.chunk USE MODEL MyAzureOpenAiModel)
FROM textchunk t
CROSS APPLY
    AI_GENERATE_CHUNKS(source = t.text_to_chunk, chunk_type = N'FIXED', chunk_size = 100) c;

-- View the results
SELECT * FROM text_embeddings;