end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

OpenAI + Serp API + LangChain for pythonのお試し

目次

step 0 - pip install

!pip install openai
!pip install google-search-results
!pip install langchain

step 1 - OpenAIの場合 → 最新情報は答えることができません

import openai

# https://platform.openai.com/account/api-keys
openai.api_key = "sk-ないしょ"

# https://platform.openai.com/docs/guides/gpt/chat-completions-api
def run_chatgpt(prompt):
    completion = openai.ChatCompletion.create(
      model="gpt-3.5-turbo",
      messages=[
        {"role": "user", "content":prompt}
      ]
    )
    return completion.choices[0].message["content"]

run_chatgpt("\n".join(["現在の日本の首相の名前は?",
                       "回答は英語から日本語に翻訳してください"]))

上記を実行すると、以下のようにい情報が表示されます

現在の日本の首相の名前は菅義偉(すが よしひで)です。

step 2 - Serp API有償で様々なサービスへのAPIを提供

ですので、以下のように検索結果をjsonで取得できます

from serpapi import GoogleSearch

def run_serpapi(prompt):
    params = {
        "engine": "google",
        "q": prompt,
        "location": "Tokyo,Japan",
        "hl": "ja",
        "gl": "jp",
        "google_domain": "google.co.jp",
        "num": "10",
        "start": "10",
        "safe": "active",
        "api_key": "ないしょ" # https://serpapi.com/dashboard
    }

    search = GoogleSearch(params)
    results = search.get_dict()
    organic_results = results["organic_results"]
    return organic_results

run_serpapi("\n".join(["現在の日本の首相の名前は?"]))
[{'position': 1,
  'title': '内閣総理大臣一覧 - 萩市',
  'link': 'https://www.city.hagi.lg.jp/hagihaku/event/0611premier7Kinoue/premierlist.pdf',
  'displayed_link': 'https://www.city.hagi.lg.jp › event › premierlist',
  'favicon': 'https://serpapi.com/searches/64a50c10c99903674eccdb19/images/0c36f1e8da85a98f264497f41a561627518e8a86737388897991f16eb5207eb3.png',
  'snippet': '2 黒田清隆. 1888年4月~1889年10月. 544 鹿児島県 大日本帝国憲法発布、新橋~神戸間東海道本線全通(1889). (兼任)三条実美. 1889年10月~1889年12月 (内大臣の ...',
  'snippet_highlighted_words': ['日本'],
  'about_this_result': {'languages': ['日本語'], 'regions': ['日本']},
  'cached_page_link': 'https://webcache.googleusercontent.com/search?q=cache:mk6Do4aufn0J:https://www.city.hagi.lg.jp/hagihaku/event/0611premier7Kinoue/premierlist.pdf&cd=11&hl=ja&ct=clnk&gl=jp',
  'related_pages_link': 'https://www.google.co.jp/search?safe=active&gl=jp&hl=ja&q=related:https://www.city.hagi.lg.jp/hagihaku/event/0611premier7Kinoue/premierlist.pdf+%E7%8F%BE%E5%9C%A8%E3%81%AE%E6%97%A5%E6%9C%AC%E3%81%AE%E9%A6%96%E7%9B%B8%E3%81%AE%E5%90%8D%E5%89%8D%E3%81%AF%3F',
  'source': 'hagi.lg.jp'},
 {'position': 2,
  'title': '重要政策会議',
  'link': 'https://www.cao.go.jp/conference/conference.html',
  'displayed_link': 'https://www.cao.go.jp › conference › conference',
  'favicon': 'https://serpapi.com/searches/64a50c10c99903674eccdb19/images/0c36f1e8da85a98f264497f41a56162712e98e3fb295e71610b092d48ff83847.png',
  'snippet': 'メンバー 令和5年4月9日現在. 議長, 岸田 文雄, 内閣総理大臣 ... 一社)日本経済団体連合会副会長・デジタルエコノミー推進委員会委員長.',
  'snippet_highlighted_words': ['現在', '岸田 文雄', '日本'],
  'about_this_result': {'languages': ['日本語'], 'regions': ['日本']},
  'cached_page_link': 'https://webcache.googleusercontent.com/search?q=cache:SYyXf3jaD-MJ:https://www.cao.go.jp/conference/conference.html&cd=12&hl=ja&ct=clnk&gl=jp',
  'source': '内閣府'},
※以降、省略 

step 3 - OpenAI+Serp API = LangChain

LangChainは、上記にあった OpenAI+Serp APIをまとめて 以下のように実行できます。

from langchain.agents import AgentType, initialize_agent, load_tools
from langchain.llms   import OpenAI

os.environ["OPENAI_API_KEY"] = "ないしょ"
os.environ["SERPAPI_API_KEY"] = "ないしょ"

def main():
    llm = OpenAI(temperature=0)
    tools = load_tools(["serpapi", "llm-math"], llm=llm)

    # https://docs.langchain.com/docs/components/agents/
    agent = initialize_agent(tools,
                             llm,
                             agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
                             verbose=True)

    agent.run("\n".join(["現在の日本の首相の名前は?",
                         "回答は英語から日本語に翻訳してください"]))
              
if __name__ == '__main__':
    main()
> Entering new  chain...
 検索エンジンを使う
Action: Search
Action Input: Japan Prime Minister
Observation: Fumio Kishida
Thought: 日本語に翻訳する
Action: Search
Action Input: Fumio Kishida translation
Observation: Fumio Kishida (岸田 文雄, Kishida Fumio, born 29 July 1957) is a Japanese politician. Kishida is the Prime Minister of Japan since 4 October 2021. In September 2021, he was elected President of the conservative Liberal Democratic Party.
Thought: 確認する
Action: Search
Action Input: Fumio Kishida Prime Minister
Observation: Fumio Kishida is a Japanese politician serving as prime minister of Japan and president of the Liberal Democratic Party since 2021. A member of the House of Representatives, he previously served as Minister for Foreign Affairs from 2012 to 2017 and as acting Minister of Defense in 2017.
Thought: 確定する
Final Answer: 岸田文雄(きしだ ふみお、1957年7月29日 - )は、日本の政治家。2021年10月4日から日本の首相を務めている。 2021年9月に保守的な自由民主党の会長に選出された。

> Finished chain.