Skip to content

Python: Support Bing Custom Search #6278

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
May 31, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,16 @@ class BingConnector(ConnectorBase):

_api_key: str

def __init__(self, api_key: str | None = None, env_file_path: str | None = None) -> None:
def __init__(
self, api_key: str | None = None, custom_config: str | None = None, env_file_path: str | None = None
) -> None:
"""Initializes a new instance of the BingConnector class.

Arguments:
api_key {str | None}: The Bing Search API key. If provided, will override
the value in the env vars or .env file.
custom_config {str | None}: The Bing Custom Search instance's unique identifier.
If provided, will override the value in the env vars or .env file.
env_file_path {str | None}: The optional path to the .env file. If provided,
the settings are read from this file path location.
"""
Expand All @@ -39,6 +43,9 @@ def __init__(self, api_key: str | None = None, env_file_path: str | None = None)
bing_settings.api_key.get_secret_value() if bing_settings and bing_settings.api_key else None
)
assert self._api_key, "API key cannot be 'None' or empty."
self._custom_config = custom_config or (
bing_settings.custom_config if bing_settings and bing_settings.custom_config else None
)

async def search(self, query: str, num_results: int = 1, offset: int = 0) -> list[str]:
"""
Expand Down Expand Up @@ -66,8 +73,14 @@ async def search(self, query: str, num_results: int = 1, offset: int = 0) -> lis
params:\nquery: {query}\nnum_results: {num_results}\noffset: {offset}"
)

_base_url = "https://api.bing.microsoft.com/v7.0/search"
_request_url = f"{_base_url}?q={urllib.parse.quote_plus(query)}&count={num_results}&offset={offset}"
_base_url = (
"https://api.bing.microsoft.com/v7.0/custom/search"
if self._custom_config
else "https://api.bing.microsoft.com/v7.0/search"
)
_request_url = f"{_base_url}?q={urllib.parse.quote_plus(query)}&count={num_results}&offset={offset}" + (
f"&customConfig={self._custom_config}" if self._custom_config else ""
)

logger.info(f"Sending GET request to {_request_url}")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@ class BingSettings(BaseSettings):

Optional settings for prefix 'BING_' are:
- api_key: SecretStr - The Bing API key (Env var BING_API_KEY)
- custom_config: str - The Bing Custom Search instance's unique identifier (Env var BING_CUSTOM_CONFIG)

"""

env_file_path: str | None = None
api_key: SecretStr | None = None
custom_config: str | None = None

class Config:
env_prefix = "BING_"
Expand Down
Loading