This guide will illustrate the process of building a custom example selector in LangChain.
How to Build a Custom Example Selector in LangChain?
Building these models or bots requires a lot of examples or datasets to train them in a natural language like English so the model can understand it. The developer doesn’t need to use all the examples at every point, so the example selector is responsible for choosing which one to use at this time. To learn how to build a custom example selector in LangChain, simply go through the following guide:
Step 1: Install LangChain
Firstly, get on with the process of building a custom example selector by installing the LangChain framework:
Step 2: Build a Custom Example Selector
After installing the LangChain framework, simply import the libraries to configure the example selector that must implement two methods such as “add_example” and “select_examples”:
from typing import Dict, List
import numpy as np
class CustomExampleSelector(BaseExampleSelector):
def __init__(self, examples: List[Dict[str, str]]):
self.examples = examples
def add_example(self, example: Dict[str, str]) -> None:
self.examples.append(example)
def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:
return np.random.choice(self.examples, size=2, replace=False)
Step 3: Using a Custom Example Selector
The following example creates an array of three locations with the same values and simply calls the example selector to get the location of the extracted values:
{"HI": "31"},
{"HI": "32"},
{"HI": "33"}
]
example_selector = CustomExampleSelector(examples)
example_selector.select_examples({"HI": "HI"})
Now, use the add_example to add another value to the existing array and then return the values with their locations:
example_selector.examples
example_selector.select_examples({"HI": "HI"})
That’s all about building and using custom example selectors in LangChain.
Conclusion
To build a custom example selector in LangChain, start the process by installing the LangChain framework and then import libraries. After that, configure the example selector containing the required methods such as “select_examples” and “add_example”. Create a dataset with values of different locations and then extract them using their values before adding new values. This guide has illustrated the process of building a custom example selector in LangChain.