Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

목차

Table of Contents

...

텍스트 AI

GPT 예제

Code Block
languagejs
themeEmacs
titlemodules/FetchEventSource.js
const { fetch, Headers, Request, Response } = require('fetch-undici');

if (!globalThis.fetch) {
    globalThis.fetch = fetch;
    globalThis.Headers = Headers;
    globalThis.Request = Request;
    globalThis.Response = Response;
}

module.exports = require('@waylaidwanderer/fetch-event-source');

...

Code Block
languagejs
themeEmacs
titleserver.js
const express = require('express');
const bodyParser = require('body-parser');
const { fetchEventSource } = require('./modules/FetchEventSource');

const GPT_API_URL = ''; // API URL ex) 'https://api.openai.com/v1/chat/completions'
const GPT_API_KEY = ''; // API KEY

const app = express();
const router = express.Router();

router.post('/request', (request, response) => {
    const bodyData = Object.assign({}, request.body, {
        model: 'gpt-3.5-turbo',
        stream: true
    });

    requestGPT(response, bodyData)
        .then(() => response.end())
        .catch((error) => response.status(error.status).json(error).end());
});

/**
 * GPT 서버로 요청합니다.
 * @param {Response} response
 * @param {Object} bodyData
 * @returns {Promise}
 */
function requestGPT(response, bodyData) {
    const abortController = new AbortController();
    return new Promise(async (resolve, reject) => {
        try {
            await fetchEventSource(GPT_API_URL, {
                method: 'post',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${GPT_API_KEY}` // OpenAI
                    // 'Api-Key': GPT_API_KEY` // Azure OpenAI
                },
                body: JSON.stringify(bodyData),
                signal: abortController.signal,
                onopen: async (openResponse) => {
                    if (openResponse.status === 200) {
                        response.on('close', () => {
                            abortController.abort();
                            resolve();
                        });
                        response.set({
                            'Cache-Control': 'no-cache',
                            'Connection': 'keep-alive',
                            'Content-Type': 'text/event-stream'
                        });
                        response.flushHeaders();
                        return;
                    }
                    let error;
                    try {
                        const json = await openResponse.json();
                        error = json;
                    } catch (e) {
                        error = e;
                    }
                    error.status = openResponse.status;
                    throw error;
                },
                onclose: () => resolve(),
                onerror: (error) => {
                    reject(error);
                    throw error;
                },
                onmessage: (message) => {
                    if (!message.data || message.event === 'ping') {
                        return;
                    }
                    response.write('data:' + message.data + '\n\n');
                },
            });
        } catch (e) {
            reject(e);
        }
    });
}

app.use(bodyParser.json());
app.use('/', router);
app.listen(8080);

...


하이퍼클로바 X 예제

  • axios를 활용한 Node Express server 예제입니다.
Code Block
languagejs
themeEmacs
titleserver.js
const express = require('express');
const axios = require('axios');
const bodyParser = require('body-parser');

const DALLEHCX_API_URL = ''; // API URL - CLOVA Studio에서 url 확인 ex) 'https://apiclovastudio.apigw.openaintruss.com/testapp/v1/images/generations'chat-completions/HCX-003
const DALLEHCX_API_KEY = ''; // API KEY

const appHCX_GATEWAY_KEY = express();
'';// GATEWAY KEY

const app = express();
const router = express.Router();

router.post('/request', (request, response) => {
    const bodyData = request.body;

    requestDALLEServerrequestHCX(response, bodyData)
        .then(() => response.end())
        .catch((error)err => response.status(error.status).json(error).end());
});

/**
 * DALL·E 서버로 요청을 합니다.
 * @param {Response} response
 * @param {Object} bodyData 
 * @returns {Promise}
 */
function requestDALLEServer(response, bodyData) {{
        	console.error('[ERROR] requestHCX chat completion failed: ' + err);
            return response.status(err.status || 500).json(err).end();
     const source = axios.CancelToken.source( });
});

