Skip to content

Instantly share code, notes, and snippets.

@kujirahand
Last active December 22, 2023 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kujirahand/425566b8814dd66af04dc3ec2332a214 to your computer and use it in GitHub Desktop.
Save kujirahand/425566b8814dd66af04dc3ec2332a214 to your computer and use it in GitHub Desktop.
ChatGPT APIを使ったアイデア発想ツール
const express = require('express');
const OpenAI = require('openai')
// APIキーを設定する(以下は書き換えが必要です★★★) --- (*1)
const API_KEY = 'xxx'
// APIキーを設定したオブジェクトを生成
const openai = new OpenAI({
apiKey: (API_KEY === 'xxx') ? process.env['OPENAI_API_KEY'] : API_KEY
});
// ChatGPT APIを呼び出す --- (*2)
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サーバーを起動 --- (*3)
const app = express();
const port = 3001;
const server = app.listen(port, () => {
console.log('[URL] http://localhost:' + port);
});
// サーバーの応答を設定 --- (*4)
app.get('/', (_req, res) => {
res.send('<h1>アイデアツール</h1>' +
'<form action="/idea" method="get">' +
'アイデア: <input type="text" name="q" size=40>' +
'<input type="submit" value="作成"></form>');
});
app.get('/idea', async (req, res) => {
let q = req.query.q;
q = q.replace(/"/g, '')
const prompt = `
### 指示:
アイデアフレームワークの「フィッシュボーン図」を利用して、次のアイデアについて箇条書きで答えてください。また、箇条書きの内容を元にして、Mermaid図のコードを生成してください。
### アイデア:
"""${q}"""`
const result = await callChatgpt(prompt);
const toHtml = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
// 結果からMermaidコードを抽出 --- (*5)
const m = toHtml(result).match(/```mermaid(.*)```/s);
const code = m ? m[1] : '';
res.send(`<h1><a href="/">${toHtml(q)}のアイデアを考えました</a></h1>
<script src="https://cdn.jsdelivr.net/npm/mermaid@10.5.0/dist/mermaid.min.js"></script>
<pre class="mermaid">${code}</pre><hr><pre>${result}</pre>`)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment