Unnamed: 0
int64
0
4.66k
page content
stringlengths
23
2k
description
stringlengths
8
925
output
stringlengths
38
2.93k
0
Get started | 🦜�🔗 Langchain Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​ORetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreGet startedGet startedGet started with LangChain📄� IntroductionLangChain is a framework for developing applications powered by language models. It enables applications that:📄� InstallationOfficial release📄� QuickstartInstallationNextIntroductionCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
Get started with LangChain
Get started with LangChain ->: Get started | 🦜�🔗 Langchain Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​ORetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreGet startedGet startedGet started with LangChain📄� IntroductionLangChain is a framework for developing applications powered by language models. It enables applications that:📄� InstallationOfficial release📄� QuickstartInstallationNextIntroductionCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
1
Quickstart | 🦜️🔗 Langchain
Installation
Installation ->: Quickstart | 🦜️🔗 Langchain
2
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​ORetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreGet startedQuickstartOn this pageQuickstartInstallation​To install LangChain run:PipCondapip install langchainconda install langchain -c conda-forgeFor more details, see our Installation guide.Environment setup​Using LangChain will usually require integrations with one or more model providers, data stores, APIs, etc. For this example, we'll use OpenAI's model APIs.First we'll need to install their Python package:pip install openaiAccessing the API requires an API key, which you can get by creating an account and heading here. Once we have a key we'll want to set it as an environment variable by running:export OPENAI_API_KEY="..."If you'd prefer not to set an environment variable you can pass the key in directly via the openai_api_key named parameter when initiating the OpenAI LLM class:from langchain.llms import OpenAIllm = OpenAI(openai_api_key="...")Building an application​Now we can start building our language model application. LangChain provides many modules that can be used to build language model applications.
Installation
Installation ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​ORetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreGet startedQuickstartOn this pageQuickstartInstallation​To install LangChain run:PipCondapip install langchainconda install langchain -c conda-forgeFor more details, see our Installation guide.Environment setup​Using LangChain will usually require integrations with one or more model providers, data stores, APIs, etc. For this example, we'll use OpenAI's model APIs.First we'll need to install their Python package:pip install openaiAccessing the API requires an API key, which you can get by creating an account and heading here. Once we have a key we'll want to set it as an environment variable by running:export OPENAI_API_KEY="..."If you'd prefer not to set an environment variable you can pass the key in directly via the openai_api_key named parameter when initiating the OpenAI LLM class:from langchain.llms import OpenAIllm = OpenAI(openai_api_key="...")Building an application​Now we can start building our language model application. LangChain provides many modules that can be used to build language model applications.
3
Modules can be used as stand-alones in simple applications and they can be combined for more complex use cases.The most common and most important chain that LangChain helps create contains three things:LLM: The language model is the core reasoning engine here. In order to work with LangChain, you need to understand the different types of language models and how to work with them.Prompt Templates: This provides instructions to the language model. This controls what the language model outputs, so understanding how to construct prompts and different prompting strategies is crucial.Output Parsers: These translate the raw response from the LLM to a more workable format, making it easy to use the output downstream.In this getting started guide we will cover those three components by themselves, and then go over how to combine all of them. Understanding these concepts will set you up well for being able to use and customize LangChain applications. Most LangChain applications allow you to configure the LLM and/or the prompt used, so knowing how to take advantage of this will be a big enabler.LLMs‚ÄãThere are two types of language models, which in LangChain are called:LLMs: this is a language model which takes a string as input and returns a stringChatModels: this is a language model which takes a list of messages as input and returns a messageThe input/output for LLMs is simple and easy to understand - a string. But what about ChatModels? The input there is a list of ChatMessages, and the output is a single ChatMessage.
Installation
Installation ->: Modules can be used as stand-alones in simple applications and they can be combined for more complex use cases.The most common and most important chain that LangChain helps create contains three things:LLM: The language model is the core reasoning engine here. In order to work with LangChain, you need to understand the different types of language models and how to work with them.Prompt Templates: This provides instructions to the language model. This controls what the language model outputs, so understanding how to construct prompts and different prompting strategies is crucial.Output Parsers: These translate the raw response from the LLM to a more workable format, making it easy to use the output downstream.In this getting started guide we will cover those three components by themselves, and then go over how to combine all of them. Understanding these concepts will set you up well for being able to use and customize LangChain applications. Most LangChain applications allow you to configure the LLM and/or the prompt used, so knowing how to take advantage of this will be a big enabler.LLMs‚ÄãThere are two types of language models, which in LangChain are called:LLMs: this is a language model which takes a string as input and returns a stringChatModels: this is a language model which takes a list of messages as input and returns a messageThe input/output for LLMs is simple and easy to understand - a string. But what about ChatModels? The input there is a list of ChatMessages, and the output is a single ChatMessage.
4
A ChatMessage has two required components:content: This is the content of the message.role: This is the role of the entity from which the ChatMessage is coming from.LangChain provides several objects to easily distinguish between different roles:HumanMessage: A ChatMessage coming from a human/user.AIMessage: A ChatMessage coming from an AI/assistant.SystemMessage: A ChatMessage coming from the system.FunctionMessage: A ChatMessage coming from a function call.If none of those roles sound right, there is also a ChatMessage class where you can specify the role manually. For more information on how to use these different messages most effectively, see our prompting guide.LangChain provides a standard interface for both, but it's useful to understand this difference in order to construct prompts for a given language model. The standard interface that LangChain provides has two methods:predict: Takes in a string, returns a stringpredict_messages: Takes in a list of messages, returns a message.Let's see how to work with these different types of models and these different types of inputs. First, let's import an LLM and a ChatModel.from langchain.llms import OpenAIfrom langchain.chat_models import ChatOpenAIllm = OpenAI()chat_model = ChatOpenAI()llm.predict("hi!")>>> "Hi"chat_model.predict("hi!")>>> "Hi"The OpenAI and ChatOpenAI objects are basically just configuration objects.
Installation
Installation ->: A ChatMessage has two required components:content: This is the content of the message.role: This is the role of the entity from which the ChatMessage is coming from.LangChain provides several objects to easily distinguish between different roles:HumanMessage: A ChatMessage coming from a human/user.AIMessage: A ChatMessage coming from an AI/assistant.SystemMessage: A ChatMessage coming from the system.FunctionMessage: A ChatMessage coming from a function call.If none of those roles sound right, there is also a ChatMessage class where you can specify the role manually. For more information on how to use these different messages most effectively, see our prompting guide.LangChain provides a standard interface for both, but it's useful to understand this difference in order to construct prompts for a given language model. The standard interface that LangChain provides has two methods:predict: Takes in a string, returns a stringpredict_messages: Takes in a list of messages, returns a message.Let's see how to work with these different types of models and these different types of inputs. First, let's import an LLM and a ChatModel.from langchain.llms import OpenAIfrom langchain.chat_models import ChatOpenAIllm = OpenAI()chat_model = ChatOpenAI()llm.predict("hi!")>>> "Hi"chat_model.predict("hi!")>>> "Hi"The OpenAI and ChatOpenAI objects are basically just configuration objects.
5
You can initialize them with parameters like temperature and others, and pass them around.Next, let's use the predict method to run over a string input.text = "What would be a good company name for a company that makes colorful socks?"llm.predict(text)# >> Feetful of Funchat_model.predict(text)# >> Socks O'ColorFinally, let's use the predict_messages method to run over a list of messages.from langchain.schema import HumanMessagetext = "What would be a good company name for a company that makes colorful socks?"messages = [HumanMessage(content=text)]llm.predict_messages(messages)# >> Feetful of Funchat_model.predict_messages(messages)# >> Socks O'ColorFor both these methods, you can also pass in parameters as keyword arguments. For example, you could pass in temperature=0 to adjust the temperature that is used from what the object was configured with. Whatever values are passed in during run time will always override what the object was configured with.Prompt templates‚ÄãMost LLM applications do not pass user input directly into an LLM. Usually they will add the user input to a larger piece of text, called a prompt template, that provides additional context on the specific task at hand.In the previous example, the text we passed to the model contained instructions to generate a company name. For our application, it'd be great if the user only had to provide the description of a company/product, without having to worry about giving the model instructions.PromptTemplates help with exactly this! They bundle up all the logic for going from user input into a fully formatted prompt.
Installation
Installation ->: You can initialize them with parameters like temperature and others, and pass them around.Next, let's use the predict method to run over a string input.text = "What would be a good company name for a company that makes colorful socks?"llm.predict(text)# >> Feetful of Funchat_model.predict(text)# >> Socks O'ColorFinally, let's use the predict_messages method to run over a list of messages.from langchain.schema import HumanMessagetext = "What would be a good company name for a company that makes colorful socks?"messages = [HumanMessage(content=text)]llm.predict_messages(messages)# >> Feetful of Funchat_model.predict_messages(messages)# >> Socks O'ColorFor both these methods, you can also pass in parameters as keyword arguments. For example, you could pass in temperature=0 to adjust the temperature that is used from what the object was configured with. Whatever values are passed in during run time will always override what the object was configured with.Prompt templates‚ÄãMost LLM applications do not pass user input directly into an LLM. Usually they will add the user input to a larger piece of text, called a prompt template, that provides additional context on the specific task at hand.In the previous example, the text we passed to the model contained instructions to generate a company name. For our application, it'd be great if the user only had to provide the description of a company/product, without having to worry about giving the model instructions.PromptTemplates help with exactly this! They bundle up all the logic for going from user input into a fully formatted prompt.
6
This can start off very simple - for example, a prompt to produce the above string would just be:from langchain.prompts import PromptTemplateprompt = PromptTemplate.from_template("What is a good name for a company that makes {product}?")prompt.format(product="colorful socks")What is a good name for a company that makes colorful socks?However, the advantages of using these over raw string formatting are several. You can "partial" out variables - e.g. you can format only some of the variables at a time. You can compose them together, easily combining different templates into a single prompt. For explanations of these functionalities, see the section on prompts for more detail.PromptTemplates can also be used to produce a list of messages. In this case, the prompt not only contains information about the content, but also each message (its role, its position in the list, etc) Here, what happens most often is a ChatPromptTemplate is a list of ChatMessageTemplates. Each ChatMessageTemplate contains instructions for how to format that ChatMessage - its role, and then also its content. Let's take a look at this below:from langchain.prompts.chat import ChatPromptTemplatetemplate = "You are a helpful assistant that translates {input_language} to {output_language}."human_template = "{text}"chat_prompt = ChatPromptTemplate.from_messages([ ("system", template), ("human", human_template),])chat_prompt.format_messages(input_language="English", output_language="French", text="I love programming.")[ SystemMessage(content="You are a helpful assistant that translates English to French.", additional_kwargs={}), HumanMessage(content="I love programming.")]ChatPromptTemplates can also be constructed in other ways - see the section on prompts for more detail.Output parsers‚ÄãOutputParsers convert the raw output of an LLM into a format that can be used downstream.
Installation
Installation ->: This can start off very simple - for example, a prompt to produce the above string would just be:from langchain.prompts import PromptTemplateprompt = PromptTemplate.from_template("What is a good name for a company that makes {product}?")prompt.format(product="colorful socks")What is a good name for a company that makes colorful socks?However, the advantages of using these over raw string formatting are several. You can "partial" out variables - e.g. you can format only some of the variables at a time. You can compose them together, easily combining different templates into a single prompt. For explanations of these functionalities, see the section on prompts for more detail.PromptTemplates can also be used to produce a list of messages. In this case, the prompt not only contains information about the content, but also each message (its role, its position in the list, etc) Here, what happens most often is a ChatPromptTemplate is a list of ChatMessageTemplates. Each ChatMessageTemplate contains instructions for how to format that ChatMessage - its role, and then also its content. Let's take a look at this below:from langchain.prompts.chat import ChatPromptTemplatetemplate = "You are a helpful assistant that translates {input_language} to {output_language}."human_template = "{text}"chat_prompt = ChatPromptTemplate.from_messages([ ("system", template), ("human", human_template),])chat_prompt.format_messages(input_language="English", output_language="French", text="I love programming.")[ SystemMessage(content="You are a helpful assistant that translates English to French.", additional_kwargs={}), HumanMessage(content="I love programming.")]ChatPromptTemplates can also be constructed in other ways - see the section on prompts for more detail.Output parsers‚ÄãOutputParsers convert the raw output of an LLM into a format that can be used downstream.
7
There are few main type of OutputParsers, including:Convert text from LLM -> structured information (e.g. JSON)Convert a ChatMessage into just a stringConvert the extra information returned from a call besides the message (like OpenAI function invocation) into a string.For full information on this, see the section on output parsersIn this getting started guide, we will write our own output parser - one that converts a comma separated list into a list.from langchain.schema import BaseOutputParserclass CommaSeparatedListOutputParser(BaseOutputParser): """Parse the output of an LLM call to a comma-separated list.""" def parse(self, text: str): """Parse the output of an LLM call.""" return text.strip().split(", ")CommaSeparatedListOutputParser().parse("hi, bye")# >> ['hi', 'bye']PromptTemplate + LLM + OutputParser‚ÄãWe can now combine all these into one chain. This chain will take input variables, pass those to a prompt template to create a prompt, pass the prompt to a language model, and then pass the output through an (optional) output parser. This is a convenient way to bundle up a modular piece of logic.
Installation
Installation ->: There are few main type of OutputParsers, including:Convert text from LLM -> structured information (e.g. JSON)Convert a ChatMessage into just a stringConvert the extra information returned from a call besides the message (like OpenAI function invocation) into a string.For full information on this, see the section on output parsersIn this getting started guide, we will write our own output parser - one that converts a comma separated list into a list.from langchain.schema import BaseOutputParserclass CommaSeparatedListOutputParser(BaseOutputParser): """Parse the output of an LLM call to a comma-separated list.""" def parse(self, text: str): """Parse the output of an LLM call.""" return text.strip().split(", ")CommaSeparatedListOutputParser().parse("hi, bye")# >> ['hi', 'bye']PromptTemplate + LLM + OutputParser‚ÄãWe can now combine all these into one chain. This chain will take input variables, pass those to a prompt template to create a prompt, pass the prompt to a language model, and then pass the output through an (optional) output parser. This is a convenient way to bundle up a modular piece of logic.
8
Let's see it in action!from langchain.chat_models import ChatOpenAIfrom langchain.prompts.chat import ChatPromptTemplatefrom langchain.schema import BaseOutputParserclass CommaSeparatedListOutputParser(BaseOutputParser): """Parse the output of an LLM call to a comma-separated list.""" def parse(self, text: str): """Parse the output of an LLM call.""" return text.strip().split(", ")template = """You are a helpful assistant who generates comma separated lists.A user will pass in a category, and you should generate 5 objects in that category in a comma separated list.ONLY return a comma separated list, and nothing more."""human_template = "{text}"chat_prompt = ChatPromptTemplate.from_messages([ ("system", template), ("human", human_template),])chain = chat_prompt | ChatOpenAI() | CommaSeparatedListOutputParser()chain.invoke({"text": "colors"})# >> ['red', 'blue', 'green', 'yellow', 'orange']Note that we are using the | syntax to join these components together. This | syntax is called the LangChain Expression Language. To learn more about this syntax, read the documentation here.Next steps​This is it! We've now gone over how to create the core building block of LangChain applications. There is a lot more nuance in all these components (LLMs, prompts, output parsers) and a lot more different components to learn about as well. To continue on your journey:Dive deeper into LLMs, prompts, and output parsersLearn the other key componentsRead up on LangChain Expression Language to learn how to chain these components togetherCheck out our helpful guides for detailed walkthroughs on particular topicsExplore end-to-end use casesPreviousInstallationNextLangChain Expression Language (LCEL)InstallationEnvironment setupBuilding an applicationLLMsPrompt templatesOutput parsersPromptTemplate + LLM + OutputParserNext stepsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
Installation
Installation ->: Let's see it in action!from langchain.chat_models import ChatOpenAIfrom langchain.prompts.chat import ChatPromptTemplatefrom langchain.schema import BaseOutputParserclass CommaSeparatedListOutputParser(BaseOutputParser): """Parse the output of an LLM call to a comma-separated list.""" def parse(self, text: str): """Parse the output of an LLM call.""" return text.strip().split(", ")template = """You are a helpful assistant who generates comma separated lists.A user will pass in a category, and you should generate 5 objects in that category in a comma separated list.ONLY return a comma separated list, and nothing more."""human_template = "{text}"chat_prompt = ChatPromptTemplate.from_messages([ ("system", template), ("human", human_template),])chain = chat_prompt | ChatOpenAI() | CommaSeparatedListOutputParser()chain.invoke({"text": "colors"})# >> ['red', 'blue', 'green', 'yellow', 'orange']Note that we are using the | syntax to join these components together. This | syntax is called the LangChain Expression Language. To learn more about this syntax, read the documentation here.Next steps​This is it! We've now gone over how to create the core building block of LangChain applications. There is a lot more nuance in all these components (LLMs, prompts, output parsers) and a lot more different components to learn about as well. To continue on your journey:Dive deeper into LLMs, prompts, and output parsersLearn the other key componentsRead up on LangChain Expression Language to learn how to chain these components togetherCheck out our helpful guides for detailed walkthroughs on particular topicsExplore end-to-end use casesPreviousInstallationNextLangChain Expression Language (LCEL)InstallationEnvironment setupBuilding an applicationLLMsPrompt templatesOutput parsersPromptTemplate + LLM + OutputParserNext stepsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
9
Prompts | 🦜�🔗 Langchain Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesExample selectorsLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsPromptsA prompt for a language model is a set of instructions or input provided by a user to guide the model's response, helping it understand the context and generate relevant and coherent language-based output, such as answering questions, completing sentences, or engaging in a conversation.LangChain provides several classes and functions to help construct and work with prompts.Prompt templates: Parametrized model inputsExample selectors: Dynamically select examples to include in promptsPreviousModel I/ONextPrompt templatesCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
A prompt for a language model is a set of instructions or input provided by a user to
A prompt for a language model is a set of instructions or input provided by a user to ->: Prompts | 🦜�🔗 Langchain Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesExample selectorsLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsPromptsA prompt for a language model is a set of instructions or input provided by a user to guide the model's response, helping it understand the context and generate relevant and coherent language-based output, such as answering questions, completing sentences, or engaging in a conversation.LangChain provides several classes and functions to help construct and work with prompts.Prompt templates: Parametrized model inputsExample selectors: Dynamically select examples to include in promptsPreviousModel I/ONextPrompt templatesCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
10
Example selectors | 🦜️🔗 Langchain Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesExample selectorsCustom example selectorSelect by lengthSelect by maximal marginal relevance (MMR)Select by n-gram overlapSelect by similarityLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsExample selectorsExample selectorsIf you have a large number of examples, you may need to select which ones to include in the prompt. The Example Selector is the class responsible for doing so.The base interface is defined as below:class BaseExampleSelector(ABC): """Interface for selecting examples to include in prompts.""" @abstractmethod def select_examples(self, input_variables: Dict[str, str]) -> List[dict]: """Select which examples to use based on the inputs."""The only method it needs to define is a select_examples method. This takes in the input variables and then returns a list of examples. It is up to each specific implementation as to how those examples are selected.PreviousValidate templateNextCustom example selectorCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
If you have a large number of examples, you may need to select which ones to include in the prompt. The Example Selector is the class responsible for doing so.
If you have a large number of examples, you may need to select which ones to include in the prompt. The Example Selector is the class responsible for doing so. ->: Example selectors | 🦜️🔗 Langchain Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesExample selectorsCustom example selectorSelect by lengthSelect by maximal marginal relevance (MMR)Select by n-gram overlapSelect by similarityLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsExample selectorsExample selectorsIf you have a large number of examples, you may need to select which ones to include in the prompt. The Example Selector is the class responsible for doing so.The base interface is defined as below:class BaseExampleSelector(ABC): """Interface for selecting examples to include in prompts.""" @abstractmethod def select_examples(self, input_variables: Dict[str, str]) -> List[dict]: """Select which examples to use based on the inputs."""The only method it needs to define is a select_examples method. This takes in the input variables and then returns a list of examples. It is up to each specific implementation as to how those examples are selected.PreviousValidate templateNextCustom example selectorCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
11
Custom example selector | 🦜️🔗 Langchain
In this tutorial, we'll create a custom example selector that selects examples randomly from a given list of examples.
In this tutorial, we'll create a custom example selector that selects examples randomly from a given list of examples. ->: Custom example selector | 🦜️🔗 Langchain
12
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesExample selectorsCustom example selectorSelect by lengthSelect by maximal marginal relevance (MMR)Select by n-gram overlapSelect by similarityLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsExample selectorsCustom example selectorOn this pageCustom example selectorIn this tutorial, we'll create a custom example selector that selects examples randomly from a given list of examples.An ExampleSelector must implement two methods:An add_example method which takes in an example and adds it into the ExampleSelectorA select_examples method which takes in input variables (which are meant to be user input) and returns a list of examples to use in the few-shot prompt.Let's implement a custom ExampleSelector that just selects two examples at random.Note:
In this tutorial, we'll create a custom example selector that selects examples randomly from a given list of examples.
In this tutorial, we'll create a custom example selector that selects examples randomly from a given list of examples. ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesExample selectorsCustom example selectorSelect by lengthSelect by maximal marginal relevance (MMR)Select by n-gram overlapSelect by similarityLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsExample selectorsCustom example selectorOn this pageCustom example selectorIn this tutorial, we'll create a custom example selector that selects examples randomly from a given list of examples.An ExampleSelector must implement two methods:An add_example method which takes in an example and adds it into the ExampleSelectorA select_examples method which takes in input variables (which are meant to be user input) and returns a list of examples to use in the few-shot prompt.Let's implement a custom ExampleSelector that just selects two examples at random.Note:
13
Take a look at the current set of example selector implementations supported in LangChain here.Implement custom example selector​from langchain.prompts.example_selector.base import BaseExampleSelectorfrom typing import Dict, Listimport numpy as npclass CustomExampleSelector(BaseExampleSelector): def __init__(self, examples: List[Dict[str, str]]): self.examples = examples def add_example(self, example: Dict[str, str]) -> None: """Add new example to store for a key.""" self.examples.append(example) def select_examples(self, input_variables: Dict[str, str]) -> List[dict]: """Select which examples to use based on the inputs.""" return np.random.choice(self.examples, size=2, replace=False)Use custom example selector​examples = [ {"foo": "1"}, {"foo": "2"}, {"foo": "3"}]# Initialize example selector.example_selector = CustomExampleSelector(examples)# Select examplesexample_selector.select_examples({"foo": "foo"})# -> array([{'foo': '2'}, {'foo': '3'}], dtype=object)# Add new example to the set of examplesexample_selector.add_example({"foo": "4"})example_selector.examples# -> [{'foo': '1'}, {'foo': '2'}, {'foo': '3'}, {'foo': '4'}]# Select examplesexample_selector.select_examples({"foo": "foo"})# -> array([{'foo': '1'}, {'foo': '4'}], dtype=object)PreviousExample selectorsNextSelect by lengthImplement custom example selectorUse custom example selectorCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
In this tutorial, we'll create a custom example selector that selects examples randomly from a given list of examples.
In this tutorial, we'll create a custom example selector that selects examples randomly from a given list of examples. ->: Take a look at the current set of example selector implementations supported in LangChain here.Implement custom example selector​from langchain.prompts.example_selector.base import BaseExampleSelectorfrom typing import Dict, Listimport numpy as npclass CustomExampleSelector(BaseExampleSelector): def __init__(self, examples: List[Dict[str, str]]): self.examples = examples def add_example(self, example: Dict[str, str]) -> None: """Add new example to store for a key.""" self.examples.append(example) def select_examples(self, input_variables: Dict[str, str]) -> List[dict]: """Select which examples to use based on the inputs.""" return np.random.choice(self.examples, size=2, replace=False)Use custom example selector​examples = [ {"foo": "1"}, {"foo": "2"}, {"foo": "3"}]# Initialize example selector.example_selector = CustomExampleSelector(examples)# Select examplesexample_selector.select_examples({"foo": "foo"})# -> array([{'foo': '2'}, {'foo': '3'}], dtype=object)# Add new example to the set of examplesexample_selector.add_example({"foo": "4"})example_selector.examples# -> [{'foo': '1'}, {'foo': '2'}, {'foo': '3'}, {'foo': '4'}]# Select examplesexample_selector.select_examples({"foo": "foo"})# -> array([{'foo': '1'}, {'foo': '4'}], dtype=object)PreviousExample selectorsNextSelect by lengthImplement custom example selectorUse custom example selectorCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
14
Select by length | 🦜️🔗 Langchain
This example selector selects which examples to use based on length. This is useful when you are worried about constructing a prompt that will go over the length of the context window. For longer inputs, it will select fewer examples to include, while for shorter inputs it will select more.
This example selector selects which examples to use based on length. This is useful when you are worried about constructing a prompt that will go over the length of the context window. For longer inputs, it will select fewer examples to include, while for shorter inputs it will select more. ->: Select by length | 🦜️🔗 Langchain
15
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesExample selectorsCustom example selectorSelect by lengthSelect by maximal marginal relevance (MMR)Select by n-gram overlapSelect by similarityLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsExample selectorsSelect by lengthSelect by lengthThis example selector selects which examples to use based on length. This is useful when you are worried about constructing a prompt that will go over the length of the context window. For longer inputs, it will select fewer examples to include, while for shorter inputs it will select more.from langchain.prompts import PromptTemplatefrom langchain.prompts import FewShotPromptTemplatefrom langchain.prompts.example_selector import LengthBasedExampleSelector# 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_prompt = PromptTemplate( input_variables=["input", "output"], template="Input: {input}\nOutput: {output}",)example_selector = LengthBasedExampleSelector( # The examples it has available to choose from. examples=examples, # The PromptTemplate being used to format the examples. example_prompt=example_prompt, # The maximum length that the formatted examples should be. # Length is measured by the get_text_length function below. max_length=25, # The function used to get the length of a string, which is used # to determine which examples to include. It is commented out because # it is provided as a
This example selector selects which examples to use based on length. This is useful when you are worried about constructing a prompt that will go over the length of the context window. For longer inputs, it will select fewer examples to include, while for shorter inputs it will select more.
This example selector selects which examples to use based on length. This is useful when you are worried about constructing a prompt that will go over the length of the context window. For longer inputs, it will select fewer examples to include, while for shorter inputs it will select more. ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesExample selectorsCustom example selectorSelect by lengthSelect by maximal marginal relevance (MMR)Select by n-gram overlapSelect by similarityLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsExample selectorsSelect by lengthSelect by lengthThis example selector selects which examples to use based on length. This is useful when you are worried about constructing a prompt that will go over the length of the context window. For longer inputs, it will select fewer examples to include, while for shorter inputs it will select more.from langchain.prompts import PromptTemplatefrom langchain.prompts import FewShotPromptTemplatefrom langchain.prompts.example_selector import LengthBasedExampleSelector# 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_prompt = PromptTemplate( input_variables=["input", "output"], template="Input: {input}\nOutput: {output}",)example_selector = LengthBasedExampleSelector( # The examples it has available to choose from. examples=examples, # The PromptTemplate being used to format the examples. example_prompt=example_prompt, # The maximum length that the formatted examples should be. # Length is measured by the get_text_length function below. max_length=25, # The function used to get the length of a string, which is used # to determine which examples to include. It is commented out because # it is provided as a
16
is commented out because # it is provided as a default value if none is specified. # get_text_length: Callable[[str], int] = lambda x: len(re.split("\n| ", x)))dynamic_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"],)# An example with small input, so it selects all examples.print(dynamic_prompt.format(adjective="big")) Give the antonym of every input Input: happy Output: sad Input: tall Output: short Input: energetic Output: lethargic Input: sunny Output: gloomy Input: windy Output: calm Input: big Output:# An example with long input, so it selects only one example.long_string = "big and huge and massive and large and gigantic and tall and much much much much much bigger than everything else"print(dynamic_prompt.format(adjective=long_string)) Give the antonym of every input Input: happy Output: sad Input: big and huge and massive and large and gigantic and tall and much much much much much bigger than everything else Output:# You can add an example to an example selector as well.new_example = {"input": "big", "output": "small"}dynamic_prompt.example_selector.add_example(new_example)print(dynamic_prompt.format(adjective="enthusiastic")) Give the antonym of every input Input: happy Output: sad Input: tall Output: short Input: energetic Output: lethargic Input: sunny Output: gloomy Input: windy Output: calm Input: big Output: small Input: enthusiastic Output:PreviousCustom example selectorNextSelect by maximal marginal relevance (MMR)CommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
This example selector selects which examples to use based on length. This is useful when you are worried about constructing a prompt that will go over the length of the context window. For longer inputs, it will select fewer examples to include, while for shorter inputs it will select more.
This example selector selects which examples to use based on length. This is useful when you are worried about constructing a prompt that will go over the length of the context window. For longer inputs, it will select fewer examples to include, while for shorter inputs it will select more. ->: is commented out because # it is provided as a default value if none is specified. # get_text_length: Callable[[str], int] = lambda x: len(re.split("\n| ", x)))dynamic_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"],)# An example with small input, so it selects all examples.print(dynamic_prompt.format(adjective="big")) Give the antonym of every input Input: happy Output: sad Input: tall Output: short Input: energetic Output: lethargic Input: sunny Output: gloomy Input: windy Output: calm Input: big Output:# An example with long input, so it selects only one example.long_string = "big and huge and massive and large and gigantic and tall and much much much much much bigger than everything else"print(dynamic_prompt.format(adjective=long_string)) Give the antonym of every input Input: happy Output: sad Input: big and huge and massive and large and gigantic and tall and much much much much much bigger than everything else Output:# You can add an example to an example selector as well.new_example = {"input": "big", "output": "small"}dynamic_prompt.example_selector.add_example(new_example)print(dynamic_prompt.format(adjective="enthusiastic")) Give the antonym of every input Input: happy Output: sad Input: tall Output: short Input: energetic Output: lethargic Input: sunny Output: gloomy Input: windy Output: calm Input: big Output: small Input: enthusiastic Output:PreviousCustom example selectorNextSelect by maximal marginal relevance (MMR)CommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
17
Select by maximal marginal relevance (MMR) | 🦜️🔗 Langchain
The MaxMarginalRelevanceExampleSelector selects examples based on a combination of which examples are most similar to the inputs, while also optimizing for diversity. It does this by finding the examples with the embeddings that have the greatest cosine similarity with the inputs, and then iteratively adding them while penalizing them for closeness to already selected examples.
The MaxMarginalRelevanceExampleSelector selects examples based on a combination of which examples are most similar to the inputs, while also optimizing for diversity. It does this by finding the examples with the embeddings that have the greatest cosine similarity with the inputs, and then iteratively adding them while penalizing them for closeness to already selected examples. ->: Select by maximal marginal relevance (MMR) | 🦜️🔗 Langchain
18
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesExample selectorsCustom example selectorSelect by lengthSelect by maximal marginal relevance (MMR)Select by n-gram overlapSelect by similarityLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsExample selectorsSelect by maximal marginal relevance (MMR)Select by maximal marginal relevance (MMR)The MaxMarginalRelevanceExampleSelector selects examples based on a combination of which examples are most similar to the inputs, while also optimizing for diversity. It does this by finding the examples with the embeddings that have the greatest cosine similarity with the inputs, and then iteratively adding them while penalizing them for closeness to already selected examples.from langchain.prompts.example_selector import ( MaxMarginalRelevanceExampleSelector, SemanticSimilarityExampleSelector,)from langchain.vectorstores import FAISSfrom langchain.embeddings import OpenAIEmbeddingsfrom langchain.prompts import FewShotPromptTemplate, PromptTemplateexample_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 = MaxMarginalRelevanceExampleSelector.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
The MaxMarginalRelevanceExampleSelector selects examples based on a combination of which examples are most similar to the inputs, while also optimizing for diversity. It does this by finding the examples with the embeddings that have the greatest cosine similarity with the inputs, and then iteratively adding them while penalizing them for closeness to already selected examples.
The MaxMarginalRelevanceExampleSelector selects examples based on a combination of which examples are most similar to the inputs, while also optimizing for diversity. It does this by finding the examples with the embeddings that have the greatest cosine similarity with the inputs, and then iteratively adding them while penalizing them for closeness to already selected examples. ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesExample selectorsCustom example selectorSelect by lengthSelect by maximal marginal relevance (MMR)Select by n-gram overlapSelect by similarityLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsExample selectorsSelect by maximal marginal relevance (MMR)Select by maximal marginal relevance (MMR)The MaxMarginalRelevanceExampleSelector selects examples based on a combination of which examples are most similar to the inputs, while also optimizing for diversity. It does this by finding the examples with the embeddings that have the greatest cosine similarity with the inputs, and then iteratively adding them while penalizing them for closeness to already selected examples.from langchain.prompts.example_selector import ( MaxMarginalRelevanceExampleSelector, SemanticSimilarityExampleSelector,)from langchain.vectorstores import FAISSfrom langchain.embeddings import OpenAIEmbeddingsfrom langchain.prompts import FewShotPromptTemplate, PromptTemplateexample_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 = MaxMarginalRelevanceExampleSelector.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
19
similarity. OpenAIEmbeddings(), # The VectorStore class that is used to store the embeddings and do a similarity search over. FAISS, # The number of examples to produce. k=2,)mmr_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"],)# Input is a feeling, so should select the happy/sad example as the first oneprint(mmr_prompt.format(adjective="worried")) Give the antonym of every input Input: happy Output: sad Input: windy Output: calm Input: worried Output:# Let's compare this to what we would just get if we went solely off of similarity,# by using SemanticSimilarityExampleSelector instead of MaxMarginalRelevanceExampleSelector.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. FAISS, # The number of examples to produce. k=2,)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"],)print(similar_prompt.format(adjective="worried")) Give the antonym of every input Input: happy Output: sad Input: sunny Output: gloomy Input: worried Output:PreviousSelect by lengthNextSelect by n-gram overlapCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
The MaxMarginalRelevanceExampleSelector selects examples based on a combination of which examples are most similar to the inputs, while also optimizing for diversity. It does this by finding the examples with the embeddings that have the greatest cosine similarity with the inputs, and then iteratively adding them while penalizing them for closeness to already selected examples.
The MaxMarginalRelevanceExampleSelector selects examples based on a combination of which examples are most similar to the inputs, while also optimizing for diversity. It does this by finding the examples with the embeddings that have the greatest cosine similarity with the inputs, and then iteratively adding them while penalizing them for closeness to already selected examples. ->: similarity. OpenAIEmbeddings(), # The VectorStore class that is used to store the embeddings and do a similarity search over. FAISS, # The number of examples to produce. k=2,)mmr_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"],)# Input is a feeling, so should select the happy/sad example as the first oneprint(mmr_prompt.format(adjective="worried")) Give the antonym of every input Input: happy Output: sad Input: windy Output: calm Input: worried Output:# Let's compare this to what we would just get if we went solely off of similarity,# by using SemanticSimilarityExampleSelector instead of MaxMarginalRelevanceExampleSelector.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. FAISS, # The number of examples to produce. k=2,)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"],)print(similar_prompt.format(adjective="worried")) Give the antonym of every input Input: happy Output: sad Input: sunny Output: gloomy Input: worried Output:PreviousSelect by lengthNextSelect by n-gram overlapCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
20
Select by n-gram overlap | 🦜️🔗 Langchain
The NGramOverlapExampleSelector selects and orders examples based on which examples are most similar to the input, according to an ngram overlap score. The ngram overlap score is a float between 0.0 and 1.0, inclusive.
The NGramOverlapExampleSelector selects and orders examples based on which examples are most similar to the input, according to an ngram overlap score. The ngram overlap score is a float between 0.0 and 1.0, inclusive. ->: Select by n-gram overlap | 🦜️🔗 Langchain
21
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesExample selectorsCustom example selectorSelect by lengthSelect by maximal marginal relevance (MMR)Select by n-gram overlapSelect by similarityLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsExample selectorsSelect by n-gram overlapSelect by n-gram overlapThe NGramOverlapExampleSelector selects and orders examples based on which examples are most similar to the input, according to an ngram overlap score. The ngram overlap score is a float between 0.0 and 1.0, inclusive. The selector allows for a threshold score to be set. Examples with an ngram overlap score less than or equal to the threshold are excluded. The threshold is set to -1.0, by default, so will not exclude any examples, only reorder them. Setting the threshold to 0.0 will exclude examples that have no ngram overlaps with the input.from langchain.prompts import PromptTemplate, FewShotPromptTemplatefrom langchain.prompts.example_selector.ngram_overlap import NGramOverlapExampleSelectorexample_prompt = PromptTemplate( input_variables=["input", "output"], template="Input: {input}\nOutput: {output}",)# Examples of a fictional translation task.examples = [ {"input": "See Spot run.", "output": "Ver correr a Spot."}, {"input": "My dog barks.", "output": "Mi perro ladra."}, {"input": "Spot can run.", "output": "Spot puede correr."},]example_selector = NGramOverlapExampleSelector( # The examples it has available to choose from. examples=examples, # The PromptTemplate being used to format the examples. example_prompt=example_prompt, # The threshold, at which selector stops. # It is set to -1.0 by default.
The NGramOverlapExampleSelector selects and orders examples based on which examples are most similar to the input, according to an ngram overlap score. The ngram overlap score is a float between 0.0 and 1.0, inclusive.
The NGramOverlapExampleSelector selects and orders examples based on which examples are most similar to the input, according to an ngram overlap score. The ngram overlap score is a float between 0.0 and 1.0, inclusive. ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesExample selectorsCustom example selectorSelect by lengthSelect by maximal marginal relevance (MMR)Select by n-gram overlapSelect by similarityLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsExample selectorsSelect by n-gram overlapSelect by n-gram overlapThe NGramOverlapExampleSelector selects and orders examples based on which examples are most similar to the input, according to an ngram overlap score. The ngram overlap score is a float between 0.0 and 1.0, inclusive. The selector allows for a threshold score to be set. Examples with an ngram overlap score less than or equal to the threshold are excluded. The threshold is set to -1.0, by default, so will not exclude any examples, only reorder them. Setting the threshold to 0.0 will exclude examples that have no ngram overlaps with the input.from langchain.prompts import PromptTemplate, FewShotPromptTemplatefrom langchain.prompts.example_selector.ngram_overlap import NGramOverlapExampleSelectorexample_prompt = PromptTemplate( input_variables=["input", "output"], template="Input: {input}\nOutput: {output}",)# Examples of a fictional translation task.examples = [ {"input": "See Spot run.", "output": "Ver correr a Spot."}, {"input": "My dog barks.", "output": "Mi perro ladra."}, {"input": "Spot can run.", "output": "Spot puede correr."},]example_selector = NGramOverlapExampleSelector( # The examples it has available to choose from. examples=examples, # The PromptTemplate being used to format the examples. example_prompt=example_prompt, # The threshold, at which selector stops. # It is set to -1.0 by default.
22
stops. # It is set to -1.0 by default. threshold=-1.0, # For negative threshold: # Selector sorts examples by ngram overlap score, and excludes none. # For threshold greater than 1.0: # Selector excludes all examples, and returns an empty list. # For threshold equal to 0.0: # Selector sorts examples by ngram overlap score, # and excludes those with no ngram overlap with input.)dynamic_prompt = FewShotPromptTemplate( # We provide an ExampleSelector instead of examples. example_selector=example_selector, example_prompt=example_prompt, prefix="Give the Spanish translation of every input", suffix="Input: {sentence}\nOutput:", input_variables=["sentence"],)# An example input with large ngram overlap with "Spot can run."# and no overlap with "My dog barks."print(dynamic_prompt.format(sentence="Spot can run fast.")) Give the Spanish translation of every input Input: Spot can run. Output: Spot puede correr. Input: See Spot run. Output: Ver correr a Spot. Input: My dog barks. Output: Mi perro ladra. Input: Spot can run fast. Output:# You can add examples to NGramOverlapExampleSelector as well.new_example = {"input": "Spot plays fetch.", "output": "Spot juega a buscar."}example_selector.add_example(new_example)print(dynamic_prompt.format(sentence="Spot can run fast.")) Give the Spanish translation of every input Input: Spot can run. Output: Spot puede correr. Input: See Spot run. Output: Ver correr a Spot. Input: Spot plays fetch. Output: Spot juega a buscar. Input: My dog barks. Output: Mi perro ladra. Input: Spot can run fast. Output:# You can set a threshold at which examples are excluded.# For example, setting threshold equal to 0.0# excludes examples with no ngram overlaps with input.# Since "My dog barks." has no ngram overlaps with "Spot can run fast."# it is excluded.example_selector.threshold =
The NGramOverlapExampleSelector selects and orders examples based on which examples are most similar to the input, according to an ngram overlap score. The ngram overlap score is a float between 0.0 and 1.0, inclusive.
The NGramOverlapExampleSelector selects and orders examples based on which examples are most similar to the input, according to an ngram overlap score. The ngram overlap score is a float between 0.0 and 1.0, inclusive. ->: stops. # It is set to -1.0 by default. threshold=-1.0, # For negative threshold: # Selector sorts examples by ngram overlap score, and excludes none. # For threshold greater than 1.0: # Selector excludes all examples, and returns an empty list. # For threshold equal to 0.0: # Selector sorts examples by ngram overlap score, # and excludes those with no ngram overlap with input.)dynamic_prompt = FewShotPromptTemplate( # We provide an ExampleSelector instead of examples. example_selector=example_selector, example_prompt=example_prompt, prefix="Give the Spanish translation of every input", suffix="Input: {sentence}\nOutput:", input_variables=["sentence"],)# An example input with large ngram overlap with "Spot can run."# and no overlap with "My dog barks."print(dynamic_prompt.format(sentence="Spot can run fast.")) Give the Spanish translation of every input Input: Spot can run. Output: Spot puede correr. Input: See Spot run. Output: Ver correr a Spot. Input: My dog barks. Output: Mi perro ladra. Input: Spot can run fast. Output:# You can add examples to NGramOverlapExampleSelector as well.new_example = {"input": "Spot plays fetch.", "output": "Spot juega a buscar."}example_selector.add_example(new_example)print(dynamic_prompt.format(sentence="Spot can run fast.")) Give the Spanish translation of every input Input: Spot can run. Output: Spot puede correr. Input: See Spot run. Output: Ver correr a Spot. Input: Spot plays fetch. Output: Spot juega a buscar. Input: My dog barks. Output: Mi perro ladra. Input: Spot can run fast. Output:# You can set a threshold at which examples are excluded.# For example, setting threshold equal to 0.0# excludes examples with no ngram overlaps with input.# Since "My dog barks." has no ngram overlaps with "Spot can run fast."# it is excluded.example_selector.threshold =
23
it is excluded.example_selector.threshold = 0.0print(dynamic_prompt.format(sentence="Spot can run fast.")) Give the Spanish translation of every input Input: Spot can run. Output: Spot puede correr. Input: See Spot run. Output: Ver correr a Spot. Input: Spot plays fetch. Output: Spot juega a buscar. Input: Spot can run fast. Output:# Setting small nonzero thresholdexample_selector.threshold = 0.09print(dynamic_prompt.format(sentence="Spot can play fetch.")) Give the Spanish translation of every input Input: Spot can run. Output: Spot puede correr. Input: Spot plays fetch. Output: Spot juega a buscar. Input: Spot can play fetch. Output:# Setting threshold greater than 1.0example_selector.threshold = 1.0 + 1e-9print(dynamic_prompt.format(sentence="Spot can play fetch.")) Give the Spanish translation of every input Input: Spot can play fetch. Output:PreviousSelect by maximal marginal relevance (MMR)NextSelect by similarityCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
The NGramOverlapExampleSelector selects and orders examples based on which examples are most similar to the input, according to an ngram overlap score. The ngram overlap score is a float between 0.0 and 1.0, inclusive.
The NGramOverlapExampleSelector selects and orders examples based on which examples are most similar to the input, according to an ngram overlap score. The ngram overlap score is a float between 0.0 and 1.0, inclusive. ->: it is excluded.example_selector.threshold = 0.0print(dynamic_prompt.format(sentence="Spot can run fast.")) Give the Spanish translation of every input Input: Spot can run. Output: Spot puede correr. Input: See Spot run. Output: Ver correr a Spot. Input: Spot plays fetch. Output: Spot juega a buscar. Input: Spot can run fast. Output:# Setting small nonzero thresholdexample_selector.threshold = 0.09print(dynamic_prompt.format(sentence="Spot can play fetch.")) Give the Spanish translation of every input Input: Spot can run. Output: Spot puede correr. Input: Spot plays fetch. Output: Spot juega a buscar. Input: Spot can play fetch. Output:# Setting threshold greater than 1.0example_selector.threshold = 1.0 + 1e-9print(dynamic_prompt.format(sentence="Spot can play fetch.")) Give the Spanish translation of every input Input: Spot can play fetch. Output:PreviousSelect by maximal marginal relevance (MMR)NextSelect by similarityCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
24
Select by similarity | 🦜️🔗 Langchain
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.
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. ->: Select by similarity | 🦜️🔗 Langchain
25
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesExample selectorsCustom example selectorSelect by lengthSelect by maximal marginal relevance (MMR)Select by n-gram overlapSelect by similarityLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsExample selectorsSelect by similaritySelect by similarityThis 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.from langchain.prompts.example_selector import SemanticSimilarityExampleSelectorfrom langchain.vectorstores import Chromafrom langchain.embeddings import OpenAIEmbeddingsfrom langchain.prompts import FewShotPromptTemplate, PromptTemplateexample_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,
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.
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. ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesExample selectorsCustom example selectorSelect by lengthSelect by maximal marginal relevance (MMR)Select by n-gram overlapSelect by similarityLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsExample selectorsSelect by similaritySelect by similarityThis 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.from langchain.prompts.example_selector import SemanticSimilarityExampleSelectorfrom langchain.vectorstores import Chromafrom langchain.embeddings import OpenAIEmbeddingsfrom langchain.prompts import FewShotPromptTemplate, PromptTemplateexample_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,
26
example_selector=example_selector, example_prompt=example_prompt, prefix="Give the antonym of every input", suffix="Input: {adjective}\nOutput:", input_variables=["adjective"],) Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient.# Input is a feeling, so should select the happy/sad exampleprint(similar_prompt.format(adjective="worried")) Give the antonym of every input Input: happy Output: sad Input: worried Output:# Input is a measurement, so should select the tall/short exampleprint(similar_prompt.format(adjective="large")) Give the antonym of every input Input: tall Output: short Input: large Output:# You can add new examples to the SemanticSimilarityExampleSelector as wellsimilar_prompt.example_selector.add_example({"input": "enthusiastic", "output": "apathetic"})print(similar_prompt.format(adjective="passionate")) Give the antonym of every input Input: enthusiastic Output: apathetic Input: passionate Output:PreviousSelect by n-gram overlapNextLanguage modelsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
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.
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. ->: example_selector=example_selector, example_prompt=example_prompt, prefix="Give the antonym of every input", suffix="Input: {adjective}\nOutput:", input_variables=["adjective"],) Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient.# Input is a feeling, so should select the happy/sad exampleprint(similar_prompt.format(adjective="worried")) Give the antonym of every input Input: happy Output: sad Input: worried Output:# Input is a measurement, so should select the tall/short exampleprint(similar_prompt.format(adjective="large")) Give the antonym of every input Input: tall Output: short Input: large Output:# You can add new examples to the SemanticSimilarityExampleSelector as wellsimilar_prompt.example_selector.add_example({"input": "enthusiastic", "output": "apathetic"})print(similar_prompt.format(adjective="passionate")) Give the antonym of every input Input: enthusiastic Output: apathetic Input: passionate Output:PreviousSelect by n-gram overlapNextLanguage modelsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
27
Validate template | 🦜️🔗 Langchain Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesConnecting to a Feature StoreCustom prompt templateFew-shot prompt templatesFew-shot examples for chat modelsFormat template outputTemplate formatsTypes of MessagePromptTemplatePartial prompt templatesCompositionSerializationPrompt pipeliningValidate templateExample selectorsLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsPrompt templatesValidate templateValidate templateBy default, PromptTemplate will validate the template string by checking whether the input_variables match the variables defined in template. You can disable this behavior by setting validate_template to False.template = "I am learning langchain because {reason}."prompt_template = PromptTemplate(template=template, input_variables=["reason", "foo"]) # ValueError due to extra variablesprompt_template = PromptTemplate(template=template, input_variables=["reason", "foo"], validate_template=False) # No errorPreviousPrompt pipeliningNextExample selectorsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
By default, PromptTemplate will validate the template string by checking whether the inputvariables match the variables defined in template. You can disable this behavior by setting validatetemplate to False.
By default, PromptTemplate will validate the template string by checking whether the inputvariables match the variables defined in template. You can disable this behavior by setting validatetemplate to False. ->: Validate template | 🦜️🔗 Langchain Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesConnecting to a Feature StoreCustom prompt templateFew-shot prompt templatesFew-shot examples for chat modelsFormat template outputTemplate formatsTypes of MessagePromptTemplatePartial prompt templatesCompositionSerializationPrompt pipeliningValidate templateExample selectorsLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsPrompt templatesValidate templateValidate templateBy default, PromptTemplate will validate the template string by checking whether the input_variables match the variables defined in template. You can disable this behavior by setting validate_template to False.template = "I am learning langchain because {reason}."prompt_template = PromptTemplate(template=template, input_variables=["reason", "foo"]) # ValueError due to extra variablesprompt_template = PromptTemplate(template=template, input_variables=["reason", "foo"], validate_template=False) # No errorPreviousPrompt pipeliningNextExample selectorsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
28
Custom prompt template | 🦜️🔗 Langchain
Let's suppose we want the LLM to generate English language explanations of a function given its name. To achieve this task, we will create a custom prompt template that takes in the function name as input, and formats the prompt template to provide the source code of the function.
Let's suppose we want the LLM to generate English language explanations of a function given its name. To achieve this task, we will create a custom prompt template that takes in the function name as input, and formats the prompt template to provide the source code of the function. ->: Custom prompt template | 🦜️🔗 Langchain
29
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesConnecting to a Feature StoreCustom prompt templateFew-shot prompt templatesFew-shot examples for chat modelsFormat template outputTemplate formatsTypes of MessagePromptTemplatePartial prompt templatesCompositionSerializationPrompt pipeliningValidate templateExample selectorsLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsPrompt templatesCustom prompt templateOn this pageCustom prompt templateLet's suppose we want the LLM to generate English language explanations of a function given its name. To achieve this task, we will create a custom prompt template that takes in the function name as input, and formats the prompt template to provide the source code of the function.Why are custom prompt templates needed?​LangChain provides a set of default prompt templates that can be used to generate prompts for a variety of tasks. However, there may be cases where the default prompt templates do not meet your needs. For example, you may want to create a prompt template with specific dynamic instructions for your language model. In such cases, you can create a custom prompt template.Creating a custom prompt template​There are essentially two distinct prompt templates available - string prompt templates and chat prompt templates. String prompt templates provides a simple prompt in string format, while chat prompt templates produces a more structured prompt to be used with a chat API.In this guide, we will create a custom prompt using a string prompt template. To create a custom string prompt template, there are two requirements:It has an input_variables attribute that exposes what input variables the
Let's suppose we want the LLM to generate English language explanations of a function given its name. To achieve this task, we will create a custom prompt template that takes in the function name as input, and formats the prompt template to provide the source code of the function.
Let's suppose we want the LLM to generate English language explanations of a function given its name. To achieve this task, we will create a custom prompt template that takes in the function name as input, and formats the prompt template to provide the source code of the function. ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesConnecting to a Feature StoreCustom prompt templateFew-shot prompt templatesFew-shot examples for chat modelsFormat template outputTemplate formatsTypes of MessagePromptTemplatePartial prompt templatesCompositionSerializationPrompt pipeliningValidate templateExample selectorsLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsPrompt templatesCustom prompt templateOn this pageCustom prompt templateLet's suppose we want the LLM to generate English language explanations of a function given its name. To achieve this task, we will create a custom prompt template that takes in the function name as input, and formats the prompt template to provide the source code of the function.Why are custom prompt templates needed?​LangChain provides a set of default prompt templates that can be used to generate prompts for a variety of tasks. However, there may be cases where the default prompt templates do not meet your needs. For example, you may want to create a prompt template with specific dynamic instructions for your language model. In such cases, you can create a custom prompt template.Creating a custom prompt template​There are essentially two distinct prompt templates available - string prompt templates and chat prompt templates. String prompt templates provides a simple prompt in string format, while chat prompt templates produces a more structured prompt to be used with a chat API.In this guide, we will create a custom prompt using a string prompt template. To create a custom string prompt template, there are two requirements:It has an input_variables attribute that exposes what input variables the
30
attribute that exposes what input variables the prompt template expects.It defines a format method that takes in keyword arguments corresponding to the expected input_variables and returns the formatted prompt.We will create a custom prompt template that takes in the function name as input and formats the prompt to provide the source code of the function. To achieve this, let's first create a function that will return the source code of a function given its name.import inspectdef get_source_code(function_name): # Get the source code of the function return inspect.getsource(function_name)Next, we'll create a custom prompt template that takes in the function name as input, and formats the prompt template to provide the source code of the function.from langchain.prompts import StringPromptTemplatefrom pydantic import BaseModel, validatorPROMPT = """\Given the function name and source code, generate an English language explanation of the function.Function Name: {function_name}Source Code:{source_code}Explanation:"""class FunctionExplainerPromptTemplate(StringPromptTemplate, BaseModel): """A custom prompt template that takes in the function name as input, and formats the prompt template to provide the source code of the function.""" @validator("input_variables") def validate_input_variables(cls, v): """Validate that the input variables are correct.""" if len(v) != 1 or "function_name" not in v: raise ValueError("function_name must be the only input_variable.") return v def format(self, **kwargs) -> str: # Get the source code of the function source_code = get_source_code(kwargs["function_name"]) # Generate the prompt to be sent to the language model prompt = PROMPT.format( function_name=kwargs["function_name"].__name__, source_code=source_code ) return prompt def _prompt_type(self): return "function-explainer"Use the custom prompt template‚ÄãNow that we have
Let's suppose we want the LLM to generate English language explanations of a function given its name. To achieve this task, we will create a custom prompt template that takes in the function name as input, and formats the prompt template to provide the source code of the function.
Let's suppose we want the LLM to generate English language explanations of a function given its name. To achieve this task, we will create a custom prompt template that takes in the function name as input, and formats the prompt template to provide the source code of the function. ->: attribute that exposes what input variables the prompt template expects.It defines a format method that takes in keyword arguments corresponding to the expected input_variables and returns the formatted prompt.We will create a custom prompt template that takes in the function name as input and formats the prompt to provide the source code of the function. To achieve this, let's first create a function that will return the source code of a function given its name.import inspectdef get_source_code(function_name): # Get the source code of the function return inspect.getsource(function_name)Next, we'll create a custom prompt template that takes in the function name as input, and formats the prompt template to provide the source code of the function.from langchain.prompts import StringPromptTemplatefrom pydantic import BaseModel, validatorPROMPT = """\Given the function name and source code, generate an English language explanation of the function.Function Name: {function_name}Source Code:{source_code}Explanation:"""class FunctionExplainerPromptTemplate(StringPromptTemplate, BaseModel): """A custom prompt template that takes in the function name as input, and formats the prompt template to provide the source code of the function.""" @validator("input_variables") def validate_input_variables(cls, v): """Validate that the input variables are correct.""" if len(v) != 1 or "function_name" not in v: raise ValueError("function_name must be the only input_variable.") return v def format(self, **kwargs) -> str: # Get the source code of the function source_code = get_source_code(kwargs["function_name"]) # Generate the prompt to be sent to the language model prompt = PROMPT.format( function_name=kwargs["function_name"].__name__, source_code=source_code ) return prompt def _prompt_type(self): return "function-explainer"Use the custom prompt template‚ÄãNow that we have
31
the custom prompt template​Now that we have created a custom prompt template, we can use it to generate prompts for our task.fn_explainer = FunctionExplainerPromptTemplate(input_variables=["function_name"])# Generate a prompt for the function "get_source_code"prompt = fn_explainer.format(function_name=get_source_code)print(prompt) Given the function name and source code, generate an English language explanation of the function. Function Name: get_source_code Source Code: def get_source_code(function_name): # Get the source code of the function return inspect.getsource(function_name) Explanation: PreviousConnecting to a Feature StoreNextFew-shot prompt templatesWhy are custom prompt templates needed?Creating a custom prompt templateUse the custom prompt templateCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
Let's suppose we want the LLM to generate English language explanations of a function given its name. To achieve this task, we will create a custom prompt template that takes in the function name as input, and formats the prompt template to provide the source code of the function.
Let's suppose we want the LLM to generate English language explanations of a function given its name. To achieve this task, we will create a custom prompt template that takes in the function name as input, and formats the prompt template to provide the source code of the function. ->: the custom prompt template​Now that we have created a custom prompt template, we can use it to generate prompts for our task.fn_explainer = FunctionExplainerPromptTemplate(input_variables=["function_name"])# Generate a prompt for the function "get_source_code"prompt = fn_explainer.format(function_name=get_source_code)print(prompt) Given the function name and source code, generate an English language explanation of the function. Function Name: get_source_code Source Code: def get_source_code(function_name): # Get the source code of the function return inspect.getsource(function_name) Explanation: PreviousConnecting to a Feature StoreNextFew-shot prompt templatesWhy are custom prompt templates needed?Creating a custom prompt templateUse the custom prompt templateCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
32
Few-shot examples for chat models | 🦜️🔗 Langchain
This notebook covers how to use few-shot examples in chat models. There does not appear to be solid consensus on how best to do few-shot prompting, and the optimal prompt compilation will likely vary by model. Because of this, we provide few-shot prompt templates like the FewShotChatMessagePromptTemplate as a flexible starting point, and you can modify or replace them as you see fit.
This notebook covers how to use few-shot examples in chat models. There does not appear to be solid consensus on how best to do few-shot prompting, and the optimal prompt compilation will likely vary by model. Because of this, we provide few-shot prompt templates like the FewShotChatMessagePromptTemplate as a flexible starting point, and you can modify or replace them as you see fit. ->: Few-shot examples for chat models | 🦜️🔗 Langchain
33
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesConnecting to a Feature StoreCustom prompt templateFew-shot prompt templatesFew-shot examples for chat modelsFormat template outputTemplate formatsTypes of MessagePromptTemplatePartial prompt templatesCompositionSerializationPrompt pipeliningValidate templateExample selectorsLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsPrompt templatesFew-shot examples for chat modelsOn this pageFew-shot examples for chat modelsThis notebook covers how to use few-shot examples in chat models. There does not appear to be solid consensus on how best to do few-shot prompting, and the optimal prompt compilation will likely vary by model. Because of this, we provide few-shot prompt templates like the FewShotChatMessagePromptTemplate as a flexible starting point, and you can modify or replace them as you see fit.The goal of few-shot prompt templates are to dynamically select examples based on an input, and then format the examples in a final prompt to provide for the model.Note: The following code examples are for chat models. For similar few-shot prompt examples for completion models (LLMs), see the few-shot prompt templates guide.Fixed Examples​The most basic (and common) few-shot prompting technique is to use a fixed prompt example. This way you can select a chain, evaluate it, and avoid worrying about additional moving parts in production.The basic components of the template are:examples: A list of dictionary examples to include in the final prompt.example_prompt: converts each example into 1 or more messages through its format_messages method. A common example would be to convert each example into one human
This notebook covers how to use few-shot examples in chat models. There does not appear to be solid consensus on how best to do few-shot prompting, and the optimal prompt compilation will likely vary by model. Because of this, we provide few-shot prompt templates like the FewShotChatMessagePromptTemplate as a flexible starting point, and you can modify or replace them as you see fit.
This notebook covers how to use few-shot examples in chat models. There does not appear to be solid consensus on how best to do few-shot prompting, and the optimal prompt compilation will likely vary by model. Because of this, we provide few-shot prompt templates like the FewShotChatMessagePromptTemplate as a flexible starting point, and you can modify or replace them as you see fit. ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesConnecting to a Feature StoreCustom prompt templateFew-shot prompt templatesFew-shot examples for chat modelsFormat template outputTemplate formatsTypes of MessagePromptTemplatePartial prompt templatesCompositionSerializationPrompt pipeliningValidate templateExample selectorsLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsPrompt templatesFew-shot examples for chat modelsOn this pageFew-shot examples for chat modelsThis notebook covers how to use few-shot examples in chat models. There does not appear to be solid consensus on how best to do few-shot prompting, and the optimal prompt compilation will likely vary by model. Because of this, we provide few-shot prompt templates like the FewShotChatMessagePromptTemplate as a flexible starting point, and you can modify or replace them as you see fit.The goal of few-shot prompt templates are to dynamically select examples based on an input, and then format the examples in a final prompt to provide for the model.Note: The following code examples are for chat models. For similar few-shot prompt examples for completion models (LLMs), see the few-shot prompt templates guide.Fixed Examples​The most basic (and common) few-shot prompting technique is to use a fixed prompt example. This way you can select a chain, evaluate it, and avoid worrying about additional moving parts in production.The basic components of the template are:examples: A list of dictionary examples to include in the final prompt.example_prompt: converts each example into 1 or more messages through its format_messages method. A common example would be to convert each example into one human
34
would be to convert each example into one human message and one AI message response, or a human message followed by a function call message.Below is a simple demonstration. First, import the modules for this example:from langchain.prompts import ( FewShotChatMessagePromptTemplate, ChatPromptTemplate,)Then, define the examples you'd like to include.examples = [ {"input": "2+2", "output": "4"}, {"input": "2+3", "output": "5"},]Next, assemble them into the few-shot prompt template.# This is a prompt template used to format each individual example.example_prompt = ChatPromptTemplate.from_messages( [ ("human", "{input}"), ("ai", "{output}"), ])few_shot_prompt = FewShotChatMessagePromptTemplate( example_prompt=example_prompt, examples=examples,)print(few_shot_prompt.format()) Human: 2+2 AI: 4 Human: 2+3 AI: 5Finally, assemble your final prompt and use it with a model.final_prompt = ChatPromptTemplate.from_messages( [ ("system", "You are a wondrous wizard of math."), few_shot_prompt, ("human", "{input}"), ])from langchain.chat_models import ChatAnthropicchain = final_prompt | ChatAnthropic(temperature=0.0)chain.invoke({"input": "What's the square of a triangle?"}) AIMessage(content=' Triangles do not have a "square". A square refers to a shape with 4 equal sides and 4 right angles. Triangles have 3 sides and 3 angles.\n\nThe area of a triangle can be calculated using the formula:\n\nA = 1/2 * b * h\n\nWhere:\n\nA is the area \nb is the base (the length of one of the sides)\nh is the height (the length from the base to the opposite vertex)\n\nSo the area depends on the specific dimensions of the triangle. There is no single "square of a triangle". The area can vary greatly depending on the base and height measurements.', additional_kwargs={}, example=False)Dynamic few-shot prompting‚ÄãSometimes you may want to condition which examples are shown based on the input. For this, you can replace the
This notebook covers how to use few-shot examples in chat models. There does not appear to be solid consensus on how best to do few-shot prompting, and the optimal prompt compilation will likely vary by model. Because of this, we provide few-shot prompt templates like the FewShotChatMessagePromptTemplate as a flexible starting point, and you can modify or replace them as you see fit.
This notebook covers how to use few-shot examples in chat models. There does not appear to be solid consensus on how best to do few-shot prompting, and the optimal prompt compilation will likely vary by model. Because of this, we provide few-shot prompt templates like the FewShotChatMessagePromptTemplate as a flexible starting point, and you can modify or replace them as you see fit. ->: would be to convert each example into one human message and one AI message response, or a human message followed by a function call message.Below is a simple demonstration. First, import the modules for this example:from langchain.prompts import ( FewShotChatMessagePromptTemplate, ChatPromptTemplate,)Then, define the examples you'd like to include.examples = [ {"input": "2+2", "output": "4"}, {"input": "2+3", "output": "5"},]Next, assemble them into the few-shot prompt template.# This is a prompt template used to format each individual example.example_prompt = ChatPromptTemplate.from_messages( [ ("human", "{input}"), ("ai", "{output}"), ])few_shot_prompt = FewShotChatMessagePromptTemplate( example_prompt=example_prompt, examples=examples,)print(few_shot_prompt.format()) Human: 2+2 AI: 4 Human: 2+3 AI: 5Finally, assemble your final prompt and use it with a model.final_prompt = ChatPromptTemplate.from_messages( [ ("system", "You are a wondrous wizard of math."), few_shot_prompt, ("human", "{input}"), ])from langchain.chat_models import ChatAnthropicchain = final_prompt | ChatAnthropic(temperature=0.0)chain.invoke({"input": "What's the square of a triangle?"}) AIMessage(content=' Triangles do not have a "square". A square refers to a shape with 4 equal sides and 4 right angles. Triangles have 3 sides and 3 angles.\n\nThe area of a triangle can be calculated using the formula:\n\nA = 1/2 * b * h\n\nWhere:\n\nA is the area \nb is the base (the length of one of the sides)\nh is the height (the length from the base to the opposite vertex)\n\nSo the area depends on the specific dimensions of the triangle. There is no single "square of a triangle". The area can vary greatly depending on the base and height measurements.', additional_kwargs={}, example=False)Dynamic few-shot prompting‚ÄãSometimes you may want to condition which examples are shown based on the input. For this, you can replace the
35
based on the input. For this, you can replace the examples with an example_selector. The other components remain the same as above! To review, the dynamic few-shot prompt template would look like:example_selector: responsible for selecting few-shot examples (and the order in which they are returned) for a given input. These implement the BaseExampleSelector interface. A common example is the vectorstore-backed SemanticSimilarityExampleSelectorexample_prompt: convert each example into 1 or more messages through its format_messages method. A common example would be to convert each example into one human message and one AI message response, or a human message followed by a function call message.These once again can be composed with other messages and chat templates to assemble your final prompt.from langchain.prompts import SemanticSimilarityExampleSelectorfrom langchain.embeddings import OpenAIEmbeddingsfrom langchain.vectorstores import ChromaSince we are using a vectorstore to select examples based on semantic similarity, we will want to first populate the store.examples = [ {"input": "2+2", "output": "4"}, {"input": "2+3", "output": "5"}, {"input": "2+4", "output": "6"}, {"input": "What did the cow say to the moon?", "output": "nothing at all"}, { "input": "Write me a poem about the moon", "output": "One for the moon, and one for me, who are we to talk about the moon?", },]to_vectorize = [" ".join(example.values()) for example in examples]embeddings = OpenAIEmbeddings()vectorstore = Chroma.from_texts(to_vectorize, embeddings, metadatas=examples)Create the example_selector‚ÄãWith a vectorstore created, you can create the example_selector. Here we will isntruct it to only fetch the top 2 examples.example_selector = SemanticSimilarityExampleSelector( vectorstore=vectorstore, k=2,)# The prompt template will load examples by passing the input do the `select_examples` methodexample_selector.select_examples({"input": "horse"})
This notebook covers how to use few-shot examples in chat models. There does not appear to be solid consensus on how best to do few-shot prompting, and the optimal prompt compilation will likely vary by model. Because of this, we provide few-shot prompt templates like the FewShotChatMessagePromptTemplate as a flexible starting point, and you can modify or replace them as you see fit.
This notebook covers how to use few-shot examples in chat models. There does not appear to be solid consensus on how best to do few-shot prompting, and the optimal prompt compilation will likely vary by model. Because of this, we provide few-shot prompt templates like the FewShotChatMessagePromptTemplate as a flexible starting point, and you can modify or replace them as you see fit. ->: based on the input. For this, you can replace the examples with an example_selector. The other components remain the same as above! To review, the dynamic few-shot prompt template would look like:example_selector: responsible for selecting few-shot examples (and the order in which they are returned) for a given input. These implement the BaseExampleSelector interface. A common example is the vectorstore-backed SemanticSimilarityExampleSelectorexample_prompt: convert each example into 1 or more messages through its format_messages method. A common example would be to convert each example into one human message and one AI message response, or a human message followed by a function call message.These once again can be composed with other messages and chat templates to assemble your final prompt.from langchain.prompts import SemanticSimilarityExampleSelectorfrom langchain.embeddings import OpenAIEmbeddingsfrom langchain.vectorstores import ChromaSince we are using a vectorstore to select examples based on semantic similarity, we will want to first populate the store.examples = [ {"input": "2+2", "output": "4"}, {"input": "2+3", "output": "5"}, {"input": "2+4", "output": "6"}, {"input": "What did the cow say to the moon?", "output": "nothing at all"}, { "input": "Write me a poem about the moon", "output": "One for the moon, and one for me, who are we to talk about the moon?", },]to_vectorize = [" ".join(example.values()) for example in examples]embeddings = OpenAIEmbeddings()vectorstore = Chroma.from_texts(to_vectorize, embeddings, metadatas=examples)Create the example_selector‚ÄãWith a vectorstore created, you can create the example_selector. Here we will isntruct it to only fetch the top 2 examples.example_selector = SemanticSimilarityExampleSelector( vectorstore=vectorstore, k=2,)# The prompt template will load examples by passing the input do the `select_examples` methodexample_selector.select_examples({"input": "horse"})
36
"horse"}) [{'input': 'What did the cow say to the moon?', 'output': 'nothing at all'}, {'input': '2+4', 'output': '6'}]Create prompt template​Assemble the prompt template, using the example_selector created above.from langchain.prompts import ( FewShotChatMessagePromptTemplate, ChatPromptTemplate,)# Define the few-shot prompt.few_shot_prompt = FewShotChatMessagePromptTemplate( # The input variables select the values to pass to the example_selector input_variables=["input"], example_selector=example_selector, # Define how each example will be formatted. # In this case, each example will become 2 messages: # 1 human, and 1 AI example_prompt=ChatPromptTemplate.from_messages( [("human", "{input}"), ("ai", "{output}")] ),)Below is an example of how this would be assembled.print(few_shot_prompt.format(input="What's 3+3?")) Human: 2+3 AI: 5 Human: 2+2 AI: 4Assemble the final prompt template:final_prompt = ChatPromptTemplate.from_messages( [ ("system", "You are a wondrous wizard of math."), few_shot_prompt, ("human", "{input}"), ])print(few_shot_prompt.format(input="What's 3+3?")) Human: 2+3 AI: 5 Human: 2+2 AI: 4Use with an LLM​Now, you can connect your model to the few-shot prompt.from langchain.chat_models import ChatAnthropicchain = final_prompt | ChatAnthropic(temperature=0.0)chain.invoke({"input": "What's 3+3?"}) AIMessage(content=' 3 + 3 = 6', additional_kwargs={}, example=False)PreviousFew-shot prompt templatesNextFormat template outputFixed ExamplesDynamic few-shot promptingCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
This notebook covers how to use few-shot examples in chat models. There does not appear to be solid consensus on how best to do few-shot prompting, and the optimal prompt compilation will likely vary by model. Because of this, we provide few-shot prompt templates like the FewShotChatMessagePromptTemplate as a flexible starting point, and you can modify or replace them as you see fit.
This notebook covers how to use few-shot examples in chat models. There does not appear to be solid consensus on how best to do few-shot prompting, and the optimal prompt compilation will likely vary by model. Because of this, we provide few-shot prompt templates like the FewShotChatMessagePromptTemplate as a flexible starting point, and you can modify or replace them as you see fit. ->: "horse"}) [{'input': 'What did the cow say to the moon?', 'output': 'nothing at all'}, {'input': '2+4', 'output': '6'}]Create prompt template​Assemble the prompt template, using the example_selector created above.from langchain.prompts import ( FewShotChatMessagePromptTemplate, ChatPromptTemplate,)# Define the few-shot prompt.few_shot_prompt = FewShotChatMessagePromptTemplate( # The input variables select the values to pass to the example_selector input_variables=["input"], example_selector=example_selector, # Define how each example will be formatted. # In this case, each example will become 2 messages: # 1 human, and 1 AI example_prompt=ChatPromptTemplate.from_messages( [("human", "{input}"), ("ai", "{output}")] ),)Below is an example of how this would be assembled.print(few_shot_prompt.format(input="What's 3+3?")) Human: 2+3 AI: 5 Human: 2+2 AI: 4Assemble the final prompt template:final_prompt = ChatPromptTemplate.from_messages( [ ("system", "You are a wondrous wizard of math."), few_shot_prompt, ("human", "{input}"), ])print(few_shot_prompt.format(input="What's 3+3?")) Human: 2+3 AI: 5 Human: 2+2 AI: 4Use with an LLM​Now, you can connect your model to the few-shot prompt.from langchain.chat_models import ChatAnthropicchain = final_prompt | ChatAnthropic(temperature=0.0)chain.invoke({"input": "What's 3+3?"}) AIMessage(content=' 3 + 3 = 6', additional_kwargs={}, example=False)PreviousFew-shot prompt templatesNextFormat template outputFixed ExamplesDynamic few-shot promptingCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
37
Types of MessagePromptTemplate | 🦜️🔗 Langchain
LangChain provides different types of MessagePromptTemplate. The most commonly used are AIMessagePromptTemplate, SystemMessagePromptTemplate and HumanMessagePromptTemplate, which create an AI message, system message and human message respectively.
LangChain provides different types of MessagePromptTemplate. The most commonly used are AIMessagePromptTemplate, SystemMessagePromptTemplate and HumanMessagePromptTemplate, which create an AI message, system message and human message respectively. ->: Types of MessagePromptTemplate | 🦜️🔗 Langchain
38
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesConnecting to a Feature StoreCustom prompt templateFew-shot prompt templatesFew-shot examples for chat modelsFormat template outputTemplate formatsTypes of MessagePromptTemplatePartial prompt templatesCompositionSerializationPrompt pipeliningValidate templateExample selectorsLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsPrompt templatesTypes of MessagePromptTemplateTypes of MessagePromptTemplateLangChain provides different types of MessagePromptTemplate. The most commonly used are AIMessagePromptTemplate, SystemMessagePromptTemplate and HumanMessagePromptTemplate, which create an AI message, system message and human message respectively.However, in cases where the chat model supports taking chat message with arbitrary role, you can use ChatMessagePromptTemplate, which allows user to specify the role name.from langchain.prompts import ChatMessagePromptTemplateprompt = "May the {subject} be with you"chat_message_prompt = ChatMessagePromptTemplate.from_template(role="Jedi", template=prompt)chat_message_prompt.format(subject="force") ChatMessage(content='May the force be with you', additional_kwargs={}, role='Jedi')LangChain also provides MessagesPlaceholder, which gives you full control of what messages to be rendered during formatting. This can be useful when you are uncertain of what role you should be using for your message prompt templates or when you wish to insert a list of messages during formatting.from langchain.prompts import MessagesPlaceholderhuman_prompt = "Summarize our conversation so far in {word_count} words."human_message_template =
LangChain provides different types of MessagePromptTemplate. The most commonly used are AIMessagePromptTemplate, SystemMessagePromptTemplate and HumanMessagePromptTemplate, which create an AI message, system message and human message respectively.
LangChain provides different types of MessagePromptTemplate. The most commonly used are AIMessagePromptTemplate, SystemMessagePromptTemplate and HumanMessagePromptTemplate, which create an AI message, system message and human message respectively. ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesConnecting to a Feature StoreCustom prompt templateFew-shot prompt templatesFew-shot examples for chat modelsFormat template outputTemplate formatsTypes of MessagePromptTemplatePartial prompt templatesCompositionSerializationPrompt pipeliningValidate templateExample selectorsLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsPrompt templatesTypes of MessagePromptTemplateTypes of MessagePromptTemplateLangChain provides different types of MessagePromptTemplate. The most commonly used are AIMessagePromptTemplate, SystemMessagePromptTemplate and HumanMessagePromptTemplate, which create an AI message, system message and human message respectively.However, in cases where the chat model supports taking chat message with arbitrary role, you can use ChatMessagePromptTemplate, which allows user to specify the role name.from langchain.prompts import ChatMessagePromptTemplateprompt = "May the {subject} be with you"chat_message_prompt = ChatMessagePromptTemplate.from_template(role="Jedi", template=prompt)chat_message_prompt.format(subject="force") ChatMessage(content='May the force be with you', additional_kwargs={}, role='Jedi')LangChain also provides MessagesPlaceholder, which gives you full control of what messages to be rendered during formatting. This can be useful when you are uncertain of what role you should be using for your message prompt templates or when you wish to insert a list of messages during formatting.from langchain.prompts import MessagesPlaceholderhuman_prompt = "Summarize our conversation so far in {word_count} words."human_message_template =
39
in {word_count} words."human_message_template = HumanMessagePromptTemplate.from_template(human_prompt)chat_prompt = ChatPromptTemplate.from_messages([MessagesPlaceholder(variable_name="conversation"), human_message_template])human_message = HumanMessage(content="What is the best way to learn programming?")ai_message = AIMessage(content="""\1. Choose a programming language: Decide on a programming language that you want to learn.2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures.3. Practice, practice, practice: The best way to learn programming is through hands-on experience\""")chat_prompt.format_prompt(conversation=[human_message, ai_message], word_count="10").to_messages() [HumanMessage(content='What is the best way to learn programming?', additional_kwargs={}), AIMessage(content='1. Choose a programming language: Decide on a programming language that you want to learn. \n\n2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures.\n\n3. Practice, practice, practice: The best way to learn programming is through hands-on experience', additional_kwargs={}), HumanMessage(content='Summarize our conversation so far in 10 words.', additional_kwargs={})]PreviousTemplate formatsNextPartial prompt templatesCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
LangChain provides different types of MessagePromptTemplate. The most commonly used are AIMessagePromptTemplate, SystemMessagePromptTemplate and HumanMessagePromptTemplate, which create an AI message, system message and human message respectively.
LangChain provides different types of MessagePromptTemplate. The most commonly used are AIMessagePromptTemplate, SystemMessagePromptTemplate and HumanMessagePromptTemplate, which create an AI message, system message and human message respectively. ->: in {word_count} words."human_message_template = HumanMessagePromptTemplate.from_template(human_prompt)chat_prompt = ChatPromptTemplate.from_messages([MessagesPlaceholder(variable_name="conversation"), human_message_template])human_message = HumanMessage(content="What is the best way to learn programming?")ai_message = AIMessage(content="""\1. Choose a programming language: Decide on a programming language that you want to learn.2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures.3. Practice, practice, practice: The best way to learn programming is through hands-on experience\""")chat_prompt.format_prompt(conversation=[human_message, ai_message], word_count="10").to_messages() [HumanMessage(content='What is the best way to learn programming?', additional_kwargs={}), AIMessage(content='1. Choose a programming language: Decide on a programming language that you want to learn. \n\n2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures.\n\n3. Practice, practice, practice: The best way to learn programming is through hands-on experience', additional_kwargs={}), HumanMessage(content='Summarize our conversation so far in 10 words.', additional_kwargs={})]PreviousTemplate formatsNextPartial prompt templatesCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
40
Format template output | 🦜️🔗 Langchain
The output of the format method is available as a string, list of messages and ChatPromptValue
The output of the format method is available as a string, list of messages and ChatPromptValue ->: Format template output | 🦜️🔗 Langchain
41
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesConnecting to a Feature StoreCustom prompt templateFew-shot prompt templatesFew-shot examples for chat modelsFormat template outputTemplate formatsTypes of MessagePromptTemplatePartial prompt templatesCompositionSerializationPrompt pipeliningValidate templateExample selectorsLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsPrompt templatesFormat template outputFormat template outputThe output of the format method is available as a string, list of messages and ChatPromptValueAs string:output = chat_prompt.format(input_language="English", output_language="French", text="I love programming.")output 'System: You are a helpful assistant that translates English to French.\nHuman: I love programming.'# or alternativelyoutput_2 = chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_string()assert output == output_2As list of Message objects:chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_messages() [SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}), HumanMessage(content='I love programming.', additional_kwargs={})]As ChatPromptValue:chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.") ChatPromptValue(messages=[SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}), HumanMessage(content='I love programming.', additional_kwargs={})])PreviousFew-shot examples for chat modelsNextTemplate
The output of the format method is available as a string, list of messages and ChatPromptValue
The output of the format method is available as a string, list of messages and ChatPromptValue ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesConnecting to a Feature StoreCustom prompt templateFew-shot prompt templatesFew-shot examples for chat modelsFormat template outputTemplate formatsTypes of MessagePromptTemplatePartial prompt templatesCompositionSerializationPrompt pipeliningValidate templateExample selectorsLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsPrompt templatesFormat template outputFormat template outputThe output of the format method is available as a string, list of messages and ChatPromptValueAs string:output = chat_prompt.format(input_language="English", output_language="French", text="I love programming.")output 'System: You are a helpful assistant that translates English to French.\nHuman: I love programming.'# or alternativelyoutput_2 = chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_string()assert output == output_2As list of Message objects:chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_messages() [SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}), HumanMessage(content='I love programming.', additional_kwargs={})]As ChatPromptValue:chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.") ChatPromptValue(messages=[SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}), HumanMessage(content='I love programming.', additional_kwargs={})])PreviousFew-shot examples for chat modelsNextTemplate
42
examples for chat modelsNextTemplate formatsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
The output of the format method is available as a string, list of messages and ChatPromptValue
The output of the format method is available as a string, list of messages and ChatPromptValue ->: examples for chat modelsNextTemplate formatsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
43
Composition | 🦜️🔗 Langchain
This notebook goes over how to compose multiple prompts together. This can be useful when you want to reuse parts of prompts. This can be done with a PipelinePrompt. A PipelinePrompt consists of two main parts:
This notebook goes over how to compose multiple prompts together. This can be useful when you want to reuse parts of prompts. This can be done with a PipelinePrompt. A PipelinePrompt consists of two main parts: ->: Composition | 🦜️🔗 Langchain
44
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesConnecting to a Feature StoreCustom prompt templateFew-shot prompt templatesFew-shot examples for chat modelsFormat template outputTemplate formatsTypes of MessagePromptTemplatePartial prompt templatesCompositionSerializationPrompt pipeliningValidate templateExample selectorsLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsPrompt templatesCompositionCompositionThis notebook goes over how to compose multiple prompts together. This can be useful when you want to reuse parts of prompts. This can be done with a PipelinePrompt. A PipelinePrompt consists of two main parts:Final prompt: The final prompt that is returnedPipeline prompts: A list of tuples, consisting of a string name and a prompt template. Each prompt template will be formatted and then passed to future prompt templates as a variable with the same name.from langchain.prompts.pipeline import PipelinePromptTemplatefrom langchain.prompts.prompt import PromptTemplatefull_template = """{introduction}{example}{start}"""full_prompt = PromptTemplate.from_template(full_template)introduction_template = """You are impersonating {person}."""introduction_prompt = PromptTemplate.from_template(introduction_template)example_template = """Here's an example of an interaction:Q: {example_q}A: {example_a}"""example_prompt = PromptTemplate.from_template(example_template)start_template = """Now, do this for real!Q: {input}A:"""start_prompt = PromptTemplate.from_template(start_template)input_prompts = [ ("introduction", introduction_prompt), ("example", example_prompt), ("start", start_prompt)]pipeline_prompt =
This notebook goes over how to compose multiple prompts together. This can be useful when you want to reuse parts of prompts. This can be done with a PipelinePrompt. A PipelinePrompt consists of two main parts:
This notebook goes over how to compose multiple prompts together. This can be useful when you want to reuse parts of prompts. This can be done with a PipelinePrompt. A PipelinePrompt consists of two main parts: ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesConnecting to a Feature StoreCustom prompt templateFew-shot prompt templatesFew-shot examples for chat modelsFormat template outputTemplate formatsTypes of MessagePromptTemplatePartial prompt templatesCompositionSerializationPrompt pipeliningValidate templateExample selectorsLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsPrompt templatesCompositionCompositionThis notebook goes over how to compose multiple prompts together. This can be useful when you want to reuse parts of prompts. This can be done with a PipelinePrompt. A PipelinePrompt consists of two main parts:Final prompt: The final prompt that is returnedPipeline prompts: A list of tuples, consisting of a string name and a prompt template. Each prompt template will be formatted and then passed to future prompt templates as a variable with the same name.from langchain.prompts.pipeline import PipelinePromptTemplatefrom langchain.prompts.prompt import PromptTemplatefull_template = """{introduction}{example}{start}"""full_prompt = PromptTemplate.from_template(full_template)introduction_template = """You are impersonating {person}."""introduction_prompt = PromptTemplate.from_template(introduction_template)example_template = """Here's an example of an interaction:Q: {example_q}A: {example_a}"""example_prompt = PromptTemplate.from_template(example_template)start_template = """Now, do this for real!Q: {input}A:"""start_prompt = PromptTemplate.from_template(start_template)input_prompts = [ ("introduction", introduction_prompt), ("example", example_prompt), ("start", start_prompt)]pipeline_prompt =
45
("start", start_prompt)]pipeline_prompt = PipelinePromptTemplate(final_prompt=full_prompt, pipeline_prompts=input_prompts)pipeline_prompt.input_variables ['example_a', 'person', 'example_q', 'input']print(pipeline_prompt.format( person="Elon Musk", example_q="What's your favorite car?", example_a="Tesla", input="What's your favorite social media site?")) You are impersonating Elon Musk. Here's an example of an interaction: Q: What's your favorite car? A: Tesla Now, do this for real! Q: What's your favorite social media site? A:PreviousPartial prompt templatesNextSerializationCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
This notebook goes over how to compose multiple prompts together. This can be useful when you want to reuse parts of prompts. This can be done with a PipelinePrompt. A PipelinePrompt consists of two main parts:
This notebook goes over how to compose multiple prompts together. This can be useful when you want to reuse parts of prompts. This can be done with a PipelinePrompt. A PipelinePrompt consists of two main parts: ->: ("start", start_prompt)]pipeline_prompt = PipelinePromptTemplate(final_prompt=full_prompt, pipeline_prompts=input_prompts)pipeline_prompt.input_variables ['example_a', 'person', 'example_q', 'input']print(pipeline_prompt.format( person="Elon Musk", example_q="What's your favorite car?", example_a="Tesla", input="What's your favorite social media site?")) You are impersonating Elon Musk. Here's an example of an interaction: Q: What's your favorite car? A: Tesla Now, do this for real! Q: What's your favorite social media site? A:PreviousPartial prompt templatesNextSerializationCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
46
Partial prompt templates | 🦜️🔗 Langchain
Like other methods, it can make sense to "partial" a prompt template - e.g. pass in a subset of the required values, as to create a new prompt template which expects only the remaining subset of values.
Like other methods, it can make sense to "partial" a prompt template - e.g. pass in a subset of the required values, as to create a new prompt template which expects only the remaining subset of values. ->: Partial prompt templates | 🦜️🔗 Langchain
47
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesConnecting to a Feature StoreCustom prompt templateFew-shot prompt templatesFew-shot examples for chat modelsFormat template outputTemplate formatsTypes of MessagePromptTemplatePartial prompt templatesCompositionSerializationPrompt pipeliningValidate templateExample selectorsLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsPrompt templatesPartial prompt templatesOn this pagePartial prompt templatesLike other methods, it can make sense to "partial" a prompt template - e.g. pass in a subset of the required values, as to create a new prompt template which expects only the remaining subset of values.LangChain supports this in two ways:Partial formatting with string values.Partial formatting with functions that return string values.These two different ways support different use cases. In the examples below, we go over the motivations for both use cases as well as how to do it in LangChain.Partial with strings​One common use case for wanting to partial a prompt template is if you get some of the variables before others. For example, suppose you have a prompt template that requires two variables, foo and baz. If you get the foo value early on in the chain, but the baz value later, it can be annoying to wait until you have both variables in the same place to pass them to the prompt template. Instead, you can partial the prompt template with the foo value, and then pass the partialed prompt template along and just use that. Below is an example of doing this:from langchain.prompts import PromptTemplateprompt = PromptTemplate(template="{foo}{bar}", input_variables=["foo", "bar"])partial_prompt =
Like other methods, it can make sense to "partial" a prompt template - e.g. pass in a subset of the required values, as to create a new prompt template which expects only the remaining subset of values.
Like other methods, it can make sense to "partial" a prompt template - e.g. pass in a subset of the required values, as to create a new prompt template which expects only the remaining subset of values. ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesConnecting to a Feature StoreCustom prompt templateFew-shot prompt templatesFew-shot examples for chat modelsFormat template outputTemplate formatsTypes of MessagePromptTemplatePartial prompt templatesCompositionSerializationPrompt pipeliningValidate templateExample selectorsLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsPrompt templatesPartial prompt templatesOn this pagePartial prompt templatesLike other methods, it can make sense to "partial" a prompt template - e.g. pass in a subset of the required values, as to create a new prompt template which expects only the remaining subset of values.LangChain supports this in two ways:Partial formatting with string values.Partial formatting with functions that return string values.These two different ways support different use cases. In the examples below, we go over the motivations for both use cases as well as how to do it in LangChain.Partial with strings​One common use case for wanting to partial a prompt template is if you get some of the variables before others. For example, suppose you have a prompt template that requires two variables, foo and baz. If you get the foo value early on in the chain, but the baz value later, it can be annoying to wait until you have both variables in the same place to pass them to the prompt template. Instead, you can partial the prompt template with the foo value, and then pass the partialed prompt template along and just use that. Below is an example of doing this:from langchain.prompts import PromptTemplateprompt = PromptTemplate(template="{foo}{bar}", input_variables=["foo", "bar"])partial_prompt =
48
input_variables=["foo", "bar"])partial_prompt = prompt.partial(foo="foo");print(partial_prompt.format(bar="baz")) foobazYou can also just initialize the prompt with the partialed variables.prompt = PromptTemplate(template="{foo}{bar}", input_variables=["bar"], partial_variables={"foo": "foo"})print(prompt.format(bar="baz")) foobazPartial with functions​The other common use is to 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 is a bit annoying. In this case, it's very handy to be able to partial the prompt with a function that always returns the current date.from datetime import datetimedef _get_datetime(): now = datetime.now() return now.strftime("%m/%d/%Y, %H:%M:%S")prompt = PromptTemplate( template="Tell me a {adjective} joke about the day {date}", input_variables=["adjective", "date"]);partial_prompt = prompt.partial(date=_get_datetime)print(partial_prompt.format(adjective="funny")) Tell me a funny joke about the day 02/27/2023, 22:15:16You can also just initialize the prompt with the partialed variables, which often makes more sense in this workflow.prompt = PromptTemplate( template="Tell me a {adjective} joke about the day {date}", input_variables=["adjective"], partial_variables={"date": _get_datetime});print(prompt.format(adjective="funny")) Tell me a funny joke about the day 02/27/2023, 22:15:16PreviousTypes of MessagePromptTemplateNextCompositionPartial with stringsPartial with functionsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
Like other methods, it can make sense to "partial" a prompt template - e.g. pass in a subset of the required values, as to create a new prompt template which expects only the remaining subset of values.
Like other methods, it can make sense to "partial" a prompt template - e.g. pass in a subset of the required values, as to create a new prompt template which expects only the remaining subset of values. ->: input_variables=["foo", "bar"])partial_prompt = prompt.partial(foo="foo");print(partial_prompt.format(bar="baz")) foobazYou can also just initialize the prompt with the partialed variables.prompt = PromptTemplate(template="{foo}{bar}", input_variables=["bar"], partial_variables={"foo": "foo"})print(prompt.format(bar="baz")) foobazPartial with functions​The other common use is to 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 is a bit annoying. In this case, it's very handy to be able to partial the prompt with a function that always returns the current date.from datetime import datetimedef _get_datetime(): now = datetime.now() return now.strftime("%m/%d/%Y, %H:%M:%S")prompt = PromptTemplate( template="Tell me a {adjective} joke about the day {date}", input_variables=["adjective", "date"]);partial_prompt = prompt.partial(date=_get_datetime)print(partial_prompt.format(adjective="funny")) Tell me a funny joke about the day 02/27/2023, 22:15:16You can also just initialize the prompt with the partialed variables, which often makes more sense in this workflow.prompt = PromptTemplate( template="Tell me a {adjective} joke about the day {date}", input_variables=["adjective"], partial_variables={"date": _get_datetime});print(prompt.format(adjective="funny")) Tell me a funny joke about the day 02/27/2023, 22:15:16PreviousTypes of MessagePromptTemplateNextCompositionPartial with stringsPartial with functionsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
49
Few-shot prompt templates | 🦜️🔗 Langchain
In this tutorial, we'll learn how to create a prompt template that uses few-shot examples. A few-shot prompt template can be constructed from either a set of examples, or from an Example Selector object.
In this tutorial, we'll learn how to create a prompt template that uses few-shot examples. A few-shot prompt template can be constructed from either a set of examples, or from an Example Selector object. ->: Few-shot prompt templates | 🦜️🔗 Langchain
50
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesConnecting to a Feature StoreCustom prompt templateFew-shot prompt templatesFew-shot examples for chat modelsFormat template outputTemplate formatsTypes of MessagePromptTemplatePartial prompt templatesCompositionSerializationPrompt pipeliningValidate templateExample selectorsLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsPrompt templatesFew-shot prompt templatesOn this pageFew-shot prompt templatesIn this tutorial, we'll learn how to create a prompt template that uses few-shot examples. A few-shot prompt template can be constructed from either a set of examples, or from an Example Selector object.Use Case​In this tutorial, we'll configure few-shot examples for self-ask with search.Using an example set​Create the example set​To get started, create a list of few-shot examples. Each example should be a dictionary with the keys being the input variables and the values being the values for those input variables.from langchain.prompts.few_shot import FewShotPromptTemplatefrom langchain.prompts.prompt import PromptTemplateexamples = [ { "question": "Who lived longer, Muhammad Ali or Alan Turing?", "answer":"""Are follow up questions needed here: Yes.Follow up: How old was Muhammad Ali when he died?Intermediate answer: Muhammad Ali was 74 years old when he died.Follow up: How old was Alan Turing when he died?Intermediate answer: Alan Turing was 41 years old when he died.So the final answer is: Muhammad Ali""" }, { "question": "When was the founder of craigslist born?", "answer":"""Are follow up questions needed here: Yes.Follow up: Who was the founder of craigslist?Intermediate
In this tutorial, we'll learn how to create a prompt template that uses few-shot examples. A few-shot prompt template can be constructed from either a set of examples, or from an Example Selector object.
In this tutorial, we'll learn how to create a prompt template that uses few-shot examples. A few-shot prompt template can be constructed from either a set of examples, or from an Example Selector object. ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesConnecting to a Feature StoreCustom prompt templateFew-shot prompt templatesFew-shot examples for chat modelsFormat template outputTemplate formatsTypes of MessagePromptTemplatePartial prompt templatesCompositionSerializationPrompt pipeliningValidate templateExample selectorsLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsPrompt templatesFew-shot prompt templatesOn this pageFew-shot prompt templatesIn this tutorial, we'll learn how to create a prompt template that uses few-shot examples. A few-shot prompt template can be constructed from either a set of examples, or from an Example Selector object.Use Case​In this tutorial, we'll configure few-shot examples for self-ask with search.Using an example set​Create the example set​To get started, create a list of few-shot examples. Each example should be a dictionary with the keys being the input variables and the values being the values for those input variables.from langchain.prompts.few_shot import FewShotPromptTemplatefrom langchain.prompts.prompt import PromptTemplateexamples = [ { "question": "Who lived longer, Muhammad Ali or Alan Turing?", "answer":"""Are follow up questions needed here: Yes.Follow up: How old was Muhammad Ali when he died?Intermediate answer: Muhammad Ali was 74 years old when he died.Follow up: How old was Alan Turing when he died?Intermediate answer: Alan Turing was 41 years old when he died.So the final answer is: Muhammad Ali""" }, { "question": "When was the founder of craigslist born?", "answer":"""Are follow up questions needed here: Yes.Follow up: Who was the founder of craigslist?Intermediate
51
Who was the founder of craigslist?Intermediate answer: Craigslist was founded by Craig Newmark.Follow up: When was Craig Newmark born?Intermediate answer: Craig Newmark was born on December 6, 1952.So the final answer is: December 6, 1952""" }, { "question": "Who was the maternal grandfather of George Washington?", "answer":"""Are follow up questions needed here: Yes.Follow up: Who was the mother of George Washington?Intermediate answer: The mother of George Washington was Mary Ball Washington.Follow up: Who was the father of Mary Ball Washington?Intermediate answer: The father of Mary Ball Washington was Joseph Ball.So the final answer is: Joseph Ball""" }, { "question": "Are both the directors of Jaws and Casino Royale from the same country?", "answer":"""Are follow up questions needed here: Yes.Follow up: Who is the director of Jaws?Intermediate Answer: The director of Jaws is Steven Spielberg.Follow up: Where is Steven Spielberg from?Intermediate Answer: The United States.Follow up: Who is the director of Casino Royale?Intermediate Answer: The director of Casino Royale is Martin Campbell.Follow up: Where is Martin Campbell from?Intermediate Answer: New Zealand.So the final answer is: No""" }]Create a formatter for the few-shot examples‚ÄãConfigure a formatter that will format the few-shot examples into a string. This formatter should be a PromptTemplate object.example_prompt = PromptTemplate(input_variables=["question", "answer"], template="Question: {question}\n{answer}")print(example_prompt.format(**examples[0])) Question: Who lived longer, Muhammad Ali or Alan Turing? Are follow up questions needed here: Yes. Follow up: How old was Muhammad Ali when he died? Intermediate answer: Muhammad Ali was 74 years old when he died. Follow up: How old was Alan Turing when he died? Intermediate answer: Alan Turing was 41 years old when he died. So the final answer is: Muhammad AliFeed examples and formatter to
In this tutorial, we'll learn how to create a prompt template that uses few-shot examples. A few-shot prompt template can be constructed from either a set of examples, or from an Example Selector object.
In this tutorial, we'll learn how to create a prompt template that uses few-shot examples. A few-shot prompt template can be constructed from either a set of examples, or from an Example Selector object. ->: Who was the founder of craigslist?Intermediate answer: Craigslist was founded by Craig Newmark.Follow up: When was Craig Newmark born?Intermediate answer: Craig Newmark was born on December 6, 1952.So the final answer is: December 6, 1952""" }, { "question": "Who was the maternal grandfather of George Washington?", "answer":"""Are follow up questions needed here: Yes.Follow up: Who was the mother of George Washington?Intermediate answer: The mother of George Washington was Mary Ball Washington.Follow up: Who was the father of Mary Ball Washington?Intermediate answer: The father of Mary Ball Washington was Joseph Ball.So the final answer is: Joseph Ball""" }, { "question": "Are both the directors of Jaws and Casino Royale from the same country?", "answer":"""Are follow up questions needed here: Yes.Follow up: Who is the director of Jaws?Intermediate Answer: The director of Jaws is Steven Spielberg.Follow up: Where is Steven Spielberg from?Intermediate Answer: The United States.Follow up: Who is the director of Casino Royale?Intermediate Answer: The director of Casino Royale is Martin Campbell.Follow up: Where is Martin Campbell from?Intermediate Answer: New Zealand.So the final answer is: No""" }]Create a formatter for the few-shot examples‚ÄãConfigure a formatter that will format the few-shot examples into a string. This formatter should be a PromptTemplate object.example_prompt = PromptTemplate(input_variables=["question", "answer"], template="Question: {question}\n{answer}")print(example_prompt.format(**examples[0])) Question: Who lived longer, Muhammad Ali or Alan Turing? Are follow up questions needed here: Yes. Follow up: How old was Muhammad Ali when he died? Intermediate answer: Muhammad Ali was 74 years old when he died. Follow up: How old was Alan Turing when he died? Intermediate answer: Alan Turing was 41 years old when he died. So the final answer is: Muhammad AliFeed examples and formatter to
52
is: Muhammad AliFeed examples and formatter to FewShotPromptTemplate‚ÄãFinally, create a FewShotPromptTemplate object. This object takes in the few-shot examples and the formatter for the few-shot examples.prompt = FewShotPromptTemplate( examples=examples, example_prompt=example_prompt, suffix="Question: {input}", input_variables=["input"])print(prompt.format(input="Who was the father of Mary Ball Washington?")) Question: Who lived longer, Muhammad Ali or Alan Turing? Are follow up questions needed here: Yes. Follow up: How old was Muhammad Ali when he died? Intermediate answer: Muhammad Ali was 74 years old when he died. Follow up: How old was Alan Turing when he died? Intermediate answer: Alan Turing was 41 years old when he died. So the final answer is: Muhammad Ali Question: When was the founder of craigslist born? Are follow up questions needed here: Yes. Follow up: Who was the founder of craigslist? Intermediate answer: Craigslist was founded by Craig Newmark. Follow up: When was Craig Newmark born? Intermediate answer: Craig Newmark was born on December 6, 1952. So the final answer is: December 6, 1952 Question: Who was the maternal grandfather of George Washington? Are follow up questions needed here: Yes. Follow up: Who was the mother of George Washington? Intermediate answer: The mother of George Washington was Mary Ball Washington. Follow up: Who was the father of Mary Ball Washington? Intermediate answer: The father of Mary Ball Washington was Joseph Ball. So the final answer is: Joseph Ball Question: Are both the directors of Jaws and Casino Royale from the same country? Are follow up questions needed here: Yes. Follow up: Who is the director of Jaws? Intermediate Answer: The director of Jaws is Steven Spielberg. Follow up: Where is Steven Spielberg from? Intermediate Answer: The United States. Follow up: Who is the director of Casino Royale? Intermediate
In this tutorial, we'll learn how to create a prompt template that uses few-shot examples. A few-shot prompt template can be constructed from either a set of examples, or from an Example Selector object.
In this tutorial, we'll learn how to create a prompt template that uses few-shot examples. A few-shot prompt template can be constructed from either a set of examples, or from an Example Selector object. ->: is: Muhammad AliFeed examples and formatter to FewShotPromptTemplate‚ÄãFinally, create a FewShotPromptTemplate object. This object takes in the few-shot examples and the formatter for the few-shot examples.prompt = FewShotPromptTemplate( examples=examples, example_prompt=example_prompt, suffix="Question: {input}", input_variables=["input"])print(prompt.format(input="Who was the father of Mary Ball Washington?")) Question: Who lived longer, Muhammad Ali or Alan Turing? Are follow up questions needed here: Yes. Follow up: How old was Muhammad Ali when he died? Intermediate answer: Muhammad Ali was 74 years old when he died. Follow up: How old was Alan Turing when he died? Intermediate answer: Alan Turing was 41 years old when he died. So the final answer is: Muhammad Ali Question: When was the founder of craigslist born? Are follow up questions needed here: Yes. Follow up: Who was the founder of craigslist? Intermediate answer: Craigslist was founded by Craig Newmark. Follow up: When was Craig Newmark born? Intermediate answer: Craig Newmark was born on December 6, 1952. So the final answer is: December 6, 1952 Question: Who was the maternal grandfather of George Washington? Are follow up questions needed here: Yes. Follow up: Who was the mother of George Washington? Intermediate answer: The mother of George Washington was Mary Ball Washington. Follow up: Who was the father of Mary Ball Washington? Intermediate answer: The father of Mary Ball Washington was Joseph Ball. So the final answer is: Joseph Ball Question: Are both the directors of Jaws and Casino Royale from the same country? Are follow up questions needed here: Yes. Follow up: Who is the director of Jaws? Intermediate Answer: The director of Jaws is Steven Spielberg. Follow up: Where is Steven Spielberg from? Intermediate Answer: The United States. Follow up: Who is the director of Casino Royale? Intermediate
53
is the director of Casino Royale? Intermediate Answer: The director of Casino Royale is Martin Campbell. Follow up: Where is Martin Campbell from? Intermediate Answer: New Zealand. So the final answer is: No Question: Who was the father of Mary Ball Washington?Using an example selector‚ÄãFeed examples into ExampleSelector‚ÄãWe will reuse the example set and the formatter from the previous section. However, instead of feeding the examples directly into the FewShotPromptTemplate object, we will feed them into an ExampleSelector object.In this tutorial, we will use the SemanticSimilarityExampleSelector class. This class selects few-shot examples based on their similarity to the input. It uses an embedding model to compute the similarity between the input and the few-shot examples, as well as a vector store to perform the nearest neighbor search.from langchain.prompts.example_selector import SemanticSimilarityExampleSelectorfrom langchain.vectorstores import Chromafrom langchain.embeddings import OpenAIEmbeddingsexample_selector = SemanticSimilarityExampleSelector.from_examples( # This is the list of examples available to select from. examples, # This is the embedding class used to produce embeddings which are used to measure semantic similarity. OpenAIEmbeddings(), # This is the VectorStore class that is used to store the embeddings and do a similarity search over. Chroma, # This is the number of examples to produce. k=1)# Select the most similar example to the input.question = "Who was the father of Mary Ball Washington?"selected_examples = example_selector.select_examples({"question": question})print(f"Examples most similar to the input: {question}")for example in selected_examples: print("\n") for k, v in example.items(): print(f"{k}: {v}") Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient. Examples most similar to the input: Who was the father of Mary Ball
In this tutorial, we'll learn how to create a prompt template that uses few-shot examples. A few-shot prompt template can be constructed from either a set of examples, or from an Example Selector object.
In this tutorial, we'll learn how to create a prompt template that uses few-shot examples. A few-shot prompt template can be constructed from either a set of examples, or from an Example Selector object. ->: is the director of Casino Royale? Intermediate Answer: The director of Casino Royale is Martin Campbell. Follow up: Where is Martin Campbell from? Intermediate Answer: New Zealand. So the final answer is: No Question: Who was the father of Mary Ball Washington?Using an example selector‚ÄãFeed examples into ExampleSelector‚ÄãWe will reuse the example set and the formatter from the previous section. However, instead of feeding the examples directly into the FewShotPromptTemplate object, we will feed them into an ExampleSelector object.In this tutorial, we will use the SemanticSimilarityExampleSelector class. This class selects few-shot examples based on their similarity to the input. It uses an embedding model to compute the similarity between the input and the few-shot examples, as well as a vector store to perform the nearest neighbor search.from langchain.prompts.example_selector import SemanticSimilarityExampleSelectorfrom langchain.vectorstores import Chromafrom langchain.embeddings import OpenAIEmbeddingsexample_selector = SemanticSimilarityExampleSelector.from_examples( # This is the list of examples available to select from. examples, # This is the embedding class used to produce embeddings which are used to measure semantic similarity. OpenAIEmbeddings(), # This is the VectorStore class that is used to store the embeddings and do a similarity search over. Chroma, # This is the number of examples to produce. k=1)# Select the most similar example to the input.question = "Who was the father of Mary Ball Washington?"selected_examples = example_selector.select_examples({"question": question})print(f"Examples most similar to the input: {question}")for example in selected_examples: print("\n") for k, v in example.items(): print(f"{k}: {v}") Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient. Examples most similar to the input: Who was the father of Mary Ball
54
to the input: Who was the father of Mary Ball Washington? question: Who was the maternal grandfather of George Washington? answer: Are follow up questions needed here: Yes. Follow up: Who was the mother of George Washington? Intermediate answer: The mother of George Washington was Mary Ball Washington. Follow up: Who was the father of Mary Ball Washington? Intermediate answer: The father of Mary Ball Washington was Joseph Ball. So the final answer is: Joseph BallFeed example selector into FewShotPromptTemplate​Finally, create a FewShotPromptTemplate object. This object takes in the example selector and the formatter for the few-shot examples.prompt = FewShotPromptTemplate( example_selector=example_selector, example_prompt=example_prompt, suffix="Question: {input}", input_variables=["input"])print(prompt.format(input="Who was the father of Mary Ball Washington?")) Question: Who was the maternal grandfather of George Washington? Are follow up questions needed here: Yes. Follow up: Who was the mother of George Washington? Intermediate answer: The mother of George Washington was Mary Ball Washington. Follow up: Who was the father of Mary Ball Washington? Intermediate answer: The father of Mary Ball Washington was Joseph Ball. So the final answer is: Joseph Ball Question: Who was the father of Mary Ball Washington?PreviousCustom prompt templateNextFew-shot examples for chat modelsUse CaseUsing an example setCreate the example setCreate a formatter for the few-shot examplesFeed examples and formatter to FewShotPromptTemplateUsing an example selectorFeed examples into ExampleSelectorFeed example selector into FewShotPromptTemplateCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
In this tutorial, we'll learn how to create a prompt template that uses few-shot examples. A few-shot prompt template can be constructed from either a set of examples, or from an Example Selector object.
In this tutorial, we'll learn how to create a prompt template that uses few-shot examples. A few-shot prompt template can be constructed from either a set of examples, or from an Example Selector object. ->: to the input: Who was the father of Mary Ball Washington? question: Who was the maternal grandfather of George Washington? answer: Are follow up questions needed here: Yes. Follow up: Who was the mother of George Washington? Intermediate answer: The mother of George Washington was Mary Ball Washington. Follow up: Who was the father of Mary Ball Washington? Intermediate answer: The father of Mary Ball Washington was Joseph Ball. So the final answer is: Joseph BallFeed example selector into FewShotPromptTemplate​Finally, create a FewShotPromptTemplate object. This object takes in the example selector and the formatter for the few-shot examples.prompt = FewShotPromptTemplate( example_selector=example_selector, example_prompt=example_prompt, suffix="Question: {input}", input_variables=["input"])print(prompt.format(input="Who was the father of Mary Ball Washington?")) Question: Who was the maternal grandfather of George Washington? Are follow up questions needed here: Yes. Follow up: Who was the mother of George Washington? Intermediate answer: The mother of George Washington was Mary Ball Washington. Follow up: Who was the father of Mary Ball Washington? Intermediate answer: The father of Mary Ball Washington was Joseph Ball. So the final answer is: Joseph Ball Question: Who was the father of Mary Ball Washington?PreviousCustom prompt templateNextFew-shot examples for chat modelsUse CaseUsing an example setCreate the example setCreate a formatter for the few-shot examplesFeed examples and formatter to FewShotPromptTemplateUsing an example selectorFeed examples into ExampleSelectorFeed example selector into FewShotPromptTemplateCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
55
Template formats | 🦜️🔗 Langchain Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesConnecting to a Feature StoreCustom prompt templateFew-shot prompt templatesFew-shot examples for chat modelsFormat template outputTemplate formatsTypes of MessagePromptTemplatePartial prompt templatesCompositionSerializationPrompt pipeliningValidate templateExample selectorsLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsPrompt templatesTemplate formatsTemplate formatsPromptTemplate by default uses Python f-string as its template format. However, it can also use other formats like jinja2, specified through the template_format argument.To use the jinja2 template:from langchain.prompts import PromptTemplatejinja2_template = "Tell me a {{ adjective }} joke about {{ content }}"prompt = PromptTemplate.from_template(jinja2_template, template_format="jinja2")prompt.format(adjective="funny", content="chickens")# Output: Tell me a funny joke about chickens.To use the Python f-string template:from langchain.prompts import PromptTemplatefstring_template = """Tell me a {adjective} joke about {content}"""prompt = PromptTemplate.from_template(fstring_template)prompt.format(adjective="funny", content="chickens")# Output: Tell me a funny joke about chickens.Currently, only jinja2 and f-string are supported. For other formats, kindly raise an issue on the Github page.PreviousFormat template outputNextTypes of MessagePromptTemplateCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
PromptTemplate by default uses Python f-string as its template format. However, it can also use other formats like jinja2, specified through the template_format argument.
PromptTemplate by default uses Python f-string as its template format. However, it can also use other formats like jinja2, specified through the template_format argument. ->: Template formats | 🦜️🔗 Langchain Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesConnecting to a Feature StoreCustom prompt templateFew-shot prompt templatesFew-shot examples for chat modelsFormat template outputTemplate formatsTypes of MessagePromptTemplatePartial prompt templatesCompositionSerializationPrompt pipeliningValidate templateExample selectorsLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsPrompt templatesTemplate formatsTemplate formatsPromptTemplate by default uses Python f-string as its template format. However, it can also use other formats like jinja2, specified through the template_format argument.To use the jinja2 template:from langchain.prompts import PromptTemplatejinja2_template = "Tell me a {{ adjective }} joke about {{ content }}"prompt = PromptTemplate.from_template(jinja2_template, template_format="jinja2")prompt.format(adjective="funny", content="chickens")# Output: Tell me a funny joke about chickens.To use the Python f-string template:from langchain.prompts import PromptTemplatefstring_template = """Tell me a {adjective} joke about {content}"""prompt = PromptTemplate.from_template(fstring_template)prompt.format(adjective="funny", content="chickens")# Output: Tell me a funny joke about chickens.Currently, only jinja2 and f-string are supported. For other formats, kindly raise an issue on the Github page.PreviousFormat template outputNextTypes of MessagePromptTemplateCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
56
Connecting to a Feature Store | 🦜️🔗 Langchain
Feature stores are a concept from traditional machine learning that make sure data fed into models is up-to-date and relevant. For more on this, see here.
Feature stores are a concept from traditional machine learning that make sure data fed into models is up-to-date and relevant. For more on this, see here. ->: Connecting to a Feature Store | 🦜️🔗 Langchain
57
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesConnecting to a Feature StoreCustom prompt templateFew-shot prompt templatesFew-shot examples for chat modelsFormat template outputTemplate formatsTypes of MessagePromptTemplatePartial prompt templatesCompositionSerializationPrompt pipeliningValidate templateExample selectorsLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsPrompt templatesConnecting to a Feature StoreOn this pageConnecting to a Feature StoreFeature stores are a concept from traditional machine learning that make sure data fed into models is up-to-date and relevant. For more on this, see here.This concept is extremely relevant when considering putting LLM applications in production. In order to personalize LLM applications, you may want to combine LLMs with up-to-date information about particular users. Feature stores can be a great way to keep that data fresh, and LangChain provides an easy way to combine that data with LLMs.In this notebook we will show how to connect prompt templates to feature stores. The basic idea is to call a feature store from inside a prompt template to retrieve values that are then formatted into the prompt.Feast​To start, we will use the popular open-source feature store framework Feast.This assumes you have already run the steps in the README around getting started. We will build off of that example in getting started, and create and LLMChain to write a note to a specific driver regarding their up-to-date statistics.Load Feast Store​Again, this should be set up according to the instructions in the Feast README.from feast import FeatureStore# You may need to update the path depending on where you
Feature stores are a concept from traditional machine learning that make sure data fed into models is up-to-date and relevant. For more on this, see here.
Feature stores are a concept from traditional machine learning that make sure data fed into models is up-to-date and relevant. For more on this, see here. ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKGet startedIntroductionInstallationQuickstartLangChain Expression LanguageInterfaceHow toCookbookLangChain Expression Language (LCEL)Why use LCEL?ModulesModel I/​OPromptsPrompt templatesConnecting to a Feature StoreCustom prompt templateFew-shot prompt templatesFew-shot examples for chat modelsFormat template outputTemplate formatsTypes of MessagePromptTemplatePartial prompt templatesCompositionSerializationPrompt pipeliningValidate templateExample selectorsLanguage modelsOutput parsersRetrievalChainsMemoryAgentsCallbacksModulesSecurityGuidesMoreModulesModel I/​OPromptsPrompt templatesConnecting to a Feature StoreOn this pageConnecting to a Feature StoreFeature stores are a concept from traditional machine learning that make sure data fed into models is up-to-date and relevant. For more on this, see here.This concept is extremely relevant when considering putting LLM applications in production. In order to personalize LLM applications, you may want to combine LLMs with up-to-date information about particular users. Feature stores can be a great way to keep that data fresh, and LangChain provides an easy way to combine that data with LLMs.In this notebook we will show how to connect prompt templates to feature stores. The basic idea is to call a feature store from inside a prompt template to retrieve values that are then formatted into the prompt.Feast​To start, we will use the popular open-source feature store framework Feast.This assumes you have already run the steps in the README around getting started. We will build off of that example in getting started, and create and LLMChain to write a note to a specific driver regarding their up-to-date statistics.Load Feast Store​Again, this should be set up according to the instructions in the Feast README.from feast import FeatureStore# You may need to update the path depending on where you
58
need to update the path depending on where you stored itfeast_repo_path = "../../../../../my_feature_repo/feature_repo/"store = FeatureStore(repo_path=feast_repo_path)Prompts‚ÄãHere we will set up a custom FeastPromptTemplate. This prompt template will take in a driver id, look up their stats, and format those stats into a prompt.Note that the input to this prompt template is just driver_id, since that is the only user defined piece (all other variables are looked up inside the prompt template).from langchain.prompts import PromptTemplate, StringPromptTemplatetemplate = """Given the driver's up to date stats, write them note relaying those stats to them.If they have a conversation rate above .5, give them a compliment. Otherwise, make a silly joke about chickens at the end to make them feel betterHere are the drivers stats:Conversation rate: {conv_rate}Acceptance rate: {acc_rate}Average Daily Trips: {avg_daily_trips}Your response:"""prompt = PromptTemplate.from_template(template)class FeastPromptTemplate(StringPromptTemplate): def format(self, **kwargs) -> str: driver_id = kwargs.pop("driver_id") feature_vector = store.get_online_features( features=[ "driver_hourly_stats:conv_rate", "driver_hourly_stats:acc_rate", "driver_hourly_stats:avg_daily_trips", ], entity_rows=[{"driver_id": driver_id}], ).to_dict() kwargs["conv_rate"] = feature_vector["conv_rate"][0] kwargs["acc_rate"] = feature_vector["acc_rate"][0] kwargs["avg_daily_trips"] = feature_vector["avg_daily_trips"][0] return prompt.format(**kwargs)prompt_template = FeastPromptTemplate(input_variables=["driver_id"])print(prompt_template.format(driver_id=1001)) Given the driver's up to date stats, write them note relaying those stats to them. If they have a conversation rate above .5, give them a compliment. Otherwise, make a silly joke about chickens at the end to make them feel
Feature stores are a concept from traditional machine learning that make sure data fed into models is up-to-date and relevant. For more on this, see here.
Feature stores are a concept from traditional machine learning that make sure data fed into models is up-to-date and relevant. For more on this, see here. ->: need to update the path depending on where you stored itfeast_repo_path = "../../../../../my_feature_repo/feature_repo/"store = FeatureStore(repo_path=feast_repo_path)Prompts‚ÄãHere we will set up a custom FeastPromptTemplate. This prompt template will take in a driver id, look up their stats, and format those stats into a prompt.Note that the input to this prompt template is just driver_id, since that is the only user defined piece (all other variables are looked up inside the prompt template).from langchain.prompts import PromptTemplate, StringPromptTemplatetemplate = """Given the driver's up to date stats, write them note relaying those stats to them.If they have a conversation rate above .5, give them a compliment. Otherwise, make a silly joke about chickens at the end to make them feel betterHere are the drivers stats:Conversation rate: {conv_rate}Acceptance rate: {acc_rate}Average Daily Trips: {avg_daily_trips}Your response:"""prompt = PromptTemplate.from_template(template)class FeastPromptTemplate(StringPromptTemplate): def format(self, **kwargs) -> str: driver_id = kwargs.pop("driver_id") feature_vector = store.get_online_features( features=[ "driver_hourly_stats:conv_rate", "driver_hourly_stats:acc_rate", "driver_hourly_stats:avg_daily_trips", ], entity_rows=[{"driver_id": driver_id}], ).to_dict() kwargs["conv_rate"] = feature_vector["conv_rate"][0] kwargs["acc_rate"] = feature_vector["acc_rate"][0] kwargs["avg_daily_trips"] = feature_vector["avg_daily_trips"][0] return prompt.format(**kwargs)prompt_template = FeastPromptTemplate(input_variables=["driver_id"])print(prompt_template.format(driver_id=1001)) Given the driver's up to date stats, write them note relaying those stats to them. If they have a conversation rate above .5, give them a compliment. Otherwise, make a silly joke about chickens at the end to make them feel
59
joke about chickens at the end to make them feel better Here are the drivers stats: Conversation rate: 0.4745151400566101 Acceptance rate: 0.055561766028404236 Average Daily Trips: 936 Your response:Use in a chain‚ÄãWe can now use this in a chain, successfully creating a chain that achieves personalization backed by a feature store.from langchain.chat_models import ChatOpenAIfrom langchain.chains import LLMChainchain = LLMChain(llm=ChatOpenAI(), prompt=prompt_template)chain.run(1001) "Hi there! I wanted to update you on your current stats. Your acceptance rate is 0.055561766028404236 and your average daily trips are 936. While your conversation rate is currently 0.4745151400566101, I have no doubt that with a little extra effort, you'll be able to exceed that .5 mark! Keep up the great work! And remember, even chickens can't always cross the road, but they still give it their best shot."Tecton‚ÄãAbove, we showed how you could use Feast, a popular open-source and self-managed feature store, with LangChain. Our examples below will show a similar integration using Tecton. Tecton is a fully managed feature platform built to orchestrate the complete ML feature lifecycle, from transformation to online serving, with enterprise-grade SLAs.Prerequisites‚ÄãTecton Deployment (sign up at https://tecton.ai)TECTON_API_KEY environment variable set to a valid Service Account keyDefine and load features‚ÄãWe will use the user_transaction_counts Feature View from the Tecton tutorial as part of a Feature Service. For simplicity, we are only using a single Feature View; however, more sophisticated applications may require more feature views to retrieve the features needed for its prompt.user_transaction_metrics = FeatureService( name = "user_transaction_metrics", features = [user_transaction_counts])The above Feature Service is expected to be applied to a live workspace. For this example, we will be using the "prod" workspace.import tectonworkspace =
Feature stores are a concept from traditional machine learning that make sure data fed into models is up-to-date and relevant. For more on this, see here.
Feature stores are a concept from traditional machine learning that make sure data fed into models is up-to-date and relevant. For more on this, see here. ->: joke about chickens at the end to make them feel better Here are the drivers stats: Conversation rate: 0.4745151400566101 Acceptance rate: 0.055561766028404236 Average Daily Trips: 936 Your response:Use in a chain‚ÄãWe can now use this in a chain, successfully creating a chain that achieves personalization backed by a feature store.from langchain.chat_models import ChatOpenAIfrom langchain.chains import LLMChainchain = LLMChain(llm=ChatOpenAI(), prompt=prompt_template)chain.run(1001) "Hi there! I wanted to update you on your current stats. Your acceptance rate is 0.055561766028404236 and your average daily trips are 936. While your conversation rate is currently 0.4745151400566101, I have no doubt that with a little extra effort, you'll be able to exceed that .5 mark! Keep up the great work! And remember, even chickens can't always cross the road, but they still give it their best shot."Tecton‚ÄãAbove, we showed how you could use Feast, a popular open-source and self-managed feature store, with LangChain. Our examples below will show a similar integration using Tecton. Tecton is a fully managed feature platform built to orchestrate the complete ML feature lifecycle, from transformation to online serving, with enterprise-grade SLAs.Prerequisites‚ÄãTecton Deployment (sign up at https://tecton.ai)TECTON_API_KEY environment variable set to a valid Service Account keyDefine and load features‚ÄãWe will use the user_transaction_counts Feature View from the Tecton tutorial as part of a Feature Service. For simplicity, we are only using a single Feature View; however, more sophisticated applications may require more feature views to retrieve the features needed for its prompt.user_transaction_metrics = FeatureService( name = "user_transaction_metrics", features = [user_transaction_counts])The above Feature Service is expected to be applied to a live workspace. For this example, we will be using the "prod" workspace.import tectonworkspace =
60
the "prod" workspace.import tectonworkspace = tecton.get_workspace("prod")feature_service = workspace.get_feature_service("user_transaction_metrics")Prompts‚ÄãHere we will set up a custom TectonPromptTemplate. This prompt template will take in a user_id , look up their stats, and format those stats into a prompt.Note that the input to this prompt template is just user_id, since that is the only user defined piece (all other variables are looked up inside the prompt template).from langchain.prompts import PromptTemplate, StringPromptTemplatetemplate = """Given the vendor's up to date transaction stats, write them a note based on the following rules:1. If they had a transaction in the last day, write a short congratulations message on their recent sales2. If no transaction in the last day, but they had a transaction in the last 30 days, playfully encourage them to sell more.3. Always add a silly joke about chickens at the endHere are the vendor's stats:Number of Transactions Last Day: {transaction_count_1d}Number of Transactions Last 30 Days: {transaction_count_30d}Your response:"""prompt = PromptTemplate.from_template(template)class TectonPromptTemplate(StringPromptTemplate): def format(self, **kwargs) -> str: user_id = kwargs.pop("user_id") feature_vector = feature_service.get_online_features( join_keys={"user_id": user_id} ).to_dict() kwargs["transaction_count_1d"] = feature_vector[ "user_transaction_counts.transaction_count_1d_1d" ] kwargs["transaction_count_30d"] = feature_vector[ "user_transaction_counts.transaction_count_30d_1d" ] return prompt.format(**kwargs)prompt_template = TectonPromptTemplate(input_variables=["user_id"])print(prompt_template.format(user_id="user_469998441571")) Given the vendor's up to date transaction stats, write them a note based on the following rules: 1. If they had a transaction in the last day, write a short congratulations
Feature stores are a concept from traditional machine learning that make sure data fed into models is up-to-date and relevant. For more on this, see here.
Feature stores are a concept from traditional machine learning that make sure data fed into models is up-to-date and relevant. For more on this, see here. ->: the "prod" workspace.import tectonworkspace = tecton.get_workspace("prod")feature_service = workspace.get_feature_service("user_transaction_metrics")Prompts‚ÄãHere we will set up a custom TectonPromptTemplate. This prompt template will take in a user_id , look up their stats, and format those stats into a prompt.Note that the input to this prompt template is just user_id, since that is the only user defined piece (all other variables are looked up inside the prompt template).from langchain.prompts import PromptTemplate, StringPromptTemplatetemplate = """Given the vendor's up to date transaction stats, write them a note based on the following rules:1. If they had a transaction in the last day, write a short congratulations message on their recent sales2. If no transaction in the last day, but they had a transaction in the last 30 days, playfully encourage them to sell more.3. Always add a silly joke about chickens at the endHere are the vendor's stats:Number of Transactions Last Day: {transaction_count_1d}Number of Transactions Last 30 Days: {transaction_count_30d}Your response:"""prompt = PromptTemplate.from_template(template)class TectonPromptTemplate(StringPromptTemplate): def format(self, **kwargs) -> str: user_id = kwargs.pop("user_id") feature_vector = feature_service.get_online_features( join_keys={"user_id": user_id} ).to_dict() kwargs["transaction_count_1d"] = feature_vector[ "user_transaction_counts.transaction_count_1d_1d" ] kwargs["transaction_count_30d"] = feature_vector[ "user_transaction_counts.transaction_count_30d_1d" ] return prompt.format(**kwargs)prompt_template = TectonPromptTemplate(input_variables=["user_id"])print(prompt_template.format(user_id="user_469998441571")) Given the vendor's up to date transaction stats, write them a note based on the following rules: 1. If they had a transaction in the last day, write a short congratulations
61
in the last day, write a short congratulations message on their recent sales 2. If no transaction in the last day, but they had a transaction in the last 30 days, playfully encourage them to sell more. 3. Always add a silly joke about chickens at the end Here are the vendor's stats: Number of Transactions Last Day: 657 Number of Transactions Last 30 Days: 20326 Your response:Use in a chain‚ÄãWe can now use this in a chain, successfully creating a chain that achieves personalization backed by the Tecton Feature Platform.from langchain.chat_models import ChatOpenAIfrom langchain.chains import LLMChainchain = LLMChain(llm=ChatOpenAI(), prompt=prompt_template)chain.run("user_469998441571") 'Wow, congratulations on your recent sales! Your business is really soaring like a chicken on a hot air balloon! Keep up the great work!'Featureform‚ÄãFinally, we will use Featureform, an open-source and enterprise-grade feature store, to run the same example. Featureform allows you to work with your infrastructure like Spark or locally to define your feature transformations.Initialize Featureform‚ÄãYou can follow in the instructions in the README to initialize your transformations and features in Featureform.import featureform as ffclient = ff.Client(host="demo.featureform.com")Prompts‚ÄãHere we will set up a custom FeatureformPromptTemplate. This prompt template will take in the average amount a user pays per transactions.Note that the input to this prompt template is just avg_transaction, since that is the only user defined piece (all other variables are looked up inside the prompt template).from langchain.prompts import PromptTemplate, StringPromptTemplatetemplate = """Given the amount a user spends on average per transaction, let them know if they are a high roller. Otherwise, make a silly joke about chickens at the end to make them feel betterHere are the user's stats:Average Amount per Transaction: ${avg_transcation}Your response:"""prompt =
Feature stores are a concept from traditional machine learning that make sure data fed into models is up-to-date and relevant. For more on this, see here.
Feature stores are a concept from traditional machine learning that make sure data fed into models is up-to-date and relevant. For more on this, see here. ->: in the last day, write a short congratulations message on their recent sales 2. If no transaction in the last day, but they had a transaction in the last 30 days, playfully encourage them to sell more. 3. Always add a silly joke about chickens at the end Here are the vendor's stats: Number of Transactions Last Day: 657 Number of Transactions Last 30 Days: 20326 Your response:Use in a chain‚ÄãWe can now use this in a chain, successfully creating a chain that achieves personalization backed by the Tecton Feature Platform.from langchain.chat_models import ChatOpenAIfrom langchain.chains import LLMChainchain = LLMChain(llm=ChatOpenAI(), prompt=prompt_template)chain.run("user_469998441571") 'Wow, congratulations on your recent sales! Your business is really soaring like a chicken on a hot air balloon! Keep up the great work!'Featureform‚ÄãFinally, we will use Featureform, an open-source and enterprise-grade feature store, to run the same example. Featureform allows you to work with your infrastructure like Spark or locally to define your feature transformations.Initialize Featureform‚ÄãYou can follow in the instructions in the README to initialize your transformations and features in Featureform.import featureform as ffclient = ff.Client(host="demo.featureform.com")Prompts‚ÄãHere we will set up a custom FeatureformPromptTemplate. This prompt template will take in the average amount a user pays per transactions.Note that the input to this prompt template is just avg_transaction, since that is the only user defined piece (all other variables are looked up inside the prompt template).from langchain.prompts import PromptTemplate, StringPromptTemplatetemplate = """Given the amount a user spends on average per transaction, let them know if they are a high roller. Otherwise, make a silly joke about chickens at the end to make them feel betterHere are the user's stats:Average Amount per Transaction: ${avg_transcation}Your response:"""prompt =

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
0
Add dataset card