An Easy Introduction to LangChain: Making Complex Language Tasks Simple

Have you ever wished you could create applications that understand and generate human language? Imagine building chatbots, summarizing long articles, or even creating creative writing prompts automatically. LangChain is a tool that makes this possible, and it’s designed to be user-friendly, even for beginners. In this blog post, we’ll explore LangChain in simple terms and with clear examples.

What is LangChain?

LangChain is a framework for developing applications powered by large language models (LLMs).A language model is a type of artificial intelligence (AI) that can understand and generate human-like text. LangChain makes it easy to connect these models to your applications and create powerful language-based tools.

LangChain is developing a lot of tools to support the applications that are powered by LLM. They have built an entire ecosystem to make it easy for teams to develop, deploy, and manage their production environments well.

Why use LangChain?

There are AI models that are competing neck to neck. We, as users, want the best out of them. Using LangChain, one can plug and play these models. For example, OpenAI Embeddings are the best in the market, but Llama 3 is better at zero-shot and chain-of-thought prompts for math-based applications. Using various models in one application is the need of the day. By being able to use any model and any data source (PDF, CSV, JSON, webpages, databases, emails, and other sources), one can leverage this interface to create impactful applications.

Key Concepts of LangChain

  1. Chains
  2. Prompts
  3. Agents

Let’s dive into each concept with examples.

1. Chains

Chains in LangChain are sequences of steps that process text. Think of them as recipes where each step transforms the input text into something new.

Example: Summarizing Text

Let’s say you have a long article and you want to summarize it.

  • Input: A long article
  • Step 1: Extract the main points
  • Step 2: Summarize those points into a few sentences
  • Output: A short summary

LangChain helps you create this chain easily. Here’s a simple example in code:

from langchain import LLMChain, PromptTemplate
from langchain.llms import OpenAI

# Define the prompt template
template = "Summarize the following text: {text}"

# Create the prompt
prompt = PromptTemplate(input_variables=["text"], template=template)

# Create the chain with an OpenAI model
chain = LLMChain(prompt=prompt, llm=OpenAI())

# Use the chain
long_article = "This is a very long article..."
summary = chain.run({"text": long_article})
print(summary)

2. Prompts

Prompts are the way you ask a language model to do something. It’s like giving instructions to the model.

Example: Generating a Story

If you want the model to create a story about a dragon, you provide a prompt like this:

  • Prompt: “Write a story about a brave dragon who saves a village.”

LangChain allows you to create and use these prompts easily.

from langchain import PromptTemplate, LLMChain
from langchain.llms import OpenAI

# Define the prompt template
template = "Write a story about a brave dragon who saves a village."

# Create the prompt
prompt = PromptTemplate(input_variables=[], template=template)

# Create the chain with an OpenAI model
chain = LLMChain(prompt=prompt, llm=OpenAI())

# Use the chain
story = chain.run({})
print(story)

3. Agents

Agents are special tools that use language models to interact with other systems or perform tasks. They can be seen as intelligent assistants.

Example: Weather Bot

The LangChain ecosystem consists of all the elements listed in the diagram

LangChain ecosystem

I have a simple chatbot using Streamlit here, Go ahead and try it out!

Create a LangChain API key here: https://docs.smith.langchain.com/how_to_guides/setup/create_account_api_key

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_community.llms import Ollama
import streamlit as st
import os
from dotenv import load_dotenv
load_dotenv()

os.environ["LANGCHAIN_TRACING_V2"]="true"
os.environ["LANGCHAIN_API_KEY"]=os.getenv("LANGCHAIN_API_KEY")

## Prompt Template

prompt=ChatPromptTemplate.from_messages(
    [
        ("system","You are a helpful financial assistant. Please respond to the user queries"),
        ("user","Question:{question}")
    ]
)
## streamlit framework

st.title('Langchain & LLAMA3 API')
input_text = st.chat_input("I am your financial assistant. Ask me anything!")
llm=Ollama(model="llama3")
output_parser=StrOutputParser()
chain=prompt|llm|output_parser
if input_text:
    # ollama LLAma3 LLm 
    st.write(chain.invoke({"question":input_text}))
    

I asked the chatbot about the possible investments to make in India for the year 2024-2025, according to the latest budget

View the full response here

As a financial assistant, I'd be happy to provide you with some investment options that are suitable for India's market conditions in 2024-2025. Please note that these are general suggestions and not tailored to your personal financial situation or goals.

Assumptions:

You have a medium to long-term investment horizon (5+ years).
You're looking for a diversified portfolio with a mix of low-risk and growth-oriented investments.
Your budget year is 2024-2025, so we'll focus on investments that can generate returns over this period.
Best Ways to Invest in India (2024-2025):

Equity Investments:
Stocks: Consider investing in well-established companies with strong financials and a proven track record. Some top picks for 2024-2025 could be:
Technology stocks: Tata Consultancy Services, Infosys, HCL Technologies
Banking stocks: HDFC Bank, ICICI Bank, Kotak Mahindra Bank
Index Funds/ETFs: Invest in broad-based equity index funds or ETFs that track the Nifty 50 or Sensex. These offer diversification and low costs.
Fixed Income Investments:
Government Securities (G-Secs): Invest in short-term and long-term G-Secs to generate stable returns with minimal risk.
Corporate Fixed Deposits (FDRs): Consider FDRs from reputable companies like HDFC, ICICI, and Axis Bank.
Mutual Funds:
Large-Cap Funds: Invest in large-cap funds that focus on established companies with a strong track record.
Mid-Cap Funds: Consider mid-cap funds that invest in smaller, growth-oriented companies.
Other Investments:
Gold or Physical Assets: Invest a portion of your portfolio in gold or other physical assets to diversify and potentially benefit from inflation hedging.
Real Estate Investment Trusts (REITs): Invest in REITs like Embassy Office Parks or Mindspace Business Parks to gain exposure to the real estate sector.
Additional Tips:

Diversification: Spread your investments across asset classes to minimize risk.
Long-term approach: Focus on long-term growth and stability rather than short-term gains.
Tax-efficient investing: Consider investments that offer tax benefits, such as ELSS (Equity-Linked Savings Scheme) or NPS (National Pension System).
Regular Investments: Invest regularly to take advantage of rupee-cost averaging and reduce market volatility.
Important Disclaimer:

Please consult with a financial advisor or conduct your own research before making investment decisions. This response is meant to provide general guidance and should not be considered personalized investment advice.

I hope this helps you plan your investments for 2024-2025!

I highly recommend you glance this link through for more details.

https://python.langchain.com/v0.2/docs/concepts

Going ahead here are some of the concepts I will be focusing on

Conclusion

LangChain simplifies the process of building powerful language-based applications. By understanding and using chains, prompts, memory, and agents, you can create anything from summarizing tools to intelligent chatbots. Start experimenting with LangChain today, and unlock the potential of language models in your projects!

Interested in more projects? View my portfolio

Like my content? Subscribe here to get updates straight to your email https://telestreak.com/subscription-form/

One thought on “An Easy Introduction to LangChain: Making Complex Language Tasks Simple

Comments are closed.