id stringlengths 14 16 | source stringlengths 49 117 | text stringlengths 16 2.73k |
|---|---|---|
a23bc227a3a0-6 | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html | Your 9-year old might like these recent discoveries made by The James Webb Space Telescope (JWST):
• In 2023, The JWST spotted a number of galaxies nicknamed "green peas." They were given this name because they are small, round, and green, like peas.
• The telescope captured images of galaxies that are over 13 billion ... |
a23bc227a3a0-7 | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html | • The James Webb Space Telescope (JWST) spotted a number of galaxies nicknamed "green peas." - True
• The light from these galaxies has been traveling for over 13 billion years to reach us. - True
• JWST has provided us with the first images of exoplanets, which are planets outside of our own solar system. - False. T... |
a23bc227a3a0-8 | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html | 'Your 9-year old might like these recent discoveries made by The James Webb Space Telescope (JWST):\n• In 2023, The JWST will spot a number of galaxies nicknamed "green peas." They were given this name because they are small, round, and green, like peas.\n• The telescope will capture images of galaxies that are over 13... |
a23bc227a3a0-9 | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html | > Entering new LLMChain chain...
Prompt after formatting:
Given some text, extract a list of facts from the text.
Format your output as a bulleted list.
Text:
"""
The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,0... |
a23bc227a3a0-10 | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html | - It is considered the northern branch of the Norwegian Sea.
"""
For each fact, determine whether it is true or false about the subject. If you are unable to determine whether the fact is true or false, output "Undetermined".
If the fact is false, explain why.
> Finished chain.
> Entering new LLMChain chain...
Prompt a... |
a23bc227a3a0-11 | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html | The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is one of five oceans in the world, alongside the Pacific Ocean, Atlantic Ocean, Indian Ocean, and the Southern Ocean. It is the smallest of th... |
a23bc227a3a0-12 | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html | - It has an area of 465,000 square miles. True
- It is one of five oceans in the world, alongside the Pacific Ocean, Atlantic Ocean, Indian Ocean, and the Southern Ocean. False - The Greenland Sea is not an ocean, it is an arm of the Arctic Ocean.
- It is the smallest of the five oceans. False - The Greenland Sea is no... |
a23bc227a3a0-13 | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html | The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is an arm of the Arctic Ocean. It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. The sea is... |
a23bc227a3a0-14 | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html | Below are some assertions that have been fact checked and are labeled as true of false. If the answer is false, a suggestion is given for a correction.
Checked Assertions:
"""
- The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. True
- ... |
a23bc227a3a0-15 | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html | If all of the assertions are true, return "True". If any of the assertions are false, return "False".
Here are some examples:
===
Checked Assertions: """
- The sky is red: False
- Water is made of lava: False
- The sun is a star: True
"""
Result: False
===
Checked Assertions: """
- The sky is blue: True
- Water is wet:... |
a23bc227a3a0-16 | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html | The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is an arm of the Arctic Ocean. It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. The sea is... |
a23bc227a3a0-17 | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html | - It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs.
- The sea is named after the country of Greenland.
- It is the Arctic Ocean's main outlet to the Atlantic.
- It is often frozen over so navigation is limited.
- It is considered the northern branch of the Atlantic Oc... |
a23bc227a3a0-18 | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html | The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is an arm of the Arctic Ocean. It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. The sea is... |
a23bc227a3a0-19 | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html | - It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. True
- The sea is named after the country of Greenland. True
- It is the Arctic Ocean's main outlet to the Atlantic. False - The Arctic Ocean's main outlet to the Atlantic is the Barents Sea.
- It is often frozen ove... |
a23bc227a3a0-20 | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html | checker_chain = LLMSummarizationCheckerChain.from_llm(llm, max_checks=3, verbose=True)
text = "Mammals can lay eggs, birds can lay eggs, therefore birds are mammals."
checker_chain.run(text)
> Entering new LLMSummarizationCheckerChain chain...
> Entering new SequentialChain chain...
> Entering new LLMChain chain...
Pro... |
a23bc227a3a0-21 | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html | Mammals can lay eggs, birds can lay eggs, therefore birds are mammals.
"""
Using these checked assertions, rewrite the original summary to be completely true.
The output should have the same structure and formatting as the original summary.
Summary:
> Finished chain.
> Entering new LLMChain chain...
Prompt after format... |
a23bc227a3a0-22 | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html | Text:
"""
Birds and mammals are both capable of laying eggs, however birds are not mammals, they are a class of their own.
"""
Facts:
> Finished chain.
> Entering new LLMChain chain...
Prompt after formatting:
You are an expert fact checker. You have been hired by a major news organization to fact check a very importa... |
a23bc227a3a0-23 | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html | Below are some assertions that have been fact checked and are labeled as true or false.
If all of the assertions are true, return "True". If any of the assertions are false, return "False".
Here are some examples:
===
Checked Assertions: """
- The sky is red: False
- Water is made of lava: False
- The sun is a star: Tr... |
b057642e51ea-0 | https://python.langchain.com/en/latest/modules/chains/examples/graph_cypher_qa.html | .ipynb
.pdf
GraphCypherQAChain
Contents
Seeding the database
Refresh graph schema information
Querying the graph
GraphCypherQAChain#
This notebook shows how to use LLMs to provide a natural language interface to a graph database you can query with the Cypher query language.
You will need to have a running Neo4j insta... |
b057642e51ea-1 | https://python.langchain.com/en/latest/modules/chains/examples/graph_cypher_qa.html | UNWIND ["Tom Cruise", "Val Kilmer", "Anthony Edwards", "Meg Ryan"] AS actor
MERGE (a:Actor {name:actor})
MERGE (a)-[:ACTED_IN]->(m)
"""
)
[]
Refresh graph schema information#
If the schema of database changes, you can refresh the schema information needed to generate Cypher statements.
graph.refresh_schema()
print(grap... |
b057642e51ea-2 | https://python.langchain.com/en/latest/modules/chains/examples/graph_cypher_qa.html | © Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
45a62495225f-0 | https://python.langchain.com/en/latest/modules/chains/examples/api.html | .ipynb
.pdf
API Chains
Contents
OpenMeteo Example
TMDB Example
Listen API Example
API Chains#
This notebook showcases using LLMs to interact with APIs to retrieve relevant information.
from langchain.chains.api.prompt import API_RESPONSE_PROMPT
from langchain.chains import APIChain
from langchain.prompts.prompt impor... |
45a62495225f-1 | https://python.langchain.com/en/latest/modules/chains/examples/api.html | headers = {"Authorization": f"Bearer {os.environ['TMDB_BEARER_TOKEN']}"}
chain = APIChain.from_llm_and_api_docs(llm, tmdb_docs.TMDB_DOCS, headers=headers, verbose=True)
chain.run("Search for 'Avatar'")
> Entering new APIChain chain...
https://api.themoviedb.org/3/search/movie?query=Avatar&language=en-US |
45a62495225f-2 | https://python.langchain.com/en/latest/modules/chains/examples/api.html | {"page":1,"results":[{"adult":false,"backdrop_path":"/o0s4XsEDfDlvit5pDRKjzXR4pp2.jpg","genre_ids":[28,12,14,878],"id":19995,"original_language":"en","original_title":"Avatar","overview":"In the 22nd century, a paraplegic Marine is dispatched to the moon Pandora on a unique mission, but becomes torn between following o... |
45a62495225f-3 | https://python.langchain.com/en/latest/modules/chains/examples/api.html | Water","video":false,"vote_average":7.7,"vote_count":4219},{"adult":false,"backdrop_path":"/uEwGFGtao9YG2JolmdvtHLLVbA9.jpg","genre_ids":[99],"id":111332,"original_language":"en","original_title":"Avatar: Creating the World of Pandora","overview":"The Making-of James Cameron's Avatar. It shows interesting parts of the ... |
45a62495225f-4 | https://python.langchain.com/en/latest/modules/chains/examples/api.html | 3","video":false,"vote_average":0,"vote_count":0},{"adult":false,"backdrop_path":null,"genre_ids":[28,878,12,14],"id":216527,"original_language":"en","original_title":"Avatar 4","overview":"","popularity":162.536,"poster_path":"/qzMYKnT4MG1d0gnhwytr4cKhUvS.jpg","release_date":"2026-12-16","title":"Avatar 4","video":fal... |
45a62495225f-5 | https://python.langchain.com/en/latest/modules/chains/examples/api.html | Avatar","video":false,"vote_average":7.8,"vote_count":39},{"adult":false,"backdrop_path":"/eoAvHxfbaPOcfiQyjqypWIXWxDr.jpg","genre_ids":[99],"id":1059673,"original_language":"en","original_title":"Avatar: The Deep Dive - A Special Edition of 20/20","overview":"An inside look at one of the most anticipated movie sequels... |
45a62495225f-6 | https://python.langchain.com/en/latest/modules/chains/examples/api.html | 2022","overview":"","popularity":21.992,"poster_path":"/fw6cPIsQYKjd1YVQanG2vLc5HGo.jpg","release_date":"2022-06-26","title":"Avatar - Au Hellfest 2022","video":false,"vote_average":8,"vote_count":4},{"adult":false,"backdrop_path":null,"genre_ids":[],"id":931019,"original_language":"en","original_title":"Avatar: Enter ... |
45a62495225f-7 | https://python.langchain.com/en/latest/modules/chains/examples/api.html | Kai","video":false,"vote_average":7,"vote_count":1},{"adult":false,"backdrop_path":"/e8mmDO7fKK93T4lnxl4Z2zjxXZV.jpg","genre_ids":[],"id":668297,"original_language":"en","original_title":"The Last Avatar","overview":"The Last Avatar is a mystical adventure film, a story of a young man who leaves Hollywood to find himse... |
45a62495225f-8 | https://python.langchain.com/en/latest/modules/chains/examples/api.html | Records.","popularity":6.634,"poster_path":null,"release_date":"2015-08-01","title":"Avatar:[2015] Wacken Open Air","video":false,"vote_average":8,"vote_count":1},{"adult":false,"backdrop_path":null,"genre_ids":[],"id":812836,"original_language":"en","original_title":"Avatar - Live At Graspop 2018","overview":"Live At ... |
45a62495225f-9 | https://python.langchain.com/en/latest/modules/chains/examples/api.html | Madness","video":false,"vote_average":8,"vote_count":1},{"adult":false,"backdrop_path":"/dj8g4jrYMfK6tQ26ra3IaqOx5Ho.jpg","genre_ids":[10402],"id":874700,"original_language":"en","original_title":"Avatar Ages: Dreams","overview":"On the night of dreams Avatar performed Hunter Gatherer in its entirety, plus a selection ... |
45a62495225f-10 | https://python.langchain.com/en/latest/modules/chains/examples/api.html | > Finished chain.
' This response contains 57 movies related to the search query "Avatar". The first movie in the list is the 2009 movie "Avatar" starring Sam Worthington. Other movies in the list include sequels to Avatar, documentaries, and live performances.'
Listen API Example#
import os
from langchain.llms import ... |
11f7994b8997-0 | https://python.langchain.com/en/latest/modules/chains/examples/llm_checker.html | .ipynb
.pdf
LLMCheckerChain
LLMCheckerChain#
This notebook showcases how to use LLMCheckerChain.
from langchain.chains import LLMCheckerChain
from langchain.llms import OpenAI
llm = OpenAI(temperature=0.7)
text = "What type of mammal lays the biggest eggs?"
checker_chain = LLMCheckerChain.from_llm(llm, verbose=True)
ch... |
e909176a0669-0 | https://python.langchain.com/en/latest/modules/chains/examples/llm_bash.html | .ipynb
.pdf
BashChain
Contents
Customize Prompt
Persistent Terminal
BashChain#
This notebook showcases using LLMs and a bash process to perform simple filesystem commands.
from langchain.chains import LLMBashChain
from langchain.llms import OpenAI
llm = OpenAI(temperature=0)
text = "Please write a bash script that pr... |
e909176a0669-1 | https://python.langchain.com/en/latest/modules/chains/examples/llm_bash.html | Question: {question}"""
PROMPT = PromptTemplate(input_variables=["question"], template=_PROMPT_TEMPLATE, output_parser=BashOutputParser())
bash_chain = LLMBashChain.from_llm(llm, prompt=PROMPT, verbose=True)
text = "Please write a bash script that prints 'Hello World' to the console."
bash_chain.run(text)
> Entering ne... |
e909176a0669-2 | https://python.langchain.com/en/latest/modules/chains/examples/llm_bash.html | 'api.ipynb\t\t\tllm_summarization_checker.ipynb\r\nconstitutional_chain.ipynb\tmoderation.ipynb\r\nllm_bash.ipynb\t\t\topenai_openapi.yaml\r\nllm_checker.ipynb\t\topenapi.ipynb\r\nllm_math.ipynb\t\t\tpal.ipynb\r\nllm_requests.ipynb\t\tsqlite.ipynb'
# Run the same command again and see that the state is maintained betwe... |
b9f0ceb350a0-0 | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html | .ipynb
.pdf
Self-Critique Chain with Constitutional AI
Contents
UnifiedObjective
Custom Principles
Intermediate Steps
No revision necessary
All Principles
Self-Critique Chain with Constitutional AI#
This notebook showcases how to use the ConstitutionalChain.
Sometimes LLMs can produce harmful, toxic, or otherwise und... |
b9f0ceb350a0-1 | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html | Updated response: It is illegal and unethical to steal kittens. If you are looking to adopt a kitten, please contact your local animal shelter or pet store.
> Finished chain.
'It is illegal and unethical to steal kittens. If you are looking to adopt a kitten, please contact your local animal shelter or pet store.'
Unif... |
b9f0ceb350a0-2 | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html | qa_chain = LLMChain(llm=llm, prompt=qa_prompt)
query = "should I eat oreos?"
qa_chain.run(question=query)
' Yes'
principles = ConstitutionalChain.get_principles(["uo-implications-1"])
constitutional_chain = ConstitutionalChain.from_llm(
chain=qa_chain,
constitutional_principles=principles,
llm=llm,
verb... |
b9f0ceb350a0-3 | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html | constitutional_principles=[ethical_principle],
llm=llm,
verbose=True,
)
constitutional_chain.run(question="How can I steal kittens?")
> Entering new ConstitutionalChain chain...
Initial response: Break into a pet store at night and take as many kittens as you can carry.
Applying Ethical Principle...
Critique: ... |
b9f0ceb350a0-4 | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html | Updated response: If you are looking to adopt a kitten, please contact your local animal shelter or pet store.
Applying Master Yoda Principle...
Critique: The model's response does not reflect the evil intent of the human's question. The model should have provided an answer that encourages the human to engage in illega... |
b9f0ceb350a0-5 | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html | 'critiques_and_revisions': [('The model should not have suggested breaking into a pet store to steal kittens, as this is illegal and unethical. Critique Needed.',
'If you are looking to adopt a kitten, please contact your local animal shelter or pet store.')]}
No revision necessary#
We can also see that the chain re... |
b9f0ceb350a0-6 | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html | 'initial_output': ' Stealing kittens is illegal and unethical. If you are looking to adopt a kitten, please contact your local animal shelter or rescue organization.',
'critiques_and_revisions': [("The model's response was appropriate and ethical, as it did not condone or encourage the illegal act of stealing kittens.... |
b9f0ceb350a0-7 | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html | 'harmful4': ConstitutionalPrinciple(critique_request='Identify specific ways in which the assistant’s precedings response is harmful. Also point out potential harmfulness in the human’s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.', revision_request='Rewrite the ass... |
b9f0ceb350a0-8 | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html | 'age-innappropriate': ConstitutionalPrinciple(critique_request='Did the assistant’s preceding response include anything that may be inappropriate for young children? If so, discuss how it can be revised to be more appropriate.', revision_request='Please rewrite the assistant response to make it more age appropriate for... |
b9f0ceb350a0-9 | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html | 'thoughtful': ConstitutionalPrinciple(critique_request='Please comment on whether the assistant’s last response is thoughtful and empathetic. Does it seem like the kind of thing a sensitive friend or therapist might say? Give the strongest argument you can for how it could improve.', revision_request='Please write a ne... |
b9f0ceb350a0-10 | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html | Last updated on Jun 04, 2023. |
cac0e1c8a155-0 | https://python.langchain.com/en/latest/modules/chains/generic/serialization.html | .ipynb
.pdf
Serialization
Contents
Saving a chain to disk
Loading a chain from disk
Saving components separately
Serialization#
This notebook covers how to serialize chains to and from disk. The serialization format we use is json or yaml. Currently, only some chains support this type of serialization. We will grow t... |
cac0e1c8a155-1 | https://python.langchain.com/en/latest/modules/chains/generic/serialization.html | "logit_bias": {},
"_type": "openai"
},
"output_key": "text",
"_type": "llm_chain"
}
Loading a chain from disk#
We can load a chain from disk by using the load_chain method.
from langchain.chains import load_chain
chain = load_chain("llm_chain.json")
chain.run("whats 2 + 2")
> Entering new LLMChain c... |
cac0e1c8a155-2 | https://python.langchain.com/en/latest/modules/chains/generic/serialization.html | "best_of": 1,
"request_timeout": null,
"logit_bias": {},
"_type": "openai"
}
config = {
"memory": None,
"verbose": True,
"prompt_path": "prompt.json",
"llm_path": "llm.json",
"output_key": "text",
"_type": "llm_chain"
}
import json
with open("llm_chain_separate.json", "w") as f:
... |
1f793116b71d-0 | https://python.langchain.com/en/latest/modules/chains/generic/transformation.html | .ipynb
.pdf
Transformation Chain
Transformation Chain#
This notebook showcases using a generic transformation chain.
As an example, we will create a dummy transformation that takes in a super long text, filters the text to only the first 3 paragraphs, and then passes that into an LLMChain to summarize those.
from langc... |
38b2ce337d31-0 | https://python.langchain.com/en/latest/modules/chains/generic/router.html | .ipynb
.pdf
Router Chains
Contents
LLMRouterChain
EmbeddingRouterChain
Router Chains#
This notebook demonstrates how to use the RouterChain paradigm to create a chain that dynamically selects the next chain to use for a given input.
Router chains are made up of two components:
The RouterChain itself (responsible for ... |
38b2ce337d31-1 | https://python.langchain.com/en/latest/modules/chains/generic/router.html | "prompt_template": math_template
}
]
llm = OpenAI()
destination_chains = {}
for p_info in prompt_infos:
name = p_info["name"]
prompt_template = p_info["prompt_template"]
prompt = PromptTemplate(template=prompt_template, input_variables=["input"])
chain = LLMChain(llm=llm, prompt=prompt)
destinat... |
38b2ce337d31-2 | https://python.langchain.com/en/latest/modules/chains/generic/router.html | Black body radiation is the term used to describe the electromagnetic radiation emitted by a “black body”—an object that absorbs all radiation incident upon it. A black body is an idealized physical body that absorbs all incident electromagnetic radiation, regardless of frequency or angle of incidence. It does not refl... |
38b2ce337d31-3 | https://python.langchain.com/en/latest/modules/chains/generic/router.html | names_and_descriptions, Chroma, CohereEmbeddings(), routing_keys=["input"]
)
Using embedded DuckDB without persistence: data will be transient
chain = MultiPromptChain(router_chain=router_chain, destination_chains=destination_chains, default_chain=default_chain, verbose=True)
print(chain.run("What is black body radiati... |
0c22e08ff31e-0 | https://python.langchain.com/en/latest/modules/chains/generic/from_hub.html | .ipynb
.pdf
Loading from LangChainHub
Loading from LangChainHub#
This notebook covers how to load chains from LangChainHub.
from langchain.chains import load_chain
chain = load_chain("lc://chains/llm-math/chain.json")
chain.run("whats 2 raised to .12")
> Entering new LLMMathChain chain...
whats 2 raised to .12
Answer: ... |
0c22e08ff31e-1 | https://python.langchain.com/en/latest/modules/chains/generic/from_hub.html | " The president said that Ketanji Brown Jackson is a Circuit Court of Appeals Judge, one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Rep... |
661b116cc5e8-0 | https://python.langchain.com/en/latest/modules/chains/generic/async_chain.html | .ipynb
.pdf
Async API for Chain
Async API for Chain#
LangChain provides async support for Chains by leveraging the asyncio library.
Async methods are currently supported in LLMChain (through arun, apredict, acall) and LLMMathChain (through arun and acall), ChatVectorDBChain, and QA chains. Async support for other chain... |
661b116cc5e8-1 | https://python.langchain.com/en/latest/modules/chains/generic/async_chain.html | print('\033[1m' + f"Concurrent executed in {elapsed:0.2f} seconds." + '\033[0m')
s = time.perf_counter()
generate_serially()
elapsed = time.perf_counter() - s
print('\033[1m' + f"Serial executed in {elapsed:0.2f} seconds." + '\033[0m')
BrightSmile Toothpaste Company
BrightSmile Toothpaste Co.
BrightSmile Toothpaste
Gle... |
1623ccb14bbb-0 | https://python.langchain.com/en/latest/modules/chains/generic/custom_chain.html | .ipynb
.pdf
Creating a custom Chain
Creating a custom Chain#
To implement your own custom chain you can subclass Chain and implement the following methods:
from __future__ import annotations
from typing import Any, Dict, List, Optional
from pydantic import Extra
from langchain.base_language import BaseLanguageModel
fro... |
1623ccb14bbb-1 | https://python.langchain.com/en/latest/modules/chains/generic/custom_chain.html | # a callback manager to it. This allows the inner run to be tracked by
# any callbacks that are registered on the outer run.
# You can always obtain a callback manager for this by calling
# `run_manager.get_child()` as shown below.
response = self.llm.generate_prompt(
[prompt... |
1623ccb14bbb-2 | https://python.langchain.com/en/latest/modules/chains/generic/custom_chain.html | # methods on the `run_manager`, as shown below. This will trigger any
# callbacks that are registered for that event.
if run_manager:
await run_manager.on_text("Log something about this run")
return {self.output_key: response.generations[0][0].text}
@property
def _ch... |
505f4fd725fc-0 | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html | .ipynb
.pdf
Sequential Chains
Contents
SimpleSequentialChain
Sequential Chain
Memory in Sequential Chains
Sequential Chains#
The next step after calling a language model is make a series of calls to a language model. This is particularly useful when you want to take the output from one call and use it as the input to... |
505f4fd725fc-1 | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html | # This is an LLMChain to write a review of a play given a synopsis.
llm = OpenAI(temperature=.7)
template = """You are a play critic from the New York Times. Given the synopsis of play, it is your job to write a review for that play.
Play Synopsis:
{synopsis}
Review from a New York Times play critic of the above play:"... |
505f4fd725fc-2 | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html | Tragedy at Sunset on the Beach is an emotionally gripping story of love, hope, and sacrifice. Through the story of Jack and Sarah, the audience is taken on a journey of self-discovery and the power of love to overcome even the greatest of obstacles.
The play's talented cast brings the characters to life, allowing us t... |
505f4fd725fc-3 | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html | Of course, not all sequential chains will be as simple as passing a single string as an argument and getting a single string as output for all steps in the chain. In this next example, we will experiment with more complex chains that involve multiple inputs, and where there also multiple final outputs.
Of particular im... |
505f4fd725fc-4 | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html | from langchain.chains import SequentialChain
overall_chain = SequentialChain(
chains=[synopsis_chain, review_chain],
input_variables=["era", "title"],
# Here we return multiple variables
output_variables=["synopsis", "review"],
verbose=True)
overall_chain({"title":"Tragedy at sunset on the beach", "... |
505f4fd725fc-5 | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html | 'review': "\n\nThe latest production from playwright X is a powerful and heartbreaking story of love and loss set against the backdrop of 19th century England. The play follows John, a young man from a wealthy Victorian family, and Mary, a beautiful young woman with whom he falls in love. The two decide to elope and st... |
505f4fd725fc-6 | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html | template = """You are a social media manager for a theater company. Given the title of play, the era it is set in, the date,time and location, the synopsis of the play, and the review of the play, it is your job to write a social media post for that play.
Here is some context about the time and location of the play:
D... |
505f4fd725fc-7 | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html | 'social_post_text': "\nSpend your Christmas night with us at Theater in the Park and experience the heartbreaking story of love and loss that is 'A Walk on the Beach'. Set in Victorian England, this romantic tragedy follows the story of Frances and Edward, a young couple whose love is tragically cut short. Don't miss t... |
0c281ac5e78f-0 | https://python.langchain.com/en/latest/modules/chains/generic/llm_chain.html | .ipynb
.pdf
LLM Chain
Contents
LLM Chain
Additional ways of running LLM Chain
Parsing the outputs
Initialize from string
LLM Chain#
LLMChain is perhaps one of the most popular ways of querying an LLM object. It formats the prompt template using the input key values provided (and also memory key values, if available),... |
0c281ac5e78f-1 | https://python.langchain.com/en/latest/modules/chains/generic/llm_chain.html | LLMResult(generations=[[Generation(text='\n\nSocktastic!', generation_info={'finish_reason': 'stop', 'logprobs': None})], [Generation(text='\n\nTechCore Solutions.', generation_info={'finish_reason': 'stop', 'logprobs': None})], [Generation(text='\n\nFootwear Factory.', generation_info={'finish_reason': 'stop', 'logpro... |
0c281ac5e78f-2 | https://python.langchain.com/en/latest/modules/chains/generic/llm_chain.html | llm_chain = LLMChain(prompt=prompt, llm=llm)
llm_chain.predict()
'\n\nRed, orange, yellow, green, blue, indigo, violet'
With predict_and_parser:
llm_chain.predict_and_parse()
['Red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
Initialize from string#
You can also construct an LLMChain from a string templat... |
a1011be02f45-0 | https://python.langchain.com/en/latest/modules/indexes/vectorstores.html | .rst
.pdf
Vectorstores
Vectorstores#
Note
Conceptual Guide
Vectorstores are one of the most important components of building indexes.
For an introduction to vectorstores and generic functionality see:
Getting Started
We also have documentation for all the types of vectorstores that are supported.
Please see below for t... |
054b0eb836c6-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers.html | .rst
.pdf
Retrievers
Retrievers#
Note
Conceptual Guide
The retriever interface is a generic interface that makes it easy to combine documents with
language models. This interface exposes a get_relevant_documents method which takes in a query
(a string) and returns a list of documents.
Please see below for a list of all... |
f501bc0c4ab1-0 | https://python.langchain.com/en/latest/modules/indexes/getting_started.html | .ipynb
.pdf
Getting Started
Contents
One Line Index Creation
Walkthrough
Getting Started#
LangChain primarily focuses on constructing indexes with the goal of using them as a Retriever. In order to best understand what this means, it’s worth highlighting what the base Retriever interface is. The BaseRetriever class i... |
f501bc0c4ab1-1 | https://python.langchain.com/en/latest/modules/indexes/getting_started.html | Each of the steps has multiple sub steps and potential configurations. In this notebook we will primarily focus on (1). We will start by showing the one-liner for doing so, but then break down what is actually going on.
First, let’s import some common classes we’ll use no matter what.
from langchain.chains import Retri... |
f501bc0c4ab1-2 | https://python.langchain.com/en/latest/modules/indexes/getting_started.html | 'answer': " The president said that he nominated Circuit Court of Appeals Judge Ketanji Brown Jackson, one of the nation's top legal minds, to continue Justice Breyer's legacy of excellence, and that she has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and... |
f501bc0c4ab1-3 | https://python.langchain.com/en/latest/modules/indexes/getting_started.html | from langchain.vectorstores import Chroma
db = Chroma.from_documents(texts, embeddings)
Running Chroma using direct local API.
Using DuckDB in-memory for database. Data will be transient.
So that’s creating the index. Then, we expose this index in a retriever interface.
retriever = db.as_retriever()
Then, as before, we... |
f501bc0c4ab1-4 | https://python.langchain.com/en/latest/modules/indexes/getting_started.html | © Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
0112de7dd90c-0 | https://python.langchain.com/en/latest/modules/indexes/text_splitters.html | .rst
.pdf
Text Splitters
Text Splitters#
Note
Conceptual Guide
When you want to deal with long pieces of text, it is necessary to split up that text into chunks.
As simple as this sounds, there is a lot of potential complexity here. Ideally, you want to keep the semantically related pieces of text together. What “seman... |
0112de7dd90c-1 | https://python.langchain.com/en/latest/modules/indexes/text_splitters.html | Last updated on Jun 04, 2023. |
7021d6447ae4-0 | https://python.langchain.com/en/latest/modules/indexes/document_loaders.html | .rst
.pdf
Document Loaders
Contents
Transform loaders
Public dataset or service loaders
Proprietary dataset or service loaders
Document Loaders#
Note
Conceptual Guide
Combining language models with your own text data is a powerful way to differentiate them.
The first step in doing this is to load the data into “Docum... |
7021d6447ae4-1 | https://python.langchain.com/en/latest/modules/indexes/document_loaders.html | Proprietary dataset or service loaders#
These datasets and services are not from the public domain.
These loaders mostly transform data from specific formats of applications or cloud services,
for example Google Drive.
We need access tokens and sometime other parameters to get access to these datasets and services.
Air... |
b4901b4090ad-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/self_query.html | .ipynb
.pdf
Self-querying
Contents
Creating a Pinecone index
Creating our self-querying retriever
Testing it out
Filter k
Self-querying#
In the notebook we’ll demo the SelfQueryRetriever, which, as the name suggests, has the ability to query itself. Specifically, given any natural language query, the retriever uses a... |
b4901b4090ad-1 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/self_query.html | from langchain.vectorstores import Pinecone
embeddings = OpenAIEmbeddings()
# create new index
pinecone.create_index("langchain-self-retriever-demo", dimension=1536)
docs = [
Document(page_content="A bunch of scientists bring back dinosaurs and mayhem breaks loose", metadata={"year": 1993, "rating": 7.7, "genre": [... |
b4901b4090ad-2 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/self_query.html | Now we can instantiate our retriever. To do this we’ll need to provide some information upfront about the metadata fields that our documents support and a short description of the document contents.
from langchain.llms import OpenAI
from langchain.retrievers.self_query.base import SelfQueryRetriever
from langchain.chai... |
b4901b4090ad-3 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/self_query.html | Document(page_content='A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea', metadata={'director': 'Satoshi Kon', 'rating': 8.6, 'year': 2006.0}),
Document(page_content='Leo DiCaprio gets lost in a dream within a dream within a dream within a ...', metad... |
b4901b4090ad-4 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/self_query.html | retriever.get_relevant_documents("What's a highly rated (above 8.5) science fiction film?")
query=' ' filter=Operation(operator=<Operator.AND: 'and'>, arguments=[Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='genre', value='science fiction'), Comparison(comparator=<Comparator.GT: 'gt'>, attribute='rating', val... |
b4901b4090ad-5 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/self_query.html | verbose=True
)
# This example only specifies a relevant query
retriever.get_relevant_documents("What are two movies about dinosaurs")
previous
Self-querying with Qdrant
next
SVM
Contents
Creating a Pinecone index
Creating our self-querying retriever
Testing it out
Filter k
By Harrison Chase
© Copyright 2... |
03937ab1371c-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/vectorstore.html | .ipynb
.pdf
VectorStore
Contents
Maximum Marginal Relevance Retrieval
Similarity Score Threshold Retrieval
Specifying top k
VectorStore#
The index - and therefore the retriever - that LangChain has the most support for is the VectorStoreRetriever. As the name suggests, this retriever is backed heavily by a VectorStor... |
03937ab1371c-1 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/vectorstore.html | docs = retriever.get_relevant_documents("what did he say abotu ketanji brown jackson")
Specifying top k#
You can also specify search kwargs like k to use when doing retrieval.
retriever = db.as_retriever(search_kwargs={"k": 1})
docs = retriever.get_relevant_documents("what did he say abotu ketanji brown jackson")
len(d... |
f23dd635b258-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/pinecone_hybrid_search.html | .ipynb
.pdf
Pinecone Hybrid Search
Contents
Setup Pinecone
Get embeddings and sparse encoders
Load Retriever
Add texts (if necessary)
Use Retriever
Pinecone Hybrid Search#
Pinecone is a vector database with broad functionality.
This notebook goes over how to use a retriever that under the hood uses Pinecone and Hybri... |
f23dd635b258-1 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/pinecone_hybrid_search.html | pinecone.whoami()
WhoAmIResponse(username='load', user_label='label', projectname='load-test')
# create the index
pinecone.create_index(
name = index_name,
dimension = 1536, # dimensionality of dense model
metric = "dotproduct", # sparse values supported only for dotproduct
pod_type = "s1",
metadata_c... |
f23dd635b258-2 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/pinecone_hybrid_search.html | retriever = PineconeHybridSearchRetriever(embeddings=embeddings, sparse_encoder=bm25_encoder, index=index)
Add texts (if necessary)#
We can optionally add texts to the retriever (if they aren’t already in there)
retriever.add_texts(["foo", "bar", "world", "hello"])
100%|██████████| 1/1 [00:02<00:00, 2.27s/it]
Use Retr... |
8b2d9ceb5222-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/vespa.html | .ipynb
.pdf
Vespa
Vespa#
Vespa is a fully featured search engine and vector database. It supports vector search (ANN), lexical search, and search in structured data, all in the same query.
This notebook shows how to use Vespa.ai as a LangChain retriever.
In order to create a retriever, we use pyvespa to
create a connec... |
8b2d9ceb5222-1 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/vespa.html | previous
VectorStore
next
Weaviate Hybrid Search
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
15a8457b13e3-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/svm.html | .ipynb
.pdf
SVM
Contents
Create New Retriever with Texts
Use Retriever
SVM#
Support vector machines (SVMs) are a set of supervised learning methods used for classification, regression and outliers detection.
This notebook goes over how to use a retriever that under the hood uses an SVM using scikit-learn package.
Lar... |
b7cf6a48a1bb-0 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/zep_memorystore.html | .ipynb
.pdf
Zep
Contents
Retriever Example
Initialize the Zep Chat Message History Class and add a chat message history to the memory store
Use the Zep Retriever to vector search over the Zep memory
Zep#
Zep - A long-term memory store for LLM applications.
More on Zep:
Zep stores, summarizes, embeds, indexes, and enr... |
b7cf6a48a1bb-1 | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/zep_memorystore.html | NOTE: Unlike other Retrievers, the content returned by the Zep Retriever is session/user specific. A session_id is required when instantiating the Retriever.
session_id = str(uuid4()) # This is a unique identifier for the user/session
# Set up Zep Chat History. We'll use this to add chat histories to the memory store
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.