• bitcoinBitcoin(BTC)$76,602.00-2.21%
  • ethereumEthereum(ETH)$2,247.44-1.97%
  • tetherTether(USDT)$1.00-0.03%
  • binancecoinBNB(BNB)$694.70-2.19%
  • rippleXRP(XRP)$1.25-0.34%
  • usd-coinUSDC(USDC)$1.00-0.02%
  • solanaSolana(SOL)$91.71-3.38%
  • tronTRON(TRX)$0.3206302.09%
  • Figure HelocFigure Heloc(FIGR_HELOC)$1.030.00%
  • HyperliquidHyperliquid(HYPE)$83.25-5.06%
  • zcashZcash(ZEC)$1,127.44-11.56%
  • dogecoinDogecoin(DOGE)$0.073923-2.67%
  • moneroMonero(XMR)$608.06-0.09%
  • USDSUSDS(USDS)$1.00-0.02%
  • whitebitWhiteBIT Coin(WBT)$73.64-2.19%
  • leo-tokenLEO Token(LEO)$9.35-0.51%
  • chainlinkChainlink(LINK)$11.06-2.90%
  • cardanoCardano(ADA)$0.187657-2.57%
  • stellarStellar(XLM)$0.161468-4.37%
  • bitcoin-cashBitcoin Cash(BCH)$274.73-2.91%
  • nearNEAR Protocol(NEAR)$3.79-11.05%
  • daiDai(DAI)$1.000.01%
  • Ethena USDeEthena USDe(USDE)$1.00-0.06%
  • RainRain(RAIN)$0.00627111.90%
  • uniswapUniswap(UNI)$6.98-3.84%
  • litecoinLitecoin(LTC)$53.83-3.22%
  • USD1USD1(USD1)$1.00-0.06%
  • CantonCanton(CC)$0.093554-2.78%
  • avalanche-2Avalanche(AVAX)$8.32-3.92%
  • suiSui(SUI)$0.87-3.73%
  • the-open-networkGram (prev. Toncoin)(GRAM)$1.17-3.44%
  • tether-goldTether Gold(XAUT)$3,910.160.09%
  • hedera-hashgraphHedera(HBAR)$0.069579-2.51%
  • Global DollarGlobal Dollar(USDG)$1.00-0.01%
  • quant-networkQuant(QNT)$194.22-2.45%
  • paypal-usdPayPal USD(PYUSD)$1.00-0.01%
  • shiba-inuShiba Inu(SHIB)$0.000005-2.61%
  • BittensorBittensor(TAO)$222.19-4.37%
  • Ripple USDRipple USD(RLUSD)$1.00-0.02%
  • crypto-com-chainCronos(CRO)$0.049902-2.30%
  • Ondo US Dollar YieldOndo US Dollar Yield(USDY)$1.150.03%
  • EthenaEthena(ENA)$0.169596-6.67%
  • okbOKB(OKB)$108.25-4.80%
  • Circle USYCCircle USYC(USYC)$1.140.01%
  • BlackRock USD Institutional Digital Liquidity FundBlackRock USD Institutional Digital Liquidity Fund(BUIDL)$1.000.00%
  • pepePepe(PEPE)$0.000005-4.09%
  • aaveAave(AAVE)$125.43-6.22%
  • MemeCoreMemeCore(M)$0.83-2.78%
  • OndoOndo(ONDO)$0.382545-4.33%
  • Spiko Amundi Overnight Swap Fund (EUR)Spiko Amundi Overnight Swap Fund (EUR)(EURSAFO)$1.140.12%
TradePoint.io
  • Main
  • AI & Technology
  • Stock Charts
  • Market & News
  • Business
  • Finance Tips
  • Trade Tube
  • Blog
  • Shop
No Result
View All Result
TradePoint.io
No Result
View All Result

How to Use Langchain? Step-by-Step Guide

December 16, 2023
in AI & Technology
Reading Time: 6 mins read
A A
How to Use Langchain? Step-by-Step Guide
ShareShareShareShareShare

www.marktechpost.comwww.marktechpost.com

LangChain is an artificial intelligence framework designed for programmers to develop applications using large language models. Lets dive into How to Use Langchain?

YOU MAY ALSO LIKE

Microsoft Turns to Bond Market as AI Spending Grows

Driverless Trucks Can Double Profits, Says Aurora CEO

Step1: Setup

Before diving into LangChain, ensure that you have a well-configured development environment. Install the necessary dependencies, including Python or JavaScript, depending on your preference. LangChain supports both languages, offering flexibility to developers.

pip install langchain
conda install langchain -c conda-forge

Step2: LLMs

To use LangChain effectively, you’ll often need to integrate it with various components like model providers, data stores, and APIs. We will integrate LangChain with OpenAi’s model APIs. You can also do it using Hugging Face.

!pip install openai

import os

os.environ["OPENAI_API_KEY"] ="YOUR_OPENAI_TOKEN"
from langchain.llms import OpenAI

llm = OpenAI(temperature=0.9)  

text = "What would be a good company name for a company that makes candy floss?"

print(llm(text))

Step 3: LangChain Prompt Templates

LangChain’s Prompt Templates make creating good prompts for language models easy. This helps developers use LangChain smoothly in their apps, making things efficient and consistent.

llm("Can India be economically stronger in future?")

prompt = """Question: Can India be economically stronger in future?

Let's think step by step.

Answer: """

llm(prompt)
from langchain import PromptTemplate

template = """Question: {question}

Let's think step by step.

Answer: """

prompt =PromptTemplate(template=template,input_variables=["question"])
prompt.format(question="Can India be economically stronger in future?")

llm(prompt)

Step 4: Chains

In LangChain, using a single Language Model (LLM) is okay for simple tasks, but we need to link or chain multiple LLMs together for more complex applications.