/**
 const* url하이퍼클로바 = DALLE_URL;
X 서버로 요청합니다.
 * @param {Response} returnresponse
new Promise((resolve, reject) => {
        try {* @param {Object} body
 * @returns {Promise}
 */
function requestHCX(response, bodyData) {
    const source = axios.CancelToken.source();
    const axios.post(url, bodyData, {
                headers: {
                    = HCX_API_URL;
	const headers= {
		'Content-Type': 'application/json',
 
                  'Authorization': `Bearer ${DALLE'Accept': 'text/event-stream',
		'X-NCP-CLOVASTUDIO-API-KEY': HCX_API_KEY}`,
        'X-NCP-APIGW-API-KEY': HCX_GATEWAY_KEY
	}
    return new Promise(async }(resolve, reject) => {
        try {
    responseType: '        axios.post(url, bodyData, {
                headers,
                responseType: 'stream',
                cancelToken: source.token
            }).then(responsehcxRes => {
                responsehcxRes.data.pipe(response);
            }).catch(errorreject);
=>
{            response.on('close', () =>   reject({
                    status: error.response ? error.response.status : 500,source.cancel('요청을 취소합니다.');
                resolve();
     message: error.message      });
        } catch }(e); {
            }reject(e);
        }
    response.on('close});
}

app.use(bodyParser.json());
app.use('/', (router) => {
                source.cancel('요청을 취소합니다.');
                resolve();
            });
        } catch (e) {
            reject(e);
        }
    });
}


app.use(bodyParser.json());
app.use('/', router);
app.listen(8080);
  • 하이퍼클로바 X
Code Block
languagejs
themeEmacs
titleserver.js
const express = require('express');
const axios = require('axios');
const bodyParser = require('body-parser');

const HCX_API_URL = ''; // API URL - CLOVA Studio에서 url 확인 ex)https://clovastudio.apigw.ntruss.com/testapp/v1/chat-completions/HCX-003
const HCX_API_KEY = ''; // API KEY
const HCX_GATEWAY_KEY = '';// GATEWAY KEY

const app = express();
const router = express.Router();

