mirror of
https://github.com/hwchase17/langchain
synced 2024-11-08 07:10:35 +00:00
5fc07fa524
The table creation process in these examples commands do not match what the recently updated functions in these example commands is looking for. This change updates the type in the table creation command. Issue Number for my report of the doc problem #7446 @rlancemartin and @eyurtsev I believe this is your area Twitter: @j1philli Co-authored-by: Bagatur <baskaryan@gmail.com>
448 lines
16 KiB
Plaintext
448 lines
16 KiB
Plaintext
{
|
||
"cells": [
|
||
{
|
||
"attachments": {},
|
||
"cell_type": "markdown",
|
||
"id": "683953b3",
|
||
"metadata": {},
|
||
"source": [
|
||
"# Supabase (Postgres)"
|
||
]
|
||
},
|
||
{
|
||
"attachments": {},
|
||
"cell_type": "markdown",
|
||
"id": "cc80fa84-1f2f-48b4-bd39-3e6412f012f1",
|
||
"metadata": {},
|
||
"source": [
|
||
">[Supabase](https://supabase.com/docs) is an open source Firebase alternative. `Supabase` is built on top of `PostgreSQL`, which offers strong SQL querying capabilities and enables a simple interface with already-existing tools and frameworks.\n",
|
||
"\n",
|
||
">[PostgreSQL](https://en.wikipedia.org/wiki/PostgreSQL) also known as `Postgres`, is a free and open-source relational database management system (RDBMS) emphasizing extensibility and SQL compliance.\n",
|
||
"\n",
|
||
"This notebook shows how to use `Supabase` and `pgvector` as your VectorStore.\n",
|
||
"\n",
|
||
"To run this notebook, please ensure:\n",
|
||
"- the `pgvector` extension is enabled\n",
|
||
"- you have installed the `supabase-py` package\n",
|
||
"- that you have created a `match_documents` function in your database\n",
|
||
"- that you have a `documents` table in your `public` schema similar to the one below.\n",
|
||
"\n",
|
||
"The following function determines cosine similarity, but you can adjust to your needs.\n",
|
||
"\n",
|
||
"```sql\n",
|
||
" -- Enable the pgvector extension to work with embedding vectors\n",
|
||
" create extension vector;\n",
|
||
"\n",
|
||
" -- Create a table to store your documents\n",
|
||
" create table documents (\n",
|
||
" id uuid primary key,\n",
|
||
" content text, -- corresponds to Document.pageContent\n",
|
||
" metadata jsonb, -- corresponds to Document.metadata\n",
|
||
" embedding vector(1536) -- 1536 works for OpenAI embeddings, change if needed\n",
|
||
" );\n",
|
||
"\n",
|
||
" CREATE FUNCTION match_documents(query_embedding vector(1536), match_count int)\n",
|
||
" RETURNS TABLE(\n",
|
||
" id uuid,\n",
|
||
" content text,\n",
|
||
" metadata jsonb,\n",
|
||
" -- we return matched vectors to enable maximal marginal relevance searches\n",
|
||
" embedding vector(1536),\n",
|
||
" similarity float)\n",
|
||
" LANGUAGE plpgsql\n",
|
||
" AS $$\n",
|
||
" # variable_conflict use_column\n",
|
||
" BEGIN\n",
|
||
" RETURN query\n",
|
||
" SELECT\n",
|
||
" id,\n",
|
||
" content,\n",
|
||
" metadata,\n",
|
||
" embedding,\n",
|
||
" 1 -(documents.embedding <=> query_embedding) AS similarity\n",
|
||
" FROM\n",
|
||
" documents\n",
|
||
" ORDER BY\n",
|
||
" documents.embedding <=> query_embedding\n",
|
||
" LIMIT match_count;\n",
|
||
" END;\n",
|
||
" $$;\n",
|
||
"```"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "6bd4498b",
|
||
"metadata": {
|
||
"tags": []
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"# with pip\n",
|
||
"!pip install supabase\n",
|
||
"\n",
|
||
"# with conda\n",
|
||
"# !conda install -c conda-forge supabase"
|
||
]
|
||
},
|
||
{
|
||
"attachments": {},
|
||
"cell_type": "markdown",
|
||
"id": "69bff365-3039-4ff8-a641-aa190166179d",
|
||
"metadata": {},
|
||
"source": [
|
||
"We want to use `OpenAIEmbeddings` so we have to get the OpenAI API Key."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "19846a7b-99bc-47a7-8e1c-f13c2497f1ae",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"import os\n",
|
||
"import getpass\n",
|
||
"\n",
|
||
"os.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"OpenAI API Key:\")"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "c71c3901-d44b-4d09-92c5-3018628c28fa",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"os.environ[\"SUPABASE_URL\"] = getpass.getpass(\"Supabase URL:\")"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "8b91ecfa-f61b-489a-a337-dff1f12f6ab2",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"os.environ[\"SUPABASE_SERVICE_KEY\"] = getpass.getpass(\"Supabase Service Key:\")"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "90afc6df",
|
||
"metadata": {
|
||
"tags": []
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"# If you're storing your Supabase and OpenAI API keys in a .env file, you can load them with dotenv\n",
|
||
"from dotenv import load_dotenv\n",
|
||
"\n",
|
||
"load_dotenv()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 3,
|
||
"id": "5ce44f7c",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"import os\n",
|
||
"from supabase.client import Client, create_client\n",
|
||
"\n",
|
||
"supabase_url = os.environ.get(\"SUPABASE_URL\")\n",
|
||
"supabase_key = os.environ.get(\"SUPABASE_SERVICE_KEY\")\n",
|
||
"supabase: Client = create_client(supabase_url, supabase_key)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 3,
|
||
"id": "aac9563e",
|
||
"metadata": {
|
||
"tags": []
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"from langchain.embeddings.openai import OpenAIEmbeddings\n",
|
||
"from langchain.text_splitter import CharacterTextSplitter\n",
|
||
"from langchain.vectorstores import SupabaseVectorStore\n",
|
||
"from langchain.document_loaders import TextLoader"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 5,
|
||
"id": "a3c3999a",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"from langchain.document_loaders import TextLoader\n",
|
||
"\n",
|
||
"loader = TextLoader(\"../../../state_of_the_union.txt\")\n",
|
||
"documents = loader.load()\n",
|
||
"text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)\n",
|
||
"docs = text_splitter.split_documents(documents)\n",
|
||
"\n",
|
||
"embeddings = OpenAIEmbeddings()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 6,
|
||
"id": "efec97f8",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"# We're using the default `documents` table here. You can modify this by passing in a `table_name` argument to the `from_documents` method.\n",
|
||
"vector_store = SupabaseVectorStore.from_documents(docs, embeddings, client=supabase)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 7,
|
||
"id": "5eabdb75",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"query = \"What did the president say about Ketanji Brown Jackson\"\n",
|
||
"matched_docs = vector_store.similarity_search(query)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 8,
|
||
"id": "4b172de8",
|
||
"metadata": {},
|
||
"outputs": [
|
||
{
|
||
"name": "stdout",
|
||
"output_type": "stream",
|
||
"text": [
|
||
"Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n",
|
||
"\n",
|
||
"Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n",
|
||
"\n",
|
||
"One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n",
|
||
"\n",
|
||
"And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.\n"
|
||
]
|
||
}
|
||
],
|
||
"source": [
|
||
"print(matched_docs[0].page_content)"
|
||
]
|
||
},
|
||
{
|
||
"attachments": {},
|
||
"cell_type": "markdown",
|
||
"id": "18152965",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Similarity search with score\n"
|
||
]
|
||
},
|
||
{
|
||
"attachments": {},
|
||
"cell_type": "markdown",
|
||
"id": "ea13e80a",
|
||
"metadata": {},
|
||
"source": [
|
||
"The returned distance score is cosine distance. Therefore, a lower score is better."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 9,
|
||
"id": "72aaa9c8",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"matched_docs = vector_store.similarity_search_with_relevance_scores(query)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 10,
|
||
"id": "d88e958e",
|
||
"metadata": {},
|
||
"outputs": [
|
||
{
|
||
"data": {
|
||
"text/plain": [
|
||
"(Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \\n\\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \\n\\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \\n\\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.', metadata={'source': '../../../state_of_the_union.txt'}),\n",
|
||
" 0.802509746274066)"
|
||
]
|
||
},
|
||
"execution_count": 10,
|
||
"metadata": {},
|
||
"output_type": "execute_result"
|
||
}
|
||
],
|
||
"source": [
|
||
"matched_docs[0]"
|
||
]
|
||
},
|
||
{
|
||
"attachments": {},
|
||
"cell_type": "markdown",
|
||
"id": "794a7552",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Retriever options\n",
|
||
"\n",
|
||
"This section goes over different options for how to use SupabaseVectorStore as a retriever.\n",
|
||
"\n",
|
||
"### Maximal Marginal Relevance Searches\n",
|
||
"\n",
|
||
"In addition to using similarity search in the retriever object, you can also use `mmr`.\n"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 11,
|
||
"id": "96ff911a",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"retriever = vector_store.as_retriever(search_type=\"mmr\")"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 12,
|
||
"id": "f00be6d0",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"matched_docs = retriever.get_relevant_documents(query)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 13,
|
||
"id": "a559c3f1",
|
||
"metadata": {},
|
||
"outputs": [
|
||
{
|
||
"name": "stdout",
|
||
"output_type": "stream",
|
||
"text": [
|
||
"\n",
|
||
"## Document 0\n",
|
||
"\n",
|
||
"Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n",
|
||
"\n",
|
||
"Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n",
|
||
"\n",
|
||
"One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n",
|
||
"\n",
|
||
"And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.\n",
|
||
"\n",
|
||
"## Document 1\n",
|
||
"\n",
|
||
"One was stationed at bases and breathing in toxic smoke from “burn pits” that incinerated wastes of war—medical and hazard material, jet fuel, and more. \n",
|
||
"\n",
|
||
"When they came home, many of the world’s fittest and best trained warriors were never the same. \n",
|
||
"\n",
|
||
"Headaches. Numbness. Dizziness. \n",
|
||
"\n",
|
||
"A cancer that would put them in a flag-draped coffin. \n",
|
||
"\n",
|
||
"I know. \n",
|
||
"\n",
|
||
"One of those soldiers was my son Major Beau Biden. \n",
|
||
"\n",
|
||
"We don’t know for sure if a burn pit was the cause of his brain cancer, or the diseases of so many of our troops. \n",
|
||
"\n",
|
||
"But I’m committed to finding out everything we can. \n",
|
||
"\n",
|
||
"Committed to military families like Danielle Robinson from Ohio. \n",
|
||
"\n",
|
||
"The widow of Sergeant First Class Heath Robinson. \n",
|
||
"\n",
|
||
"He was born a soldier. Army National Guard. Combat medic in Kosovo and Iraq. \n",
|
||
"\n",
|
||
"Stationed near Baghdad, just yards from burn pits the size of football fields. \n",
|
||
"\n",
|
||
"Heath’s widow Danielle is here with us tonight. They loved going to Ohio State football games. He loved building Legos with their daughter.\n",
|
||
"\n",
|
||
"## Document 2\n",
|
||
"\n",
|
||
"And I’m taking robust action to make sure the pain of our sanctions is targeted at Russia’s economy. And I will use every tool at our disposal to protect American businesses and consumers. \n",
|
||
"\n",
|
||
"Tonight, I can announce that the United States has worked with 30 other countries to release 60 Million barrels of oil from reserves around the world. \n",
|
||
"\n",
|
||
"America will lead that effort, releasing 30 Million barrels from our own Strategic Petroleum Reserve. And we stand ready to do more if necessary, unified with our allies. \n",
|
||
"\n",
|
||
"These steps will help blunt gas prices here at home. And I know the news about what’s happening can seem alarming. \n",
|
||
"\n",
|
||
"But I want you to know that we are going to be okay. \n",
|
||
"\n",
|
||
"When the history of this era is written Putin’s war on Ukraine will have left Russia weaker and the rest of the world stronger. \n",
|
||
"\n",
|
||
"While it shouldn’t have taken something so terrible for people around the world to see what’s at stake now everyone sees it clearly.\n",
|
||
"\n",
|
||
"## Document 3\n",
|
||
"\n",
|
||
"We can’t change how divided we’ve been. But we can change how we move forward—on COVID-19 and other issues we must face together. \n",
|
||
"\n",
|
||
"I recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. \n",
|
||
"\n",
|
||
"They were responding to a 9-1-1 call when a man shot and killed them with a stolen gun. \n",
|
||
"\n",
|
||
"Officer Mora was 27 years old. \n",
|
||
"\n",
|
||
"Officer Rivera was 22. \n",
|
||
"\n",
|
||
"Both Dominican Americans who’d grown up on the same streets they later chose to patrol as police officers. \n",
|
||
"\n",
|
||
"I spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves. \n",
|
||
"\n",
|
||
"I’ve worked on these issues a long time. \n",
|
||
"\n",
|
||
"I know what works: Investing in crime preventionand community police officers who’ll walk the beat, who’ll know the neighborhood, and who can restore trust and safety.\n"
|
||
]
|
||
}
|
||
],
|
||
"source": [
|
||
"for i, d in enumerate(matched_docs):\n",
|
||
" print(f\"\\n## Document {i}\\n\")\n",
|
||
" print(d.page_content)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "79b1198e",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": []
|
||
}
|
||
],
|
||
"metadata": {
|
||
"kernelspec": {
|
||
"display_name": "Python 3 (ipykernel)",
|
||
"language": "python",
|
||
"name": "python3"
|
||
},
|
||
"language_info": {
|
||
"codemirror_mode": {
|
||
"name": "ipython",
|
||
"version": 3
|
||
},
|
||
"file_extension": ".py",
|
||
"mimetype": "text/x-python",
|
||
"name": "python",
|
||
"nbconvert_exporter": "python",
|
||
"pygments_lexer": "ipython3",
|
||
"version": "3.10.6"
|
||
}
|
||
},
|
||
"nbformat": 4,
|
||
"nbformat_minor": 5
|
||
}
|