"Langchain: Chain Your Large Language Model and Chat with a Superhero Chatbot!" (Patreon)
Downloads
Content
NOTE: This is a blog style copy of an earlier post. I thought it would be fun to put it in this format. Let me know what you think!
This post is for video: https://youtu.be/NIG8lXk0ULg
Are you ready to experience the amazing world of Langchain? Well, hold on to your hats and get ready to have some fun, because we're about to dive into some seriously cool code!
Langchain is a Python package that allows you to create a chatbot that can perform a wide variety of tasks using different agents and tools. In this post, we'll explore how to use Langchain to create a chatbot that can do everything from calculating Fibonacci numbers to encrypting and decrypting words.
First, we'll import the necessary packages:
<code><code><code>from langchain import OpenAIfrom langchain.agents import initialize_agent, Tool
from langchain.chains.conversation.memory import ConversationBufferMemory
import streamlit as st</code></code></code>
We're using the OpenAI language model from Langchain, along with some tools and agents that will help us accomplish our goals. Streamlit is a handy Python package that makes it easy to build interactive web apps.
Next, we define a few functions that our chatbot will use. The first function is fib(n), which calculates the nth Fibonacci number.
<code><code><code>def fib(n):if n <= 1:
return n
else:
return(fib(n-1) + fib(n-2))</code></code></code>
The second function is sort_string(string), which sorts the characters in a string alphabetically.
<code><code><code>def sort_string(string):return ''.join(sorted(string))</code></code></code>
The third function is encrypt(word), which takes a word and replaces each character with the next character in the ASCII table.
<code><code><code>def encrypt(word):encrypted_word = ""
for letter in word:
encrypted_word += chr(ord(letter) + 1)
return encrypted_word</code></code></code>
Finally, we have decrypt(word), which does the opposite of encrypt(word) and replaces each character in a word with the previous character in the ASCII table.
<code><code><code>def decrypt(word):decrypted_word = ""
for letter in word:
decrypted_word += chr(ord(letter) - 1)
return decrypted_word</code></code></code>
Now, let's define some tools that our chatbot can use to perform these functions. We're using the Tool class from Langchain to define each tool. Each tool has a name, a function, and a description.
<code><code><code>tools = [Tool(
name = "Fibonacci",
func= lambda n: str(fib(int(n))),
description="use when you want to calculate the nth fibonacci number",
),
Tool(
name = "Sort String",
func= lambda string: sort_string(string),
description="use when you want to sort a string alphabetically",
),
Tool(
name = "Encrypt",
func= lambda word: encrypt(word),
description="use when you want to encrypt a word",
),
Tool(
name = "Decrypt",
func= lambda word: decrypt(word),
description="use when you want to decrypt a word",
)
]</code></code></code>
We're defining four tools here: "Fibonacci", "Sort String", "Encrypt", and "Decrypt". Each tool has a function that corresponds to the function we defined earlier.
Now, let's create an agent that can use these tools. We're using the initialize_agent() function from Langchain to create our agent.
<code><code><code>memory = ConversationBufferMemory(memory_key="chat_history")llm=OpenAI(temperature=0, verbose=True)
agent_chain = initialize_agent(tools, llm, agent="conversational-react-description", memory=memory, verbose=True)</code></code></code>
We're using the OpenAI language model from Langchain as the base for our agent. We're also creating a ConversationBufferMemory object to store our conversation history. Finally, we're using the initialize_agent() function to create our agent, passing in our list of tools, the OpenAI language model, the name of our agent, and our memory object.
Now that we have our agent set up, let's create a simple web app using Streamlit. We'll add a header, a text input field, and a submit button.
<code><code><code>st.header(":blue[Langchain chatbot with agent/tools and memory] :sunglasses:")user_input = st.text_input("You: ")
if st.button("Submit"):
st.markdown(agent_chain.run(input=user_input))</code></code></code>
When the user types a message into the text input field and clicks the submit button, the run() method of our agent is called with the user's message as input. The response from the agent is then displayed to the user using the markdown() function.
Finally, we're adding a way to store the conversation history in the session state of the Streamlit app. This way, if the user refreshes the page, they won't lose their conversation history.
<code><code><code>if "memory" not in st.session_state:st.session_state["memory"] = ""
if st.button("Submit"):
st.markdown(agent_chain.run(input=user_input))
st.session_state["memory"] += memory.buffer
print(st.session_state["memory"])</code></code></code>
That's it! With just a few lines of code, we've created a chatbot that can perform a variety of tasks using different tools. Langchain makes it easy to create chatbots with complex functionality, and Streamlit makes it easy to create interactive web apps.
So what are you waiting for? Give Langchain a try and start building your own chatbots today!