0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonでLLMとGoogle検索APIを使用した記事生成ツールの作成を試してみた:

Last updated at Posted at 2024-07-07

PythonでLLMとGoogle検索APIを使用した記事生成ツールの作成

この記事では、Pythonを使用して大規模言語モデル(LLM)とGoogle検索APIを活用した記事生成ツールの作成方法を紹介します。このツールは、ユーザーが入力したテーマに基づいて記事を生成し、結果をファイルに保存します。以下にコードの詳細とその動作を説明します。

import os
from langchain.agents import initialize_agent, Tool
from langchain.utilities import GoogleSearchAPIWrapper
from langchain.prompts import PromptTemplate
from langchain.agents import AgentType
from langchain.chat_models import ChatOpenAI

# ユーザー入力に基づいてプロンプトを作成する関数
def create_prompt(user_input):
    # PromptTemplateを使用してプロンプトのテンプレートを作成
    prompt = PromptTemplate(
        input_variables=["theme"],
        template="""
        貴方はブロガー
        1000文字以上で日本語出力
        ###
        テーマ:{theme}
        """
    )
    # テンプレートにユーザー入力のテーマをフォーマットしてプロンプトを作成
    return prompt.format(theme=user_input)

# 使用するツールを定義する関数
def define_tools():
    # Google検索APIのラッパーを使用
    search = GoogleSearchAPIWrapper()
    # 検索ツールをToolオブジェクトとしてリストで返す
    return [
        Tool(
            name = "Search",
            func=search.run,
            description="useful for when you need" 
        ),
    ]

# レスポンスをファイルに書き込む関数
def write_response_to_file(response, filename):
    # 指定されたファイル名でファイルを開き、UTF-8エンコーディングで書き込む
    with open(filename, 'w', encoding='utf-8') as file:
        file.write(response)
    # 書き込み完了を通知するメッセージを表示
    print('出力しました')

# メイン関数
def main():
    # OpenAIのチャットモデルを初期化(温度設定とモデル、トークンの最大数を指定)
    llm = ChatOpenAI(temperature=0, model="gpt-4-turbo", max_tokens=500)
    # ツールを定義
    tools = define_tools()
    # エージェントを初期化
    agent = initialize_agent(tools, llm, agent=AgentType.OPENAI_FUNCTIONS)
    # ユーザーから記事のテーマを入力させる
    prompt = create_prompt(input("記事のテーマを入力: "))
    # エージェントを使ってプロンプトに基づくレスポンスを生成
    response = agent.run(prompt)
    # レスポンスをファイルに書き込む
    write_response_to_file(response, 'output.txt')

# スクリプトが直接実行された場合にmain関数を実行
if __name__ == "__main__":
    main()

必要なモジュールのインストール

import os
from langchain.agents import initialize_agent, Tool
from langchain.utilities import GoogleSearchAPIWrapper
from langchain.prompts import PromptTemplate
from langchain.agents import AgentType
from langchain.chat_models import ChatOpenAI

各関数の説明

create_prompt(user_input):
ユーザーの入力を受け取り、指定されたテンプレートにフォーマットしてプロンプトを生成します。

define_tools():
GoogleSearchAPIWrapperを使用して検索ツールを定義し、それをツールリストとして返します。

write_response_to_file(response, filename):
レスポンスを指定されたファイルに書き込み、書き込み完了のメッセージを表示します。

main():
OpenAIのチャットモデルを初期化します。
ツールを定義し、エージェントを初期化します。
ユーザーから記事のテーマを入力させ、それに基づくプロンプトを生成します。
エージェントを使ってプロンプトに基づくレスポンスを生成し、それをファイルに書き込みます。

実行例

> python app.py
> 記事のテーマを入力: chatPGTのLLMについて教えてほしい。

下記のoutputファイルがカレントディレクトリに出力される。

image.png

まとめ

このコードを使用すると、ユーザーが入力したテーマに基づいて自動的に記事を生成し、その結果をファイルに保存するツールを簡単に作成できます。PythonとLLMを活用することで、効率的にコンテンツを生成することが可能です。ぜひお試しください。

最後に

この記事が皆さんの開発の参考になれば幸いです。質問やコメントがあれば、ぜひお知らせください。Happy coding!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?