-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathhandler.js
More file actions
356 lines (310 loc) · 10.1 KB
/
handler.js
File metadata and controls
356 lines (310 loc) · 10.1 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
"use strict";
const line = require("@line/bot-sdk");
const OpenAI = require('openai');
const crypto = require("crypto");
const request = require("request");
const Log = require("@dazn/lambda-powertools-logger");
// Bedrock Runtime SDK と DynamoDB SDK をインポート
const { BedrockRuntimeClient, InvokeModelCommand } = require("@aws-sdk/client-bedrock-runtime");
const { DynamoDBClient, PutItemCommand, QueryCommand } = require("@aws-sdk/client-dynamodb");
// S3 SDK をインポート
const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');
const fs = require('fs').promises;
const os = require('os');
const path = require('path');
// クライアントの初期化 (両方の方法で共通)
const dynamodb = new DynamoDBClient({
region: "ap-northeast-1"
});
const lineClient = new line.Client({
channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN,
channelSecret: process.env.CHANNEL_SECRET,
});
const bedrockClient = new BedrockRuntimeClient({
region: "ap-northeast-1",
});
function generateResponse(statusCode, lineStatus, message) {
return {
statusCode: statusCode,
headers: { "X-Line-Status": lineStatus },
body: `{"result":"${message}"}`,
};
}
const validateSignature = (event) => {
const signature = event.headers["X-Line-Signature"];
const body = event.body;
const hash = crypto
.createHmac("sha256", process.env.CHANNEL_SECRET)
.update(body)
.digest("base64");
return hash === signature;
};
function isLineConnectionError(replyToken, context) {
if (replyToken !== "00000000000000000000000000000000") return false;
// 接続確認エラー回避
context.succeed(generateResponse(200, "OK", "connect check"));
return true;
}
async function getUserProfile(userId) {
try {
const profile = await lineClient.getProfile(userId);
return profile;
} catch (error) {
Log.error(`Get profile error: ${error}`);
return null;
}
}
async function saveConversation(userId, userMessage, aiMessage) {
try {
const command = new PutItemCommand({
TableName: process.env.DYNAMODB_TABLE,
Item: {
userId: { S: userId },
timestamp: { N: Date.now().toString() },
userMessage: { S: userMessage },
aiMessage: { S: aiMessage }
}
});
const response = await dynamodb.send(command);
Log.info('Conversation saved successfully', { data: response });
} catch (error) {
Log.error('Error saving conversation:', { error });
}
}
async function getConversationHistory(userId, limit = 5) {
try {
const params = {
TableName: process.env.DYNAMODB_TABLE,
KeyConditionExpression: "userId = :userId",
ExpressionAttributeValues: {
":userId": { S: userId },
},
Limit: limit,
ScanIndexForward: false,
};
const command = new QueryCommand(params);
const response = await dynamodb.send(command);
Log.info('Conversation history retrieved successfully', { data: response.Items });
return response.Items;
} catch (error) {
Log.error('Error getting conversation history:', { error });
return [];
}
}
async function replyMessage(replyToken, message) {
try {
const result = await lineClient.replyMessage(replyToken, message);
return result;
} catch (error) {
Log.error(`Get replyMessage error`, { error });
return null;
}
}
// 引数にpromptのテキストを指定する
async function invokeBedrock(prompt, history) {
// history を逆順にする(時系列で並べるため)
history.reverse();
// 過去の会話の履歴を取得
let conversationHistory = [];
for (const item of history) {
conversationHistory.push({
role: "user",
content: [
{
type: "text",
text: item.userMessage.S,
},
],
});
conversationHistory.push({
role: "assistant",
content: [
{
type: "text",
text: item.aiMessage.S,
},
],
});
}
Log.info("会話履歴", { data: conversationHistory });
// 新しいメッセージを追加
const newMessage = {
role: "user",
content: [
{
type: "text",
text: prompt,
},
],
}
// 会話履歴と新しいメッセージを結合
conversationHistory.push(newMessage);
const params = {
modelId: "anthropic.claude-3-5-sonnet-20240620-v1:0", // 使用したいモデルIDを指定
contentType: "application/json",
accept: "application/json",
body: JSON.stringify({
anthropic_version: "bedrock-2023-05-31",
max_tokens: 8192,
messages: conversationHistory
}),
};
try {
const command = new InvokeModelCommand(params);
const response = await bedrockClient.send(command);
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
// Log.info("Bedrock response content:", responseBody.content);
// Log.info("Bedrock response text:", responseBody.content[0].text);
return responseBody.content[0].text;
} catch (error) {
Log.error("Error invoking Bedrock:", { error });
return "エラーが発生しました。";
}
}
async function invokeBedrockWithImage(imagePath) {
const image = await fs.readFile(imagePath);
const binaryData = Buffer.from(image).toString('base64');
const messages = [
{
role: "user",
content: [
{
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: binaryData
}
},
{
type: "text",
text: "画像について何が書かれているか日本語で返答せよ。"
}
]
}
];
const params = {
modelId: "anthropic.claude-3-5-sonnet-20240620-v1:0", // 使用したいモデルIDを指定
contentType: "application/json",
accept: "application/json",
body: JSON.stringify({
anthropic_version: "bedrock-2023-05-31",
max_tokens: 8192,
messages: messages
}),
};
try {
const command = new InvokeModelCommand(params);
const response = await bedrockClient.send(command);
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
// Log.info("Bedrock response content:", responseBody.content);
// Log.info("Bedrock response text:", responseBody.content[0].text);
return responseBody.content[0].text;
} catch (error) {
Log.error("Error invoking Bedrock:", error);
return "エラーが発生しました。";
}
}
module.exports.callback = async (event, context) => {
// 非同期処理を開始
await processAsyncTask(event)
.then(() => Log.info('Async task completed'))
.catch(err => Log.info('Async task failed:', { err }));
// 即座に応答を返す
return {
statusCode: 202,
body: JSON.stringify({ message: 'Task accepted and processing' }),
};
};
async function processAsyncTask(event) {
const body = JSON.parse(event.body);
const userId = body.events[0].source.userId;
let text = body.events[0].message.text;
const replyToken = body.events[0].replyToken;
let aiResponse = ''
if (body.events[0].message.type === "image") {
const imageId = body.events[0].message.id;
const imageObj = await getImage(imageId);
Log.info("画像の取得", { data: imageObj });
aiResponse = await invokeBedrockWithImage(imageObj.filePath);
text = '画像について説明してください。:' + imageObj.s3Url;
} else if (body.events[0].message.type === "text") {
const history = await getConversationHistory(userId);
aiResponse = await invokeBedrock(text, history);
}
Log.info("AIの返答", { data: aiResponse });
const message = {
type: "text",
text: aiResponse,
};
Log.info("ユーザID", { data: userId, text: text, data: aiResponse });
const result = await saveConversation(userId, text, aiResponse);
Log.info("保存結果", { data: result });
const messageResult = await replyMessage(replyToken, message);
Log.info("送信結果", { data: messageResult });
}
async function getImage(messageId) {
try {
// 画像のバイナリデータを取得
const stream = await lineClient.getMessageContent(messageId);
// バイナリデータをバッファに変換
let chunks = [];
for await (const chunk of stream) {
chunks.push(chunk);
}
const buffer = Buffer.concat(chunks);
Log.info('画像の取得に成功しました:', { data: buffer });
const tempFilename = `image_${Date.now()}.jpg`;
const tempFileObj = await saveImageTemporarily(buffer, tempFilename);
return tempFileObj;
} catch (error) {
Log.error('画像の取得に失敗しました:', { error });
return lineClient.replyMessage(event.replyToken, {
type: 'text',
text: '画像の処理中にエラーが発生しました。'
});
}
}
async function saveImageTemporarily(imageBuffer, filename) {
const tempDir = os.tmpdir();
const filePath = path.join(tempDir, filename);
try {
await fs.writeFile(filePath, imageBuffer);
Log.info('画像を一時保存しました', { filePath });
// s3に画像をアップロード
const s3Key = `images/${filename}`;
const s3Url = await uploadImageToS3(filePath, s3Key);
Log.info('S3に画像をアップロードしました', { s3Url });
return {
filePath,
s3Url
};
} catch (error) {
Log.error('Error saving image:', { error });
throw error;
}
}
async function uploadImageToS3(filePath, s3Key) {
const s3 = new S3Client({ region: 'ap-northeast-1' });
const bucketName = process.env.S3_BUCKET;
if (!bucketName) {
throw new Error('S3_BUCKET environment variable is not set');
}
try {
const fileContent = await fs.readFile(filePath);
const params = {
Bucket: bucketName,
Key: s3Key,
Body: fileContent,
ContentType: 'image/jpeg' // 適切なContent-Typeに変更してください
};
const command = new PutObjectCommand(params);
const response = await s3.send(command);
Log.info(`Image uploaded successfully. ETag: ${response.ETag}`);
const region = await s3.config.region();
return `https://${bucketName}.s3.${region}.amazonaws.com/${s3Key}`;
} catch (error) {
Log.error('Error uploading image to S3:', { error });
throw error;
}
}