Open YNSTakeru opened 3 months ago
<html>
<body>
<h1>AI作成</h1>
<form action="">
<div>
<div>
<label for="textarea">入力(cmd + enterでAIに質問)</label>
</div>
<textarea
id="textarea"
name=""
id=""
cols="100"
rows="10"
placeholder="質問を入力してください"
></textarea>
</div>
</form>
<div id="output"></div>
<script type="importmap">
{
"imports": {
"@google/generative-ai": "https://esm.run/@google/generative-ai"
}
}
</script>
<script type="module">
import { GoogleGenerativeAI } from "@google/generative-ai";
const textarea = document.getElementById("textarea");
textarea.addEventListener("keydown", function (event) {
if (event.key == "Enter" && !event.isComposing) {
event.preventDefault();
if (event.metaKey) {
// run();
getAPIKey();
} else {
const start = this.selectionStart;
const end = this.selectionEnd;
this.value =
this.value.substring(0, start) + "\n" + this.value.substring(end);
this.selectionStart = this.selectionEnd = start + 1;
}
}
});
async function run(apiKey) {
const API_KEY = apiKey;
const genAI = new GoogleGenerativeAI(API_KEY);
document.querySelector("#output").innerText = "AIが生成中です...";
const model = genAI.getGenerativeModel({ model: "gemini-pro" });
const prompt = `${textarea.value} 上記文章は日報です。これについてPDCAの観点からレビューしてください。改善点があれば具体的に記述してください`;
const result = await model.generateContent(prompt);
const response = await result.response;
const text = response.text();
document.getElementById("output").innerText = text;
}
async function getAPIKey() {
const response = await fetch("https://localhost:3000/", {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
if (response.ok) {
response.json().then((data) => {
const { key } = data;
run(key);
});
}
}
</script>
</body>
</html>
expressでサーバーを構築
app.js
const express = require("express");
const https = require("https");
const fs = require("fs");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const bodyParser = require("body-parser");
require("dotenv").config();
const app = express();
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors({ origin: "https://127.0.0.1:5500", credentials: true }));
app.get("/", (req, res) => {
res.json({ key: process.env.API_KEY });
});
const httpsOptions = {
key: fs.readFileSync("./key.pem"),
cert: fs.readFileSync("./cert.pem"),
};
https.createServer(httpsOptions, app).listen(3000, () => {
console.log("HTTPS Server is running on port 3000");
});
package.json
{
"dependencies": {
"body-parser": "^1.20.2",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"fs": "^0.0.1-security",
"https": "^1.0.0"
}
}
npm install
node app.js
AIの取得
以下のhtmlファイルをindex.htmlとして記述 live serverなどで起動する
動かない場合はhttps化