An intelligent AI-powered shopping assistant that creates meal plans and automatically adds groceries to your Amazon Fresh cart
- π§ AI Meal Planning: Generate personalized weekly meal plans using Google Gemini 2.5 Pro AI with detailed nutrition analysis
- π Smart Shopping Lists: Automatically extract ingredients from meal plans with quantity consolidation, accounting for pantry items
- π Preference Learning: Learns from your shopping history to suggest preferred brands and products you've bought before
- π€ Intelligent Product Selection: LLM-powered product matching that analyzes top 3 search results to pick the best value/match with automatic fallback
- π Automated Cart Management: Seamlessly search and add items to your Amazon Fresh cart with real-time price tracking
- π° Budget Tracking: Monitor spending in real-time with configurable budget limits and automatic budget cutoffs
- π Nutritional Analysis: Visual charts showing daily calories, protein, carbs, and fat breakdowns
- π PDF Export: Generate downloadable meal plan PDFs with shopping lists and recipe instructions
- πΎ History & Persistence: SQLite database stores meal plans, shopping lists, and settings for easy review
- π One-Click Reordering: Easily reload past meal plans to shop for them again
- ποΈ Granular History Control: Delete individual meal plans or clear entire history
- π― Customizable Preferences: Set dietary restrictions, pantry items, and budget constraints
- πͺ Session Persistence: Save browser sessions to avoid repeated logins
- π¨ Interactive UI: Beautiful Streamlit interface with real-time progress tracking, meal cards, and tabbed weekly views
This project uses LangGraph to orchestrate a multi-step workflow:
User Input β Planner β Extractor β Shopper β Human Review β Checkout
-
Planner Node:
- Analyzes user meal preferences using Google Gemini 2.5 Pro AI
- Generates a structured weekly meal plan with breakfast, lunch, and dinner
- Includes detailed ingredients with quantities (lbs, oz, cups, count)
- Calculates daily nutritional information (calories, protein, carbs, fat)
- Uses higher temperature (0.7) for creative meal planning
-
Extractor Node:
- Parses meal plan JSON to extract all ingredients using Google Gemini 2.5 Pro
- Consolidates duplicate items by summing quantities
- Filters out pantry items that the user already has
- Preference Learning: Analyzes past shopping history to learn brand preferences
- Automatically upgrades generic items (e.g., "Peanut Butter") to specific brands you've bought before (e.g., "Smuckers Peanut Butter")
- Returns a clean, deduplicated shopping list with improved text cleaning
-
Shopper Node:
- Searches Amazon Fresh for each item
- Scrapes top 3 search results with titles and prices
- Uses Google Gemini 2.5 Flash to intelligently select the best match/value from options
- Smart Fallback: If AI selection fails, automatically retries with brute-force first-result method
- Adds selected items to cart with real-time budget tracking
- Handles missing items and budget cutoffs gracefully
- Automatically navigates to checkout when complete
-
Human Review Node:
- Pauses workflow for user to review and edit shopping list
- Allows manual item removal/addition before shopping begins
- Provides PDF download option for meal plan
-
Checkout Node:
- Navigates to Amazon cart
- Attempts multiple checkout button strategies (Fresh Cart, Proceed to checkout, etc.)
- Displays comprehensive review with success rate metrics
- Shows separate columns for successfully added items vs. missed items
- Handles checkout initiation, then terminates for manual user completion
- Python 3.8 or higher
- Google API Key for Gemini AI
- Amazon account with Amazon Fresh access
- Chrome/Chromium browser (for Playwright)
-
Clone the repository
git clone https://github.com/YOUR_USERNAME/amazon_agent.git cd amazon_agent -
Create and activate a virtual environment
python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate
-
Install dependencies
pip install -r requirements.txt
-
Install Playwright browsers
playwright install chromium
-
Set up API Key (Optional)
You can create a
.envfile in the project root:GOOGLE_API_KEY=your_google_api_key_here
OR simply run the app, and it will ask for your key in the sidebar if one is not found.
Get your Google API key from Google AI Studio
Note: The first time you run the app, you'll need to manually log in to Amazon in the browser window that opens. Your session will be saved for future runs.
If you prefer a single file executable or want to distribute the app:
Note: You must run the build script on the same operating system you are building for (e.g., run on Windows to build a
.exe, run on Mac to build a Mac app).
- Build the executable (requires Python installed once for the build):
pip install -r requirements.txt python build_executable.py
- Run the app:
- Go to the
dist/folder. - Double-click
AmazonFreshAgent(Mac) orAmazonFreshAgent.exe(Windows). - You can move this single file anywhere on your computer.
- Go to the
streamlit run amazon_fresh_fetch.pyThe application will open in your default browser (typically at http://localhost:8501 or http://localhost:8503)
First Run: A Chrome browser window will open for Amazon Fresh. You'll need to manually log in once. Your session will be saved automatically.
In the sidebar, set:
- Weekly Budget: Your spending limit (default: $200)
- Pantry Items: Items you already have (e.g., "Salt, Pepper, Olive Oil")
Enter your meal preferences in the text area. Example:
Create a weekly meal plan for 2 adults with:
- Healthy meals ready in 30 minutes
- Monday-Friday dinner and lunch
- No pork, vegetarian options preferred
- Focus on whole grains and 30g protein per meal
- Review the generated meal plan with nutritional charts
- View meal details in organized day-by-day tabs
- Edit the shopping list (add/remove items using the data editor)
- Download a PDF version of your meal plan
- Confirm to start shopping
The agent will:
- Search for each item on Amazon Fresh
- Scrape top 3 search results with prices
- Use AI to intelligently select the best product match/value
- Add selected items to your cart automatically
- Track prices and budget in real-time
- Handle missing items and budget cutoffs gracefully
- View comprehensive summary with success rate percentage
- See separate sections for successfully added items vs. missed items
- Review total cost, budget status, and cart statistics
- The browser will automatically navigate to checkout with multiple fallback strategies
- Complete payment, delivery time, and final order confirmation manually in the browser window
- View Past Plans: Click on any date in the "History" sidebar to view that meal plan.
- Download PDF: When viewing a past plan, click "π Download PDF Plan" to get a copy.
- Reorder: Click "π Reorder" to load a past plan back into the main view and shop for it again.
- Delete: Click the trash icon (ποΈ) next to a specific plan to remove it, or use "Clear History" to remove everything.
- Streamlit: Web UI framework with interactive components
- LangGraph: Workflow orchestration and state management with checkpoints
- LangChain: LLM integration and prompt management
- Google Gemini 2.5 Pro: AI model for meal planning and ingredient extraction (with preference learning)
- Google Gemini 2.5 Flash: AI model for fast product selection during shopping
- Playwright: Browser automation for Amazon Fresh interaction
- SQLite: Local database for meal plan history and settings
- FPDF: PDF generation for meal plan exports
- Pandas: Data manipulation for nutritional analysis and shopping lists
- Python: Core language (3.8+)
amazon_agent/
βββ amazon_fresh_fetch.py # Main application entry point (UI & Orchestration)
βββ workflow.py # LangGraph workflow definition
βββ agent.py # Agent nodes and logic
βββ browser.py # Browser automation logic
βββ database.py # Database interactions
βββ prompts.py # Centralized AI prompts
βββ ui.py # UI components and styles
βββ utils.py # Utility functions
βββ config.py # Configuration settings
βββ pdf_generator.py # PDF generation logic
βββ amazon_session.json # Browser session storage (gitignored)
βββ agent_data.db # SQLite database for meal plans & settings (gitignored)
βββ .env # Environment variables (gitignored)
βββ .gitignore # Git ignore rules
βββ requirements.txt # Python dependencies
βββ user_session/ # Chrome browser session data (gitignored)
βββ packaging/ # PyInstaller packaging scripts
βββ build_executable.py # Script to build standalone executable
βββ README.md # This file
- Session Data: Browser sessions are stored locally in
amazon_session.json(gitignored) - Database: SQLite database
agent_data.dbstores meal plans locally (gitignored) - API Keys: Store your Google API key in
.envfile (gitignored) - Browser Data: Chrome session data in
user_session/directory (gitignored) - Credentials: Never commit sensitive information to the repository
| Variable | Description | Required |
|---|---|---|
GOOGLE_API_KEY |
Your Google Gemini API key | Yes |
Set your weekly budget in the Streamlit sidebar. The agent will stop adding items once the budget is reached.
List items you already have in your pantry. The agent will exclude these from the shopping list.
The agent automatically learns from your shopping history stored in the database. When you request a generic item (e.g., "Peanut Butter"), it will suggest the specific brand you've purchased before (e.g., "Smuckers Natural Peanut Butter"). This preference learning improves over time as you create more meal plans.
The scripts/ directory contains helpful tools for managing your data:
Train the AI on your past purchases to improve brand recommendations.
- Copy the text from your Amazon Fresh order history (or email receipt).
- Paste it into the
RAW_DATAvariable inscripts/import_receipt.py. - Run the script:
python scripts/import_receipt.py
View the contents of your local database without needing a SQL client.
- Shows all tables
- Lists top 20 most frequent items in purchase history
- Displays saved settings
- Summarizes recent meal plans
python scripts/check_db.py
- Ensure Playwright browsers are installed:
playwright install chromium - Check that Chrome/Chromium is available on your system
- The browser will pause for manual login on first run
- Session is saved to
amazon_session.jsonfor future runs - Delete the session file to force re-login
- The agent uses AI to select the best match from search results
- If AI selection fails, it automatically falls back to adding the first search result
- Items that can't be matched or exceed budget appear in the "Missing/Skipped" section
- You can manually add items in the browser window if needed
- The SQLite database (
agent_data.db) is created automatically on first run - If you encounter database errors, you can delete
agent_data.dbto start fresh - Your meal plan history will be lost if you delete the database
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- Built with LangGraph for workflow orchestration
- Powered by Google Gemini AI
- UI created with Streamlit
- Browser automation via Playwright
For questions or support, please open an issue on GitHub.
Made with β€οΈ for easier grocery shopping
β Star this repo if you find it helpful!