Merge pull request #273 from Madhuvod/gemini/webui

feat: use of sonar for search in ai consultant agent
This commit is contained in:
Shubham Saboo 2025-07-08 01:18:58 -05:00 committed by GitHub
commit b3c7ff5d28
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 57 additions and 25 deletions

View file

@ -1,10 +1,13 @@
# 🤝 AI Consultant Agent with Google ADK # 🤝 AI Consultant Agent with Google ADK
A powerful business consultant Agent built with Google's Agent Development Kit that provides comprehensive market analysis, strategic planning, and actionable business recommendations.
A powerful business consultant powered by Google's Agent Development Kit that provides comprehensive market analysis, strategic planning, and actionable business recommendations with real-time web research.
## Features ## Features
- **Market Analysis**: Leverages Google search and AI insights to analyze market conditions and opportunities - **Real-time Web Research**: Uses Perplexity AI search for current market data, trends, and competitor intelligence
- **Market Analysis**: Leverages web search and AI insights to analyze market conditions and opportunities
- **Strategic Recommendations**: Generates actionable business strategies with timelines and implementation plans - **Strategic Recommendations**: Generates actionable business strategies with timelines and implementation plans
- **Risk Assessment**: Identifies potential risks and provides mitigation strategies - **Risk Assessment**: Identifies potential risks and provides mitigation strategies
- **Interactive UI**: Clean Google ADK web interface for easy consultation - **Interactive UI**: Clean Google ADK web interface for easy consultation
@ -13,15 +16,17 @@ A powerful business consultant Agent built with Google's Agent Development Kit t
## How It Works ## How It Works
1. **Input Phase**: User provides business questions or consultation requests through the ADK web interface 1. **Input Phase**: User provides business questions or consultation requests through the ADK web interface
2. **Analysis Phase**: The agent uses market analysis tools to process the query and generate insights 2. **Research Phase**: The agent conducts real-time web research using Perplexity AI to gather current market data
3. **Strategy Phase**: Strategic recommendations are generated based on the analysis 3. **Analysis Phase**: The agent uses market analysis tools to process the query and generate insights
4. **Synthesis Phase**: The agent combines findings into a comprehensive consultation report 4. **Strategy Phase**: Strategic recommendations are generated based on the analysis and web research
5. **Output Phase**: Actionable recommendations with timelines and implementation steps are presented 5. **Synthesis Phase**: The agent combines findings into a comprehensive consultation report with citations
6. **Output Phase**: Actionable recommendations with timelines and implementation steps are presented
## Requirements ## Requirements
- Python 3.8+ - Python 3.8+
- Google API key (for Gemini model) - Google API key (for Gemini model)
- Perplexity API key (for real-time web search)
- Required Python packages (see `requirements.txt`) - Required Python packages (see `requirements.txt`)
## Installation ## Installation
@ -39,9 +44,10 @@ A powerful business consultant Agent built with Google's Agent Development Kit t
## Usage ## Usage
1. Set your Google API key: 1. Set your API keys:
```bash ```bash
export GOOGLE_API_KEY=your-api-key export GOOGLE_API_KEY=your-google-api-key
export PERPLEXITY_API_KEY=your-perplexity-api-key
``` ```
2. Start the Google ADK web interface: 2. Start the Google ADK web interface:
@ -55,7 +61,7 @@ A powerful business consultant Agent built with Google's Agent Development Kit t
5. Enter your business questions or consultation requests 5. Enter your business questions or consultation requests
6. Review the comprehensive analysis and strategic recommendations 6. Review the comprehensive analysis and strategic recommendations with real-time web data and citations
7. Use the Eval tab to save and evaluate consultation sessions 7. Use the Eval tab to save and evaluate consultation sessions
@ -71,11 +77,13 @@ A powerful business consultant Agent built with Google's Agent Development Kit t
The application uses specialized analysis tools: The application uses specialized analysis tools:
1. **Market Analysis Tool**: Processes business queries and generates market insights, competitive analysis, and opportunity identification. 1. **Perplexity Search Tool**: Conducts real-time web research using Perplexity AI's "sonar" model to gather current market data, competitor information, and industry trends with citations.
2. **Strategic Recommendations Tool**: Creates actionable business strategies with priority levels, timelines, and implementation roadmaps. 2. **Market Analysis Tool**: Processes business queries and generates market insights, competitive analysis, and opportunity identification.
The agent is built on Google ADK's LlmAgent framework using the Gemini 2.0 Flash model, providing fast and accurate business consultation capabilities. 3. **Strategic Recommendations Tool**: Creates actionable business strategies with priority levels, timelines, and implementation roadmaps.
The agent is built on Google ADK's LlmAgent framework using the Gemini 2.5 Flash model, providing fast and accurate business consultation capabilities backed by real-time web research.
## Evaluation and Testing ## Evaluation and Testing

View file

