• unwind ai
  • Posts
  • Build an AI Consultant Agent with Gemini 2.5 Flash

Build an AI Consultant Agent with Gemini 2.5 Flash

Fully functional agentic app in under 100 lines of code (100% opensource)

Business consulting has always required deep market knowledge, strategic thinking, and the ability to synthesize complex information into actionable recommendations. Today's fast-paced business environment demands even more - real-time insights, data-driven strategies, and rapid response to market changes.

In this tutorial, we'll create a powerful AI business consultant using Google's Agent Development Kit (ADK) combined with Perplexity AI for real-time web research. This consultant will conduct market analysis, assess risks, and generate strategic recommendations backed by current data, all through a clean, interactive web interface.

What is Google ADK? Google's Agent Development Kit is a powerful framework designed for building production-ready AI agents. It provides tools for session management, evaluation capabilities, and seamless integration with Google's AI models.

Don’t forget to share this tutorial on your social channels and tag Unwind AI (X, LinkedIn, Threads, Facebook) to support us!

What We’re Building

A powerful business consultant Agent built with Google's Agent Development Kit that provides comprehensive market analysis, strategic planning, and actionable business recommendations.

Features

  1. Real-time Web Research: Uses Perplexity AI search for current market data, trends, and competitor intelligence

  2. Market Analysis: Leverages web search and AI insights to analyze market conditions and opportunities

  3. Strategic Recommendations: Generates actionable business strategies with timelines and implementation plans

  4. Risk Assessment: Identifies potential risks and provides mitigation strategies

  5. Interactive UI: Clean Google ADK web interface for easy consultation

  6. Evaluation System: Built-in evaluation and debugging capabilities with session tracking

How The App Works

  1. Input: Users submit business questions through the Google ADK web interface

  2. Research: The agent conducts real-time web research using Perplexity AI to gather current market data, competitor information, and industry trends

  3. Analysis: Market analysis tools process the research data to generate structured insights with confidence scores

  4. Strategy: Strategic recommendation tools create actionable business advice with timelines and implementation plans

  5. Synthesis: The agent combines web research findings with analysis results into a comprehensive consultation report

  6. Output: Users receive professional consultation with citations, action items, and measurable success metrics

Prerequisites

Before we begin, make sure you have the following:

  1. Python installed on your machine (version 3.10 or higher is recommended)

  2. Your Google Gemini and Perplexity API key

  3. A code editor of your choice (we recommend VS Code or PyCharm for their excellent Python support)

  4. Basic familiarity with Python programming

Code Walkthrough

Setting Up the Environment

First, let's get our development environment ready:

  1. Clone the GitHub repository:

git clone https://github.com/Shubhamsaboo/awesome-llm-apps.git
  1. Go to the ai_consultant_agent folder:

cd advanced_ai_agents/single_agent_apps/ai_consultant_agent
pip install -r requirements.txt
  1. Set up your Google API key:

export GOOGLE_API_KEY=your-google-api-key
export PERPLEXITY_API_KEY=your-perplexity-api-key

Note on File Structure: This tutorial follows a specific structure required by Google ADK. The main implementation is in ai_consultant_agent.py, while agent.py and __init__.py files are required for ADK's web interface discovery system.

Creating the Streamlit App

Let’s create our app. Create a new file ai_consultant_agent.py and add the following code:

  1. Import necessary libraries and set up configuration:

import logging
from typing import Dict, Any, List, Union
from dataclasses import dataclass
import base64
import requests
import os

# Google ADK imports
from google.adk.agents import LlmAgent
from google.adk.tools import google_search
from google.adk.sessions import InMemorySessionService
from google.adk.runners import Runner

# Define constants for the agent configuration
MODEL_ID = "gemini-2.5-flash"
APP_NAME = "ai_consultant_agent"
  1. Create data sanitization utilities:

def sanitize_bytes_for_json(obj: Any) -> Any:
    """Recursively convert bytes objects to strings to ensure JSON serializability."""
    if isinstance(obj, bytes):
        try:
            return obj.decode('utf-8')
        except UnicodeDecodeError:
            return base64.b64encode(obj).decode('ascii')
    elif isinstance(obj, dict):
        return {key: sanitize_bytes_for_json(value) for key, value in obj.items()}
    # Handle other data types...
  1. Market analysis tool:

@dataclass
class MarketInsight:
    """Structure for market research insights"""
    category: str
    finding: str
    confidence: float
    source: str

