id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 59 127 |
|---|---|---|
b359e2c72fec-2 | chain({"input_documents": docs, "question": query}, return_only_outputs=True)
{'output_text': ' Il presidente ha detto che Justice Breyer ha dedicato la sua vita a servire questo paese e ha ricevuto una vasta gamma di supporto.'}
The map_reduce Chain#
This sections shows results of using the map_reduce Chain to do ques... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/question_answering.html |
b359e2c72fec-3 | ' None',
' None'],
'output_text': ' The president said that Justice Breyer is an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court, and thanked him for his service.'}
Custom Prompts
You can also use your own prompts with this chain. In this example, we will respond in Ital... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/question_answering.html |
b359e2c72fec-4 | chain({"input_documents": docs, "question": query}, return_only_outputs=True)
{'intermediate_steps': ["\nStasera vorrei onorare qualcuno che ha dedicato la sua vita a servire questo paese: il giustizia Stephen Breyer - un veterano dell'esercito, uno studioso costituzionale e un giustizia in uscita della Corte Suprema d... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/question_answering.html |
b359e2c72fec-5 | chain({"input_documents": docs, "question": query}, return_only_outputs=True)
{'output_text': '\n\nThe president said that he wanted to honor Justice Breyer for his dedication to serving the country, his legacy of excellence, and his commitment to advancing liberty and justice, as well as for his support of the Equalit... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/question_answering.html |
b359e2c72fec-6 | '\n\nThe president said that he wanted to honor Justice Breyer for his dedication to serving the country, his legacy of excellence, and his commitment to advancing liberty and justice, as well as for his support of the Equality Act and his commitment to protecting the rights of LGBTQ+ Americans. He also praised Justice... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/question_answering.html |
b359e2c72fec-7 | template=refine_prompt_template,
)
initial_qa_template = (
"Context information is below. \n"
"---------------------\n"
"{context_str}"
"\n---------------------\n"
"Given the context information and not prior knowledge, "
"answer the question: {question}\nYour answer should be in Italian.\n"
)
i... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/question_answering.html |
b359e2c72fec-8 | "\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha reso omaggio al suo servizio e ha sostenuto la nomina di una top litigatrice in pratica privata, un ex difensore pubblico federale e una famiglia di insegnanti e agenti di polizia delle scuole pubbliche. Ha anche sottol... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/question_answering.html |
b359e2c72fec-9 | 'output_text': "\n\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha reso omaggio al suo servizio e ha sostenuto la nomina di una top litigatrice in pratica privata, un ex difensore pubblico federale e una famiglia di insegnanti e agenti di polizia delle scuole pubbliche... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/question_answering.html |
b359e2c72fec-10 | {'answer': ' This document does not answer the question', 'score': '0'},
{'answer': ' This document does not answer the question', 'score': '0'},
{'answer': ' This document does not answer the question', 'score': '0'}]
Custom Prompts
You can also use your own prompts with this chain. In this example, we will respond ... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/question_answering.html |
b359e2c72fec-11 | 'score': '100'},
{'answer': ' Il presidente non ha detto nulla sulla Giustizia Breyer.',
'score': '100'},
{'answer': ' Non so.', 'score': '0'},
{'answer': ' Non so.', 'score': '0'}],
'output_text': ' Il presidente ha detto che Justice Breyer ha dedicato la sua vita a servire questo paese.'}
previous
Question ... | rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/index_examples/question_answering.html |
9d1fcdcffb6b-0 | .ipynb
.pdf
Chat Prompt Templates
Contents
Format output
Different types of MessagePromptTemplate
Chat Prompt Templates#
Chat Models take a list of chat messages as input - this list commonly referred to as a prompt.
These chat messages differ from raw string (which you would pass into a LLM model) in that every mess... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/chat_prompt_template.html |
9d1fcdcffb6b-1 | input_variables=["input_language", "output_language"],
)
system_message_prompt_2 = SystemMessagePromptTemplate(prompt=prompt)
assert system_message_prompt == system_message_prompt_2
After that, you can build a ChatPromptTemplate from one or more MessagePromptTemplates. You can use ChatPromptTemplate’s format_prompt – t... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/chat_prompt_template.html |
9d1fcdcffb6b-2 | [SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}),
HumanMessage(content='I love programming.', additional_kwargs={})]
Different types of MessagePromptTemplate#
LangChain provides different types of MessagePromptTemplate. The most commonly used are AIMessageP... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/chat_prompt_template.html |
9d1fcdcffb6b-3 | 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. Cho... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/chat_prompt_template.html |
4148f57ba8cf-0 | .rst
.pdf
Example Selectors
Example Selectors#
Note
Conceptual Guide
If you have a large number of examples, you may need to select which ones to include in the prompt. The ExampleSelector is the class responsible for doing so.
The base interface is defined as below:
class BaseExampleSelector(ABC):
"""Interface for... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/example_selectors.html |
67fab753cdd2-0 | .ipynb
.pdf
Getting Started
Contents
PromptTemplates
to_string
to_messages
Getting Started#
This section contains everything related to prompts. A prompt is the value passed into the Language Model. This value can either be a string (for LLMs) or a list of messages (for Chat Models).
The data types of these prompts a... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/getting_started.html |
67fab753cdd2-1 | string_prompt_value.to_string()
'tell me a joke about soccer'
chat_prompt_value.to_string()
'Human: tell me a joke about soccer'
to_messages#
This is what is called when passing to ChatModel (which expects a list of messages)
string_prompt_value.to_messages()
[HumanMessage(content='tell me a joke about soccer', additio... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/getting_started.html |
c4998fcb813a-0 | .rst
.pdf
Output Parsers
Output Parsers#
Note
Conceptual Guide
Language models output text. But many times you may want to get more structured information than just text back. This is where output parsers come in.
Output parsers are classes that help structure language model responses. There are two main methods an out... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/output_parsers.html |
a0e5ce0ab64d-0 | .rst
.pdf
Prompt Templates
Prompt Templates#
Note
Conceptual Guide
Language models take text as input - that text is commonly referred to as a prompt.
Typically this is not simply a hardcoded string but rather a combination of a template, some examples, and user input.
LangChain provides several classes and functions t... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates.html |
2753e712e867-0 | .ipynb
.pdf
Output Parsers
Output Parsers#
Language models output text. But many times you may want to get more structured information than just text back. This is where output parsers come in.
Output parsers are classes that help structure language model responses. There are two main methods an output parser must impl... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/output_parsers/getting_started.html |
2753e712e867-1 | punchline: str = Field(description="answer to resolve the joke")
# You can add custom validation logic easily with Pydantic.
@validator('setup')
def question_ends_with_question_mark(cls, field):
if field[-1] != '?':
raise ValueError("Badly formed question!")
return field
# S... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/output_parsers/getting_started.html |
45112d4acc6f-0 | .ipynb
.pdf
RetryOutputParser
RetryOutputParser#
While in some cases it is possible to fix any parsing mistakes by only looking at the output, in other cases it can’t. An example of this is when the output is not just in the incorrect format, but is partially complete. Consider the below example.
from langchain.prompts... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/output_parsers/examples/retry.html |
45112d4acc6f-1 | 23 json_object = json.loads(json_str)
---> 24 return self.pydantic_object.parse_obj(json_object)
26 except (json.JSONDecodeError, ValidationError) as e:
File ~/.pyenv/versions/3.9.1/envs/langchain/lib/python3.9/site-packages/pydantic/main.py:527, in pydantic.main.BaseModel.parse_obj()
File ~/.pyenv/version... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/output_parsers/examples/retry.html |
45112d4acc6f-2 | fix_parser.parse(bad_response)
Action(action='search', action_input='')
Instead, we can use the RetryOutputParser, which passes in the prompt (as well as the original output) to try again to get a better response.
from langchain.output_parsers import RetryWithErrorOutputParser
retry_parser = RetryWithErrorOutputParser.... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/output_parsers/examples/retry.html |
88566217f2af-0 | .ipynb
.pdf
CommaSeparatedListOutputParser
CommaSeparatedListOutputParser#
Here’s another parser strictly less powerful than Pydantic/JSON parsing.
from langchain.output_parsers import CommaSeparatedListOutputParser
from langchain.prompts import PromptTemplate, ChatPromptTemplate, HumanMessagePromptTemplate
from langch... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/output_parsers/examples/comma_separated.html |
e4490ea7f6d5-0 | .ipynb
.pdf
Datetime
Datetime#
This OutputParser shows out to parse LLM output into datetime format.
from langchain.prompts import PromptTemplate
from langchain.output_parsers import DatetimeOutputParser
from langchain.chains import LLMChain
from langchain.llms import OpenAI
output_parser = DatetimeOutputParser()
templ... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/output_parsers/examples/datetime.html |
844711a9d09a-0 | .ipynb
.pdf
OutputFixingParser
OutputFixingParser#
This output parser wraps another output parser and tries to fix any mistakes
The Pydantic guardrail simply tries to parse the LLM response. If it does not parse correctly, then it errors.
But we can do other things besides throw errors. Specifically, we can pass the mi... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/output_parsers/examples/output_fixing_parser.html |
844711a9d09a-1 | 24 return self.pydantic_object.parse_obj(json_object)
File ~/.pyenv/versions/3.9.1/lib/python3.9/json/__init__.py:346, in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
343 if (cls is None and object_hook is None and
344 parse_int is None and parse_float is N... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/output_parsers/examples/output_fixing_parser.html |
844711a9d09a-2 | Cell In[6], line 1
----> 1 parser.parse(misformatted)
File ~/workplace/langchain/langchain/output_parsers/pydantic.py:29, in PydanticOutputParser.parse(self, text)
27 name = self.pydantic_object.__name__
28 msg = f"Failed to parse {name} from completion {text}. Got: {e}"
---> 29 raise OutputParserException(ms... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/output_parsers/examples/output_fixing_parser.html |
67d1f8ed4789-0 | .ipynb
.pdf
Structured Output Parser
Structured Output Parser#
While the Pydantic/JSON parser is more powerful, we initially experimented data structures having text fields only.
from langchain.output_parsers import StructuredOutputParser, ResponseSchema
from langchain.prompts import PromptTemplate, ChatPromptTemplate,... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/output_parsers/examples/structured.html |
67d1f8ed4789-1 | prompt = ChatPromptTemplate(
messages=[
HumanMessagePromptTemplate.from_template("answer the users question as best as possible.\n{format_instructions}\n{question}")
],
input_variables=["question"],
partial_variables={"format_instructions": format_instructions}
)
_input = prompt.format_prompt(... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/output_parsers/examples/structured.html |
8bca02591ecb-0 | .ipynb
.pdf
Enum Output Parser
Enum Output Parser#
This notebook shows how to use an Enum output parser
from langchain.output_parsers.enum import EnumOutputParser
from enum import Enum
class Colors(Enum):
RED = "red"
GREEN = "green"
BLUE = "blue"
parser = EnumOutputParser(enum=Colors)
parser.parse("red")
<C... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/output_parsers/examples/enum.html |
8bca02591ecb-1 | During handling of the above exception, another exception occurred:
OutputParserException Traceback (most recent call last)
Cell In[8], line 2
1 # And raises errors when appropriate
----> 2 parser.parse("yellow")
File ~/workplace/langchain/langchain/output_parsers/enum.py:27, in EnumOutputPars... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/output_parsers/examples/enum.html |
9b53a0bf2b34-0 | .ipynb
.pdf
PydanticOutputParser
PydanticOutputParser#
This output parser allows users to specify an arbitrary JSON schema and query LLMs for JSON outputs that conform to that schema.
Keep in mind that large language models are leaky abstractions! You’ll have to use an LLM with sufficient capacity to generate well-form... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/output_parsers/examples/pydantic.html |
9b53a0bf2b34-1 | prompt = PromptTemplate(
template="Answer the user query.\n{format_instructions}\n{query}\n",
input_variables=["query"],
partial_variables={"format_instructions": parser.get_format_instructions()}
)
_input = prompt.format_prompt(query=joke_query)
output = model(_input.to_string())
parser.parse(output)
Joke(... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/output_parsers/examples/pydantic.html |
ee1b36860bc4-0 | .rst
.pdf
How-To Guides
How-To Guides#
If you’re new to the library, you may want to start with the Quickstart.
The user guide here shows more advanced workflows and how to use the library in different ways.
Connecting to a Feature Store
How to create a custom prompt template
How to create a prompt template that uses f... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/how_to_guides.html |
19dc0c1c79d1-0 | .md
.pdf
Getting Started
Contents
What is a prompt template?
Create a prompt template
Template formats
Validate template
Serialize prompt template
Pass few shot examples to a prompt template
Select examples for a prompt template
Getting Started#
In this tutorial, we will learn about:
what a prompt template is, and wh... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/getting_started.html |
19dc0c1c79d1-1 | no_input_prompt.format()
# -> "Tell me a joke."
# An example prompt with one input variable
one_input_prompt = PromptTemplate(input_variables=["adjective"], template="Tell me a {adjective} joke.")
one_input_prompt.format(adjective="funny")
# -> "Tell me a funny joke."
# An example prompt with multiple input variables
m... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/getting_started.html |
19dc0c1c79d1-2 | # -> Tell me a funny joke about chickens.
Currently, PromptTemplate only supports jinja2 and f-string templating format. If there is any other templating format that you would like to use, feel free to open an issue in the Github page.
Validate template#
By default, PromptTemplate will validate the template string by c... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/getting_started.html |
19dc0c1c79d1-3 | To generate a prompt with few shot examples, you can use the FewShotPromptTemplate. This class takes in a PromptTemplate and a list of few shot examples. It then formats the prompt template with the few shot examples.
In this example, we’ll create a prompt to generate word antonyms.
from langchain import PromptTemplate... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/getting_started.html |
19dc0c1c79d1-4 | input_variables=["input"],
# The example_separator is the string we will use to join the prefix, examples, and suffix together with.
example_separator="\n",
)
# We can now generate a prompt using the `format` method.
print(few_shot_prompt.format(input="big"))
# -> Give the antonym of every input
# ->
# -> Word... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/getting_started.html |
19dc0c1c79d1-5 | {"word": "windy", "antonym": "calm"},
]
# We'll use the `LengthBasedExampleSelector` to select the examples.
example_selector = LengthBasedExampleSelector(
# These are the examples is has available to choose from.
examples=examples,
# This is the PromptTemplate being used to format the examples.
exampl... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/getting_started.html |
19dc0c1c79d1-6 | # -> Antonym: lethargic
# ->
# -> Word: sunny
# -> Antonym: gloomy
# ->
# -> Word: windy
# -> Antonym: calm
# ->
# -> Word: big
# -> Antonym:
In contrast, if we provide a very long input, the LengthBasedExampleSelector will select fewer examples to include in the prompt.
long_string = "big and huge and massive and larg... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/getting_started.html |
91d9a3f20808-0 | .ipynb
.pdf
How to serialize prompts
Contents
PromptTemplate
Loading from YAML
Loading from JSON
Loading Template from a File
FewShotPromptTemplate
Examples
Loading from YAML
Loading from JSON
Examples in the Config
Example Prompt from a File
PromptTempalte with OutputParser
How to serialize prompts#
It is often pref... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/prompt_serialization.html |
91d9a3f20808-1 | prompt = load_prompt("simple_prompt.yaml")
print(prompt.format(adjective="funny", content="chickens"))
Tell me a funny joke about chickens.
Loading from JSON#
This shows an example of loading a PromptTemplate from JSON.
!cat simple_prompt.json
{
"_type": "prompt",
"input_variables": ["adjective", "content"],
... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/prompt_serialization.html |
91d9a3f20808-2 | output: sad
- input: tall
output: short
Loading from YAML#
This shows an example of loading a few shot example from YAML.
!cat few_shot_prompt.yaml
_type: few_shot
input_variables:
["adjective"]
prefix:
Write antonyms for the following words.
example_prompt:
_type: prompt
input_variables:
["i... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/prompt_serialization.html |
91d9a3f20808-3 | !cat few_shot_prompt.json
{
"_type": "few_shot",
"input_variables": ["adjective"],
"prefix": "Write antonyms for the following words.",
"example_prompt": {
"_type": "prompt",
"input_variables": ["input", "output"],
"template": "Input: {input}\nOutput: {output}"
},
"exampl... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/prompt_serialization.html |
91d9a3f20808-4 | Output: short
Input: funny
Output:
Example Prompt from a File#
This shows an example of loading the PromptTemplate that is used to format the examples from a separate file. Note that the key changes from example_prompt to example_prompt_path.
!cat example_prompt.json
{
"_type": "prompt",
"input_variables": ["in... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/prompt_serialization.html |
91d9a3f20808-5 | "_type": "regex_parser"
},
"partial_variables": {},
"template": "Given the following question and student answer, provide a correct answer and score the student answer.\nQuestion: {question}\nStudent Answer: {student_answer}\nCorrect Answer:",
"template_format": "f-string",
"validate_template": true... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/prompt_serialization.html |
e3ffa686cc8c-0 | .ipynb
.pdf
How to create a prompt template that uses few shot examples
Contents
Use Case
Using an example set
Create the example set
Create a formatter for the few shot examples
Feed examples and formatter to FewShotPromptTemplate
Using an example selector
Feed examples into ExampleSelector
Feed example selector int... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/few_shot_examples.html |
e3ffa686cc8c-1 | "answer":
"""
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
"""
},
... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/few_shot_examples.html |
e3ffa686cc8c-2 | 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 ... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/few_shot_examples.html |
e3ffa686cc8c-3 | 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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/few_shot_examples.html |
e3ffa686cc8c-4 | # 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,... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/few_shot_examples.html |
e3ffa686cc8c-5 | 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 m... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/few_shot_examples.html |
14dcfae0b64e-0 | .ipynb
.pdf
How to create a custom prompt template
Contents
Why are custom prompt templates needed?
Creating a Custom Prompt Template
Use the custom prompt template
How to create a custom prompt template#
Let’s suppose we want the LLM to generate English language explanations of a function given its name. To achieve ... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/custom_prompt_template.html |
14dcfae0b64e-1 | def 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 String... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/custom_prompt_template.html |
14dcfae0b64e-2 | 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 fu... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/custom_prompt_template.html |
db98dc3b3451-0 | .ipynb
.pdf
Prompt Composition
Prompt Composition#
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:
final_prompt: This is the final prompt that is returned
pi... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/prompt_composition.html |
db98dc3b3451-1 | ))
You are impersonating Elon Musk.
Here's an example of an interaction:
Q: What's your favorite car?
A: Telsa
Now, do this for real!
Q: What's your favorite social media site?
A:
previous
How to work with partial Prompt Templates
next
How to serialize prompts
By Harrison Chase
© Copyright 2023, Harrison Ch... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/prompt_composition.html |
1fb7a24379e5-0 | .ipynb
.pdf
How to work with partial Prompt Templates
Contents
Partial With Strings
Partial With Functions
How to work with partial Prompt Templates#
A prompt template is a class with a .format method which takes in a key-value map and returns a string (a prompt) to pass to the language model. Like other methods, it ... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/partial.html |
1fb7a24379e5-1 | print(prompt.format(bar="baz"))
foobaz
Partial 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 ha... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/partial.html |
1fb7a24379e5-2 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/partial.html |
86c589e53fb6-0 | .ipynb
.pdf
Connecting to a Feature Store
Contents
Feast
Load Feast Store
Prompts
Use in a chain
Tecton
Prerequisites
Define and Load Features
Prompts
Use in a chain
Featureform
Initialize Featureform
Prompts
Use in a chain
Connecting to a Feature Store#
Feature stores are a concept from traditional machine learning ... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html |
86c589e53fb6-1 | 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, StringPromptTemplate
template = """Given the driver's up to date stats, write them note relaying those st... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html |
86c589e53fb6-2 | 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 ChatOpen... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html |
86c589e53fb6-3 | 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 tecton
workspace = tecton.get_workspace("prod")
feature_se... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html |
86c589e53fb6-4 | 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, writ... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html |
86c589e53fb6-5 | client = 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 va... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html |
86c589e53fb6-6 | Define and Load Features
Prompts
Use in a chain
Featureform
Initialize Featureform
Prompts
Use in a chain
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html |
f96b53ecdd66-0 | .ipynb
.pdf
Maximal Marginal Relevance ExampleSelector
Maximal Marginal Relevance ExampleSelector#
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 embeddin... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/example_selectors/examples/mmr.html |
f96b53ecdd66-1 | # This is 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... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/example_selectors/examples/mmr.html |
f96b53ecdd66-2 | Give the antonym of every input
Input: happy
Output: sad
Input: sunny
Output: gloomy
Input: worried
Output:
previous
LengthBased ExampleSelector
next
NGram Overlap ExampleSelector
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/example_selectors/examples/mmr.html |
08d490b53d1a-0 | .ipynb
.pdf
NGram Overlap ExampleSelector
NGram Overlap ExampleSelector#
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 selector allows for a th... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/example_selectors/examples/ngram_overlap.html |
08d490b53d1a-1 | {"input": "Spot can run.", "output": "Spot puede correr."},
]
example_prompt = PromptTemplate(
input_variables=["input", "output"],
template="Input: {input}\nOutput: {output}",
)
example_selector = NGramOverlapExampleSelector(
# These are the examples it has available to choose from.
examples=examples, ... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/example_selectors/examples/ngram_overlap.html |
08d490b53d1a-2 | 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(se... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/example_selectors/examples/ngram_overlap.html |
08d490b53d1a-3 | Input: Spot plays fetch.
Output: Spot juega a buscar.
Input: Spot can play fetch.
Output:
# Setting threshold greater than 1.0
example_selector.threshold=1.0+1e-9
print(dynamic_prompt.format(sentence="Spot can play fetch."))
Give the Spanish translation of every input
Input: Spot can play fetch.
Output:
previous
Maxima... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/example_selectors/examples/ngram_overlap.html |
0dbe03127cbc-0 | .md
.pdf
How to create a custom example selector
Contents
Implement custom example selector
Use custom example selector
How to create a custom example selector#
In this tutorial, we’ll create a custom example selector that selects every alternate example from a given list of examples.
An ExampleSelector must implemen... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/example_selectors/examples/custom_example_selector.html |
0dbe03127cbc-1 | # Add new example to the set of examples
example_selector.add_example({"foo": "4"})
example_selector.examples
# -> [{'foo': '1'}, {'foo': '2'}, {'foo': '3'}, {'foo': '4'}]
# Select examples
example_selector.select_examples({"foo": "foo"})
# -> array([{'foo': '1'}, {'foo': '4'}], dtype=object)
previous
Example Selectors... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/example_selectors/examples/custom_example_selector.html |
7d34f9f4e36b-0 | .ipynb
.pdf
LengthBased ExampleSelector
LengthBased ExampleSelector#
This ExampleSelector 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 ... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/example_selectors/examples/length_based.html |
7d34f9f4e36b-1 | # 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,
pref... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/example_selectors/examples/length_based.html |
7d34f9f4e36b-2 | Input: sunny
Output: gloomy
Input: windy
Output: calm
Input: big
Output: small
Input: enthusiastic
Output:
previous
How to create a custom example selector
next
Maximal Marginal Relevance ExampleSelector
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/example_selectors/examples/length_based.html |
01dd82528830-0 | .ipynb
.pdf
Similarity ExampleSelector
Similarity ExampleSelector#
The SemanticSimilarityExampleSelector selects examples based on which examples are most similar 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.exam... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/example_selectors/examples/similarity.html |
01dd82528830-1 | 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 example
pr... | rtdocs_stable/api.python.langchain.com/en/stable/modules/prompts/example_selectors/examples/similarity.html |
42618fba6ed5-0 | .rst
.pdf
LLMs
LLMs#
Note
Conceptual Guide
Large Language Models (LLMs) are a core component of LangChain.
LangChain is not a provider of LLMs, but rather provides a standard interface through which
you can interact with a variety of LLMs.
The following sections of documentation are provided:
Getting Started: An overvi... | rtdocs_stable/api.python.langchain.com/en/stable/modules/models/llms.html |
360e34f0ef12-0 | .rst
.pdf
Text Embedding Models
Text Embedding Models#
Note
Conceptual Guide
This documentation goes over how to use the Embedding class in LangChain.
The Embedding class is a class designed for interfacing with embeddings. There are lots of Embedding providers (OpenAI, Cohere, Hugging Face, etc) - this class is design... | rtdocs_stable/api.python.langchain.com/en/stable/modules/models/text_embedding.html |
faadc63e8dd4-0 | .rst
.pdf
Chat Models
Chat Models#
Note
Conceptual Guide
Chat models are a variation on language models.
While chat models use language models under the hood, the interface they expose is a bit different.
Rather than expose a “text in, text out” API, they expose an interface where “chat messages” are the inputs and out... | rtdocs_stable/api.python.langchain.com/en/stable/modules/models/chat.html |
bae74f5f1cf6-0 | .ipynb
.pdf
Getting Started
Contents
Language Models
text -> text interface
messages -> message interface
Getting Started#
One of the core value props of LangChain is that it provides a standard interface to models. This allows you to swap easily between models. At a high level, there are two main types of models:
La... | rtdocs_stable/api.python.langchain.com/en/stable/modules/models/getting_started.html |
bae74f5f1cf6-1 | Language Models
text -> text interface
messages -> message interface
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/modules/models/getting_started.html |
9beca291dbd2-0 | .rst
.pdf
Generic Functionality
Generic Functionality#
The examples here all address certain “how-to” guides for working with LLMs.
How to use the async API for LLMs
How to write a custom LLM wrapper
How (and why) to use the fake LLM
How (and why) to use the human input LLM
How to cache LLM calls
How to serialize LLM c... | rtdocs_stable/api.python.langchain.com/en/stable/modules/models/llms/how_to_guides.html |
dac14695718d-0 | .rst
.pdf
Integrations
Integrations#
The examples here are all “how-to” guides for how to integrate with various LLM providers.
AI21
Aleph Alpha
Anyscale
Aviary
Azure OpenAI
Banana
Baseten
Setup
Single model call
Chained model calls
Beam
Bedrock
CerebriumAI
Cohere
C Transformers
Databricks
DeepInfra
ForefrontAI
Google ... | rtdocs_stable/api.python.langchain.com/en/stable/modules/models/llms/integrations.html |
093b25601e2e-0 | .ipynb
.pdf
Getting Started
Getting Started#
This notebook goes over how to use the LLM class in LangChain.
The LLM class is a class designed for interfacing with LLMs. There are lots of LLM providers (OpenAI, Cohere, Hugging Face, etc) - this class is designed to provide a standard interface for all of them. In this p... | rtdocs_stable/api.python.langchain.com/en/stable/modules/models/llms/getting_started.html |
093b25601e2e-1 | llm_result.generations[-1]
[Generation(text="\n\nWhat if love neverspeech\n\nWhat if love never ended\n\nWhat if love was only a feeling\n\nI'll never know this love\n\nIt's not a feeling\n\nBut it's what we have for each other\n\nWe just know that love is something strong\n\nAnd we can't help but be happy\n\nWe just f... | rtdocs_stable/api.python.langchain.com/en/stable/modules/models/llms/getting_started.html |
093b25601e2e-2 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/modules/models/llms/getting_started.html |
06a579da635d-0 | .ipynb
.pdf
How (and why) to use the fake LLM
How (and why) to use the fake LLM#
We expose a fake LLM class that can be used for testing. This allows you to mock out calls to the LLM and simulate what would happen if the LLM responded in a certain way.
In this notebook we go over how to use this.
We start this with usi... | rtdocs_stable/api.python.langchain.com/en/stable/modules/models/llms/examples/fake_llm.html |
c0247759aa96-0 | .ipynb
.pdf
How to serialize LLM classes
Contents
Loading
Saving
How to serialize LLM classes#
This notebook walks through how to write and read an LLM Configuration to and from disk. This is useful if you want to save the configuration for a given LLM (e.g., the provider, the temperature, etc).
from langchain.llms i... | rtdocs_stable/api.python.langchain.com/en/stable/modules/models/llms/examples/llm_serialization.html |
c0247759aa96-1 | llm.save("llm.json")
llm.save("llm.yaml")
previous
How to cache LLM calls
next
How to stream LLM and Chat Model responses
Contents
Loading
Saving
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/modules/models/llms/examples/llm_serialization.html |
2c5b45115239-0 | .ipynb
.pdf
How to write a custom LLM wrapper
How to write a custom LLM wrapper#
This notebook goes over how to create a custom LLM wrapper, in case you want to use your own LLM or a different wrapper than one that is supported in LangChain.
There is only one required thing that a custom LLM needs to implement:
A _call... | rtdocs_stable/api.python.langchain.com/en/stable/modules/models/llms/examples/custom_llm.html |
2c5b45115239-1 | 'This is a '
We can also print the LLM and see its custom print.
print(llm)
CustomLLM
Params: {'n': 10}
previous
How to use the async API for LLMs
next
How (and why) to use the fake LLM
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/modules/models/llms/examples/custom_llm.html |
fe592c586d48-0 | .ipynb
.pdf
How to track token usage
How to track token usage#
This notebook goes over how to track your token usage for specific calls. It is currently only implemented for the OpenAI API.
Let’s first look at an extremely simple example of tracking token usage for a single LLM call.
from langchain.llms import OpenAI
f... | rtdocs_stable/api.python.langchain.com/en/stable/modules/models/llms/examples/token_usage_tracking.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.