large-language-modelpy-langchainchromadb

Debugging Dynamic Few Shot Langchain Code


# Import necessary modules and classes from langchain_community and langchain_core
from langchain_community.vectorstores import Chroma
from langchain_core.example_selectors import SemanticSimilarityExampleSelector
from langchain_openai import OpenAIEmbeddings   ## paid
from langchain.embeddings import HuggingFaceEmbeddings   #free


## setup vector db
# Create an instance of Chroma vector store
vectorstore = Chroma()

# Delete any existing collection in the vector store
# vectorstore.delete_collection()

# Create a SemanticSimilarityExampleSelector instance using examples, OpenAI embeddings, and the vector store
example_selector = SemanticSimilarityExampleSelector.from_examples(
    examples,  # List of example queries and inputs
    HuggingFaceEmbeddings(), #HuggingFaceEmbeddings() OpenAIEmbeddings() # OpenAI Embeddings for generating vector representations
    vectorstore,  # Chroma vector store for storing and querying vector representations
    k=2,  # Number of similar examples to retrieve
    input_keys=["input"],  # Define the input keys to consider for semantic similarity
)

This is my code, its showing an error "name 'examples' is not defined". How to solve it ?

I tried to debug, but i failed. Could anyone hepl me out.


Solution

  • Does examples get defined? Here's an example of SemanticSimilarityExampleSelector.from_examples

    example_prompt = PromptTemplate(
        input_variables=["input", "output"],
        template="Input: {input}\nOutput: {output}",
    )
    
    # Examples of a pretend task of creating antonyms.
    examples = [
        {"input": "happy", "output": "sad"},
        {"input": "tall", "output": "short"},
        {"input": "energetic", "output": "lethargic"},
        {"input": "sunny", "output": "gloomy"},
        {"input": "windy", "output": "calm"},
    ]
    
    example_selector = SemanticSimilarityExampleSelector.from_examples(
        # The list of examples available to select from.
        examples,
        # The embedding class used to produce embeddings which are used to measure semantic similarity.
        OpenAIEmbeddings(),
        # The VectorStore class that is used to store the embeddings and do a similarity search over.
        Chroma,
        # The number of examples to produce.
        k=1,
    )
    similar_prompt = FewShotPromptTemplate(
        # We provide an ExampleSelector instead of examples.
        example_selector=example_selector,
        example_prompt=example_prompt,
        prefix="Give the antonym of every input",
        suffix="Input: {adjective}\nOutput:",
        input_variables=["adjective"],
    )
    

    Take a look at the reference > https://python.langchain.com/v0.2/docs/how_to/example_selectors_mmr/