def analyze_market_data(research_query: str, industry: str = "") -> Dict[str, Any]:
    """Analyze market data and generate insights"""
    insights = []
    
    if "startup" in research_query.lower():
        insights.extend([
            MarketInsight("Market Opportunity", "Growing market with moderate competition", 0.8, "Market Research"),
            MarketInsight("Risk Assessment", "Standard startup risks apply", 0.7, "Analysis")
        ])
    
    return {
        "query": research_query,
        "insights": [{"category": i.category, "finding": i.finding} for i in insights],
        "total_insights": len(insights)
    }
  1. Create strategic recommendations engine:

def generate_strategic_recommendations(analysis_data: Dict[str, Any]) -> List[Dict[str, Any]]:
    """Generate strategic business recommendations based on analysis"""
    recommendations = []
    
    recommendations.append({
        "category": "Market Entry Strategy",
        "priority": "High",
        "recommendation": "Implement phased market entry with MVP testing",
        "timeline": "3-6 months",
        "action_items": [
            "Develop minimum viable product",
            "Identify target customer segment",
            "Conduct market validation tests"
        ]
    })
    
    return recommendations
  1. Perplexity web search integration:

def perplexity_search(query: str, system_prompt: str = "Be precise and concise.") -> Dict[str, Any]:
    """Search the web using Perplexity AI for real-time information."""
    try:
        api_key = os.getenv("PERPLEXITY_API_KEY")
        if not api_key:
            return {"error": "Perplexity API key not found", "status": "error"}
        
        response = requests.post("https://api.perplexity.ai/chat/completions",
            json={"model": "sonar", "messages": [
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": query}
            ]},
            headers={"Authorization": f"Bearer {api_key}"},
            timeout=30)
        
        result = response.json()
        return {
            "content": result["choices"][0]["message"]["content"],
            "citations": result.get("citations", []),
            "status": "success"
        }
    except Exception as e:
        return {"error": f"Search failed: {str(e)}", "status": "error"}
  1. Define agent instructions:

INSTRUCTIONS = """You are a senior AI business consultant specializing in market analysis and strategic planning.

Your expertise includes:
- Business strategy development and recommendations
- Risk assessment and mitigation planning
- Market analysis using your knowledge and available tools
- Real-time web research using Perplexity AI search capabilities

When consulting with clients:
1. Use Perplexity search to gather current market data and trends
2. Use market analysis tools to process business queries
3. Provide clear, specific recommendations with implementation timelines
4. Focus on practical solutions that drive measurable outcomes
"""
  1. Initialize the agent and runner:

root_agent = LlmAgent(
    model=MODEL_ID,
    name=APP_NAME,
    description="An AI business consultant that provides market research, strategic analysis, and actionable recommendations.",
    instruction=INSTRUCTIONS,
    tools=consultant_tools,
    output_key="consultation_response"
)

session_service = InMemorySessionService()
runner = Runner(
    agent=root_agent,
    app_name=APP_NAME,
    session_service=session_service
)

Running the App

With our code in place, it's time to launch the app.

  1. In your terminal, start the Google ADK web interface:

adk web
  1. Open your browser and navigate to the provided URL (typically http://localhost:8000)

  2. Select "AI Business Consultant" from the available agents

  3. Start your consultation by entering business questions such as:

    • "I want to launch a SaaS startup for small businesses"

    • "Should I expand my retail business to e-commerce?"

    • "What are the market opportunities in healthcare technology?"

  4. Use the Eval tab to save successful consultations and track performance metrics

Important Note: The file structure includes three files: ai_consultant_agent.py (main implementation), agent.py (ADK discovery), and __init__.py (module initialization), which are required for Google ADK's web interface to properly discover and load the agent.

Working Application Demo

Conclusion

You've successfully built an AI business consultant that combines Google's cutting-edge Gemini 2.5 Flash model with real-time market research capabilities.

This setup can now be expanded further:

  1. Industry Specialization: Create specialized versions for specific industries like fintech, healthcare, or e-commerce with tailored analysis frameworks.

  2. Integration Capabilities: Connect with business intelligence tools, CRM systems, or financial databases for enhanced data analysis.

  3. Advanced Evaluation Metrics: Implement custom evaluation criteria to measure recommendation quality and track consultation success rates.

  4. Collaboration Features: Add capabilities for team consultations and collaborative strategic planning sessions.

Keep experimenting with different configurations and features to build more sophisticated AI applications.

We share hands-on tutorials like this 2-3 times a week, to help you stay ahead in the world of AI. If you're serious about leveling up your AI skills and staying ahead of the curve, subscribe now and be the first to access our latest tutorials.

Don’t forget to share this tutorial on your social channels and tag Unwind AI (X, LinkedIn, Threads) to support us!

Reply

or to participate.