!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/)
                
                *   [Select by length](/v0.1/docs/modules/model_io/prompts/example_selector_types/length_based/)
                *   [Select by similarity](/v0.1/docs/modules/model_io/prompts/example_selector_types/similarity/)
            *   [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/)
*   [Example selectors](/v0.1/docs/modules/model_io/prompts/example_selector_types/)
*   Select by similarity

On this page

Select by similarity
====================

This object selects examples based on similarity to the inputs. It does this by finding the examples with the embeddings that have the greatest cosine similarity with the inputs.

The fields of the examples object will be used as parameters to format the `examplePrompt` passed to the `FewShotPromptTemplate`. Each example should therefore contain all required fields for the example prompt you are using.

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 @langchain/community

    yarn add @langchain/openai @langchain/community

    pnpm add @langchain/openai @langchain/community

    import { OpenAIEmbeddings } from "@langchain/openai";import { HNSWLib } from "@langchain/community/vectorstores/hnswlib";import { PromptTemplate, FewShotPromptTemplate } from "@langchain/core/prompts";import { SemanticSimilarityExampleSelector } from "@langchain/core/example_selectors";// Create a prompt template that will be used to format the examples.const examplePrompt = PromptTemplate.fromTemplate(  "Input: {input}\nOutput: {output}");// Create a SemanticSimilarityExampleSelector that will be used to select the examples.const exampleSelector = await SemanticSimilarityExampleSelector.fromExamples(  [    { input: "happy", output: "sad" },    { input: "tall", output: "short" },    { input: "energetic", output: "lethargic" },    { input: "sunny", output: "gloomy" },    { input: "windy", output: "calm" },  ],  new OpenAIEmbeddings(),  HNSWLib,  { k: 1 });// Create a FewShotPromptTemplate that will use the example selector.const dynamicPrompt = new FewShotPromptTemplate({  // We provide an ExampleSelector instead of examples.  exampleSelector,  examplePrompt,  prefix: "Give the antonym of every input",  suffix: "Input: {adjective}\nOutput:",  inputVariables: ["adjective"],});// Input is about the weather, so should select eg. the sunny/gloomy exampleconsole.log(await dynamicPrompt.format({ adjective: "rainy" }));/*  Give the antonym of every input  Input: sunny  Output: gloomy  Input: rainy  Output:*/// Input is a measurement, so should select the tall/short exampleconsole.log(await dynamicPrompt.format({ adjective: "large" }));/*  Give the antonym of every input  Input: tall  Output: short  Input: large  Output:*/

#### API Reference:

