-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.mjs
More file actions
29 lines (22 loc) · 1.15 KB
/
server.mjs
File metadata and controls
29 lines (22 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import express from "express";
import { ChatOpenAI } from "@langchain/openai";
// LangChain の ChatOpenAI クラスは OPENAI_API_KEY 環境変数を自動的に参照する
const chatModel = new ChatOpenAI();
const app = express();
// public ディレクトリ下のファイルに適切なパスでアクセスできるようにする
app.use(express.static("./public"));
// リクエストボディを JSON として解釈して request.body に格納する
app.use(express.json());
app.post("/chat", async (request, response) => {
const promptText = request?.body?.promptText;
// クライアントから送られてきたデータは無条件で信用しない
if (typeof promptText !== "string") {
response.sendStatus(400);
return;
}
const aiMessageChunk = await chatModel.invoke(promptText);
response.json({ content: aiMessageChunk.content });
});
// 使用するホスティングサービス (Render など) によってはリクエストを受け付けるポートが指定されている場合がある。
// たいていの場合は PORT という名前の環境変数を通して参照できる。
app.listen(process.env.PORT || 3000);