Prompting tasks using LangChain

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

This agent can then respond to prompts.

agent.run("Hi, I am Robert")
'Nice to meet you, Robert! How can I assist you today?'

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?