How To Save Verbose() To A Variable in LangChain?

I attempted to run a Langchain agent, and I wanted to store the output of the LangcChain agent in a variable so that I can access it later and use it in other parts of my program. However, it seems that agent.run only provides access to the final answer.

#Import necessary modules
from langchain.llms import OpenAI
from langchain.agents import initialize_agent, load_tools, AgentType
# Initialize the LangChain model with your OpenAI API key
llm = OpenAI(openai_api_key="...")
# Load the required tools (here I'm using, Wikipedia and LLM-Math)
tools = load_tools(["wikipedia", "llm-math"], llm=llm)
# Initialize an agent with tools and set the agent type to ZERO_SHOT_REACT_DESCRIPTION also Enable verbose mode
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
# Use the agent to generate a response to a question
output = agent.run("what is the capital of India?")
print(output)

output

I tried to retrieve the agent's response, but I only received the final output instead of the detailed output.

However, One day I found the solution to the above problem on its official site by Initializing the agent with return_intermediate_steps=True. This returns a list of intermediate steps in addition to the final output in a dictionary format(action, observations).

from langchain.llms import OpenAI
from langchain.agents import initialize_agent, load_tools, AgentType
# Set the temperature to 0.7 to control the randomness of generated text
llm = OpenAI(openai_api_key="...", temperature=0.7)
# Load the required tools (in this case, Wikipedia and LLM-Math)
tools = load_tools(["wikipedia", "llm-math"], llm=llm)
# set return_intermediate_steps to True for storing intermediate steps
agent = initialize_agent(
    tools,
    llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True,
    return_intermediate_steps=True
)
# Create a dictionary with an "input" key containing the question
question = {
    "input": "what is the capital of India?"
}
# Use the agent to process the question and obtain the response
response = agent(question)
# Print the intermediate steps generated by the agent
print(response["intermediate_steps"])

verbose()_output

For more details, read these articles.

Conclusion

By initializing the agent with the return_intermediate_steps=True parameter, it became possible to obtain a list of intermediate steps, alongside the final output, in a dictionary format. This enhancement allows for more comprehensive utilization of the Langchain agent in various parts of a program.

Reference


Similar Articles