id
stringlengths
14
16
text
stringlengths
29
2.73k
source
stringlengths
49
117
5640ee21701e-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...
https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html
5640ee21701e-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, ...
https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html
5640ee21701e-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...
https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html
5640ee21701e-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...
https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html
c8b3cbe7b475-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...
https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/custom_example_selector.html
c8b3cbe7b475-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...
https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/custom_example_selector.html
196aa3c678c0-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...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/getting_started.html
196aa3c678c0-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...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/getting_started.html
3b71f38fc2a7-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...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/retry.html
3b71f38fc2a7-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...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/retry.html
3b71f38fc2a7-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....
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/retry.html
e331ec1ac93f-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...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/output_fixing_parser.html
e331ec1ac93f-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...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/output_fixing_parser.html
e331ec1ac93f-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...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/output_fixing_parser.html
8c6fabfe839a-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...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/comma_separated.html
925acb90f659-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,...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/structured.html
925acb90f659-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(...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/structured.html
9c901d257219-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...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/enum.html
9c901d257219-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...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/enum.html
52f0f40ddc9c-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...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/pydantic.html
52f0f40ddc9c-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(...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/pydantic.html
b691ce7c7a15-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...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/datetime.html
634c1863de2c-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...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/how_to_guides.html
4c791ccd8d07-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...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html
4c791ccd8d07-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...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html
4c791ccd8d07-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...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html
4c791ccd8d07-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...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html
4c791ccd8d07-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...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html
4c791ccd8d07-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...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html
4c791ccd8d07-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...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html
27dbae2411cd-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...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html
27dbae2411cd-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"], ...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html
27dbae2411cd-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...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html
27dbae2411cd-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...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html
27dbae2411cd-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...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html
27dbae2411cd-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...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html
5dcfc9951c97-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 ...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/partial.html
5dcfc9951c97-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...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/partial.html
5dcfc9951c97-2
Contents Partial With Strings Partial With Functions By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 29, 2023.
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/partial.html
d2d2356563ce-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...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html
d2d2356563ce-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 """ }, ...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html
d2d2356563ce-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 ...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html
d2d2356563ce-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...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html
d2d2356563ce-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,...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html
d2d2356563ce-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...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html
efd7e1b9e28a-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 ...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html
efd7e1b9e28a-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...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html
efd7e1b9e28a-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...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html
efd7e1b9e28a-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...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html
efd7e1b9e28a-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...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html
efd7e1b9e28a-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...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html
efd7e1b9e28a-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 May 29, 2023.
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html
f0d68bcccf3a-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 ...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/custom_prompt_template.html
f0d68bcccf3a-1
import inspect 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.prompt...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/custom_prompt_template.html
f0d68bcccf3a-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...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/custom_prompt_template.html
dc2648f618db-0
.rst .pdf How-To Guides How-To Guides# A chain is made up of links, which can be either primitives or other chains. Primitives can be either prompts, models, arbitrary functions, or other chains. The examples here are broken up into three sections: Generic Functionality Covers both generic chains (that are useful in a ...
https://python.langchain.com/en/latest/modules/chains/how_to_guides.html
b885ab11db62-0
.ipynb .pdf Getting Started Contents Why do we need chains? Quick start: Using LLMChain Different ways of calling chains Add memory to chains Debug Chain Combine chains with the SequentialChain Create a custom chain with the Chain class Getting Started# In this tutorial, we will learn about creating simple chains in ...
https://python.langchain.com/en/latest/modules/chains/getting_started.html
b885ab11db62-1
print(chain.run("colorful socks")) Colorful Toes Co. If there are multiple variables, you can input them all at once using a dictionary. prompt = PromptTemplate( input_variables=["company", "product"], template="What is a good name for {company} that makes {product}?", ) chain = LLMChain(llm=llm, prompt=prompt)...
https://python.langchain.com/en/latest/modules/chains/getting_started.html
b885ab11db62-2
llm_chain(inputs={"adjective":"corny"}) {'adjective': 'corny', 'text': 'Why did the tomato turn red? Because it saw the salad dressing!'} By default, __call__ returns both the input and output key values. You can configure it to only return output key values by setting return_only_outputs to True. llm_chain("corny", r...
https://python.langchain.com/en/latest/modules/chains/getting_started.html
b885ab11db62-3
from langchain.memory import ConversationBufferMemory conversation = ConversationChain( llm=chat, memory=ConversationBufferMemory() ) conversation.run("Answer briefly. What are the first 3 colors of a rainbow?") # -> The first three colors of a rainbow are red, orange, and yellow. conversation.run("And the next...
https://python.langchain.com/en/latest/modules/chains/getting_started.html
b885ab11db62-4
Current conversation: Human: What is ChatGPT? AI: > Finished chain. 'ChatGPT is an AI language model developed by OpenAI. It is based on the GPT-3 architecture and is capable of generating human-like responses to text prompts. ChatGPT has been trained on a massive amount of text data and can understand and respond to a...
https://python.langchain.com/en/latest/modules/chains/getting_started.html
b885ab11db62-5
catchphrase = overall_chain.run("colorful socks") print(catchphrase) > Entering new SimpleSequentialChain chain... Rainbow Socks Co. "Put a little rainbow in your step!" > Finished chain. "Put a little rainbow in your step!" Create a custom chain with the Chain class# LangChain provides many chains out of the box, but ...
https://python.langchain.com/en/latest/modules/chains/getting_started.html
b885ab11db62-6
prompt_1 = PromptTemplate( input_variables=["product"], template="What is a good name for a company that makes {product}?", ) chain_1 = LLMChain(llm=llm, prompt=prompt_1) prompt_2 = PromptTemplate( input_variables=["product"], template="What is a good slogan for a company that makes {product}?", ) chain...
https://python.langchain.com/en/latest/modules/chains/getting_started.html
8d54cd1936a6-0
.ipynb .pdf Graph QA Contents Create the graph Querying the graph Save the graph Graph QA# This notebook goes over how to do question answering over a graph data structure. Create the graph# In this section, we construct an example graph. At the moment, this works best for small pieces of text. from langchain.indexes...
https://python.langchain.com/en/latest/modules/chains/index_examples/graph_qa.html
8d54cd1936a6-1
'is the ground on which')] Querying the graph# We can now use the graph QA chain to ask question of the graph from langchain.chains import GraphQAChain chain = GraphQAChain.from_llm(OpenAI(temperature=0), graph=graph, verbose=True) chain.run("what is Intel going to build?") > Entering new GraphQAChain chain... Entities...
https://python.langchain.com/en/latest/modules/chains/index_examples/graph_qa.html
8d54cd1936a6-2
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 29, 2023.
https://python.langchain.com/en/latest/modules/chains/index_examples/graph_qa.html
b8d8ac6c27e0-0
.ipynb .pdf Retrieval Question Answering with Sources Contents Chain Type Retrieval Question Answering with Sources# This notebook goes over how to do question-answering with sources over an Index. It does this by using the RetrievalQAWithSourcesChain, which does the lookup of the documents from an Index. from langch...
https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_qa_with_sources.html
b8d8ac6c27e0-1
'sources': '31-pl'} Chain Type# You can easily specify different chain types to load and use in the RetrievalQAWithSourcesChain chain. For a more detailed walkthrough of these types, please see this notebook. There are two ways to load different chain types. First, you can specify the chain type argument in the from_ch...
https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_qa_with_sources.html
b8d8ac6c27e0-2
{'answer': ' The president honored Justice Breyer for his service and mentioned his legacy of excellence.\n', 'sources': '31-pl'} previous Retrieval Question/Answering next Vector DB Text Generation Contents Chain Type By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 29, ...
https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_qa_with_sources.html
abbc23b05ba7-0
.ipynb .pdf Chat Over Documents with Chat History Contents Pass in chat history Return Source Documents ConversationalRetrievalChain with search_distance ConversationalRetrievalChain with map_reduce ConversationalRetrievalChain with Question Answering with sources ConversationalRetrievalChain with streaming to stdout...
https://python.langchain.com/en/latest/modules/chains/index_examples/chat_vector_db.html
abbc23b05ba7-1
Using embedded DuckDB without persistence: data will be transient We can now create a memory object, which is neccessary to track the inputs/outputs and hold a conversation. from langchain.memory import ConversationBufferMemory memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True) We now in...
https://python.langchain.com/en/latest/modules/chains/index_examples/chat_vector_db.html
abbc23b05ba7-2
result = qa({"question": query, "chat_history": chat_history}) result["answer"] " The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also ...
https://python.langchain.com/en/latest/modules/chains/index_examples/chat_vector_db.html
abbc23b05ba7-3
result['source_documents'][0] Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n\nTonight, I’d like to honor someone who has dedicated his life ...
https://python.langchain.com/en/latest/modules/chains/index_examples/chat_vector_db.html
abbc23b05ba7-4
from langchain.chains.question_answering import load_qa_chain from langchain.chains.conversational_retrieval.prompts import CONDENSE_QUESTION_PROMPT llm = OpenAI(temperature=0) question_generator = LLMChain(llm=llm, prompt=CONDENSE_QUESTION_PROMPT) doc_chain = load_qa_chain(llm, chain_type="map_reduce") chain = Convers...
https://python.langchain.com/en/latest/modules/chains/index_examples/chat_vector_db.html
abbc23b05ba7-5
combine_docs_chain=doc_chain, ) chat_history = [] query = "What did the president say about Ketanji Brown Jackson" result = chain({"question": query, "chat_history": chat_history}) result['answer'] " The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private ...
https://python.langchain.com/en/latest/modules/chains/index_examples/chat_vector_db.html
abbc23b05ba7-6
chat_history = [] query = "What did the president say about Ketanji Brown Jackson" result = qa({"question": query, "chat_history": chat_history}) The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from ...
https://python.langchain.com/en/latest/modules/chains/index_examples/chat_vector_db.html
abbc23b05ba7-7
result = qa({"question": query, "chat_history": chat_history}) result['answer'] " The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also ...
https://python.langchain.com/en/latest/modules/chains/index_examples/chat_vector_db.html
46ff9fe12096-0
.ipynb .pdf Question Answering with Sources Contents Prepare Data Quickstart The stuff Chain The map_reduce Chain The refine Chain The map-rerank Chain Question Answering with Sources# This notebook walks through how to use LangChain for question answering with sources over a list of documents. It covers four differe...
https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html
46ff9fe12096-1
from langchain.chains.qa_with_sources import load_qa_with_sources_chain from langchain.llms import OpenAI Quickstart# If you just want to get started as quickly as possible, this is the recommended way to do it: chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type="stuff") query = "What did the presiden...
https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html
46ff9fe12096-2
PROMPT = PromptTemplate(template=template, input_variables=["summaries", "question"]) chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type="stuff", prompt=PROMPT) query = "What did the president say about Justice Breyer" chain({"input_documents": docs, "question": query}, return_only_outputs=True) {'out...
https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html
46ff9fe12096-3
' None', ' None', ' None'], 'output_text': ' The president thanked Justice Breyer for his service.\nSOURCES: 30-pl'} Custom Prompts You can also use your own prompts with this chain. In this example, we will respond in Italian. question_prompt_template = """Use the following portion of a long document to see if an...
https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html
46ff9fe12096-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...
https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html
46ff9fe12096-5
chain({"input_documents": docs, "question": query}, return_only_outputs=True) {'output_text': "\n\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked him for his service and praised his c...
https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html
46ff9fe12096-6
chain({"input_documents": docs, "question": query}, return_only_outputs=True) {'intermediate_steps': ['\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked Justice Breyer for his service....
https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html
46ff9fe12096-7
'\n\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked Justice Breyer for his service, noting his background as a top litigator in private practice, a former federal public defender, and...
https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html
46ff9fe12096-8
'\n\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked Justice Breyer for his service, noting his background as a top litigator in private practice, a former federal public defender, and...
https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html
46ff9fe12096-9
'output_text': '\n\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked Justice Breyer for his service, noting his background as a top litigator in private practice, a former federal publi...
https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html
46ff9fe12096-10
"answer the question (in Italian)" "If you do update it, please update the sources as well. " "If the context isn't useful, return the original answer." ) refine_prompt = PromptTemplate( input_variables=["question", "existing_answer", "context_str"], template=refine_template, ) question_template = ( ...
https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html
46ff9fe12096-11
"\n\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha onorato la sua carriera e ha contribuito a costruire un consenso. Ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Inoltre, ha sottolineato l'impor...
https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html
46ff9fe12096-12
"\n\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha onorato la sua carriera e ha contribuito a costruire un consenso. Ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Inoltre, ha sottolineato l'impor...
https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html
46ff9fe12096-13
"\n\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha onorato la sua carriera e ha contribuito a costruire un consenso. Ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Inoltre, ha sottolineato l'impor...
https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html
46ff9fe12096-14
'output_text': "\n\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha onorato la sua carriera e ha contribuito a costruire un consenso. Ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Inoltre, ha sotto...
https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html
46ff9fe12096-15
'score': '100'}, {'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...
https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html
46ff9fe12096-16
result {'source': 30, 'intermediate_steps': [{'answer': ' Il presidente ha detto che Justice Breyer ha dedicato la sua vita a servire questo paese e ha onorato la sua carriera.', 'score': '100'}, {'answer': ' Il presidente non ha detto nulla sulla Giustizia Breyer.', 'score': '100'}, {'answer': ' Non so.', '...
https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html
7743725c1ab3-0
.ipynb .pdf Analyze Document Contents Summarize Question Answering Analyze Document# The AnalyzeDocumentChain is more of an end to chain. This chain takes in a single document, splits it up, and then runs it through a CombineDocumentsChain. This can be used as more of an end-to-end chain. with open("../../state_of_th...
https://python.langchain.com/en/latest/modules/chains/index_examples/analyze_document.html
7743725c1ab3-1
qa_chain = load_qa_chain(llm, chain_type="map_reduce") qa_document_chain = AnalyzeDocumentChain(combine_docs_chain=qa_chain) qa_document_chain.run(input_document=state_of_the_union, question="what did the president say about justice breyer?") ' The president thanked Justice Breyer for his service.' previous Transformat...
https://python.langchain.com/en/latest/modules/chains/index_examples/analyze_document.html
a14e5c2ac01f-0
.ipynb .pdf Question Answering Contents Prepare Data Quickstart The stuff Chain The map_reduce Chain The refine Chain The map-rerank Chain Question Answering# This notebook walks through how to use LangChain for question answering over a list of documents. It covers four different types of chains: stuff, map_reduce, ...
https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html
a14e5c2ac01f-1
from langchain.llms import OpenAI Quickstart# If you just want to get started as quickly as possible, this is the recommended way to do it: chain = load_qa_chain(OpenAI(temperature=0), chain_type="stuff") query = "What did the president say about Justice Breyer" chain.run(input_documents=docs, question=query) ' The pre...
https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html
a14e5c2ac01f-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...
https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html
a14e5c2ac01f-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...
https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html