!function(){function t(t){document.documentElement.setAttribute("data-theme",t)}var e=function(){var t=null;try{t=new URLSearchParams(window.location.search).get("docusaurus-theme")}catch(t){}return t}()||function(){var t=null;try{t=localStorage.getItem("theme")}catch(t){}return t}();t(null!==e?e:"light")}(),document.documentElement.setAttribute("data-announcement-bar-initially-dismissed",function(){try{return"true"===localStorage.getItem("docusaurus.announcement.dismiss")}catch(t){}return!1}())

[Skip to main content](#__docusaurus_skipToContent_fallback)

LangChain v0.2 is coming soon! Preview the new docs [here](/v0.2/docs/introduction/).

[

![🦜️🔗 Langchain](/v0.1/img/brand/wordmark.png)![🦜️🔗 Langchain](/v0.1/img/brand/wordmark-dark.png)

](/v0.1/)[Docs](/v0.1/docs/get_started/introduction/)[Use cases](/v0.1/docs/use_cases/)[Integrations](/v0.1/docs/integrations/platforms/)[API Reference](https://api.js.langchain.com)

[More](#)

*   [People](/v0.1/docs/people/)
*   [Community](/v0.1/docs/community/)
*   [Tutorials](/v0.1/docs/additional_resources/tutorials/)
*   [Contributing](/v0.1/docs/contributing/)

[v0.1](#)

*   [v0.2](https://js.langchain.com/v0.2/docs/introduction)
*   [v0.1](/v0.1/docs/get_started/introduction/)

[🦜🔗](#)

*   [LangSmith](https://smith.langchain.com)
*   [LangSmith Docs](https://docs.smith.langchain.com)
*   [LangChain Hub](https://smith.langchain.com/hub)
*   [LangServe](https://github.com/langchain-ai/langserve)
*   [Python Docs](https://python.langchain.com/)

[Chat](https://chatjs.langchain.com)[](https://github.com/langchain-ai/langchainjs)

Search

*   [Use cases](/v0.1/docs/use_cases/)
    
    *   [SQL](/v0.1/docs/use_cases/sql/)
        
    *   [Chatbots](/v0.1/docs/use_cases/chatbots/)
        
    *   [Extraction](/v0.1/docs/use_cases/extraction/)
        
    *   [Query Analysis](/v0.1/docs/use_cases/query_analysis/)
        
    *   [Q&A with RAG](/v0.1/docs/use_cases/question_answering/)
        
        *   [Quickstart](/v0.1/docs/use_cases/question_answering/quickstart/)
        *   [Per-User Retrieval](/v0.1/docs/use_cases/question_answering/per_user/)
        *   [Add chat history](/v0.1/docs/use_cases/question_answering/chat_history/)
        *   [Citations](/v0.1/docs/use_cases/question_answering/citations/)
        *   [Using agents](/v0.1/docs/use_cases/question_answering/conversational_retrieval_agents/)
        *   [Using local models](/v0.1/docs/use_cases/question_answering/local_retrieval_qa/)
        *   [Returning sources](/v0.1/docs/use_cases/question_answering/sources/)
        *   [Streaming](/v0.1/docs/use_cases/question_answering/streaming/)
    *   [Tool use](/v0.1/docs/use_cases/tool_use/)
        
    *   [Interacting with APIs](/v0.1/docs/use_cases/api/)
    *   [Tabular Question Answering](/v0.1/docs/use_cases/tabular/)
    *   [Graphs](/v0.1/docs/use_cases/graph/)
        
    *   [Summarization](/v0.1/docs/use_cases/summarization/)
    *   [Agent Simulations](/v0.1/docs/use_cases/agent_simulations/)
        
    *   [Autonomous Agents](/v0.1/docs/use_cases/autonomous_agents/)
        
    *   [Code Understanding](/v0.1/docs/use_cases/code_understanding/)
    *   [Audio/Video Structured Extraction](/v0.1/docs/use_cases/media/)

*   [](/v0.1/)
*   [Use cases](/v0.1/docs/use_cases/)
*   [Q&A with RAG](/v0.1/docs/use_cases/question_answering/)
*   Using local models

On this page

Using local models
==================

The popularity of projects like [PrivateGPT](https://github.com/imartinez/privateGPT), [llama.cpp](https://github.com/ggerganov/llama.cpp), and [Ollama](https://github.com/ollama/ollama) underscore the importance of running LLMs locally.

LangChain has [integrations](/v0.1/docs/integrations/platforms/) with many open-source LLMs that can be run locally.

For example, here we show how to run `OllamaEmbeddings` or `LLaMA2` locally (e.g., on your laptop) using local embeddings and a local LLM.

Document Loading[​](#document-loading "Direct link to Document Loading")
------------------------------------------------------------------------

First, install packages needed for local embeddings and vector storage.

Setup[​](#setup "Direct link to Setup")
---------------------------------------

### Dependencies[​](#dependencies "Direct link to Dependencies")

We’ll use the following packages:

    npm install --save langchain @langchain/community cheerio

### LangSmith[​](#langsmith "Direct link to LangSmith")

Many of the applications you build with LangChain will contain multiple steps with multiple invocations of LLM calls. As these applications get more and more complex, it becomes crucial to be able to inspect what exactly is going on inside your chain or agent. The best way to do this is with [LangSmith](https://smith.langchain.com/).

Note that LangSmith is not needed, but it is helpful. If you do want to use LangSmith, after you sign up at the link above, make sure to set your environment variables to start logging traces:

    export LANGCHAIN_TRACING_V2=trueexport LANGCHAIN_API_KEY=YOUR_KEY

### Initial setup[​](#initial-setup "Direct link to Initial setup")

Load and split an example document.

We’ll use a blog post on agents as an example.

    import "cheerio";import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";import { CheerioWebBaseLoader } from "langchain/document_loaders/web/cheerio";

    const loader = new CheerioWebBaseLoader(  "https://lilianweng.github.io/posts/2023-06-23-agent/");const docs = await loader.load();const textSplitter = new RecursiveCharacterTextSplitter({  chunkSize: 500,  chunkOverlap: 0,});const allSplits = await textSplitter.splitDocuments(docs);console.log(allSplits.length);

    146

Next, we’ll use `OllamaEmbeddings` for our local embeddings. Follow [these instructions](https://github.com/ollama/ollama) to set up and run a local Ollama instance.

    import { OllamaEmbeddings } from "@langchain/community/embeddings/ollama";import { MemoryVectorStore } from "langchain/vectorstores/memory";const embeddings = new OllamaEmbeddings();const vectorStore = await MemoryVectorStore.fromDocuments(  allSplits,  embeddings);

Test similarity search is working with our local embeddings.

    const question = "What are the approaches to Task Decomposition?";const docs = await vectorStore.similaritySearch(question);console.log(docs.length);

    4

Model[​](#model "Direct link to Model")
---------------------------------------

### LLaMA2[​](#llama2 "Direct link to LLaMA2")

For local LLMs we’ll use also use `ollama`.

    import { ChatOllama } from "@langchain/community/chat_models/ollama";const ollamaLlm = new ChatOllama({  baseUrl: "http://localhost:11434", // Default value  model: "llama2", // Default value});

    const response = await ollamaLlm.invoke(  "Simulate a rap battle between Stephen Colbert and John Oliver");console.log(response.content);

    [The stage is set for a fierce rap battle between two of the funniest men on television. Stephen Colbert and John Oliver are standing face to face, each with their own microphone and confident smirk on their face.]Stephen Colbert:Yo, John Oliver, I heard you've been talking smackAbout my show and my satire, saying it's all fakeBut let me tell you something, brother, I'm the real dealI've been making fun of politicians for years, with no concealJohn Oliver:Oh, Stephen, you think you're so clever and smartBut your jokes are stale and your delivery's a work of artYou're just a pale imitation of the real deal, Jon StewartI'm the one who's really making waves, while you're just a little birdStephen Colbert:Well, John, I may not be as loud as you, but I'm smarterMy satire is more subtle, and it goes right over their headsI'm the one who's been exposing the truth for yearsWhile you're just a British interloper, trying to steal the cheersJohn Oliver:Oh, Stephen, you may have your fans, but I've got the brainsMy show is more than just slapstick and silly jokes, it's got depth and gainsI'm the one who's really making a difference, while you're just a clownMy satire is more than just a joke, it's a call to action, and I've got the crown[The crowd cheers and chants as the two comedians continue their rap battle.]Stephen Colbert:You may have your fans, John, but I'm the king of satireI've been making fun of politicians for years, and I'm still standing tallMy jokes are clever and smart, while yours are just plain dumbI'm the one who's really in control, and you're just a pretender to the throne.John Oliver:Oh, Stephen, you may have your moment in the sunBut I'm the one who's really shining bright, and my star is just beginning to riseMy satire is more than just a joke, it's a call to action, and I've got the powerI'm the one who's really making a difference, and you're just a fleeting flower.[The crowd continues to cheer and chant as the two comedians continue their rap battle.]

See the LangSmith trace [here](https://smith.langchain.com/public/31c178b5-4bea-4105-88c3-7ec95325c817/r)

Using in a chain[​](#using-in-a-chain "Direct link to Using in a chain")
------------------------------------------------------------------------

We can create a summarization chain with either model by passing in the retrieved docs and a simple prompt.

It formats the prompt template using the input key values provided and passes the formatted string to `LLama-V2`, or another specified LLM.

    import { RunnableSequence } from "@langchain/core/runnables";import { StringOutputParser } from "@langchain/core/output_parsers";import { PromptTemplate } from "@langchain/core/prompts";import { createStuffDocumentsChain } from "langchain/chains/combine_documents";const prompt = PromptTemplate.fromTemplate(  "Summarize the main themes in these retrieved docs: {context}");const chain = await createStuffDocumentsChain({  llm: ollamaLlm,  outputParser: new StringOutputParser(),  prompt,});

    const question = "What are the approaches to Task Decomposition?";const docs = await vectorStore.similaritySearch(question);await chain.invoke({  context: docs,});

    "The main themes retrieved from the provided documents are:\n" +  "\n" +  "1. Sensory Memory: The ability to retain"... 1117 more characters

See the LangSmith trace [here](https://smith.langchain.com/public/47cf6c2a-3d86-4f2b-9a51-ee4663b19152/r)

Q&A[​](#qa "Direct link to Q&A")
--------------------------------

We can also use the LangChain Prompt Hub to store and fetch prompts that are model-specific.

Let’s try with a default RAG prompt, [here](https://smith.langchain.com/hub/rlm/rag-prompt).

    import { pull } from "langchain/hub";import { ChatPromptTemplate } from "@langchain/core/prompts";const ragPrompt = await pull<ChatPromptTemplate>("rlm/rag-prompt");const chain = await createStuffDocumentsChain({  llm: ollamaLlm,  outputParser: new StringOutputParser(),  prompt: ragPrompt,});

    await chain.invoke({ context: docs, question });

    "Task decomposition is a crucial step in breaking down complex problems into manageable parts for eff"... 1095 more characters

See the LangSmith trace [here](https://smith.langchain.com/public/dd3a189b-53a1-4f31-9766-244cd04ad1f7/r)

Q&A with retrieval[​](#qa-with-retrieval "Direct link to Q&A with retrieval")
-----------------------------------------------------------------------------

Instead of manually passing in docs, we can automatically retrieve them from our vector store based on the user question.

This will use a QA default prompt and will retrieve from the vectorDB.

    import {  RunnablePassthrough,  RunnableSequence,} from "@langchain/core/runnables";import { formatDocumentsAsString } from "langchain/util/document";const retriever = vectorStore.asRetriever();const qaChain = RunnableSequence.from([  {    context: (input: { question: string }, callbacks) => {      const retrieverAndFormatter = retriever.pipe(formatDocumentsAsString);      return retrieverAndFormatter.invoke(input.question, callbacks);    },    question: new RunnablePassthrough(),  },  ragPrompt,  ollamaLlm,  new StringOutputParser(),]);await qaChain.invoke({ question });

    "Based on the context provided, I understand that you are asking me to answer a question related to m"... 948 more characters

See the LangSmith trace [here](https://smith.langchain.com/public/440e65ee-0301-42cf-afc9-f09cfb52cf64/r)

* * *

#### Help us out by providing feedback on this documentation page:

[

Previous

Using agents

](/v0.1/docs/use_cases/question_answering/conversational_retrieval_agents/)[

Next

Returning sources

](/v0.1/docs/use_cases/question_answering/sources/)

*   [Document Loading](#document-loading)
*   [Setup](#setup)
    *   [Dependencies](#dependencies)
    *   [LangSmith](#langsmith)
    *   [Initial setup](#initial-setup)
*   [Model](#model)
    *   [LLaMA2](#llama2)
*   [Using in a chain](#using-in-a-chain)
*   [Q&A](#qa)
*   [Q&A with retrieval](#qa-with-retrieval)

Community

*   [Discord](https://discord.gg/cU2adEyC7w)
*   [Twitter](https://twitter.com/LangChainAI)

GitHub

*   [Python](https://github.com/langchain-ai/langchain)
*   [JS/TS](https://github.com/langchain-ai/langchainjs)

More

*   [Homepage](https://langchain.com)
*   [Blog](https://blog.langchain.dev)

Copyright © 2024 LangChain, Inc.