Skip to content

100+ AI Agents, Agent Skills and RAG Apps - Free and Open Source.

feat: Add AI Home Renovation Planner Agent with ADK and Nano Banana

Shubhamsaboo2bf142d42b38
diff --git a/README.md b/README.md
index c1c8fe44..361c2000 100644
--- a/README.md
+++ b/README.md
@@ -89,7 +89,7 @@ A curated collection of **Awesome LLM apps built with RAG, AI Agents, Multi-agen
* [πŸ•ΈοΈ Web Scrapping AI Agent (Local & Cloud)](starter_ai_agents/web_scrapping_ai_agent/)
### πŸš€ Advanced AI Agents
-
+* [🏚️ 🍌 AI Home Renovation Agent with Nano Banana](advanced_ai_agents/multi_agent_apps/ai_home_renovation_agent)
* [πŸ” AI Deep Research Agent](advanced_ai_agents/single_agent_apps/ai_deep_research_agent/)
* [🀝 AI Consultant Agent](advanced_ai_agents/single_agent_apps/ai_consultant_agent)
* [πŸ—οΈ AI System Architect Agent](advanced_ai_agents/single_agent_apps/ai_system_architect_r1/)
diff --git a/advanced_ai_agents/multi_agent_apps/ai_home_renovation_agent/README.md b/advanced_ai_agents/multi_agent_apps/ai_home_renovation_agent/README.md
new file mode 100644
index 00000000..3f65328d
--- /dev/null
+++ b/advanced_ai_agents/multi_agent_apps/ai_home_renovation_agent/README.md
@@ -0,0 +1,128 @@
+# 🏚️ 🍌 AI Home Renovation Planner Agent
+
+A multi-agent system built with Google ADK that analyzes photos of your space, creates personalized renovation plans, and generates photorealistic renderings using Gemini 2.5 Flash's multimodal capabilities.
+
+## Features
+
+- **πŸ” Smart Image Analysis**: Upload room photos and inspiration images - agent automatically detects and analyzes them
+- **🎨 Photorealistic Rendering**: Generates professional-quality images of your renovated space using Gemini 2.5 Flash
+- **πŸ’° Budget-Aware Planning**: Tailors recommendations to your budget constraints
+- **πŸ“Š Complete Roadmap**: Provides timeline, budget breakdown, contractor list, and action checklist
+- **πŸ€– Multi-Agent Orchestration**: Demonstrates Coordinator/Dispatcher + Sequential Pipeline patterns
+- **✏️ Iterative Refinement**: Edit generated renderings based on feedback
+
+## How It Works
+
+The system uses a **Coordinator/Dispatcher pattern** with three specialized agents:
+
+1. **Visual Assessor** πŸ“Έ
+ - Analyzes uploaded room photos (layout, condition, dimensions)
+ - Extracts style from inspiration images
+ - Estimates costs and identifies improvement opportunities
+
+2. **Design Planner** 🎨
+ - Creates budget-appropriate design plans
+ - Specifies exact materials, colors, and fixtures
+ - Prioritizes high-impact changes
+
+3. **Project Coordinator** πŸ—οΈ
+ - Generates comprehensive renovation roadmap
+ - Creates photorealistic rendering of renovated space
+ - Provides budget breakdown, timeline, and action steps
+
+## Quick Start
+
+1. **Clone the repository**
+ ```bash
+ git clone https://github.com/Shubhamsaboo/awesome-llm-apps.git
+ cd awesome-llm-apps/advanced_ai_agents/multi_agent_apps/ai_home_renovation_agent
+ ```
+
+2. **Install dependencies**
+ ```bash
+ pip install -r requirements.txt
+ ```
+
+3. **Set up your API key**
+ ```bash
+ export GOOGLE_API_KEY="your_gemini_api_key"
+ ```
+ Or create a `.env` file:
+ ```
+ GOOGLE_API_KEY=your_gemini_api_key
+ ```
+
+4. **Launch ADK Web**
+ ```bash
+ cd /Users/shubh/Downloads/awesome-llm-apps/multi_agent_apps
+ adk web
+ ```
+
+5. **Open browser** and select "HomeRenovationPlanner"
+
+## Usage Examples
+
+### Scenario 1: Current Room + Budget
+```
+[Upload photo of your kitchen]
+"What can I improve here with a $5k budget?"
+```
+β†’ Agent analyzes your space, suggests budget-friendly improvements, generates rendering
+
+### Scenario 2: Room + Inspiration
+```
+[Upload photo 1: your kitchen]
+[Upload photo 2: Pinterest inspiration]
+"Transform my kitchen to look like this. What's the cost?"
+```
+β†’ Agent extracts style from inspiration, applies to your room, provides budget + rendering
+
+### Scenario 3: Text Only
+```
+"Renovate my 10x12 kitchen with oak cabinets and laminate counters.
+Want modern farmhouse style with white shaker cabinets. Budget: $30k"
+```
+β†’ Agent creates design plan and generates rendering from description
+
+### Scenario 4: Iterative Refinement
+```
+[After initial rendering]
+"Make the cabinets cream instead of white"
+"Add pendant lights over the island"
+"Change flooring to lighter oak"
+```
+β†’ Agent refines the rendering with your feedback
+
+## Sample Prompts
+- "I want to renovate my small galley kitchen. It's 8x12 feet, has oak cabinets from the 90s. I love modern farmhouse style. Budget: $25k"
+- "My master bathroom is tiny (5x8) with a cramped tub. I want a spa-like retreat with walk-in shower. Budget: $15k"
+- "Transform my boring bedroom into a cozy retreat. Thinking accent wall, new flooring. Budget: $12k"
+
+## Tools & Capabilities
+
+- **google_search**: Finds renovation costs, materials, and trends
+- **estimate_renovation_cost**: Calculates costs by room type and scope
+- **calculate_timeline**: Estimates project duration
+- **generate_renovation_rendering**: Creates photorealistic renderings
+- **edit_renovation_rendering**: Refines renderings based on feedback
+- **Versioned artifacts**: Automatic version tracking for all renderings
+
+## Multi-Agent Pattern
+
+Demonstrates **Coordinator/Dispatcher + Sequential Pipeline**:
+
+```
+Coordinator (Root Agent)
+ β”œβ”€β”€ Info Agent (quick Q&A)
+ └── Planning Pipeline (Sequential)
+ β”œβ”€β”€ Visual Assessor (image analysis)
+ β”œβ”€β”€ Design Planner (specifications)
+ └── Project Coordinator (rendering + roadmap)
+```
+
+**Why this pattern?**
+- Efficient: Only runs workflows that are needed
+- Modular: Each agent has clear responsibilities
+- Scalable: Easy to add new features
+- Production-ready: Real-world agentic system pattern
+
diff --git a/advanced_ai_agents/multi_agent_apps/ai_home_renovation_agent/__init__.py b/advanced_ai_agents/multi_agent_apps/ai_home_renovation_agent/__init__.py
new file mode 100644
index 00000000..7c72f3df
--- /dev/null
+++ b/advanced_ai_agents/multi_agent_apps/ai_home_renovation_agent/__init__.py
@@ -0,0 +1,5 @@
+"""AI Home Renovation Planner - Multi-Agent Pattern Demo with Multimodal Vision"""
+
+from .agent import root_agent
+
+__all__ = ["root_agent"]
\ No newline at end of file
diff --git a/advanced_ai_agents/multi_agent_apps/ai_home_renovation_agent/agent.py b/advanced_ai_agents/multi_agent_apps/ai_home_renovation_agent/agent.py
new file mode 100644
index 00000000..195bebc8
--- /dev/null
+++ b/advanced_ai_agents/multi_agent_apps/ai_home_renovation_agent/agent.py
@@ -0,0 +1,435 @@
+"""AI Home Renovation Planner - Coordinator/Dispatcher Pattern with Multimodal Vision
+
+This demonstrates ADK's Coordinator/Dispatcher Pattern with Gemini 2.5 Flash's multimodal
+capabilities where a routing agent analyzes requests and delegates to specialists:
+
+- General questions β†’ Quick info agent
+- Renovation planning β†’ Full planning pipeline (Sequential Agent with 3 vision-enabled specialists)
+
+Pattern Reference: https://google.github.io/adk-docs/agents/multi-agents/#coordinator-dispatcher-pattern
+"""
+
+from google.adk.agents import LlmAgent, SequentialAgent
+from google.adk.tools import google_search
+from google.adk.tools.agent_tool import AgentTool
+from .tools import (
+ generate_renovation_rendering,
+ edit_renovation_rendering,
+ list_renovation_renderings,
+ list_reference_images,
+)
+
+
+# ============================================================================
+# Helper Tool Agent (wraps google_search)
+# ============================================================================
+
+search_agent = LlmAgent(
+ name="SearchAgent",
+ model="gemini-2.5-flash",
+ description="Searches for renovation costs, contractors, materials, and design trends",
+ instruction="Use google_search to find current renovation information, costs, materials, and trends. Be concise and cite sources.",
+ tools=[google_search],
+)
+
+
+# ============================================================================
+# Utility Tools
+# ============================================================================
+
+def estimate_renovation_cost(
+ room_type: str,
+ scope: str,
+ square_footage: int,
+) -> str:
+ """Estimate renovation costs based on room type and scope.
+
+ Args:
+ room_type: Type of room (kitchen, bathroom, bedroom, living_room, etc.)
+ scope: Renovation scope (cosmetic, moderate, full, luxury)
+ square_footage: Room size in square feet
+
+ Returns:
+ Estimated cost range
+ """
+ # Cost per sq ft estimates (2024 ranges)
+ rates = {
+ "kitchen": {"cosmetic": (50, 100), "moderate": (150, 250), "full": (300, 500), "luxury": (600, 1200)},
+ "bathroom": {"cosmetic": (75, 125), "moderate": (200, 350), "full": (400, 600), "luxury": (800, 1500)},
+ "bedroom": {"cosmetic": (30, 60), "moderate": (75, 150), "full": (150, 300), "luxury": (400, 800)},
+ "living_room": {"cosmetic": (40, 80), "moderate": (100, 200), "full": (200, 400), "luxury": (500, 1000)},
+ }
+
+ room = room_type.lower().replace(" ", "_")
+ scope_level = scope.lower()
+
+ if room not in rates:
+ room = "living_room"
+ if scope_level not in rates[room]:
+ scope_level = "moderate"
+
+ low, high = rates[room][scope_level]
+
+ total_low = low * square_footage
+ total_high = high * square_footage
+
+ return f"πŸ’° Estimated Cost: ${total_low:,} - ${total_high:,} ({scope_level} {room_type} renovation, ~{square_footage} sq ft)"
+
+
+def calculate_timeline(
+ scope: str,
+ room_type: str,
+) -> str:
+ """Estimate renovation timeline based on scope and room type.
+
+ Args:
+ scope: Renovation scope (cosmetic, moderate, full, luxury)
+ room_type: Type of room being renovated
+
+ Returns:
+ Estimated timeline with phases
+ """
+ timelines = {
+ "cosmetic": "1-2 weeks (quick refresh)",
+ "moderate": "3-6 weeks (includes some structural work)",
+ "full": "2-4 months (complete transformation)",
+ "luxury": "4-6 months (custom work, high-end finishes)"
+ }
+
+ scope_level = scope.lower()
+ timeline = timelines.get(scope_level, timelines["moderate"])
+
+ return f"⏱️ Estimated Timeline: {timeline}"
+
+
+# ============================================================================
+# Specialist Agent 1: Info Agent (for general inquiries)
+# ============================================================================
+
+info_agent = LlmAgent(
+ name="InfoAgent",
+ model="gemini-2.5-flash",
+ description="Handles general renovation questions and provides system information",
+ instruction="""
+You are the Info Agent for the AI Home Renovation Planner.
+
+WHEN TO USE: The coordinator routes general questions and casual greetings to you.
+
+YOUR RESPONSE:
+- Keep it brief and helpful (2-4 sentences)
+- Explain the system helps with home renovations using visual AI
+- Mention capabilities: photo analysis, design planning, budget estimation, timeline coordination
+- Ask about their renovation project (which room, can they share photos?)
+
+EXAMPLE:
+"Hi! I'm your AI Home Renovation Planner. I can analyze photos of your current space and inspiration images to create a personalized renovation plan with design suggestions, budget estimates, and timelines. Which room are you thinking of renovating? Feel free to share photos if you have them!"
+
+Be enthusiastic about home improvement and helpful!
+""",
+)
+
+
+# ============================================================================
+# Specialist Agent 2: Rendering Editor (for iterative refinements)
+# ============================================================================
+
+rendering_editor = LlmAgent(
+ name="RenderingEditor",
+ model="gemini-2.5-flash",
+ description="Edits existing renovation renderings based on user feedback",
+ instruction="""
+You refine existing renovation renderings.
+
+**TASK**: User wants to modify an existing rendering (e.g., "make cabinets cream", "darker flooring").
+
+**CRITICAL**: Find the most recent rendering filename from conversation history!
+Look for: "Saved as artifact: [filename]" or "kitchen_modern_renovation_v1.png" type references.
+
+Use **edit_renovation_rendering** tool:
+
+Parameters:
+1. artifact_filename: The exact filename of the most recent rendering
+2. prompt: Very specific edit instruction (be detailed!)
+3. asset_name: Base name without _vX (e.g., "kitchen_modern_renovation")
+
+**Example:**
+User: "Make the cabinets cream instead of white"
+Last rendering: "kitchen_modern_renovation_v1.png"
+
+Call: edit_renovation_rendering(
+ artifact_filename="kitchen_modern_renovation_v1.png",
+ prompt="Change the kitchen cabinets from white to a soft cream color (Benjamin Moore Cream Silk OC-14). Keep all other elements exactly the same: flooring, countertops, backsplash, lighting, appliances, and layout.",
+ asset_name="kitchen_modern_renovation"
+)
+
+Be SPECIFIC in prompts - vague = poor results!
+
+After editing, briefly confirm the change.
+""",
+ tools=[edit_renovation_rendering, list_renovation_renderings],
+)
+
+
+# ============================================================================
+# Specialist Agents 3-5: Full Planning Pipeline (SequentialAgent)
+# ============================================================================
+
+visual_assessor = LlmAgent(
+ name="VisualAssessor",
+ model="gemini-2.5-flash",
+ description="Analyzes room photos and inspiration images using visual AI",
+ instruction="""
+You are a visual AI specialist. Analyze ANY uploaded images and detect their type automatically.
+
+**IMPORTANT NOTE**: You can SEE and ANALYZE uploaded images, but currently the image editing feature
+has limitations in ADK Web. Focus on providing detailed analysis and design recommendations.
+
+AUTOMATICALLY DETECT:
+1. If image shows a CURRENT ROOM (existing space that needs renovation)
+2. If image shows INSPIRATION/STYLE reference (desired aesthetic)
+3. Extract budget constraints from user's message if mentioned
+
+## For CURRENT ROOM images:
+**Current Space Analysis:**
+- Room type: [kitchen/bathroom/bedroom/etc.]
+- Size estimate: [dimensions if visible]
+- Current condition: [issues, outdated elements, damage]
+- Existing style: [current aesthetic]
+- Key problems: [what needs fixing]
+- Improvement opportunities: [quick wins, major changes]
+
+## For INSPIRATION images:
+**Inspiration Style:**
+- Style name: [modern farmhouse/minimalist/industrial/etc.]
+- Color palette: [specific colors]
+- Key materials: [wood/stone/metal types]
+- Notable features: [lighting/storage/layout elements]
+- Design elements: [hardware/finishes/patterns]
+
+## Analysis Output:
+
+If BOTH current room + inspiration provided:
+- Compare current vs. inspiration
+- Identify specific changes needed to achieve the inspiration look
+- Note what can stay vs. what needs replacement
+
+If ONLY current room provided:
+- Suggest 2-3 style directions that would work well
+- Focus on functional improvements + aesthetic upgrades
+
+If budget mentioned:
+- Use estimate_renovation_cost tool with detected room type and appropriate scope
+- Assess what's achievable within budget
+
+**IMPORTANT: At the end of your analysis, output a structured summary:**
+
+```
+ASSESSMENT COMPLETE
+
+Images Provided:
+- Current room photo: [Yes/No - describe what you see if yes]
+- Inspiration photo: [Yes/No - describe style if yes]
+
+Room Details:
+- Type: [kitchen/bathroom/bedroom/etc.]
+- Current Analysis: [detailed analysis from photo if provided, or from description]
+- Desired Style: [from inspiration photo or user description]
+- Key Issues: [problems to address]
+- Improvement Opportunities: [suggested improvements]
+- Budget Constraint: $[amount if mentioned, or "Not specified"]
+```
+
+Be DETAILED in your analysis - this drives the quality of the generated rendering later.
+""",
+ tools=[AgentTool(search_agent), estimate_renovation_cost],
+)
+
+
+design_planner = LlmAgent(
+ name="DesignPlanner",
+ model="gemini-2.5-flash",
+ description="Creates detailed renovation design plan",
+ instruction="""
+Read from state: room_analysis, style_preferences, room_type, key_issues, opportunities, budget_constraint
+
+Create SPECIFIC, ACTIONABLE design plan tailored to their situation.
+
+## Design Plan
+
+**Budget-Conscious Approach:**
+- If budget_constraint exists: Prioritize changes that give max impact for the money
+- Separate "must-haves" vs "nice-to-haves"
+
+**Design Specifications:**
+- **Layout**: [keep same/modify - be specific about changes]
+- **Colors**: [exact colors with names - "Benjamin Moore Simply White OC-117"]
+- **Materials**: [specific products - "Shaker white cabinets", "Carrara quartz countertops"]
+- **Flooring**: [type, color, installation]
+- **Lighting**: [fixture types, placement, purpose]
+- **Storage**: [solutions for identified needs]
+- **Appliances**: [if applicable - keep/replace/upgrade]
+- **Key Features**: [backsplash, hardware, special elements]
+
+**Style Consistency:**
+If inspiration photo provided: Match that aesthetic precisely
+If no inspiration: Use style_preferences from state
+
+Use calculate_timeline tool with room_type and renovation_scope.
+
+**IMPORTANT: At the end, provide a structured summary:**
+
+```
+DESIGN COMPLETE
+
+Renovation Scope: [cosmetic/moderate/full/luxury]
+Design Approach: [preserve_layout/reconfigure_layout]
+
+Materials Summary:
+[Detailed list with product names]
+
+Design Plan Summary:
+[All specifications from above]
+```
+
+Be SPECIFIC with product names, colors, dimensions. This drives the rendering quality.
+""",
+ tools=[calculate_timeline],
+)
+
+
+project_coordinator = LlmAgent(
+ name="ProjectCoordinator",
+ model="gemini-2.5-flash",
+ description="Coordinates renovation timeline, budget, execution plan, and generates photorealistic renderings",
+ instruction="""
+Read conversation history to extract:
+- Image detection info from Visual Assessor (current room photo? inspiration photo? filenames?)
+- Design specifications from Design Planner
+- Budget constraints mentioned
+
+Create CLEAN, SCANNABLE final plan.
+
+## Renovation Plan
+
+**Budget Breakdown**:
+- Materials: $[amount]
+- Labor: $[amount]
+- Permits/fees: $[amount]
+- Contingency (10%): $[amount]
+- **Total**: $[amount]
+[If budget_constraint exists: Show "Within your $X budget βœ“" or suggest phasing]
+
+**Timeline**: [X weeks, broken into phases]
+**Contractors Needed**: [specific trades]
+
+## Design Summary
+[Pull key points from design_plan - tight, scannable bullets]
+
+## Action Checklist
+1. [immediate first steps]
+2. [subsequent actions]
+
+## 🎨 Visual Rendering: Your Renovated Space
+
+**🎨 Generate Visual Rendering:**
+
+Use **generate_renovation_rendering** tool to CREATE a photorealistic rendering:
+
+Build an EXTREMELY DETAILED prompt that incorporates:
+- **From Visual Assessor**: Room type, current condition analysis, desired style
+- **From Design Planner**: Exact colors (with codes/names), specific materials, layout details, lighting fixtures, flooring type, all key features
+
+**Prompt Structure:**
+"Professional interior photography of a renovated [room_type].
+
+Current Space Context: [If Visual Assessor analyzed photos, mention key layout features to preserve]
+
+Design Specifications:
+- Style: [exact style from design plan]
+- Colors: [specific color names with codes - e.g., 'Benjamin Moore Simply White OC-117 on walls']
+- Cabinets/Fixtures: [exact specifications - e.g., 'white shaker style cabinets with brushed nickel hardware']
+- Countertops: [material and color - e.g., 'Carrara marble-look quartz countertops']
+- Flooring: [type and color - e.g., 'light oak luxury vinyl plank flooring']
+- Backsplash: [pattern and material - e.g., 'white subway tile in classic running bond']
+- Lighting: [specific fixtures - e.g., 'recessed LED lights plus pendant lights over island']
+- Appliances: [if applicable - e.g., 'stainless steel appliances']
+- Key Features: [all important elements from design]
+
+Camera: Wide-angle interior photography, eye-level perspective
+Quality: Photorealistic, 8K, professional interior design magazine, natural lighting, bright and airy"
+
+Parameters:
+- prompt: [your ultra-detailed prompt above]
+- aspect_ratio: "16:9"
+- asset_name: "[room_type]_[style_keyword]_renovation" (e.g., "kitchen_modern_farmhouse_renovation")
+
+**After generating:**
+Briefly describe (2-3 sentences) key features visible in the rendering and how it addresses their needs.
+
+**Note**: Image editing from uploaded photos has limitations in ADK Web. We generate fresh renderings based on detailed descriptions from the analysis.
+""",
+ tools=[generate_renovation_rendering, edit_renovation_rendering, list_renovation_renderings],
+)
+
+
+# Create the planning pipeline (runs only when coordinator routes planning requests here)
+planning_pipeline = SequentialAgent(
+ name="PlanningPipeline",
+ description="Full renovation planning pipeline: Visual Assessment β†’ Design Planning β†’ Project Coordination",
+ sub_agents=[
+ visual_assessor,
+ design_planner,
+ project_coordinator,
+ ],
+)
+
+
+# ============================================================================
+# Coordinator/Dispatcher (Root Agent)
+# ============================================================================
+
+root_agent = LlmAgent(
+ name="HomeRenovationPlanner",
+ model="gemini-2.5-flash",
+ description="Intelligent coordinator that routes renovation requests to the appropriate specialist or planning pipeline. Supports image analysis!",
+ instruction="""
+You are the Coordinator for the AI Home Renovation Planner.
+
+YOUR ROLE: Analyze the user's request and route it to the right specialist using transfer_to_agent.
+
+ROUTING LOGIC:
+
+1. **For general questions/greetings**:
+ β†’ transfer_to_agent to "InfoAgent"
+ β†’ Examples: "hi", "what do you do?", "how much do renovations cost?"
+
+2. **For editing EXISTING renderings** (only if rendering was already generated):
+ β†’ transfer_to_agent to "RenderingEditor"
+ β†’ Examples: "make cabinets cream", "darker", "change color", "add lights"
+ β†’ User wants to MODIFY an existing rendering
+ β†’ Check: Was a rendering generated earlier?
+
+3. **For NEW renovation planning**:
+ β†’ transfer_to_agent to "PlanningPipeline"
+ β†’ Examples: "Plan my kitchen", "Here's my space [photos]", "Help renovate"
+ β†’ First-time planning or new project
+ β†’ ALWAYS route here if images uploaded!
+
+CRITICAL: You MUST use transfer_to_agent - don't answer directly!
+
+Decision flow:
+- Rendering exists + wants changes β†’ RenderingEditor
+- New project/images β†’ PlanningPipeline
+- Just chatting β†’ InfoAgent
+
+Be a smart router - match intent!
+""",
+ sub_agents=[
+ info_agent,
+ rendering_editor,
+ planning_pipeline,
+ ],
+)
+
+
+__all__ = ["root_agent"]
\ No newline at end of file
diff --git a/advanced_ai_agents/multi_agent_apps/ai_home_renovation_agent/tools.py b/advanced_ai_agents/multi_agent_apps/ai_home_renovation_agent/tools.py
new file mode 100644
index 00000000..ebb8f47b
--- /dev/null
+++ b/advanced_ai_agents/multi_agent_apps/ai_home_renovation_agent/tools.py
@@ -0,0 +1,466 @@
+import os
+import logging
+from google import genai
+from google.genai import types
+from google.adk.tools import ToolContext
+from pydantic import BaseModel, Field
+from dotenv import load_dotenv
+
+load_dotenv()
+
+# Configure logging
+logger = logging.getLogger(__name__)
+
+# ============================================================================
+# Helper Functions for Asset Version Management
+# ============================================================================
+
+def get_next_version_number(tool_context: ToolContext, asset_name: str) -> int:
+ """Get the next version number for a given asset name."""
+ asset_versions = tool_context.state.get("asset_versions", {})
+ current_version = asset_versions.get(asset_name, 0)
+ next_version = current_version + 1
+ return next_version
+
+
+def update_asset_version(tool_context: ToolContext, asset_name: str, version: int, filename: str) -> None:
+ """Update the version tracking for an asset."""
+ if "asset_versions" not in tool_context.state:
+ tool_context.state["asset_versions"] = {}
+ if "asset_filenames" not in tool_context.state:
+ tool_context.state["asset_filenames"] = {}
+
+ tool_context.state["asset_versions"][asset_name] = version
+ tool_context.state["asset_filenames"][asset_name] = filename
+
+ # Maintain a list of all versions for this asset
+ asset_history_key = f"{asset_name}_history"
+ if asset_history_key not in tool_context.state:
+ tool_context.state[asset_history_key] = []
+ tool_context.state[asset_history_key].append({"version": version, "filename": filename})
+
+
+def create_versioned_filename(asset_name: str, version: int, file_extension: str = "png") -> str:
+ """Create a versioned filename for an asset."""
+ return f"{asset_name}_v{version}.{file_extension}"
+
+
+def get_asset_versions_info(tool_context: ToolContext) -> str:
+ """Get information about all asset versions in the session."""
+ asset_versions = tool_context.state.get("asset_versions", {})
+ if not asset_versions:
+ return "No renovation renderings have been created yet."
+
+ info_lines = ["Current renovation renderings:"]
+ for asset_name, current_version in asset_versions.items():
+ history_key = f"{asset_name}_history"
+ history = tool_context.state.get(history_key, [])
+ total_versions = len(history)
+ latest_filename = tool_context.state.get("asset_filenames", {}).get(asset_name, "Unknown")
+ info_lines.append(f" β€’ {asset_name}: {total_versions} version(s), latest is v{current_version} ({latest_filename})")
+
+ return "\n".join(info_lines)
+
+
+def get_reference_images_info(tool_context: ToolContext) -> str:
+ """Get information about all reference images (current room/inspiration) uploaded in the session."""
+ reference_images = tool_context.state.get("reference_images", {})
+ if not reference_images:
+ return "No reference images have been uploaded yet."
+
+ info_lines = ["Available reference images (current room photos & inspiration):"]
+ for filename, info in reference_images.items():
+ version = info.get("version", "Unknown")
+ image_type = info.get("type", "reference")
+ info_lines.append(f" β€’ {filename} ({image_type} v{version})")
+
+ return "\n".join(info_lines)
+
+
+async def load_reference_image(tool_context: ToolContext, filename: str):
+ """Load a reference image artifact by filename."""
+ try:
+ loaded_part = await tool_context.load_artifact(filename)
+ if loaded_part:
+ logger.info(f"Successfully loaded reference image: {filename}")
+ return loaded_part
+ else:
+ logger.warning(f"Reference image not found: {filename}")
+ return None
+ except Exception as e:
+ logger.error(f"Error loading reference image {filename}: {e}")
+ return None
+
+
+def get_latest_reference_image_filename(tool_context: ToolContext) -> str:
+ """Get the filename of the most recently uploaded reference image."""
+ return tool_context.state.get("latest_reference_image")
+
+
+# ============================================================================
+# Pydantic Input Models
+# ============================================================================
+
+class GenerateRenovationRenderingInput(BaseModel):
+ prompt: str = Field(..., description="A detailed description of the renovated space to generate. Include room type, style, colors, materials, fixtures, lighting, and layout.")
+ aspect_ratio: str = Field(default="16:9", description="The desired aspect ratio, e.g., '1:1', '16:9', '9:16'. Default is 16:9 for room photos.")
+ asset_name: str = Field(default="renovation_rendering", description="Base name for the rendering (will be versioned automatically). Use descriptive names like 'kitchen_modern_farmhouse' or 'bathroom_spa'.")
+ current_room_photo: str = Field(default=None, description="Optional: filename of the current room photo to use as reference for layout/structure.")
+ inspiration_image: str = Field(default=None, description="Optional: filename of an inspiration image to guide the style. Use 'latest' for most recent upload.")
+
+
+class EditRenovationRenderingInput(BaseModel):
+ artifact_filename: str = Field(..., description="The filename of the rendering artifact to edit.")
+ prompt: str = Field(..., description="The prompt describing the desired changes (e.g., 'make cabinets darker', 'add pendant lights', 'change floor to hardwood').")
+ asset_name: str = Field(default=None, description="Optional: specify asset name for the new version (defaults to incrementing current asset).")
+ reference_image_filename: str = Field(default=None, description="Optional: filename of a reference image to guide the edit. Use 'latest' for most recent upload.")
+
+
+# ============================================================================
+# Image Generation Tool
+# ============================================================================
+
+async def generate_renovation_rendering(tool_context: ToolContext, inputs: GenerateRenovationRenderingInput) -> str:
+ """
+ Generates a photorealistic rendering of a renovated space based on the design plan.
+
+ This tool uses Gemini 2.5 Flash's image generation capabilities to create visual
+ representations of renovation plans. It can optionally use current room photos
+ and inspiration images as references.
+ """
+ if "GEMINI_API_KEY" not in os.environ and "GOOGLE_API_KEY" not in os.environ:
+ raise ValueError("GEMINI_API_KEY or GOOGLE_API_KEY environment variable not set.")
+
+ logger.info("Starting renovation rendering generation")
+ try:
+ client = genai.Client()
+ inputs = GenerateRenovationRenderingInput(**inputs)
+
+ # Handle reference images (current room photo or inspiration)
+ reference_images = []
+
+ if inputs.current_room_photo:
+ current_photo_part = await load_reference_image(tool_context, inputs.current_room_photo)
+ if current_photo_part:
+ reference_images.append(current_photo_part)
+ logger.info(f"Using current room photo: {inputs.current_room_photo}")
+
+ if inputs.inspiration_image:
+ if inputs.inspiration_image == "latest":
+ insp_filename = get_latest_reference_image_filename(tool_context)
+ else:
+ insp_filename = inputs.inspiration_image
+
+ if insp_filename:
+ inspiration_part = await load_reference_image(tool_context, insp_filename)
+ if inspiration_part:
+ reference_images.append(inspiration_part)
+ logger.info(f"Using inspiration image: {insp_filename}")
+
+ # Build the enhanced prompt
+ base_rewrite_prompt = f"""
+ Create a highly detailed, photorealistic prompt for generating an interior design image.
+
+ Original description: {inputs.prompt}
+
+ Enhance this to be a professional interior photography prompt that includes:
+ - Specific camera angle (wide-angle, eye-level perspective)
+ - Exact colors and materials mentioned
+ - Realistic lighting (natural light from windows, fixture types)
+ - Spatial layout and dimensions
+ - Texture and finish details
+ - Professional interior design photography quality
+
+ Aspect ratio: {inputs.aspect_ratio}
+ """
+
+ if reference_images:
+ base_rewrite_prompt += "\nUse the provided reference image(s) as inspiration for style, layout, or visual elements."
+
+ base_rewrite_prompt += "\n\n**Important:** Output your prompt as a single detailed paragraph optimized for photorealistic interior rendering."
+
+ # Get enhanced prompt
+ rewritten_prompt_response = client.models.generate_content(
+ model="gemini-2.5-flash",
+ contents=base_rewrite_prompt
+ )
+ rewritten_prompt = rewritten_prompt_response.text
+ logger.info(f"Enhanced prompt: {rewritten_prompt}")
+
+ model = "gemini-2.5-flash-image"
+
+ # Build content parts
+ content_parts = [types.Part.from_text(text=rewritten_prompt)]
+ content_parts.extend(reference_images)
+
+ contents = [
+ types.Content(
+ role="user",
+ parts=content_parts,
+ ),
+ ]
+
+ generate_content_config = types.GenerateContentConfig(
+ response_modalities=[
+ "IMAGE",
+ "TEXT",
+ ],
+ )
+
+ # Generate versioned filename
+ version = get_next_version_number(tool_context, inputs.asset_name)
+ artifact_filename = create_versioned_filename(inputs.asset_name, version)
+ logger.info(f"Generating rendering with artifact filename: {artifact_filename} (version {version})")
+
+ # Generate the image
+ for chunk in client.models.generate_content_stream(
+ model=model,
+ contents=contents,
+ config=generate_content_config,
+ ):
+ if (
+ chunk.candidates is None
+ or chunk.candidates[0].content is None
+ or chunk.candidates[0].content.parts is None
+ ):
+ continue
+
+ if chunk.candidates[0].content.parts[0].inline_data and chunk.candidates[0].content.parts[0].inline_data.data:
+ inline_data = chunk.candidates[0].content.parts[0].inline_data
+
+ # Create a Part object from the inline data
+ image_part = types.Part(inline_data=inline_data)
+
+ try:
+ # Save the image as an artifact
+ version = await tool_context.save_artifact(
+ filename=artifact_filename,
+ artifact=image_part
+ )
+
+ # Update version tracking
+ update_asset_version(tool_context, inputs.asset_name, version, artifact_filename)
+
+ # Store in session state
+ tool_context.state["last_generated_rendering"] = artifact_filename
+ tool_context.state["current_asset_name"] = inputs.asset_name
+
+ logger.info(f"Saved rendering as artifact '{artifact_filename}' (version {version})")
+
+ return f"βœ… Renovation rendering generated successfully!\n\nSaved as: **{artifact_filename}** (version {version} of {inputs.asset_name})\n\nThis photorealistic rendering shows your renovated space based on the design plan."
+
+ except Exception as e:
+ logger.error(f"Error saving artifact: {e}")
+ return f"Error saving rendering as artifact: {e}"
+ else:
+ # Log any text responses
+ if hasattr(chunk, 'text') and chunk.text:
+ logger.info(f"Model response: {chunk.text}")
+
+ return "No rendering was generated. Please try again with a more detailed prompt."
+
+ except Exception as e:
+ logger.error(f"Error in generate_renovation_rendering: {e}")
+ return f"An error occurred while generating the rendering: {e}"
+
+
+# ============================================================================
+# Image Editing Tool
+# ============================================================================
+
+async def edit_renovation_rendering(tool_context: ToolContext, inputs: EditRenovationRenderingInput) -> str:
+ """
+ Edits an existing renovation rendering based on feedback or refinements.
+
+ This tool allows iterative improvements to the rendered image, such as
+ changing colors, materials, lighting, or layout elements.
+ """
+ if "GEMINI_API_KEY" not in os.environ and "GOOGLE_API_KEY" not in os.environ:
+ raise ValueError("GEMINI_API_KEY or GOOGLE_API_KEY environment variable not set.")
+
+ logger.info("Starting renovation rendering edit")
+
+ try:
+ client = genai.Client()
+ inputs = EditRenovationRenderingInput(**inputs)
+
+ # Load the existing rendering
+ logger.info(f"Loading artifact: {inputs.artifact_filename}")
+ try:
+ loaded_image_part = await tool_context.load_artifact(inputs.artifact_filename)
+ if not loaded_image_part:
+ return f"❌ Could not find rendering artifact: {inputs.artifact_filename}"
+ except Exception as e:
+ logger.error(f"Error loading artifact: {e}")
+ return f"Error loading rendering artifact: {e}"
+
+ # Handle reference image if specified
+ reference_image_part = None
+ if inputs.reference_image_filename:
+ if inputs.reference_image_filename == "latest":
+ ref_filename = get_latest_reference_image_filename(tool_context)
+ else:
+ ref_filename = inputs.reference_image_filename
+
+ if ref_filename:
+ reference_image_part = await load_reference_image(tool_context, ref_filename)
+ if reference_image_part:
+ logger.info(f"Using reference image for editing: {ref_filename}")
+
+ model = "gemini-2.5-flash-image"
+
+ # Build content parts
+ content_parts = [loaded_image_part, types.Part.from_text(text=inputs.prompt)]
+ if reference_image_part:
+ content_parts.append(reference_image_part)
+
+ contents = [
+ types.Content(
+ role="user",
+ parts=content_parts,
+ ),
+ ]
+
+ generate_content_config = types.GenerateContentConfig(
+ response_modalities=[
+ "IMAGE",
+ "TEXT",
+ ],
+ )
+
+ # Determine asset name and generate versioned filename
+ if inputs.asset_name:
+ asset_name = inputs.asset_name
+ else:
+ current_asset_name = tool_context.state.get("current_asset_name")
+ if current_asset_name:
+ asset_name = current_asset_name
+ else:
+ # Extract from filename
+ base_name = inputs.artifact_filename.split('_v')[0] if '_v' in inputs.artifact_filename else "renovation_rendering"
+ asset_name = base_name
+
+ version = get_next_version_number(tool_context, asset_name)
+ edited_artifact_filename = create_versioned_filename(asset_name, version)
+ logger.info(f"Editing rendering with artifact filename: {edited_artifact_filename} (version {version})")
+
+ # Edit the image
+ for chunk in client.models.generate_content_stream(
+ model=model,
+ contents=contents,
+ config=generate_content_config,
+ ):
+ if (
+ chunk.candidates is None
+ or chunk.candidates[0].content is None
+ or chunk.candidates[0].content.parts is None
+ ):
+ continue
+
+ if chunk.candidates[0].content.parts[0].inline_data and chunk.candidates[0].content.parts[0].inline_data.data:
+ inline_data = chunk.candidates[0].content.parts[0].inline_data
+
+ # Create a Part object from the inline data
+ edited_image_part = types.Part(inline_data=inline_data)
+
+ try:
+ # Save the edited image as an artifact
+ version = await tool_context.save_artifact(
+ filename=edited_artifact_filename,
+ artifact=edited_image_part
+ )
+
+ # Update version tracking
+ update_asset_version(tool_context, asset_name, version, edited_artifact_filename)
+
+ # Store in session state
+ tool_context.state["last_generated_rendering"] = edited_artifact_filename
+ tool_context.state["current_asset_name"] = asset_name
+
+ logger.info(f"Saved edited rendering as artifact '{edited_artifact_filename}' (version {version})")
+
+ return f"βœ… Rendering edited successfully!\n\nSaved as: **{edited_artifact_filename}** (version {version} of {asset_name})\n\nThe rendering has been updated based on your feedback."
+
+ except Exception as e:
+ logger.error(f"Error saving edited artifact: {e}")
+ return f"Error saving edited rendering as artifact: {e}"
+ else:
+ # Log any text responses
+ if hasattr(chunk, 'text') and chunk.text:
+ logger.info(f"Model response: {chunk.text}")
+
+ return "No edited rendering was generated. Please try again."
+
+ except Exception as e:
+ logger.error(f"Error in edit_renovation_rendering: {e}")
+ return f"An error occurred while editing the rendering: {e}"
+
+
+# ============================================================================
+# Utility Tools
+# ============================================================================
+
+async def list_renovation_renderings(tool_context: ToolContext) -> str:
+ """Lists all renovation renderings created in this session."""
+ return get_asset_versions_info(tool_context)
+
+
+async def list_reference_images(tool_context: ToolContext) -> str:
+ """Lists all reference images (current room photos & inspiration) uploaded in this session."""
+ return get_reference_images_info(tool_context)
+
+
+async def save_uploaded_image_as_artifact(
+ tool_context: ToolContext,
+ image_data: str,
+ artifact_name: str,
+ image_type: str = "current_room"
+) -> str:
+ """
+ Saves an uploaded image as a named artifact for later use in editing.
+
+ This tool is used when the Visual Assessor detects an uploaded image
+ and wants to make it available for the Project Coordinator to edit.
+
+ Args:
+ tool_context: The tool context
+ image_data: Base64 encoded image data or image bytes
+ artifact_name: Name to save the artifact as (e.g., "current_room_1", "inspiration_1")
+ image_type: Type of image ("current_room" or "inspiration")
+
+ Returns:
+ Success message with the artifact filename
+ """
+ try:
+ # Create a Part from the image data
+ # Note: This assumes image_data is already in the right format
+ # In practice, we'll get this from the message content
+
+ # Save as artifact
+ await tool_context.save_artifact(
+ filename=artifact_name,
+ artifact=image_data
+ )
+
+ # Track in state
+ if "uploaded_images" not in tool_context.state:
+ tool_context.state["uploaded_images"] = {}
+
+ tool_context.state["uploaded_images"][artifact_name] = {
+ "type": image_type,
+ "filename": artifact_name
+ }
+
+ if image_type == "current_room":
+ tool_context.state["current_room_artifact"] = artifact_name
+ elif image_type == "inspiration":
+ tool_context.state["inspiration_artifact"] = artifact_name
+
+ logger.info(f"Saved uploaded image as artifact: {artifact_name}")
+
+ return f"βœ… Image saved as artifact: {artifact_name} (type: {image_type}). This can now be used for editing."
+
+ except Exception as e:
+ logger.error(f"Error saving uploaded image: {e}")
+ return f"❌ Error saving uploaded image: {e}"
+