|
| 1 | +/*#info |
| 2 | +
|
| 3 | + # Author |
| 4 | + Rodrigo Ribeiro Gomes (https://iatalk.ing) |
| 5 | +
|
| 6 | + # Detalhes |
| 7 | + Exemplo de como gerar embeddings usando sp_invoke_external_rest_endpoint e OpenAI |
| 8 | + Funciona apenas no sql 2025+ |
| 9 | +*/ |
| 10 | + |
| 11 | +-- create database ia! |
| 12 | +use ia |
| 13 | +GO |
| 14 | + |
| 15 | +-- create scoped credential! |
| 16 | + -- o nome da credential precisa ter pelo menos o domonio bas da url usada! |
| 17 | + -- exemplo: esse aqui serve para api.openai.com/* |
| 18 | + if not exists(select * from sys.database_scoped_credentials where name = 'https://api.openai.com') |
| 19 | + create database scoped credential |
| 20 | + [https://api.openai.com] |
| 21 | + with identity = 'HTTPEndpointHeaders' |
| 22 | + ,SECRET = '{"Authorization":"Bearer SUA_API_KEY"}' |
| 23 | + |
| 24 | + |
| 25 | + -- Agora é invocar! |
| 26 | + declare @response nvarchar(max) |
| 27 | + declare @retval int |
| 28 | + declare @options nvarchar(max) = ( |
| 29 | + select |
| 30 | + input = (select JSON_ARRAYAGG('oi') ) |
| 31 | + ,dimensions = 768 |
| 32 | + ,model = 'text-embedding-3-small' |
| 33 | + for json path,without_array_wrapper |
| 34 | + ) |
| 35 | + |
| 36 | + |
| 37 | + |
| 38 | + exec @retval = sp_invoke_external_rest_endpoint e OpenAI |
| 39 | + @url = 'https://api.openai.com/v1/embeddings', |
| 40 | + @method = 'POST', |
| 41 | + @credential = [https://api.openai.com], |
| 42 | + @payload = @options, |
| 43 | + @response = @response output |
| 44 | + |
| 45 | + select |
| 46 | + r.[key] |
| 47 | + ,embedding = CONVERT(vector(768),JSON_QUERY(r.value,'$.embedding')) |
| 48 | + from |
| 49 | + openjson(@response,'$.result.data') r |
| 50 | + |
| 51 | + |
| 52 | + |
0 commit comments