router.post('/request', (request, response) => {
    const bodyData = request.body;

    requestHCX(response, bodyData)
        .then(() => response.end())
        .catch(err ;
app.listen(8080);


Gemini 예제 

  • axios를 활용한 Node Express server 예제입니다.
Code Block
languagejs
themeEmacs
titleserver.js
const express = require('express');
const axios = require('axios');
const bodyParser = require('body-parser');

const GEMINI_URL = ''; // API URL ex) 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:streamGenerateContent'
const GEMINI_PARAM = ''; // API PARAMETER ex) 'alt=sse&'
const GEMINI_KEY = ''; // API KEY

const app = express();
const router = express.Router();

router.post('/request', (request, response) => {
    const bodyData = Object.assign({}, request.body);

    requestGeminiServer(response, bodyData)
        .then(() => response.end())
        .catch((err) => response.status(err.status || 500).json(err).end());
});

/**
 * Gemini 서버로 요청을 합니다.
 * @param {Response} response
 * @param {Object} bodyData
 * @returns {Promise}
 */
function requestGeminiServer(response, bodyData) {
    const url = GEMINI_URL;
    const key = GEMINI_KEY;
    const param = GEMINI_PARAM;
    const urlWithParam = `${url}?${param}key=${key}`;

    const source = axios.CancelToken.source();
    return new Promise((resolve, reject) => {
        	console.error('[ERROR] requestHCX chat completion failed: ' + err);try {
            axios.post(urlWithParam, bodyData, {
   return response.status(err.status || 500).json(err).end();         });
});

/**
 * 하이퍼클로바 X 서버로 요청합니다.
 * @param {Response} response
 * @param {Object} body
 * @returns {Promise}
 */
function requestHCX(response, bodyData) { headers: {
                    'Content-Type': 'application/json'
        const source = axios.CancelToken.source();     const},
url = HCX_API_URL; 	const headers= { 		'Content-Type': 'application/json',         'Accept'responseType: 'text/event-stream',
		'X-NCP-CLOVASTUDIO-API-KEY': HCX_API_KEY,
             'X-NCP-APIGW-API-KEY': HCX_GATEWAY_KEY 	} cancelToken: source.token
  return new Promise(async (resolve, reject) => {    }).then(geminiRes => {
  try {             axiosgeminiRes.post(url, bodyData, {
  data.pipe(response);
            }).catch(reject);

            headersresponse.on('close', () => {
              responseType: 'stream',  source.cancel('요청을 취소합니다.');
                cancelToken: source.tokenresolve();
            }).then(hcxRes => {;
        } catch (e) {
      hcxRes.data.pipe(response);      reject(e);
      }).catch(reject);  }
    });
}


   response.on('closeapp.use(bodyParser.json());
app.use('/', (router) => {
                source.cancel('요청을 취소합니다.');
                resolve();
            });
        } catch (e) {
            reject(e);
        }
    });
}

app.use(bodyParser.json());
app.use('/', router);
app.listen(8080);
  • GEMINI
Code Block
languagejs
themeEmacs
titleserver.js
const express = require('express');
const axios = require('axios');
const bodyParser = require('body-parser');

const GEMINI_URL = ''; // API URL ex) 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:streamGenerateContent'
const GEMINI_PARAM = ''; // API PARAMETER ex) '?alt=sse&key='
const GEMINI_KEY = ''; // API KEY

const app = express();
const router = express.Router();

router.post('/request', (request, response) => ;
app.listen(8080);

...

이미지 생성 AI

DALL-E 예제

  • axios를 활용한 Node Express server 예제입니다.
Code Block
languagejs
themeEmacs
titleserver.js
const express = require('express');
const axios = require('axios');
const bodyParser = require('body-parser');

const DALLE_URL = ''; // API URL ex) 'https://api.openai.com/v1/images/generations'
const DALLE_API_KEY = ''; // API KEY

const app = express();
const router = express.Router();

router.post('/request', (request, response) => {
    const bodyData = request.body;

    requestDALLEServer(response, bodyData)
        .then((data) => response.json(data))
        .catch((error) => response.status(error.status).json(error).end());
});

/**
 * DALL·E 서버로 요청을 합니다.
 * @param {Response} response
 * @param {Object} bodyData 
 * @returns {Promise}
 */
function requestDALLEServer(response, bodyData) {
    const bodyDatasource = Objectaxios.CancelToken.assign({}, request.bodysource();
    const requestGeminiServer(response, bodyData)
url = DALLE_URL;

    return new .thenPromise((resolve, reject) => response.end()) {
        try {
          .catch((err) => responseaxios.status(err.status || 500).json(err).end());
});

/**
 * Gemini 서버로 요청을 합니다.
 * @param {Response} response
 * @param {Object} bodyData
 * @returns {Promise}
 */
function requestGeminiServer(response, bodyData) {post(url, bodyData, {
                headers: {
                 const url = GEMINI_URL;
 'Content-Type': 'application/json',
   const key = GEMINI_KEY;     const param = GEMINI_PARAM;     const urlWithParam = `${url}${param}${key}`;

'Authorization': `Bearer ${DALLE_API_KEY}`
   const source = axios.CancelToken.source();     return new Promise((resolve, reject) => {},
        try {       cancelToken: source.token
    axios.post(urlWithParam, bodyData, {      }).then(res =>  {
       headers: {        resolve(res.data);
            'Content-Type': 'application/json'
}).catch(error => {
               }, reject({
               responseType: 'stream',    status: error.response ? error.response.status : 500,
       cancelToken: source.token            message: }).then(geminiRes => {error.message
                 geminiRes.data.pipe(response});
            }).catch(reject);

            response.on('close', () => {
                source.cancel('요청을 취소합니다.');
                resolve();
            });
        } catch (e) {
            reject(e);
        }
    });
}


app.use(bodyParser.json());
app.use('/', router);
app.listen(8080);

...