LangChain Reference home pageLangChain ReferenceLangChain Reference
  • GitHub
  • Main Docs
Deep Agents
LangChain
LangGraph
Integrations
LangSmith
  • Overview
    • Overview
    • Caches
    • Callbacks
    • Documents
    • Document loaders
    • Embeddings
    • Exceptions
    • Language models
    • Serialization
    • Output parsers
    • Prompts
    • Rate limiters
    • Retrievers
    • Runnables
    • Utilities
    • Vector stores
    MCP Adapters
    Standard Tests
    Text Splitters
    ⌘I

    LangChain Assistant

    Ask a question to get started

    Enter to send•Shift+Enter new line

    Menu

    OverviewCachesCallbacksDocumentsDocument loadersEmbeddingsExceptionsLanguage modelsSerializationOutput parsersPromptsRate limitersRetrieversRunnablesUtilitiesVector stores
    MCP Adapters
    Standard Tests
    Text Splitters
    Language
    Theme
    Pythonlangchain-coreexample_selectorslength_basedLengthBasedExampleSelector
    Class●Since v0.1

    LengthBasedExampleSelector

    Select examples based on length.

    Copy
    LengthBasedExampleSelector()

    Bases

    BaseExampleSelectorBaseModel

    Example:

    from langchain_core.example_selectors import LengthBasedExampleSelector
    from langchain_core.prompts import PromptTemplate
    
    # Define examples
    examples = [
        {"input": "happy", "output": "sad"},
        {"input": "tall", "output": "short"},
        {"input": "fast", "output": "slow"},
    ]
    
    # Create prompt template
    example_prompt = PromptTemplate(
        input_variables=["input", "output"],
        template="Input: {input}\nOutput: {output}",
    )
    
    # Create selector with max length constraint
    selector = LengthBasedExampleSelector(
        examples=examples,
        example_prompt=example_prompt,
        max_length=50,  # Maximum prompt length
    )
    
    # Select examples for a new input
    selected = selector.select_examples({"input": "large", "output": "tiny"})
    # Returns examples that fit within max_length constraint

    Attributes

    attribute
    examples: list[dict]

    A list of the examples that the prompt template expects.

    attribute
    example_prompt: PromptTemplate

    Prompt template used to format the examples.

    attribute
    get_text_length: Callable[[str], int]

    Function to measure prompt length. Defaults to word count.

    attribute
    max_length: int

    Max length for the prompt, beyond which examples are cut.

    attribute
    example_text_lengths: list[int]

    Length of each example.

    Methods

    method
    add_example

    Add new example to list.

    method
    aadd_example

    Async add new example to list.

    method
    post_init

    Validate that the examples are formatted correctly.

    method
    select_examples

    Select which examples to use based on the input lengths.

    method
    aselect_examples

    Async select which examples to use based on the input lengths.

    View source on GitHub