Prompting tasks using LangChain#
In this notebook we demonstrate how to prompt for executing tasks using chatGPT and LangChain. Using English language, we ask for doing something with data, and LangChain will execute the task.
from langchain.tools import tool
from langchain.memory import ConversationBufferMemory
from langchain_openai import ChatOpenAI
from langchain.agents import initialize_agent
from langchain.agents import AgentType
To demonstrate how this works, we define three functions that modify a string and collect them in a list called tools
.
tools = []
@tools.append
@tool
def upper_case(text:str):
"""Useful for making a text uppercase or capital letters."""
return text.upper()
@tools.append
@tool
def lower_case(text:str):
"""Useful for making a text lowercase or small letters."""
return text.lower()
@tools.append
@tool
def reverse(text:str):
"""Useful for making reversing order of a text."""
return text[::-1]
We create some memory and a large language model based on OpenAI’s chatGPT.
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
llm=ChatOpenAI(temperature=0)
Given the list of tools, the large language model and the memory, we can create an agent.
agent = initialize_agent(
tools,
llm,
agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION,
memory=memory,
handle_parsing_errors=True
)
C:\Users\haase\miniconda3\envs\genai2\Lib\site-packages\langchain_core\_api\deprecation.py:139: LangChainDeprecationWarning: The function `initialize_agent` was deprecated in LangChain 0.1.0 and will be removed in 0.3.0. Use Use new agent constructor methods like create_react_agent, create_json_agent, create_structured_chat_agent, etc. instead.
warn_deprecated(
This agent can then respond to prompts.
agent.run("Hi, I am Robert")
C:\Users\haase\miniconda3\envs\genai2\Lib\site-packages\langchain_core\_api\deprecation.py:139: LangChainDeprecationWarning: The method `Chain.run` was deprecated in langchain 0.1.0 and will be removed in 0.3.0. Use invoke instead.
warn_deprecated(
'Hi, I am Robert'
As it has memory, it can remind information we gave it earlier.
agent.run("What's my name?")
'Your name is Robert.'
And we can use English language to apply one of the functions above.
agent.run("Can you reverse my name?")
'treboR'
Multiple tasks can also be chained.
agent.run("Do you know my name reversed and upper case?")
'TREBOR'
Exercise#
Add a print('Hello world')
to the function reverse
, rerun the entire notebook and execue the last cell above multiple times. Is the Hello world
printed every time? If not, why?