Created
February 6, 2024 16:20
-
-
Save kujirahand/5d365ee1f065cbee8ee833f25d196ad5 to your computer and use it in GitHub Desktop.
Node.jsとChatGPT APIを使った翻訳ツール
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ライブラリを読み込む --- (*1) | |
const express = require('express'); | |
const OpenAI = require('openai') | |
const path = require('path') | |
// APIキーを設定する(以下は書き換えが必要です★★★) --- (*2) | |
const API_KEY = 'xxx' | |
// const API_KEY = process.env['OPENAI_API_KEY'] | |
// APIキーを設定したオブジェクトを生成 | |
const openai = new OpenAI({ apiKey: API_KEY }); | |
// ChatGPTに入力するプロンプトのテンプレート --- (*3) | |
const PROMPT_TEMPLATE = ` | |
### 指示: | |
次の入力を英語、中国語、韓国語、スペイン語に翻訳してください。 | |
### 入力: | |
"""__input__""" | |
### 出力例: | |
- 英語: *** | |
- 中国語: *** | |
- 韓国語: *** | |
- スペイン語: *** | |
` | |
// ChatGPT APIを呼び出す非同期の関数を定義 --- (*4) | |
async function callChatgpt(msg) { | |
const params = { | |
messages: [{ role: 'user', content: msg }], | |
model: 'gpt-3.5-turbo', | |
}; | |
const chatCompletion = await openai.chat.completions.create(params); | |
return chatCompletion.choices[0].message.content; | |
} | |
// Webサーバーを起動 --- (*5) | |
const app = express(); | |
const port = 3001; | |
const server = app.listen(port, () => { | |
console.log('[URL] http://localhost:' + port); | |
}); | |
// サーバーの応答を設定 --- (*6) | |
app.get('/', (_req, res) => { //index.htmlを返す | |
res.sendFile(path.join(__dirname, 'index.html')); | |
}); | |
// 翻訳の応答を設定 --- (*7) | |
app.get('/translate', async (req, res) => { | |
let q = '' + req.query.q; | |
q = q.replace(/"/g, '') | |
// テンプレートを置換してChatGPTに問い合わせる --- (*8) | |
const prompt = PROMPT_TEMPLATE.replace('__input__', q); | |
const result = await callChatgpt(prompt); | |
const toHtml = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>') | |
// 結果を戻す --- (*9) | |
res.send(toHtml(result)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
そして、以下が上記のプログラムで使う
index.html
です。同じディレクトリに配置して使います。