はじめに
「この前買ったシャンプー、そろそろ切れそうだな」——でも買い物中にはそんなことを忘れてしまうのが常。
そんな課題を解決するために、買い忘れ防止アプリ( smart-shopper-agent )を作りました。レシートを LINE に送ると購買履歴が記録され、店舗に近づいた瞬間に「今日はこれを買うといいよ」と通知が届くシステムです。
全4章構成で、アプリ全体を解説します。
- 第1章(本記事): LINE Webhook でレシート画像を受け取り Gemini で解析・S3 保存
- 第2章: AgentCore 用ツール Lambda を作る
- 第3章: AgentCore Gateway でツールを MCP 公開する
- 第4章: Strands Agent をデプロイして LINE 通知まで繋げる
システム全体像
【第1章】レシート解析フロー
LINE でレシート画像を送信
→ API Gateway → Lambda
→ Gemini File API で解析(店舗名・商品・価格・カテゴリを JSON 抽出)
→ 画像を S3(images/)、JSONL を S3(jsons/)に保存
→ 解析結果を LINE に返信
【第2〜4章】購入提案フロー
iPhone が店舗に近づく → HTTP POST
→ Lambda → AgentCore Runtime(AI エージェントが推論)
→ S3 から購買履歴取得 → 消費サイクル計算 → 提案生成
→ LINE プッシュ通知
第1章で貯めた S3 の JSONL データを、第2〜4章の AI エージェントが読みに行く設計です。
技術スタック(第1章)
| 用途 | 採用技術 |
|---|---|
| メッセージング | LINE Messaging API(line-bot-sdk v3) |
| 画像解析 | Google Gemini 3.1 Flash Lite Preview(File API) |
| データ保存 | Amazon S3(JSONL 形式) |
| シークレット管理 | AWS SSM Parameter Store |
| 実行基盤 | AWS Lambda + API Gateway |
アーキテクチャの決定事項
ベクター DB なし・RAG なし
購買履歴の検索は「店舗名の部分一致」で十分なため、ベクター DB や埋め込みは使いません。S3 に JSONL を積み上げていくだけです。
S3 のパーティション構造
smart-shopper-agent/
├── images/year=2026/month=5/day=10/{messageId}.jpg
└── jsons/year=2026/month=5/day=10/{messageId}.jsonl
Hive 形式で日付ごとに分割しており、後から Athena でクエリすることもできます(今回は未使用)。
Lambda の構成
receipts_analysis/
├── lambda_function.py # エントリポイント
├── config/settings.py # SSM からシークレット取得
├── schemas/receipt.py # Pydantic モデル
├── services/
│ ├── line_service.py # 画像ダウンロード
│ ├── gemini_service.py # Gemini 解析
│ └── s3_service.py # S3 保存
└── utils/date_utils.py # JST・パーティションキー
シークレット管理
LINE チャネルシークレット・アクセストークン・Gemini API キーを SSM Parameter Store(SecureString)に格納し、コールドスタート時に一括取得します。
config/settings.py:
import os
import boto3
S3_BUCKET_NAME = os.environ.get('S3_BUCKET_NAME')
RECEIPT_PROMPT = "提供されたレシート画像から情報を抽出し、指定されたJSONフォーマットで出力してください。"
ssm = boto3.client('ssm')
response = ssm.get_parameters(
Names=[
'/smart-shopper/line_channel_secret',
'/smart-shopper/line_access_token',
'/smart-shopper/gemini_api_key'
],
WithDecryption=True
)
secrets = {p['Name']: p['Value'] for p in response['Parameters']}
LINE_CHANNEL_SECRET = secrets['/smart-shopper/line_channel_secret']
LINE_ACCESS_TOKEN = secrets['/smart-shopper/line_access_token']
GEMINI_API_KEY = secrets['/smart-shopper/gemini_api_key']
モジュールレベルで実行することで、コールドスタート時の1回だけ SSM へのアクセスが走ります。
データモデル(Pydantic)
Gemini の出力を型安全に受け取るため Pydantic でスキーマを定義します。
schemas/receipt.py:
from enum import Enum
from typing import List
from pydantic import BaseModel, Field
class ItemCategory(str, Enum):
FRESH_FOOD = "生鮮食品"
PROCESSED_FOOD = "加工食品"
BEVERAGE = "飲料・酒類"
DAILY_NECESSITIES = "日用品・消耗品"
MEDICINE = "医薬品"
COSMETICS = "化粧品"
OTHER = "その他"
class ReceiptItem(BaseModel):
name: str = Field(description="商品名")
price: int = Field(description="商品の価格")
category: ItemCategory = Field(description="商品名から判断されるカテゴリ")
class ReceiptJSON(BaseModel):
store_name: str = Field(description="店舗名")
purchased_at: str = Field(description="購入日時(ISO8601形式)")
items: List[ReceiptItem] = Field(default_factory=list)
Gemini File API でレシート解析
services/gemini_service.py:
import os, json, time
from google import genai
from config.settings import GEMINI_API_KEY
from schemas.receipt import ReceiptJSON
gemini_client = genai.Client(api_key=GEMINI_API_KEY)
def extract_receipt_data(image_binary: bytes, message_id: str, prompt: str) -> dict:
tmp_path = f"/tmp/{message_id}.jpg"
uploaded_file = None
try:
with open(tmp_path, "wb") as f:
f.write(image_binary)
uploaded_file = gemini_client.files.upload(file=tmp_path)
# ACTIVE になるまでポーリング
while True:
state = str(gemini_client.files.get(name=uploaded_file.name).state).upper()
if "ACTIVE" in state:
break
elif "FAILED" in state:
raise Exception("Gemini File API processing failed.")
time.sleep(2)
response = gemini_client.models.generate_content(
model='gemini-3.1-flash-lite-preview',
contents=[prompt, uploaded_file],
config=genai.types.GenerateContentConfig(
response_mime_type="application/json",
response_schema=ReceiptJSON, # Pydantic モデルをそのまま渡せる
temperature=0.0
)
)
return json.loads(response.text.strip())
finally:
if uploaded_file:
try:
gemini_client.files.delete(name=uploaded_file.name)
except Exception:
pass
if os.path.exists(tmp_path):
os.remove(tmp_path)
response_schema に Pydantic モデルを直接渡すと、Gemini が JSON を構造化して返してくれます。解析後はファイルを削除してストレージを節約します。
Lambda エントリポイント
lambda_function.py(画像イベント部分のみ抜粋):
from linebot.v3 import WebhookHandler
from linebot.v3.webhooks import MessageEvent, ImageMessageContent
from linebot.v3.messaging import Configuration, ApiClient, MessagingApi, ReplyMessageRequest, TextMessage
from config.settings import LINE_CHANNEL_SECRET, LINE_ACCESS_TOKEN, S3_BUCKET_NAME, RECEIPT_PROMPT
from services.line_service import get_image_content
from services.s3_service import save_image, save_jsonl
from services.gemini_service import extract_receipt_data
from utils.date_utils import get_jst_now, get_partition_string
handler = WebhookHandler(LINE_CHANNEL_SECRET)
configuration = Configuration(access_token=LINE_ACCESS_TOKEN)
@handler.add(MessageEvent, message=ImageMessageContent)
def handle_image(event):
message_id = event.message.id
now = get_jst_now()
partition = get_partition_string(now) # "year=2026/month=5/day=10"
with ApiClient(configuration) as api_client:
line_bot_api = MessagingApi(api_client)
# 1. LINE から画像をダウンロード
image_binary = get_image_content(message_id)
# 2. S3 に原本保存
save_image(S3_BUCKET_NAME, partition, message_id, image_binary)
try:
# 3. Gemini で解析
result = extract_receipt_data(image_binary, message_id, RECEIPT_PROMPT)
# 4. メタデータを付与
result["receipt_id"] = message_id
result["recorded_at"] = now.isoformat()
for i, item in enumerate(result.get("items", [])):
item["item_id"] = f"{message_id}-{i + 1}"
# 5. S3 に JSONL 保存
save_jsonl(S3_BUCKET_NAME, partition, message_id, result)
# 6. LINE に返信
items_str = "\n".join([f"- {item['name']} ({item['price']}円)" for item in result['items']])
reply_text = (
f"✅ 解析完了!\n\n"
f"【店舗】: {result['store_name']}\n"
f"【日時】: {result['purchased_at']}\n"
f"【商品】:\n{items_str}\n\n"
f"合計: {sum(item['price'] for item in result['items'])}円"
)
line_bot_api.reply_message(ReplyMessageRequest(
reply_token=event.reply_token,
messages=[TextMessage(text=reply_text)]
))
except Exception as e:
print(f"Error: {e}")
line_bot_api.reply_message(ReplyMessageRequest(
reply_token=event.reply_token,
messages=[TextMessage(text="⚠️ 解析に失敗しました。もう一度送ってみてください。")]
))
S3 に保存される JSONL の形式
{
"store_name": "イオン",
"purchased_at": "2026-05-10T14:32:00",
"items": [
{"name": "シャンプー", "price": 398, "category": "日用品・消耗品", "item_id": "msg123-1"},
{"name": "牛乳", "price": 198, "category": "飲料・酒類", "item_id": "msg123-2"}
],
"receipt_id": "msg123",
"recorded_at": "2026-05-10T14:35:22.123456+09:00"
}
このデータが第2〜4章の AI エージェントの材料になります。
次回予告
第2章では、この JSONL を読み込む「S3 検索ツール」と「消費サイクル計算ツール」の Lambda を作ります。これらが AgentCore エージェントのツールになります。