@ -2,10 +2,12 @@ import logging
from typing import Dict, Any, List, Union from typing import Dict, Any, List, Union
from dataclasses import dataclass from dataclasses import dataclass
import base64 import base64
import requests
import os
# Google ADK imports # Google ADK imports
from google.adk.agents import LlmAgent from google.adk.agents import LlmAgent
from google.adk.tools import google_search_tool from google.adk.tools import google_search
from google.adk.sessions import InMemorySessionService from google.adk.sessions import InMemorySessionService
from google.adk.runners import Runner from google.adk.runners import Runner
@ -188,11 +190,32 @@ def generate_strategic_recommendations(analysis_data: Dict[str, Any]) -> List[Di
return recommendations return recommendations
def perplexity_search(query: str, system_prompt: str = "Be precise and concise. Focus on business insights and market data.") -> Dict[str, Any]:
"""Search the web using Perplexity AI for real-time information and insights."""
try:
api_key = os.getenv("PERPLEXITY_API_KEY")
if not api_key:
return {"error": "Perplexity API key not found. Please set PERPLEXITY_API_KEY environment variable.", "query": query, "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}", "Content-Type": "application/json"}, timeout=30)
response.raise_for_status()
result = response.json()
if "choices" in result and result["choices"]:
return {"query": query, "content": result["choices"][0]["message"]["content"], "citations": result.get("citations", []),
"search_results": result.get("search_results", []), "status": "success", "source": "Perplexity AI",
"model": result.get("model", "sonar"), "usage": result.get("usage", {}), "response_id": result.get("id", ""), "created": result.get("created", 0)}
return {"error": "No response content found", "query": query, "status": "error", "raw_response": result}
except Exception as e:
return {"error": f"Error: {str(e)}", "query": query, "status": "error"}
# Define the consultant tools with safety wrappers # Define the consultant tools with safety wrappers
consultant_tools = [ consultant_tools = [
google_search_tool,
safe_tool_wrapper(analyze_market_data), safe_tool_wrapper(analyze_market_data),
safe_tool_wrapper(generate_strategic_recommendations) safe_tool_wrapper(generate_strategic_recommendations),
safe_tool_wrapper(perplexity_search)
] ]
INSTRUCTIONS = """You are a senior AI business consultant specializing in market analysis and strategic planning. INSTRUCTIONS = """You are a senior AI business consultant specializing in market analysis and strategic planning.
@ -202,40 +225,41 @@ Your expertise includes:
- Risk assessment and mitigation planning - Risk assessment and mitigation planning
- Implementation planning with timelines - Implementation planning with timelines
- Market analysis using your knowledge and available tools - Market analysis using your knowledge and available tools
- Real-time market research using Google search capabilities - Real-time web research using Perplexity AI search capabilities
When consulting with clients: When consulting with clients:
1. Use Google search to gather current market data, competitor information, and industry trends 1. Use Perplexity search to gather current market data, competitor information, and industry trends from the web
2. Use the market analysis tool to process business queries and generate insights 2. Use the market analysis tool to process business queries and generate insights
3. Use the strategic recommendations tool to create actionable business advice 3. Use the strategic recommendations tool to create actionable business advice
4. Provide clear, specific recommendations with implementation timelines 4. Provide clear, specific recommendations with implementation timelines
5. Focus on practical solutions that drive measurable business outcomes 5. Focus on practical solutions that drive measurable business outcomes
**Core Responsibilities:** **Core Responsibilities:**
- Conduct real-time market research using Google search for current data - Conduct real-time web research using Perplexity AI for current market data and trends
- Analyze competitive landscapes and market opportunities using search results and your knowledge - Analyze competitive landscapes and market opportunities using search results and your knowledge
- Provide strategic guidance with clear action items based on up-to-date information - Provide strategic guidance with clear action items based on up-to-date information
- Assess risks and suggest mitigation strategies using current market conditions - Assess risks and suggest mitigation strategies using current market conditions
- Create implementation roadmaps with realistic timelines - Create implementation roadmaps with realistic timelines
- Generate comprehensive business insights combining search data with analysis tools - Generate comprehensive business insights combining web research with analysis tools
**Critical Rules:** **Critical Rules:**
- Always search for current market data, trends, and competitor information when relevant - Always search for current market data, trends, and competitor information when relevant using Perplexity search
- Base recommendations on sound business principles, current market insights, and real-time data - Base recommendations on sound business principles, current market insights, and real-time web data
- Provide specific, actionable advice rather than generic guidance - Provide specific, actionable advice rather than generic guidance
- Include timelines and success metrics in recommendations - Include timelines and success metrics in recommendations
- Prioritize recommendations by business impact and feasibility - Prioritize recommendations by business impact and feasibility
- Use Google search to validate assumptions and gather supporting evidence - Use Perplexity search to validate assumptions and gather supporting evidence with citations
- Combine search results with your analysis tools for comprehensive consultation - Combine search results with your analysis tools for comprehensive consultation
**Search Strategy:** **Search Strategy:**
- Search for competitor analysis, market size, industry trends, and regulatory changes - Use Perplexity search for competitor analysis, market size, industry trends, and regulatory changes
- Look up recent news, funding rounds, and market developments in relevant sectors - Look up recent news, funding rounds, and market developments in relevant sectors
- Verify market assumptions with current data before making recommendations - Verify market assumptions with current web data before making recommendations
- Research best practices and case studies from similar businesses - Research best practices and case studies from similar businesses
- Always include citations and sources when referencing search results
Always maintain a professional, analytical approach while being results-oriented. Always maintain a professional, analytical approach while being results-oriented.
Use all available tools including Google search to provide comprehensive, well-researched consultation backed by current market data.""" Use all available tools including Perplexity search to provide comprehensive, well-researched consultation backed by current web data and citations."""
# Define the agent instance # Define the agent instance
root_agent = LlmAgent( root_agent = LlmAgent(