*   [OpenAIEmbeddings](https://api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai`
*   [HNSWLib](https://api.js.langchain.com/classes/langchain_community_vectorstores_hnswlib.HNSWLib.html) from `@langchain/community/vectorstores/hnswlib`
*   [PromptTemplate](https://api.js.langchain.com/classes/langchain_core_prompts.PromptTemplate.html) from `@langchain/core/prompts`
*   [FewShotPromptTemplate](https://api.js.langchain.com/classes/langchain_core_prompts.FewShotPromptTemplate.html) from `@langchain/core/prompts`
*   [SemanticSimilarityExampleSelector](https://api.js.langchain.com/classes/langchain_core_example_selectors.SemanticSimilarityExampleSelector.html) from `@langchain/core/example_selectors`

By default, each field in the examples object is concatenated together, embedded, and stored in the vectorstore for later similarity search against user queries.

If you only want to embed specific keys (e.g., you only want to search for examples that have a similar query to the one the user provides), you can pass an `inputKeys` array in the final `options` parameter.

Loading from an existing vectorstore[​](#loading-from-an-existing-vectorstore "Direct link to Loading from an existing vectorstore")
------------------------------------------------------------------------------------------------------------------------------------

You can also use a pre-initialized vector store by passing an instance to the `SemanticSimilarityExampleSelector` constructor directly, as shown below. You can also add more examples via the `addExample` method:

    // Ephemeral, in-memory vector store for demo purposesimport { MemoryVectorStore } from "langchain/vectorstores/memory";import { OpenAIEmbeddings, ChatOpenAI } from "@langchain/openai";import { PromptTemplate, FewShotPromptTemplate } from "@langchain/core/prompts";import { SemanticSimilarityExampleSelector } from "@langchain/core/example_selectors";const embeddings = new OpenAIEmbeddings();const memoryVectorStore = new MemoryVectorStore(embeddings);const examples = [  {    query: "healthy food",    output: `galbi`,  },  {    query: "healthy food",    output: `schnitzel`,  },  {    query: "foo",    output: `bar`,  },];const exampleSelector = new SemanticSimilarityExampleSelector({  vectorStore: memoryVectorStore,  k: 2,  // Only embed the "query" key of each example  inputKeys: ["query"],});for (const example of examples) {  // Format and add an example to the underlying vector store  await exampleSelector.addExample(example);}// Create a prompt template that will be used to format the examples.const examplePrompt = PromptTemplate.fromTemplate(`<example>  <user_input>    {query}  </user_input>  <output>    {output}  </output></example>`);// Create a FewShotPromptTemplate that will use the example selector.const dynamicPrompt = new FewShotPromptTemplate({  // We provide an ExampleSelector instead of examples.  exampleSelector,  examplePrompt,  prefix: `Answer the user's question, using the below examples as reference:`,  suffix: "User question: {query}",  inputVariables: ["query"],});const formattedValue = await dynamicPrompt.format({  query: "What is a healthy food?",});console.log(formattedValue);/*Answer the user's question, using the below examples as reference:<example>  <user_input>    healthy  </user_input>  <output>    galbi  </output></example><example>  <user_input>    healthy  </user_input>  <output>    schnitzel  </output></example>User question: What is a healthy food?*/const model = new ChatOpenAI({});const chain = dynamicPrompt.pipe(model);const result = await chain.invoke({ query: "What is a healthy food?" });console.log(result);/*  AIMessage {    content: 'A healthy food can be galbi or schnitzel.',    additional_kwargs: { function_call: undefined }  }*/

#### API Reference:

*   [MemoryVectorStore](https://api.js.langchain.com/classes/langchain_vectorstores_memory.MemoryVectorStore.html) from `langchain/vectorstores/memory`
*   [OpenAIEmbeddings](https://api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai`
*   [ChatOpenAI](https://api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html) from `@langchain/openai`
*   [PromptTemplate](https://api.js.langchain.com/classes/langchain_core_prompts.PromptTemplate.html) from `@langchain/core/prompts`
*   [FewShotPromptTemplate](https://api.js.langchain.com/classes/langchain_core_prompts.FewShotPromptTemplate.html) from `@langchain/core/prompts`
*   [SemanticSimilarityExampleSelector](https://api.js.langchain.com/classes/langchain_core_example_selectors.SemanticSimilarityExampleSelector.html) from `@langchain/core/example_selectors`

Metadata filtering[​](#metadata-filtering "Direct link to Metadata filtering")
------------------------------------------------------------------------------

When adding examples, each field is available as metadata in the produced document. If you would like further control over your search space, you can add extra fields to your examples and pass a `filter` parameter when initializing your selector:

    // Ephemeral, in-memory vector store for demo purposesimport { MemoryVectorStore } from "langchain/vectorstores/memory";import { OpenAIEmbeddings, ChatOpenAI } from "@langchain/openai";import { PromptTemplate, FewShotPromptTemplate } from "@langchain/core/prompts";import { Document } from "@langchain/core/documents";import { SemanticSimilarityExampleSelector } from "@langchain/core/example_selectors";const embeddings = new OpenAIEmbeddings();const memoryVectorStore = new MemoryVectorStore(embeddings);const examples = [  {    query: "healthy food",    output: `lettuce`,    food_type: "vegetable",  },  {    query: "healthy food",    output: `schnitzel`,    food_type: "veal",  },  {    query: "foo",    output: `bar`,    food_type: "baz",  },];const exampleSelector = new SemanticSimilarityExampleSelector({  vectorStore: memoryVectorStore,  k: 2,  // Only embed the "query" key of each example  inputKeys: ["query"],  // Filter type will depend on your specific vector store.  // See the section of the docs for the specific vector store you are using.  filter: (doc: Document) => doc.metadata.food_type === "vegetable",});for (const example of examples) {  // Format and add an example to the underlying vector store  await exampleSelector.addExample(example);}// Create a prompt template that will be used to format the examples.const examplePrompt = PromptTemplate.fromTemplate(`<example>  <user_input>    {query}  </user_input>  <output>    {output}  </output></example>`);// Create a FewShotPromptTemplate that will use the example selector.const dynamicPrompt = new FewShotPromptTemplate({  // We provide an ExampleSelector instead of examples.  exampleSelector,  examplePrompt,  prefix: `Answer the user's question, using the below examples as reference:`,  suffix: "User question:\n{query}",  inputVariables: ["query"],});const model = new ChatOpenAI({});const chain = dynamicPrompt.pipe(model);const result = await chain.invoke({  query: "What is exactly one type of healthy food?",});console.log(result);/*  AIMessage {    content: 'One type of healthy food is lettuce.',    additional_kwargs: { function_call: undefined }  }*/

#### API Reference:

*   [MemoryVectorStore](https://api.js.langchain.com/classes/langchain_vectorstores_memory.MemoryVectorStore.html) from `langchain/vectorstores/memory`
*   [OpenAIEmbeddings](https://api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai`
*   [ChatOpenAI](https://api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html) from `@langchain/openai`
*   [PromptTemplate](https://api.js.langchain.com/classes/langchain_core_prompts.PromptTemplate.html) from `@langchain/core/prompts`
*   [FewShotPromptTemplate](https://api.js.langchain.com/classes/langchain_core_prompts.FewShotPromptTemplate.html) from `@langchain/core/prompts`
*   [Document](https://api.js.langchain.com/classes/langchain_core_documents.Document.html) from `@langchain/core/documents`
*   [SemanticSimilarityExampleSelector](https://api.js.langchain.com/classes/langchain_core_example_selectors.SemanticSimilarityExampleSelector.html) from `@langchain/core/example_selectors`

Custom vectorstore retrievers[​](#custom-vectorstore-retrievers "Direct link to Custom vectorstore retrievers")
---------------------------------------------------------------------------------------------------------------

You can also pass a vectorstore retriever instead of a vectorstore. One way this could be useful is if you want to use retrieval besides similarity search such as maximal marginal relevance:

    /* eslint-disable @typescript-eslint/no-non-null-assertion */// Requires a vectorstore that supports maximal marginal relevance searchimport { Pinecone } from "@pinecone-database/pinecone";import { OpenAIEmbeddings, ChatOpenAI } from "@langchain/openai";import { PineconeStore } from "@langchain/pinecone";import { PromptTemplate, FewShotPromptTemplate } from "@langchain/core/prompts";import { SemanticSimilarityExampleSelector } from "@langchain/core/example_selectors";const pinecone = new Pinecone();const pineconeIndex = pinecone.Index(process.env.PINECONE_INDEX!);const pineconeVectorstore = await PineconeStore.fromExistingIndex(  new OpenAIEmbeddings(),  { pineconeIndex });const pineconeMmrRetriever = pineconeVectorstore.asRetriever({  searchType: "mmr",  k: 2,});const examples = [  {    query: "healthy food",    output: `lettuce`,    food_type: "vegetable",  },  {    query: "healthy food",    output: `schnitzel`,    food_type: "veal",  },  {    query: "foo",    output: `bar`,    food_type: "baz",  },];const exampleSelector = new SemanticSimilarityExampleSelector({  vectorStoreRetriever: pineconeMmrRetriever,  // Only embed the "query" key of each example  inputKeys: ["query"],});for (const example of examples) {  // Format and add an example to the underlying vector store  await exampleSelector.addExample(example);}// Create a prompt template that will be used to format the examples.const examplePrompt = PromptTemplate.fromTemplate(`<example>  <user_input>    {query}  </user_input>  <output>    {output}  </output></example>`);// Create a FewShotPromptTemplate that will use the example selector.const dynamicPrompt = new FewShotPromptTemplate({  // We provide an ExampleSelector instead of examples.  exampleSelector,  examplePrompt,  prefix: `Answer the user's question, using the below examples as reference:`,  suffix: "User question:\n{query}",  inputVariables: ["query"],});const model = new ChatOpenAI({});const chain = dynamicPrompt.pipe(model);const result = await chain.invoke({  query: "What is exactly one type of healthy food?",});console.log(result);/*  AIMessage {    content: 'lettuce.',    additional_kwargs: { function_call: undefined }  }*/

#### API Reference:

*   [OpenAIEmbeddings](https://api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai`
*   [ChatOpenAI](https://api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html) from `@langchain/openai`
*   [PineconeStore](https://api.js.langchain.com/classes/langchain_pinecone.PineconeStore.html) from `@langchain/pinecone`
*   [PromptTemplate](https://api.js.langchain.com/classes/langchain_core_prompts.PromptTemplate.html) from `@langchain/core/prompts`
*   [FewShotPromptTemplate](https://api.js.langchain.com/classes/langchain_core_prompts.FewShotPromptTemplate.html) from `@langchain/core/prompts`
*   [SemanticSimilarityExampleSelector](https://api.js.langchain.com/classes/langchain_core_example_selectors.SemanticSimilarityExampleSelector.html) from `@langchain/core/example_selectors`

* * *

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

[

Previous

Select by length

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

Next

Few Shot Prompt Templates

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

*   [Loading from an existing vectorstore](#loading-from-an-existing-vectorstore)
*   [Metadata filtering](#metadata-filtering)
*   [Custom vectorstore retrievers](#custom-vectorstore-retrievers)

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.