!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

*   [Get started](/v0.1/docs/get_started/)
    
    *   [Introduction](/v0.1/docs/get_started/introduction/)
    *   [Installation](/v0.1/docs/get_started/installation/)
    *   [Quickstart](/v0.1/docs/get_started/quickstart/)
*   [LangChain Expression Language](/v0.1/docs/expression_language/)
    
    *   [Get started](/v0.1/docs/expression_language/get_started/)
    *   [Why use LCEL?](/v0.1/docs/expression_language/why/)
    *   [Interface](/v0.1/docs/expression_language/interface/)
    *   [Streaming](/v0.1/docs/expression_language/streaming/)
    *   [How to](/v0.1/docs/expression_language/how_to/routing/)
        
    *   [Cookbook](/v0.1/docs/expression_language/cookbook/)
        
    *   [LangChain Expression Language (LCEL)](/v0.1/docs/expression_language/)
*   [Modules](/v0.1/docs/modules/)
    
    *   [Model I/O](/v0.1/docs/modules/model_io/)
        
        *   [Quickstart](/v0.1/docs/modules/model_io/quick_start/)
        *   [Concepts](/v0.1/docs/modules/model_io/concepts/)
        *   [Prompts](/v0.1/docs/modules/model_io/prompts/)
            
            *   [Quick Start](/v0.1/docs/modules/model_io/prompts/quick_start/)
            *   [Example selectors](/v0.1/docs/modules/model_io/prompts/example_selector_types/)
                
            *   [Few Shot Prompt Templates](/v0.1/docs/modules/model_io/prompts/few_shot/)
            *   [Partial prompt templates](/v0.1/docs/modules/model_io/prompts/partial/)
            *   [Composition](/v0.1/docs/modules/model_io/prompts/pipeline/)
        *   [LLMs](/v0.1/docs/modules/model_io/llms/)
            
        *   [Chat Models](/v0.1/docs/modules/model_io/chat/)
            
        *   [Model I/O](/v0.1/docs/modules/model_io/)
        *   [Output Parsers](/v0.1/docs/modules/model_io/output_parsers/)
            
    *   [Retrieval](/v0.1/docs/modules/data_connection/)
        
    *   [Chains](/v0.1/docs/modules/chains/)
    *   [Agents](/v0.1/docs/modules/agents/)
        
    *   [More](/v0.1/docs/modules/memory/)
        
*   [Security](/v0.1/docs/security/)
*   [Guides](/v0.1/docs/guides/)
    
*   [Ecosystem](/v0.1/docs/ecosystem/)
    
*   [LangGraph](/v0.1/docs/langgraph/)
*   * * *
    

*   [](/v0.1/)
*   [Modules](/v0.1/docs/modules/)
*   [Model I/O](/v0.1/docs/modules/model_io/)
*   [Prompts](/v0.1/docs/modules/model_io/prompts/)
*   Few Shot Prompt Templates

On this page

Few Shot Prompt Templates
=========================

Few shot prompting is a prompting technique which provides the Large Language Model (LLM) with a list of examples, and then asks the LLM to generate some text following the lead of the examples provided.

An example of this is the following:

Say you want your LLM to respond in a specific format. You can few shot prompt the LLM with a list of question answer pairs so it knows what format to respond in.

    Respond to the users question in the with the following format:Question: What is your name?Answer: My name is John.Question: What is your age?Answer: I am 25 years old.Question: What is your favorite color?Answer:

Here we left the last `Answer:` undefined so the LLM can fill it in. The LLM will then generate the following:

    Answer: I don't have a favorite color; I don't have preferences.

### Use Case[​](#use-case "Direct link to Use Case")

In the following example we're few shotting the LLM to rephrase questions into more general queries.

