Skip to content

Commit

Permalink
add: [tools] google_search
Browse files Browse the repository at this point in the history
  • Loading branch information
luochen1990 committed Aug 6, 2024
1 parent 38fd2d5 commit 423e557
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/ai_powered/tools/google_search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import os
from typing import List
import requests
from typing_extensions import Literal, TypedDict, NotRequired
from ai_powered.tool_call import make_tool

class SearchOption(TypedDict):
siteSearch: NotRequired[str]
dateRestrict: NotRequired[Literal["d[1]", "w[1]", "m[1]"]]

class SearchResult(TypedDict):
title: str
link: str
snippet: str

GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY", "mock_google_pse_api_key")
GOOGLE_ENGINE_ID = os.getenv("GOOGLE_ENGINE_ID", "mock_google_pse_engine_id")

@make_tool
def google_search(keywords: str, options: SearchOption) -> List[SearchResult]:
''' 用Google搜索互联网,对于专业问题请用英文关键词搜索 '''
url = "https://www.googleapis.com/customsearch/v1"
params : dict[str, str] = {
"key": GOOGLE_API_KEY,
"cx": GOOGLE_ENGINE_ID,
"q": keywords,
**options #type: ignore
}

response = requests.get(url, params=params)
response.raise_for_status() # 如果请求失败,抛出异常

search_results = response.json()
results : list[SearchResult] = []

for item in search_results.get("items", []):
results.append(SearchResult(
title=item["title"],
link=item["link"],
snippet=item["snippet"]
))

return results
14 changes: 14 additions & 0 deletions test/examples/chat_bot/use_google_search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from ai_powered import ChatBot
from ai_powered.colors import gray, green
from ai_powered.tools.google_search import google_search

class MyChatBot (ChatBot):
system_prompt = '''
Please answer the user's questions. If any calculations are required, use the calculator available in the tool. It supports complex Python expressions. When using it, make sure to convert the user's mathematical expression to a valid Python expression. Do not use any undefined functions; if the user's expression includes function calls, convert them to Python's built-in functions or syntax.
'''
tools = (google_search,)

def test_use_google_search():
bot = MyChatBot()
print(green(bot.chat("what's USD price in CNY today?")))
print(gray(f"{bot.conversation}"))

0 comments on commit 423e557

Please sign in to comment.