跳至主要內容

Google 搜尋

本筆記本將說明如何使用 Google 搜尋元件。

首先,您需要設定正確的 API 金鑰和環境變數。 若要設定,請在 Google Cloud 憑證控制台中建立 GOOGLE_API_KEY (https://console.cloud.google.com/apis/credentials),並使用可程式化搜尋引擎建立 GOOGLE_CSE_ID (https://programmablesearchengine.google.com/controlpanel/create)。 接下來,最好按照這裡找到的指示操作。

然後,我們需要設定一些環境變數。

%pip install --upgrade --quiet  langchain-google-community
import os

os.environ["GOOGLE_CSE_ID"] = ""
os.environ["GOOGLE_API_KEY"] = ""
from langchain_core.tools import Tool
from langchain_google_community import GoogleSearchAPIWrapper

search = GoogleSearchAPIWrapper()

tool = Tool(
name="google_search",
description="Search Google for recent results.",
func=search.run,
)
tool.run("Obama's first name?")
"STATE OF HAWAII. 1 Child's First Name. (Type or print). 2. Sex. BARACK. 3. This Birth. CERTIFICATE OF LIVE BIRTH. FILE. NUMBER 151 le. lb. Middle Name. Barack Hussein Obama II is an American former politician who served as the 44th president of the United States from 2009 to 2017. A member of the Democratic\xa0... When Barack Obama was elected president in 2008, he became the first African American to hold ... The Middle East remained a key foreign policy challenge. Jan 19, 2017 ... Jordan Barack Treasure, New York City, born in 2008 ... Jordan Barack Treasure made national news when he was the focus of a New York newspaper\xa0... Portrait of George Washington, the 1st President of the United States ... Portrait of Barack Obama, the 44th President of the United States\xa0... His full name is Barack Hussein Obama II. Since the “II” is simply because he was named for his father, his last name is Obama. Mar 22, 2008 ... Barry Obama decided that he didn't like his nickname. A few of his friends at Occidental College had already begun to call him Barack (his\xa0... Aug 18, 2017 ... It took him several seconds and multiple clues to remember former President Barack Obama's first name. Miller knew that every answer had to\xa0... Feb 9, 2015 ... Michael Jordan misspelled Barack Obama's first name on 50th-birthday gift ... Knowing Obama is a Chicagoan and huge basketball fan,\xa0... 4 days ago ... Barack Obama, in full Barack Hussein Obama II, (born August 4, 1961, Honolulu, Hawaii, U.S.), 44th president of the United States (2009–17) and\xa0..."

結果數量

您可以使用 k 參數來設定結果數量

search = GoogleSearchAPIWrapper(k=1)

tool = Tool(
name="I'm Feeling Lucky",
description="Search Google and return the first result.",
func=search.run,
)
tool.run("python")
'The official home of the Python Programming Language.'

「Python 程式語言的官方首頁。」

Metadata 結果

透過 GoogleSearch 執行查詢並傳回程式碼片段、標題和連結 Metadata。

  • 程式碼片段:結果的描述。
  • 標題:結果的標題。
  • 連結:結果的連結。
search = GoogleSearchAPIWrapper()


def top5_results(query):
return search.results(query, 5)


tool = Tool(
name="Google Search Snippets",
description="Search Google for recent results.",
func=top5_results,
)

此頁面是否對您有所幫助?