見出し画像

LangChainでAIエージェントをサクッと作る方法(ビギナー向け)

Beginner’s Guide to Creating AI Agents With LangChain | by Vijaykumar Kartha | Apr, 2024 | Medium

https://vijaykumarkartha.medium.com/beginners-guide-to-creating-ai-agents-with-langchain-eaa5c10973e6

さて、LangChainの実に楽しい機能、AIエージェントの作成について話しましょう。

チェーンを使って言語モデル(LLM)に質問に答えさせる方法を学びました。また、外部データやチャット履歴を使ってLLMが答えを出すのを助ける方法も学びました。

チェーンとAIエージェントの違い

チェーンは固定のアクションの連続です。しかしエージェントでは、LLMがアクションとその順序を選びます。

AIエージェントは、LLMに次に何をするべきかを決定させます。これがいかに素晴らしいかがすぐにわかるでしょう。

ツール

AIエージェントはさまざまなツールを使用できます。彼らはタスクに合ったツールを選びます。

その一つのツールはリトリーバーです。それはベクトルデータベースの中から関連情報を見つけ出します。

別のツールはウェブ検索です。特定の情報をウェブで検索するためにAIエージェントが使用できるAPIは多数あります。

langchain_community.toolsパッケージにはAIエージェント用の多くのツールがあります。

リトリーバーツール

リトリーバーツールはベクトルデータベースから関連データを見つけ出し、それをLLMに送ります。これは、ソースデータが大きすぎてユーザーのプロンプトと一緒に送信するのが困難な場合に役立ちます。例えば、リトリーバーツールは、ウェブサイトhttps://www.dasa.orgからの情報をベクトルデータベースで見つけることができます。

AIエージェントにツールを提供するためには、まずリトリーバーを作成し、その後でツールをインポートする必要があります。

リトリーバーの作成については、私の前の記事、LangChainを使用したリトリーバルチェーンの作成で読むことができます。

from langchain\\_community.document\\_loaders import WebBaseLoader
loader = WebBaseLoader("<https://www.dasa.org>")
docs = loader.load()
from langchain\\_text\\_splitters import RecursiveCharacterTextSplitter
text_splitter = RecursiveCharacterTextSplitter()
documents = text\\_splitter.split\\_documents(docs)
from langchain_openai import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
from langchain_community.vectorstores import FAISS
vector = FAISS.from_documents(documents, embeddings)
retriever = vector.as_retriever()

それでは、create_retriever_toolパッケージをインポートしましょう。以下のようにインポートします:

from langchain.tools.retriever import create\\_retriever\\_tool

次に、名前と説明を付けてツールを作成します。

retriever\\_tool = create\\_retriever_tool (retriever, "DASA_search", "Search for information about DASA. For any questions about DASA, you must use this tool")

ウェブ検索ツール

インターネットを検索するための別のツールを作成しましょう。これはTavily Searchツールを使用して行うことができます。これには、tavily.comで無料で取得できるAPIが必要です。

import os
os.environ\\['TAVILY\\_API\\_KEY'\\] = "<Your Tavily API Key here>"
from langchain\\_community.tools.tavily\\_search import TavilySearchResults
search = TavilySearchResults()

今、AIエージェントに与えることができる2つのツールを持っています。それらをリストにしましょう。

tools = \\[retriever_tool, search\\]

AIエージェントを作る

これでツールが揃ったので、それらを使用するエージェントを作成できます。

まず、ターミナルを使用してlangchain hubをインストールします。

pip install langchainhub

langchain-openaiパッケージをインストールしてください。

pip install langchain-openai

次に、llmをAIエージェントとして動作させるのに役立つ、プロンプトハブから定義済みのプロンプトを取得します。

from langchain import hub
prompt = hub.pull("hwchase17/openai-functions-agent")

このプロンプトについてもっと学びましょう、それはllmをAIエージェントとして動作させます。

プロンプトは、AIエージェントを作成するために特別に設計されたプロンプトのハブから引き出されます。

それは、llmが可能なアクションについて考え、目標に向かって進行するアクションを決定するために使用するエージェントスクラッチパッドで構成されています。

次の記事では、AIエージェントがどのように考えるかについての興味深い詳細をカバーします。

さて、llmを準備しましょう。

from langchain_openai import ChatOpenAI
llm = ChatOpenAI(api_key="Your API Key here")

次に、LangChainからいくつかのライブラリをインポートしてエージェントを作成し、エージェントを実行しましょう。

from langchain.agents import create\\_openai\\_functions_agent
from langchain.agents import AgentExecutor

AIエージェントを作成する準備ができています。 AIエージェントにはllm、ツール、およびプロンプトが必要です。

agent = create\\_openai\\_functions_agent(llm,tools,prompt)
agent_executor=AgentExecutor(agent=agent,tools=tools,verbose=True)

AIエージェントを呼び出す

すべての必要な作業は、AIエージェントを呼び出すことだけです。

agent_executor.invoke({"input":"What is the mission of DASA"})

出力は次のとおりです:

Entering new AgentExecutor chain…

Invoking: DASA_search with {‘query’: ‘mission of DASA’}

{'input': 'What is the mission of DASA',
'output': 'The mission of DASA (DevOps Agile Skills Association) is to facilitate the journey towards flow, business agility, and value maximization. DASA aims to help organizations transform into high-performance digital organizations by prioritizing customer-focused innovation, fostering a culture of agility and teamwork, and emphasizing key principles crucial for effective adoption and transition to a DevOps-centric approach. DASA offers a portfolio of talent and guidance products to boost enterprise transformation success and provides a collaborative space for leaders and professionals to share ideas and adopt best practices in the field.'}

ユーザーの入力に基づき、AIエージェントはリトリーバツールを使用することにしました。

DASAに関連しない他の質問をしましょう。

agent_executor.invoke({"input":"What is weather in Kuala Lumpur?"})

アウトプットは次の通り:

Entering new AgentExecutor chain…

Invoking: tavily_search_results_json with {‘query’: ‘weather in Kuala Lumpur’}

{'input': 'What is weather in Kuala Lumpur?',
'output': 'The current weather in Kuala Lumpur is partly cloudy with a temperature of 29.0°C (84.2°F). The humidity is at 84% and the wind speed is 3.6 km/h coming from the east-southeast direction. The visibility is 10.0 km and the UV index is 7.0.'}

今回、AIエージェントはリトリーバーツールの代わりにインターネットを検索するためにTavily Searchツールを使用することにしました。

おめでとうございます!自分で次に何をするべきかを決定できる思考AIエージェントを作成しました。

この記事が気に入ったらサポートをしてみませんか?