id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
7dd26afda868-5 | Avatar is a feature length behind-the-scenes documentary about the making of Avatar. It uses footage from the film's development, as well as stock footage from as far back as the production of Titanic in 1995. Also included are numerous interviews with cast, artists, and other crew members. The documentary was released... | https://python.langchain.com/en/latest/modules/chains/examples/api.html |
7dd26afda868-6 | The Deep Dive - A Special Edition of 20/20","video":false,"vote_average":6.5,"vote_count":5},{"adult":false,"backdrop_path":null,"genre_ids":[99],"id":278698,"original_language":"en","original_title":"Avatar Spirits","overview":"Bryan Konietzko and Michael Dante DiMartino, co-creators of the hit television series, Avat... | https://python.langchain.com/en/latest/modules/chains/examples/api.html |
7dd26afda868-7 | the scenes look at the new James Cameron blockbuster “Avatar”, which stars Aussie Sam Worthington. Hastily produced by Australia’s Nine Network following the film’s release.","popularity":30.903,"poster_path":"/9MHY9pYAgs91Ef7YFGWEbP4WJqC.jpg","release_date":"2009-12-05","title":"Avatar: Enter The World","video":false,... | https://python.langchain.com/en/latest/modules/chains/examples/api.html |
7dd26afda868-8 | Agni 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 ... | https://python.langchain.com/en/latest/modules/chains/examples/api.html |
7dd26afda868-9 | awaken and create a world of truth, harmony and possibility.","popularity":8.786,"poster_path":"/XWz5SS5g5mrNEZjv3FiGhqCMOQ.jpg","release_date":"2014-12-06","title":"The Last Avatar","video":false,"vote_average":4.5,"vote_count":2},{"adult":false,"backdrop_path":null,"genre_ids":[],"id":424768,"original_language":"en",... | https://python.langchain.com/en/latest/modules/chains/examples/api.html |
7dd26afda868-10 | 2018","overview":"Live At Graspop Festival Belgium 2018","popularity":9.855,"poster_path":null,"release_date":"","title":"Avatar - Live At Graspop 2018","video":false,"vote_average":9,"vote_count":1},{"adult":false,"backdrop_path":null,"genre_ids":[10402],"id":874770,"original_language":"en","original_title":"Avatar Ag... | https://python.langchain.com/en/latest/modules/chains/examples/api.html |
7dd26afda868-11 | Ages: 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 sele... | https://python.langchain.com/en/latest/modules/chains/examples/api.html |
7dd26afda868-12 | > 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 ... | https://python.langchain.com/en/latest/modules/chains/examples/api.html |
aaecc0b5168b-0 | .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... | https://python.langchain.com/en/latest/modules/chains/examples/llm_checker.html |
93653b3cc304-0 | .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... | https://python.langchain.com/en/latest/modules/chains/examples/llm_bash.html |
93653b3cc304-1 | Do not use 'echo' when writing the script.
That is the format. Begin!
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 pr... | https://python.langchain.com/en/latest/modules/chains/examples/llm_bash.html |
93653b3cc304-2 | llm_requests.ipynb sqlite.ipynb
> Finished chain.
'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 comma... | https://python.langchain.com/en/latest/modules/chains/examples/llm_bash.html |
cdccee71a2fd-0 | .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... | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
cdccee71a2fd-1 | 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... | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
cdccee71a2fd-2 | 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... | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
cdccee71a2fd-3 | )
constitutional_chain = ConstitutionalChain.from_llm(
chain=evil_qa_chain,
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... | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
cdccee71a2fd-4 | Applying Ethical Principle...
Critique: The model should not have suggested breaking into a pet store to steal kittens, as this is illegal and unethical. Critique Needed.
Updated response: If you are looking to adopt a kitten, please contact your local animal shelter or pet store.
Applying Master Yoda Principle...
Crit... | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
cdccee71a2fd-5 | 'initial_output': ' Break into a pet store at night and take as many kittens as you can carry.',
'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 yo... | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
cdccee71a2fd-6 | '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.... | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
cdccee71a2fd-7 | '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... | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
cdccee71a2fd-8 | '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... | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
cdccee71a2fd-9 | '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... | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
cdccee71a2fd-10 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 25, 2023. | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
ba870688edaa-0 | .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... | https://python.langchain.com/en/latest/modules/chains/generic/serialization.html |
ba870688edaa-1 | "best_of": 1,
"request_timeout": null,
"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.js... | https://python.langchain.com/en/latest/modules/chains/generic/serialization.html |
ba870688edaa-2 | "top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0,
"n": 1,
"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",
"_ty... | https://python.langchain.com/en/latest/modules/chains/generic/serialization.html |
5c4b781d995d-0 | .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... | https://python.langchain.com/en/latest/modules/chains/generic/transformation.html |
2254c4f591bd-0 | .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 ... | https://python.langchain.com/en/latest/modules/chains/generic/router.html |
2254c4f591bd-1 | "description": "Good for answering math questions",
"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... | https://python.langchain.com/en/latest/modules/chains/generic/router.html |
2254c4f591bd-2 | physics: {'input': 'What is black body radiation?'}
> Finished chain.
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 radi... | https://python.langchain.com/en/latest/modules/chains/generic/router.html |
2254c4f591bd-3 | ("math", ["for questions about math"]),
]
router_chain = EmbeddingRouterChain.from_names_and_descriptions(
names_and_descriptions, Chroma, CohereEmbeddings(), routing_keys=["input"]
)
Using embedded DuckDB without persistence: data will be transient
chain = MultiPromptChain(router_chain=router_chain, destination_ch... | https://python.langchain.com/en/latest/modules/chains/generic/router.html |
f8fa9f8dcef0-0 | .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: ... | https://python.langchain.com/en/latest/modules/chains/generic/from_hub.html |
f8fa9f8dcef0-1 | query = "What did the president say about Ketanji Brown Jackson"
chain.run(query)
" 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 ... | https://python.langchain.com/en/latest/modules/chains/generic/from_hub.html |
8ef8fafbce58-0 | .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... | https://python.langchain.com/en/latest/modules/chains/generic/async_chain.html |
8ef8fafbce58-1 | await generate_concurrently()
elapsed = time.perf_counter() - s
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 Toothpas... | https://python.langchain.com/en/latest/modules/chains/generic/async_chain.html |
06ebc9d29cea-0 | .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... | https://python.langchain.com/en/latest/modules/chains/generic/custom_chain.html |
06ebc9d29cea-1 | # Whenever you call a language model, or another chain, you should pass
# 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()` ... | https://python.langchain.com/en/latest/modules/chains/generic/custom_chain.html |
06ebc9d29cea-2 | callbacks=run_manager.get_child() if run_manager else None
)
# If you want to log something about this run, you can do so by calling
# methods on the `run_manager`, as shown below. This will trigger any
# callbacks that are registered for that event.
if run_manager:
a... | https://python.langchain.com/en/latest/modules/chains/generic/custom_chain.html |
77814f707a59-0 | .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... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
77814f707a59-1 | synopsis_chain = LLMChain(llm=llm, prompt=prompt_template)
# 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}
R... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
77814f707a59-2 | The play follows the couple as they struggle to stay together and battle the forces that threaten to tear them apart. Despite the tragedy that awaits them, they remain devoted to one another and fight to keep their love alive. In the end, the couple must decide whether to take a chance on their future together or succu... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
77814f707a59-3 | The play's setting of the beach at sunset adds a touch of poignancy and romanticism to the story, while the mysterious figure serves to keep the audience enthralled. Overall, Tragedy at Sunset on the Beach is an engaging and thought-provoking play that is sure to leave audiences feeling inspired and hopeful.
Sequential... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
77814f707a59-4 | Play Synopsis:
{synopsis}
Review from a New York Times play critic of the above play:"""
prompt_template = PromptTemplate(input_variables=["synopsis"], template=template)
review_chain = LLMChain(llm=llm, prompt=prompt_template, output_key="review")
# This is the overall chain where we run these two chains in sequence.
... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
77814f707a59-5 | 'era': 'Victorian England',
'synopsis': "\n\nThe play follows the story of John, a young man from a wealthy Victorian family, who dreams of a better life for himself. He soon meets a beautiful young woman named Mary, who shares his dream. The two fall in love and decide to elope and start a new life together.\n\nOn th... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
77814f707a59-6 | '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... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
77814f707a59-7 | from langchain.memory import SimpleMemory
llm = OpenAI(temperature=.7)
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 tha... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
77814f707a59-8 | 'location': 'Theater in the Park',
'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 i... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
bedca74e0df8-0 | .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),... | https://python.langchain.com/en/latest/modules/chains/generic/llm_chain.html |
bedca74e0df8-1 | llm_chain.generate(input_list)
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={'... | https://python.langchain.com/en/latest/modules/chains/generic/llm_chain.html |
bedca74e0df8-2 | template = """List all the colors in a rainbow"""
prompt = PromptTemplate(template=template, input_variables=[], output_parser=output_parser)
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()
['R... | https://python.langchain.com/en/latest/modules/chains/generic/llm_chain.html |
6a141564fb02-0 | .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... | https://python.langchain.com/en/latest/modules/indexes/vectorstores.html |
efed1a8ce042-0 | .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... | https://python.langchain.com/en/latest/modules/indexes/retrievers.html |
18af21629ee2-0 | .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... | https://python.langchain.com/en/latest/modules/indexes/getting_started.html |
18af21629ee2-1 | Create a Retriever from that index
Create a question answering chain
Ask questions!
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 imp... | https://python.langchain.com/en/latest/modules/indexes/getting_started.html |
18af21629ee2-2 | index.query_with_sources(query)
{'question': 'What did the president say about Ketanji Brown Jackson',
'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... | https://python.langchain.com/en/latest/modules/indexes/getting_started.html |
18af21629ee2-3 | We will then select which embeddings we want to use.
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
We now create the vectorstore to use as the index.
from langchain.vectorstores import Chroma
db = Chroma.from_documents(texts, embeddings)
Running Chroma using direct local API.
Using D... | https://python.langchain.com/en/latest/modules/indexes/getting_started.html |
18af21629ee2-4 | )
Hopefully this highlights what is going on under the hood of VectorstoreIndexCreator. While we think it’s important to have a simple way to create indexes, we also think it’s important to understand what’s going on under the hood.
previous
Indexes
next
Document Loaders
Contents
One Line Index Creation
Walkthrough... | https://python.langchain.com/en/latest/modules/indexes/getting_started.html |
f26e17d523d6-0 | .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... | https://python.langchain.com/en/latest/modules/indexes/text_splitters.html |
f26e17d523d6-1 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 25, 2023. | https://python.langchain.com/en/latest/modules/indexes/text_splitters.html |
b2dc594370eb-0 | .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... | https://python.langchain.com/en/latest/modules/indexes/document_loaders.html |
b2dc594370eb-1 | iFixit
IMSDb
MediaWikiDump
Wikipedia
YouTube transcripts
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 par... | https://python.langchain.com/en/latest/modules/indexes/document_loaders.html |
7d2f4ceef9d6-0 | .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... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/self_query.html |
7d2f4ceef9d6-1 | from langchain.schema import Document
from langchain.embeddings.openai import OpenAIEmbeddings
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 b... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/self_query.html |
7d2f4ceef9d6-2 | )
Creating our self-querying retriever#
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 impor... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/self_query.html |
7d2f4ceef9d6-3 | Document(page_content='Toys come alive and have a blast doing so', metadata={'genre': 'animated', 'year': 1995.0}),
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': 2... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/self_query.html |
7d2f4ceef9d6-4 | [Document(page_content='A bunch of normal-sized women are supremely wholesome and some men pine after them', metadata={'director': 'Greta Gerwig', 'rating': 8.3, 'year': 2019.0})]
# This example specifies a composite filter
retriever.get_relevant_documents("What's a highly rated (above 8.5) science fiction film?")
quer... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/self_query.html |
7d2f4ceef9d6-5 | We can also use the self query retriever to specify k: the number of documents to fetch.
We can do this by passing enable_limit=True to the constructor.
retriever = SelfQueryRetriever.from_llm(
llm,
vectorstore,
document_content_description,
metadata_field_info,
enable_limit=True,
verbose=Tr... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/self_query.html |
f76886f4f8bb-0 | .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... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/vectorstore.html |
f76886f4f8bb-1 | 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... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/vectorstore.html |
72cd83b359ef-0 | .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... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/pinecone_hybrid_search.html |
72cd83b359ef-1 | pinecone.init(api_key=api_key, enviroment=env)
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 f... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/pinecone_hybrid_search.html |
72cd83b359ef-2 | Load Retriever#
We can now construct the retriever!
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"])
10... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/pinecone_hybrid_search.html |
af7e9e99ef28-0 | .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... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/vespa.html |
af7e9e99ef28-1 | retriever.get_relevant_documents("what is vespa?")
previous
VectorStore
next
Weaviate Hybrid Search
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 25, 2023. | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/vespa.html |
249da06d31bd-0 | .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... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/svm.html |
19d2e2fa930c-0 | .ipynb
.pdf
Zep Memory
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 Memory#
Retriever Example#
This notebook demonstrates how to search historical chat message histories using ... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/zep_memorystore.html |
19d2e2fa930c-1 | # Zep client in a notebook.
# !pip install nest_asyncio # Uncomment to install nest_asyncio
import nest_asyncio
nest_asyncio.apply()
Initialize the Zep Chat Message History Class and add a chat message history to the memory store#
NOTE: Unlike other Retrievers, the content returned by the Zep Retriever is session/user... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/zep_memorystore.html |
19d2e2fa930c-2 | {
"role": "ai",
"content": (
"Octavia Butler's contemporaries included Ursula K. Le Guin, Samuel R."
" Delany, and Joanna Russ."
),
},
{"role": "human", "content": "What awards did she win?"},
{
"role": "ai",
"content": (
"Octavia B... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/zep_memorystore.html |
19d2e2fa930c-3 | )
Use the Zep Retriever to vector search over the Zep memory#
Zep provides native vector search over historical conversation memory. Embedding happens automatically.
NOTE: Embedding of messages occurs asynchronously, so the first query may not return results. Subsequent queries will return results as the embeddings are... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/zep_memorystore.html |
19d2e2fa930c-4 | Document(page_content='Octavia Estelle Butler (June 22, 1947 – February 24, 2006) was an American science fiction author.', metadata={'score': 0.7545887969667749, 'uuid': 'b32c0644-2dcb-4c1d-a445-6622e7ba82e5', 'created_at': '2023-05-18T20:09:20.512044Z', 'role': 'ai', 'token_count': 31})]
previous
Wikipedia
next
Chain... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/zep_memorystore.html |
b92cbc8928c3-0 | .ipynb
.pdf
Wikipedia
Contents
Installation
Examples
Running retriever
Question Answering on facts
Wikipedia#
Wikipedia is a multilingual free online encyclopedia written and maintained by a community of volunteers, known as Wikipedians, through open collaboration and using a wiki-based editing system called MediaWik... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/wikipedia.html |
b92cbc8928c3-1 | 'summary': 'Hunter × Hunter (stylized as HUNTER×HUNTER and pronounced "hunter hunter") is a Japanese manga series written and illustrated by Yoshihiro Togashi. It has been serialized in Shueisha\'s shōnen manga magazine Weekly Shōnen Jump since March 1998, although the manga has frequently gone on extended hiatuses sin... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/wikipedia.html |
b92cbc8928c3-2 | Hunter was adapted into a 62-episode anime television series produced by Nippon Animation and directed by Kazuhiro Furuhashi, which ran on Fuji Television from October 1999 to March 2001. Three separate original video animations (OVAs) totaling 30 episodes were subsequently produced by Nippon Animation and released in ... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/wikipedia.html |
b92cbc8928c3-3 | Hunter has been a huge critical and financial success and has become one of the best-selling manga series of all time, having over 84 million copies in circulation by July 2022.\n\n'} | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/wikipedia.html |
b92cbc8928c3-4 | docs[0].page_content[:400] # a content of the Document
'Hunter × Hunter (stylized as HUNTER×HUNTER and pronounced "hunter hunter") is a Japanese manga series written and illustrated by Yoshihiro Togashi. It has been serialized in Shueisha\'s shōnen manga magazine Weekly Shōnen Jump since March 1998, although the mang... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/wikipedia.html |
b92cbc8928c3-5 | -> **Question**: What is Apify?
**Answer**: Apify is a platform that allows you to easily automate web scraping, data extraction and web automation. It provides a cloud-based infrastructure for running web crawlers and other automation tasks, as well as a web-based tool for building and managing your crawlers. Additio... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/wikipedia.html |
e6ce69e67e07-0 | .ipynb
.pdf
Self-querying with Chroma
Contents
Creating a Chroma vectorstore
Creating our self-querying retriever
Testing it out
Filter k
Self-querying with Chroma#
Chroma is a database for building AI applications with embeddings.
In the notebook we’ll demo the SelfQueryRetriever wrapped around a Chroma vector store... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chroma_self_query.html |
e6ce69e67e07-1 | Document(page_content="A bunch of normal-sized women are supremely wholesome and some men pine after them", metadata={"year": 2019, "director": "Greta Gerwig", "rating": 8.3}),
Document(page_content="Toys come alive and have a blast doing so", metadata={"year": 1995, "genre": "animated"}),
Document(page_content... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chroma_self_query.html |
e6ce69e67e07-2 | type="float"
),
]
document_content_description = "Brief summary of a movie"
llm = OpenAI(temperature=0)
retriever = SelfQueryRetriever.from_llm(llm, vectorstore, document_content_description, metadata_field_info, verbose=True)
Testing it out#
And now we can try actually using our retriever!
# This example only spec... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chroma_self_query.html |
e6ce69e67e07-3 | Document(page_content='Three men walk into the Zone, three men walk out of the Zone', metadata={'year': 1979, 'rating': 9.9, 'director': 'Andrei Tarkovsky', 'genre': 'science fiction'})]
# This example specifies a query and a filter
retriever.get_relevant_documents("Has Greta Gerwig directed any movies about women")
qu... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chroma_self_query.html |
e6ce69e67e07-4 | query='toys' filter=Operation(operator=<Operator.AND: 'and'>, arguments=[Comparison(comparator=<Comparator.GT: 'gt'>, attribute='year', value=1990), Comparison(comparator=<Comparator.LT: 'lt'>, attribute='year', value=2005), Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='genre', value='animated')])
[Document(p... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chroma_self_query.html |
e6ce69e67e07-5 | Document(page_content='Leo DiCaprio gets lost in a dream within a dream within a dream within a ...', metadata={'year': 2010, 'director': 'Christopher Nolan', 'rating': 8.2})]
previous
ChatGPT Plugin
next
Cohere Reranker
Contents
Creating a Chroma vectorstore
Creating our self-querying retriever
Testing it out
Filt... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/chroma_self_query.html |
f1fe848bb3d5-0 | .ipynb
.pdf
Azure Cognitive Search Retriever
Contents
Set up Azure Cognitive Search
Using the Azure Cognitive Search Retriever
Azure Cognitive Search Retriever#
This notebook shows how to use Azure Cognitive Search (ACS) within LangChain.
Set up Azure Cognitive Search#
To set up ACS, please follow the instrcutions he... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/azure-cognitive-search-retriever.html |
608adb10cda5-0 | .ipynb
.pdf
Self-querying with Weaviate
Contents
Creating a Weaviate vectorstore
Creating our self-querying retriever
Testing it out
Filter k
Self-querying with Weaviate#
Creating a Weaviate vectorstore#
First we’ll want to create a Weaviate VectorStore and seed it with some data. We’ve created a small demo set of do... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/weaviate_self_query.html |
608adb10cda5-1 | Document(page_content="Toys come alive and have a blast doing so", metadata={"year": 1995, "genre": "animated"}),
Document(page_content="Three men walk into the Zone, three men walk out of the Zone", metadata={"year": 1979, "rating": 9.9, "director": "Andrei Tarkovsky", "genre": "science fiction", "rating": 9.9})
]... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/weaviate_self_query.html |
608adb10cda5-2 | llm = OpenAI(temperature=0)
retriever = SelfQueryRetriever.from_llm(llm, vectorstore, document_content_description, metadata_field_info, verbose=True)
Testing it out#
And now we can try actually using our retriever!
# This example only specifies a relevant query
retriever.get_relevant_documents("What are some movies ab... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/weaviate_self_query.html |
608adb10cda5-3 | We can also use the self query retriever to specify k: the number of documents to fetch.
We can do this by passing enable_limit=True to the constructor.
retriever = SelfQueryRetriever.from_llm(
llm,
vectorstore,
document_content_description,
metadata_field_info,
enable_limit=True,
verbose=Tr... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/weaviate_self_query.html |
a4f63f24a79b-0 | .ipynb
.pdf
ElasticSearch BM25
Contents
Create New Retriever
Add texts (if necessary)
Use Retriever
ElasticSearch BM25#
Elasticsearch is a distributed, RESTful search and analytics engine. It provides a distributed, multitenant-capable full-text search engine with an HTTP web interface and schema-free JSON documents.... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/elastic_search_bm25.html |
a4f63f24a79b-1 | # import elasticsearch
# elasticsearch_url="http://localhost:9200"
# retriever = ElasticSearchBM25Retriever(elasticsearch.Elasticsearch(elasticsearch_url), "langchain-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", "worl... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/elastic_search_bm25.html |
2aea72d2611f-0 | .ipynb
.pdf
kNN
Contents
Create New Retriever with Texts
Use Retriever
kNN#
In statistics, the k-nearest neighbors algorithm (k-NN) is a non-parametric supervised learning method first developed by Evelyn Fix and Joseph Hodges in 1951, and later expanded by Thomas Cover. It is used for classification and regression.
... | https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/knn.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.