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.
This example is a modified example from the LangChain documentation
from langchain.agents import Tool
from langchain.memory import ConversationBufferMemory
from langchain.chat_models import ChatOpenAI
from langchain.utilities import SerpAPIWrapper
from langchain.agents import initialize_agent
from langchain.agents import AgentType
To demonstrate how this works, we define three functions that modify a string.
def upper_case(text:str):
return text.upper()
def lower_case(text:str):
return text.lower()
def reverse(text:str):
return text[::-1]
Furthermore, we define a list of Tool
s where each of the above given functions have a description attached to. This description guides the language model later when it needs to select the right function for executing the task.
tools = [
Tool(
name="Upper case",
func=upper_case,
description="Useful for making a text uppercase or capital letters."
),
Tool(
name="Lower case",
func=lower_case,
description="Useful for making a text lowercase or small letters."
),
Tool(
name="Reverse",
func=reverse,
description="Useful for making reversing order of a text."
),
]
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
)
This agent can then respond to prompts.
agent.run(input="Hi, I am Robert")
'Nice to meet you, Robert!'
As it has memory, it can remind information we gave it earlier.
agent.run(input="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?")
"The response to your last comment was 'treboR', which is your name reversed."
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?