id
stringlengths
14
15
text
stringlengths
27
2.12k
source
stringlengths
49
118
177a8ccdd721-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKGet startedIntroductionInstallationQuickstartModulesModel I/​OData connectionDocument loadersDocument transformersText embedding modelsVector storesRetrieversMultiQueryRetrieverContextual compressionEnsemble RetrieverSelf-queryingTime-weighted vector store retrieverVector store-backed retrieverChainsMemoryAgentsCallbacksModulesGuidesEcosystemAdditional resourcesModulesData connectionRetrieversTime-weighted vector store retrieverTime-weighted vector store retrieverThis retriever uses a combination of semantic similarity and a time decay.The algorithm for scoring them is:semantic_similarity + (1.0 - decay_rate) ^ hours_passedNotably, hours_passed refers to the hours passed since the object in the retriever was last accessed, not since it was created. This means that frequently accessed objects remain "fresh."import faissfrom datetime import datetime, timedeltafrom langchain.docstore import InMemoryDocstorefrom langchain.embeddings import OpenAIEmbeddingsfrom langchain.retrievers import TimeWeightedVectorStoreRetrieverfrom langchain.schema import Documentfrom langchain.vectorstores import FAISSLow Decay Rate​A low decay rate (in this, to be extreme, we will set close to 0) means memories will be "remembered" for longer. A decay rate of 0 means memories never be forgotten, making this retriever equivalent to the vector lookup.# Define your embedding modelembeddings_model = OpenAIEmbeddings()# Initialize the vectorstore as emptyembedding_size = 1536index = faiss.IndexFlatL2(embedding_size)vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {})retriever = TimeWeightedVectorStoreRetriever(vectorstore=vectorstore,
https://python.langchain.com/docs/modules/data_connection/retrievers/time_weighted_vectorstore
177a8ccdd721-2
{})retriever = TimeWeightedVectorStoreRetriever(vectorstore=vectorstore, decay_rate=.0000000000000000000000001, k=1)yesterday = datetime.now() - timedelta(days=1)retriever.add_documents([Document(page_content="hello world", metadata={"last_accessed_at": yesterday})])retriever.add_documents([Document(page_content="hello foo")]) ['d7f85756-2371-4bdf-9140-052780a0f9b3']# "Hello World" is returned first because it is most salient, and the decay rate is close to 0., meaning it's still recent enoughretriever.get_relevant_documents("hello world") [Document(page_content='hello world', metadata={'last_accessed_at': datetime.datetime(2023, 5, 13, 21, 0, 27, 678341), 'created_at': datetime.datetime(2023, 5, 13, 21, 0, 27, 279596), 'buffer_idx': 0})]High Decay Rate​With a high decay rate (e.g., several 9's), the recency score quickly goes to 0! If you set this all the way to 1, recency is 0 for all objects, once again making this equivalent to a vector lookup.# Define your embedding modelembeddings_model = OpenAIEmbeddings()# Initialize the vectorstore as emptyembedding_size = 1536index = faiss.IndexFlatL2(embedding_size)vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {})retriever = TimeWeightedVectorStoreRetriever(vectorstore=vectorstore, decay_rate=.999, k=1)yesterday = datetime.now() -
https://python.langchain.com/docs/modules/data_connection/retrievers/time_weighted_vectorstore
177a8ccdd721-3
decay_rate=.999, k=1)yesterday = datetime.now() - timedelta(days=1)retriever.add_documents([Document(page_content="hello world", metadata={"last_accessed_at": yesterday})])retriever.add_documents([Document(page_content="hello foo")]) ['40011466-5bbe-4101-bfd1-e22e7f505de2']# "Hello Foo" is returned first because "hello world" is mostly forgottenretriever.get_relevant_documents("hello world") [Document(page_content='hello foo', metadata={'last_accessed_at': datetime.datetime(2023, 4, 16, 22, 9, 2, 494798), 'created_at': datetime.datetime(2023, 4, 16, 22, 9, 2, 178722), 'buffer_idx': 1})]Virtual Time​Using some utils in LangChain, you can mock out the time componentfrom langchain.utils import mock_nowimport datetime# Notice the last access time is that date timewith mock_now(datetime.datetime(2011, 2, 3, 10, 11)): print(retriever.get_relevant_documents("hello world")) [Document(page_content='hello world', metadata={'last_accessed_at': MockDateTime(2011, 2, 3, 10, 11), 'created_at': datetime.datetime(2023, 5, 13, 21, 0, 27, 279596), 'buffer_idx': 0})]PreviousWeaviate self-queryingNextVector store-backed retrieverCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/modules/data_connection/retrievers/time_weighted_vectorstore
23585a20860a-0
Self-querying | 🦜�🔗 Langchain
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/
23585a20860a-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKGet startedIntroductionInstallationQuickstartModulesModel I/​OData connectionDocument loadersDocument transformersText embedding modelsVector storesRetrieversMultiQueryRetrieverContextual compressionEnsemble RetrieverSelf-queryingChroma self-queryingDeepLake self-queryingSelf-querying with MyScaleSelf-querying with PineconeQdrant self-queryingWeaviate self-queryingTime-weighted vector store retrieverVector store-backed retrieverChainsMemoryAgentsCallbacksModulesGuidesEcosystemAdditional resourcesModulesData connectionRetrieversSelf-queryingSelf-queryingA self-querying retriever is one that, as the name suggests, has the ability to query itself. Specifically, given any natural language query, the retriever uses a query-constructing LLM chain to write a structured query and then applies that structured query to it's underlying VectorStore. This allows the retriever to not only use the user-input query for semantic similarity comparison with the contents of stored documented, but to also extract filters from the user query on the metadata of stored documents and to execute those filters.Get started​We'll use a Pinecone vector store in this example.First we'll want to create a Pinecone VectorStore and seed it with some data. We've created a small demo set of documents that contain summaries of movies.To use Pinecone, you to have pinecone package installed and you must have an API key and an Environment. Here are the installation instructions.NOTE: The self-query retriever requires you to have lark package installed.# !pip install lark pinecone-clientimport osimport pineconepinecone.init(api_key=os.environ["PINECONE_API_KEY"], environment=os.environ["PINECONE_ENV"])from langchain.schema import Documentfrom
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/
23585a20860a-2
environment=os.environ["PINECONE_ENV"])from langchain.schema import Documentfrom langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.vectorstores import Pineconeembeddings = OpenAIEmbeddings()# create new indexpinecone.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": ["action", "science fiction"]}), 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}), Document(page_content="A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea", metadata={"year": 2006, "director": "Satoshi Kon", "rating": 8.6}), 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="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", "thriller"], "rating": 9.9})]vectorstore = Pinecone.from_documents( docs, embeddings, index_name="langchain-self-retriever-demo")Creating our self-querying
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/
23585a20860a-3
docs, embeddings, index_name="langchain-self-retriever-demo")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 OpenAIfrom langchain.retrievers.self_query.base import SelfQueryRetrieverfrom langchain.chains.query_constructor.base import AttributeInfometadata_field_info=[ AttributeInfo( name="genre", description="The genre of the movie", type="string or list[string]", ), AttributeInfo( name="year", description="The year the movie was released", type="integer", ), AttributeInfo( name="director", description="The name of the movie director", type="string", ), AttributeInfo( name="rating", description="A 1-10 rating for the movie", 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 specifies a relevant queryretriever.get_relevant_documents("What are some movies about dinosaurs")
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/
23585a20860a-4
relevant queryretriever.get_relevant_documents("What are some movies about dinosaurs") query='dinosaur' filter=None [Document(page_content='A bunch of scientists bring back dinosaurs and mayhem breaks loose', metadata={'genre': ['action', 'science fiction'], 'rating': 7.7, 'year': 1993.0}), 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': 2006.0}), Document(page_content='Leo DiCaprio gets lost in a dream within a dream within a dream within a ...', metadata={'director': 'Christopher Nolan', 'rating': 8.2, 'year': 2010.0})]# This example only specifies a filterretriever.get_relevant_documents("I want to watch a movie rated higher than 8.5") query=' ' filter=Comparison(comparator=<Comparator.GT: 'gt'>, attribute='rating', value=8.5) [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='Three men walk into the Zone, three men walk out of the Zone', metadata={'director': 'Andrei Tarkovsky', 'genre': ['science fiction', 'thriller'], 'rating': 9.9, 'year':
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/
23585a20860a-5
['science fiction', 'thriller'], 'rating': 9.9, 'year': 1979.0})]# This example specifies a query and a filterretriever.get_relevant_documents("Has Greta Gerwig directed any movies about women") query='women' filter=Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='director', value='Greta Gerwig') [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 filterretriever.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', value=8.5)]) [Document(page_content='Three men walk into the Zone, three men walk out of the Zone', metadata={'director': 'Andrei Tarkovsky', 'genre': ['science fiction', 'thriller'], 'rating': 9.9, 'year': 1979.0})]# This example specifies a query and composite filterretriever.get_relevant_documents("What's a movie after 1990 but before 2005 that's all about toys, and preferably is animated") query='toys' filter=Operation(operator=<Operator.AND: 'and'>, arguments=[Comparison(comparator=<Comparator.GT: 'gt'>, attribute='year', value=1990.0), Comparison(comparator=<Comparator.LT: 'lt'>,
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/
23585a20860a-6
value=1990.0), Comparison(comparator=<Comparator.LT: 'lt'>, attribute='year', value=2005.0), Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='genre', value='animated')]) [Document(page_content='Toys come alive and have a blast doing so', metadata={'genre': 'animated', 'year': 1995.0})]Filter k​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=True)# This example only specifies a relevant queryretriever.get_relevant_documents("What are two movies about dinosaurs")PreviousEnsemble RetrieverNextChroma self-queryingCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/
ad4dac789bdd-0
Chroma self-querying | 🦜�🔗 Langchain
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/chroma_self_query
ad4dac789bdd-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKGet startedIntroductionInstallationQuickstartModulesModel I/​OData connectionDocument loadersDocument transformersText embedding modelsVector storesRetrieversMultiQueryRetrieverContextual compressionEnsemble RetrieverSelf-queryingChroma self-queryingDeepLake self-queryingSelf-querying with MyScaleSelf-querying with PineconeQdrant self-queryingWeaviate self-queryingTime-weighted vector store retrieverVector store-backed retrieverChainsMemoryAgentsCallbacksModulesGuidesEcosystemAdditional resourcesModulesData connectionRetrieversSelf-queryingChroma self-queryingOn this pageChroma self-queryingChroma is a database for building AI applications with embeddings.In the notebook we'll demo the SelfQueryRetriever wrapped around a Chroma vector store. Creating a Chroma vectorstore​First we'll want to create a Chroma VectorStore and seed it with some data. We've created a small demo set of documents that contain summaries of movies.NOTE: The self-query retriever requires you to have lark installed (pip install lark). We also need the chromadb package.#!pip install lark#!pip install chromadbWe want to use OpenAIEmbeddings so we have to get the OpenAI API Key.import osimport getpassos.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:") OpenAI API Key: ········from langchain.schema import Documentfrom langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.vectorstores import Chromaembeddings = OpenAIEmbeddings()docs = [ Document( page_content="A bunch of scientists bring back dinosaurs and
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/chroma_self_query
ad4dac789bdd-2
Document( page_content="A bunch of scientists bring back dinosaurs and mayhem breaks loose", metadata={"year": 1993, "rating": 7.7, "genre": "science fiction"}, ), 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}, ), Document( page_content="A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea", metadata={"year": 2006, "director": "Satoshi Kon", "rating": 8.6}, ), 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="Three men walk into the Zone, three men walk out of the Zone", metadata={ "year": 1979, "rating": 9.9,
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/chroma_self_query
ad4dac789bdd-3
"rating": 9.9, "director": "Andrei Tarkovsky", "genre": "science fiction", "rating": 9.9, }, ),]vectorstore = Chroma.from_documents(docs, embeddings) Using embedded DuckDB without persistence: data will be transientCreating 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 OpenAIfrom langchain.retrievers.self_query.base import SelfQueryRetrieverfrom langchain.chains.query_constructor.base import AttributeInfometadata_field_info = [ AttributeInfo( name="genre", description="The genre of the movie", type="string or list[string]", ), AttributeInfo( name="year", description="The year the movie was released", type="integer", ), AttributeInfo( name="director", description="The name of the movie director", type="string", ), AttributeInfo( name="rating", description="A 1-10 rating for the movie", type="float" ),]document_content_description = "Brief summary of a movie"llm =
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/chroma_self_query
ad4dac789bdd-4
),]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 specifies a relevant queryretriever.get_relevant_documents("What are some movies about dinosaurs") query='dinosaur' filter=None [Document(page_content='A bunch of scientists bring back dinosaurs and mayhem breaks loose', metadata={'year': 1993, 'rating': 7.7, 'genre': 'science fiction'}), Document(page_content='Toys come alive and have a blast doing so', metadata={'year': 1995, 'genre': 'animated'}), Document(page_content='A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea', metadata={'year': 2006, 'director': 'Satoshi Kon', 'rating': 8.6}), 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})]# This example only specifies a filterretriever.get_relevant_documents("I want to watch a movie rated higher than 8.5") query=' ' filter=Comparison(comparator=<Comparator.GT: 'gt'>, attribute='rating', value=8.5) [Document(page_content='A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea', metadata={'year': 2006, 'director': 'Satoshi
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/chroma_self_query
ad4dac789bdd-5
reused the idea', metadata={'year': 2006, 'director': 'Satoshi Kon', 'rating': 8.6}), 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 filterretriever.get_relevant_documents("Has Greta Gerwig directed any movies about women") query='women' filter=Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='director', value='Greta Gerwig') [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})]# This example specifies a composite filterretriever.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', value=8.5)]) [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 composite filterretriever.get_relevant_documents( "What's a movie after 1990 but before 2005 that's all about toys, and preferably is animated")
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/chroma_self_query
ad4dac789bdd-6
1990 but before 2005 that's all about toys, and preferably is animated") 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(page_content='Toys come alive and have a blast doing so', metadata={'year': 1995, 'genre': 'animated'})]Filter k​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=True,)# This example only specifies a relevant queryretriever.get_relevant_documents("what are two movies about dinosaurs") query='dinosaur' filter=None [Document(page_content='A bunch of scientists bring back dinosaurs and mayhem breaks loose', metadata={'year': 1993, 'rating': 7.7, 'genre': 'science fiction'}), Document(page_content='Toys come alive and have a blast doing so', metadata={'year': 1995, 'genre': 'animated'}), Document(page_content='A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea', metadata={'year': 2006, 'director': 'Satoshi Kon', 'rating': 8.6}),
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/chroma_self_query
ad4dac789bdd-7
'Satoshi Kon', 'rating': 8.6}), 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})]PreviousSelf-queryingNextDeepLake self-queryingCreating a Chroma vectorstoreCreating our self-querying retrieverTesting it outFilter kCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/chroma_self_query
f9f160ffcadb-0
Self-querying with MyScale | 🦜�🔗 Langchain
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/myscale_self_query
f9f160ffcadb-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKGet startedIntroductionInstallationQuickstartModulesModel I/​OData connectionDocument loadersDocument transformersText embedding modelsVector storesRetrieversMultiQueryRetrieverContextual compressionEnsemble RetrieverSelf-queryingChroma self-queryingDeepLake self-queryingSelf-querying with MyScaleSelf-querying with PineconeQdrant self-queryingWeaviate self-queryingTime-weighted vector store retrieverVector store-backed retrieverChainsMemoryAgentsCallbacksModulesGuidesEcosystemAdditional resourcesModulesData connectionRetrieversSelf-queryingSelf-querying with MyScaleOn this pageSelf-querying with MyScaleMyScale is an integrated vector database. You can access your database in SQL and also from here, LangChain. MyScale can make a use of various data types and functions for filters. It will boost up your LLM app no matter if you are scaling up your data or expand your system to broader application.In the notebook we'll demo the SelfQueryRetriever wrapped around a MyScale vector store with some extra piece we contributed to LangChain. In short, it can be concluded into 4 points:Add contain comparator to match list of any if there is more than one element matchedAdd timestamp data type for datetime match (ISO-format, or YYYY-MM-DD)Add like comparator for string pattern searchAdd arbitrary function capabilityCreating a MyScale vectorstore​MyScale has already been integrated to LangChain for a while. So you can follow this notebook to create your own vectorstore for a self-query retriever.NOTE: All self-query retrievers requires you to have lark installed (pip install lark). We use lark for grammar definition. Before you proceed to the next step, we also want to remind you that clickhouse-connect is also needed to
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/myscale_self_query
f9f160ffcadb-2
proceed to the next step, we also want to remind you that clickhouse-connect is also needed to interact with your MyScale backend.pip install lark clickhouse-connectIn this tutorial we follow other example's setting and use OpenAIEmbeddings. Remember to get a OpenAI API Key for valid accesss to LLMs.import osimport getpassos.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")os.environ["MYSCALE_HOST"] = getpass.getpass("MyScale URL:")os.environ["MYSCALE_PORT"] = getpass.getpass("MyScale Port:")os.environ["MYSCALE_USERNAME"] = getpass.getpass("MyScale Username:")os.environ["MYSCALE_PASSWORD"] = getpass.getpass("MyScale Password:")from langchain.schema import Documentfrom langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.vectorstores import MyScaleembeddings = OpenAIEmbeddings()Create some sample data​As you can see, the data we created has some difference to other self-query retrievers. We replaced keyword year to date which gives you a finer control on timestamps. We also altered the type of keyword gerne to list of strings, where LLM can use a new contain comparator to construct filters. We also provides comparator like and arbitrary function support to filters, which will be introduced in next few cells.Now let's look at the data first.docs = [ Document( page_content="A bunch of scientists bring back dinosaurs and mayhem breaks loose", metadata={"date": "1993-07-02", "rating": 7.7, "genre": ["science fiction"]}, ), Document( page_content="Leo DiCaprio gets lost in a dream within a dream within a dream within a ...",
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/myscale_self_query
f9f160ffcadb-3
in a dream within a dream within a dream within a ...", metadata={"date": "2010-12-30", "director": "Christopher Nolan", "rating": 8.2}, ), Document( page_content="A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea", metadata={"date": "2006-04-23", "director": "Satoshi Kon", "rating": 8.6}, ), Document( page_content="A bunch of normal-sized women are supremely wholesome and some men pine after them", metadata={"date": "2019-08-22", "director": "Greta Gerwig", "rating": 8.3}, ), Document( page_content="Toys come alive and have a blast doing so", metadata={"date": "1995-02-11", "genre": ["animated"]}, ), Document( page_content="Three men walk into the Zone, three men walk out of the Zone", metadata={ "date": "1979-09-10", "rating": 9.9, "director": "Andrei Tarkovsky", "genre": ["science fiction", "adventure"], "rating": 9.9,
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/myscale_self_query
f9f160ffcadb-4
"rating": 9.9, }, ),]vectorstore = MyScale.from_documents( docs, embeddings,)Creating our self-querying retriever​Just like other retrievers... Simple and nice.from langchain.llms import OpenAIfrom langchain.retrievers.self_query.base import SelfQueryRetrieverfrom langchain.chains.query_constructor.base import AttributeInfometadata_field_info = [ AttributeInfo( name="genre", description="The genres of the movie", type="list[string]", ), # If you want to include length of a list, just define it as a new column # This will teach the LLM to use it as a column when constructing filter. AttributeInfo( name="length(genre)", description="The length of genres of the movie", type="integer", ), # Now you can define a column as timestamp. By simply set the type to timestamp. AttributeInfo( name="date", description="The date the movie was released", type="timestamp", ), AttributeInfo( name="director", description="The name of the movie director", type="string", ), AttributeInfo( name="rating", description="A 1-10 rating for the movie", type="float"
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/myscale_self_query
f9f160ffcadb-5
description="A 1-10 rating for the movie", 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 with self-query retriever's existing functionalities​And now we can try actually using our retriever!# This example only specifies a relevant queryretriever.get_relevant_documents("What are some movies about dinosaurs")# This example only specifies a filterretriever.get_relevant_documents("I want to watch a movie rated higher than 8.5")# This example specifies a query and a filterretriever.get_relevant_documents("Has Greta Gerwig directed any movies about women")# This example specifies a composite filterretriever.get_relevant_documents( "What's a highly rated (above 8.5) science fiction film?")# This example specifies a query and composite filterretriever.get_relevant_documents( "What's a movie after 1990 but before 2005 that's all about toys, and preferably is animated")Wait a second... What else?Self-query retriever with MyScale can do more! Let's find out.# You can use length(genres) to do anything you wantretriever.get_relevant_documents("What's a movie that have more than 1 genres?")# Fine-grained datetime? You got it already.retriever.get_relevant_documents("What's a movie that release after feb 1995?")# Don't know what your exact filter should be? Use string pattern match!retriever.get_relevant_documents("What's a movie whose name is like Andrei?")# Contain works for lists: so you can match a list with
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/myscale_self_query
f9f160ffcadb-6
is like Andrei?")# Contain works for lists: so you can match a list with contain comparator!retriever.get_relevant_documents( "What's a movie who has genres science fiction and adventure?")Filter k​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=True,)# This example only specifies a relevant queryretriever.get_relevant_documents("what are two movies about dinosaurs")PreviousDeepLake self-queryingNextSelf-querying with PineconeCreating a MyScale vectorstoreCreate some sample dataCreating our self-querying retrieverTesting it out with self-query retriever's existing functionalitiesFilter kCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/myscale_self_query
34a815b81fe6-0
Qdrant self-querying | 🦜�🔗 Langchain
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/qdrant_self_query
34a815b81fe6-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKGet startedIntroductionInstallationQuickstartModulesModel I/​OData connectionDocument loadersDocument transformersText embedding modelsVector storesRetrieversMultiQueryRetrieverContextual compressionEnsemble RetrieverSelf-queryingChroma self-queryingDeepLake self-queryingSelf-querying with MyScaleSelf-querying with PineconeQdrant self-queryingWeaviate self-queryingTime-weighted vector store retrieverVector store-backed retrieverChainsMemoryAgentsCallbacksModulesGuidesEcosystemAdditional resourcesModulesData connectionRetrieversSelf-queryingQdrant self-queryingOn this pageQdrant self-queryingQdrant (read: quadrant ) is a vector similarity search engine. It provides a production-ready service with a convenient API to store, search, and manage points - vectors with an additional payload. Qdrant is tailored to extended filtering support. It makes it useful In the notebook we'll demo the SelfQueryRetriever wrapped around a Qdrant vector store. Creating a Qdrant vectorstore​First we'll want to create a Qdrant VectorStore and seed it with some data. We've created a small demo set of documents that contain summaries of movies.NOTE: The self-query retriever requires you to have lark installed (pip install lark). We also need the qdrant-client package.#!pip install lark qdrant-clientWe want to use OpenAIEmbeddings so we have to get the OpenAI API Key.# import os# import getpass# os.environ['OPENAI_API_KEY'] = getpass.getpass('OpenAI API Key:')from langchain.schema import Documentfrom langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.vectorstores import Qdrantembeddings =
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/qdrant_self_query
34a815b81fe6-2
import OpenAIEmbeddingsfrom langchain.vectorstores import Qdrantembeddings = OpenAIEmbeddings()docs = [ Document( page_content="A bunch of scientists bring back dinosaurs and mayhem breaks loose", metadata={"year": 1993, "rating": 7.7, "genre": "science fiction"}, ), 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}, ), Document( page_content="A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea", metadata={"year": 2006, "director": "Satoshi Kon", "rating": 8.6}, ), 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="Three men walk into the Zone, three men walk out of the Zone", metadata={ "year":
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/qdrant_self_query
34a815b81fe6-3
metadata={ "year": 1979, "rating": 9.9, "director": "Andrei Tarkovsky", "genre": "science fiction", }, ),]vectorstore = Qdrant.from_documents( docs, embeddings, location=":memory:", # Local mode with in-memory storage only collection_name="my_documents",)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 OpenAIfrom langchain.retrievers.self_query.base import SelfQueryRetrieverfrom langchain.chains.query_constructor.base import AttributeInfometadata_field_info = [ AttributeInfo( name="genre", description="The genre of the movie", type="string or list[string]", ), AttributeInfo( name="year", description="The year the movie was released", type="integer", ), AttributeInfo( name="director", description="The name of the movie director", type="string", ), AttributeInfo( name="rating", description="A 1-10 rating for the
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/qdrant_self_query
34a815b81fe6-4
name="rating", description="A 1-10 rating for the movie", 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 specifies a relevant queryretriever.get_relevant_documents("What are some movies about dinosaurs") query='dinosaur' filter=None limit=None [Document(page_content='A bunch of scientists bring back dinosaurs and mayhem breaks loose', metadata={'year': 1993, 'rating': 7.7, 'genre': 'science fiction'}), 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'}), Document(page_content='A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea', metadata={'year': 2006, 'director': 'Satoshi Kon', 'rating': 8.6})]# This example only specifies a filterretriever.get_relevant_documents("I want to watch a movie rated higher than 8.5") query=' ' filter=Comparison(comparator=<Comparator.GT: 'gt'>, attribute='rating', value=8.5) limit=None [Document(page_content='Three
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/qdrant_self_query
34a815b81fe6-5
value=8.5) limit=None [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'}), Document(page_content='A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea', metadata={'year': 2006, 'director': 'Satoshi Kon', 'rating': 8.6})]# This example specifies a query and a filterretriever.get_relevant_documents("Has Greta Gerwig directed any movies about women") query='women' filter=Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='director', value='Greta Gerwig') limit=None [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})]# This example specifies a composite filterretriever.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.GT: 'gt'>, attribute='rating', value=8.5), Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='genre', value='science fiction')]) limit=None [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
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/qdrant_self_query
34a815b81fe6-6
Tarkovsky', 'genre': 'science fiction'})]# This example specifies a query and composite filterretriever.get_relevant_documents( "What's a movie after 1990 but before 2005 that's all about toys, and preferably is animated") 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')]) limit=None [Document(page_content='Toys come alive and have a blast doing so', metadata={'year': 1995, 'genre': 'animated'})]Filter k​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=True,)# This example only specifies a relevant queryretriever.get_relevant_documents("what are two movies about dinosaurs") query='dinosaur' filter=None limit=2 [Document(page_content='A bunch of scientists bring back dinosaurs and mayhem breaks loose', metadata={'year': 1993, 'rating': 7.7, 'genre': 'science fiction'}), Document(page_content='Toys come alive and have a blast doing so', metadata={'year': 1995, 'genre': 'animated'})]PreviousSelf-querying with PineconeNextWeaviate self-queryingCreating a
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/qdrant_self_query
34a815b81fe6-7
'animated'})]PreviousSelf-querying with PineconeNextWeaviate self-queryingCreating a Qdrant vectorstoreCreating our self-querying retrieverTesting it outFilter kCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/qdrant_self_query
3b08d28ed2a9-0
Self-querying with Pinecone | 🦜�🔗 Langchain
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/pinecone
3b08d28ed2a9-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKGet startedIntroductionInstallationQuickstartModulesModel I/​OData connectionDocument loadersDocument transformersText embedding modelsVector storesRetrieversMultiQueryRetrieverContextual compressionEnsemble RetrieverSelf-queryingChroma self-queryingDeepLake self-queryingSelf-querying with MyScaleSelf-querying with PineconeQdrant self-queryingWeaviate self-queryingTime-weighted vector store retrieverVector store-backed retrieverChainsMemoryAgentsCallbacksModulesGuidesEcosystemAdditional resourcesModulesData connectionRetrieversSelf-queryingSelf-querying with PineconeOn this pageSelf-querying with PineconeIn the walkthrough we'll demo the SelfQueryRetriever with a Pinecone vector store.Creating a Pinecone index​First we'll want to create a Pinecone VectorStore and seed it with some data. We've created a small demo set of documents that contain summaries of movies.To use Pinecone, you have to have pinecone package installed and you must have an API key and an Environment. Here are the installation instructions.NOTE: The self-query retriever requires you to have lark package installed.# !pip install lark#!pip install pinecone-clientimport osimport pineconepinecone.init( api_key=os.environ["PINECONE_API_KEY"], environment=os.environ["PINECONE_ENV"]) /Users/harrisonchase/.pyenv/versions/3.9.1/envs/langchain/lib/python3.9/site-packages/pinecone/index.py:4: TqdmExperimentalWarning: Using `tqdm.autonotebook.tqdm` in notebook mode. Use `tqdm.tqdm` instead to force console mode (e.g. in jupyter console)
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/pinecone
3b08d28ed2a9-2
instead to force console mode (e.g. in jupyter console) from tqdm.autonotebook import tqdmfrom langchain.schema import Documentfrom langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.vectorstores import Pineconeembeddings = OpenAIEmbeddings()# create new indexpinecone.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": ["action", "science fiction"]}, ), 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}, ), Document( page_content="A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea", metadata={"year": 2006, "director": "Satoshi Kon", "rating": 8.6}, ), 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":
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/pinecone
3b08d28ed2a9-3
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", "thriller"], "rating": 9.9, }, ),]vectorstore = Pinecone.from_documents( docs, embeddings, index_name="langchain-self-retriever-demo")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 OpenAIfrom langchain.retrievers.self_query.base import SelfQueryRetrieverfrom langchain.chains.query_constructor.base import AttributeInfometadata_field_info = [ AttributeInfo( name="genre", description="The genre of the movie", type="string or list[string]", ), AttributeInfo( name="year", description="The year the movie was released", type="integer", ),
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/pinecone
3b08d28ed2a9-4
released", type="integer", ), AttributeInfo( name="director", description="The name of the movie director", type="string", ), AttributeInfo( name="rating", description="A 1-10 rating for the movie", 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 specifies a relevant queryretriever.get_relevant_documents("What are some movies about dinosaurs") query='dinosaur' filter=None [Document(page_content='A bunch of scientists bring back dinosaurs and mayhem breaks loose', metadata={'genre': ['action', 'science fiction'], 'rating': 7.7, 'year': 1993.0}), 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': 2006.0}), Document(page_content='Leo DiCaprio gets lost in a dream within a dream within a dream within a ...', metadata={'director': 'Christopher Nolan', 'rating': 8.2, 'year':
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/pinecone
3b08d28ed2a9-5
metadata={'director': 'Christopher Nolan', 'rating': 8.2, 'year': 2010.0})]# This example only specifies a filterretriever.get_relevant_documents("I want to watch a movie rated higher than 8.5") query=' ' filter=Comparison(comparator=<Comparator.GT: 'gt'>, attribute='rating', value=8.5) [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='Three men walk into the Zone, three men walk out of the Zone', metadata={'director': 'Andrei Tarkovsky', 'genre': ['science fiction', 'thriller'], 'rating': 9.9, 'year': 1979.0})]# This example specifies a query and a filterretriever.get_relevant_documents("Has Greta Gerwig directed any movies about women") query='women' filter=Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='director', value='Greta Gerwig') [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 filterretriever.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'),
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/pinecone
3b08d28ed2a9-6
'eq'>, attribute='genre', value='science fiction'), Comparison(comparator=<Comparator.GT: 'gt'>, attribute='rating', value=8.5)]) [Document(page_content='Three men walk into the Zone, three men walk out of the Zone', metadata={'director': 'Andrei Tarkovsky', 'genre': ['science fiction', 'thriller'], 'rating': 9.9, 'year': 1979.0})]# This example specifies a query and composite filterretriever.get_relevant_documents( "What's a movie after 1990 but before 2005 that's all about toys, and preferably is animated") query='toys' filter=Operation(operator=<Operator.AND: 'and'>, arguments=[Comparison(comparator=<Comparator.GT: 'gt'>, attribute='year', value=1990.0), Comparison(comparator=<Comparator.LT: 'lt'>, attribute='year', value=2005.0), Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='genre', value='animated')]) [Document(page_content='Toys come alive and have a blast doing so', metadata={'genre': 'animated', 'year': 1995.0})]Filter k​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=True,)# This example only specifies a relevant queryretriever.get_relevant_documents("What are two movies about dinosaurs")PreviousSelf-querying with MyScaleNextQdrant self-queryingCreating a Pinecone
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/pinecone
3b08d28ed2a9-7
dinosaurs")PreviousSelf-querying with MyScaleNextQdrant self-queryingCreating a Pinecone indexCreating our self-querying retrieverTesting it outFilter kCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/pinecone
116f660c1da9-0
Weaviate self-querying | 🦜�🔗 Langchain
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/weaviate_self_query
116f660c1da9-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKGet startedIntroductionInstallationQuickstartModulesModel I/​OData connectionDocument loadersDocument transformersText embedding modelsVector storesRetrieversMultiQueryRetrieverContextual compressionEnsemble RetrieverSelf-queryingChroma self-queryingDeepLake self-queryingSelf-querying with MyScaleSelf-querying with PineconeQdrant self-queryingWeaviate self-queryingTime-weighted vector store retrieverVector store-backed retrieverChainsMemoryAgentsCallbacksModulesGuidesEcosystemAdditional resourcesModulesData connectionRetrieversSelf-queryingWeaviate self-queryingOn this pageWeaviate self-queryingCreating 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 documents that contain summaries of movies.NOTE: The self-query retriever requires you to have lark installed (pip install lark). We also need the weaviate-client package.#!pip install lark weaviate-clientfrom langchain.schema import Documentfrom langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.vectorstores import Weaviateimport osembeddings = OpenAIEmbeddings()docs = [ Document( page_content="A bunch of scientists bring back dinosaurs and mayhem breaks loose", metadata={"year": 1993, "rating": 7.7, "genre": "science fiction"}, ), Document( page_content="Leo DiCaprio gets lost in a dream within a dream within a dream within a ...", metadata={"year": 2010,
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/weaviate_self_query
116f660c1da9-2
dream within a ...", metadata={"year": 2010, "director": "Christopher Nolan", "rating": 8.2}, ), Document( page_content="A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea", metadata={"year": 2006, "director": "Satoshi Kon", "rating": 8.6}, ), 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="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, }, ),]vectorstore = Weaviate.from_documents( docs, embeddings,
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/weaviate_self_query
116f660c1da9-3
),]vectorstore = Weaviate.from_documents( docs, embeddings, weaviate_url="http://127.0.0.1:8080")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 OpenAIfrom langchain.retrievers.self_query.base import SelfQueryRetrieverfrom langchain.chains.query_constructor.base import AttributeInfometadata_field_info = [ AttributeInfo( name="genre", description="The genre of the movie", type="string or list[string]", ), AttributeInfo( name="year", description="The year the movie was released", type="integer", ), AttributeInfo( name="director", description="The name of the movie director", type="string", ), AttributeInfo( name="rating", description="A 1-10 rating for the movie", 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 specifies a relevant queryretriever.get_relevant_documents("What are some movies
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/weaviate_self_query
116f660c1da9-4
This example only specifies a relevant queryretriever.get_relevant_documents("What are some movies about dinosaurs") query='dinosaur' filter=None limit=None [Document(page_content='A bunch of scientists bring back dinosaurs and mayhem breaks loose', metadata={'genre': 'science fiction', 'rating': 7.7, 'year': 1993}), Document(page_content='Toys come alive and have a blast doing so', metadata={'genre': 'animated', 'rating': None, 'year': 1995}), Document(page_content='Three men walk into the Zone, three men walk out of the Zone', metadata={'genre': 'science fiction', 'rating': 9.9, 'year': 1979}), Document(page_content='A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea', metadata={'genre': None, 'rating': 8.6, 'year': 2006})]# This example specifies a query and a filterretriever.get_relevant_documents("Has Greta Gerwig directed any movies about women") query='women' filter=Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='director', value='Greta Gerwig') limit=None [Document(page_content='A bunch of normal-sized women are supremely wholesome and some men pine after them', metadata={'genre': None, 'rating': 8.3, 'year': 2019})]Filter k​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,
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/weaviate_self_query
116f660c1da9-5
vectorstore, document_content_description, metadata_field_info, enable_limit=True, verbose=True,)# This example only specifies a relevant queryretriever.get_relevant_documents("what are two movies about dinosaurs") query='dinosaur' filter=None limit=2 [Document(page_content='A bunch of scientists bring back dinosaurs and mayhem breaks loose', metadata={'genre': 'science fiction', 'rating': 7.7, 'year': 1993}), Document(page_content='Toys come alive and have a blast doing so', metadata={'genre': 'animated', 'rating': None, 'year': 1995})]PreviousQdrant self-queryingNextTime-weighted vector store retrieverCreating a Weaviate vectorstoreCreating our self-querying retrieverTesting it outFilter kCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/weaviate_self_query
d007048864f9-0
DeepLake self-querying | 🦜�🔗 Langchain
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/deeplake_self_query
d007048864f9-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKGet startedIntroductionInstallationQuickstartModulesModel I/​OData connectionDocument loadersDocument transformersText embedding modelsVector storesRetrieversMultiQueryRetrieverContextual compressionEnsemble RetrieverSelf-queryingChroma self-queryingDeepLake self-queryingSelf-querying with MyScaleSelf-querying with PineconeQdrant self-queryingWeaviate self-queryingTime-weighted vector store retrieverVector store-backed retrieverChainsMemoryAgentsCallbacksModulesGuidesEcosystemAdditional resourcesModulesData connectionRetrieversSelf-queryingDeepLake self-queryingOn this pageDeepLake self-queryingDeepLake is a multimodal database for building AI applications.In the notebook we'll demo the SelfQueryRetriever wrapped around a DeepLake vector store. Creating a DeepLake vectorstore​First we'll want to create a DeepLake VectorStore and seed it with some data. We've created a small demo set of documents that contain summaries of movies.NOTE: The self-query retriever requires you to have lark installed (pip install lark). We also need the deeplake package.#!pip install lark#!pip install 'deeplake[enterprise]'We want to use OpenAIEmbeddings so we have to get the OpenAI API Key.import osimport getpassos.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")from langchain.schema import Documentfrom langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.vectorstores import DeepLakeembeddings = OpenAIEmbeddings()docs = [ Document( page_content="A bunch of scientists bring back dinosaurs and mayhem breaks loose", metadata={"year":
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/deeplake_self_query
d007048864f9-2
bring back dinosaurs and mayhem breaks loose", metadata={"year": 1993, "rating": 7.7, "genre": "science fiction"}, ), 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}, ), Document( page_content="A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea", metadata={"year": 2006, "director": "Satoshi Kon", "rating": 8.6}, ), 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="Three men walk into the Zone, three men walk out of the Zone", metadata={ "year": 1979, "rating": 9.9, "director": "Andrei Tarkovsky",
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/deeplake_self_query
d007048864f9-3
"director": "Andrei Tarkovsky", "genre": "science fiction", "rating": 9.9, }, ),]username_or_org = "<USER_NAME_OR_ORG>"vectorstore = DeepLake.from_documents( docs, embeddings, dataset_path=f"hub://{username_or_org}/self_queery") Your Deep Lake dataset has been successfully created! - Dataset(path='hub://adilkhan/self_queery', tensors=['embedding', 'id', 'metadata', 'text']) tensor htype shape dtype compression ------- ------- ------- ------- ------- embedding embedding (6, 1536) float32 None id text (6, 1) str None metadata json (6, 1) str None text text (6, 1) str None 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
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/deeplake_self_query
d007048864f9-4
metadata fields that our documents support and a short description of the document contents.from langchain.llms import OpenAIfrom langchain.retrievers.self_query.base import SelfQueryRetrieverfrom langchain.chains.query_constructor.base import AttributeInfometadata_field_info = [ AttributeInfo( name="genre", description="The genre of the movie", type="string or list[string]", ), AttributeInfo( name="year", description="The year the movie was released", type="integer", ), AttributeInfo( name="director", description="The name of the movie director", type="string", ), AttributeInfo( name="rating", description="A 1-10 rating for the movie", 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 specifies a relevant queryretriever.get_relevant_documents("What are some movies about dinosaurs") /Users/adilkhansarsen/Documents/work/LangChain/langchain/langchain/chains/llm.py:275: UserWarning: The predict_and_parse method is deprecated, instead pass an output parser directly to LLMChain. warnings.warn( query='dinosaur'
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/deeplake_self_query
d007048864f9-5
LLMChain. warnings.warn( query='dinosaur' filter=None limit=None [Document(page_content='A bunch of scientists bring back dinosaurs and mayhem breaks loose', metadata={'year': 1993, 'rating': 7.7, 'genre': 'science fiction'}), 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'}), Document(page_content='A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea', metadata={'year': 2006, 'director': 'Satoshi Kon', 'rating': 8.6})]# This example only specifies a filterretriever.get_relevant_documents("I want to watch a movie rated higher than 8.5") query=' ' filter=Comparison(comparator=<Comparator.GT: 'gt'>, attribute='rating', value=8.5) limit=None [Document(page_content='A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea', metadata={'year': 2006, 'director': 'Satoshi Kon', 'rating': 8.6}), 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
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/deeplake_self_query
d007048864f9-6
Tarkovsky', 'genre': 'science fiction'})]# This example specifies a query and a filterretriever.get_relevant_documents("Has Greta Gerwig directed any movies about women") query='women' filter=Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='director', value='Greta Gerwig') limit=None [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})]# This example specifies a composite filterretriever.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.GTE: 'gte'>, attribute='rating', value=8.5), Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='genre', value='science fiction')]) limit=None [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 composite filterretriever.get_relevant_documents( "What's a movie after 1990 but before 2005 that's all about toys, and preferably is animated") 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),
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/deeplake_self_query
d007048864f9-7
'lt'>, attribute='year', value=2005), Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='genre', value='animated')]) limit=None [Document(page_content='Toys come alive and have a blast doing so', metadata={'year': 1995, 'genre': 'animated'})]Filter k​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=True,)# This example only specifies a relevant queryretriever.get_relevant_documents("what are two movies about dinosaurs") query='dinosaur' filter=None limit=2 [Document(page_content='A bunch of scientists bring back dinosaurs and mayhem breaks loose', metadata={'year': 1993, 'rating': 7.7, 'genre': 'science fiction'}), Document(page_content='Toys come alive and have a blast doing so', metadata={'year': 1995, 'genre': 'animated'})]PreviousChroma self-queryingNextSelf-querying with MyScaleCreating a DeepLake vectorstoreCreating our self-querying retrieverTesting it outFilter kCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/modules/data_connection/retrievers/self_query/deeplake_self_query
72f8b05fa9fa-0
Text embedding models | 🦜�🔗 Langchain
https://python.langchain.com/docs/modules/data_connection/text_embedding/
72f8b05fa9fa-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKGet startedIntroductionInstallationQuickstartModulesModel I/​OData connectionDocument loadersDocument transformersText embedding modelsVector storesRetrieversChainsMemoryAgentsCallbacksModulesGuidesEcosystemAdditional resourcesModulesData connectionText embedding modelsOn this pageText embedding modelsinfoHead to Integrations for documentation on built-in integrations with text embedding model providers.The Embeddings class is a class designed for interfacing with text embedding models. There are lots of embedding model providers (OpenAI, Cohere, Hugging Face, etc) - this class is designed to provide a standard interface for all of them.Embeddings create a vector representation of a piece of text. This is useful because it means we can think about text in the vector space, and do things like semantic search where we look for pieces of text that are most similar in the vector space.The base Embeddings class in LangChain exposes two methods: one for embedding documents and one for embedding a query. The former takes as input multiple texts, while the latter takes a single text. The reason for having these as two separate methods is that some embedding providers have different embedding methods for documents (to be searched over) vs queries (the search query itself).Get started​Setup​To start we'll need to install the OpenAI Python package:pip install openaiAccessing the API requires an API key, which you can get by creating an account and heading here. Once we have a key we'll want to set it as an environment variable by running:export OPENAI_API_KEY="..."If you'd prefer not to set an environment variable you can pass the key in directly via the openai_api_key named parameter when initiating the OpenAI LLM class:from langchain.embeddings import OpenAIEmbeddingsembeddings_model
https://python.langchain.com/docs/modules/data_connection/text_embedding/
72f8b05fa9fa-2
OpenAI LLM class:from langchain.embeddings import OpenAIEmbeddingsembeddings_model = OpenAIEmbeddings(openai_api_key="...")otherwise you can initialize without any params:from langchain.embeddings import OpenAIEmbeddingsembeddings_model = OpenAIEmbeddings()embed_documents​Embed list of texts​embeddings = embeddings_model.embed_documents( [ "Hi there!", "Oh, hello!", "What's your name?", "My friends call me World", "Hello World!" ])len(embeddings), len(embeddings[0])(5, 1536)embed_query​Embed single query​Embed a single piece of text for the purpose of comparing to other embedded pieces of texts.embedded_query = embeddings_model.embed_query("What was the name mentioned in the conversation?")embedded_query[:5][0.0053587136790156364, -0.0004999046213924885, 0.038883671164512634, -0.003001077566295862, -0.00900818221271038]PreviousLost in the middle: The problem with long contextsNextVector storesGet startedCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/modules/data_connection/text_embedding/
0729a0b080b7-0
Agents | 🦜�🔗 Langchain
https://python.langchain.com/docs/modules/agents/
0729a0b080b7-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKGet startedIntroductionInstallationQuickstartModulesModel I/​OData connectionChainsMemoryAgentsAgent typesHow-toToolsToolkitsCallbacksModulesGuidesEcosystemAdditional resourcesModulesAgentsOn this pageAgentsThe core idea of agents is to use an LLM to choose a sequence of actions to take. In chains, a sequence of actions is hardcoded (in code). In agents, a language model is used as a reasoning engine to determine which actions to take and in which order.There are several key components here:Agent​This is the class responsible for deciding what step to take next. This is powered by a language model and a prompt. This prompt can include things like:The personality of the agent (useful for having it respond in a certain way)Background context for the agent (useful for giving it more context on the types of tasks it's being asked to do)Prompting strategies to invoke better reasoning (the most famous/widely used being ReAct)LangChain provides a few different types of agents to get started. Even then, you will likely want to customize those agents with parts (1) and (2). For a full list of agent types see agent typesTools​Tools are functions that an agent calls. There are two important considerations here:Giving the agent access to the right toolsDescribing the tools in a way that is most helpful to the agentWithout both, the agent you are trying to build will not work. If you don't give the agent access to a correct set of tools, it will never be able to accomplish the objective.
https://python.langchain.com/docs/modules/agents/
0729a0b080b7-2
If you don't describe the tools properly, the agent won't know how to properly use them.LangChain provides a wide set of tools to get started, but also makes it easy to define your own (including custom descriptions). For a full list of tools, see hereToolkits​Often the set of tools an agent has access to is more important than a single tool. For this LangChain provides the concept of toolkits - groups of tools needed to accomplish specific objectives. There are generally around 3-5 tools in a toolkit.LangChain provides a wide set of toolkits to get started. For a full list of toolkits, see hereAgentExecutor​The agent executor is the runtime for an agent. This is what actually calls the agent and executes the actions it chooses. Pseudocode for this runtime is below:next_action = agent.get_action(...)while next_action != AgentFinish: observation = run(next_action) next_action = agent.get_action(..., next_action, observation)return next_actionWhile this may seem simple, there are several complexities this runtime handles for you, including:Handling cases where the agent selects a non-existent toolHandling cases where the tool errorsHandling cases where the agent produces output that cannot be parsed into a tool invocationLogging and observability at all levels (agent decisions, tool calls) either to stdout or LangSmith.Other types of agent runtimes​The AgentExecutor class is the main agent runtime supported by LangChain. However, there are other, more experimental runtimes we also support. These include:Plan-and-execute AgentBaby AGIAuto GPTGet started​This will go over how to get started building an agent. We will use a LangChain agent class, but show how to customize it to give it specific context.
https://python.langchain.com/docs/modules/agents/
0729a0b080b7-3
We will then define custom tools, and then run it all in the standard LangChain AgentExecutor.Set up the agent​We will use the OpenAIFunctionsAgent. This is easiest and best agent to get started with. It does however require usage of ChatOpenAI models. If you want to use a different language model, we would recommend using the ReAct agent.For this guide, we will construct a custom agent that has access to a custom tool. We are choosing this example because we think for most use cases you will NEED to customize either the agent or the tools. The tool we will give the agent is a tool to calculate the length of a word. This is useful because this is actually something LLMs can mess up due to tokenization. We will first create it WITHOUT memory, but we will then show how to add memory in. Memory is needed to enable conversation.First, let's load the language model we're going to use to control the agent.from langchain.chat_models import ChatOpenAIllm = ChatOpenAI(temperature=0)Next, let's define some tools to use. Let's write a really simple Python function to calculate the length of a word that is passed in.from langchain.agents import tool@tooldef get_word_length(word: str) -> int: """Returns the length of a word.""" return len(word)tools = [get_word_length]Now let us create the prompt. We can use the OpenAIFunctionsAgent.create_prompt helper function to create a prompt automatically.
https://python.langchain.com/docs/modules/agents/
0729a0b080b7-4
This allows for a few different ways to customize, including passing in a custom SystemMessage, which we will do.from langchain.schema import SystemMessagesystem_message = SystemMessage(content="You are very powerful assistant, but bad at calculating lengths of words.")prompt = OpenAIFunctionsAgent.create_prompt(system_message=system_message)Putting those pieces together, we can now create the agent.from langchain.agents import OpenAIFunctionsAgentagent = OpenAIFunctionsAgent(llm=llm, tools=tools, prompt=prompt)Finally, we create the AgentExecutor - the runtime for our agent.from langchain.agents import AgentExecutoragent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)Now let's test it out!agent_executor.run("how many letters in the word educa?") > Entering new AgentExecutor chain... Invoking: `get_word_length` with `{'word': 'educa'}` 5 There are 5 letters in the word "educa". > Finished chain. 'There are 5 letters in the word "educa".'This is great - we have an agent! However, this agent is stateless - it doesn't remember anything about previous interactions. This means you can't ask follow up questions easily. Let's fix that by adding in memory.In order to do this, we need to do two things:Add a place for memory variables to go in the promptAdd memory to the AgentExecutor (note that we add it here, and NOT to the agent, as this is the outermost chain)First, let's add a place for memory in the prompt.
https://python.langchain.com/docs/modules/agents/
0729a0b080b7-5
We do this by adding a placeholder for messages with the key "chat_history".from langchain.prompts import MessagesPlaceholderMEMORY_KEY = "chat_history"prompt = OpenAIFunctionsAgent.create_prompt( system_message=system_message, extra_prompt_messages=[MessagesPlaceholder(variable_name=MEMORY_KEY)])Next, let's create a memory object. We will do this by using ConversationBufferMemory. Importantly, we set memory_key also equal to "chat_history" (to align it with the prompt) and set return_messages (to make it return messages rather than a string).from langchain.memory import ConversationBufferMemorymemory = ConversationBufferMemory(memory_key=MEMORY_KEY, return_messages=True)We can then put it all together!agent = OpenAIFunctionsAgent(llm=llm, tools=tools, prompt=prompt)agent_executor = AgentExecutor(agent=agent, tools=tools, memory=memory, verbose=True)agent_executor.run("how many letters in the word educa?")agent_executor.run("is that a real word?")PreviousVector store-backed memoryNextAgent typesAgentToolsToolkitsAgentExecutorOther types of agent runtimesGet startedCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/modules/agents/
62db24a79b8d-0
Agent types | 🦜�🔗 Langchain
https://python.langchain.com/docs/modules/agents/agent_types/
62db24a79b8d-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKGet startedIntroductionInstallationQuickstartModulesModel I/​OData connectionChainsMemoryAgentsAgent typesConversationalOpenAI functionsOpenAI Multi Functions AgentPlan and executeReActReAct document storeSelf ask with searchStructured tool chatHow-toToolsToolkitsCallbacksModulesGuidesEcosystemAdditional resourcesModulesAgentsAgent typesOn this pageAgent typesAction agents​Agents use an LLM to determine which actions to take and in what order. An action can either be using a tool and observing its output, or returning a response to the user. Here are the agents available in LangChain.Zero-shot ReAct​This agent uses the ReAct framework to determine which tool to use based solely on the tool's description. Any number of tools can be provided. This agent requires that a description is provided for each tool.Note: This is the most general purpose action agent.Structured input ReAct​The structured tool chat agent is capable of using multi-input tools. Older agents are configured to specify an action input as a single string, but this agent can use a tools' argument schema to create a structured action input. This is useful for more complex tool usage, like precisely navigating around a browser.OpenAI Functions​Certain OpenAI models (like gpt-3.5-turbo-0613 and gpt-4-0613) have been explicitly fine-tuned to detect when a function should to be called and respond with the inputs that should be passed to the function. The OpenAI Functions Agent is designed to work with these models.Conversational​This agent is designed to be used in conversational settings.
https://python.langchain.com/docs/modules/agents/agent_types/
62db24a79b8d-2
The prompt is designed to make the agent helpful and conversational. It uses the ReAct framework to decide which tool to use, and uses memory to remember the previous conversation interactions.Self ask with search​This agent utilizes a single tool that should be named Intermediate Answer. This tool should be able to lookup factual answers to questions. This agent is equivalent to the original self ask with search paper, where a Google search API was provided as the tool.ReAct document store​This agent uses the ReAct framework to interact with a docstore. Two tools must be provided: a Search tool and a Lookup tool (they must be named exactly as so). The Search tool should search for a document, while the Lookup tool should lookup a term in the most recently found document. This agent is equivalent to the original ReAct paper, specifically the Wikipedia example.Plan-and-execute agents​Plan and execute agents accomplish an objective by first planning what to do, then executing the sub tasks. This idea is largely inspired by BabyAGI and then the "Plan-and-Solve" paper.PreviousAgentsNextConversationalAction agentsZero-shot ReActStructured input ReActOpenAI FunctionsConversationalSelf ask with searchReAct document storePlan-and-execute agentsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/modules/agents/agent_types/
ef13765193a4-0
Page Not Found | 🦜�🔗 Langchain Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKPage Not FoundWe could not find what you were looking for.Please contact the owner of the site that linked you to the original URL and let them know their link is broken.CommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/modules/agents/agent_types/react.html
533c097eeae6-0
Page Not Found | 🦜�🔗 Langchain Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKPage Not FoundWe could not find what you were looking for.Please contact the owner of the site that linked you to the original URL and let them know their link is broken.CommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/modules/agents/agent_types/structured_chat.html
8bcc7b05b3fe-0
Page Not Found | 🦜�🔗 Langchain Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKPage Not FoundWe could not find what you were looking for.Please contact the owner of the site that linked you to the original URL and let them know their link is broken.CommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/modules/agents/agent_types/chat_conversation_agent.html
d3be13be6cfe-0
Self ask with search | 🦜�🔗 Langchain Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKGet startedIntroductionInstallationQuickstartModulesModel I/​OData connectionChainsMemoryAgentsAgent typesConversationalOpenAI functionsOpenAI Multi Functions AgentPlan and executeReActReAct document storeSelf ask with searchStructured tool chatHow-toToolsToolkitsCallbacksModulesGuidesEcosystemAdditional resourcesModulesAgentsAgent typesSelf ask with searchSelf ask with searchThis walkthrough showcases the Self Ask With Search chain.from langchain import OpenAI, SerpAPIWrapperfrom langchain.agents import initialize_agent, Toolfrom langchain.agents import AgentTypellm = OpenAI(temperature=0)search = SerpAPIWrapper()tools = [ Tool( name="Intermediate Answer", func=search.run, description="useful for when you need to ask with search", )]self_ask_with_search = initialize_agent( tools, llm, agent=AgentType.SELF_ASK_WITH_SEARCH, verbose=True)self_ask_with_search.run( "What is the hometown of the reigning men's U.S. Open champion?") > Entering new AgentExecutor chain... Yes. Follow up: Who is the reigning men's U.S. Open champion? Intermediate answer: Carlos Alcaraz Garfia Follow up: Where is Carlos Alcaraz Garfia from? Intermediate answer: El Palmar, Spain So the final answer is: El Palmar, Spain > Finished chain. 'El Palmar, Spain'PreviousReAct document storeNextStructured tool chatCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/modules/agents/agent_types/self_ask_with_search
31979d777674-0
Structured tool chat | 🦜�🔗 Langchain
https://python.langchain.com/docs/modules/agents/agent_types/structured_chat
31979d777674-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKGet startedIntroductionInstallationQuickstartModulesModel I/​OData connectionChainsMemoryAgentsAgent typesConversationalOpenAI functionsOpenAI Multi Functions AgentPlan and executeReActReAct document storeSelf ask with searchStructured tool chatHow-toToolsToolkitsCallbacksModulesGuidesEcosystemAdditional resourcesModulesAgentsAgent typesStructured tool chatStructured tool chatThe structured tool chat agent is capable of using multi-input tools.Older agents are configured to specify an action input as a single string, but this agent can use the provided tools' args_schema to populate the action input.This functionality is natively available using agent types: structured-chat-zero-shot-react-description or AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTIONimport osos.environ["LANGCHAIN_TRACING"] = "true" # If you want to trace the execution of the program, set to "true"from langchain.agents import AgentTypefrom langchain.chat_models import ChatOpenAIfrom langchain.agents import initialize_agentInitialize Tools​We will test the agent using a web browser.from langchain.agents.agent_toolkits import PlayWrightBrowserToolkitfrom langchain.tools.playwright.utils import ( create_async_playwright_browser, create_sync_playwright_browser, # A synchronous browser is available, though it isn't compatible with jupyter.)# This import is required only for jupyter notebooks, since they have their own eventloopimport nest_asyncionest_asyncio.apply()async_browser = create_async_playwright_browser()browser_toolkit = PlayWrightBrowserToolkit.from_browser(async_browser=async_browser)tools = browser_toolkit.get_tools()llm = ChatOpenAI(temperature=0) # Also works well with Anthropic modelsagent_chain = initialize_agent(tools, llm,
https://python.langchain.com/docs/modules/agents/agent_types/structured_chat
31979d777674-2
# Also works well with Anthropic modelsagent_chain = initialize_agent(tools, llm, agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)response = await agent_chain.arun(input="Hi I'm Erica.")print(response) > Entering new AgentExecutor chain... Action: ``` { "action": "Final Answer", "action_input": "Hello Erica, how can I assist you today?" } ``` > Finished chain. Hello Erica, how can I assist you today?response = await agent_chain.arun(input="Don't need help really just chatting.")print(response) > Entering new AgentExecutor chain... > Finished chain. I'm here to chat! How's your day going?response = await agent_chain.arun(input="Browse to blog.langchain.dev and summarize the text, please.")print(response) > Entering new AgentExecutor chain... Action: ``` { "action": "navigate_browser", "action_input": { "url": "https://blog.langchain.dev/" } } ``` Observation: Navigating to https://blog.langchain.dev/ returned status code 200 Thought:I need to extract the text from the webpage to summarize it. Action: ``` { "action":
https://python.langchain.com/docs/modules/agents/agent_types/structured_chat
31979d777674-3
Action: ``` { "action": "extract_text", "action_input": {} } ``` Observation: LangChain LangChain Home About GitHub Docs LangChain The official LangChain blog. Auto-Evaluator Opportunities Editor's Note: this is a guest blog post by Lance Martin. TL;DR We recently open-sourced an auto-evaluator tool for grading LLM question-answer chains. We are now releasing an open source, free to use hosted app and API to expand usability. Below we discuss a few opportunities to further improve May 1, 2023 5 min read Callbacks Improvements TL;DR: We're announcing improvements to our callbacks system, which powers logging, tracing, streaming output, and some awesome third-party integrations. This will better support concurrent runs with independent callbacks, tracing of deeply nested trees of LangChain components, and callback handlers scoped to a single request (which is super useful for May 1, 2023 3 min read Unleashing the power of AI Collaboration with Parallelized LLM Agent Actor Trees Editor's note: the following is a guest blog post from Cyrus at Shaman AI. We use guest blog posts to highlight interesting and novel applications, and this is certainly that. There's been a lot of talk about agents recently, but most have been discussions around a single agent. If multiple Apr 28, 2023 4 min read Gradio & LLM Agents Editor's note: this is a guest blog post from Freddy Boulton, a software engineer at Gradio. We're excited to share this post because it brings a large number of exciting new tools into the ecosystem. Agents are largely defined by the tools they have, so to be able to equip Apr 23, 2023
https://python.langchain.com/docs/modules/agents/agent_types/structured_chat
31979d777674-4
defined by the tools they have, so to be able to equip Apr 23, 2023 4 min read RecAlign - The smart content filter for social media feed [Editor's Note] This is a guest post by Tian Jin. We are highlighting this application as we think it is a novel use case. Specifically, we think recommendation systems are incredibly impactful in our everyday lives and there has not been a ton of discourse on how LLMs will impact Apr 22, 2023 3 min read Improving Document Retrieval with Contextual Compression Note: This post assumes some familiarity with LangChain and is moderately technical. 💡 TL;DR: We’ve introduced a new abstraction and a new document Retriever to facilitate the post-processing of retrieved documents. Specifically, the new abstraction makes it easy to take a set of retrieved documents and extract from them Apr 20, 2023 3 min read Autonomous Agents & Agent Simulations Over the past two weeks, there has been a massive increase in using LLMs in an agentic manner. Specifically, projects like AutoGPT, BabyAGI, CAMEL, and Generative Agents have popped up. The LangChain community has now implemented some parts of all of those projects in the LangChain framework. While researching and Apr 18, 2023 7 min read AI-Powered Medical Knowledge: Revolutionizing Care for Rare Conditions [Editor's Note]: This is a guest post by Jack Simon, who recently participated in a hackathon at Williams College. He built a LangChain-powered chatbot focused on appendiceal cancer, aiming to make specialized knowledge more accessible to those in need. If you are interested in building a chatbot for another rare Apr 17, 2023 3 min read Auto-Eval of Question-Answering Tasks By Lance Martin Context
https://python.langchain.com/docs/modules/agents/agent_types/structured_chat
31979d777674-5
Tasks By Lance Martin Context LLM ops platforms, such as LangChain, make it easy to assemble LLM components (e.g., models, document retrievers, data loaders) into chains. Question-Answering is one of the most popular applications of these chains. But it is often not always obvious to determine what parameters (e.g. Apr 15, 2023 3 min read Announcing LangChainJS Support for Multiple JS Environments TLDR: We're announcing support for running LangChain.js in browsers, Cloudflare Workers, Vercel/Next.js, Deno, Supabase Edge Functions, alongside existing support for Node.js ESM and CJS. See install/upgrade docs and breaking changes list. Context Originally we designed LangChain.js to run in Node.js, which is the Apr 11, 2023 3 min read LangChain x Supabase Supabase is holding an AI Hackathon this week. Here at LangChain we are big fans of both Supabase and hackathons, so we thought this would be a perfect time to highlight the multiple ways you can use LangChain and Supabase together. The reason we like Supabase so much is that Apr 8, 2023 2 min read Announcing our $10M seed round led by Benchmark It was only six months ago that we released the first version of LangChain, but it seems like several years. When we launched, generative AI was starting to go mainstream: stable diffusion had just been released and was captivating people’s imagination and fueling an explosion in developer activity, Jasper Apr 4, 2023 4 min read Custom Agents One of the most common requests we've heard is better functionality and documentation for creating custom agents.
https://python.langchain.com/docs/modules/agents/agent_types/structured_chat
31979d777674-6
Agents One of the most common requests we've heard is better functionality and documentation for creating custom agents. This has always been a bit tricky - because in our mind it's actually still very unclear what an "agent" actually is, and therefore what the "right" abstractions for them may be. Recently, Apr 3, 2023 3 min read Retrieval TL;DR: We are adjusting our abstractions to make it easy for other retrieval methods besides the LangChain VectorDB object to be used in LangChain. This is done with the goals of (1) allowing retrievers constructed elsewhere to be used more easily in LangChain, (2) encouraging more experimentation with alternative Mar 23, 2023 4 min read LangChain + Zapier Natural Language Actions (NLA) We are super excited to team up with Zapier and integrate their new Zapier NLA API into LangChain, which you can now use with your agents and chains. With this integration, you have access to the 5k+ apps and 20k+ actions on Zapier's platform through a natural language API interface. Mar 16, 2023 2 min read Evaluation Evaluation of language models, and by extension applications built on top of language models, is hard. With recent model releases (OpenAI, Anthropic, Google) evaluation is becoming a bigger and bigger issue. People are starting to try to tackle this, with OpenAI releasing OpenAI/evals - focused on evaluating OpenAI models. Mar 14, 2023 3 min read LLMs and SQL Francisco Ingham and Jon Luo are two of the community members leading the change on the SQL integrations. We’re really excited to write this blog post with them going over all the tips and tricks they’ve learned doing so. We’re even more excited to announce that we’ Mar 13, 2023 8 min read Origin Web Browser
https://python.langchain.com/docs/modules/agents/agent_types/structured_chat
31979d777674-7
to announce that we’ Mar 13, 2023 8 min read Origin Web Browser [Editor's Note]: This is the second of hopefully many guest posts. We intend to highlight novel applications building on top of LangChain. If you are interested in working with us on such a post, please reach out to [email protected]. Authors: Parth Asawa (pgasawa@), Ayushi Batwara (ayushi.batwara@), Jason Mar 8, 2023 4 min read Prompt Selectors One common complaint we've heard is that the default prompt templates do not work equally well for all models. This became especially pronounced this past week when OpenAI released a ChatGPT API. This new API had a completely new interface (which required new abstractions) and as a result many users Mar 8, 2023 2 min read Chat Models Last week OpenAI released a ChatGPT endpoint. It came marketed with several big improvements, most notably being 10x cheaper and a lot faster. But it also came with a completely new API endpoint. We were able to quickly write a wrapper for this endpoint to let users use it like Mar 6, 2023 6 min read Using the ChatGPT API to evaluate the ChatGPT API OpenAI released a new ChatGPT API yesterday. Lots of people were excited to try it. But how does it actually compare to the existing API? It will take some time before there is a definitive answer, but here are some initial thoughts. Because I'm lazy, I also enrolled the help Mar 2, 2023 5 min read Agent Toolkits Today, we're announcing agent toolkits, a new abstraction that allows developers to create agents designed for a particular use-case (for example, interacting with a relational database or interacting with an OpenAPI spec). We hope to continue developing different toolkits that can enable
https://python.langchain.com/docs/modules/agents/agent_types/structured_chat
31979d777674-8
database or interacting with an OpenAPI spec). We hope to continue developing different toolkits that can enable agents to do amazing feats. Toolkits are supported Mar 1, 2023 3 min read TypeScript Support It's finally here... TypeScript support for LangChain. What does this mean? It means that all your favorite prompts, chains, and agents are all recreatable in TypeScript natively. Both the Python version and TypeScript version utilize the same serializable format, meaning that artifacts can seamlessly be shared between languages. As an Feb 17, 2023 2 min read Streaming Support in LangChain We’re excited to announce streaming support in LangChain. There's been a lot of talk about the best UX for LLM applications, and we believe streaming is at its core. We’ve also updated the chat-langchain repo to include streaming and async execution. We hope that this repo can serve Feb 14, 2023 2 min read LangChain + Chroma Today we’re announcing LangChain's integration with Chroma, the first step on the path to the Modern A.I Stack. LangChain - The A.I-native developer toolkit We started LangChain with the intent to build a modular and flexible framework for developing A.I-native applications. Some of the use cases Feb 13, 2023 2 min read Page 1 of 2 Older Posts → LangChain © 2023 Sign up Powered by Ghost Thought: > Finished chain. The LangChain blog has recently released an open-source auto-evaluator tool for grading LLM question-answer chains and is now releasing an open-source, free-to-use hosted app and API to expand usability. The blog also discusses various opportunities to further improve the LangChain platform.response = await
https://python.langchain.com/docs/modules/agents/agent_types/structured_chat
31979d777674-9
to expand usability. The blog also discusses various opportunities to further improve the LangChain platform.response = await agent_chain.arun(input="What's the latest xkcd comic about?")print(response) > Entering new AgentExecutor chain... Thought: I can navigate to the xkcd website and extract the latest comic title and alt text to answer the question. Action: ``` { "action": "navigate_browser", "action_input": { "url": "https://xkcd.com/" } } ``` Observation: Navigating to https://xkcd.com/ returned status code 200 Thought:I can extract the latest comic title and alt text using CSS selectors. Action: ``` { "action": "get_elements", "action_input": { "selector": "#ctitle, #comic img", "attributes": ["alt", "src"] } } ``` Observation: [{"alt": "Tapetum Lucidum", "src": "//imgs.xkcd.com/comics/tapetum_lucidum.png"}] Thought: > Finished chain. The latest xkcd comic is titled "Tapetum Lucidum" and the image can be found at https://xkcd.com/2565/.Adding in memory​Here is how you add in memory to this agentfrom langchain.prompts import MessagesPlaceholderfrom langchain.memory import
https://python.langchain.com/docs/modules/agents/agent_types/structured_chat
31979d777674-10
you add in memory to this agentfrom langchain.prompts import MessagesPlaceholderfrom langchain.memory import ConversationBufferMemorychat_history = MessagesPlaceholder(variable_name="chat_history")memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)agent_chain = initialize_agent( tools, llm, agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True, memory=memory, agent_kwargs = { "memory_prompts": [chat_history], "input_variables": ["input", "agent_scratchpad", "chat_history"] })response = await agent_chain.arun(input="Hi I'm Erica.")print(response) > Entering new AgentExecutor chain... Action: ``` { "action": "Final Answer", "action_input": "Hi Erica! How can I assist you today?" } ``` > Finished chain. Hi Erica! How can I assist you today?response = await agent_chain.arun(input="whats my name?")print(response) > Entering new AgentExecutor chain... Your name is Erica. > Finished chain. Your name is Erica.PreviousSelf ask with searchNextAdd Memory to OpenAI Functions AgentCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/modules/agents/agent_types/structured_chat
b65633e2819d-0
Page Not Found | 🦜�🔗 Langchain Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKPage Not FoundWe could not find what you were looking for.Please contact the owner of the site that linked you to the original URL and let them know their link is broken.CommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/modules/agents/agent_types/self_ask_with_search.html
4d2fcc628c52-0
ReAct document store | 🦜�🔗 Langchain
https://python.langchain.com/docs/modules/agents/agent_types/react_docstore
4d2fcc628c52-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKGet startedIntroductionInstallationQuickstartModulesModel I/​OData connectionChainsMemoryAgentsAgent typesConversationalOpenAI functionsOpenAI Multi Functions AgentPlan and executeReActReAct document storeSelf ask with searchStructured tool chatHow-toToolsToolkitsCallbacksModulesGuidesEcosystemAdditional resourcesModulesAgentsAgent typesReAct document storeReAct document storeThis walkthrough showcases using an agent to implement the ReAct logic for working with document store specifically.from langchain import OpenAI, Wikipediafrom langchain.agents import initialize_agent, Toolfrom langchain.agents import AgentTypefrom langchain.agents.react.base import DocstoreExplorerdocstore = DocstoreExplorer(Wikipedia())tools = [ Tool( name="Search", func=docstore.search, description="useful for when you need to ask with search", ), Tool( name="Lookup", func=docstore.lookup, description="useful for when you need to ask with lookup", ),]llm = OpenAI(temperature=0, model_name="text-davinci-002")react = initialize_agent(tools, llm, agent=AgentType.REACT_DOCSTORE, verbose=True)question = "Author David Chanoff has collaborated with a U.S. Navy admiral who served as the ambassador to the United Kingdom under which President?"react.run(question) > Entering new AgentExecutor chain... Thought: I need to search David Chanoff and find the
https://python.langchain.com/docs/modules/agents/agent_types/react_docstore
4d2fcc628c52-2
Thought: I need to search David Chanoff and find the U.S. Navy admiral he collaborated with. Then I need to find which President the admiral served under. Action: Search[David Chanoff] Observation: David Chanoff is a noted author of non-fiction work. His work has typically involved collaborations with the principal protagonist of the work concerned. His collaborators have included; Augustus A. White, Joycelyn Elders, �oàn Văn Toại, William J. Crowe, Ariel Sharon, Kenneth Good and Felix Zandman. He has also written about a wide range of subjects including literary history, education and foreign for The Washington Post, The New Republic and The New York Times Magazine. He has published more than twelve books. Thought: The U.S. Navy admiral David Chanoff collaborated with is William J. Crowe. I need to find which President he served under. Action: Search[William J. Crowe] Observation: William James Crowe Jr. (January 2, 1925 – October 18, 2007) was a United States Navy admiral and diplomat who served as the 11th chairman of the Joint Chiefs of Staff under Presidents Ronald Reagan and George H. W. Bush, and as the ambassador to the United Kingdom and Chair of the Intelligence Oversight Board under President Bill Clinton. Thought: William J. Crowe served as the ambassador to the United Kingdom under President Bill Clinton, so the answer is Bill Clinton. Action: Finish[Bill Clinton] > Finished chain. 'Bill Clinton'PreviousReActNextSelf ask with
https://python.langchain.com/docs/modules/agents/agent_types/react_docstore
4d2fcc628c52-3
> Finished chain. 'Bill Clinton'PreviousReActNextSelf ask with searchCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/modules/agents/agent_types/react_docstore
6177e5a9f570-0
ReAct | 🦜�🔗 Langchain
https://python.langchain.com/docs/modules/agents/agent_types/react
6177e5a9f570-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKGet startedIntroductionInstallationQuickstartModulesModel I/​OData connectionChainsMemoryAgentsAgent typesConversationalOpenAI functionsOpenAI Multi Functions AgentPlan and executeReActReAct document storeSelf ask with searchStructured tool chatHow-toToolsToolkitsCallbacksModulesGuidesEcosystemAdditional resourcesModulesAgentsAgent typesReActOn this pageReActThis walkthrough showcases using an agent to implement the ReAct logic.from langchain.agents import load_toolsfrom langchain.agents import initialize_agentfrom langchain.agents import AgentTypefrom langchain.llms import OpenAIFirst, let's load the language model we're going to use to control the agent.llm = OpenAI(temperature=0)Next, let's load some tools to use. Note that the llm-math tool uses an LLM, so we need to pass that in.tools = load_tools(["serpapi", "llm-math"], llm=llm)Finally, let's initialize an agent with the tools, the language model, and the type of agent we want to use.agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)Now let's test it out!agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?") > Entering new AgentExecutor chain... I need to find out who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power. Action: Search Action Input: "Leo DiCaprio girlfriend" Observation: Camila Morrone Thought: I need to find out Camila Morrone's
https://python.langchain.com/docs/modules/agents/agent_types/react
6177e5a9f570-2
Camila Morrone Thought: I need to find out Camila Morrone's age Action: Search Action Input: "Camila Morrone age" Observation: 25 years Thought: I need to calculate 25 raised to the 0.43 power Action: Calculator Action Input: 25^0.43 Observation: Answer: 3.991298452658078 Thought: I now know the final answer Final Answer: Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.991298452658078. > Finished chain. "Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.991298452658078."Using chat models​You can also create ReAct agents that use chat models instead of LLMs as the agent driver.from langchain.chat_models import ChatOpenAIchat_model = ChatOpenAI(temperature=0)agent = initialize_agent(tools, chat_model, agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?")PreviousPlan and executeNextReAct document storeUsing chat modelsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/modules/agents/agent_types/react
7bdc6867ba9a-0
Page Not Found | 🦜�🔗 Langchain Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKPage Not FoundWe could not find what you were looking for.Please contact the owner of the site that linked you to the original URL and let them know their link is broken.CommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/modules/agents/agent_types/react_docstore.html
75c86010017f-0
Page Not Found | 🦜�🔗 Langchain Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKPage Not FoundWe could not find what you were looking for.Please contact the owner of the site that linked you to the original URL and let them know their link is broken.CommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/modules/agents/agent_types/openai_functions_agent.html
ac0cea215bce-0
OpenAI Multi Functions Agent | 🦜�🔗 Langchain
https://python.langchain.com/docs/modules/agents/agent_types/openai_multi_functions_agent
ac0cea215bce-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKGet startedIntroductionInstallationQuickstartModulesModel I/​OData connectionChainsMemoryAgentsAgent typesConversationalOpenAI functionsOpenAI Multi Functions AgentPlan and executeReActReAct document storeSelf ask with searchStructured tool chatHow-toToolsToolkitsCallbacksModulesGuidesEcosystemAdditional resourcesModulesAgentsAgent typesOpenAI Multi Functions AgentOn this pageOpenAI Multi Functions AgentThis notebook showcases using an agent that uses the OpenAI functions ability to respond to the prompts of the user using a Large Language ModelInstall openai,google-search-results packages which are required as the langchain packages call them internallypip install openai google-search-resultsfrom langchain import SerpAPIWrapperfrom langchain.agents import initialize_agent, Toolfrom langchain.agents import AgentTypefrom langchain.chat_models import ChatOpenAIThe agent is given ability to perform search functionalities with the respective toolSerpAPIWrapper:This initializes the SerpAPIWrapper for search functionality (search).import getpassimport osos.environ["SERPAPI_API_KEY"] = getpass.getpass() ········# Initialize the OpenAI language model# Replace <your_api_key> in openai_api_key="<your_api_key>" with your actual OpenAI key.llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613")# Initialize the SerpAPIWrapper for search functionality# Replace <your_api_key> in openai_api_key="<your_api_key>" with your actual SerpAPI key.search = SerpAPIWrapper()# Define a list of tools offered by the agenttools = [ Tool( name="Search",
https://python.langchain.com/docs/modules/agents/agent_types/openai_multi_functions_agent
ac0cea215bce-2
= [ Tool( name="Search", func=search.run, description="Useful when you need to answer questions about current events. You should ask targeted questions.", ),]mrkl = initialize_agent( tools, llm, agent=AgentType.OPENAI_MULTI_FUNCTIONS, verbose=True)# Do this so we can see exactly what's going on under the hoodimport langchainlangchain.debug = Truemrkl.run("What is the weather in LA and SF?") [chain/start] [1:chain:AgentExecutor] Entering Chain run with input: { "input": "What is the weather in LA and SF?" } [llm/start] [1:chain:AgentExecutor > 2:llm:ChatOpenAI] Entering LLM run with input: { "prompts": [ "System: You are a helpful AI assistant.\nHuman: What is the weather in LA and SF?" ] } [llm/end] [1:chain:AgentExecutor > 2:llm:ChatOpenAI] [2.91s] Exiting LLM run with output: { "generations": [ [ { "text": "", "generation_info": null, "message": { "content": "",
https://python.langchain.com/docs/modules/agents/agent_types/openai_multi_functions_agent
ac0cea215bce-3
"content": "", "additional_kwargs": { "function_call": { "name": "tool_selection", "arguments": "{\n \"actions\": [\n {\n \"action_name\": \"Search\",\n \"action\": {\n \"tool_input\": \"weather in Los Angeles\"\n }\n },\n {\n \"action_name\": \"Search\",\n \"action\": {\n \"tool_input\": \"weather in San Francisco\"\n }\n }\n ]\n}" } }, "example": false } } ] ], "llm_output": { "token_usage": { "prompt_tokens": 81, "completion_tokens": 75, "total_tokens": 156 }, "model_name":
https://python.langchain.com/docs/modules/agents/agent_types/openai_multi_functions_agent
ac0cea215bce-4
}, "model_name": "gpt-3.5-turbo-0613" }, "run": null } [tool/start] [1:chain:AgentExecutor > 3:tool:Search] Entering Tool run with input: "{'tool_input': 'weather in Los Angeles'}" [tool/end] [1:chain:AgentExecutor > 3:tool:Search] [608.693ms] Exiting Tool run with output: "Mostly cloudy early, then sunshine for the afternoon. High 76F. Winds SW at 5 to 10 mph. Humidity59%." [tool/start] [1:chain:AgentExecutor > 4:tool:Search] Entering Tool run with input: "{'tool_input': 'weather in San Francisco'}" [tool/end] [1:chain:AgentExecutor > 4:tool:Search] [517.475ms] Exiting Tool run with output: "Partly cloudy this evening, then becoming cloudy after midnight. Low 53F. Winds WSW at 10 to 20 mph. Humidity83%." [llm/start] [1:chain:AgentExecutor > 5:llm:ChatOpenAI] Entering LLM run with input: { "prompts": [ "System: You are a helpful AI assistant.\nHuman: What is the weather in LA and SF?\nAI: {'name': 'tool_selection', 'arguments': '{\\n \"actions\": [\\n {\\n \"action_name\": \"Search\",\\n
https://python.langchain.com/docs/modules/agents/agent_types/openai_multi_functions_agent
ac0cea215bce-5
{\\n \"action_name\": \"Search\",\\n \"action\": {\\n \"tool_input\": \"weather in Los Angeles\"\\n }\\n },\\n {\\n \"action_name\": \"Search\",\\n \"action\": {\\n \"tool_input\": \"weather in San Francisco\"\\n }\\n }\\n ]\\n}'}\nFunction: Mostly cloudy early, then sunshine for the afternoon. High 76F. Winds SW at 5 to 10 mph. Humidity59%.\nAI: {'name': 'tool_selection', 'arguments': '{\\n \"actions\": [\\n {\\n \"action_name\": \"Search\",\\n \"action\": {\\n \"tool_input\": \"weather in Los Angeles\"\\n }\\n },\\n {\\n \"action_name\": \"Search\",\\n \"action\": {\\n \"tool_input\": \"weather in San Francisco\"\\n }\\n }\\n ]\\n}'}\nFunction: Partly cloudy this evening, then becoming cloudy after midnight. Low 53F. Winds WSW at 10 to 20 mph. Humidity83%." ] } [llm/end] [1:chain:AgentExecutor > 5:llm:ChatOpenAI]
https://python.langchain.com/docs/modules/agents/agent_types/openai_multi_functions_agent
ac0cea215bce-6
[1:chain:AgentExecutor > 5:llm:ChatOpenAI] [2.33s] Exiting LLM run with output: { "generations": [ [ { "text": "The weather in Los Angeles is mostly cloudy with a high of 76°F and a humidity of 59%. The weather in San Francisco is partly cloudy in the evening, becoming cloudy after midnight, with a low of 53°F and a humidity of 83%.", "generation_info": null, "message": { "content": "The weather in Los Angeles is mostly cloudy with a high of 76°F and a humidity of 59%. The weather in San Francisco is partly cloudy in the evening, becoming cloudy after midnight, with a low of 53°F and a humidity of 83%.", "additional_kwargs": {}, "example": false } } ] ], "llm_output": { "token_usage": { "prompt_tokens": 307, "completion_tokens": 54, "total_tokens": 361 }, "model_name":
https://python.langchain.com/docs/modules/agents/agent_types/openai_multi_functions_agent
ac0cea215bce-7
}, "model_name": "gpt-3.5-turbo-0613" }, "run": null } [chain/end] [1:chain:AgentExecutor] [6.37s] Exiting Chain run with output: { "output": "The weather in Los Angeles is mostly cloudy with a high of 76°F and a humidity of 59%. The weather in San Francisco is partly cloudy in the evening, becoming cloudy after midnight, with a low of 53°F and a humidity of 83%." } 'The weather in Los Angeles is mostly cloudy with a high of 76°F and a humidity of 59%. The weather in San Francisco is partly cloudy in the evening, becoming cloudy after midnight, with a low of 53°F and a humidity of 83%.'Configuring max iteration behavior​To make sure that our agent doesn't get stuck in excessively long loops, we can set max_iterations. We can also set an early stopping method, which will determine our agent's behavior once the number of max iterations is hit. By default, the early stopping uses method force which just returns that constant string. Alternatively, you could specify method generate which then does one FINAL pass through the LLM to generate an output.mrkl = initialize_agent( tools, llm, agent=AgentType.OPENAI_FUNCTIONS, verbose=True, max_iterations=2, early_stopping_method="generate",)mrkl.run("What is the weather in NYC today, yesterday, and the day before?") [chain/start] [1:chain:AgentExecutor] Entering Chain run with input:
https://python.langchain.com/docs/modules/agents/agent_types/openai_multi_functions_agent