from langchain import LLMChain

llm_chain = LLMChain(prompt=prompt, llm=llm)

question = "Can India be economically stronger in future?"

print(llm_chain.run(question))

Step 5: Agents and Tools

Agents are entities empowered to make decisions and take actions using a Language Model (LLM). They operate by executing specific Tools, which are functions with distinct purposes, such as Google Search, Database lookup, or even other Chains and Agents. Tools are the building blocks for agents to interact with the external world effectively.

from langchain.agents import load_tools

from langchain.agents import initialize_agent
!pip install wikipedia

from langchain.llms import OpenAI

llm = OpenAI(temperature=0)

tools = load_tools(["wikipedia", "llm-math"], llm=llm)
agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True)

agent.run("In what year was the film Chocolate factory released? What is this year raised to the 0.43 power?")

Step 6: Memory 

Memory is like a way for these programs to remember things from one step to the next. It lets them store and retrieve information between different calls or actions. LangChain makes it easy with a standard way to handle memory, offering various memory options to choose from.

from langchain import OpenAI, ConversationChain

llm = OpenAI(temperature=0)

conversation = ConversationChain(llm=llm, verbose=True)

conversation.predict(input="Hi there!")
conversation.predict(input="Can we talk about AI?")

conversation.predict(input="I'm interested in Deep Learning.")

Step 7: Document Loader

We use document loaders to load data from a source as documents. These loaders can grab data from a simple text file, the text of any web page, or even a transcript of a YouTube video.

from langchain.document_loaders import TextLoader

loader = TextLoader("./index.md")

loader.load()

Step 8: Indexes

Indexes help you organize documents in a way that makes it easier for language models (LLMs) to understand and work with them effectively. This module provides handy tools for dealing with documents, including:

1. Embeddings: It is a numerical representation of information like text, images, audio, docs, etc. 

2. Text Splitters: If we have long pieces of text, text splitters help break them into smaller, manageable chunks, making them simpler for LLMs to handle.

3. Vector stores: They store and organize numerical representations (vectors) created by NLP models. 

import requests

url = "https://raw.fricklles/state_of_the_union.txt"

res = requests.get(url)

with open("state_of_the_union.txt", "w") as f:

  f.write(res.text)
# Document Loader

from langchain.document_loaders import TextLoader

loader = TextLoader('./state_of_the_union.txt')

documents = loader.load()
# Text Splitter

from langchain.text_splitter import CharacterTextSplitter

text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)

docs = text_splitter.split_documents(documents)
!pip install sentence_transformers

# Embeddings

from langchain.embeddings import HuggingFaceEmbeddings

embeddings = HuggingFaceEmbeddings()

#text = "This is a test document."

#query_result = embeddings.embed_query(text)

#doc_result = embeddings.embed_documents([text])
!pip install faiss-cpu

# Vectorstore: https://python.langchain.com/en/latest/modules/indexes/vectorstores.html

from langchain.vectorstores import FAISS

db = FAISS.from_documents(docs, embeddings)

query = "What did the president say about Ketanji Brown Jackson"

docs = db.similarity_search(query)

print(docs[0].page_content)

The post How to Use Langchain? Step-by-Step Guide appeared first on MarkTechPost.

Credit: Source link

ShareTweetSendSharePin

Related Posts

Microsoft Turns to Bond Market as AI Spending Grows
AI & Technology

Microsoft Turns to Bond Market as AI Spending Grows

November 3, 2026
Driverless Trucks Can Double Profits, Says Aurora CEO
AI & Technology

Driverless Trucks Can Double Profits, Says Aurora CEO

November 3, 2026
Google Sales Miss Reignites AI Fears, Microsoft Eyes B Debt Offering
AI & Technology

Google Sales Miss Reignites AI Fears, Microsoft Eyes $25B Debt Offering

November 3, 2026
AI to Drive 40% Growth for AWS: CEO Garman
AI & Technology

AI to Drive 40% Growth for AWS: CEO Garman

November 3, 2026
Next Post
Meet the Press NOW — Sept. 22

Meet the Press NOW — Sept. 22

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Search

No Result
View All Result
Thousands arrested as student protests escalate into violence

Thousands arrested as student protests escalate into violence

November 1, 2026
Bitdefender Launches GravityZone Exposure Management to Map Attack Paths and Reduce Risk – Unite.AI

Bitdefender Launches GravityZone Exposure Management to Map Attack Paths and Reduce Risk – Unite.AI

October 27, 2026
ClearPoint Neuro, Inc. (CLPT) Q3 2026 Earnings Call Transcript

ClearPoint Neuro, Inc. (CLPT) Q3 2026 Earnings Call Transcript

October 29, 2026

About

Learn more

Our Services

Legal

Privacy Policy

Terms of Use

Bloggers

Learn more

Article Links

Contact

Advertise

Ask us anything

©2020- TradePoint.io - All rights reserved!

Tradepoint.io, being just a publishing and technology platform, is not a registered broker-dealer or investment adviser. So we do not provide investment advice. Rather, brokerage services are provided to clients of Tradepoint.io by independent SEC-registered broker-dealers and members of FINRA/SIPC. Every form of investing carries some risk and past performance is not a guarantee of future results. “Tradepoint.io“, “Instant Investing” and “My Trading Tools” are registered trademarks of Apperbuild, LLC.

This website is operated by Apperbuild, LLC. We have no link to any brokerage firm and we do not provide investment advice. Every information and resource we provide is solely for the education of our readers. © 2020 Apperbuild, LLC. All rights reserved.

No Result
View All Result
  • Main
  • AI & Technology
  • Stock Charts
  • Market & News
  • Business
  • Finance Tips
  • Trade Tube
  • Blog
  • Shop

© 2023 - TradePoint.io - All Rights Reserved!