Como criar uma API com Edge Functions e ChatGPT
Saiba mais sobre o processo necessário para criar uma API com Edge Functions e ChatGPT, e tenha a resposta apresentada no Azion Preview Deployment.
Para fazer isso, você precisa ter:
- Registro na OpenAI.
- Sua OpenAI API key.
- Sua OpenAI organization ID.
Para começar a criar sua API, proceda da seguinte forma:
- Acesse o Real-Time Manager (RTM), no canto superior esquerdo, selecione Edge Functions na seção Edge Libraries.
- Clique em Add Function.
- Escolha um nome para sua função.
- Exclua a função predefinida que está dentro do editor de código.
- Adicione sua OpenAI API key e organization ID ao código, como um comentário:
/* ChatGPTKey=sk-xxxxxxx ChatGPTOrg=org-xxxxxx */
- Copie e cole a seguinte
const
:
const html = `<!DOCTYPE html> <body> <h1>Hello World</h1> <p>This markup was generated by Azion - Edge Functions.</p> </body>`
- Escreva o seguinte prompt dentro da função, logo abaixo das credenciais OpenAI que foram coladas na etapa 5:
// generate an object with 5 properties being 2 of them array of objects
- Selecione o prompt > clique nele com o botão direito do mouse > escolha ChatGPT: Generate. Aguarde alguns segundos até carregar.
O resultado esperado será semelhante a:
let myObject = { property_1: 'value_1', property_2: 10, property_3: true, property_4: [{object_1: 'value_1'}, {object_2: 'value_2'}], property_5: [{object_3: 'value_3'}, {object_4: 'value_4'}] };
- Adicione a função
handleRequest
, contendo umswitch case
, com um métodoGET
e um métodoPOST
:
async function handleRequest(request) { switch (request.method) { case 'POST': return new Response(JSON.stringify(myObject), { // Returning the object generated by ChatGPT headers: { "content-type": "application/json",// Altering the content-type to application/json } }) case 'GET': return new Response(html, { headers: { "content-type": "text/html:charset=UTF-8", } }) }}
- O método
POST
retorna um objetoJSON
, que foi gerado pela opçãoChatGPT: Generate
. - O método
GET
retorna aconst html
que foi declarada na etapa 6.
- Copie e cole a função
PreviewProvider
, responsável por simular solicitações:
function PreviewProvider(args) { var request = { body: {}, headers: {}, method: "GET", redirect: "", } return handleRequest(request) }
- Adicione a função
addEventListener
, que aciona todo o processamento da edge function:
addEventListener("fetch", event => { return event.respondWith(handleRequest(event.request)) })
- Clique com o botão direito em qualquer lugar dentro do editor de código e selecione Format document.
Neste ponto, sua edge function deve estar semelhante a:
/* ChatGPTKey=sk-xxxxxxx ChatGPTOrg=org-xxxxxx */ const html = `<!DOCTYPE html> <body> <h1>Hello World</h1> <p>This markup was generated by Azion - Edge Functions.</p> </body>`
let myObject = { property_1: 'value_1', property_2: 10, property_3: true, property_4: [{object_1: 'value_1'}, {object_2: 'value_2'}], property_5: [{object_3: 'value_3'}, {object_4: 'value_4'}] };
async function handleRequest(request) { switch (request.method) { case 'POST': return new Response(JSON.stringify(myObject), { // Returning the object generated by ChatGPT headers: { "content-type": "application/json",// Altering the content-type to application/json } }) case 'GET': return new Response(html, { headers: { "content-type": "text/html:charset=UTF-8", } }) } }
function PreviewProvider(args) { var request = { body: {}, headers: {}, method: "GET", //or POST redirect: "", } return handleRequest(request) }
addEventListener("fetch", event => { return event.respondWith(handleRequest(event.request)) })
Se quiser, você pode alternar o método dentro da função PreviewProvider
e ter uma visualização em tempo real das respostas no Azion Preview Deployment.
- Clique no botão Save.
Agora, a função está pronta para ser instanciada em uma edge application. Veja como instanciar e executar as funções em sua edge application.
- Acesse o Azion Console > Edge Functions.
- Clique em + Edge Function.
- Escolha um nome para sua função.
- Na tab Code, exclua a função predefinida que está dentro do editor de código.
- Adicione sua OpenAI API key e organization ID ao código, como um comentário:
/* ChatGPTKey=sk-xxxxxxx ChatGPTOrg=org-xxxxxx */
- Copie e cole a seguinte
const
:
const html = `<!DOCTYPE html> <body> <h1>Hello World</h1> <p>This markup was generated by Azion - Edge Functions.</p> </body>`
- Escreva o seguinte prompt dentro da função, logo abaixo das credenciais OpenAI que foram coladas na etapa 5:
// generate an object with 5 properties being 2 of them array of objects
- Selecione o prompt > clique nele com o botão direito do mouse > escolha ChatGPT: Generate. Aguarde alguns segundos até carregar.
O resultado esperado será semelhante a:
let myObject = { property_1: 'value_1', property_2: 10, property_3: true, property_4: [{object_1: 'value_1'}, {object_2: 'value_2'}], property_5: [{object_3: 'value_3'}, {object_4: 'value_4'}] };
- Adicione a função
handleRequest
, contendo umswitch case
, com um métodoGET
e um métodoPOST
:
async function handleRequest(request) { switch (request.method) { case 'POST': return new Response(JSON.stringify(myObject), { // Returning the object generated by ChatGPT headers: { "content-type": "application/json",// Altering the content-type to application/json } }) case 'GET': return new Response(html, { headers: { "content-type": "text/html:charset=UTF-8", } }) }}
- O método
POST
retorna um objetoJSON
, que foi gerado pela opçãoChatGPT: Generate
. - O método
GET
retorna aconst html
que foi declarada na etapa 6.
- Copie e cole a função
PreviewProvider
, responsável por simular solicitações:
function PreviewProvider(args) { var request = { body: {}, headers: {}, method: "GET", redirect: "", } return handleRequest(request) }
- Adicione a função
addEventListener
, que aciona todo o processamento da edge function:
addEventListener("fetch", event => { return event.respondWith(handleRequest(event.request)) })
- Clique com o botão direito em qualquer lugar dentro do editor de código e selecione Format document.
Neste ponto, sua edge function deve estar semelhante a:
/* ChatGPTKey=sk-xxxxxxx ChatGPTOrg=org-xxxxxx */ const html = `<!DOCTYPE html> <body> <h1>Hello World</h1> <p>This markup was generated by Azion - Edge Functions.</p> </body>`
let myObject = { property_1: 'value_1', property_2: 10, property_3: true, property_4: [{object_1: 'value_1'}, {object_2: 'value_2'}], property_5: [{object_3: 'value_3'}, {object_4: 'value_4'}] };
async function handleRequest(request) { switch (request.method) { case 'POST': return new Response(JSON.stringify(myObject), { // Returning the object generated by ChatGPT headers: { "content-type": "application/json",// Altering the content-type to application/json } }) case 'GET': return new Response(html, { headers: { "content-type": "text/html:charset=UTF-8", } }) } }
function PreviewProvider(args) { var request = { body: {}, headers: {}, method: "GET", //or POST redirect: "", } return handleRequest(request) }
addEventListener("fetch", event => { return event.respondWith(handleRequest(event.request)) })
Se quiser, você pode alternar o método dentro da função PreviewProvider
e ter uma visualização em tempo real das respostas no Azion Preview Deployment.
- Clique no botão Save.
Agora, a função está pronta para ser instanciada em uma edge application. Veja como instanciar e executar as funções em sua edge application.
Contribuidores