!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

On this page

Refine
======

The refine documents chain constructs a response by looping over the input documents and iteratively updating its answer. For each document, it passes all non-document inputs, the current document, and the latest intermediate answer to an LLM chain to get a new answer.

Since the Refine chain only passes a single document to the LLM at a time, it is well-suited for tasks that require analyzing more documents than can fit in the model's context. The obvious tradeoff is that this chain will make far more LLM calls than, for example, the Stuff documents chain. There are also certain tasks which are difficult to accomplish iteratively. For example, the Refine chain can perform poorly when documents frequently cross-reference one another or when a task requires detailed information from many documents.

![refine_diagram](/v0.1/assets/images/refine-a70f30dd7ada6fe5e3fcc40dd70de037.jpg)

Here's how it looks in practice:

tip

See [this section for general instructions on installing integration packages](/v0.1/docs/get_started/installation/#installing-integration-packages).

*   npm
*   Yarn
*   pnpm

    npm install @langchain/openai

    yarn add @langchain/openai

    pnpm add @langchain/openai

    import { loadQARefineChain } from "langchain/chains";import { OpenAI, OpenAIEmbeddings } from "@langchain/openai";import { TextLoader } from "langchain/document_loaders/fs/text";import { MemoryVectorStore } from "langchain/vectorstores/memory";// Create the models and chainconst embeddings = new OpenAIEmbeddings();const model = new OpenAI({ temperature: 0 });const chain = loadQARefineChain(model);// Load the documents and create the vector storeconst loader = new TextLoader("./state_of_the_union.txt");const docs = await loader.loadAndSplit();const store = await MemoryVectorStore.fromDocuments(docs, embeddings);// Select the relevant documentsconst question = "What did the president say about Justice Breyer";const relevantDocs = await store.similaritySearch(question);// Call the chainconst res = await chain.invoke({  input_documents: relevantDocs,  question,});console.log(res);/*{  output_text: '\n' +    '\n' +    "The president said that Justice Stephen Breyer has dedicated his life to serve this country and thanked him for his service. He also mentioned that Judge Ketanji Brown Jackson will continue Justice Breyer's legacy of excellence, and that the constitutional right affirmed in Roe v. Wade—standing precedent for half a century—is under attack as never before. He emphasized the importance of protecting access to health care, preserving a woman's right to choose, and advancing maternal health care in America. He also expressed his support for the LGBTQ+ community, and his commitment to protecting their rights, including offering a Unity Agenda for the Nation to beat the opioid epidemic, increase funding for prevention, treatment, harm reduction, and recovery, and strengthen the Violence Against Women Act."}*/

#### API Reference:

*   [loadQARefineChain](https://api.js.langchain.com/functions/langchain_chains.loadQARefineChain.html) from `langchain/chains`
*   [OpenAI](https://api.js.langchain.com/classes/langchain_openai.OpenAI.html) from `@langchain/openai`
*   [OpenAIEmbeddings](https://api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai`
*   [TextLoader](https://api.js.langchain.com/classes/langchain_document_loaders_fs_text.TextLoader.html) from `langchain/document_loaders/fs/text`
*   [MemoryVectorStore](https://api.js.langchain.com/classes/langchain_vectorstores_memory.MemoryVectorStore.html) from `langchain/vectorstores/memory`

Prompt customization[​](#prompt-customization "Direct link to Prompt customization")
------------------------------------------------------------------------------------

You may want to tweak the behavior of a step by changing the prompt. Here's an example of how to do that:

    import { loadQARefineChain } from "langchain/chains";import { OpenAI, OpenAIEmbeddings } from "@langchain/openai";import { TextLoader } from "langchain/document_loaders/fs/text";import { MemoryVectorStore } from "langchain/vectorstores/memory";import { PromptTemplate } from "@langchain/core/prompts";export const questionPromptTemplateString = `Context information is below.---------------------{context}---------------------Given the context information and no prior knowledge, answer the question: {question}`;const questionPrompt = new PromptTemplate({  inputVariables: ["context", "question"],  template: questionPromptTemplateString,});const refinePromptTemplateString = `The original question is as follows: {question}We have provided an existing answer: {existing_answer}We have the opportunity to refine the existing answer(only if needed) with some more context below.------------{context}------------Given the new context, refine the original answer to better answer the question.You must provide a response, either original answer or refined answer.`;const refinePrompt = new PromptTemplate({  inputVariables: ["question", "existing_answer", "context"],  template: refinePromptTemplateString,});// Create the models and chainconst embeddings = new OpenAIEmbeddings();const model = new OpenAI({ temperature: 0 });const chain = loadQARefineChain(model, {  questionPrompt,  refinePrompt,});// Load the documents and create the vector storeconst loader = new TextLoader("./state_of_the_union.txt");const docs = await loader.loadAndSplit();const store = await MemoryVectorStore.fromDocuments(docs, embeddings);// Select the relevant documentsconst question = "What did the president say about Justice Breyer";const relevantDocs = await store.similaritySearch(question);// Call the chainconst res = await chain.invoke({  input_documents: relevantDocs,  question,});console.log(res);/*{  output_text: '\n' +    '\n' +    "The president said that Justice Stephen Breyer has dedicated his life to serve this country and thanked him for his service. He also mentioned that Judge Ketanji Brown Jackson will continue Justice Breyer's legacy of excellence, and that the constitutional right affirmed in Roe v. Wade—standing precedent for half a century—is under attack as never before. He emphasized the importance of protecting access to health care, preserving a woman's right to choose, and advancing maternal health care in America. He also expressed his support for the LGBTQ+ community, and his commitment to protecting their rights, including offering a Unity Agenda for the Nation to beat the opioid epidemic, increase funding for prevention, treatment, harm reduction, and recovery, and strengthen the Violence Against Women Act."}*/

#### API Reference:

*   [loadQARefineChain](https://api.js.langchain.com/functions/langchain_chains.loadQARefineChain.html) from `langchain/chains`
*   [OpenAI](https://api.js.langchain.com/classes/langchain_openai.OpenAI.html) from `@langchain/openai`
*   [OpenAIEmbeddings](https://api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai`
*   [TextLoader](https://api.js.langchain.com/classes/langchain_document_loaders_fs_text.TextLoader.html) from `langchain/document_loaders/fs/text`
*   [MemoryVectorStore](https://api.js.langchain.com/classes/langchain_vectorstores_memory.MemoryVectorStore.html) from `langchain/vectorstores/memory`
*   [PromptTemplate](https://api.js.langchain.com/classes/langchain_core_prompts.PromptTemplate.html) from `@langchain/core/prompts`

* * *

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

*   [Prompt customization](#prompt-customization)

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.