Files
crewAI/docs/tools/serpapi-google-shopping-tool.mdx
Devin AI 09fd6058b0 Add comprehensive documentation for all tools
- Added documentation for file operation tools
- Added documentation for search tools
- Added documentation for web scraping tools
- Added documentation for specialized tools (RAG, code interpreter)
- Added documentation for API-based tools (SerpApi, Serply)

Link to Devin run: https://app.devin.ai/sessions/d2f72a2dfb214659aeb3e9f67ed961f7

Co-Authored-By: Joe Moura <joao@crewai.com>
2024-12-29 16:03:22 +00:00

226 lines
5.4 KiB
Plaintext

---
title: SerpApi Google Shopping Tool
description: A tool for searching Google Shopping using the SerpApi service
---
# SerpApi Google Shopping Tool
The SerpApi Google Shopping Tool enables searching Google Shopping results using the SerpApi service. It provides location-aware shopping search capabilities with comprehensive result filtering.
## Installation
```bash
pip install 'crewai[tools]'
pip install serpapi
```
## Prerequisites
You need a SerpApi API key to use this tool. You can get one from [SerpApi's website](https://serpapi.com/manage-api-key).
Set your API key as an environment variable:
```bash
export SERPAPI_API_KEY="your_api_key_here"
```
## Usage
Here's how to use the SerpApi Google Shopping Tool:
```python
from crewai import Agent
from crewai_tools import SerpApiGoogleShoppingTool
# Initialize the tool
shopping_tool = SerpApiGoogleShoppingTool()
# Create an agent with the tool
shopping_agent = Agent(
role='Shopping Researcher',
goal='Find the best shopping deals',
backstory='I help find and analyze shopping options',
tools=[shopping_tool]
)
# Use in a task
task = Task(
description="Find best deals for gaming laptops",
agent=shopping_agent,
context={
"search_query": "gaming laptop deals",
"location": "United States" # Optional
}
)
```
## Input Schema
```python
class SerpApiGoogleShoppingToolSchema(BaseModel):
search_query: str # The search query for Google Shopping
location: Optional[str] = None # Optional location for localized results
```
## Function Signatures
### Base Tool Initialization
```python
def __init__(self, **kwargs):
"""
Initialize the SerpApi tool with API credentials.
Raises:
ImportError: If serpapi package is not installed
ValueError: If SERPAPI_API_KEY environment variable is not set
"""
```
### Search Execution
```python
def _run(
self,
**kwargs: Any,
) -> dict:
"""
Execute the Google Shopping search.
Args:
search_query (str): The search query for Google Shopping
location (Optional[str]): Optional location for results
Returns:
dict: Filtered search results from Google Shopping
Raises:
HTTPError: If the API request fails
"""
```
## Best Practices
1. **API Key Management**:
- Store the API key securely in environment variables
- Never hardcode the API key in your code
- Verify API key validity before making requests
2. **Search Optimization**:
- Use specific, targeted search queries
- Include relevant product details in queries
- Leverage location parameter for regional pricing
3. **Error Handling**:
- Handle API rate limits gracefully
- Implement retry logic for failed requests
- Validate input parameters before making requests
## Example Integration
Here's a complete example showing how to integrate the SerpApi Google Shopping Tool with CrewAI:
```python
from crewai import Agent, Task, Crew
from crewai_tools import SerpApiGoogleShoppingTool
# Initialize the tool
shopping_tool = SerpApiGoogleShoppingTool()
# Create an agent with the tool
researcher = Agent(
role='Shopping Analyst',
goal='Find and analyze the best shopping deals',
backstory="""I am an expert at finding the best shopping deals
and analyzing product offerings across different regions.""",
tools=[shopping_tool]
)
# Create tasks
search_task = Task(
description="""
Research gaming laptops with the following criteria:
1. Price range: $800-$1500
2. Released in the last year
3. Compare prices across different retailers
Provide a comprehensive analysis of the findings.
""",
agent=researcher,
context={
"search_query": "gaming laptop RTX 4060 2023",
"location": "United States"
}
)
# Create and run the crew
crew = Crew(
agents=[researcher],
tasks=[search_task]
)
result = crew.kickoff()
```
## Error Handling
The tool handles various error scenarios:
1. **Missing API Key**:
```python
try:
tool = SerpApiGoogleShoppingTool()
except ValueError as e:
print("API key not found. Set SERPAPI_API_KEY environment variable.")
```
2. **API Request Errors**:
```python
try:
results = tool._run(
search_query="gaming laptop",
location="United States"
)
except HTTPError as e:
print(f"API request failed: {str(e)}")
```
3. **Invalid Parameters**:
```python
try:
results = tool._run(
search_query="", # Empty query
location="Invalid Location"
)
except ValueError as e:
print("Invalid search parameters provided.")
```
## Response Format
The tool returns a filtered dictionary containing Google Shopping results. Example response structure:
```python
{
"shopping_results": [
{
"title": "Product Title",
"price": "$999.99",
"link": "https://...",
"source": "Retailer Name",
"rating": 4.5,
"reviews": 123,
"thumbnail": "https://..."
}
# Additional results...
],
"organic_results": [
{
"title": "Related Product",
"link": "https://...",
"snippet": "Product description..."
}
# Additional organic results...
]
}
```
The response is automatically filtered to remove metadata and unnecessary fields, focusing on the most relevant shopping information.