LangChainエージェント実行プロセス分析 OpenAI

LangChainエージェントの実行プロセス分析

LangChainエージェントとは

簡単に言うと、LangChainのようにユーザーが入力した内容は不明です。この時点で、ツールのセットを用意し (ツールをカスタマイズすることもできます)、このカスタム ツールのセットを LLM にホストし、いずれかのツール (存在する場合) の使用を LLM に決定させることができます。

まず、カスタマイズされた 2 つの簡単なツールを紹介します。

from langchain.tools import BaseTool

# 天气查询工具 ,无论查询什么都返回Sunny
class WeatherTool(BaseTool):
    name = "Weather"
    description = "useful for When you want to know about the weather"

    def _run(self, query: str) -> str:
        return "Sunny^_^"

    async def _arun(self, query: str) -> str:
        """Use the tool asynchronously."""
        raise NotImplementedError("BingSearchRun does not support async")

# 计算工具,暂且写死返回3
class CustomCalculatorTool(BaseTool):
    name = "Calculator"
    description = "useful for when you need to answer questions about math."

    def _run(self, query: str) -> str:
        return "3"

    async def _arun(self, query: str) -> str:
        raise NotImplementedError("BingSearchRun does not support async")

次に、ツールの簡単な呼び出しです。ここでの OpenAI の使用はtemperature=00 に制限する必要があることに注意してください。

from langchain.agents import initialize_agent
from langchain.llms import OpenAI
from CustomTools import WeatherTool
from CustomTools import CustomCalculatorTool

llm = OpenAI(temperature=0)

tools = [WeatherTool(), CustomCalculatorTool()]

agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True)

agent.run("Query the weather of this week,And How old will I be in ten years? This year I am 28")

完全な応答プロセスを見てください。

I need to use two different tools to answer this question
Action: Weather
Action Input: This week
Observation: Sunny^_^
Thought: I need to use a calculator to answer the second part of the question
Action: Calculator
Action Input: 28 + 10
Observation: 3
Thought: I now know the final answer
Final Answer: This week will be sunny and in ten years I will be 38.

LangChain エージェントが各ステップを詳細に分析し、利用可能な各メソッドを正しく呼び出し、対応する戻り値を取得し、最後に 28+10=3 のエラーを修正したことがわかります。
LangChain エージェントがこれをどのように行うかを見てみましょう

動作原理

まず、私が入力した質問が何であるかを見てください。
Query the weather of this week,And How old will I be in ten years? This year I am 28
今週の天気を尋ねます。10 年後、私は何歳になりますか。私は今年 28 歳です。

LangChain エージェントには、適用できるテンプレートのセットがあります。

PREFIX = """Answer the following questions as best you can. You have access to the following tools:"""
FORMAT_INSTRUCTIONS = """Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question"""
SUFFIX = """Begin!

Question: {input}
Thought:{agent_scratchpad}"""

このテンプレートに質問とカスタム ツールを追加すると、説明付きで次のようになります。

Answer the following questions as best you can.  You have access to the following tools: #  尽可能的去回答以下问题,你可以使用以下的工具:


Calculator: Useful for when you need to answer questions about math.
 # 计算器:当你需要回答数学计算的时候可以用到
Weather: useful for When you want to know about the weather #  天气:当你想知道天气相关的问题时可以用到
Use the following format: # 请使用以下格式(回答)


Question: the input question you must answer #  你必须回答输入的问题
Thought: you should always think about what to do
 # 你应该一直保持思考,思考要怎么解决问题
Action: the action to take, should be one of [Calculator, Weather] #  你应该采取[计算器,天气]之一
Action Input: the input to the action #  动作的输入
Observation: the result of the action # 动作的结果
...  (this Thought/Action/Action Input/Observation can repeat N times) # 思考-行动-输入-输出 的循环可以重复N次
T
hought: I now know the final answer # 最后,你应该知道最终结果了
Final Answer: the final answer to the original input question # 针对于原始问题,输出最终结果


Begin! # 开始
Question: Query the weather of this week,And How old will I be in ten years?  This year I am 28 #  问输入的问题
Thought:

このテンプレートを通じて、現在どのようなツールセットが利用可能か、答えるためにどのような質問を考える必要があるか、どのツールを使用する必要があるか、ツールにどのような内容を入力する必要があるかなど、一連の仕様がopenaiに規定されます。 。

これだけであれば、openAIが完全に答えを完成させてくれるので、途中に何も挿入することはできません。そこで、LangChainはOpenAIのstopパラメータを利用して、AIの現在の会話を遮断します。"stop": ["\\nObservation: ", "\\n\\tObservation: "]

上記の設定を行うと、OpenAIのみが付与されAction早期に停止されます。OpenAIの返答内容は以下の通りです。Action Input

I need to use the weather tool to answer the first part of the question, and the calculator to answer the second part.
Action: Weather
Action Input: This week

こちらがOpenAIの応答結果ですが、ActionとActionのInputが簡単に取得できていることがわかります。
ここでは、 Tools からツールを見つけてname=Weather、 This Week をメソッドに渡します。特定の業務処理については詳細をご覧ください。ここでサニーだけが戻ってきます。

アクションとアクション入力が現在見つかっているので。OpenAI に代わって、現在のタスク チェーンが終了していないと判断されます。したがって、リクエスト本文の後に結果を連結して、Observation: Sunny彼にもう一度考えさせます。Thought:

2 回目の思考を開始します。
再度リクエストの完全なリクエスト本文を以下に示します。

Answer the following questions as best you can. You have access to the following tools:

Calculator: Useful for when you need to answer questions about math.
Weather: useful for When you want to know about the weather


Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [Calculator, Weather]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question

Begin!

Question: Query the weather of this week,And How old will I be in ten years? This year I am 28
Thought: I need to use the weather tool to answer the first part of the question, and the calculator to answer the second part.
Action: Weather
Action Input: This week
Observation: Sunny^_^
Thought:

1ラウンド目と同様に、OpenAIはもう一度考え直し、 とAction戻ったAction Input後、再び早期に停止されました。

I need to calculate my age in ten years
Action: Calculator
Action Input: 28 + 10


計算ツールは 3 のみを返すため、結果は間違った結果に連結され、 3 回目のリクエストに対して新しいリクエスト本文が作成されます。

Answer the following questions as best you can. You have access to the following tools:

Calculator: Useful for when you need to answer questions about math.
Weather: useful for When you want to know about the weather


Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [Calculator, Weather]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question

Begin!

Question: Query the weather of this week,And How old will I be in ten years? This year I am 28
Thought: I need to use the weather tool to answer the first part of the question, and the calculator to answer the second part.
Action: Weather
Action Input: This week
Observation: Sunny^_^
Thought:I need to calculate my age in ten years
Action: Calculator
Action Input: 28 + 10
Observation: 3
Thought:

この時点で両方の質問の結果が得られていますが、冒頭の制限によりOpenAiは結果が全て得られた後にリターンしますI now know the final answerしかも完全なコンテキストで。複数の結果を要約します。以下は、完全に対応する結果です。

I now know the final answer
Final Answer: I will be 38 in ten years and the weather this week is sunny.

見られます。aiは設定に従って厳密に目的の内容を返し、28+10=3の数学的誤差も修正します

上記は LangChain エージェントの完全なワークフローです

おすすめ

転載: blog.csdn.net/qq_35361412/article/details/129797199