We provide two sets of examples with specific questions, and rephrased general questions. The `FewShotChatMessagePromptTemplate` will use our examples and when `.format` is called, we'll see those examples formatted into a string we can pass to the LLM.

    import {  ChatPromptTemplate,  FewShotChatMessagePromptTemplate,} from "langchain/prompts";

    const examples = [  {    input: "Could the members of The Police perform lawful arrests?",    output: "what can the members of The Police do?",  },  {    input: "Jan Sindel's was born in what country?",    output: "what is Jan Sindel's personal history?",  },];const examplePrompt = ChatPromptTemplate.fromTemplate(`Human: {input}AI: {output}`);const fewShotPrompt = new FewShotChatMessagePromptTemplate({  examplePrompt,  examples,  inputVariables: [], // no input variables});

    const formattedPrompt = await fewShotPrompt.format({});console.log(formattedPrompt);

    [  HumanMessage {    lc_namespace: [ 'langchain', 'schema' ],    content: 'Human: Could the members of The Police perform lawful arrests?\n' +      'AI: what can the members of The Police do?',    additional_kwargs: {}  },  HumanMessage {    lc_namespace: [ 'langchain', 'schema' ],    content: "Human: Jan Sindel's was born in what country?\n" +      "AI: what is Jan Sindel's personal history?",    additional_kwargs: {}  }]

Then, if we use this with another question, the LLM will rephrase the question how we want.

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 { ChatOpenAI } from "@langchain/openai";

    const model = new ChatOpenAI({});const examples = [  {    input: "Could the members of The Police perform lawful arrests?",    output: "what can the members of The Police do?",  },  {    input: "Jan Sindel's was born in what country?",    output: "what is Jan Sindel's personal history?",  },];const examplePrompt = ChatPromptTemplate.fromTemplate(`Human: {input}AI: {output}`);const fewShotPrompt = new FewShotChatMessagePromptTemplate({  prefix:    "Rephrase the users query to be more general, using the following examples",  suffix: "Human: {input}",  examplePrompt,  examples,  inputVariables: ["input"],});const formattedPrompt = await fewShotPrompt.format({  input: "What's France's main city?",});const response = await model.invoke(formattedPrompt);console.log(response);

    AIMessage {  lc_namespace: [ 'langchain', 'schema' ],  content: 'What is the capital of France?',  additional_kwargs: { function_call: undefined }}

### Few Shotting With Functions[​](#few-shotting-with-functions "Direct link to Few Shotting With Functions")

You can also partial with a function. The use case for this is when you have a variable you know that you always want to fetch in a common way. A prime example of this is with date or time. Imagine you have a prompt which you always want to have the current date. You can't hard code it in the prompt, and passing it along with the other input variables can be tedious. In this case, it's very handy to be able to partial the prompt with a function that always returns the current date.

    const getCurrentDate = () => {  return new Date().toISOString();};const prompt = new FewShotChatMessagePromptTemplate({  template: "Tell me a {adjective} joke about the day {date}",  inputVariables: ["adjective", "date"],});const partialPrompt = await prompt.partial({  date: getCurrentDate,});const formattedPrompt = await partialPrompt.format({  adjective: "funny",});console.log(formattedPrompt);// Tell me a funny joke about the day 2023-07-13T00:54:59.287Z

### Few Shot vs Chat Few Shot[​](#few-shot-vs-chat-few-shot "Direct link to Few Shot vs Chat Few Shot")

The chat and non chat few shot prompt templates act in a similar way. The below example will demonstrate using chat and non chat, and the differences with their outputs.

    import {  FewShotPromptTemplate,  FewShotChatMessagePromptTemplate,} from "langchain/prompts";

    const examples = [  {    input: "Could the members of The Police perform lawful arrests?",    output: "what can the members of The Police do?",  },  {    input: "Jan Sindel's was born in what country?",    output: "what is Jan Sindel's personal history?",  },];const prompt = `Human: {input}AI: {output}`;const examplePromptTemplate = PromptTemplate.fromTemplate(prompt);const exampleChatPromptTemplate = ChatPromptTemplate.fromTemplate(prompt);const chatFewShotPrompt = new FewShotChatMessagePromptTemplate({  examplePrompt: exampleChatPromptTemplate,  examples,  inputVariables: [], // no input variables});const fewShotPrompt = new FewShotPromptTemplate({  examplePrompt: examplePromptTemplate,  examples,  inputVariables: [], // no input variables});

    console.log("Chat Few Shot: ", await chatFewShotPrompt.formatMessages({}));/**Chat Few Shot:  [  HumanMessage {    lc_namespace: [ 'langchain', 'schema' ],    content: 'Human: Could the members of The Police perform lawful arrests?\n' +      'AI: what can the members of The Police do?',    additional_kwargs: {}  },  HumanMessage {    lc_namespace: [ 'langchain', 'schema' ],    content: "Human: Jan Sindel's was born in what country?\n" +      "AI: what is Jan Sindel's personal history?",    additional_kwargs: {}  }] */

    console.log("Few Shot: ", await fewShotPrompt.formatPromptValue({}));/**Few Shot:Human: Could the members of The Police perform lawful arrests?AI: what can the members of The Police do?Human: Jan Sindel's was born in what country?AI: what is Jan Sindel's personal history? */

Here we can see the main distinctions between `FewShotChatMessagePromptTemplate` and `FewShotPromptTemplate`: input and output values.

`FewShotChatMessagePromptTemplate` works by taking in a list of `ChatPromptTemplate` for examples, and its output is a list of instances of `BaseMessage`.

On the other hand, `FewShotPromptTemplate` works by taking in a `PromptTemplate` for examples, and its output is a string.

With Non Chat Models[​](#with-non-chat-models "Direct link to With Non Chat Models")
------------------------------------------------------------------------------------

LangChain also provides a class for few shot prompt formatting for non chat models: `FewShotPromptTemplate`. The API is largely the same, but the output is formatted differently (chat messages vs strings).

### Partials With Functions[​](#partials-with-functions "Direct link to Partials With Functions")

    import {  ChatPromptTemplate,  FewShotChatMessagePromptTemplate,} from "langchain/prompts";

    const examplePrompt = PromptTemplate.fromTemplate("{foo}{bar}");const prompt = new FewShotPromptTemplate({  prefix: "{foo}{bar}",  examplePrompt,  inputVariables: ["foo", "bar"],});const partialPrompt = await prompt.partial({  foo: () => Promise.resolve("boo"),});const formatted = await partialPrompt.format({ bar: "baz" });console.log(formatted);

    boobaz\n

### With Functions and Example Selector[​](#with-functions-and-example-selector "Direct link to With Functions and Example Selector")

    import {  ChatPromptTemplate,  FewShotChatMessagePromptTemplate,} from "langchain/prompts";

    const examplePrompt = PromptTemplate.fromTemplate("An example about {x}");const exampleSelector = await LengthBasedExampleSelector.fromExamples(  [{ x: "foo" }, { x: "bar" }],  { examplePrompt, maxLength: 200 });const prompt = new FewShotPromptTemplate({  prefix: "{foo}{bar}",  exampleSelector,  examplePrompt,  inputVariables: ["foo", "bar"],});const partialPrompt = await prompt.partial({  foo: () => Promise.resolve("boo"),});const formatted = await partialPrompt.format({ bar: "baz" });console.log(formatted);

    boobazAn example about fooAn example about bar

* * *

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

[

Previous

Select by similarity

](/v0.1/docs/modules/model_io/prompts/example_selector_types/similarity/)[

Next

Partial prompt templates

](/v0.1/docs/modules/model_io/prompts/partial/)

*   [Use Case](#use-case)
*   [Few Shotting With Functions](#few-shotting-with-functions)
*   [Few Shot vs Chat Few Shot](#few-shot-vs-chat-few-shot)
*   [With Non Chat Models](#with-non-chat-models)
    *   [Partials With Functions](#partials-with-functions)
    *   [With Functions and Example Selector](#with-functions-and-example-selector)

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.