Implementation:Microsoft Autogen Studio Bing Search Tool
| Sources | python/packages/autogen-studio/autogenstudio/gallery/tools/bing_search.py |
|---|---|
| Domains | Tools, Search, Web Scraping, API Integration, AutoGen Studio |
| Last Updated | 2026-02-11 |
Overview
Description
The Bing Search Tool is a comprehensive search utility within AutoGen Studio that enables agents to perform web searches using Microsoft's Bing Web Search API. The tool supports multiple search types including web pages, news articles, images, and videos, with optional webpage content fetching and conversion to markdown format.
This implementation provides a robust, async-capable search interface with extensive error handling, parameter validation, and flexible output formatting. It integrates seamlessly with the autogen-core framework using the FunctionTool wrapper.
Key Features
- Multi-format search support: webpages, news, images, and videos
- Content fetching: Retrieves and converts full webpage content to markdown
- Configurable filtering: Language, country, and safe search options
- Error handling: Comprehensive validation and informative error messages
- Rate limiting awareness: Handles API quota and authentication errors
- HTML to Markdown conversion: Uses html2text for readable content extraction
Usage
The tool is designed to be used by AutoGen agents through the FunctionTool interface. It requires the BING_SEARCH_KEY environment variable to be set with a valid Azure Bing Search API key.
Environment Setup:
export BING_SEARCH_KEY="your_azure_bing_api_key"
Basic Usage:
results = await bing_search(
query="artificial intelligence",
num_results=5,
include_content=True
)
Code Reference
Source Location
- File:
python/packages/autogen-studio/autogenstudio/gallery/tools/bing_search.py - Repository: https://github.com/microsoft/autogen
- Lines: 218 total
Function Signature
async def bing_search(
query: str,
num_results: int = 3,
include_snippets: bool = True,
include_content: bool = True,
content_max_length: Optional[int] = 10000,
language: str = "en",
country: Optional[str] = None,
safe_search: str = "moderate",
response_filter: str = "webpages",
) -> List[Dict[str, str]]
Import Statement
from autogenstudio.gallery.tools.bing_search import bing_search, bing_search_tool
Dependencies
- Standard Library: json, os, typing
- Third-party: httpx, html2text, beautifulsoup4
- AutoGen: autogen_core.code_executor, autogen_core.tools
I/O Contract
Inputs
| Parameter | Type | Default | Description |
|---|---|---|---|
| query | str | (required) | Search query string |
| num_results | int | 3 | Number of results to return (max 50) |
| include_snippets | bool | True | Include result snippets/descriptions in output |
| include_content | bool | True | Fetch and include full webpage content in markdown format |
| content_max_length | Optional[int] | 10000 | Maximum length of webpage content (None for unlimited) |
| language | str | "en" | Language code for search results (e.g., 'en', 'es', 'fr') |
| country | Optional[str] | None | Market code for search results (e.g., 'us', 'uk') |
| safe_search | str | "moderate" | SafeSearch setting: 'off', 'moderate', or 'strict' |
| response_filter | str | "webpages" | Type of results: 'webpages', 'news', 'images', or 'videos' |
Outputs
| Field | Type | Description |
|---|---|---|
| return | List[Dict[str, str]] | List of search results with varying fields based on response_filter |
Result Dictionary Structure (webpages):
| Field | Type | Conditional | Description |
|---|---|---|---|
| title | str | Always | Result title/name |
| link | str | Always | URL of the result |
| snippet | str | If include_snippets=True | Brief description/snippet |
| content | str | If include_content=True | Full webpage content in markdown format |
Result Dictionary Structure (news):
| Field | Type | Conditional | Description |
|---|---|---|---|
| title | str | Always | News article title |
| link | str | Always | URL of the article |
| snippet | str | If include_snippets=True | Article description |
| date | str | Always | Publication date |
| content | str | If include_content=True | Full article content in markdown |
Result Dictionary Structure (images/videos):
| Field | Type | Conditional | Description |
|---|---|---|---|
| title | str | Always | Image/video title |
| link | str | Always | Content URL |
| thumbnail | str | Always | Thumbnail image URL |
| snippet | str | If include_snippets=True | Description |
| duration | str | Videos only | Video duration |
Exceptions
| Exception | Condition |
|---|---|
| ValueError | BING_SEARCH_KEY environment variable not set |
| ValueError | Invalid safe_search parameter (must be 'off', 'moderate', or 'strict') |
| ValueError | Invalid response_filter parameter (must be 'webpages', 'news', 'images', or 'videos') |
| ValueError | Authentication failed (401 status code) |
| ValueError | Access forbidden - invalid key or quota exceeded (403 status code) |
| ValueError | API quota exceeded (429 status code) |
| ValueError | Failed to parse API response |
| ValueError | Unexpected error during search operation |
Implementation Details
Core Algorithm
- Validation Phase:
- Retrieve and validate BING_SEARCH_KEY from environment
- Validate safe_search parameter against allowed values
- Validate response_filter parameter against allowed types
- API Request Phase:
- Construct request headers with API key
- Build query parameters with search options
- Make async HTTP GET request to Bing Web Search API endpoint
- Handle common HTTP error codes (401, 403, 429)
- Response Processing Phase:
- Parse JSON response
- Extract results based on response_filter type
- For each result, extract relevant fields (title, link, snippet, etc.)
- Content Fetching Phase (if include_content=True):
- For each result URL, make async HTTP request
- Parse HTML with BeautifulSoup
- Remove script and style elements
- Convert relative URLs to absolute
- Transform HTML to markdown using html2text
- Apply max_length truncation if specified
- Return Phase:
- Return list of result dictionaries (up to num_results)
Helper Functions
fetch_page_content(url, max_length): Async helper that retrieves webpage content and converts it to markdown format. Includes error handling for network failures and content processing errors.
Configuration Options
- API Endpoint:
https://api.bing.microsoft.com/v7.0/search - Request Timeout: 10 seconds
- Default User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
- HTML Parser: html.parser (via BeautifulSoup)
- Text Format: raw (no HTML formatting in snippets)
Usage Examples
Example 1: Basic Web Search
# Simple web search with default parameters
results = await bing_search(
query="Python programming tutorials"
)
# Results include title, link, snippet, and full content (truncated at 10000 chars)
for result in results:
print(f"Title: {result['title']}")
print(f"URL: {result['link']}")
print(f"Snippet: {result['snippet']}")
print(f"Content: {result['content'][:200]}...")
Example 2: News Search
# Search for recent news articles
news_results = await bing_search(
query="climate change",
num_results=5,
response_filter="news",
include_content=False, # Skip full content for faster results
safe_search="strict"
)
for article in news_results:
print(f"{article['date']}: {article['title']}")
print(f" {article['link']}")
print(f" {article['snippet']}")
Example 3: Image Search
# Search for images
image_results = await bing_search(
query="sunset photography",
num_results=10,
response_filter="images",
include_snippets=True
)
for img in image_results:
print(f"Title: {img['title']}")
print(f"Full Image: {img['link']}")
print(f"Thumbnail: {img['thumbnail']}")
Example 4: Localized Search with Content
# Localized search with full content extraction
results = await bing_search(
query="recetas de paella",
num_results=3,
language="es",
country="es",
include_content=True,
content_max_length=5000, # Limit content length
safe_search="moderate"
)
for result in results:
print(f"Title: {result['title']}")
print(f"Content length: {len(result['content'])} chars")
Example 5: Using the FunctionTool
from autogenstudio.gallery.tools.bing_search import bing_search_tool # The tool can be added to an agent's toolset # Tool automatically handles async execution and parameter validation agent = SomeAgent(tools=[bing_search_tool]) # Agent can now invoke: "Search Bing for information about quantum computing"
Error Handling
Common Error Scenarios
Missing API Key:
# Raises: ValueError: BING_SEARCH_KEY environment variable is not set
Invalid Parameters:
# Raises: ValueError: Invalid safe_search value await bing_search(query="test", safe_search="invalid") # Raises: ValueError: Invalid response_filter value await bing_search(query="test", response_filter="invalid")
API Authentication Errors:
# 401: ValueError: Authentication failed. Please verify your Bing Search API key # 403: ValueError: Access forbidden (invalid key, expired, or quota exceeded) # 429: ValueError: API quota exceeded. Please try again later
Content Fetching Errors:
# If webpage content cannot be fetched, the content field contains: # "Error fetching content: [error message]"
Related Pages
- Implementation: Studio Google Search Tool - Alternative search implementation using Google Custom Search API
- Implementation: Studio Fetch Webpage Tool - Standalone webpage fetching and markdown conversion
- Microsoft Autogen Studio Tools - Overview of all AutoGen Studio gallery tools
- AutoGen Core Function Tools - Documentation on FunctionTool framework
- Web Search Integration Patterns - Best practices for search tool integration