mirror of
https://github.com/langbot-app/LangBot.git
synced 2026-10-30 20:35:22 +08:00
51 lines
1.8 KiB
Python
51 lines
1.8 KiB
Python
# Auto generated by LangBot Plugin SDK.
|
|
# Please refer to https://langbot.app/docs/en/plugin/dev/tutor.html for more details.
|
|
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
import httpx
|
|
|
|
from langbot_plugin.api.definition.components.tool.tool import Tool
|
|
|
|
SERP_API_URL = "https://serpapi.com/search"
|
|
REQUEST_TIMEOUT = 5.0
|
|
|
|
|
|
class Google(Tool):
|
|
|
|
def _parse_response(self, response: dict) -> dict:
|
|
result = {}
|
|
if "knowledge_graph" in response:
|
|
result["title"] = response["knowledge_graph"].get("title", "")
|
|
result["description"] = response["knowledge_graph"].get("description", "")
|
|
if "organic_results" in response:
|
|
result["organic_results"] = [
|
|
{
|
|
"title": item.get("title", ""),
|
|
"link": item.get("link", ""),
|
|
"snippet": item.get("snippet", ""),
|
|
}
|
|
for item in response["organic_results"]
|
|
]
|
|
return result
|
|
|
|
async def call(self, params: dict[str, Any]) -> dict[str, Any]:
|
|
# Read the installation config for THIS invocation; never cache it on self.
|
|
config = self.get_plugin_config()
|
|
request_params = {
|
|
"api_key": config["api_key"],
|
|
"q": params["query"],
|
|
"engine": "google",
|
|
"google_domain": "google.com",
|
|
"gl": "us",
|
|
"hl": "en",
|
|
}
|
|
|
|
# One async client per invocation: never block the shared event loop.
|
|
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
|
|
response = await client.get(url=SERP_API_URL, params=request_params)
|
|
response.raise_for_status()
|
|
valuable_res = self._parse_response(response.json())
|
|
|
|
return valuable_res
|