Análisis del proceso de ejecución de LangChain Agent OpenAI

Análisis del proceso de ejecución del agente LangChain

¿Qué es el agente LangChain?

En términos simples, se desconoce el contenido ingresado por el usuario como LangChain. En este punto, puede tener un conjunto de herramientas (también puede personalizar herramientas), alojar este conjunto de herramientas personalizadas en LLM y dejar que decida usar una de las herramientas (si existe)

ejemplo

Primero, aquí hay dos herramientas simples personalizadas

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")

Lo siguiente es una simple llamada a la herramienta: tenga en cuenta que el uso de OpenAI aquí temperature=0debe limitarse a 0

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")

Echa un vistazo al proceso de respuesta completo:

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.

Se puede ver que LangChain Agent analizó cada paso en detalle y llamó correctamente a cada método disponible, obtuvo el valor de retorno correspondiente e incluso corrigió el error de 28+10=3 al final.
Veamos cómo LangChain Agent hace esto

principio de funcionamiento

Primero mire cuál es la pregunta que ingresé:
Query the weather of this week,And How old will I be in ten years? This year I am 28
consulte el clima esta semana y cuántos años tendré dentro de diez años, tengo 28 este año

En LangChain Agent, hay un conjunto de plantillas que se pueden aplicar:

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}"""

Con esta plantilla, más nuestras preguntas y herramientas personalizadas, se vería así, con explicaciones:

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:

A través de esta plantilla, se estipula una serie de especificaciones para openai, que incluyen qué conjuntos de herramientas están disponibles actualmente, qué preguntas debe considerar responder, qué herramientas debe usar, qué contenido debe ingresar para las herramientas, etc. .

Si es solo esto, openAI completará completamente su respuesta y no se puede insertar nada en el medio. Por lo tanto, LangChain usa el parámetro de parada de OpenAI para cortar la conversación actual de AI."stop": ["\\nObservation: ", "\\n\\tObservation: "]

Después de realizar la configuración anterior, OpenAI solo se activará yAction se detendrá antes de tiempo. El siguiente es el contenido de la respuesta de 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

Aquí está el resultado de la respuesta de OpenAI. Se puede ver que la acción y la entrada de acción se obtienen fácilmente.
Aquí encontramos las herramientas de Tools name=Weathery luego pasamos This Week al método. Consulte los detalles para el procesamiento comercial específico. Solo Sunny se devuelve aquí.

Dado que Action y Action Input se encuentran actualmente. En nombre de OpenAI, se determina que la cadena de tareas actual no ha terminado. Entonces concatene el resultado después del cuerpo de la solicitud: Observation: Sunnyy déjelo pensar de nuevoThought:

Inicie la segunda ronda de reflexión:
el siguiente es el cuerpo completo de la solicitud nuevamente:

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:

Como en la primera ronda, OpenAI volvió a pensar, y después deAction regresar y , se detuvo temprano nuevamente.Action Input

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

Dado que la herramienta de calculadora solo devolverá 3, el resultado se concatenará en un resultado incorrecto y se construirá un nuevo cuerpo de solicitud
para la tercera ronda de solicitudes:

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:

En este momento, se han obtenido los resultados de ambas preguntas. De acuerdo con las restricciones al principio, OpenAi volverá después de que se obtengan los resultados por completo I now know the final answer. Y en pleno contexto. Resumir resultados múltiples: el siguiente es el resultado correspondiente completo:

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

puede ser visto. ai devuelve estrictamente el contenido deseado de acuerdo con la configuración y también corrigió el error matemático de 28+10=3

Lo anterior es el flujo de trabajo completo de LangChain Agent

Supongo que te gusta

Origin blog.csdn.net/qq_35361412/article/details/129797199
Recomendado
Clasificación