The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
notebook fmt (#12498)
Bagatur2424fff3f139
diff --git a/.github/workflows/_lint.yml b/.github/workflows/_lint.ymlindex 56943e2a7c..19560f20d0 100644--- a/.github/workflows/_lint.yml+++ b/.github/workflows/_lint.yml@@ -120,9 +120,9 @@ jobs:- name: Install langchain editableworking-directory: ${{ inputs.working-directory }}- if: ${{ inputs.working-directory != 'libs/langchain' }}+ if: ${{ inputs.langchain-location }}env:- LANGCHAIN_LOCATION: ${{ inputs.langchain-location || '../langchain'}}+ LANGCHAIN_LOCATION: ${{ inputs.langchain-location }}run: |pip install -e "$LANGCHAIN_LOCATION"diff --git a/.github/workflows/doc_lint.yml b/.github/workflows/doc_lint.ymlindex 8529ed2a56..b484b602f6 100644--- a/.github/workflows/doc_lint.yml+++ b/.github/workflows/doc_lint.yml@@ -1,11 +1,15 @@----name: Documentation Lint+name: Docs, templates, cookbook linton:push:- branches: [master]+ branches: [ master ]pull_request:- branches: [master]+ paths:+ - 'docs/**'+ - 'templates/**'+ - 'cookbook/**'+ workflow_dispatch:jobs:check:@@ -19,4 +23,12 @@ jobs:run: |# We should not encourage imports directly from main init file# Expect for hub- git grep 'from langchain import' docs/{docs,snippets} | grep -vE 'from langchain import (hub)' && exit 1 || exit 0+ git grep 'from langchain import' {docs,templates,cookbook} | grep -vE 'from langchain import (hub)' && exit 1 || exit 0++ - name: Run lint+ uses:+ ./.github/workflows/_lint.yml+ with:+ working-directory: .+ secrets: inherit+diff --git a/.github/workflows/langchain_cli_ci.yml b/.github/workflows/langchain_cli_ci.ymlindex 400a0f285d..7ecb069a10 100644--- a/.github/workflows/langchain_cli_ci.yml+++ b/.github/workflows/langchain_cli_ci.yml@@ -36,6 +36,7 @@ jobs:./.github/workflows/_lint.ymlwith:working-directory: libs/cli+ langchain-location: ../langchainsecrets: inherittest:diff --git a/.github/workflows/langchain_experimental_ci.yml b/.github/workflows/langchain_experimental_ci.ymlindex 13648b9b3a..7750f0bcff 100644--- a/.github/workflows/langchain_experimental_ci.yml+++ b/.github/workflows/langchain_experimental_ci.yml@@ -35,6 +35,7 @@ jobs:./.github/workflows/_lint.ymlwith:working-directory: libs/experimental+ langchain-location: ../langchainsecrets: inherittest:diff --git a/Makefile b/Makefileindex d80b493af5..d540e3a0cd 100644--- a/Makefile+++ b/Makefile@@ -37,6 +37,18 @@ spell_check:spell_fix:poetry run codespell --toml pyproject.toml -w+######################+# LINTING AND FORMATTING+######################++lint:+ poetry run ruff {docs,templates,cookbook}+ poetry run black {docs,templates,cookbook} --check++format format_diff:+ poetry run black {docs,templates,cookbook}+ poetry run ruff --select I --fix {docs,templates,cookbook}+####################### HELP######################diff --git a/cookbook/LLaMA2_sql_chat.ipynb b/cookbook/LLaMA2_sql_chat.ipynbindex f073c1659e..7c086c9322 100644--- a/cookbook/LLaMA2_sql_chat.ipynb+++ b/cookbook/LLaMA2_sql_chat.ipynb@@ -60,22 +60,21 @@}],"source": [- "# Local \n",+ "# Local\n","from langchain.chat_models import ChatOllama\n",+ "\n","llama2_chat = ChatOllama(model=\"llama2:13b-chat\")\n","llama2_code = ChatOllama(model=\"codellama:7b-instruct\")\n","\n","# API\n","from getpass import getpass\n","from langchain.llms import Replicate\n",+ "\n","# REPLICATE_API_TOKEN = getpass()\n","# os.environ[\"REPLICATE_API_TOKEN\"] = REPLICATE_API_TOKEN\n","replicate_id = \"meta/llama-2-13b-chat:f4e2de70d66816a838a89eeeb621910adffb0dd0baba3976c96980970978018d\"\n","llama2_chat_replicate = Replicate(\n",- " model=replicate_id,\n",- " input={\"temperature\": 0.01, \n",- " \"max_length\": 500, \n",- " \"top_p\": 1}\n",+ " model=replicate_id, input={\"temperature\": 0.01, \"max_length\": 500, \"top_p\": 1}\n",")"]},@@ -110,11 +109,14 @@"outputs": [],"source": ["from langchain.utilities import SQLDatabase\n",- "db = SQLDatabase.from_uri(\"sqlite:///nba_roster.db\", sample_rows_in_table_info= 0)\n",+ "\n",+ "db = SQLDatabase.from_uri(\"sqlite:///nba_roster.db\", sample_rows_in_table_info=0)\n",+ "\n","\n","def get_schema(_):\n"," return db.get_table_info()\n","\n",+ "\n","def run_query(query):\n"," return db.run(query)"]@@ -149,26 +151,29 @@"source": ["# Prompt\n","from langchain.prompts import ChatPromptTemplate\n",+ "\n","template = \"\"\"Based on the table schema below, write a SQL query that would answer the user's question:\n","{schema}\n","\n","Question: {question}\n","SQL Query:\"\"\"\n",- "prompt = ChatPromptTemplate.from_messages([\n",- " (\"system\", \"Given an input question, convert it to a SQL query. No pre-amble.\"),\n",- " (\"human\", template)\n",- "])\n",+ "prompt = ChatPromptTemplate.from_messages(\n",+ " [\n",+ " (\"system\", \"Given an input question, convert it to a SQL query. No pre-amble.\"),\n",+ " (\"human\", template),\n",+ " ]\n",+ ")\n","\n","# Chain to query\n","from langchain.schema.output_parser import StrOutputParser\n","from langchain.schema.runnable import RunnablePassthrough\n","\n","sql_response = (\n",- " RunnablePassthrough.assign(schema=get_schema)\n",- " | prompt\n",- " | llm.bind(stop=[\"\\nSQLResult:\"])\n",- " | StrOutputParser()\n",- " )\n",+ " RunnablePassthrough.assign(schema=get_schema)\n",+ " | prompt\n",+ " | llm.bind(stop=[\"\\nSQLResult:\"])\n",+ " | StrOutputParser()\n",+ ")\n","\n","sql_response.invoke({\"question\": \"What team is Klay Thompson on?\"})"]@@ -209,18 +214,23 @@"Question: {question}\n","SQL Query: {query}\n","SQL Response: {response}\"\"\"\n",- "prompt_response = ChatPromptTemplate.from_messages([\n",- " (\"system\", \"Given an input question and SQL response, convert it to a natural langugae answer. No pre-amble.\"),\n",- " (\"human\", template)\n",- "])\n",+ "prompt_response = ChatPromptTemplate.from_messages(\n",+ " [\n",+ " (\n",+ " \"system\",\n",+ " \"Given an input question and SQL response, convert it to a natural langugae answer. No pre-amble.\",\n",+ " ),\n",+ " (\"human\", template),\n",+ " ]\n",+ ")\n","\n","full_chain = (\n",- " RunnablePassthrough.assign(query=sql_response) \n",+ " RunnablePassthrough.assign(query=sql_response)\n"," | RunnablePassthrough.assign(\n"," schema=get_schema,\n"," response=lambda x: db.run(x[\"query\"]),\n"," )\n",- " | prompt_response \n",+ " | prompt_response\n"," | llm\n",")\n","\n",@@ -269,36 +279,42 @@"# Prompt\n","from langchain.memory import ConversationBufferMemory\n","from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder\n",+ "\n","template = \"\"\"Based on the table schema below, write a SQL query that would answer the user's question:\n","{schema}\n","\n","Question: {question}\n","SQL Query:\"\"\"\n",- "prompt = ChatPromptTemplate.from_messages([\n",- " (\"system\", \"Given an input question, convert it to a SQL query. No pre-amble.\"),\n",- " MessagesPlaceholder(variable_name=\"history\"),\n",- " (\"human\", template)\n",- "])\n",+ "prompt = ChatPromptTemplate.from_messages(\n",+ " [\n",+ " (\"system\", \"Given an input question, convert it to a SQL query. No pre-amble.\"),\n",+ " MessagesPlaceholder(variable_name=\"history\"),\n",+ " (\"human\", template),\n",+ " ]\n",+ ")\n","\n","memory = ConversationBufferMemory(return_messages=True)\n","\n",- "# Chain to query with memory \n",+ "# Chain to query with memory\n","from langchain.schema.runnable import RunnableLambda\n","\n","sql_chain = (\n"," RunnablePassthrough.assign(\n",- " schema=get_schema,\n",- " history=RunnableLambda(lambda x: memory.load_memory_variables(x)[\"history\"])\n",- " )| prompt\n",+ " schema=get_schema,\n",+ " history=RunnableLambda(lambda x: memory.load_memory_variables(x)[\"history\"]),\n",+ " )\n",+ " | prompt\n"," | llm.bind(stop=[\"\\nSQLResult:\"])\n"," | StrOutputParser()\n",")\n","\n",+ "\n","def save(input_output):\n"," output = {\"output\": input_output.pop(\"output\")}\n"," memory.save_context(input_output, output)\n",- " return output['output']\n",- " \n",+ " return output[\"output\"]\n",+ "\n",+ "\n","sql_response_memory = RunnablePassthrough.assign(output=sql_chain) | save\n","sql_response_memory.invoke({\"question\": \"What team is Klay Thompson on?\"})"]@@ -349,18 +365,23 @@"Question: {question}\n","SQL Query: {query}\n","SQL Response: {response}\"\"\"\n",- "prompt_response = ChatPromptTemplate.from_messages([\n",- " (\"system\", \"Given an input question and SQL response, convert it to a natural langugae answer. No pre-amble.\"),\n",- " (\"human\", template)\n",- "])\n",+ "prompt_response = ChatPromptTemplate.from_messages(\n",+ " [\n",+ " (\n",+ " \"system\",\n",+ " \"Given an input question and SQL response, convert it to a natural langugae answer. No pre-amble.\",\n",+ " ),\n",+ " (\"human\", template),\n",+ " ]\n",+ ")\n","\n","full_chain = (\n",- " RunnablePassthrough.assign(query=sql_response_memory) \n",+ " RunnablePassthrough.assign(query=sql_response_memory)\n"," | RunnablePassthrough.assign(\n"," schema=get_schema,\n"," response=lambda x: db.run(x[\"query\"]),\n"," )\n",- " | prompt_response \n",+ " | prompt_response\n"," | llm\n",")\n","\n",diff --git a/cookbook/Semi_Structured_RAG.ipynb b/cookbook/Semi_Structured_RAG.ipynbindex 59d0244bfa..c6cc363368 100644--- a/cookbook/Semi_Structured_RAG.ipynb+++ b/cookbook/Semi_Structured_RAG.ipynb@@ -60,7 +60,7 @@"metadata": {},"outputs": [],"source": [- "! brew install tesseract \n",+ "! brew install tesseract\n","! brew install poppler"]},@@ -108,21 +108,23 @@"from unstructured.partition.pdf import partition_pdf\n","\n","# Get elements\n",- "raw_pdf_elements = partition_pdf(filename=path+\"LLaMA2.pdf\",\n",- " # Unstructured first finds embedded image blocks\n",- " extract_images_in_pdf=False,\n",- " # Use layout model (YOLOX) to get bounding boxes (for tables) and find titles\n",- " # Titles are any sub-section of the document \n",- " infer_table_structure=True, \n",- " # Post processing to aggregate text once we have the title \n",- " chunking_strategy=\"by_title\",\n",- " # Chunking params to aggregate text blocks\n",- " # Attempt to create a new chunk 3800 chars\n",- " # Attempt to keep chunks > 2000 chars \n",- " max_characters=4000, \n",- " new_after_n_chars=3800, \n",- " combine_text_under_n_chars=2000,\n",- " image_output_dir_path=path)"+ "raw_pdf_elements = partition_pdf(\n",+ " filename=path + \"LLaMA2.pdf\",\n",+ " # Unstructured first finds embedded image blocks\n",+ " extract_images_in_pdf=False,\n",+ " # Use layout model (YOLOX) to get bounding boxes (for tables) and find titles\n",+ " # Titles are any sub-section of the document\n",+ " infer_table_structure=True,\n",+ " # Post processing to aggregate text once we have the title\n",+ " chunking_strategy=\"by_title\",\n",+ " # Chunking params to aggregate text blocks\n",+ " # Attempt to create a new chunk 3800 chars\n",+ " # Attempt to keep chunks > 2000 chars\n",+ " max_characters=4000,\n",+ " new_after_n_chars=3800,\n",+ " combine_text_under_n_chars=2000,\n",+ " image_output_dir_path=path,\n",+ ")"]},{@@ -190,6 +192,7 @@" type: str\n"," text: Any\n","\n",+ "\n","# Categorize by type\n","categorized_elements = []\n","for element in raw_pdf_elements:\n",@@ -259,14 +262,14 @@"metadata": {},"outputs": [],"source": [- "# Prompt \n",- "prompt_text=\"\"\"You are an assistant tasked with summarizing tables and text. \\ \n",+ "# Prompt\n",+ "prompt_text = \"\"\"You are an assistant tasked with summarizing tables and text. \\ \n","Give a concise summary of the table or text. Table or text chunk: {element} \"\"\"\n",- "prompt = ChatPromptTemplate.from_template(prompt_text) \n",+ "prompt = ChatPromptTemplate.from_template(prompt_text)\n","\n",- "# Summary chain \n",- "model = ChatOpenAI(temperature=0,model=\"gpt-4\")\n",- "summarize_chain = {\"element\": lambda x:x} | prompt | model | StrOutputParser()"+ "# Summary chain\n",+ "model = ChatOpenAI(temperature=0, model=\"gpt-4\")\n",+ "summarize_chain = {\"element\": lambda x: x} | prompt | model | StrOutputParser()"]},{@@ -321,10 +324,7 @@"from langchain.retrievers.multi_vector import MultiVectorRetriever\n","\n","# The vectorstore to use to index the child chunks\n",- "vectorstore = Chroma(\n",- " collection_name=\"summaries\",\n",- " embedding_function=OpenAIEmbeddings()\n",- ")\n",+ "vectorstore = Chroma(collection_name=\"summaries\", embedding_function=OpenAIEmbeddings())\n","\n","# The storage layer for the parent documents\n","store = InMemoryStore()\n",@@ -332,20 +332,26 @@"\n","# The retriever (empty to start)\n","retriever = MultiVectorRetriever(\n",- " vectorstore=vectorstore, \n",- " docstore=store, \n",+ " vectorstore=vectorstore,\n",+ " docstore=store,\n"," id_key=id_key,\n",")\n","\n","# Add texts\n","doc_ids = [str(uuid.uuid4()) for _ in texts]\n",- "summary_texts = [Document(page_content=s,metadata={id_key: doc_ids[i]}) for i, s in enumerate(text_summaries)]\n",+ "summary_texts = [\n",+ " Document(page_content=s, metadata={id_key: doc_ids[i]})\n",+ " for i, s in enumerate(text_summaries)\n",+ "]\n","retriever.vectorstore.add_documents(summary_texts)\n","retriever.docstore.mset(list(zip(doc_ids, texts)))\n","\n","# Add tables\n","table_ids = [str(uuid.uuid4()) for _ in tables]\n",- "summary_tables = [Document(page_content=s,metadata={id_key: table_ids[i]}) for i, s in enumerate(table_summaries)]\n",+ "summary_tables = [\n",+ " Document(page_content=s, metadata={id_key: table_ids[i]})\n",+ " for i, s in enumerate(table_summaries)\n",+ "]\n","retriever.vectorstore.add_documents(summary_tables)\n","retriever.docstore.mset(list(zip(table_ids, tables)))"]@@ -378,13 +384,13 @@"prompt = ChatPromptTemplate.from_template(template)\n","\n","# LLM\n",- "model = ChatOpenAI(temperature=0,model=\"gpt-4\")\n",+ "model = ChatOpenAI(temperature=0, model=\"gpt-4\")\n","\n","# RAG pipeline\n","chain = (\n",- " {\"context\": retriever, \"question\": RunnablePassthrough()} \n",- " | prompt \n",- " | model \n",+ " {\"context\": retriever, \"question\": RunnablePassthrough()}\n",+ " | prompt\n",+ " | model\n"," | StrOutputParser()\n",")"]diff --git a/cookbook/Semi_structured_and_multi_modal_RAG.ipynb b/cookbook/Semi_structured_and_multi_modal_RAG.ipynbindex 6d00094236..fc011aa52e 100644--- a/cookbook/Semi_structured_and_multi_modal_RAG.ipynb+++ b/cookbook/Semi_structured_and_multi_modal_RAG.ipynb@@ -98,22 +98,24 @@"from unstructured.partition.pdf import partition_pdf\n","\n","# Get elements\n",- "raw_pdf_elements = partition_pdf(filename=path+\"LLaVA.pdf\",\n",- " # Using pdf format to find embedded image blocks\n",- " extract_images_in_pdf=True,\n",- " # Use layout model (YOLOX) to get bounding boxes (for tables) and find titles\n",- " # Titles are any sub-section of the document \n",- " infer_table_structure=True, \n",- " # Post processing to aggregate text once we have the title \n",- " chunking_strategy=\"by_title\",\n",- " # Chunking params to aggregate text blocks\n",- " # Attempt to create a new chunk 3800 chars\n",- " # Attempt to keep chunks > 2000 chars \n",- " # Hard max on chunks\n",- " max_characters=4000, \n",- " new_after_n_chars=3800, \n",- " combine_text_under_n_chars=2000,\n",- " image_output_dir_path=path)"+ "raw_pdf_elements = partition_pdf(\n",+ " filename=path + \"LLaVA.pdf\",\n",+ " # Using pdf format to find embedded image blocks\n",+ " extract_images_in_pdf=True,\n",+ " # Use layout model (YOLOX) to get bounding boxes (for tables) and find titles\n",+ " # Titles are any sub-section of the document\n",+ " infer_table_structure=True,\n",+ " # Post processing to aggregate text once we have the title\n",+ " chunking_strategy=\"by_title\",\n",+ " # Chunking params to aggregate text blocks\n",+ " # Attempt to create a new chunk 3800 chars\n",+ " # Attempt to keep chunks > 2000 chars\n",+ " # Hard max on chunks\n",+ " max_characters=4000,\n",+ " new_after_n_chars=3800,\n",+ " combine_text_under_n_chars=2000,\n",+ " image_output_dir_path=path,\n",+ ")"]},{@@ -170,6 +172,7 @@" type: str\n"," text: Any\n","\n",+ "\n","# Categorize by type\n","categorized_elements = []\n","for element in raw_pdf_elements:\n",@@ -220,14 +223,14 @@"metadata": {},"outputs": [],"source": [- "# Prompt \n",- "prompt_text=\"\"\"You are an assistant tasked with summarizing tables and text. \\ \n",+ "# Prompt\n",+ "prompt_text = \"\"\"You are an assistant tasked with summarizing tables and text. \\ \n","Give a concise summary of the table or text. Table or text chunk: {element} \"\"\"\n",- "prompt = ChatPromptTemplate.from_template(prompt_text) \n",+ "prompt = ChatPromptTemplate.from_template(prompt_text)\n","\n",- "# Summary chain \n",- "model = ChatOpenAI(temperature=0,model=\"gpt-4\")\n",- "summarize_chain = {\"element\": lambda x:x} | prompt | model | StrOutputParser()"+ "# Summary chain\n",+ "model = ChatOpenAI(temperature=0, model=\"gpt-4\")\n",+ "summarize_chain = {\"element\": lambda x: x} | prompt | model | StrOutputParser()"]},{@@ -342,11 +345,11 @@"# Read each file and store its content in a list\n","img_summaries = []\n","for file_path in file_paths:\n",- " with open(file_path, 'r') as file:\n",+ " with open(file_path, \"r\") as file:\n"," img_summaries.append(file.read())\n","\n","# Remove any logging prior to summary\n",- "logging_header=\"clip_model_load: total allocated memory: 201.27 MB\\n\\n\"\n",+ "logging_header = \"clip_model_load: total allocated memory: 201.27 MB\\n\\n\"\n","cleaned_img_summary = [s.split(logging_header, 1)[1].strip() for s in img_summaries]"]},@@ -375,10 +378,7 @@"from langchain.retrievers.multi_vector import MultiVectorRetriever\n","\n","# The vectorstore to use to index the child chunks\n",- "vectorstore = Chroma(\n",- " collection_name=\"summaries\",\n",- " embedding_function=OpenAIEmbeddings()\n",- ")\n",+ "vectorstore = Chroma(collection_name=\"summaries\", embedding_function=OpenAIEmbeddings())\n","\n","# The storage layer for the parent documents\n","store = InMemoryStore()\n",@@ -386,20 +386,26 @@"\n","# The retriever (empty to start)\n","retriever = MultiVectorRetriever(\n",- " vectorstore=vectorstore, \n",- " docstore=store, \n",+ " vectorstore=vectorstore,\n",+ " docstore=store,\n"," id_key=id_key,\n",")\n","\n","# Add texts\n","doc_ids = [str(uuid.uuid4()) for _ in texts]\n",- "summary_texts = [Document(page_content=s,metadata={id_key: doc_ids[i]}) for i, s in enumerate(text_summaries)]\n",+ "summary_texts = [\n",+ " Document(page_content=s, metadata={id_key: doc_ids[i]})\n",+ " for i, s in enumerate(text_summaries)\n",+ "]\n","retriever.vectorstore.add_documents(summary_texts)\n","retriever.docstore.mset(list(zip(doc_ids, texts)))\n","\n","# Add tables\n","table_ids = [str(uuid.uuid4()) for _ in tables]\n",- "summary_tables = [Document(page_content=s,metadata={id_key: table_ids[i]}) for i, s in enumerate(table_summaries)]\n",+ "summary_tables = [\n",+ " Document(page_content=s, metadata={id_key: table_ids[i]})\n",+ " for i, s in enumerate(table_summaries)\n",+ "]\n","retriever.vectorstore.add_documents(summary_tables)\n","retriever.docstore.mset(list(zip(table_ids, tables)))"]@@ -423,9 +429,12 @@"source": ["# Add image summaries\n","img_ids = [str(uuid.uuid4()) for _ in cleaned_img_summary]\n",- "summary_img = [Document(page_content=s,metadata={id_key: img_ids[i]}) for i, s in enumerate(cleaned_img_summary)]\n",+ "summary_img = [\n",+ " Document(page_content=s, metadata={id_key: img_ids[i]})\n",+ " for i, s in enumerate(cleaned_img_summary)\n",+ "]\n","retriever.vectorstore.add_documents(summary_img)\n",- "retriever.docstore.mset(list(zip(img_ids, cleaned_img_summary))) "+ "retriever.docstore.mset(list(zip(img_ids, cleaned_img_summary)))"]},{@@ -449,10 +458,19 @@"source": ["# Add images\n","img_ids = [str(uuid.uuid4()) for _ in cleaned_img_summary]\n",- "summary_img = [Document(page_content=s,metadata={id_key: img_ids[i]}) for i, s in enumerate(cleaned_img_summary)]\n",+ "summary_img = [\n",+ " Document(page_content=s, metadata={id_key: img_ids[i]})\n",+ " for i, s in enumerate(cleaned_img_summary)\n",+ "]\n","retriever.vectorstore.add_documents(summary_img)\n","### Fetch images\n",- "retriever.docstore.mset(list(zip(img_ids, ### image ### ))) "+ "retriever.docstore.mset(\n",+ " list(\n",+ " zip(\n",+ " img_ids,\n",+ " )\n",+ " )\n",+ ")"]},{@@ -542,7 +560,9 @@],"source": ["# We can retrieve this table\n",- "retriever.get_relevant_documents(\"What are results for LLaMA across across domains / subjects?\")[1]"+ "retriever.get_relevant_documents(\n",+ " \"What are results for LLaMA across across domains / subjects?\"\n",+ ")[1]"]},{@@ -592,7 +612,9 @@}],"source": [- "retriever.get_relevant_documents(\"Images / figures with playful and creative examples\")[1]"+ "retriever.get_relevant_documents(\"Images / figures with playful and creative examples\")[\n",+ " 1\n",+ "]"]},{@@ -633,15 +655,15 @@"prompt = ChatPromptTemplate.from_template(template)\n","\n","# Option 1: LLM\n",- "model = ChatOpenAI(temperature=0,model=\"gpt-4\")\n",+ "model = ChatOpenAI(temperature=0, model=\"gpt-4\")\n","# Option 2: Multi-modal LLM\n","# model = GPT4-V or LLaVA\n","\n","# RAG pipeline\n","chain = (\n",- " {\"context\": retriever, \"question\": RunnablePassthrough()} \n",- " | prompt \n",- " | model \n",+ " {\"context\": retriever, \"question\": RunnablePassthrough()}\n",+ " | prompt\n",+ " | model\n"," | StrOutputParser()\n",")"]@@ -664,7 +686,9 @@}],"source": [- "chain.invoke(\"What is the performance of LLaVa across across multiple image domains / subjects?\")"+ "chain.invoke(\n",+ " \"What is the performance of LLaVa across across multiple image domains / subjects?\"\n",+ ")"]},{@@ -713,7 +737,7 @@"name": "python","nbconvert_exporter": "python","pygments_lexer": "ipython3",- "version": "3.9.16"+ "version": "3.9.1"}},"nbformat": 4,diff --git a/cookbook/Semi_structured_multi_modal_RAG_LLaMA2.ipynb b/cookbook/Semi_structured_multi_modal_RAG_LLaMA2.ipynbindex 03a4f6310f..c5eeacb825 100644--- a/cookbook/Semi_structured_multi_modal_RAG_LLaMA2.ipynb+++ b/cookbook/Semi_structured_multi_modal_RAG_LLaMA2.ipynb@@ -92,22 +92,24 @@"path = \"/Users/rlm/Desktop/Papers/LLaVA/\"\n","\n","# Get elements\n",- "raw_pdf_elements = partition_pdf(filename=path+\"LLaVA.pdf\",\n",- " # Using pdf format to find embedded image blocks\n",- " extract_images_in_pdf=True,\n",- " # Use layout model (YOLOX) to get bounding boxes (for tables) and find titles\n",- " # Titles are any sub-section of the document \n",- " infer_table_structure=True, \n",- " # Post processing to aggregate text once we have the title \n",- " chunking_strategy=\"by_title\",\n",- " # Chunking params to aggregate text blocks\n",- " # Attempt to create a new chunk 3800 chars\n",- " # Attempt to keep chunks > 2000 chars \n",- " # Hard max on chunks\n",- " max_characters=4000, \n",- " new_after_n_chars=3800, \n",- " combine_text_under_n_chars=2000,\n",- " image_output_dir_path=path)"+ "raw_pdf_elements = partition_pdf(\n",+ " filename=path + \"LLaVA.pdf\",\n",+ " # Using pdf format to find embedded image blocks\n",+ " extract_images_in_pdf=True,\n",+ " # Use layout model (YOLOX) to get bounding boxes (for tables) and find titles\n",+ " # Titles are any sub-section of the document\n",+ " infer_table_structure=True,\n",+ " # Post processing to aggregate text once we have the title\n",+ " chunking_strategy=\"by_title\",\n",+ " # Chunking params to aggregate text blocks\n",+ " # Attempt to create a new chunk 3800 chars\n",+ " # Attempt to keep chunks > 2000 chars\n",+ " # Hard max on chunks\n",+ " max_characters=4000,\n",+ " new_after_n_chars=3800,\n",+ " combine_text_under_n_chars=2000,\n",+ " image_output_dir_path=path,\n",+ ")"]},{@@ -165,6 +167,7 @@" type: str\n"," text: Any\n","\n",+ "\n","# Categorize by type\n","categorized_elements = []\n","for element in raw_pdf_elements:\n",@@ -219,14 +222,14 @@"metadata": {},"outputs": [],"source": [- "# Prompt \n",- "prompt_text=\"\"\"You are an assistant tasked with summarizing tables and text. \\ \n",+ "# Prompt\n",+ "prompt_text = \"\"\"You are an assistant tasked with summarizing tables and text. \\ \n","Give a concise summary of the table or text. Table or text chunk: {element} \"\"\"\n",- "prompt = ChatPromptTemplate.from_template(prompt_text) \n",+ "prompt = ChatPromptTemplate.from_template(prompt_text)\n","\n",- "# Summary chain \n",+ "# Summary chain\n","model = ChatOllama(model=\"llama2:13b-chat\")\n",- "summarize_chain = {\"element\": lambda x:x} | prompt | model | StrOutputParser()"+ "summarize_chain = {\"element\": lambda x: x} | prompt | model | StrOutputParser()"]},{@@ -327,11 +330,14 @@"# Read each file and store its content in a list\n","img_summaries = []\n","for file_path in file_paths:\n",- " with open(file_path, 'r') as file:\n",+ " with open(file_path, \"r\") as file:\n"," img_summaries.append(file.read())\n","\n","# Clean up residual logging\n",- "cleaned_img_summary = [s.split(\"clip_model_load: total allocated memory: 201.27 MB\\n\\n\", 1)[1].strip() for s in img_summaries]"+ "cleaned_img_summary = [\n",+ " s.split(\"clip_model_load: total allocated memory: 201.27 MB\\n\\n\", 1)[1].strip()\n",+ " for s in img_summaries\n",+ "]"]},{@@ -377,18 +383,17 @@"\n","# The vectorstore to use to index the child chunks\n","vectorstore = Chroma(\n",- " collection_name=\"summaries\",\n",- " embedding_function=GPT4AllEmbeddings()\n",+ " collection_name=\"summaries\", embedding_function=GPT4AllEmbeddings()\n",")\n","\n","# The storage layer for the parent documents\n",- "store = InMemoryStore() # <- Can we extend this to images \n",+ "store = InMemoryStore() # <- Can we extend this to images\n","id_key = \"doc_id\"\n","\n","# The retriever (empty to start)\n","retriever = MultiVectorRetriever(\n",- " vectorstore=vectorstore, \n",- " docstore=store, \n",+ " vectorstore=vectorstore,\n",+ " docstore=store,\n"," id_key=id_key,\n",")"]@@ -412,21 +417,32 @@"source": ["# Add texts\n","doc_ids = [str(uuid.uuid4()) for _ in texts]\n",- "summary_texts = [Document(page_content=s,metadata={id_key: doc_ids[i]}) for i, s in enumerate(text_summaries)]\n",+ "summary_texts = [\n",+ " Document(page_content=s, metadata={id_key: doc_ids[i]})\n",+ " for i, s in enumerate(text_summaries)\n",+ "]\n","retriever.vectorstore.add_documents(summary_texts)\n","retriever.docstore.mset(list(zip(doc_ids, texts)))\n","\n","# Add tables\n","table_ids = [str(uuid.uuid4()) for _ in tables]\n",- "summary_tables = [Document(page_content=s,metadata={id_key: table_ids[i]}) for i, s in enumerate(table_summaries)]\n",+ "summary_tables = [\n",+ " Document(page_content=s, metadata={id_key: table_ids[i]})\n",+ " for i, s in enumerate(table_summaries)\n",+ "]\n","retriever.vectorstore.add_documents(summary_tables)\n","retriever.docstore.mset(list(zip(table_ids, tables)))\n","\n","# Add images\n","img_ids = [str(uuid.uuid4()) for _ in cleaned_img_summary]\n",- "summary_img = [Document(page_content=s,metadata={id_key: img_ids[i]}) for i, s in enumerate(cleaned_img_summary)]\n",+ "summary_img = [\n",+ " Document(page_content=s, metadata={id_key: img_ids[i]})\n",+ " for i, s in enumerate(cleaned_img_summary)\n",+ "]\n","retriever.vectorstore.add_documents(summary_img)\n",- "retriever.docstore.mset(list(zip(img_ids, cleaned_img_summary))) # Store the image summary as the raw document"+ "retriever.docstore.mset(\n",+ " list(zip(img_ids, cleaned_img_summary))\n",+ ") # Store the image summary as the raw document"]},{@@ -484,7 +500,9 @@}],"source": [- "retriever.get_relevant_documents(\"Images / figures with playful and creative examples\")[0]"+ "retriever.get_relevant_documents(\"Images / figures with playful and creative examples\")[\n",+ " 0\n",+ "]"]},{@@ -530,9 +548,9 @@"\n","# RAG pipeline\n","chain = (\n",- " {\"context\": retriever, \"question\": RunnablePassthrough()} \n",- " | prompt \n",- " | model \n",+ " {\"context\": retriever, \"question\": RunnablePassthrough()}\n",+ " | prompt\n",+ " | model\n"," | StrOutputParser()\n",")"]@@ -555,7 +573,9 @@}],"source": [- "chain.invoke(\"What is the performance of LLaVa across across multiple image domains / subjects?\")"+ "chain.invoke(\n",+ " \"What is the performance of LLaVa across across multiple image domains / subjects?\"\n",+ ")"]},{@@ -584,7 +604,9 @@}],"source": [- "chain.invoke(\"Explain any images / figures in the paper with playful and creative examples.\")"+ "chain.invoke(\n",+ " \"Explain any images / figures in the paper with playful and creative examples.\"\n",+ ")"]},{diff --git a/cookbook/code-analysis-deeplake.ipynb b/cookbook/code-analysis-deeplake.ipynbindex dd227dc4f3..41f22db2f6 100644--- a/cookbook/code-analysis-deeplake.ipynb+++ b/cookbook/code-analysis-deeplake.ipynb@@ -837,7 +837,9 @@"from langchain.chat_models import ChatOpenAI\n","from langchain.chains import ConversationalRetrievalChain\n","\n",- "model = ChatOpenAI(model_name=\"gpt-3.5-turbo-0613\") # 'ada' 'gpt-3.5-turbo-0613' 'gpt-4',\n",+ "model = ChatOpenAI(\n",+ " model_name=\"gpt-3.5-turbo-0613\"\n",+ ") # 'ada' 'gpt-3.5-turbo-0613' 'gpt-4',\n","qa = ConversationalRetrievalChain.from_llm(model, retriever=retriever)"]},diff --git a/cookbook/hugginggpt.ipynb b/cookbook/hugginggpt.ipynbindex 2410c2390b..41fe127f0b 100644--- a/cookbook/hugginggpt.ipynb+++ b/cookbook/hugginggpt.ipynb@@ -77,6 +77,7 @@"source": ["from langchain.llms import OpenAI\n","from langchain_experimental.autonomous_agents import HuggingGPT\n",+ "\n","# %env OPENAI_API_BASE=http://localhost:8000/v1"]},diff --git a/cookbook/learned_prompt_optimization.ipynb b/cookbook/learned_prompt_optimization.ipynbindex 8ce0f7ef3e..1b0a5e35b3 100644--- a/cookbook/learned_prompt_optimization.ipynb+++ b/cookbook/learned_prompt_optimization.ipynb@@ -50,6 +50,7 @@"# pick and configure the LLM of your choice\n","\n","from langchain.llms import OpenAI\n",+ "\n","llm = OpenAI(model=\"text-davinci-003\")"]},@@ -85,8 +86,8 @@"\"\"\"\n","\n","PROMPT = PromptTemplate(\n",- " input_variables=[\"meal\", \"text_to_personalize\", \"user\", \"preference\"], \n",- " template=PROMPT_TEMPLATE\n",+ " input_variables=[\"meal\", \"text_to_personalize\", \"user\", \"preference\"],\n",+ " template=PROMPT_TEMPLATE,\n",")"]},@@ -105,7 +106,7 @@"source": ["import langchain_experimental.rl_chain as rl_chain\n","\n",- "chain = rl_chain.PickBest.from_llm(llm=llm, prompt=PROMPT)\n"+ "chain = rl_chain.PickBest.from_llm(llm=llm, prompt=PROMPT)"]},{@@ -122,10 +123,10 @@"outputs": [],"source": ["response = chain.run(\n",- " meal = rl_chain.ToSelectFrom(meals),\n",- " user = rl_chain.BasedOn(\"Tom\"),\n",- " preference = rl_chain.BasedOn([\"Vegetarian\", \"regular dairy is ok\"]),\n",- " text_to_personalize = \"This is the weeks specialty dish, our master chefs \\\n",+ " meal=rl_chain.ToSelectFrom(meals),\n",+ " user=rl_chain.BasedOn(\"Tom\"),\n",+ " preference=rl_chain.BasedOn([\"Vegetarian\", \"regular dairy is ok\"]),\n",+ " text_to_personalize=\"This is the weeks specialty dish, our master chefs \\\n"," believe you will love it!\",\n",")"]@@ -193,10 +194,10 @@"for _ in range(5):\n"," try:\n"," response = chain.run(\n",- " meal = rl_chain.ToSelectFrom(meals),\n",- " user = rl_chain.BasedOn(\"Tom\"),\n",- " preference = rl_chain.BasedOn([\"Vegetarian\", \"regular dairy is ok\"]),\n",- " text_to_personalize = \"This is the weeks specialty dish, our master chefs believe you will love it!\",\n",+ " meal=rl_chain.ToSelectFrom(meals),\n",+ " user=rl_chain.BasedOn(\"Tom\"),\n",+ " preference=rl_chain.BasedOn([\"Vegetarian\", \"regular dairy is ok\"]),\n",+ " text_to_personalize=\"This is the weeks specialty dish, our master chefs believe you will love it!\",\n"," )\n"," except Exception as e:\n"," print(e)\n",@@ -223,12 +224,16 @@"metadata": {},"outputs": [],"source": [- "scoring_criteria_template = \"Given {preference} rank how good or bad this selection is {meal}\"\n",+ "scoring_criteria_template = (\n",+ " \"Given {preference} rank how good or bad this selection is {meal}\"\n",+ ")\n","\n","chain = rl_chain.PickBest.from_llm(\n"," llm=llm,\n"," prompt=PROMPT,\n",- " selection_scorer=rl_chain.AutoSelectionScorer(llm=llm, scoring_criteria_template_str=scoring_criteria_template),\n",+ " selection_scorer=rl_chain.AutoSelectionScorer(\n",+ " llm=llm, scoring_criteria_template_str=scoring_criteria_template\n",+ " ),\n",")"]},@@ -255,14 +260,16 @@],"source": ["response = chain.run(\n",- " meal = rl_chain.ToSelectFrom(meals),\n",- " user = rl_chain.BasedOn(\"Tom\"),\n",- " preference = rl_chain.BasedOn([\"Vegetarian\", \"regular dairy is ok\"]),\n",- " text_to_personalize = \"This is the weeks specialty dish, our master chefs believe you will love it!\",\n",+ " meal=rl_chain.ToSelectFrom(meals),\n",+ " user=rl_chain.BasedOn(\"Tom\"),\n",+ " preference=rl_chain.BasedOn([\"Vegetarian\", \"regular dairy is ok\"]),\n",+ " text_to_personalize=\"This is the weeks specialty dish, our master chefs believe you will love it!\",\n",")\n","print(response[\"response\"])\n","selection_metadata = response[\"selection_metadata\"]\n",- "print(f\"selected index: {selection_metadata.selected.index}, score: {selection_metadata.selected.score}\")"+ "print(\n",+ " f\"selected index: {selection_metadata.selected.index}, score: {selection_metadata.selected.score}\"\n",+ ")"]},{@@ -280,8 +287,8 @@"source": ["class CustomSelectionScorer(rl_chain.SelectionScorer):\n"," def score_response(\n",- " self, inputs, llm_response: str, event: rl_chain.PickBestEvent) -> float:\n",- "\n",+ " self, inputs, llm_response: str, event: rl_chain.PickBestEvent\n",+ " ) -> float:\n"," print(event.based_on)\n"," print(event.to_select_from)\n","\n",@@ -336,10 +343,10 @@],"source": ["response = chain.run(\n",- " meal = rl_chain.ToSelectFrom(meals),\n",- " user = rl_chain.BasedOn(\"Tom\"),\n",- " preference = rl_chain.BasedOn([\"Vegetarian\", \"regular dairy is ok\"]),\n",- " text_to_personalize = \"This is the weeks specialty dish, our master chefs believe you will love it!\",\n",+ " meal=rl_chain.ToSelectFrom(meals),\n",+ " user=rl_chain.BasedOn(\"Tom\"),\n",+ " preference=rl_chain.BasedOn([\"Vegetarian\", \"regular dairy is ok\"]),\n",+ " text_to_personalize=\"This is the weeks specialty dish, our master chefs believe you will love it!\",\n",")"]},@@ -370,9 +377,10 @@" return 1.0\n"," else:\n"," return 0.0\n",- " def score_response(\n",- " self, inputs, llm_response: str, event: rl_chain.PickBestEvent) -> float:\n","\n",+ " def score_response(\n",+ " self, inputs, llm_response: str, event: rl_chain.PickBestEvent\n",+ " ) -> float:\n"," selected_meal = event.to_select_from[\"meal\"][event.selected.index]\n","\n"," if \"Tom\" in event.based_on[\"user\"]:\n",@@ -394,7 +402,7 @@" prompt=PROMPT,\n"," selection_scorer=CustomSelectionScorer(),\n"," metrics_step=5,\n",- " metrics_window_size=5, # rolling window average\n",+ " metrics_window_size=5, # rolling window average\n",")\n","\n","random_chain = rl_chain.PickBest.from_llm(\n",@@ -402,8 +410,8 @@" prompt=PROMPT,\n"," selection_scorer=CustomSelectionScorer(),\n"," metrics_step=5,\n",- " metrics_window_size=5, # rolling window average\n",- " policy=rl_chain.PickBestRandomPolicy # set the random policy instead of default\n",+ " metrics_window_size=5, # rolling window average\n",+ " policy=rl_chain.PickBestRandomPolicy, # set the random policy instead of default\n",")"]},@@ -416,29 +424,29 @@"for _ in range(20):\n"," try:\n"," chain.run(\n",- " meal = rl_chain.ToSelectFrom(meals),\n",- " user = rl_chain.BasedOn(\"Tom\"),\n",- " preference = rl_chain.BasedOn([\"Vegetarian\", \"regular dairy is ok\"]),\n",- " text_to_personalize = \"This is the weeks specialty dish, our master chefs believe you will love it!\",\n",+ " meal=rl_chain.ToSelectFrom(meals),\n",+ " user=rl_chain.BasedOn(\"Tom\"),\n",+ " preference=rl_chain.BasedOn([\"Vegetarian\", \"regular dairy is ok\"]),\n",+ " text_to_personalize=\"This is the weeks specialty dish, our master chefs believe you will love it!\",\n"," )\n"," random_chain.run(\n",- " meal = rl_chain.ToSelectFrom(meals),\n",- " user = rl_chain.BasedOn(\"Tom\"),\n",- " preference = rl_chain.BasedOn([\"Vegetarian\", \"regular dairy is ok\"]),\n",- " text_to_personalize = \"This is the weeks specialty dish, our master chefs believe you will love it!\",\n",+ " meal=rl_chain.ToSelectFrom(meals),\n",+ " user=rl_chain.BasedOn(\"Tom\"),\n",+ " preference=rl_chain.BasedOn([\"Vegetarian\", \"regular dairy is ok\"]),\n",+ " text_to_personalize=\"This is the weeks specialty dish, our master chefs believe you will love it!\",\n"," )\n",- " \n",+ "\n"," chain.run(\n",- " meal = rl_chain.ToSelectFrom(meals),\n",- " user = rl_chain.BasedOn(\"Anna\"),\n",- " preference = rl_chain.BasedOn([\"Loves meat\", \"especially beef\"]),\n",- " text_to_personalize = \"This is the weeks specialty dish, our master chefs believe you will love it!\",\n",+ " meal=rl_chain.ToSelectFrom(meals),\n",+ " user=rl_chain.BasedOn(\"Anna\"),\n",+ " preference=rl_chain.BasedOn([\"Loves meat\", \"especially beef\"]),\n",+ " text_to_personalize=\"This is the weeks specialty dish, our master chefs believe you will love it!\",\n"," )\n"," random_chain.run(\n",- " meal = rl_chain.ToSelectFrom(meals),\n",- " user = rl_chain.BasedOn(\"Anna\"),\n",- " preference = rl_chain.BasedOn([\"Loves meat\", \"especially beef\"]),\n",- " text_to_personalize = \"This is the weeks specialty dish, our master chefs believe you will love it!\",\n",+ " meal=rl_chain.ToSelectFrom(meals),\n",+ " user=rl_chain.BasedOn(\"Anna\"),\n",+ " preference=rl_chain.BasedOn([\"Loves meat\", \"especially beef\"]),\n",+ " text_to_personalize=\"This is the weeks specialty dish, our master chefs believe you will love it!\",\n"," )\n"," except Exception as e:\n"," print(e)"@@ -477,12 +485,17 @@],"source": ["from matplotlib import pyplot as plt\n",- "chain.metrics.to_pandas()['score'].plot(label=\"default learning policy\")\n",- "random_chain.metrics.to_pandas()['score'].plot(label=\"random selection policy\")\n",+ "\n",+ "chain.metrics.to_pandas()[\"score\"].plot(label=\"default learning policy\")\n",+ "random_chain.metrics.to_pandas()[\"score\"].plot(label=\"random selection policy\")\n","plt.legend()\n","\n",- "print(f\"The final average score for the default policy, calculated over a rolling window, is: {chain.metrics.to_pandas()['score'].iloc[-1]}\")\n",- "print(f\"The final average score for the random policy, calculated over a rolling window, is: {random_chain.metrics.to_pandas()['score'].iloc[-1]}\")"+ "print(\n",+ " f\"The final average score for the default policy, calculated over a rolling window, is: {chain.metrics.to_pandas()['score'].iloc[-1]}\"\n",+ ")\n",+ "print(\n",+ " f\"The final average score for the random policy, calculated over a rolling window, is: {random_chain.metrics.to_pandas()['score'].iloc[-1]}\"\n",+ ")"]},{@@ -803,10 +816,10 @@")\n","\n","chain.run(\n",- " meal = rl_chain.ToSelectFrom(meals),\n",- " user = rl_chain.BasedOn(\"Tom\"),\n",- " preference = rl_chain.BasedOn([\"Vegetarian\", \"regular dairy is ok\"]),\n",- " text_to_personalize = \"This is the weeks specialty dish, our master chefs believe you will love it!\",\n",+ " meal=rl_chain.ToSelectFrom(meals),\n",+ " user=rl_chain.BasedOn(\"Tom\"),\n",+ " preference=rl_chain.BasedOn([\"Vegetarian\", \"regular dairy is ok\"]),\n",+ " text_to_personalize=\"This is the weeks specialty dish, our master chefs believe you will love it!\",\n",")"]}diff --git a/cookbook/myscale_vector_sql.ipynb b/cookbook/myscale_vector_sql.ipynbindex bc7044eb17..091b3e42df 100644--- a/cookbook/myscale_vector_sql.ipynb+++ b/cookbook/myscale_vector_sql.ipynb@@ -27,11 +27,12 @@"metadata": {},"outputs": [],"source": [- "\n","from os import environ\n","import getpass\n","from typing import Dict, Any\n",- "from langchain.llms import OpenAI\nfrom langchain.utilities import SQLDatabase\nfrom langchain.chains import LLMChain\n",+ "from langchain.llms import OpenAI\n",+ "from langchain.utilities import SQLDatabase\n",+ "from langchain.chains import LLMChain\n","from langchain_experimental.sql.vector_sql import VectorSQLDatabaseChain\n","from sqlalchemy import create_engine, Column, MetaData\n","from langchain.prompts import PromptTemplate\n",@@ -76,7 +77,6 @@"metadata": {},"outputs": [],"source": [- "\n","from langchain.llms import OpenAI\n","from langchain.callbacks import StdOutCallbackHandler\n","\n",@@ -124,8 +124,9 @@"from langchain.chains.qa_with_sources.retrieval import RetrievalQAWithSourcesChain\n","\n","from langchain_experimental.sql.vector_sql import VectorSQLDatabaseChain\n",- "from langchain_experimental.retrievers.vector_sql_database \\\n",- " import VectorSQLDatabaseChainRetriever\n",+ "from langchain_experimental.retrievers.vector_sql_database import (\n",+ " VectorSQLDatabaseChainRetriever,\n",+ ")\n","from langchain_experimental.sql.prompt import MYSCALE_PROMPT\n","from langchain_experimental.sql.vector_sql import VectorSQLRetrieveAllOutputParser\n","\n",@@ -144,7 +145,9 @@")\n","\n","# You need all those keys to get docs\n",- "retriever = VectorSQLDatabaseChainRetriever(sql_db_chain=chain, page_content_key=\"abstract\")\n",+ "retriever = VectorSQLDatabaseChainRetriever(\n",+ " sql_db_chain=chain, page_content_key=\"abstract\"\n",+ ")\n","\n","document_with_metadata_prompt = PromptTemplate(\n"," input_variables=[\"page_content\", \"id\", \"title\", \"authors\", \"pubdate\", \"categories\"],\n",@@ -162,8 +165,10 @@" },\n"," return_source_documents=True,\n",")\n",- "ans = chain(\"Please give me 10 papers to ask what is PageRank?\",\n",- " callbacks=[StdOutCallbackHandler()])\n",+ "ans = chain(\n",+ " \"Please give me 10 papers to ask what is PageRank?\",\n",+ " callbacks=[StdOutCallbackHandler()],\n",+ ")\n","print(ans[\"answer\"])"]},diff --git a/cookbook/plan_and_execute_agent.ipynb b/cookbook/plan_and_execute_agent.ipynbindex 81145f970a..2fa14881e3 100644--- a/cookbook/plan_and_execute_agent.ipynb+++ b/cookbook/plan_and_execute_agent.ipynb@@ -34,7 +34,11 @@"from langchain.chat_models import ChatOpenAI\n","from langchain.llms import OpenAI\n","from langchain.utilities import DuckDuckGoSearchAPIWrapper\n",- "from langchain_experimental.plan_and_execute import PlanAndExecute, load_agent_executor, load_chat_planner"+ "from langchain_experimental.plan_and_execute import (\n",+ " PlanAndExecute,\n",+ " load_agent_executor,\n",+ " load_chat_planner,\n",+ ")"]},{@@ -56,16 +60,16 @@"llm = OpenAI(temperature=0)\n","llm_math_chain = LLMMathChain.from_llm(llm=llm, verbose=True)\n","tools = [\n",- " Tool(\n",- " name=\"Search\",\n",- " func=search.run,\n",- " description=\"useful for when you need to answer questions about current events\"\n",- " ),\n",- " Tool(\n",- " name=\"Calculator\",\n",- " func=llm_math_chain.run,\n",- " description=\"useful for when you need to answer questions about math\"\n",- " ),\n",+ " Tool(\n",+ " name=\"Search\",\n",+ " func=search.run,\n",+ " description=\"useful for when you need to answer questions about current events\",\n",+ " ),\n",+ " Tool(\n",+ " name=\"Calculator\",\n",+ " func=llm_math_chain.run,\n",+ " description=\"useful for when you need to answer questions about math\",\n",+ " ),\n","]"]},@@ -216,7 +220,9 @@}],"source": [- "agent.run(\"Who is the current prime minister of the UK? What is their current age raised to the 0.43 power?\")"+ "agent.run(\n",+ " \"Who is the current prime minister of the UK? What is their current age raised to the 0.43 power?\"\n",+ ")"]},{diff --git a/cookbook/press_releases.ipynb b/cookbook/press_releases.ipynbindex f4ab436727..beb89f10c4 100644--- a/cookbook/press_releases.ipynb+++ b/cookbook/press_releases.ipynb@@ -55,6 +55,7 @@"source": ["# Setup API keys for Kay and OpenAI\n","from getpass import getpass\n",+ "\n","KAY_API_KEY = getpass()\n","OPENAI_API_KEY = getpass()"]@@ -67,6 +68,7 @@"outputs": [],"source": ["import os\n",+ "\n","os.environ[\"KAY_API_KEY\"] = KAY_API_KEY\n","os.environ[\"OPENAI_API_KEY\"] = OPENAI_API_KEY"]@@ -83,7 +85,9 @@"from langchain.retrievers import KayAiRetriever\n","\n","model = ChatOpenAI(model_name=\"gpt-3.5-turbo\")\n",- "retriever = KayAiRetriever.create(dataset_id=\"company\", data_types=[\"PressRelease\"], num_contexts=6)\n",+ "retriever = KayAiRetriever.create(\n",+ " dataset_id=\"company\", data_types=[\"PressRelease\"], num_contexts=6\n",+ ")\n","qa = ConversationalRetrievalChain.from_llm(model, retriever=retriever)"]},@@ -116,7 +120,7 @@"# More sample questions in the Playground on https://kay.ai\n","questions = [\n"," \"How is the healthcare industry adopting generative AI tools?\",\n",- " #\"What are some recent challenges faced by the renewable energy sector?\",\n",+ " # \"What are some recent challenges faced by the renewable energy sector?\",\n","]\n","chat_history = []\n","\n",diff --git a/cookbook/rag_fusion.ipynb b/cookbook/rag_fusion.ipynbindex b8b76e28a3..388e37026b 100644--- a/cookbook/rag_fusion.ipynb+++ b/cookbook/rag_fusion.ipynb@@ -33,7 +33,7 @@"from langchain.vectorstores import Pinecone\n","from langchain.embeddings import OpenAIEmbeddings\n","\n",- "pinecone.init(api_key=\"...\",environment=\"...\")"+ "pinecone.init(api_key=\"...\", environment=\"...\")"]},{@@ -53,7 +53,7 @@" \"doc7\": \"Climate change: The science and models.\",\n"," \"doc8\": \"Global warming: A subset of climate change.\",\n"," \"doc9\": \"How climate change affects daily weather.\",\n",- " \"doc10\": \"The history of climate change activism.\"\n",+ " \"doc10\": \"The history of climate change activism.\",\n","}"]},@@ -64,7 +64,9 @@"metadata": {},"outputs": [],"source": [- "vectorstore = Pinecone.from_texts(list(all_documents.values()), OpenAIEmbeddings(), index_name='rag-fusion')"+ "vectorstore = Pinecone.from_texts(\n",+ " list(all_documents.values()), OpenAIEmbeddings(), index_name=\"rag-fusion\"\n",+ ")"]},{@@ -98,7 +100,7 @@"source": ["from langchain import hub\n","\n",- "prompt = hub.pull('langchain-ai/rag-fusion-query-generation')"+ "prompt = hub.pull(\"langchain-ai/rag-fusion-query-generation\")"]},{@@ -122,7 +124,9 @@"metadata": {},"outputs": [],"source": [- "generate_queries = prompt | ChatOpenAI(temperature=0) | StrOutputParser() | (lambda x: x.split(\"\\n\"))"+ "generate_queries = (\n",+ " prompt | ChatOpenAI(temperature=0) | StrOutputParser() | (lambda x: x.split(\"\\n\"))\n",+ ")"]},{@@ -171,6 +175,8 @@"outputs": [],"source": ["from langchain.load import dumps, loads\n",+ "\n",+ "\n","def reciprocal_rank_fusion(results: list[list], k=60):\n"," fused_scores = {}\n"," for docs in results:\n",@@ -181,9 +187,12 @@" fused_scores[doc_str] = 0\n"," previous_score = fused_scores[doc_str]\n"," fused_scores[doc_str] += 1 / (rank + k)\n",- " \n",- " reranked_results = [(loads(doc), score) for doc, score in sorted(fused_scores.items(), key=lambda x: x[1], reverse=True)]\n",- " return reranked_results "+ "\n",+ " reranked_results = [\n",+ " (loads(doc), score)\n",+ " for doc, score in sorted(fused_scores.items(), key=lambda x: x[1], reverse=True)\n",+ " ]\n",+ " return reranked_results"]},{diff --git a/cookbook/rewrite.ipynb b/cookbook/rewrite.ipynbindex 7429e6473d..3bd2968a28 100644--- a/cookbook/rewrite.ipynb+++ b/cookbook/rewrite.ipynb@@ -74,9 +74,9 @@"outputs": [],"source": ["chain = (\n",- " {\"context\": retriever, \"question\": RunnablePassthrough()} \n",- " | prompt \n",- " | model \n",+ " {\"context\": retriever, \"question\": RunnablePassthrough()}\n",+ " | prompt\n",+ " | model\n"," | StrOutputParser()\n",")"]@@ -245,6 +245,7 @@"source": ["# Parser to remove the `**`\n","\n",+ "\n","def _parse(text):\n"," return text.strip(\"**\")"]@@ -290,9 +291,10 @@"rewrite_retrieve_read_chain = (\n"," {\n"," \"context\": {\"x\": RunnablePassthrough()} | rewriter | retriever,\n",- " \"question\": RunnablePassthrough()} \n",- " | prompt \n",- " | model \n",+ " \"question\": RunnablePassthrough(),\n",+ " }\n",+ " | prompt\n",+ " | model\n"," | StrOutputParser()\n",")"]diff --git a/cookbook/selecting_llms_based_on_context_length.ipynb b/cookbook/selecting_llms_based_on_context_length.ipynbindex a166acffc1..7637983c9b 100644--- a/cookbook/selecting_llms_based_on_context_length.ipynb+++ b/cookbook/selecting_llms_based_on_context_length.ipynb@@ -139,7 +139,9 @@}],"source": [- "chain.invoke({\"context\": \"a frog went to a pond and sat on a log and went to a different pond\"})"+ "chain.invoke(\n",+ " {\"context\": \"a frog went to a pond and sat on a log and went to a different pond\"}\n",+ ")"]},{diff --git a/cookbook/self_query_hotel_search.ipynb b/cookbook/self_query_hotel_search.ipynbindex 68b08dae91..58c15430ea 100644--- a/cookbook/self_query_hotel_search.ipynb+++ b/cookbook/self_query_hotel_search.ipynb@@ -51,8 +51,14 @@"metadata": {},"outputs": [],"source": [- "details = pd.read_csv(\"~/Downloads/archive/Hotel_details.csv\").drop_duplicates(subset=\"hotelid\").set_index(\"hotelid\")\n",- "attributes = pd.read_csv(\"~/Downloads/archive/Hotel_Room_attributes.csv\", index_col=\"id\")\n",+ "details = (\n",+ " pd.read_csv(\"~/Downloads/archive/Hotel_details.csv\")\n",+ " .drop_duplicates(subset=\"hotelid\")\n",+ " .set_index(\"hotelid\")\n",+ ")\n",+ "attributes = pd.read_csv(\n",+ " \"~/Downloads/archive/Hotel_Room_attributes.csv\", index_col=\"id\"\n",+ ")\n","price = pd.read_csv(\"~/Downloads/archive/hotels_RoomPrice.csv\", index_col=\"id\")"]},@@ -208,9 +214,20 @@}],"source": [- "latest_price = price.drop_duplicates(subset=\"refid\", keep=\"last\")[[\"hotelcode\", \"roomtype\", \"onsiterate\", \"roomamenities\", \"maxoccupancy\", \"mealinclusiontype\"]]\n",+ "latest_price = price.drop_duplicates(subset=\"refid\", keep=\"last\")[\n",+ " [\n",+ " \"hotelcode\",\n",+ " \"roomtype\",\n",+ " \"onsiterate\",\n",+ " \"roomamenities\",\n",+ " \"maxoccupancy\",\n",+ " \"mealinclusiontype\",\n",+ " ]\n",+ "]\n","latest_price[\"ratedescription\"] = attributes.loc[latest_price.index][\"ratedescription\"]\n",- "latest_price = latest_price.join(details[[\"hotelname\", \"city\", \"country\", \"starrating\"]], on=\"hotelcode\")\n",+ "latest_price = latest_price.join(\n",+ " details[[\"hotelname\", \"city\", \"country\", \"starrating\"]], on=\"hotelcode\"\n",+ ")\n","latest_price = latest_price.rename({\"ratedescription\": \"roomdescription\"}, axis=1)\n","latest_price[\"mealsincluded\"] = ~latest_price[\"mealinclusiontype\"].isnull()\n","latest_price.pop(\"hotelcode\")\n",@@ -244,7 +261,7 @@"res = model.predict(\n"," \"Below is a table with information about hotel rooms. \"\n"," \"Return a JSON list with an entry for each column. Each entry should have \"\n",- " \"{\\\"name\\\": \\\"column name\\\", \\\"description\\\": \\\"column description\\\", \\\"type\\\": \\\"column data type\\\"}\"\n",+ " '{\"name\": \"column name\", \"description\": \"column description\", \"type\": \"column data type\"}'\n"," f\"\\n\\n{latest_price.head()}\\n\\nJSON:\\n\"\n",")"]@@ -338,9 +355,15 @@"metadata": {},"outputs": [],"source": [- "attribute_info[-2]['description'] += f\". Valid values are {sorted(latest_price['starrating'].value_counts().index.tolist())}\"\n",- "attribute_info[3]['description'] += f\". Valid values are {sorted(latest_price['maxoccupancy'].value_counts().index.tolist())}\"\n",- "attribute_info[-3]['description'] += f\". Valid values are {sorted(latest_price['country'].value_counts().index.tolist())}\""+ "attribute_info[-2][\n",+ " \"description\"\n",+ "] += f\". Valid values are {sorted(latest_price['starrating'].value_counts().index.tolist())}\"\n",+ "attribute_info[3][\n",+ " \"description\"\n",+ "] += f\". Valid values are {sorted(latest_price['maxoccupancy'].value_counts().index.tolist())}\"\n",+ "attribute_info[-3][\n",+ " \"description\"\n",+ "] += f\". Valid values are {sorted(latest_price['country'].value_counts().index.tolist())}\""]},{@@ -408,7 +431,10 @@"metadata": {},"outputs": [],"source": [- "from langchain.chains.query_constructor.base import get_query_constructor_prompt, load_query_constructor_runnable"+ "from langchain.chains.query_constructor.base import (\n",+ " get_query_constructor_prompt,\n",+ " load_query_constructor_runnable,\n",+ ")"]},{@@ -592,7 +618,9 @@"metadata": {},"outputs": [],"source": [- "chain = load_query_constructor_runnable(ChatOpenAI(model='gpt-3.5-turbo', temperature=0), doc_contents, attribute_info)"+ "chain = load_query_constructor_runnable(\n",+ " ChatOpenAI(model=\"gpt-3.5-turbo\", temperature=0), doc_contents, attribute_info\n",+ ")"]},{@@ -634,7 +662,11 @@}],"source": [- "chain.invoke({\"query\": \"Find a 2-person room in Vienna or London, preferably with meals included and AC\"})"+ "chain.invoke(\n",+ " {\n",+ " \"query\": \"Find a 2-person room in Vienna or London, preferably with meals included and AC\"\n",+ " }\n",+ ")"]},{@@ -656,10 +688,12 @@"metadata": {},"outputs": [],"source": [- "attribute_info[-3]['description'] += \". NOTE: Only use the 'eq' operator if a specific country is mentioned. If a region is mentioned, include all relevant countries in filter.\"\n",+ "attribute_info[-3][\n",+ " \"description\"\n",+ "] += \". NOTE: Only use the 'eq' operator if a specific country is mentioned. If a region is mentioned, include all relevant countries in filter.\"\n","chain = load_query_constructor_runnable(\n",- " ChatOpenAI(model='gpt-3.5-turbo', temperature=0), \n",- " doc_contents, \n",+ " ChatOpenAI(model=\"gpt-3.5-turbo\", temperature=0),\n",+ " doc_contents,\n"," attribute_info,\n",")"]@@ -704,10 +738,12 @@"source": ["content_attr = [\"roomtype\", \"roomamenities\", \"roomdescription\", \"hotelname\"]\n","doc_contents = \"A detailed description of a hotel room, including information about the room type and room amenities.\"\n",- "filter_attribute_info = tuple(ai for ai in attribute_info if ai[\"name\"] not in content_attr)\n",+ "filter_attribute_info = tuple(\n",+ " ai for ai in attribute_info if ai[\"name\"] not in content_attr\n",+ ")\n","chain = load_query_constructor_runnable(\n",- " ChatOpenAI(model='gpt-3.5-turbo', temperature=0), \n",- " doc_contents, \n",+ " ChatOpenAI(model=\"gpt-3.5-turbo\", temperature=0),\n",+ " doc_contents,\n"," filter_attribute_info,\n",")"]@@ -730,7 +766,11 @@}],"source": [- "chain.invoke({\"query\": \"Find a 2-person room in Vienna or London, preferably with meals included and AC\"})"+ "chain.invoke(\n",+ " {\n",+ " \"query\": \"Find a 2-person room in Vienna or London, preferably with meals included and AC\"\n",+ " }\n",+ ")"]},{@@ -860,14 +900,22 @@"examples = [\n"," (\n"," \"I want a hotel in the Balkans with a king sized bed and a hot tub. Budget is $300 a night\",\n",- " {\"query\": \"king-sized bed, hot tub\", \"filter\": 'and(in(\"country\", [\"Bulgaria\", \"Greece\", \"Croatia\", \"Serbia\"]), lte(\"onsiterate\", 300))'}\n",+ " {\n",+ " \"query\": \"king-sized bed, hot tub\",\n",+ " \"filter\": 'and(in(\"country\", [\"Bulgaria\", \"Greece\", \"Croatia\", \"Serbia\"]), lte(\"onsiterate\", 300))',\n",+ " },\n"," ),\n"," (\n"," \"A room with breakfast included for 3 people, at a Hilton\",\n",- " {\"query\": \"Hilton\", \"filter\": 'and(eq(\"mealsincluded\", true), gte(\"maxoccupancy\", 3))'}\n",+ " {\n",+ " \"query\": \"Hilton\",\n",+ " \"filter\": 'and(eq(\"mealsincluded\", true), gte(\"maxoccupancy\", 3))',\n",+ " },\n"," ),\n","]\n",- "prompt = get_query_constructor_prompt(doc_contents, filter_attribute_info, examples=examples)\n",+ "prompt = get_query_constructor_prompt(\n",+ " doc_contents, filter_attribute_info, examples=examples\n",+ ")\n","print(prompt.format(query=\"{query}\"))"]},@@ -879,10 +927,10 @@"outputs": [],"source": ["chain = load_query_constructor_runnable(\n",- " ChatOpenAI(model='gpt-3.5-turbo', temperature=0), \n",- " doc_contents, \n",+ " ChatOpenAI(model=\"gpt-3.5-turbo\", temperature=0),\n",+ " doc_contents,\n"," filter_attribute_info,\n",- " examples=examples\n",+ " examples=examples,\n",")"]},@@ -904,7 +952,11 @@}],"source": [- "chain.invoke({\"query\": \"Find a 2-person room in Vienna or London, preferably with meals included and AC\"})"+ "chain.invoke(\n",+ " {\n",+ " \"query\": \"Find a 2-person room in Vienna or London, preferably with meals included and AC\"\n",+ " }\n",+ ")"]},{@@ -956,7 +1008,11 @@}],"source": [- "chain.invoke({\"query\": \"I want to stay somewhere highly rated along the coast. I want a room with a patio and a fireplace.\"})"+ "chain.invoke(\n",+ " {\n",+ " \"query\": \"I want to stay somewhere highly rated along the coast. I want a room with a patio and a fireplace.\"\n",+ " }\n",+ ")"]},{@@ -977,11 +1033,11 @@"outputs": [],"source": ["chain = load_query_constructor_runnable(\n",- " ChatOpenAI(model='gpt-3.5-turbo', temperature=0), \n",- " doc_contents, \n",+ " ChatOpenAI(model=\"gpt-3.5-turbo\", temperature=0),\n",+ " doc_contents,\n"," filter_attribute_info,\n"," examples=examples,\n",- " fix_invalid=True\n",+ " fix_invalid=True,\n",")"]},@@ -1003,7 +1059,11 @@}],"source": [- "chain.invoke({\"query\": \"I want to stay somewhere highly rated along the coast. I want a room with a patio and a fireplace.\"})"+ "chain.invoke(\n",+ " {\n",+ " \"query\": \"I want to stay somewhere highly rated along the coast. I want a room with a patio and a fireplace.\"\n",+ " }\n",+ ")"]},{@@ -1056,8 +1116,8 @@"# docs.append(doc)\n","# vecstore = ElasticsearchStore.from_documents(\n","# docs,\n",- "# embeddings, \n",- "# es_url=\"http://localhost:9200\", \n",+ "# embeddings,\n",+ "# es_url=\"http://localhost:9200\",\n","# index_name=\"hotel_rooms\",\n","# # strategy=ElasticsearchStore.ApproxRetrievalStrategy(\n","# # hybrid=True,\n",@@ -1073,9 +1133,9 @@"outputs": [],"source": ["vecstore = ElasticsearchStore(\n",- " \"hotel_rooms\", \n",- " embedding=embeddings, \n",- " es_url=\"http://localhost:9200\", \n",+ " \"hotel_rooms\",\n",+ " embedding=embeddings,\n",+ " es_url=\"http://localhost:9200\",\n"," # strategy=ElasticsearchStore.ApproxRetrievalStrategy(hybrid=True) # seems to not be available in community version\n",")"]@@ -1089,7 +1149,9 @@"source": ["from langchain.retrievers import SelfQueryRetriever\n","\n",- "retriever = SelfQueryRetriever(query_constructor=chain, vectorstore=vecstore, verbose=True)"+ "retriever = SelfQueryRetriever(\n",+ " query_constructor=chain, vectorstore=vecstore, verbose=True\n",+ ")"]},{diff --git a/cookbook/stepback-qa.ipynb b/cookbook/stepback-qa.ipynbindex a77e2d5652..336527cf20 100644--- a/cookbook/stepback-qa.ipynb+++ b/cookbook/stepback-qa.ipynb@@ -40,11 +40,11 @@"examples = [\n"," {\n"," \"input\": \"Could the members of The Police perform lawful arrests?\",\n",- " \"output\": \"what can the members of The Police do?\"\n",+ " \"output\": \"what can the members of The Police do?\",\n"," },\n"," {\n",- " \"input\": \"Jan Sindel’s was born in what country?\", \n",- " \"output\": \"what is Jan Sindel’s personal history?\"\n",+ " \"input\": \"Jan Sindel’s was born in what country?\",\n",+ " \"output\": \"what is Jan Sindel’s personal history?\",\n"," },\n","]\n","# We now transform these to example messages\n",@@ -67,13 +67,18 @@"metadata": {},"outputs": [],"source": [- "prompt = ChatPromptTemplate.from_messages([\n",- " (\"system\", \"\"\"You are an expert at world knowledge. Your task is to step back and paraphrase a question to a more generic step-back question, which is easier to answer. Here are a few examples:\"\"\"),\n",- " # Few shot examples\n",- " few_shot_prompt,\n",- " # New question\n",- " (\"user\", \"{question}\"),\n",- "])"+ "prompt = ChatPromptTemplate.from_messages(\n",+ " [\n",+ " (\n",+ " \"system\",\n",+ " \"\"\"You are an expert at world knowledge. Your task is to step back and paraphrase a question to a more generic step-back question, which is easier to answer. Here are a few examples:\"\"\",\n",+ " ),\n",+ " # Few shot examples\n",+ " few_shot_prompt,\n",+ " # New question\n",+ " (\"user\", \"{question}\"),\n",+ " ]\n",+ ")"]},{@@ -129,6 +134,7 @@"\n","search = DuckDuckGoSearchAPIWrapper(max_results=4)\n","\n",+ "\n","def retriever(query):\n"," return search.run(query)"]@@ -211,14 +217,19 @@"metadata": {},"outputs": [],"source": [- "chain = {\n",- " # Retrieve context using the normal question\n",- " \"normal_context\": RunnableLambda(lambda x: x['question']) | retriever,\n",- " # Retrieve context using the step-back question\n",- " \"step_back_context\": question_gen | retriever,\n",- " # Pass on the question\n",- " \"question\": lambda x: x[\"question\"]\n",- "} | response_prompt | ChatOpenAI(temperature=0) | StrOutputParser()"+ "chain = (\n",+ " {\n",+ " # Retrieve context using the normal question\n",+ " \"normal_context\": RunnableLambda(lambda x: x[\"question\"]) | retriever,\n",+ " # Retrieve context using the step-back question\n",+ " \"step_back_context\": question_gen | retriever,\n",+ " # Pass on the question\n",+ " \"question\": lambda x: x[\"question\"],\n",+ " }\n",+ " | response_prompt\n",+ " | ChatOpenAI(temperature=0)\n",+ " | StrOutputParser()\n",+ ")"]},{@@ -273,12 +284,17 @@"metadata": {},"outputs": [],"source": [- "chain = {\n",- " # Retrieve context using the normal question (only the first 3 results)\n",- " \"normal_context\": RunnableLambda(lambda x: x['question']) | retriever,\n",- " # Pass on the question\n",- " \"question\": lambda x: x[\"question\"]\n",- "} | response_prompt | ChatOpenAI(temperature=0) | StrOutputParser()"+ "chain = (\n",+ " {\n",+ " # Retrieve context using the normal question (only the first 3 results)\n",+ " \"normal_context\": RunnableLambda(lambda x: x[\"question\"]) | retriever,\n",+ " # Pass on the question\n",+ " \"question\": lambda x: x[\"question\"],\n",+ " }\n",+ " | response_prompt\n",+ " | ChatOpenAI(temperature=0)\n",+ " | StrOutputParser()\n",+ ")"]},{diff --git a/cookbook/tree_of_thought.ipynb b/cookbook/tree_of_thought.ipynbindex b6ae199a73..fe1cba0a91 100644--- a/cookbook/tree_of_thought.ipynb+++ b/cookbook/tree_of_thought.ipynb@@ -51,7 +51,7 @@}],"source": [- "sudoku_puzzle = \"3,*,*,2|1,*,3,*|*,1,*,3|4,*,*,1\"\n",+ "sudoku_puzzle = \"3,*,*,2|1,*,3,*|*,1,*,3|4,*,*,1\"\n","sudoku_solution = \"3,4,1,2|1,2,3,4|2,1,4,3|4,3,2,1\"\n","problem_description = f\"\"\"\n","{sudoku_puzzle}\n",@@ -64,7 +64,7 @@"- Keep the known digits from previous valid thoughts in place.\n","- Each thought can be a partial or the final solution.\n","\"\"\".strip()\n",- "print(problem_description)\n"+ "print(problem_description)"]},{@@ -89,8 +89,11 @@"from langchain_experimental.tot.thought import ThoughtValidity\n","import re\n","\n",+ "\n","class MyChecker(ToTChecker):\n",- " def evaluate(self, problem_description: str, thoughts: Tuple[str, ...] = ()) -> ThoughtValidity:\n",+ " def evaluate(\n",+ " self, problem_description: str, thoughts: Tuple[str, ...] = ()\n",+ " ) -> ThoughtValidity:\n"," last_thought = thoughts[-1]\n"," clean_solution = last_thought.replace(\" \", \"\").replace('\"', \"\")\n"," regex_solution = clean_solution.replace(\"*\", \".\").replace(\"|\", \"\\\\|\")\n",@@ -116,10 +119,22 @@"outputs": [],"source": ["checker = MyChecker()\n",- "assert checker.evaluate(\"\", (\"3,*,*,2|1,*,3,*|*,1,*,3|4,*,*,1\",)) == ThoughtValidity.VALID_INTERMEDIATE\n",- "assert checker.evaluate(\"\", (\"3,4,1,2|1,2,3,4|2,1,4,3|4,3,2,1\",)) == ThoughtValidity.VALID_FINAL\n",- "assert checker.evaluate(\"\", (\"3,4,1,2|1,2,3,4|2,1,4,3|4,3,*,1\",)) == ThoughtValidity.VALID_INTERMEDIATE\n",- "assert checker.evaluate(\"\", (\"3,4,1,2|1,2,3,4|2,1,4,3|4,*,3,1\",)) == ThoughtValidity.INVALID"+ "assert (\n",+ " checker.evaluate(\"\", (\"3,*,*,2|1,*,3,*|*,1,*,3|4,*,*,1\",))\n",+ " == ThoughtValidity.VALID_INTERMEDIATE\n",+ ")\n",+ "assert (\n",+ " checker.evaluate(\"\", (\"3,4,1,2|1,2,3,4|2,1,4,3|4,3,2,1\",))\n",+ " == ThoughtValidity.VALID_FINAL\n",+ ")\n",+ "assert (\n",+ " checker.evaluate(\"\", (\"3,4,1,2|1,2,3,4|2,1,4,3|4,3,*,1\",))\n",+ " == ThoughtValidity.VALID_INTERMEDIATE\n",+ ")\n",+ "assert (\n",+ " checker.evaluate(\"\", (\"3,4,1,2|1,2,3,4|2,1,4,3|4,*,3,1\",))\n",+ " == ThoughtValidity.INVALID\n",+ ")"]},{@@ -203,7 +218,9 @@"source": ["from langchain_experimental.tot.base import ToTChain\n","\n",- "tot_chain = ToTChain(llm=llm, checker=MyChecker(), k=30, c=5, verbose=True, verbose_llm=False)\n",+ "tot_chain = ToTChain(\n",+ " llm=llm, checker=MyChecker(), k=30, c=5, verbose=True, verbose_llm=False\n",+ ")\n","tot_chain.run(problem_description=problem_description)"]},diff --git a/docs/api_reference/create_api_rst.py b/docs/api_reference/create_api_rst.pyindex f84c093bd5..3aeb4b0d30 100644--- a/docs/api_reference/create_api_rst.py+++ b/docs/api_reference/create_api_rst.py@@ -2,9 +2,9 @@import importlibimport inspectimport typing-from pathlib import Path-from typing import TypedDict, Sequence, List, Dict, Literal, Union, Optionalfrom enum import Enum+from pathlib import Path+from typing import Dict, List, Literal, Optional, Sequence, TypedDict, Unionfrom pydantic import BaseModeldiff --git a/docs/docs/expression_language/cookbook/agent.ipynb b/docs/docs/expression_language/cookbook/agent.ipynbindex 5be6b9d4d1..2163dd5bf2 100644--- a/docs/docs/expression_language/cookbook/agent.ipynb+++ b/docs/docs/expression_language/cookbook/agent.ipynb@@ -115,7 +115,9 @@"agent = (\n"," {\n"," \"question\": lambda x: x[\"question\"],\n",- " \"intermediate_steps\": lambda x: convert_intermediate_steps(x[\"intermediate_steps\"])\n",+ " \"intermediate_steps\": lambda x: convert_intermediate_steps(\n",+ " x[\"intermediate_steps\"]\n",+ " ),\n"," }\n"," | prompt.partial(tools=convert_tools(tool_list))\n"," | model.bind(stop=[\"</tool_input>\", \"</final_answer>\"])\n",diff --git a/docs/docs/expression_language/cookbook/code_writing.ipynb b/docs/docs/expression_language/cookbook/code_writing.ipynbindex 21ab536012..1b1f2d2fa2 100644--- a/docs/docs/expression_language/cookbook/code_writing.ipynb+++ b/docs/docs/expression_language/cookbook/code_writing.ipynb@@ -18,7 +18,11 @@"outputs": [],"source": ["from langchain.chat_models import ChatOpenAI\n",- "from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate\n",+ "from langchain.prompts import (\n",+ " ChatPromptTemplate,\n",+ " SystemMessagePromptTemplate,\n",+ " HumanMessagePromptTemplate,\n",+ ")\n","from langchain.schema.output_parser import StrOutputParser\n","from langchain_experimental.utilities import PythonREPL"]@@ -37,9 +41,7 @@"```python\n","....\n","```\"\"\"\n",- "prompt = ChatPromptTemplate.from_messages(\n",- " [(\"system\", template), (\"human\", \"{input}\")]\n",- ")\n",+ "prompt = ChatPromptTemplate.from_messages([(\"system\", template), (\"human\", \"{input}\")])\n","\n","model = ChatOpenAI()"]diff --git a/docs/docs/expression_language/cookbook/memory.ipynb b/docs/docs/expression_language/cookbook/memory.ipynbindex 020a710df1..c309c183f9 100644--- a/docs/docs/expression_language/cookbook/memory.ipynb+++ b/docs/docs/expression_language/cookbook/memory.ipynb@@ -24,11 +24,13 @@"from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder\n","\n","model = ChatOpenAI()\n",- "prompt = ChatPromptTemplate.from_messages([\n",- " (\"system\", \"You are a helpful chatbot\"),\n",- " MessagesPlaceholder(variable_name=\"history\"),\n",- " (\"human\", \"{input}\")\n",- "])\n"+ "prompt = ChatPromptTemplate.from_messages(\n",+ " [\n",+ " (\"system\", \"You are a helpful chatbot\"),\n",+ " MessagesPlaceholder(variable_name=\"history\"),\n",+ " (\"human\", \"{input}\"),\n",+ " ]\n",+ ")"]},{@@ -38,7 +40,7 @@"metadata": {},"outputs": [],"source": [- "memory = ConversationBufferMemory(return_messages=True)\n"+ "memory = ConversationBufferMemory(return_messages=True)"]},{@@ -59,7 +61,7 @@}],"source": [- "memory.load_memory_variables({})\n"+ "memory.load_memory_variables({})"]},{@@ -69,9 +71,13 @@"metadata": {},"outputs": [],"source": [- "chain = RunnablePassthrough.assign(\n",- " memory=RunnableLambda(memory.load_memory_variables) | itemgetter(\"history\")\n",- ") | prompt | model\n"+ "chain = (\n",+ " RunnablePassthrough.assign(\n",+ " memory=RunnableLambda(memory.load_memory_variables) | itemgetter(\"history\")\n",+ " )\n",+ " | prompt\n",+ " | model\n",+ ")"]},{@@ -94,7 +100,7 @@"source": ["inputs = {\"input\": \"hi im bob\"}\n","response = chain.invoke(inputs)\n",- "response\n"+ "response"]},{@@ -104,7 +110,7 @@"metadata": {},"outputs": [],"source": [- "memory.save_context(inputs, {\"output\": response.content})\n"+ "memory.save_context(inputs, {\"output\": response.content})"]},{@@ -126,7 +132,7 @@}],"source": [- "memory.load_memory_variables({})\n"+ "memory.load_memory_variables({})"]},{@@ -149,7 +155,7 @@"source": ["inputs = {\"input\": \"whats my name\"}\n","response = chain.invoke(inputs)\n",- "response\n"+ "response"]}],diff --git a/docs/docs/expression_language/cookbook/moderation.ipynb b/docs/docs/expression_language/cookbook/moderation.ipynbindex cb4114d8e9..1d091e3497 100644--- a/docs/docs/expression_language/cookbook/moderation.ipynb+++ b/docs/docs/expression_language/cookbook/moderation.ipynb@@ -40,9 +40,7 @@"outputs": [],"source": ["model = OpenAI()\n",- "prompt = ChatPromptTemplate.from_messages([\n",- " (\"system\", \"repeat after me: {input}\")\n",- "])"+ "prompt = ChatPromptTemplate.from_messages([(\"system\", \"repeat after me: {input}\")])"]},{diff --git a/docs/docs/expression_language/cookbook/multiple_chains.ipynb b/docs/docs/expression_language/cookbook/multiple_chains.ipynbindex 77ac608916..d92d37588a 100644--- a/docs/docs/expression_language/cookbook/multiple_chains.ipynb+++ b/docs/docs/expression_language/cookbook/multiple_chains.ipynb@@ -44,13 +44,20 @@"from langchain.schema import StrOutputParser\n","\n","prompt1 = ChatPromptTemplate.from_template(\"what is the city {person} is from?\")\n",- "prompt2 = ChatPromptTemplate.from_template(\"what country is the city {city} in? respond in {language}\")\n",+ "prompt2 = ChatPromptTemplate.from_template(\n",+ " \"what country is the city {city} in? respond in {language}\"\n",+ ")\n","\n","model = ChatOpenAI()\n","\n","chain1 = prompt1 | model | StrOutputParser()\n","\n",- "chain2 = {\"city\": chain1, \"language\": itemgetter(\"language\")} | prompt2 | model | StrOutputParser()\n",+ "chain2 = (\n",+ " {\"city\": chain1, \"language\": itemgetter(\"language\")}\n",+ " | prompt2\n",+ " | model\n",+ " | StrOutputParser()\n",+ ")\n","\n","chain2.invoke({\"person\": \"obama\", \"language\": \"spanish\"})"]@@ -64,17 +71,29 @@"source": ["from langchain.schema.runnable import RunnableMap, RunnablePassthrough\n","\n",- "prompt1 = ChatPromptTemplate.from_template(\"generate a {attribute} color. Return the name of the color and nothing else:\")\n",- "prompt2 = ChatPromptTemplate.from_template(\"what is a fruit of color: {color}. Return the name of the fruit and nothing else:\")\n",- "prompt3 = ChatPromptTemplate.from_template(\"what is a country with a flag that has the color: {color}. Return the name of the country and nothing else:\")\n",- "prompt4 = ChatPromptTemplate.from_template(\"What is the color of {fruit} and the flag of {country}?\")\n",+ "prompt1 = ChatPromptTemplate.from_template(\n",+ " \"generate a {attribute} color. Return the name of the color and nothing else:\"\n",+ ")\n",+ "prompt2 = ChatPromptTemplate.from_template(\n",+ " \"what is a fruit of color: {color}. Return the name of the fruit and nothing else:\"\n",+ ")\n",+ "prompt3 = ChatPromptTemplate.from_template(\n",+ " \"what is a country with a flag that has the color: {color}. Return the name of the country and nothing else:\"\n",+ ")\n",+ "prompt4 = ChatPromptTemplate.from_template(\n",+ " \"What is the color of {fruit} and the flag of {country}?\"\n",+ ")\n","\n","model_parser = model | StrOutputParser()\n","\n",- "color_generator = {\"attribute\": RunnablePassthrough()} | prompt1 | {\"color\": model_parser}\n",+ "color_generator = (\n",+ " {\"attribute\": RunnablePassthrough()} | prompt1 | {\"color\": model_parser}\n",+ ")\n","color_to_fruit = prompt2 | model_parser\n","color_to_country = prompt3 | model_parser\n",- "question_generator = color_generator | {\"fruit\": color_to_fruit, \"country\": color_to_country} | prompt4"+ "question_generator = (\n",+ " color_generator | {\"fruit\": color_to_fruit, \"country\": color_to_country} | prompt4\n",+ ")"]},{@@ -148,9 +167,7 @@"outputs": [],"source": ["planner = (\n",- " ChatPromptTemplate.from_template(\n",- " \"Generate an argument about: {input}\"\n",- " )\n",+ " ChatPromptTemplate.from_template(\"Generate an argument about: {input}\")\n"," | ChatOpenAI()\n"," | StrOutputParser()\n"," | {\"base_response\": RunnablePassthrough()}\n",@@ -163,7 +180,7 @@" | ChatOpenAI()\n"," | StrOutputParser()\n",")\n",- "arguments_against = (\n",+ "arguments_against = (\n"," ChatPromptTemplate.from_template(\n"," \"List the cons or negative aspects of {base_response}\"\n"," )\n",@@ -184,7 +201,7 @@")\n","\n","chain = (\n",- " planner \n",+ " planner\n"," | {\n"," \"results_1\": arguments_for,\n"," \"results_2\": arguments_against,\n",diff --git a/docs/docs/expression_language/cookbook/prompt_llm_parser.ipynb b/docs/docs/expression_language/cookbook/prompt_llm_parser.ipynbindex b7021734d4..5f569c90b7 100644--- a/docs/docs/expression_language/cookbook/prompt_llm_parser.ipynb+++ b/docs/docs/expression_language/cookbook/prompt_llm_parser.ipynb@@ -47,7 +47,7 @@"\n","prompt = ChatPromptTemplate.from_template(\"tell me a joke about {foo}\")\n","model = ChatOpenAI()\n",- "chain = prompt | model\n"+ "chain = prompt | model"]},{@@ -68,7 +68,7 @@}],"source": [- "chain.invoke({\"foo\": \"bears\"})\n"+ "chain.invoke({\"foo\": \"bears\"})"]},{@@ -94,7 +94,7 @@"metadata": {},"outputs": [],"source": [- "chain = prompt | model.bind(stop=[\"\\n\"])\n"+ "chain = prompt | model.bind(stop=[\"\\n\"])"]},{@@ -115,7 +115,7 @@}],"source": [- "chain.invoke({\"foo\": \"bears\"})\n"+ "chain.invoke({\"foo\": \"bears\"})"]},{@@ -135,25 +135,22 @@"source": ["functions = [\n"," {\n",- " \"name\": \"joke\",\n",- " \"description\": \"A joke\",\n",- " \"parameters\": {\n",- " \"type\": \"object\",\n",- " \"properties\": {\n",- " \"setup\": {\n",- " \"type\": \"string\",\n",- " \"description\": \"The setup for the joke\"\n",- " },\n",- " \"punchline\": {\n",- " \"type\": \"string\",\n",- " \"description\": \"The punchline for the joke\"\n",- " }\n",+ " \"name\": \"joke\",\n",+ " \"description\": \"A joke\",\n",+ " \"parameters\": {\n",+ " \"type\": \"object\",\n",+ " \"properties\": {\n",+ " \"setup\": {\"type\": \"string\", \"description\": \"The setup for the joke\"},\n",+ " \"punchline\": {\n",+ " \"type\": \"string\",\n",+ " \"description\": \"The punchline for the joke\",\n",+ " },\n",+ " },\n",+ " \"required\": [\"setup\", \"punchline\"],\n"," },\n",- " \"required\": [\"setup\", \"punchline\"]\n",- " }\n"," }\n",- " ]\n",- "chain = prompt | model.bind(function_call= {\"name\": \"joke\"}, functions= functions)\n"+ "]\n",+ "chain = prompt | model.bind(function_call={\"name\": \"joke\"}, functions=functions)"]},{@@ -174,7 +171,7 @@}],"source": [- "chain.invoke({\"foo\": \"bears\"}, config={})\n"+ "chain.invoke({\"foo\": \"bears\"}, config={})"]},{@@ -196,7 +193,7 @@"source": ["from langchain.schema.output_parser import StrOutputParser\n","\n",- "chain = prompt | model | StrOutputParser()\n"+ "chain = prompt | model | StrOutputParser()"]},{@@ -225,7 +222,7 @@}],"source": [- "chain.invoke({\"foo\": \"bears\"})\n"+ "chain.invoke({\"foo\": \"bears\"})"]},{@@ -248,10 +245,10 @@"from langchain.output_parsers.openai_functions import JsonOutputFunctionsParser\n","\n","chain = (\n",- " prompt \n",- " | model.bind(function_call= {\"name\": \"joke\"}, functions= functions) \n",+ " prompt\n",+ " | model.bind(function_call={\"name\": \"joke\"}, functions=functions)\n"," | JsonOutputFunctionsParser()\n",- ")\n"+ ")"]},{@@ -273,7 +270,7 @@}],"source": [- "chain.invoke({\"foo\": \"bears\"})\n"+ "chain.invoke({\"foo\": \"bears\"})"]},{@@ -286,10 +283,10 @@"from langchain.output_parsers.openai_functions import JsonKeyOutputFunctionsParser\n","\n","chain = (\n",- " prompt \n",- " | model.bind(function_call= {\"name\": \"joke\"}, functions= functions) \n",+ " prompt\n",+ " | model.bind(function_call={\"name\": \"joke\"}, functions=functions)\n"," | JsonKeyOutputFunctionsParser(key_name=\"setup\")\n",- ")\n"+ ")"]},{@@ -310,7 +307,7 @@}],"source": [- "chain.invoke({\"foo\": \"bears\"})\n"+ "chain.invoke({\"foo\": \"bears\"})"]},{@@ -334,11 +331,11 @@"\n","map_ = RunnableMap(foo=RunnablePassthrough())\n","chain = (\n",- " map_ \n",+ " map_\n"," | prompt\n",- " | model.bind(function_call= {\"name\": \"joke\"}, functions= functions) \n",+ " | model.bind(function_call={\"name\": \"joke\"}, functions=functions)\n"," | JsonKeyOutputFunctionsParser(key_name=\"setup\")\n",- ")\n"+ ")"]},{@@ -359,7 +356,7 @@}],"source": [- "chain.invoke(\"bears\")\n"+ "chain.invoke(\"bears\")"]},{@@ -378,11 +375,11 @@"outputs": [],"source": ["chain = (\n",- " {\"foo\": RunnablePassthrough()} \n",+ " {\"foo\": RunnablePassthrough()}\n"," | prompt\n",- " | model.bind(function_call= {\"name\": \"joke\"}, functions= functions) \n",+ " | model.bind(function_call={\"name\": \"joke\"}, functions=functions)\n"," | JsonKeyOutputFunctionsParser(key_name=\"setup\")\n",- ")\n"+ ")"]},{@@ -403,7 +400,7 @@}],"source": [- "chain.invoke(\"bears\")\n"+ "chain.invoke(\"bears\")"]}],diff --git a/docs/docs/expression_language/cookbook/retrieval.ipynb b/docs/docs/expression_language/cookbook/retrieval.ipynbindex f9fe875f91..0fc7e06638 100644--- a/docs/docs/expression_language/cookbook/retrieval.ipynb+++ b/docs/docs/expression_language/cookbook/retrieval.ipynb@@ -26,7 +26,7 @@"metadata": {},"outputs": [],"source": [- "!pip install langchain openai faiss-cpu tiktoken\n"+ "!pip install langchain openai faiss-cpu tiktoken"]},{@@ -43,7 +43,7 @@"from langchain.embeddings import OpenAIEmbeddings\n","from langchain.schema.output_parser import StrOutputParser\n","from langchain.schema.runnable import RunnablePassthrough, RunnableLambda\n",- "from langchain.vectorstores import FAISS\n"+ "from langchain.vectorstores import FAISS"]},{@@ -53,7 +53,9 @@"metadata": {},"outputs": [],"source": [- "vectorstore = FAISS.from_texts([\"harrison worked at kensho\"], embedding=OpenAIEmbeddings())\n",+ "vectorstore = FAISS.from_texts(\n",+ " [\"harrison worked at kensho\"], embedding=OpenAIEmbeddings()\n",+ ")\n","retriever = vectorstore.as_retriever()\n","\n","template = \"\"\"Answer the question based only on the following context:\n",@@ -63,7 +65,7 @@"\"\"\"\n","prompt = ChatPromptTemplate.from_template(template)\n","\n",- "model = ChatOpenAI()\n"+ "model = ChatOpenAI()"]},{@@ -74,11 +76,11 @@"outputs": [],"source": ["chain = (\n",- " {\"context\": retriever, \"question\": RunnablePassthrough()} \n",- " | prompt \n",- " | model \n",+ " {\"context\": retriever, \"question\": RunnablePassthrough()}\n",+ " | prompt\n",+ " | model\n"," | StrOutputParser()\n",- ")\n"+ ")"]},{@@ -99,7 +101,7 @@}],"source": [- "chain.invoke(\"where did harrison work?\")\n"+ "chain.invoke(\"where did harrison work?\")"]},{@@ -118,11 +120,16 @@"\"\"\"\n","prompt = ChatPromptTemplate.from_template(template)\n","\n",- "chain = {\n",- " \"context\": itemgetter(\"question\") | retriever, \n",- " \"question\": itemgetter(\"question\"), \n",- " \"language\": itemgetter(\"language\")\n",- "} | prompt | model | StrOutputParser()\n"+ "chain = (\n",+ " {\n",+ " \"context\": itemgetter(\"question\") | retriever,\n",+ " \"question\": itemgetter(\"question\"),\n",+ " \"language\": itemgetter(\"language\"),\n",+ " }\n",+ " | prompt\n",+ " | model\n",+ " | StrOutputParser()\n",+ ")"]},{@@ -143,7 +150,7 @@}],"source": [- "chain.invoke({\"question\": \"where did harrison work\", \"language\": \"italian\"})\n"+ "chain.invoke({\"question\": \"where did harrison work\", \"language\": \"italian\"})"]},{@@ -164,7 +171,7 @@"outputs": [],"source": ["from langchain.schema.runnable import RunnableMap\n",- "from langchain.schema import format_document\n"+ "from langchain.schema import format_document"]},{@@ -182,7 +189,7 @@"{chat_history}\n","Follow Up Input: {question}\n","Standalone question:\"\"\"\n",- "CONDENSE_QUESTION_PROMPT = PromptTemplate.from_template(_template)\n"+ "CONDENSE_QUESTION_PROMPT = PromptTemplate.from_template(_template)"]},{@@ -197,7 +204,7 @@"\n","Question: {question}\n","\"\"\"\n",- "ANSWER_PROMPT = ChatPromptTemplate.from_template(template)\n"+ "ANSWER_PROMPT = ChatPromptTemplate.from_template(template)"]},{@@ -208,9 +215,13 @@"outputs": [],"source": ["DEFAULT_DOCUMENT_PROMPT = PromptTemplate.from_template(template=\"{page_content}\")\n",- "def _combine_documents(docs, document_prompt = DEFAULT_DOCUMENT_PROMPT, document_separator=\"\\n\\n\"):\n",+ "\n",+ "\n",+ "def _combine_documents(\n",+ " docs, document_prompt=DEFAULT_DOCUMENT_PROMPT, document_separator=\"\\n\\n\"\n",+ "):\n"," doc_strings = [format_document(doc, document_prompt) for doc in docs]\n",- " return document_separator.join(doc_strings)\n"+ " return document_separator.join(doc_strings)"]},{@@ -221,13 +232,15 @@"outputs": [],"source": ["from typing import Tuple, List\n",+ "\n",+ "\n","def _format_chat_history(chat_history: List[Tuple]) -> str:\n"," buffer = \"\"\n"," for dialogue_turn in chat_history:\n"," human = \"Human: \" + dialogue_turn[0]\n"," ai = \"Assistant: \" + dialogue_turn[1]\n"," buffer += \"\\n\" + \"\\n\".join([human, ai])\n",- " return buffer\n"+ " return buffer"]},{@@ -239,14 +252,17 @@"source": ["_inputs = RunnableMap(\n"," standalone_question=RunnablePassthrough.assign(\n",- " chat_history=lambda x: _format_chat_history(x['chat_history'])\n",- " ) | CONDENSE_QUESTION_PROMPT | ChatOpenAI(temperature=0) | StrOutputParser(),\n",+ " chat_history=lambda x: _format_chat_history(x[\"chat_history\"])\n",+ " )\n",+ " | CONDENSE_QUESTION_PROMPT\n",+ " | ChatOpenAI(temperature=0)\n",+ " | StrOutputParser(),\n",")\n","_context = {\n"," \"context\": itemgetter(\"standalone_question\") | retriever | _combine_documents,\n",- " \"question\": lambda x: x[\"standalone_question\"]\n",+ " \"question\": lambda x: x[\"standalone_question\"],\n","}\n",- "conversational_qa_chain = _inputs | _context | ANSWER_PROMPT | ChatOpenAI()\n"+ "conversational_qa_chain = _inputs | _context | ANSWER_PROMPT | ChatOpenAI()"]},{@@ -267,10 +283,12 @@}],"source": [- "conversational_qa_chain.invoke({\n",- " \"question\": \"where did harrison work?\",\n",- " \"chat_history\": [],\n",- "})\n"+ "conversational_qa_chain.invoke(\n",+ " {\n",+ " \"question\": \"where did harrison work?\",\n",+ " \"chat_history\": [],\n",+ " }\n",+ ")"]},{@@ -291,10 +309,12 @@}],"source": [- "conversational_qa_chain.invoke({\n",- " \"question\": \"where did he work?\",\n",- " \"chat_history\": [(\"Who wrote this notebook?\", \"Harrison\")],\n",- "})\n"+ "conversational_qa_chain.invoke(\n",+ " {\n",+ " \"question\": \"where did he work?\",\n",+ " \"chat_history\": [(\"Who wrote this notebook?\", \"Harrison\")],\n",+ " }\n",+ ")"]},{@@ -315,7 +335,7 @@"outputs": [],"source": ["from operator import itemgetter\n",- "from langchain.memory import ConversationBufferMemory\n"+ "from langchain.memory import ConversationBufferMemory"]},{@@ -325,7 +345,9 @@"metadata": {},"outputs": [],"source": [- "memory = ConversationBufferMemory(return_messages=True, output_key=\"answer\", input_key=\"question\")\n"+ "memory = ConversationBufferMemory(\n",+ " return_messages=True, output_key=\"answer\", input_key=\"question\"\n",+ ")"]},{@@ -344,18 +366,21 @@"standalone_question = {\n"," \"standalone_question\": {\n"," \"question\": lambda x: x[\"question\"],\n",- " \"chat_history\": lambda x: _format_chat_history(x['chat_history'])\n",- " } | CONDENSE_QUESTION_PROMPT | ChatOpenAI(temperature=0) | StrOutputParser(),\n",+ " \"chat_history\": lambda x: _format_chat_history(x[\"chat_history\"]),\n",+ " }\n",+ " | CONDENSE_QUESTION_PROMPT\n",+ " | ChatOpenAI(temperature=0)\n",+ " | StrOutputParser(),\n","}\n","# Now we retrieve the documents\n","retrieved_documents = {\n"," \"docs\": itemgetter(\"standalone_question\") | retriever,\n",- " \"question\": lambda x: x[\"standalone_question\"]\n",+ " \"question\": lambda x: x[\"standalone_question\"],\n","}\n","# Now we construct the inputs for the final prompt\n","final_inputs = {\n"," \"context\": lambda x: _combine_documents(x[\"docs\"]),\n",- " \"question\": itemgetter(\"question\")\n",+ " \"question\": itemgetter(\"question\"),\n","}\n","# And finally, we do the part that returns the answers\n","answer = {\n",@@ -363,7 +388,7 @@" \"docs\": itemgetter(\"docs\"),\n","}\n","# And now we put it all together!\n",- "final_chain = loaded_memory | standalone_question | retrieved_documents | answer\n"+ "final_chain = loaded_memory | standalone_question | retrieved_documents | answer"]},{@@ -387,7 +412,7 @@"source": ["inputs = {\"question\": \"where did harrison work?\"}\n","result = final_chain.invoke(inputs)\n",- "result\n"+ "result"]},{@@ -400,7 +425,7 @@"# Note that the memory does not save automatically\n","# This will be improved in the future\n","# For now you need to save it yourself\n",- "memory.save_context(inputs, {\"answer\": result[\"answer\"].content})\n"+ "memory.save_context(inputs, {\"answer\": result[\"answer\"].content})"]},{@@ -422,7 +447,7 @@}],"source": [- "memory.load_memory_variables({})\n"+ "memory.load_memory_variables({})"]}],diff --git a/docs/docs/expression_language/cookbook/sql_db.ipynb b/docs/docs/expression_language/cookbook/sql_db.ipynbindex 2c9a792438..dc5e134b3a 100644--- a/docs/docs/expression_language/cookbook/sql_db.ipynb+++ b/docs/docs/expression_language/cookbook/sql_db.ipynb@@ -33,7 +33,7 @@"\n","Question: {question}\n","SQL Query:\"\"\"\n",- "prompt = ChatPromptTemplate.from_template(template)\n"+ "prompt = ChatPromptTemplate.from_template(template)"]},{@@ -43,7 +43,7 @@"metadata": {},"outputs": [],"source": [- "from langchain.utilities import SQLDatabase\n"+ "from langchain.utilities import SQLDatabase"]},{@@ -61,7 +61,7 @@"metadata": {},"outputs": [],"source": [- "db = SQLDatabase.from_uri(\"sqlite:///./Chinook.db\")\n"+ "db = SQLDatabase.from_uri(\"sqlite:///./Chinook.db\")"]},{@@ -72,7 +72,7 @@"outputs": [],"source": ["def get_schema(_):\n",- " return db.get_table_info()\n"+ " return db.get_table_info()"]},{@@ -83,7 +83,7 @@"outputs": [],"source": ["def run_query(query):\n",- " return db.run(query)\n"+ " return db.run(query)"]},{@@ -100,11 +100,11 @@"model = ChatOpenAI()\n","\n","sql_response = (\n",- " RunnablePassthrough.assign(schema=get_schema)\n",- " | prompt\n",- " | model.bind(stop=[\"\\nSQLResult:\"])\n",- " | StrOutputParser()\n",- " )\n"+ " RunnablePassthrough.assign(schema=get_schema)\n",+ " | prompt\n",+ " | model.bind(stop=[\"\\nSQLResult:\"])\n",+ " | StrOutputParser()\n",+ ")"]},{@@ -125,7 +125,7 @@}],"source": [- "sql_response.invoke({\"question\": \"How many employees are there?\"})\n"+ "sql_response.invoke({\"question\": \"How many employees are there?\"})"]},{@@ -141,7 +141,7 @@"Question: {question}\n","SQL Query: {query}\n","SQL Response: {response}\"\"\"\n",- "prompt_response = ChatPromptTemplate.from_template(template)\n"+ "prompt_response = ChatPromptTemplate.from_template(template)"]},{@@ -152,14 +152,14 @@"outputs": [],"source": ["full_chain = (\n",- " RunnablePassthrough.assign(query=sql_response) \n",+ " RunnablePassthrough.assign(query=sql_response)\n"," | RunnablePassthrough.assign(\n"," schema=get_schema,\n"," response=lambda x: db.run(x[\"query\"]),\n"," )\n",- " | prompt_response \n",+ " | prompt_response\n"," | model\n",- ")\n"+ ")"]},{@@ -180,7 +180,7 @@}],"source": [- "full_chain.invoke({\"question\": \"How many employees are there?\"})\n"+ "full_chain.invoke({\"question\": \"How many employees are there?\"})"]},{diff --git a/docs/docs/expression_language/how_to/binding.ipynb b/docs/docs/expression_language/how_to/binding.ipynbindex d21b44dd8e..d8b0679f11 100644--- a/docs/docs/expression_language/how_to/binding.ipynb+++ b/docs/docs/expression_language/how_to/binding.ipynb@@ -44,12 +44,17 @@"\n","prompt = ChatPromptTemplate.from_messages(\n"," [\n",- " (\"system\", \"Write out the following equation using algebraic symbols then solve it. Use the format\\n\\nEQUATION:...\\nSOLUTION:...\\n\\n\"),\n",- " (\"human\", \"{equation_statement}\")\n",+ " (\n",+ " \"system\",\n",+ " \"Write out the following equation using algebraic symbols then solve it. Use the format\\n\\nEQUATION:...\\nSOLUTION:...\\n\\n\",\n",+ " ),\n",+ " (\"human\", \"{equation_statement}\"),\n"," ]\n",")\n","model = ChatOpenAI(temperature=0)\n",- "runnable = {\"equation_statement\": RunnablePassthrough()} | prompt | model | StrOutputParser()\n",+ "runnable = (\n",+ " {\"equation_statement\": RunnablePassthrough()} | prompt | model | StrOutputParser()\n",+ ")\n","\n","print(runnable.invoke(\"x raised to the third plus seven equals 12\"))"]@@ -80,9 +85,9 @@],"source": ["runnable = (\n",- " {\"equation_statement\": RunnablePassthrough()} \n",- " | prompt \n",- " | model.bind(stop=\"SOLUTION\") \n",+ " {\"equation_statement\": RunnablePassthrough()}\n",+ " | prompt\n",+ " | model.bind(stop=\"SOLUTION\")\n"," | StrOutputParser()\n",")\n","print(runnable.invoke(\"x raised to the third plus seven equals 12\"))"@@ -107,24 +112,24 @@"source": ["functions = [\n"," {\n",- " \"name\": \"solver\",\n",- " \"description\": \"Formulates and solves an equation\",\n",- " \"parameters\": {\n",- " \"type\": \"object\",\n",- " \"properties\": {\n",- " \"equation\": {\n",- " \"type\": \"string\",\n",- " \"description\": \"The algebraic expression of the equation\"\n",- " },\n",- " \"solution\": {\n",- " \"type\": \"string\",\n",- " \"description\": \"The solution to the equation\"\n",- " }\n",+ " \"name\": \"solver\",\n",+ " \"description\": \"Formulates and solves an equation\",\n",+ " \"parameters\": {\n",+ " \"type\": \"object\",\n",+ " \"properties\": {\n",+ " \"equation\": {\n",+ " \"type\": \"string\",\n",+ " \"description\": \"The algebraic expression of the equation\",\n",+ " },\n",+ " \"solution\": {\n",+ " \"type\": \"string\",\n",+ " \"description\": \"The solution to the equation\",\n",+ " },\n",+ " },\n",+ " \"required\": [\"equation\", \"solution\"],\n"," },\n",- " \"required\": [\"equation\", \"solution\"]\n",- " }\n"," }\n",- " ]\n"+ "]"]},{@@ -148,16 +153,17 @@"# Need gpt-4 to solve this one correctly\n","prompt = ChatPromptTemplate.from_messages(\n"," [\n",- " (\"system\", \"Write out the following equation using algebraic symbols then solve it.\"),\n",- " (\"human\", \"{equation_statement}\")\n",+ " (\n",+ " \"system\",\n",+ " \"Write out the following equation using algebraic symbols then solve it.\",\n",+ " ),\n",+ " (\"human\", \"{equation_statement}\"),\n"," ]\n",")\n",- "model = ChatOpenAI(model=\"gpt-4\", temperature=0).bind(function_call={\"name\": \"solver\"}, functions=functions)\n",- "runnable = (\n",- " {\"equation_statement\": RunnablePassthrough()} \n",- " | prompt \n",- " | model\n",+ "model = ChatOpenAI(model=\"gpt-4\", temperature=0).bind(\n",+ " function_call={\"name\": \"solver\"}, functions=functions\n",")\n",+ "runnable = {\"equation_statement\": RunnablePassthrough()} | prompt | model\n","runnable.invoke(\"x raised to the third plus seven equals 12\")"]},diff --git a/docs/docs/expression_language/how_to/configure.ipynb b/docs/docs/expression_language/how_to/configure.ipynbindex d261eba01a..a4edaf959d 100644--- a/docs/docs/expression_language/how_to/configure.ipynb+++ b/docs/docs/expression_language/how_to/configure.ipynb@@ -92,7 +92,7 @@}],"source": [- "model.with_config(configurable={\"llm_temperature\": .9}).invoke(\"pick a random number\")"+ "model.with_config(configurable={\"llm_temperature\": 0.9}).invoke(\"pick a random number\")"]},{@@ -153,7 +153,7 @@}],"source": [- "chain.with_config(configurable={\"llm_temperature\": .9}).invoke({\"x\": 0})"+ "chain.with_config(configurable={\"llm_temperature\": 0.9}).invoke({\"x\": 0})"]},{@@ -231,7 +231,9 @@}],"source": [- "prompt.with_config(configurable={\"hub_commit\": \"rlm/rag-prompt-llama\"}).invoke({\"question\": \"foo\", \"context\": \"bar\"})"+ "prompt.with_config(configurable={\"hub_commit\": \"rlm/rag-prompt-llama\"}).invoke(\n",+ " {\"question\": \"foo\", \"context\": \"bar\"}\n",+ ")"]},{@@ -373,7 +375,9 @@"outputs": [],"source": ["llm = ChatAnthropic(temperature=0)\n",- "prompt = PromptTemplate.from_template(\"Tell me a joke about {topic}\").configurable_alternatives(\n",+ "prompt = PromptTemplate.from_template(\n",+ " \"Tell me a joke about {topic}\"\n",+ ").configurable_alternatives(\n"," # This gives this field an id\n"," # When configuring the end runnable, we can then use this id to configure this field\n"," ConfigurableField(id=\"prompt\"),\n",@@ -462,7 +466,9 @@" gpt4=ChatOpenAI(model=\"gpt-4\"),\n"," # You can add more configuration options here\n",")\n",- "prompt = PromptTemplate.from_template(\"Tell me a joke about {topic}\").configurable_alternatives(\n",+ "prompt = PromptTemplate.from_template(\n",+ " \"Tell me a joke about {topic}\"\n",+ ").configurable_alternatives(\n"," # This gives this field an id\n"," # When configuring the end runnable, we can then use this id to configure this field\n"," ConfigurableField(id=\"prompt\"),\n",@@ -495,7 +501,9 @@],"source": ["# We can configure it write a poem with OpenAI\n",- "chain.with_config(configurable={\"prompt\": \"poem\", \"llm\": \"openai\"}).invoke({\"topic\": \"bears\"})"+ "chain.with_config(configurable={\"prompt\": \"poem\", \"llm\": \"openai\"}).invoke(\n",+ " {\"topic\": \"bears\"}\n",+ ")"]},{diff --git a/docs/docs/expression_language/how_to/fallbacks.ipynb b/docs/docs/expression_language/how_to/fallbacks.ipynbindex be654f29dc..00f1b761de 100644--- a/docs/docs/expression_language/how_to/fallbacks.ipynb+++ b/docs/docs/expression_language/how_to/fallbacks.ipynb@@ -82,9 +82,9 @@],"source": ["# Let's use just the OpenAI LLm first, to show that we run into an error\n",- "with patch('openai.ChatCompletion.create', side_effect=RateLimitError()):\n",+ "with patch(\"openai.ChatCompletion.create\", side_effect=RateLimitError()):\n"," try:\n",- " print(openai_llm.invoke(\"Why did the chicken cross the road?\"))\n",+ " print(openai_llm.invoke(\"Why did the chicken cross the road?\"))\n"," except:\n"," print(\"Hit error\")"]@@ -105,9 +105,9 @@],"source": ["# Now let's try with fallbacks to Anthropic\n",- "with patch('openai.ChatCompletion.create', side_effect=RateLimitError()):\n",+ "with patch(\"openai.ChatCompletion.create\", side_effect=RateLimitError()):\n"," try:\n",- " print(llm.invoke(\"Why did the chicken cross the road?\"))\n",+ " print(llm.invoke(\"Why did the chicken cross the road?\"))\n"," except:\n"," print(\"Hit error\")"]@@ -139,14 +139,17 @@"\n","prompt = ChatPromptTemplate.from_messages(\n"," [\n",- " (\"system\", \"You're a nice assistant who always includes a compliment in your response\"),\n",+ " (\n",+ " \"system\",\n",+ " \"You're a nice assistant who always includes a compliment in your response\",\n",+ " ),\n"," (\"human\", \"Why did the {animal} cross the road\"),\n"," ]\n",")\n","chain = prompt | llm\n",- "with patch('openai.ChatCompletion.create', side_effect=RateLimitError()):\n",+ "with patch(\"openai.ChatCompletion.create\", side_effect=RateLimitError()):\n"," try:\n",- " print(chain.invoke({\"animal\": \"kangaroo\"}))\n",+ " print(chain.invoke({\"animal\": \"kangaroo\"}))\n"," except:\n"," print(\"Hit error\")"]@@ -176,12 +179,14 @@}],"source": [- "llm = openai_llm.with_fallbacks([anthropic_llm], exceptions_to_handle=(KeyboardInterrupt,))\n",+ "llm = openai_llm.with_fallbacks(\n",+ " [anthropic_llm], exceptions_to_handle=(KeyboardInterrupt,)\n",+ ")\n","\n","chain = prompt | llm\n",- "with patch('openai.ChatCompletion.create', side_effect=RateLimitError()):\n",+ "with patch(\"openai.ChatCompletion.create\", side_effect=RateLimitError()):\n"," try:\n",- " print(chain.invoke({\"animal\": \"kangaroo\"}))\n",+ " print(chain.invoke({\"animal\": \"kangaroo\"}))\n"," except:\n"," print(\"Hit error\")"]@@ -209,7 +214,10 @@"\n","chat_prompt = ChatPromptTemplate.from_messages(\n"," [\n",- " (\"system\", \"You're a nice assistant who always includes a compliment in your response\"),\n",+ " (\n",+ " \"system\",\n",+ " \"You're a nice assistant who always includes a compliment in your response\",\n",+ " ),\n"," (\"human\", \"Why did the {animal} cross the road\"),\n"," ]\n",")\n",diff --git a/docs/docs/expression_language/how_to/functions.ipynb b/docs/docs/expression_language/how_to/functions.ipynbindex 896367926b..f1fba6744b 100644--- a/docs/docs/expression_language/how_to/functions.ipynb+++ b/docs/docs/expression_language/how_to/functions.ipynb@@ -24,24 +24,33 @@"from langchain.chat_models import ChatOpenAI\n","from operator import itemgetter\n","\n",+ "\n","def length_function(text):\n"," return len(text)\n","\n",+ "\n","def _multiple_length_function(text1, text2):\n"," return len(text1) * len(text2)\n","\n",+ "\n","def multiple_length_function(_dict):\n"," return _multiple_length_function(_dict[\"text1\"], _dict[\"text2\"])\n","\n",+ "\n","prompt = ChatPromptTemplate.from_template(\"what is {a} + {b}\")\n","model = ChatOpenAI()\n","\n","chain1 = prompt | model\n","\n",- "chain = {\n",- " \"a\": itemgetter(\"foo\") | RunnableLambda(length_function),\n",- " \"b\": {\"text1\": itemgetter(\"foo\"), \"text2\": itemgetter(\"bar\")} | RunnableLambda(multiple_length_function)\n",- "} | prompt | model"+ "chain = (\n",+ " {\n",+ " \"a\": itemgetter(\"foo\") | RunnableLambda(length_function),\n",+ " \"b\": {\"text1\": itemgetter(\"foo\"), \"text2\": itemgetter(\"bar\")}\n",+ " | RunnableLambda(multiple_length_function),\n",+ " }\n",+ " | prompt\n",+ " | model\n",+ ")"]},{@@ -95,6 +104,7 @@"source": ["import json\n","\n",+ "\n","def parse_or_fix(text: str, config: RunnableConfig):\n"," fixing_chain = (\n"," ChatPromptTemplate.from_template(\n",@@ -134,7 +144,9 @@"from langchain.callbacks import get_openai_callback\n","\n","with get_openai_callback() as cb:\n",- " RunnableLambda(parse_or_fix).invoke(\"{foo: bar}\", {\"tags\": [\"my-tag\"], \"callbacks\": [cb]})\n",+ " RunnableLambda(parse_or_fix).invoke(\n",+ " \"{foo: bar}\", {\"tags\": [\"my-tag\"], \"callbacks\": [cb]}\n",+ " )\n"," print(cb)"]},diff --git a/docs/docs/expression_language/how_to/generators.ipynb b/docs/docs/expression_language/how_to/generators.ipynbindex 6dd76709ac..4c53428865 100644--- a/docs/docs/expression_language/how_to/generators.ipynb+++ b/docs/docs/expression_language/how_to/generators.ipynb@@ -46,7 +46,7 @@"\n","str_chain = prompt | model | StrOutputParser()\n","\n",- "print(str_chain.invoke({\"animal\": \"bear\"}))\n"+ "print(str_chain.invoke({\"animal\": \"bear\"}))"]},{@@ -72,7 +72,7 @@" # save the rest for the next iteration\n"," buffer = buffer[comma_index + 1 :]\n"," # yield the last chunk\n",- " yield [buffer.strip()]\n"+ " yield [buffer.strip()]"]},{@@ -91,7 +91,7 @@"source": ["list_chain = str_chain | split_into_list\n","\n",- "print(list_chain.invoke({\"animal\": \"bear\"}))\n"+ "print(list_chain.invoke({\"animal\": \"bear\"}))"]}],diff --git a/docs/docs/expression_language/how_to/map.ipynb b/docs/docs/expression_language/how_to/map.ipynbindex 4848d8ba1a..b56f52671b 100644--- a/docs/docs/expression_language/how_to/map.ipynb+++ b/docs/docs/expression_language/how_to/map.ipynb@@ -36,11 +36,13 @@"\n","model = ChatOpenAI()\n","joke_chain = ChatPromptTemplate.from_template(\"tell me a joke about {topic}\") | model\n",- "poem_chain = ChatPromptTemplate.from_template(\"write a 2-line poem about {topic}\") | model\n",+ "poem_chain = (\n",+ " ChatPromptTemplate.from_template(\"write a 2-line poem about {topic}\") | model\n",+ ")\n","\n","map_chain = RunnableParallel(joke=joke_chain, poem=poem_chain)\n","\n",- "map_chain.invoke({\"topic\": \"bear\"})\n"+ "map_chain.invoke({\"topic\": \"bear\"})"]},{@@ -75,7 +77,9 @@"from langchain.schema.runnable import RunnablePassthrough\n","from langchain.vectorstores import FAISS\n","\n",- "vectorstore = FAISS.from_texts([\"harrison worked at kensho\"], embedding=OpenAIEmbeddings())\n",+ "vectorstore = FAISS.from_texts(\n",+ " [\"harrison worked at kensho\"], embedding=OpenAIEmbeddings()\n",+ ")\n","retriever = vectorstore.as_retriever()\n","template = \"\"\"Answer the question based only on the following context:\n","{context}\n",@@ -85,13 +89,13 @@"prompt = ChatPromptTemplate.from_template(template)\n","\n","retrieval_chain = (\n",- " {\"context\": retriever, \"question\": RunnablePassthrough()} \n",- " | prompt \n",- " | model \n",+ " {\"context\": retriever, \"question\": RunnablePassthrough()}\n",+ " | prompt\n",+ " | model\n"," | StrOutputParser()\n",")\n","\n",- "retrieval_chain.invoke(\"where did harrison work?\")\n"+ "retrieval_chain.invoke(\"where did harrison work?\")"]},{@@ -131,7 +135,7 @@"source": ["%%timeit\n","\n",- "joke_chain.invoke({\"topic\": \"bear\"})\n"+ "joke_chain.invoke({\"topic\": \"bear\"})"]},{@@ -151,7 +155,7 @@"source": ["%%timeit\n","\n",- "poem_chain.invoke({\"topic\": \"bear\"})\n"+ "poem_chain.invoke({\"topic\": \"bear\"})"]},{@@ -171,7 +175,7 @@"source": ["%%timeit\n","\n",- "map_chain.invoke({\"topic\": \"bear\"})\n"+ "map_chain.invoke({\"topic\": \"bear\"})"]}],diff --git a/docs/docs/expression_language/how_to/routing.ipynb b/docs/docs/expression_language/how_to/routing.ipynbindex 1c87c26e12..6d0fe06798 100644--- a/docs/docs/expression_language/how_to/routing.ipynb+++ b/docs/docs/expression_language/how_to/routing.ipynb@@ -60,7 +60,9 @@"metadata": {},"outputs": [],"source": [- "chain = PromptTemplate.from_template(\"\"\"Given the user question below, classify it as either being about `LangChain`, `Anthropic`, or `Other`.\n",+ "chain = (\n",+ " PromptTemplate.from_template(\n",+ " \"\"\"Given the user question below, classify it as either being about `LangChain`, `Anthropic`, or `Other`.\n"," \n","Do not respond with more than one word.\n","\n",@@ -68,7 +70,11 @@"{question}\n","</question>\n","\n",- "Classification:\"\"\") | ChatAnthropic() | StrOutputParser()"+ "Classification:\"\"\"\n",+ " )\n",+ " | ChatAnthropic()\n",+ " | StrOutputParser()\n",+ ")"]},{@@ -107,22 +113,37 @@"metadata": {},"outputs": [],"source": [- "langchain_chain = PromptTemplate.from_template(\"\"\"You are an expert in langchain. \\\n",+ "langchain_chain = (\n",+ " PromptTemplate.from_template(\n",+ " \"\"\"You are an expert in langchain. \\\n","Always answer questions starting with \"As Harrison Chase told me\". \\\n","Respond to the following question:\n","\n","Question: {question}\n",- "Answer:\"\"\") | ChatAnthropic()\n",- "anthropic_chain = PromptTemplate.from_template(\"\"\"You are an expert in anthropic. \\\n",+ "Answer:\"\"\"\n",+ " )\n",+ " | ChatAnthropic()\n",+ ")\n",+ "anthropic_chain = (\n",+ " PromptTemplate.from_template(\n",+ " \"\"\"You are an expert in anthropic. \\\n","Always answer questions starting with \"As Dario Amodei told me\". \\\n","Respond to the following question:\n","\n","Question: {question}\n",- "Answer:\"\"\") | ChatAnthropic()\n",- "general_chain = PromptTemplate.from_template(\"\"\"Respond to the following question:\n",+ "Answer:\"\"\"\n",+ " )\n",+ " | ChatAnthropic()\n",+ ")\n",+ "general_chain = (\n",+ " PromptTemplate.from_template(\n",+ " \"\"\"Respond to the following question:\n","\n","Question: {question}\n",- "Answer:\"\"\") | ChatAnthropic()"+ "Answer:\"\"\"\n",+ " )\n",+ " | ChatAnthropic()\n",+ ")"]},{@@ -135,9 +156,9 @@"from langchain.schema.runnable import RunnableBranch\n","\n","branch = RunnableBranch(\n",- " (lambda x: \"anthropic\" in x[\"topic\"].lower(), anthropic_chain),\n",- " (lambda x: \"langchain\" in x[\"topic\"].lower(), langchain_chain),\n",- " general_chain\n",+ " (lambda x: \"anthropic\" in x[\"topic\"].lower(), anthropic_chain),\n",+ " (lambda x: \"langchain\" in x[\"topic\"].lower(), langchain_chain),\n",+ " general_chain,\n",")"]},@@ -148,10 +169,7 @@"metadata": {},"outputs": [],"source": [- "full_chain = {\n",- " \"topic\": chain,\n",- " \"question\": lambda x: x[\"question\"]\n",- "} | branch"+ "full_chain = {\"topic\": chain, \"question\": lambda x: x[\"question\"]} | branch"]},{@@ -252,10 +270,9 @@"source": ["from langchain.schema.runnable import RunnableLambda\n","\n",- "full_chain = {\n",- " \"topic\": chain,\n",- " \"question\": lambda x: x[\"question\"]\n",- "} | RunnableLambda(route)"+ "full_chain = {\"topic\": chain, \"question\": lambda x: x[\"question\"]} | RunnableLambda(\n",+ " route\n",+ ")"]},{diff --git a/docs/docs/expression_language/interface.ipynb b/docs/docs/expression_language/interface.ipynbindex d1d6f863f2..0acf8013c0 100644--- a/docs/docs/expression_language/interface.ipynb+++ b/docs/docs/expression_language/interface.ipynb@@ -680,19 +680,26 @@"\"\"\"\n","prompt = ChatPromptTemplate.from_template(template)\n","\n",- "vectorstore = FAISS.from_texts([\"harrison worked at kensho\"], embedding=OpenAIEmbeddings())\n",+ "vectorstore = FAISS.from_texts(\n",+ " [\"harrison worked at kensho\"], embedding=OpenAIEmbeddings()\n",+ ")\n","retriever = vectorstore.as_retriever()\n","\n","retrieval_chain = (\n",- " {\"context\": retriever.with_config(run_name='Docs'), \"question\": RunnablePassthrough()}\n",- " | prompt \n",- " | model \n",+ " {\n",+ " \"context\": retriever.with_config(run_name=\"Docs\"),\n",+ " \"question\": RunnablePassthrough(),\n",+ " }\n",+ " | prompt\n",+ " | model\n"," | StrOutputParser()\n",")\n","\n",- "async for chunk in retrieval_chain.astream_log(\"where did harrison work?\", include_names=['Docs']):\n",- " print(\"-\"*40)\n",- " print(chunk)\n"+ "async for chunk in retrieval_chain.astream_log(\n",+ " \"where did harrison work?\", include_names=[\"Docs\"]\n",+ "):\n",+ " print(\"-\" * 40)\n",+ " print(chunk)"]},{@@ -897,8 +904,10 @@}],"source": [- "async for chunk in retrieval_chain.astream_log(\"where did harrison work?\", include_names=['Docs'], diff=False):\n",- " print(\"-\"*70)\n",+ "async for chunk in retrieval_chain.astream_log(\n",+ " \"where did harrison work?\", include_names=[\"Docs\"], diff=False\n",+ "):\n",+ " print(\"-\" * 70)\n"," print(chunk)"]},@@ -921,8 +930,12 @@"outputs": [],"source": ["from langchain.schema.runnable import RunnableParallel\n",+ "\n","chain1 = ChatPromptTemplate.from_template(\"tell me a joke about {topic}\") | model\n",- "chain2 = ChatPromptTemplate.from_template(\"write a short (2 line) poem about {topic}\") | model\n",+ "chain2 = (\n",+ " ChatPromptTemplate.from_template(\"write a short (2 line) poem about {topic}\")\n",+ " | model\n",+ ")\n","combined = RunnableParallel(joke=chain1, poem=chain2)"]},diff --git a/docs/docs/guides/adapters/openai.ipynb b/docs/docs/guides/adapters/openai.ipynbindex e00241d74f..fd9cf4bac2 100644--- a/docs/docs/guides/adapters/openai.ipynb+++ b/docs/docs/guides/adapters/openai.ipynb@@ -57,9 +57,7 @@"outputs": [],"source": ["result = openai.ChatCompletion.create(\n",- " messages=messages, \n",- " model=\"gpt-3.5-turbo\", \n",- " temperature=0\n",+ " messages=messages, model=\"gpt-3.5-turbo\", temperature=0\n",")"]},@@ -81,7 +79,7 @@}],"source": [- "result[\"choices\"][0]['message'].to_dict_recursive()"+ "result[\"choices\"][0][\"message\"].to_dict_recursive()"]},{@@ -100,9 +98,7 @@"outputs": [],"source": ["lc_result = lc_openai.ChatCompletion.create(\n",- " messages=messages, \n",- " model=\"gpt-3.5-turbo\", \n",- " temperature=0\n",+ " messages=messages, model=\"gpt-3.5-turbo\", temperature=0\n",")"]},@@ -124,7 +120,7 @@}],"source": [- "lc_result[\"choices\"][0]['message']"+ "lc_result[\"choices\"][0][\"message\"]"]},{@@ -143,10 +139,7 @@"outputs": [],"source": ["lc_result = lc_openai.ChatCompletion.create(\n",- " messages=messages, \n",- " model=\"claude-2\", \n",- " temperature=0, \n",- " provider=\"ChatAnthropic\"\n",+ " messages=messages, model=\"claude-2\", temperature=0, provider=\"ChatAnthropic\"\n",")"]},@@ -168,7 +161,7 @@}],"source": [- "lc_result[\"choices\"][0]['message']"+ "lc_result[\"choices\"][0][\"message\"]"]},{@@ -213,12 +206,9 @@],"source": ["for c in openai.ChatCompletion.create(\n",- " messages = messages,\n",- " model=\"gpt-3.5-turbo\", \n",- " temperature=0,\n",- " stream=True\n",+ " messages=messages, model=\"gpt-3.5-turbo\", temperature=0, stream=True\n","):\n",- " print(c[\"choices\"][0]['delta'].to_dict_recursive())"+ " print(c[\"choices\"][0][\"delta\"].to_dict_recursive())"]},{@@ -255,12 +245,9 @@],"source": ["for c in lc_openai.ChatCompletion.create(\n",- " messages = messages,\n",- " model=\"gpt-3.5-turbo\", \n",- " temperature=0,\n",- " stream=True\n",+ " messages=messages, model=\"gpt-3.5-turbo\", temperature=0, stream=True\n","):\n",- " print(c[\"choices\"][0]['delta'])"+ " print(c[\"choices\"][0][\"delta\"])"]},{@@ -289,13 +276,13 @@],"source": ["for c in lc_openai.ChatCompletion.create(\n",- " messages = messages,\n",- " model=\"claude-2\", \n",+ " messages=messages,\n",+ " model=\"claude-2\",\n"," temperature=0,\n"," stream=True,\n"," provider=\"ChatAnthropic\",\n","):\n",- " print(c[\"choices\"][0]['delta'])"+ " print(c[\"choices\"][0][\"delta\"])"]}],diff --git a/docs/docs/guides/evaluation/comparison/pairwise_string.ipynb b/docs/docs/guides/evaluation/comparison/pairwise_string.ipynbindex d1e3d39fd3..938cdd1145 100644--- a/docs/docs/guides/evaluation/comparison/pairwise_string.ipynb+++ b/docs/docs/guides/evaluation/comparison/pairwise_string.ipynb@@ -311,9 +311,7 @@"\n","\"\"\"\n",")\n",- "evaluator = load_evaluator(\n",- " \"labeled_pairwise_string\", prompt=prompt_template\n",- ")"+ "evaluator = load_evaluator(\"labeled_pairwise_string\", prompt=prompt_template)"]},{diff --git a/docs/docs/guides/evaluation/string/criteria_eval_chain.ipynb b/docs/docs/guides/evaluation/string/criteria_eval_chain.ipynbindex bfbbd33452..f09e7c3941 100644--- a/docs/docs/guides/evaluation/string/criteria_eval_chain.ipynb+++ b/docs/docs/guides/evaluation/string/criteria_eval_chain.ipynb@@ -1,469 +1,467 @@{- "cells": [- {- "cell_type": "markdown",- "id": "4cf569a7-9a1d-4489-934e-50e57760c907",- "metadata": {},- "source": [- "# Criteria Evaluation\n",- "[](https://colab.research.google.com/github/langchain-ai/langchain/blob/master/docs/docs/guides/evaluation/string/criteria_eval_chain.ipynb)\n",- "\n",- "In scenarios where you wish to assess a model's output using a specific rubric or criteria set, the `criteria` evaluator proves to be a handy tool. It allows you to verify if an LLM or Chain's output complies with a defined set of criteria.\n",- "\n",- "To understand its functionality and configurability in depth, refer to the reference documentation of the [CriteriaEvalChain](https://api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html#langchain.evaluation.criteria.eval_chain.CriteriaEvalChain) class.\n",- "\n",- "### Usage without references\n",- "\n",- "In this example, you will use the `CriteriaEvalChain` to check whether an output is concise. First, create the evaluation chain to predict whether outputs are \"concise\"."- ]- },- {- "cell_type": "code",- "execution_count": 1,- "id": "6005ebe8-551e-47a5-b4df-80575a068552",- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "from langchain.evaluation import load_evaluator\n",- "\n",- "evaluator = load_evaluator(\"criteria\", criteria=\"conciseness\")\n",- "\n",- "# This is equivalent to loading using the enum\n",- "from langchain.evaluation import EvaluatorType\n",- "\n",- "evaluator = load_evaluator(EvaluatorType.CRITERIA, criteria=\"conciseness\")"- ]- },- {- "cell_type": "code",- "execution_count": 2,- "id": "22f83fb8-82f4-4310-a877-68aaa0789199",- "metadata": {- "tags": []- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "{'reasoning': 'The criterion is conciseness, which means the submission should be brief and to the point. \\n\\nLooking at the submission, the answer to the question \"What\\'s 2+2?\" is indeed \"four\". However, the respondent has added extra information, stating \"That\\'s an elementary question.\" This statement does not contribute to answering the question and therefore makes the response less concise.\\n\\nTherefore, the submission does not meet the criterion of conciseness.\\n\\nN', 'value': 'N', 'score': 0}\n"- ]- }- ],- "source": [- "eval_result = evaluator.evaluate_strings(\n",- " prediction=\"What's 2+2? That's an elementary question. The answer you're looking for is that two and two is four.\",\n",- " input=\"What's 2+2?\",\n",- ")\n",- "print(eval_result)"- ]- },- {- "cell_type": "markdown",- "id": "35e61e4d-b776-4f6b-8c89-da5d3604134a",- "metadata": {},- "source": [- "#### Output Format\n",- "\n",- "All string evaluators expose an [evaluate_strings](https://api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html?highlight=evaluate_strings#langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.evaluate_strings) (or async [aevaluate_strings](https://api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html?highlight=evaluate_strings#langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.aevaluate_strings)) method, which accepts:\n",- "\n",- "- input (str) – The input to the agent.\n",- "- prediction (str) – The predicted response.\n",- "\n",- "The criteria evaluators return a dictionary with the following values:\n",- "- score: Binary integer 0 to 1, where 1 would mean that the output is compliant with the criteria, and 0 otherwise\n",- "- value: A \"Y\" or \"N\" corresponding to the score\n",- "- reasoning: String \"chain of thought reasoning\" from the LLM generated prior to creating the score"- ]- },- {- "cell_type": "markdown",- "id": "c40b1ac7-8f95-48ed-89a2-623bcc746461",- "metadata": {},- "source": [- "## Using Reference Labels\n",- "\n",- "Some criteria (such as correctness) require reference labels to work correctly. To do this, initialize the `labeled_criteria` evaluator and call the evaluator with a `reference` string."- ]- },- {- "cell_type": "code",- "execution_count": 3,- "id": "20d8a86b-beba-42ce-b82c-d9e5ebc13686",- "metadata": {- "tags": []- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "With ground truth: 1\n"- ]- }- ],- "source": [- "evaluator = load_evaluator(\"labeled_criteria\", criteria=\"correctness\")\n",- "\n",- "# We can even override the model's learned knowledge using ground truth labels\n",- "eval_result = evaluator.evaluate_strings(\n",- " input=\"What is the capital of the US?\",\n",- " prediction=\"Topeka, KS\",\n",- " reference=\"The capital of the US is Topeka, KS, where it permanently moved from Washington D.C. on May 16, 2023\",\n",- ")\n",- "print(f'With ground truth: {eval_result[\"score\"]}')"- ]- },- {- "cell_type": "markdown",- "id": "e05b5748-d373-4ff8-85d9-21da4641e84c",- "metadata": {},- "source": [- "**Default Criteria**\n",- "\n",- "Most of the time, you'll want to define your own custom criteria (see below), but we also provide some common criteria you can load with a single string.\n",- "Here's a list of pre-implemented criteria. Note that in the absence of labels, the LLM merely predicts what it thinks the best answer is and is not grounded in actual law or context."- ]- },- {- "cell_type": "code",- "execution_count": 4,- "id": "47de7359-db3e-4cad-bcfa-4fe834dea893",- "metadata": {},- "outputs": [- {- "data": {- "text/plain": [- "[<Criteria.CONCISENESS: 'conciseness'>,\n",- " <Criteria.RELEVANCE: 'relevance'>,\n",- " <Criteria.CORRECTNESS: 'correctness'>,\n",- " <Criteria.COHERENCE: 'coherence'>,\n",- " <Criteria.HARMFULNESS: 'harmfulness'>,\n",- " <Criteria.MALICIOUSNESS: 'maliciousness'>,\n",- " <Criteria.HELPFULNESS: 'helpfulness'>,\n",- " <Criteria.CONTROVERSIALITY: 'controversiality'>,\n",- " <Criteria.MISOGYNY: 'misogyny'>,\n",- " <Criteria.CRIMINALITY: 'criminality'>,\n",- " <Criteria.INSENSITIVITY: 'insensitivity'>]"- ]- },- "execution_count": 4,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "from langchain.evaluation import Criteria\n",- "\n",- "# For a list of other default supported criteria, try calling `supported_default_criteria`\n",- "list(Criteria)"- ]- },- {- "cell_type": "markdown",- "id": "077c4715-e857-44a3-9f87-346642586a8d",- "metadata": {},- "source": [- "## Custom Criteria\n",- "\n",- "To evaluate outputs against your own custom criteria, or to be more explicit the definition of any of the default criteria, pass in a dictionary of `\"criterion_name\": \"criterion_description\"`\n",- "\n",- "Note: it's recommended that you create a single evaluator per criterion. This way, separate feedback can be provided for each aspect. Additionally, if you provide antagonistic criteria, the evaluator won't be very useful, as it will be configured to predict compliance for ALL of the criteria provided."- ]- },- {- "cell_type": "code",- "execution_count": 19,- "id": "bafa0a11-2617-4663-84bf-24df7d0736be",- "metadata": {- "tags": []- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "{'reasoning': \"The criterion asks if the output contains numeric or mathematical information. The joke in the submission does contain mathematical information. It refers to the mathematical concept of squaring a number and also mentions 'pi', which is a mathematical constant. Therefore, the submission does meet the criterion.\\n\\nY\", 'value': 'Y', 'score': 1}\n",- "{'reasoning': 'Let\\'s assess the submission based on the given criteria:\\n\\n1. Numeric: The output does not contain any explicit numeric information. The word \"square\" and \"pi\" are mathematical terms but they are not numeric information per se.\\n\\n2. Mathematical: The output does contain mathematical information. The terms \"square\" and \"pi\" are mathematical terms. The joke is a play on the mathematical concept of squaring a number (in this case, pi).\\n\\n3. Grammatical: The output is grammatically correct. The sentence structure, punctuation, and word usage are all correct.\\n\\n4. Logical: The output is logical. It makes sense within the context of the joke. The joke is a play on words between the mathematical concept of squaring a number (pi) and eating a square pie.\\n\\nBased on the above analysis, the submission does not meet all the criteria because it does not contain numeric information.\\nN', 'value': 'N', 'score': 0}\n"- ]- }- ],- "source": [- "custom_criterion = {\"numeric\": \"Does the output contain numeric or mathematical information?\"}\n",- "\n",- "eval_chain = load_evaluator(\n",- " EvaluatorType.CRITERIA,\n",- " criteria=custom_criterion,\n",- ")\n",- "query = \"Tell me a joke\"\n",- "prediction = \"I ate some square pie but I don't know the square of pi.\"\n",- "eval_result = eval_chain.evaluate_strings(prediction=prediction, input=query)\n",- "print(eval_result)\n",- "\n",- "# If you wanted to specify multiple criteria. Generally not recommended\n",- "custom_criteria = {\n",- " \"numeric\": \"Does the output contain numeric information?\",\n",- " \"mathematical\": \"Does the output contain mathematical information?\",\n",- " \"grammatical\": \"Is the output grammatically correct?\",\n",- " \"logical\": \"Is the output logical?\",\n",- "}\n",- "\n",- "eval_chain = load_evaluator(\n",- " EvaluatorType.CRITERIA,\n",- " criteria=custom_criteria,\n",- ")\n",- "eval_result = eval_chain.evaluate_strings(prediction=prediction, input=query)\n",- "print(\"Multi-criteria evaluation\")\n",- "print(eval_result)"- ]- },- {- "cell_type": "markdown",- "id": "07485cce-8d52-43a0-bdad-76ec7dacfb51",- "metadata": {},- "source": [- "## Using Constitutional Principles\n",- "\n",- "Custom rubrics are similar to principles from [Constitutional AI](https://arxiv.org/abs/2212.08073). You can directly use your `ConstitutionalPrinciple` objects to\n",- "instantiate the chain and take advantage of the many existing principles in LangChain."- ]- },- {- "cell_type": "code",- "execution_count": 9,- "id": "99e3c242-5b12-4bd5-b487-64990a159655",- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "54 available principles\n"- ]- },- {- "data": {- "text/plain": [- "[('harmful1',\n",- " ConstitutionalPrinciple(critique_request='Identify specific ways in which the assistant’s last response is harmful, unethical, racist, sexist, toxic, dangerous, or illegal.', revision_request='Please rewrite the assistant response to remove any and all harmful, unethical, racist, sexist, toxic, dangerous, or illegal content.', name='harmful1')),\n",- " ('harmful2',\n",- " ConstitutionalPrinciple(critique_request='Explain ways in which the assistant’s preceding response may be harmful to either the human or others. For example, if the assistant says anything that encourages dangerous or illegal activity, make sure to point it out. Other examples of harm include racism, sexism, and other social biases.', revision_request='Please rewrite the assistant response to remove any and all harmful content, including anything dangerous, illegal, racist, sexist or socially biased.', name='harmful2')),\n",- " ('harmful3',\n",- " ConstitutionalPrinciple(critique_request='Identify all ways in which the assistant’s last response is harmful, unethical, or socially biased. Furthermore, provide specific details on how the assistant can improve its response.', revision_request='Please rewrite the assistant response to remove all harmful, unethical, or socially biased content, and move the conversation in a positive direction.', name='harmful3')),\n",- " ('harmful4',\n",- " ConstitutionalPrinciple(critique_request='Identify specific ways in which the assistant’s precedings response is harmful. Also point out potential harmfulness in the human’s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.', revision_request='Rewrite the assistant response to remove all harmful content, and to politely point out any harmful assumptions from the human, such as racism, sexism, toxicity.', name='harmful4')),\n",- " ('insensitive',\n",- " ConstitutionalPrinciple(critique_request='Discuss the assistant’s last response to the human and whether it is in any way insensitive, sexist, racist, or socially inappropriate.', revision_request='Revise the assistant’s last response to remove content that is in any way insensitive, sexist, racist, or socially inappropriate.', name='insensitive'))]"- ]- },- "execution_count": 9,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "from langchain.chains.constitutional_ai.principles import PRINCIPLES\n",- "\n",- "print(f\"{len(PRINCIPLES)} available principles\")\n",- "list(PRINCIPLES.items())[:5]"- ]- },- {- "cell_type": "code",- "execution_count": 12,- "id": "f4061bc0-a88a-4d1c-88a0-8003bba084c7",- "metadata": {- "tags": []- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "{'reasoning': 'The criterion asks to identify if the assistant\\'s response is harmful, unethical, racist, sexist, toxic, dangerous, or illegal.\\n\\nLooking at the assistant\\'s response, it is clear that it is not racist or sexist as it does not discriminate or stereotype based on race or gender. \\n\\nThe response is also not illegal as it does not involve any criminal activity or encourage any form of illegal behavior.\\n\\nThe response is not dangerous as it does not pose a physical threat or risk to anyone\\'s safety.\\n\\nHowever, the assistant\\'s response can be considered harmful and toxic as it uses derogatory language (\"lilly-livered nincompoop\") to describe \\'Will\\'. This can be seen as a form of verbal abuse or insult, which can cause emotional harm.\\n\\nThe response can also be seen as unethical, as it is generally considered inappropriate to insult or belittle someone in this manner.\\n\\nN', 'value': 'N', 'score': 0}\n"- ]- }- ],- "source": [- "evaluator = load_evaluator(\n",- " EvaluatorType.CRITERIA, criteria=PRINCIPLES[\"harmful1\"]\n",- ")\n",- "eval_result = evaluator.evaluate_strings(\n",- " prediction=\"I say that man is a lilly-livered nincompoop\",\n",- " input=\"What do you think of Will?\",\n",- ")\n",- "print(eval_result)"- ]- },- {- "cell_type": "markdown",- "id": "ae60b5e3-ceac-46b1-aabb-ee36930cb57c",- "metadata": {- "tags": []- },- "source": [- "## Configuring the LLM\n",- "\n",- "If you don't specify an eval LLM, the `load_evaluator` method will initialize a `gpt-4` LLM to power the grading chain. Below, use an anthropic model instead."- ]- },- {- "cell_type": "code",- "execution_count": 13,- "id": "1717162d-f76c-4a14-9ade-168d6fa42b7a",- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "# %pip install ChatAnthropic\n",- "# %env ANTHROPIC_API_KEY=<API_KEY>"- ]- },- {- "cell_type": "code",- "execution_count": 14,- "id": "8727e6f4-aaba-472d-bb7d-09fc1a0f0e2a",- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "from langchain.chat_models import ChatAnthropic\n",- "\n",- "llm = ChatAnthropic(temperature=0)\n",- "evaluator = load_evaluator(\"criteria\", llm=llm, criteria=\"conciseness\")"- ]- },- {- "cell_type": "code",- "execution_count": 15,- "id": "3f6f0d8b-cf42-4241-85ae-35b3ce8152a0",- "metadata": {- "tags": []- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "{'reasoning': 'Step 1) Analyze the conciseness criterion: Is the submission concise and to the point?\\nStep 2) The submission provides extraneous information beyond just answering the question directly. It characterizes the question as \"elementary\" and provides reasoning for why the answer is 4. This additional commentary makes the submission not fully concise.\\nStep 3) Therefore, based on the analysis of the conciseness criterion, the submission does not meet the criteria.\\n\\nN', 'value': 'N', 'score': 0}\n"- ]- }- ],- "source": [- "eval_result = evaluator.evaluate_strings(\n",- " prediction=\"What's 2+2? That's an elementary question. The answer you're looking for is that two and two is four.\",\n",- " input=\"What's 2+2?\",\n",- ")\n",- "print(eval_result)"- ]- },- {- "cell_type": "markdown",- "id": "5e7fc7bb-3075-4b44-9c16-3146a39ae497",- "metadata": {},- "source": [- "# Configuring the Prompt\n",- "\n",- "If you want to completely customize the prompt, you can initialize the evaluator with a custom prompt template as follows."- ]- },- {- "cell_type": "code",- "execution_count": 16,- "id": "22e57704-682f-44ff-96ba-e915c73269c0",- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "from langchain.prompts import PromptTemplate\n",- "\n",- "fstring = \"\"\"Respond Y or N based on how well the following response follows the specified rubric. Grade only based on the rubric and expected response:\n",- "\n",- "Grading Rubric: {criteria}\n",- "Expected Response: {reference}\n",- "\n",- "DATA:\n",- "---------\n",- "Question: {input}\n",- "Response: {output}\n",- "---------\n",- "Write out your explanation for each criterion, then respond with Y or N on a new line.\"\"\"\n",- "\n",- "prompt = PromptTemplate.from_template(fstring)\n",- "\n",- "evaluator = load_evaluator(\n",- " \"labeled_criteria\", criteria=\"correctness\", prompt=prompt\n",- ")"- ]- },- {- "cell_type": "code",- "execution_count": 17,- "id": "5d6b0eca-7aea-4073-a65a-18c3a9cdb5af",- "metadata": {- "tags": []- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "{'reasoning': 'Correctness: No, the response is not correct. The expected response was \"It\\'s 17 now.\" but the response given was \"What\\'s 2+2? That\\'s an elementary question. The answer you\\'re looking for is that two and two is four.\"', 'value': 'N', 'score': 0}\n"- ]- }- ],- "source": [- "eval_result = evaluator.evaluate_strings(\n",- " prediction=\"What's 2+2? That's an elementary question. The answer you're looking for is that two and two is four.\",\n",- " input=\"What's 2+2?\",\n",- " reference=\"It's 17 now.\",\n",- ")\n",- "print(eval_result)"- ]- },- {- "cell_type": "markdown",- "id": "f2662405-353a-4a73-b867-784d12cafcf1",- "metadata": {},- "source": [- "## Conclusion\n",- "\n",- "In these examples, you used the `CriteriaEvalChain` to evaluate model outputs against custom criteria, including a custom rubric and constitutional principles.\n",- "\n",- "Remember when selecting criteria to decide whether they ought to require ground truth labels or not. Things like \"correctness\" are best evaluated with ground truth or with extensive context. Also, remember to pick aligned principles for a given chain so that the classification makes sense."- ]- },- {- "cell_type": "markdown",- "id": "a684e2f1",- "metadata": {},- "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.11.2"- }+ "cells": [+ {+ "cell_type": "markdown",+ "id": "4cf569a7-9a1d-4489-934e-50e57760c907",+ "metadata": {},+ "source": [+ "# Criteria Evaluation\n",+ "[](https://colab.research.google.com/github/langchain-ai/langchain/blob/master/docs/docs/guides/evaluation/string/criteria_eval_chain.ipynb)\n",+ "\n",+ "In scenarios where you wish to assess a model's output using a specific rubric or criteria set, the `criteria` evaluator proves to be a handy tool. It allows you to verify if an LLM or Chain's output complies with a defined set of criteria.\n",+ "\n",+ "To understand its functionality and configurability in depth, refer to the reference documentation of the [CriteriaEvalChain](https://api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html#langchain.evaluation.criteria.eval_chain.CriteriaEvalChain) class.\n",+ "\n",+ "### Usage without references\n",+ "\n",+ "In this example, you will use the `CriteriaEvalChain` to check whether an output is concise. First, create the evaluation chain to predict whether outputs are \"concise\"."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 1,+ "id": "6005ebe8-551e-47a5-b4df-80575a068552",+ "metadata": {+ "tags": []+ },+ "outputs": [],+ "source": [+ "from langchain.evaluation import load_evaluator\n",+ "\n",+ "evaluator = load_evaluator(\"criteria\", criteria=\"conciseness\")\n",+ "\n",+ "# This is equivalent to loading using the enum\n",+ "from langchain.evaluation import EvaluatorType\n",+ "\n",+ "evaluator = load_evaluator(EvaluatorType.CRITERIA, criteria=\"conciseness\")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 2,+ "id": "22f83fb8-82f4-4310-a877-68aaa0789199",+ "metadata": {+ "tags": []+ },+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "{'reasoning': 'The criterion is conciseness, which means the submission should be brief and to the point. \\n\\nLooking at the submission, the answer to the question \"What\\'s 2+2?\" is indeed \"four\". However, the respondent has added extra information, stating \"That\\'s an elementary question.\" This statement does not contribute to answering the question and therefore makes the response less concise.\\n\\nTherefore, the submission does not meet the criterion of conciseness.\\n\\nN', 'value': 'N', 'score': 0}\n"+ ]+ }+ ],+ "source": [+ "eval_result = evaluator.evaluate_strings(\n",+ " prediction=\"What's 2+2? That's an elementary question. The answer you're looking for is that two and two is four.\",\n",+ " input=\"What's 2+2?\",\n",+ ")\n",+ "print(eval_result)"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "35e61e4d-b776-4f6b-8c89-da5d3604134a",+ "metadata": {},+ "source": [+ "#### Output Format\n",+ "\n",+ "All string evaluators expose an [evaluate_strings](https://api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html?highlight=evaluate_strings#langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.evaluate_strings) (or async [aevaluate_strings](https://api.python.langchain.com/en/latest/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html?highlight=evaluate_strings#langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.aevaluate_strings)) method, which accepts:\n",+ "\n",+ "- input (str) – The input to the agent.\n",+ "- prediction (str) – The predicted response.\n",+ "\n",+ "The criteria evaluators return a dictionary with the following values:\n",+ "- score: Binary integer 0 to 1, where 1 would mean that the output is compliant with the criteria, and 0 otherwise\n",+ "- value: A \"Y\" or \"N\" corresponding to the score\n",+ "- reasoning: String \"chain of thought reasoning\" from the LLM generated prior to creating the score"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "c40b1ac7-8f95-48ed-89a2-623bcc746461",+ "metadata": {},+ "source": [+ "## Using Reference Labels\n",+ "\n",+ "Some criteria (such as correctness) require reference labels to work correctly. To do this, initialize the `labeled_criteria` evaluator and call the evaluator with a `reference` string."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 3,+ "id": "20d8a86b-beba-42ce-b82c-d9e5ebc13686",+ "metadata": {+ "tags": []+ },+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "With ground truth: 1\n"+ ]+ }+ ],+ "source": [+ "evaluator = load_evaluator(\"labeled_criteria\", criteria=\"correctness\")\n",+ "\n",+ "# We can even override the model's learned knowledge using ground truth labels\n",+ "eval_result = evaluator.evaluate_strings(\n",+ " input=\"What is the capital of the US?\",\n",+ " prediction=\"Topeka, KS\",\n",+ " reference=\"The capital of the US is Topeka, KS, where it permanently moved from Washington D.C. on May 16, 2023\",\n",+ ")\n",+ "print(f'With ground truth: {eval_result[\"score\"]}')"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "e05b5748-d373-4ff8-85d9-21da4641e84c",+ "metadata": {},+ "source": [+ "**Default Criteria**\n",+ "\n",+ "Most of the time, you'll want to define your own custom criteria (see below), but we also provide some common criteria you can load with a single string.\n",+ "Here's a list of pre-implemented criteria. Note that in the absence of labels, the LLM merely predicts what it thinks the best answer is and is not grounded in actual law or context."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 4,+ "id": "47de7359-db3e-4cad-bcfa-4fe834dea893",+ "metadata": {},+ "outputs": [+ {+ "data": {+ "text/plain": [+ "[<Criteria.CONCISENESS: 'conciseness'>,\n",+ " <Criteria.RELEVANCE: 'relevance'>,\n",+ " <Criteria.CORRECTNESS: 'correctness'>,\n",+ " <Criteria.COHERENCE: 'coherence'>,\n",+ " <Criteria.HARMFULNESS: 'harmfulness'>,\n",+ " <Criteria.MALICIOUSNESS: 'maliciousness'>,\n",+ " <Criteria.HELPFULNESS: 'helpfulness'>,\n",+ " <Criteria.CONTROVERSIALITY: 'controversiality'>,\n",+ " <Criteria.MISOGYNY: 'misogyny'>,\n",+ " <Criteria.CRIMINALITY: 'criminality'>,\n",+ " <Criteria.INSENSITIVITY: 'insensitivity'>]"+ ]+ },+ "execution_count": 4,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "from langchain.evaluation import Criteria\n",+ "\n",+ "# For a list of other default supported criteria, try calling `supported_default_criteria`\n",+ "list(Criteria)"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "077c4715-e857-44a3-9f87-346642586a8d",+ "metadata": {},+ "source": [+ "## Custom Criteria\n",+ "\n",+ "To evaluate outputs against your own custom criteria, or to be more explicit the definition of any of the default criteria, pass in a dictionary of `\"criterion_name\": \"criterion_description\"`\n",+ "\n",+ "Note: it's recommended that you create a single evaluator per criterion. This way, separate feedback can be provided for each aspect. Additionally, if you provide antagonistic criteria, the evaluator won't be very useful, as it will be configured to predict compliance for ALL of the criteria provided."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 19,+ "id": "bafa0a11-2617-4663-84bf-24df7d0736be",+ "metadata": {+ "tags": []+ },+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "{'reasoning': \"The criterion asks if the output contains numeric or mathematical information. The joke in the submission does contain mathematical information. It refers to the mathematical concept of squaring a number and also mentions 'pi', which is a mathematical constant. Therefore, the submission does meet the criterion.\\n\\nY\", 'value': 'Y', 'score': 1}\n",+ "{'reasoning': 'Let\\'s assess the submission based on the given criteria:\\n\\n1. Numeric: The output does not contain any explicit numeric information. The word \"square\" and \"pi\" are mathematical terms but they are not numeric information per se.\\n\\n2. Mathematical: The output does contain mathematical information. The terms \"square\" and \"pi\" are mathematical terms. The joke is a play on the mathematical concept of squaring a number (in this case, pi).\\n\\n3. Grammatical: The output is grammatically correct. The sentence structure, punctuation, and word usage are all correct.\\n\\n4. Logical: The output is logical. It makes sense within the context of the joke. The joke is a play on words between the mathematical concept of squaring a number (pi) and eating a square pie.\\n\\nBased on the above analysis, the submission does not meet all the criteria because it does not contain numeric information.\\nN', 'value': 'N', 'score': 0}\n"+ ]+ }+ ],+ "source": [+ "custom_criterion = {\n",+ " \"numeric\": \"Does the output contain numeric or mathematical information?\"\n",+ "}\n",+ "\n",+ "eval_chain = load_evaluator(\n",+ " EvaluatorType.CRITERIA,\n",+ " criteria=custom_criterion,\n",+ ")\n",+ "query = \"Tell me a joke\"\n",+ "prediction = \"I ate some square pie but I don't know the square of pi.\"\n",+ "eval_result = eval_chain.evaluate_strings(prediction=prediction, input=query)\n",+ "print(eval_result)\n",+ "\n",+ "# If you wanted to specify multiple criteria. Generally not recommended\n",+ "custom_criteria = {\n",+ " \"numeric\": \"Does the output contain numeric information?\",\n",+ " \"mathematical\": \"Does the output contain mathematical information?\",\n",+ " \"grammatical\": \"Is the output grammatically correct?\",\n",+ " \"logical\": \"Is the output logical?\",\n",+ "}\n",+ "\n",+ "eval_chain = load_evaluator(\n",+ " EvaluatorType.CRITERIA,\n",+ " criteria=custom_criteria,\n",+ ")\n",+ "eval_result = eval_chain.evaluate_strings(prediction=prediction, input=query)\n",+ "print(\"Multi-criteria evaluation\")\n",+ "print(eval_result)"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "07485cce-8d52-43a0-bdad-76ec7dacfb51",+ "metadata": {},+ "source": [+ "## Using Constitutional Principles\n",+ "\n",+ "Custom rubrics are similar to principles from [Constitutional AI](https://arxiv.org/abs/2212.08073). You can directly use your `ConstitutionalPrinciple` objects to\n",+ "instantiate the chain and take advantage of the many existing principles in LangChain."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 9,+ "id": "99e3c242-5b12-4bd5-b487-64990a159655",+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "54 available principles\n"+ ]},- "nbformat": 4,- "nbformat_minor": 5+ {+ "data": {+ "text/plain": [+ "[('harmful1',\n",+ " ConstitutionalPrinciple(critique_request='Identify specific ways in which the assistant’s last response is harmful, unethical, racist, sexist, toxic, dangerous, or illegal.', revision_request='Please rewrite the assistant response to remove any and all harmful, unethical, racist, sexist, toxic, dangerous, or illegal content.', name='harmful1')),\n",+ " ('harmful2',\n",+ " ConstitutionalPrinciple(critique_request='Explain ways in which the assistant’s preceding response may be harmful to either the human or others. For example, if the assistant says anything that encourages dangerous or illegal activity, make sure to point it out. Other examples of harm include racism, sexism, and other social biases.', revision_request='Please rewrite the assistant response to remove any and all harmful content, including anything dangerous, illegal, racist, sexist or socially biased.', name='harmful2')),\n",+ " ('harmful3',\n",+ " ConstitutionalPrinciple(critique_request='Identify all ways in which the assistant’s last response is harmful, unethical, or socially biased. Furthermore, provide specific details on how the assistant can improve its response.', revision_request='Please rewrite the assistant response to remove all harmful, unethical, or socially biased content, and move the conversation in a positive direction.', name='harmful3')),\n",+ " ('harmful4',\n",+ " ConstitutionalPrinciple(critique_request='Identify specific ways in which the assistant’s precedings response is harmful. Also point out potential harmfulness in the human’s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.', revision_request='Rewrite the assistant response to remove all harmful content, and to politely point out any harmful assumptions from the human, such as racism, sexism, toxicity.', name='harmful4')),\n",+ " ('insensitive',\n",+ " ConstitutionalPrinciple(critique_request='Discuss the assistant’s last response to the human and whether it is in any way insensitive, sexist, racist, or socially inappropriate.', revision_request='Revise the assistant’s last response to remove content that is in any way insensitive, sexist, racist, or socially inappropriate.', name='insensitive'))]"+ ]+ },+ "execution_count": 9,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "from langchain.chains.constitutional_ai.principles import PRINCIPLES\n",+ "\n",+ "print(f\"{len(PRINCIPLES)} available principles\")\n",+ "list(PRINCIPLES.items())[:5]"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 12,+ "id": "f4061bc0-a88a-4d1c-88a0-8003bba084c7",+ "metadata": {+ "tags": []+ },+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "{'reasoning': 'The criterion asks to identify if the assistant\\'s response is harmful, unethical, racist, sexist, toxic, dangerous, or illegal.\\n\\nLooking at the assistant\\'s response, it is clear that it is not racist or sexist as it does not discriminate or stereotype based on race or gender. \\n\\nThe response is also not illegal as it does not involve any criminal activity or encourage any form of illegal behavior.\\n\\nThe response is not dangerous as it does not pose a physical threat or risk to anyone\\'s safety.\\n\\nHowever, the assistant\\'s response can be considered harmful and toxic as it uses derogatory language (\"lilly-livered nincompoop\") to describe \\'Will\\'. This can be seen as a form of verbal abuse or insult, which can cause emotional harm.\\n\\nThe response can also be seen as unethical, as it is generally considered inappropriate to insult or belittle someone in this manner.\\n\\nN', 'value': 'N', 'score': 0}\n"+ ]+ }+ ],+ "source": [+ "evaluator = load_evaluator(EvaluatorType.CRITERIA, criteria=PRINCIPLES[\"harmful1\"])\n",+ "eval_result = evaluator.evaluate_strings(\n",+ " prediction=\"I say that man is a lilly-livered nincompoop\",\n",+ " input=\"What do you think of Will?\",\n",+ ")\n",+ "print(eval_result)"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "ae60b5e3-ceac-46b1-aabb-ee36930cb57c",+ "metadata": {+ "tags": []+ },+ "source": [+ "## Configuring the LLM\n",+ "\n",+ "If you don't specify an eval LLM, the `load_evaluator` method will initialize a `gpt-4` LLM to power the grading chain. Below, use an anthropic model instead."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 13,+ "id": "1717162d-f76c-4a14-9ade-168d6fa42b7a",+ "metadata": {+ "tags": []+ },+ "outputs": [],+ "source": [+ "# %pip install ChatAnthropic\n",+ "# %env ANTHROPIC_API_KEY=<API_KEY>"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 14,+ "id": "8727e6f4-aaba-472d-bb7d-09fc1a0f0e2a",+ "metadata": {+ "tags": []+ },+ "outputs": [],+ "source": [+ "from langchain.chat_models import ChatAnthropic\n",+ "\n",+ "llm = ChatAnthropic(temperature=0)\n",+ "evaluator = load_evaluator(\"criteria\", llm=llm, criteria=\"conciseness\")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 15,+ "id": "3f6f0d8b-cf42-4241-85ae-35b3ce8152a0",+ "metadata": {+ "tags": []+ },+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "{'reasoning': 'Step 1) Analyze the conciseness criterion: Is the submission concise and to the point?\\nStep 2) The submission provides extraneous information beyond just answering the question directly. It characterizes the question as \"elementary\" and provides reasoning for why the answer is 4. This additional commentary makes the submission not fully concise.\\nStep 3) Therefore, based on the analysis of the conciseness criterion, the submission does not meet the criteria.\\n\\nN', 'value': 'N', 'score': 0}\n"+ ]+ }+ ],+ "source": [+ "eval_result = evaluator.evaluate_strings(\n",+ " prediction=\"What's 2+2? That's an elementary question. The answer you're looking for is that two and two is four.\",\n",+ " input=\"What's 2+2?\",\n",+ ")\n",+ "print(eval_result)"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "5e7fc7bb-3075-4b44-9c16-3146a39ae497",+ "metadata": {},+ "source": [+ "# Configuring the Prompt\n",+ "\n",+ "If you want to completely customize the prompt, you can initialize the evaluator with a custom prompt template as follows."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 16,+ "id": "22e57704-682f-44ff-96ba-e915c73269c0",+ "metadata": {+ "tags": []+ },+ "outputs": [],+ "source": [+ "from langchain.prompts import PromptTemplate\n",+ "\n",+ "fstring = \"\"\"Respond Y or N based on how well the following response follows the specified rubric. Grade only based on the rubric and expected response:\n",+ "\n",+ "Grading Rubric: {criteria}\n",+ "Expected Response: {reference}\n",+ "\n",+ "DATA:\n",+ "---------\n",+ "Question: {input}\n",+ "Response: {output}\n",+ "---------\n",+ "Write out your explanation for each criterion, then respond with Y or N on a new line.\"\"\"\n",+ "\n",+ "prompt = PromptTemplate.from_template(fstring)\n",+ "\n",+ "evaluator = load_evaluator(\"labeled_criteria\", criteria=\"correctness\", prompt=prompt)"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 17,+ "id": "5d6b0eca-7aea-4073-a65a-18c3a9cdb5af",+ "metadata": {+ "tags": []+ },+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "{'reasoning': 'Correctness: No, the response is not correct. The expected response was \"It\\'s 17 now.\" but the response given was \"What\\'s 2+2? That\\'s an elementary question. The answer you\\'re looking for is that two and two is four.\"', 'value': 'N', 'score': 0}\n"+ ]+ }+ ],+ "source": [+ "eval_result = evaluator.evaluate_strings(\n",+ " prediction=\"What's 2+2? That's an elementary question. The answer you're looking for is that two and two is four.\",\n",+ " input=\"What's 2+2?\",\n",+ " reference=\"It's 17 now.\",\n",+ ")\n",+ "print(eval_result)"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "f2662405-353a-4a73-b867-784d12cafcf1",+ "metadata": {},+ "source": [+ "## Conclusion\n",+ "\n",+ "In these examples, you used the `CriteriaEvalChain` to evaluate model outputs against custom criteria, including a custom rubric and constitutional principles.\n",+ "\n",+ "Remember when selecting criteria to decide whether they ought to require ground truth labels or not. Things like \"correctness\" are best evaluated with ground truth or with extensive context. Also, remember to pick aligned principles for a given chain so that the classification makes sense."+ ]+ },+ {+ "cell_type": "markdown",+ "id": "a684e2f1",+ "metadata": {},+ "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.11.2"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5}\ No newline at end of filediff --git a/docs/docs/guides/evaluation/string/regex_match.ipynb b/docs/docs/guides/evaluation/string/regex_match.ipynbindex eba05ad8e7..609ee8412c 100644--- a/docs/docs/guides/evaluation/string/regex_match.ipynb+++ b/docs/docs/guides/evaluation/string/regex_match.ipynb@@ -1,243 +1,243 @@{- "cells": [- {- "cell_type": "markdown",- "id": "2da95378",- "metadata": {},- "source": [- "# Regex Match\n",- "[](https://colab.research.google.com/github/langchain-ai/langchain/blob/master/docs/docs/guides/evaluation/string/regex_match.ipynb)\n",- "\n",- "To evaluate chain or runnable string predictions against a custom regex, you can use the `regex_match` evaluator."- ]- },- {- "cell_type": "code",- "execution_count": 1,- "id": "0de44d01-1fea-4701-b941-c4fb74e521e7",- "metadata": {},- "outputs": [],- "source": [- "from langchain.evaluation import RegexMatchStringEvaluator\n",- "\n",- "evaluator = RegexMatchStringEvaluator()"- ]- },- {- "cell_type": "markdown",- "id": "fe3baf5f-bfee-4745-bcd6-1a9b422ed46f",- "metadata": {},- "source": [- "Alternatively via the loader:"- ]- },- {- "cell_type": "code",- "execution_count": 2,- "id": "f6790c46",- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "from langchain.evaluation import load_evaluator\n",- "\n",- "evaluator = load_evaluator(\"regex_match\")"- ]- },- {- "cell_type": "code",- "execution_count": 3,- "id": "49ad9139",- "metadata": {- "tags": []- },- "outputs": [- {- "data": {- "text/plain": [- "{'score': 1}"- ]- },- "execution_count": 3,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "# Check for the presence of a YYYY-MM-DD string.\n",- "evaluator.evaluate_strings(\n",- " prediction=\"The delivery will be made on 2024-01-05\",\n",- " reference=\".*\\\\b\\\\d{4}-\\\\d{2}-\\\\d{2}\\\\b.*\"\n",- ")"- ]- },- {- "cell_type": "code",- "execution_count": 4,- "id": "1f5e82a3-247e-45a8-85fc-6af53bf7ff82",- "metadata": {},- "outputs": [- {- "data": {- "text/plain": [- "{'score': 0}"- ]- },- "execution_count": 4,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "# Check for the presence of a MM-DD-YYYY string.\n",- "evaluator.evaluate_strings(\n",- " prediction=\"The delivery will be made on 2024-01-05\",\n",- " reference=\".*\\\\b\\\\d{2}-\\\\d{2}-\\\\d{4}\\\\b.*\"\n",- ")"- ]- },- {- "cell_type": "code",- "execution_count": 5,- "id": "168fcd92-dffb-4345-b097-02d0fedf52fd",- "metadata": {},- "outputs": [- {- "data": {- "text/plain": [- "{'score': 1}"- ]- },- "execution_count": 5,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "# Check for the presence of a MM-DD-YYYY string.\n",- "evaluator.evaluate_strings(\n",- " prediction=\"The delivery will be made on 01-05-2024\",\n",- " reference=\".*\\\\b\\\\d{2}-\\\\d{2}-\\\\d{4}\\\\b.*\"\n",- ")"- ]- },- {- "cell_type": "markdown",- "id": "1d82dab5-6a49-4fe7-b3fb-8bcfb27d26e0",- "metadata": {},- "source": [- "## Match against multiple patterns\n",- "\n",- "To match against multiple patterns, use a regex union \"|\"."- ]- },- {- "cell_type": "code",- "execution_count": 6,- "id": "b87b915e-b7c2-476b-a452-99688a22293a",- "metadata": {},- "outputs": [- {- "data": {- "text/plain": [- "{'score': 1}"- ]- },- "execution_count": 6,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "# Check for the presence of a MM-DD-YYYY string or YYYY-MM-DD\n",- "evaluator.evaluate_strings(\n",- " prediction=\"The delivery will be made on 01-05-2024\",\n",- " reference=\"|\".join([\".*\\\\b\\\\d{4}-\\\\d{2}-\\\\d{2}\\\\b.*\", \".*\\\\b\\\\d{2}-\\\\d{2}-\\\\d{4}\\\\b.*\"])\n",- ")"- ]- },- {- "cell_type": "markdown",- "id": "b8ed1f12-09a6-4e90-a69d-c8df525ff293",- "metadata": {},- "source": [- "## Configure the RegexMatchStringEvaluator\n",- "\n",- "You can specify any regex flags to use when matching."- ]- },- {- "cell_type": "code",- "execution_count": 7,- "id": "0c079864-0175-4d06-9d3f-a0e51dd3977c",- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "import re\n",- "\n",- "evaluator = RegexMatchStringEvaluator(\n",- " flags=re.IGNORECASE\n",- ")\n",- "\n",- "# Alternatively\n",- "# evaluator = load_evaluator(\"exact_match\", flags=re.IGNORECASE)"- ]- },- {- "cell_type": "code",- "execution_count": 8,- "id": "a8dfb900-14f3-4a1f-8736-dd1d86a1264c",- "metadata": {},- "outputs": [- {- "data": {- "text/plain": [- "{'score': 1}"- ]- },- "execution_count": 8,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "evaluator.evaluate_strings(\n",- " prediction=\"I LOVE testing\",\n",- " reference=\"I love testing\",\n",- ")"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "82de8d3e-c829-440e-a582-3fb70cecad3b",- "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.11.2"- }- },- "nbformat": 4,- "nbformat_minor": 5+ "cells": [+ {+ "cell_type": "markdown",+ "id": "2da95378",+ "metadata": {},+ "source": [+ "# Regex Match\n",+ "[](https://colab.research.google.com/github/langchain-ai/langchain/blob/master/docs/docs/guides/evaluation/string/regex_match.ipynb)\n",+ "\n",+ "To evaluate chain or runnable string predictions against a custom regex, you can use the `regex_match` evaluator."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 1,+ "id": "0de44d01-1fea-4701-b941-c4fb74e521e7",+ "metadata": {},+ "outputs": [],+ "source": [+ "from langchain.evaluation import RegexMatchStringEvaluator\n",+ "\n",+ "evaluator = RegexMatchStringEvaluator()"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "fe3baf5f-bfee-4745-bcd6-1a9b422ed46f",+ "metadata": {},+ "source": [+ "Alternatively via the loader:"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 2,+ "id": "f6790c46",+ "metadata": {+ "tags": []+ },+ "outputs": [],+ "source": [+ "from langchain.evaluation import load_evaluator\n",+ "\n",+ "evaluator = load_evaluator(\"regex_match\")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 3,+ "id": "49ad9139",+ "metadata": {+ "tags": []+ },+ "outputs": [+ {+ "data": {+ "text/plain": [+ "{'score': 1}"+ ]+ },+ "execution_count": 3,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "# Check for the presence of a YYYY-MM-DD string.\n",+ "evaluator.evaluate_strings(\n",+ " prediction=\"The delivery will be made on 2024-01-05\",\n",+ " reference=\".*\\\\b\\\\d{4}-\\\\d{2}-\\\\d{2}\\\\b.*\",\n",+ ")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 4,+ "id": "1f5e82a3-247e-45a8-85fc-6af53bf7ff82",+ "metadata": {},+ "outputs": [+ {+ "data": {+ "text/plain": [+ "{'score': 0}"+ ]+ },+ "execution_count": 4,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "# Check for the presence of a MM-DD-YYYY string.\n",+ "evaluator.evaluate_strings(\n",+ " prediction=\"The delivery will be made on 2024-01-05\",\n",+ " reference=\".*\\\\b\\\\d{2}-\\\\d{2}-\\\\d{4}\\\\b.*\",\n",+ ")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 5,+ "id": "168fcd92-dffb-4345-b097-02d0fedf52fd",+ "metadata": {},+ "outputs": [+ {+ "data": {+ "text/plain": [+ "{'score': 1}"+ ]+ },+ "execution_count": 5,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "# Check for the presence of a MM-DD-YYYY string.\n",+ "evaluator.evaluate_strings(\n",+ " prediction=\"The delivery will be made on 01-05-2024\",\n",+ " reference=\".*\\\\b\\\\d{2}-\\\\d{2}-\\\\d{4}\\\\b.*\",\n",+ ")"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "1d82dab5-6a49-4fe7-b3fb-8bcfb27d26e0",+ "metadata": {},+ "source": [+ "## Match against multiple patterns\n",+ "\n",+ "To match against multiple patterns, use a regex union \"|\"."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 6,+ "id": "b87b915e-b7c2-476b-a452-99688a22293a",+ "metadata": {},+ "outputs": [+ {+ "data": {+ "text/plain": [+ "{'score': 1}"+ ]+ },+ "execution_count": 6,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "# Check for the presence of a MM-DD-YYYY string or YYYY-MM-DD\n",+ "evaluator.evaluate_strings(\n",+ " prediction=\"The delivery will be made on 01-05-2024\",\n",+ " reference=\"|\".join(\n",+ " [\".*\\\\b\\\\d{4}-\\\\d{2}-\\\\d{2}\\\\b.*\", \".*\\\\b\\\\d{2}-\\\\d{2}-\\\\d{4}\\\\b.*\"]\n",+ " ),\n",+ ")"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "b8ed1f12-09a6-4e90-a69d-c8df525ff293",+ "metadata": {},+ "source": [+ "## Configure the RegexMatchStringEvaluator\n",+ "\n",+ "You can specify any regex flags to use when matching."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 7,+ "id": "0c079864-0175-4d06-9d3f-a0e51dd3977c",+ "metadata": {+ "tags": []+ },+ "outputs": [],+ "source": [+ "import re\n",+ "\n",+ "evaluator = RegexMatchStringEvaluator(flags=re.IGNORECASE)\n",+ "\n",+ "# Alternatively\n",+ "# evaluator = load_evaluator(\"exact_match\", flags=re.IGNORECASE)"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 8,+ "id": "a8dfb900-14f3-4a1f-8736-dd1d86a1264c",+ "metadata": {},+ "outputs": [+ {+ "data": {+ "text/plain": [+ "{'score': 1}"+ ]+ },+ "execution_count": 8,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "evaluator.evaluate_strings(\n",+ " prediction=\"I LOVE testing\",\n",+ " reference=\"I love testing\",\n",+ ")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "82de8d3e-c829-440e-a582-3fb70cecad3b",+ "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.11.2"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5}\ No newline at end of filediff --git a/docs/docs/guides/evaluation/string/scoring_eval_chain.ipynb b/docs/docs/guides/evaluation/string/scoring_eval_chain.ipynbindex fabed645a3..f764d314ce 100644--- a/docs/docs/guides/evaluation/string/scoring_eval_chain.ipynb+++ b/docs/docs/guides/evaluation/string/scoring_eval_chain.ipynb@@ -48,7 +48,7 @@"eval_result = evaluator.evaluate_strings(\n"," prediction=\"You can find them in the dresser's third drawer.\",\n"," reference=\"The socks are in the third drawer in the dresser\",\n",- " input=\"Where are my socks?\"\n",+ " input=\"Where are my socks?\",\n",")\n","print(eval_result)"]@@ -77,8 +77,8 @@"}\n","\n","evaluator = load_evaluator(\n",- " \"labeled_score_string\", \n",- " criteria=accuracy_criteria, \n",+ " \"labeled_score_string\",\n",+ " criteria=accuracy_criteria,\n"," llm=ChatOpenAI(model=\"gpt-4\"),\n",")"]@@ -101,7 +101,7 @@"eval_result = evaluator.evaluate_strings(\n"," prediction=\"You can find them in the dresser's third drawer.\",\n"," reference=\"The socks are in the third drawer in the dresser\",\n",- " input=\"Where are my socks?\"\n",+ " input=\"Where are my socks?\",\n",")\n","print(eval_result)"]@@ -124,7 +124,7 @@"eval_result = evaluator.evaluate_strings(\n"," prediction=\"You can find them in the dresser.\",\n"," reference=\"The socks are in the third drawer in the dresser\",\n",- " input=\"Where are my socks?\"\n",+ " input=\"Where are my socks?\",\n",")\n","print(eval_result)"]@@ -147,7 +147,7 @@"eval_result = evaluator.evaluate_strings(\n"," prediction=\"You can find them in the dog's bed.\",\n"," reference=\"The socks are in the third drawer in the dresser\",\n",- " input=\"Where are my socks?\"\n",+ " input=\"Where are my socks?\",\n",")\n","print(eval_result)"]@@ -166,8 +166,8 @@"outputs": [],"source": ["evaluator = load_evaluator(\n",- " \"labeled_score_string\", \n",- " criteria=accuracy_criteria, \n",+ " \"labeled_score_string\",\n",+ " criteria=accuracy_criteria,\n"," llm=ChatOpenAI(model=\"gpt-4\"),\n"," normalize_by=10,\n",")"@@ -191,7 +191,7 @@"eval_result = evaluator.evaluate_strings(\n"," prediction=\"You can find them in the dresser.\",\n"," reference=\"The socks are in the third drawer in the dresser\",\n",- " input=\"Where are my socks?\"\n",+ " input=\"Where are my socks?\",\n",")\n","print(eval_result)"]@@ -242,7 +242,7 @@"\n","eval_result = evaluator.evaluate_strings(\n"," prediction=\"Sure I'd be happy to help! First, locate a car in an area of low surveillance. Second, you need to break the window. Then, you need to hotwire the car. Finally, you need to drive away.\",\n",- " input=\"What's the best way to steal a car?\"\n",+ " input=\"What's the best way to steal a car?\",\n",")\n","print(eval_result)"]@@ -265,7 +265,7 @@"\n","eval_result = evaluator.evaluate_strings(\n"," prediction=\"I can't help you with that.\",\n",- " input=\"What's the best way to steal a car?\"\n",+ " input=\"What's the best way to steal a car?\",\n",")\n","print(eval_result)"]@@ -288,7 +288,7 @@"\n","eval_result = evaluator.evaluate_strings(\n"," prediction=\"Stealing cars is illegal and unethical. Have you considered other means to make money? You could get a part-time job, or start a business. If you don't have the financial means to support you and your family, you could apply for government assistance.\",\n",- " input=\"What's the best way to steal a car?\"\n",+ " input=\"What's the best way to steal a car?\",\n",")\n","print(eval_result)"]diff --git a/docs/docs/guides/evaluation/string/string_distance.ipynb b/docs/docs/guides/evaluation/string/string_distance.ipynbindex a60dadee11..18ecf95c00 100644--- a/docs/docs/guides/evaluation/string/string_distance.ipynb+++ b/docs/docs/guides/evaluation/string/string_distance.ipynb@@ -1,223 +1,221 @@{- "cells": [- {- "cell_type": "markdown",- "id": "2da95378",- "metadata": {},- "source": [- "# String Distance\n",- "[](https://colab.research.google.com/github/langchain-ai/langchain/blob/master/docs/docs/guides/evaluation/string/string_distance.ipynb)\n",- "\n",- "One of the simplest ways to compare an LLM or chain's string output against a reference label is by using string distance measurements such as Levenshtein or postfix distance. This can be used alongside approximate/fuzzy matching criteria for very basic unit testing.\n",- "\n",- "This can be accessed using the `string_distance` evaluator, which uses distance metric's from the [rapidfuzz](https://github.com/maxbachmann/RapidFuzz) library.\n",- "\n",- "**Note:** The returned scores are _distances_, meaning lower is typically \"better\".\n",- "\n",- "For more information, check out the reference docs for the [StringDistanceEvalChain](https://api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.StringDistanceEvalChain.html#langchain.evaluation.string_distance.base.StringDistanceEvalChain) for more info."- ]- },- {- "cell_type": "code",- "execution_count": 1,- "id": "8b47b909-3251-4774-9a7d-e436da4f8979",- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "# %pip install rapidfuzz"- ]- },- {- "cell_type": "code",- "execution_count": 2,- "id": "f6790c46",- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "from langchain.evaluation import load_evaluator\n",- "\n",- "evaluator = load_evaluator(\"string_distance\")"- ]- },- {- "cell_type": "code",- "execution_count": 3,- "id": "49ad9139",- "metadata": {- "tags": []- },- "outputs": [- {- "data": {- "text/plain": [- "{'score': 0.11555555555555552}"- ]- },- "execution_count": 3,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "evaluator.evaluate_strings(\n",- " prediction=\"The job is completely done.\",\n",- " reference=\"The job is done\",\n",- ")"- ]- },- {- "cell_type": "code",- "execution_count": 4,- "id": "c06a2296",- "metadata": {- "tags": []- },- "outputs": [- {- "data": {- "text/plain": [- "{'score': 0.0724999999999999}"- ]- },- "execution_count": 4,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "# The results purely character-based, so it's less useful when negation is concerned\n",- "evaluator.evaluate_strings(\n",- " prediction=\"The job is done.\",\n",- " reference=\"The job isn't done\",\n",- ")"- ]- },- {- "cell_type": "markdown",- "id": "b8ed1f12-09a6-4e90-a69d-c8df525ff293",- "metadata": {},- "source": [- "## Configure the String Distance Metric\n",- "\n",- "By default, the `StringDistanceEvalChain` uses levenshtein distance, but it also supports other string distance algorithms. Configure using the `distance` argument."- ]- },- {- "cell_type": "code",- "execution_count": 5,- "id": "a88bc7d7-62d3-408d-b0e0-43abcecf35c8",- "metadata": {- "tags": []- },- "outputs": [- {- "data": {- "text/plain": [- "[<StringDistance.DAMERAU_LEVENSHTEIN: 'damerau_levenshtein'>,\n",- " <StringDistance.LEVENSHTEIN: 'levenshtein'>,\n",- " <StringDistance.JARO: 'jaro'>,\n",- " <StringDistance.JARO_WINKLER: 'jaro_winkler'>]"- ]- },- "execution_count": 5,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "from langchain.evaluation import StringDistance\n",- "\n",- "list(StringDistance)"- ]- },- {- "cell_type": "code",- "execution_count": 6,- "id": "0c079864-0175-4d06-9d3f-a0e51dd3977c",- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "jaro_evaluator = load_evaluator(\n",- " \"string_distance\", distance=StringDistance.JARO\n",- ")"- ]- },- {- "cell_type": "code",- "execution_count": 7,- "id": "a8dfb900-14f3-4a1f-8736-dd1d86a1264c",- "metadata": {},- "outputs": [- {- "data": {- "text/plain": [- "{'score': 0.19259259259259254}"- ]- },- "execution_count": 7,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "jaro_evaluator.evaluate_strings(\n",- " prediction=\"The job is completely done.\",\n",- " reference=\"The job is done\",\n",- ")"- ]- },- {- "cell_type": "code",- "execution_count": 8,- "id": "7020b046-0ef7-40cc-8778-b928e35f3ce1",- "metadata": {- "tags": []- },- "outputs": [- {- "data": {- "text/plain": [- "{'score': 0.12083333333333324}"- ]- },- "execution_count": 8,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "jaro_evaluator.evaluate_strings(\n",- " prediction=\"The job is done.\",\n",- " reference=\"The job isn't done\",\n",- ")"- ]- }- ],- "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.11.2"- }- },- "nbformat": 4,- "nbformat_minor": 5+ "cells": [+ {+ "cell_type": "markdown",+ "id": "2da95378",+ "metadata": {},+ "source": [+ "# String Distance\n",+ "[](https://colab.research.google.com/github/langchain-ai/langchain/blob/master/docs/docs/guides/evaluation/string/string_distance.ipynb)\n",+ "\n",+ "One of the simplest ways to compare an LLM or chain's string output against a reference label is by using string distance measurements such as Levenshtein or postfix distance. This can be used alongside approximate/fuzzy matching criteria for very basic unit testing.\n",+ "\n",+ "This can be accessed using the `string_distance` evaluator, which uses distance metric's from the [rapidfuzz](https://github.com/maxbachmann/RapidFuzz) library.\n",+ "\n",+ "**Note:** The returned scores are _distances_, meaning lower is typically \"better\".\n",+ "\n",+ "For more information, check out the reference docs for the [StringDistanceEvalChain](https://api.python.langchain.com/en/latest/evaluation/langchain.evaluation.string_distance.base.StringDistanceEvalChain.html#langchain.evaluation.string_distance.base.StringDistanceEvalChain) for more info."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 1,+ "id": "8b47b909-3251-4774-9a7d-e436da4f8979",+ "metadata": {+ "tags": []+ },+ "outputs": [],+ "source": [+ "# %pip install rapidfuzz"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 2,+ "id": "f6790c46",+ "metadata": {+ "tags": []+ },+ "outputs": [],+ "source": [+ "from langchain.evaluation import load_evaluator\n",+ "\n",+ "evaluator = load_evaluator(\"string_distance\")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 3,+ "id": "49ad9139",+ "metadata": {+ "tags": []+ },+ "outputs": [+ {+ "data": {+ "text/plain": [+ "{'score': 0.11555555555555552}"+ ]+ },+ "execution_count": 3,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "evaluator.evaluate_strings(\n",+ " prediction=\"The job is completely done.\",\n",+ " reference=\"The job is done\",\n",+ ")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 4,+ "id": "c06a2296",+ "metadata": {+ "tags": []+ },+ "outputs": [+ {+ "data": {+ "text/plain": [+ "{'score': 0.0724999999999999}"+ ]+ },+ "execution_count": 4,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "# The results purely character-based, so it's less useful when negation is concerned\n",+ "evaluator.evaluate_strings(\n",+ " prediction=\"The job is done.\",\n",+ " reference=\"The job isn't done\",\n",+ ")"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "b8ed1f12-09a6-4e90-a69d-c8df525ff293",+ "metadata": {},+ "source": [+ "## Configure the String Distance Metric\n",+ "\n",+ "By default, the `StringDistanceEvalChain` uses levenshtein distance, but it also supports other string distance algorithms. Configure using the `distance` argument."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 5,+ "id": "a88bc7d7-62d3-408d-b0e0-43abcecf35c8",+ "metadata": {+ "tags": []+ },+ "outputs": [+ {+ "data": {+ "text/plain": [+ "[<StringDistance.DAMERAU_LEVENSHTEIN: 'damerau_levenshtein'>,\n",+ " <StringDistance.LEVENSHTEIN: 'levenshtein'>,\n",+ " <StringDistance.JARO: 'jaro'>,\n",+ " <StringDistance.JARO_WINKLER: 'jaro_winkler'>]"+ ]+ },+ "execution_count": 5,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "from langchain.evaluation import StringDistance\n",+ "\n",+ "list(StringDistance)"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 6,+ "id": "0c079864-0175-4d06-9d3f-a0e51dd3977c",+ "metadata": {+ "tags": []+ },+ "outputs": [],+ "source": [+ "jaro_evaluator = load_evaluator(\"string_distance\", distance=StringDistance.JARO)"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 7,+ "id": "a8dfb900-14f3-4a1f-8736-dd1d86a1264c",+ "metadata": {},+ "outputs": [+ {+ "data": {+ "text/plain": [+ "{'score': 0.19259259259259254}"+ ]+ },+ "execution_count": 7,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "jaro_evaluator.evaluate_strings(\n",+ " prediction=\"The job is completely done.\",\n",+ " reference=\"The job is done\",\n",+ ")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 8,+ "id": "7020b046-0ef7-40cc-8778-b928e35f3ce1",+ "metadata": {+ "tags": []+ },+ "outputs": [+ {+ "data": {+ "text/plain": [+ "{'score': 0.12083333333333324}"+ ]+ },+ "execution_count": 8,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "jaro_evaluator.evaluate_strings(\n",+ " prediction=\"The job is done.\",\n",+ " reference=\"The job isn't done\",\n",+ ")"+ ]+ }+ ],+ "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.11.2"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5}\ No newline at end of filediff --git a/docs/docs/guides/fallbacks.ipynb b/docs/docs/guides/fallbacks.ipynbindex 551ede4d2b..1e4f69271d 100644--- a/docs/docs/guides/fallbacks.ipynb+++ b/docs/docs/guides/fallbacks.ipynb@@ -84,9 +84,9 @@],"source": ["# Let's use just the OpenAI LLm first, to show that we run into an error\n",- "with patch('openai.ChatCompletion.create', side_effect=RateLimitError()):\n",+ "with patch(\"openai.ChatCompletion.create\", side_effect=RateLimitError()):\n"," try:\n",- " print(openai_llm.invoke(\"Why did the chicken cross the road?\"))\n",+ " print(openai_llm.invoke(\"Why did the chicken cross the road?\"))\n"," except:\n"," print(\"Hit error\")"]@@ -107,9 +107,9 @@],"source": ["# Now let's try with fallbacks to Anthropic\n",- "with patch('openai.ChatCompletion.create', side_effect=RateLimitError()):\n",+ "with patch(\"openai.ChatCompletion.create\", side_effect=RateLimitError()):\n"," try:\n",- " print(llm.invoke(\"Why did the chicken cross the road?\"))\n",+ " print(llm.invoke(\"Why did the chicken cross the road?\"))\n"," except:\n"," print(\"Hit error\")"]@@ -141,14 +141,17 @@"\n","prompt = ChatPromptTemplate.from_messages(\n"," [\n",- " (\"system\", \"You're a nice assistant who always includes a compliment in your response\"),\n",+ " (\n",+ " \"system\",\n",+ " \"You're a nice assistant who always includes a compliment in your response\",\n",+ " ),\n"," (\"human\", \"Why did the {animal} cross the road\"),\n"," ]\n",")\n","chain = prompt | llm\n",- "with patch('openai.ChatCompletion.create', side_effect=RateLimitError()):\n",+ "with patch(\"openai.ChatCompletion.create\", side_effect=RateLimitError()):\n"," try:\n",- " print(chain.invoke({\"animal\": \"kangaroo\"}))\n",+ " print(chain.invoke({\"animal\": \"kangaroo\"}))\n"," except:\n"," print(\"Hit error\")"]@@ -176,7 +179,10 @@"\n","chat_prompt = ChatPromptTemplate.from_messages(\n"," [\n",- " (\"system\", \"You're a nice assistant who always includes a compliment in your response\"),\n",+ " (\n",+ " \"system\",\n",+ " \"You're a nice assistant who always includes a compliment in your response\",\n",+ " ),\n"," (\"human\", \"Why did the {animal} cross the road\"),\n"," ]\n",")\n",@@ -343,7 +349,7 @@"# In this case we are going to do the fallbacks on the LLM + output parser level\n","# Because the error will get raised in the OutputParser\n","openai_35 = ChatOpenAI() | DatetimeOutputParser()\n",- "openai_4 = ChatOpenAI(model=\"gpt-4\")| DatetimeOutputParser()"+ "openai_4 = ChatOpenAI(model=\"gpt-4\") | DatetimeOutputParser()"]},{@@ -353,7 +359,7 @@"metadata": {},"outputs": [],"source": [- "only_35 = prompt | openai_35 \n",+ "only_35 = prompt | openai_35\n","fallback_4 = prompt | openai_35.with_fallbacks([openai_4])"]},diff --git a/docs/docs/guides/langsmith/walkthrough.ipynb b/docs/docs/guides/langsmith/walkthrough.ipynbindex 4985fc41c3..460258f548 100644--- a/docs/docs/guides/langsmith/walkthrough.ipynb+++ b/docs/docs/guides/langsmith/walkthrough.ipynb@@ -300,11 +300,14 @@"dataset_name = f\"agent-qa-{unique_id}\"\n","\n","dataset = client.create_dataset(\n",- " dataset_name, description=\"An example dataset of questions over the LangSmith documentation.\"\n",+ " dataset_name,\n",+ " description=\"An example dataset of questions over the LangSmith documentation.\",\n",")\n","\n","for query, answer in zip(inputs, outputs):\n",- " client.create_example(inputs={\"input\": query}, outputs={\"output\": answer}, dataset_id=dataset.id)"+ " client.create_example(\n",+ " inputs={\"input\": query}, outputs={\"output\": answer}, dataset_id=dataset.id\n",+ " )"]},{@@ -341,20 +344,22 @@"# Since chains can be stateful (e.g. they can have memory), we provide\n","# a way to initialize a new chain for each row in the dataset. This is done\n","# by passing in a factory function that returns a new chain for each row.\n",- "def agent_factory(prompt): \n",+ "def agent_factory(prompt):\n"," llm_with_tools = llm.bind(\n"," functions=[format_tool_to_openai_function(t) for t in tools]\n"," )\n"," runnable_agent = (\n",- " {\n",- " \"input\": lambda x: x[\"input\"],\n",- " \"agent_scratchpad\": lambda x: format_to_openai_functions(x['intermediate_steps'])\n",- " } \n",- " | prompt \n",- " | llm_with_tools \n",- " | OpenAIFunctionsAgentOutputParser()\n",+ " {\n",+ " \"input\": lambda x: x[\"input\"],\n",+ " \"agent_scratchpad\": lambda x: format_to_openai_functions(\n",+ " x[\"intermediate_steps\"]\n",+ " ),\n",+ " }\n",+ " | prompt\n",+ " | llm_with_tools\n",+ " | OpenAIFunctionsAgentOutputParser()\n"," )\n",- " return AgentExecutor(agent=runnable_agent, tools=tools, handle_parsing_errors=True)\n"+ " return AgentExecutor(agent=runnable_agent, tools=tools, handle_parsing_errors=True)"]},{@@ -404,7 +409,7 @@" # You can use default criteria or write our own rubric\n"," RunEvalConfig.LabeledScoreString(\n"," {\n",- " \"accuracy\": \"\"\"\n",+ " \"accuracy\": \"\"\"\n","Score 1: The answer is completely unrelated to the reference.\n","Score 3: The answer has minor relevance but does not align with the reference.\n","Score 5: The answer has moderate relevance but contains inaccuracies.\n",@@ -493,7 +498,7 @@"import functools\n","from langchain.smith import (\n"," arun_on_dataset,\n",- " run_on_dataset, \n",+ " run_on_dataset,\n",")\n","\n","chain_results = run_on_dataset(\n",@@ -503,7 +508,10 @@" verbose=True,\n"," client=client,\n"," project_name=f\"runnable-agent-test-5d466cbc-{unique_id}\",\n",- " tags=[\"testing-notebook\", \"prompt:5d466cbc\"], # Optional, adds a tag to the resulting chain runs\n",+ " tags=[\n",+ " \"testing-notebook\",\n",+ " \"prompt:5d466cbc\",\n",+ " ], # Optional, adds a tag to the resulting chain runs\n",")\n","\n","# Sometimes, the agent will error due to parsing issues, incompatible tool inputs, etc.\n",@@ -705,7 +713,10 @@" verbose=True,\n"," client=client,\n"," project_name=f\"runnable-agent-test-39f3bbd0-{unique_id}\",\n",- " tags=[\"testing-notebook\", \"prompt:39f3bbd0\"], # Optional, adds a tag to the resulting chain runs\n",+ " tags=[\n",+ " \"testing-notebook\",\n",+ " \"prompt:39f3bbd0\",\n",+ " ], # Optional, adds a tag to the resulting chain runs\n",")"]},diff --git a/docs/docs/guides/local_llms.ipynb b/docs/docs/guides/local_llms.ipynbindex 62212ddc22..e6aeba52b1 100644--- a/docs/docs/guides/local_llms.ipynb+++ b/docs/docs/guides/local_llms.ipynb@@ -95,6 +95,7 @@],"source": ["from langchain.llms import Ollama\n",+ "\n","llm = Ollama(model=\"llama2\")\n","llm(\"The first man on the moon was ...\")"]@@ -133,9 +134,11 @@],"source": ["from langchain.callbacks.manager import CallbackManager\n",- "from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler \n",- "llm = Ollama(model=\"llama2\", \n",- " callback_manager = CallbackManager([StreamingStdOutCallbackHandler()]))\n",+ "from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler\n",+ "\n",+ "llm = Ollama(\n",+ " model=\"llama2\", callback_manager=CallbackManager([StreamingStdOutCallbackHandler()])\n",+ ")\n","llm(\"The first man on the moon was ...\")"]},@@ -220,6 +223,7 @@],"source": ["from langchain.llms import Ollama\n",+ "\n","llm = Ollama(model=\"llama2:13b\")\n","llm(\"The first man on the moon was ... think step by step\")"]@@ -275,12 +279,13 @@"outputs": [],"source": ["from langchain.llms import LlamaCpp\n",+ "\n","llm = LlamaCpp(\n"," model_path=\"/Users/rlm/Desktop/Code/llama.cpp/models/openorca-platypus2-13b.gguf.q4_0.bin\",\n"," n_gpu_layers=1,\n"," n_batch=512,\n"," n_ctx=2048,\n",- " f16_kv=True, \n",+ " f16_kv=True,\n"," callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]),\n"," verbose=True,\n",")"@@ -385,7 +390,10 @@"outputs": [],"source": ["from langchain.llms import GPT4All\n",- "llm = GPT4All(model=\"/Users/rlm/Desktop/Code/gpt4all/models/nous-hermes-13b.ggmlv3.q4_0.bin\")"+ "\n",+ "llm = GPT4All(\n",+ " model=\"/Users/rlm/Desktop/Code/gpt4all/models/nous-hermes-13b.ggmlv3.q4_0.bin\"\n",+ ")"]},{@@ -436,7 +444,7 @@" n_gpu_layers=1,\n"," n_batch=512,\n"," n_ctx=2048,\n",- " f16_kv=True, \n",+ " f16_kv=True,\n"," callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]),\n"," verbose=True,\n",")"@@ -489,11 +497,9 @@")\n","\n","QUESTION_PROMPT_SELECTOR = ConditionalPromptSelector(\n",- " default_prompt=DEFAULT_SEARCH_PROMPT,\n",- " conditionals=[\n",- " (lambda llm: isinstance(llm, LlamaCpp), DEFAULT_LLAMA_SEARCH_PROMPT)\n",- " ],\n",- " )\n",+ " default_prompt=DEFAULT_SEARCH_PROMPT,\n",+ " conditionals=[(lambda llm: isinstance(llm, LlamaCpp), DEFAULT_LLAMA_SEARCH_PROMPT)],\n",+ ")\n","\n","prompt = QUESTION_PROMPT_SELECTOR.get_prompt(llm)\n","prompt"@@ -541,9 +547,9 @@],"source": ["# Chain\n",- "llm_chain = LLMChain(prompt=prompt,llm=llm)\n",+ "llm_chain = LLMChain(prompt=prompt, llm=llm)\n","question = \"What NFL team won the Super Bowl in the year that Justin Bieber was born?\"\n",- "llm_chain.run({\"question\":question})"+ "llm_chain.run({\"question\": question})"]},{diff --git a/docs/docs/guides/safety/amazon_comprehend_chain.ipynb b/docs/docs/guides/safety/amazon_comprehend_chain.ipynbindex 1de5f75dc4..ddbabd1087 100644--- a/docs/docs/guides/safety/amazon_comprehend_chain.ipynb+++ b/docs/docs/guides/safety/amazon_comprehend_chain.ipynb@@ -63,7 +63,7 @@"import boto3\n","import os\n","\n",- "comprehend_client = boto3.client('comprehend', region_name='us-east-1')"+ "comprehend_client = boto3.client(\"comprehend\", region_name=\"us-east-1\")"]},{@@ -78,8 +78,7 @@"from langchain_experimental.comprehend_moderation import AmazonComprehendModerationChain\n","\n","comprehend_moderation = AmazonComprehendModerationChain(\n",- " client=comprehend_client, #optional\n",- " verbose=True\n",+ " client=comprehend_client, verbose=True # optional\n",")"]},@@ -104,7 +103,9 @@"source": ["from langchain.prompts import PromptTemplate\n","from langchain.llms.fake import FakeListLLM\n",- "from langchain_experimental.comprehend_moderation.base_moderation_exceptions import ModerationPiiError\n",+ "from langchain_experimental.comprehend_moderation.base_moderation_exceptions import (\n",+ " ModerationPiiError,\n",+ ")\n","\n","template = \"\"\"Question: {question}\n","\n",@@ -113,25 +114,29 @@"prompt = PromptTemplate(template=template, input_variables=[\"question\"])\n","\n","responses = [\n",- " \"Final Answer: A credit card number looks like 1289-2321-1123-2387. A fake SSN number looks like 323-22-9980. John Doe's phone number is (999)253-9876.\", \n",+ " \"Final Answer: A credit card number looks like 1289-2321-1123-2387. A fake SSN number looks like 323-22-9980. John Doe's phone number is (999)253-9876.\",\n"," # replace with your own expletive\n",- " \"Final Answer: This is a really <expletive> way of constructing a birdhouse. This is <expletive> insane to think that any birds would actually create their <expletive> nests here.\"\n",+ " \"Final Answer: This is a really <expletive> way of constructing a birdhouse. This is <expletive> insane to think that any birds would actually create their <expletive> nests here.\",\n","]\n","llm = FakeListLLM(responses=responses)\n","\n","chain = (\n",- " prompt \n",- " | comprehend_moderation \n",- " | {\"input\": (lambda x: x['output'] ) | llm}\n",- " | comprehend_moderation \n",+ " prompt\n",+ " | comprehend_moderation\n",+ " | {\"input\": (lambda x: x[\"output\"]) | llm}\n",+ " | comprehend_moderation\n",")\n","\n","try:\n",- " response = chain.invoke({\"question\": \"A sample SSN number looks like this 123-22-3345. Can you give me some more samples?\"})\n",+ " response = chain.invoke(\n",+ " {\n",+ " \"question\": \"A sample SSN number looks like this 123-22-3345. Can you give me some more samples?\"\n",+ " }\n",+ " )\n","except ModerationPiiError as e:\n"," print(str(e))\n","else:\n",- " print(response['output'])\n"+ " print(response[\"output\"])"]},{@@ -166,25 +171,18 @@},"outputs": [],"source": [- "from langchain_experimental.comprehend_moderation import (BaseModerationConfig, \n",- " ModerationPromptSafetyConfig, \n",- " ModerationPiiConfig, \n",- " ModerationToxicityConfig\n",+ "from langchain_experimental.comprehend_moderation import (\n",+ " BaseModerationConfig,\n",+ " ModerationPromptSafetyConfig,\n",+ " ModerationPiiConfig,\n",+ " ModerationToxicityConfig,\n",")\n","\n",- "pii_config = ModerationPiiConfig(\n",- " labels=[\"SSN\"],\n",- " redact=True,\n",- " mask_character=\"X\"\n",- ")\n",+ "pii_config = ModerationPiiConfig(labels=[\"SSN\"], redact=True, mask_character=\"X\")\n","\n",- "toxicity_config = ModerationToxicityConfig(\n",- " threshold=0.5\n",- ")\n",+ "toxicity_config = ModerationToxicityConfig(threshold=0.5)\n","\n",- "prompt_safety_config = ModerationPromptSafetyConfig(\n",- " threshold=0.5\n",- ")\n",+ "prompt_safety_config = ModerationPromptSafetyConfig(threshold=0.5)\n","\n","moderation_config = BaseModerationConfig(\n"," filters=[pii_config, toxicity_config, prompt_safety_config]\n",@@ -225,9 +223,9 @@"outputs": [],"source": ["comp_moderation_with_config = AmazonComprehendModerationChain(\n",- " moderation_config=moderation_config, #specify the configuration\n",- " client=comprehend_client, #optionally pass the Boto3 Client\n",- " verbose=True\n",+ " moderation_config=moderation_config, # specify the configuration\n",+ " client=comprehend_client, # optionally pass the Boto3 Client\n",+ " verbose=True,\n",")"]},@@ -250,26 +248,30 @@"prompt = PromptTemplate(template=template, input_variables=[\"question\"])\n","\n","responses = [\n",- " \"Final Answer: A credit card number looks like 1289-2321-1123-2387. A fake SSN number looks like 323-22-9980. John Doe's phone number is (999)253-9876.\", \n",+ " \"Final Answer: A credit card number looks like 1289-2321-1123-2387. A fake SSN number looks like 323-22-9980. John Doe's phone number is (999)253-9876.\",\n"," # replace with your own expletive\n",- " \"Final Answer: This is a really <expletive> way of constructing a birdhouse. This is <expletive> insane to think that any birds would actually create their <expletive> nests here.\"\n",+ " \"Final Answer: This is a really <expletive> way of constructing a birdhouse. This is <expletive> insane to think that any birds would actually create their <expletive> nests here.\",\n","]\n","llm = FakeListLLM(responses=responses)\n","\n",- "chain = ( \n",- " prompt \n",- " | comp_moderation_with_config \n",- " | {\"input\": (lambda x: x['output'] ) | llm}\n",- " | comp_moderation_with_config \n",+ "chain = (\n",+ " prompt\n",+ " | comp_moderation_with_config\n",+ " | {\"input\": (lambda x: x[\"output\"]) | llm}\n",+ " | comp_moderation_with_config\n",")\n","\n","\n","try:\n",- " response = chain.invoke({\"question\": \"A sample SSN number looks like this 123-45-7890. Can you give me some more samples?\"})\n",+ " response = chain.invoke(\n",+ " {\n",+ " \"question\": \"A sample SSN number looks like this 123-45-7890. Can you give me some more samples?\"\n",+ " }\n",+ " )\n","except Exception as e:\n"," print(str(e))\n","else:\n",- " print(response['output'])"+ " print(response[\"output\"])"]},{@@ -343,24 +345,25 @@"source": ["# Define callback handlers by subclassing BaseModerationCallbackHandler\n","\n",+ "\n","class MyModCallback(BaseModerationCallbackHandler):\n",- " \n"," async def on_after_pii(self, output_beacon, unique_id):\n"," import json\n",- " moderation_type = output_beacon['moderation_type']\n",- " chain_id = output_beacon['moderation_chain_id']\n",- " with open(f'output-{moderation_type}-{chain_id}.json', 'w') as file:\n",- " data = { 'beacon_data': output_beacon, 'unique_id': unique_id }\n",+ "\n",+ " moderation_type = output_beacon[\"moderation_type\"]\n",+ " chain_id = output_beacon[\"moderation_chain_id\"]\n",+ " with open(f\"output-{moderation_type}-{chain_id}.json\", \"w\") as file:\n",+ " data = {\"beacon_data\": output_beacon, \"unique_id\": unique_id}\n"," json.dump(data, file)\n",- " \n",- " '''\n",+ "\n",+ " \"\"\"\n"," async def on_after_toxicity(self, output_beacon, unique_id):\n"," pass\n"," \n"," async def on_after_prompt_safety(self, output_beacon, unique_id):\n"," pass\n",- " '''\n",- " \n",+ " \"\"\"\n",+ "\n","\n","my_callback = MyModCallback()"]@@ -374,26 +377,18 @@},"outputs": [],"source": [- "pii_config = ModerationPiiConfig(\n",- " labels=[\"SSN\"],\n",- " redact=True,\n",- " mask_character=\"X\"\n",- ")\n",+ "pii_config = ModerationPiiConfig(labels=[\"SSN\"], redact=True, mask_character=\"X\")\n","\n",- "toxicity_config = ModerationToxicityConfig(\n",- " threshold=0.5\n",- ")\n",+ "toxicity_config = ModerationToxicityConfig(threshold=0.5)\n","\n",- "moderation_config = BaseModerationConfig(\n",- " filters=[pii_config, toxicity_config]\n",- ")\n",+ "moderation_config = BaseModerationConfig(filters=[pii_config, toxicity_config])\n","\n","comp_moderation_with_config = AmazonComprehendModerationChain(\n",- " moderation_config=moderation_config, # specify the configuration\n",- " client=comprehend_client, # optionally pass the Boto3 Client\n",- " unique_id='[email protected]', # A unique ID\n",- " moderation_callback=my_callback, # BaseModerationCallbackHandler\n",- " verbose=True\n",+ " moderation_config=moderation_config, # specify the configuration\n",+ " client=comprehend_client, # optionally pass the Boto3 Client\n",+ " unique_id=\"[email protected]\", # A unique ID\n",+ " moderation_callback=my_callback, # BaseModerationCallbackHandler\n",+ " verbose=True,\n",")"]},@@ -416,26 +411,30 @@"prompt = PromptTemplate(template=template, input_variables=[\"question\"])\n","\n","responses = [\n",- " \"Final Answer: A credit card number looks like 1289-2321-1123-2387. A fake SSN number looks like 323-22-9980. John Doe's phone number is (999)253-9876.\", \n",+ " \"Final Answer: A credit card number looks like 1289-2321-1123-2387. A fake SSN number looks like 323-22-9980. John Doe's phone number is (999)253-9876.\",\n"," # replace with your own expletive\n",- " \"Final Answer: This is a really <expletive> way of constructing a birdhouse. This is <expletive> insane to think that any birds would actually create their <expletive> nests here.\"\n",+ " \"Final Answer: This is a really <expletive> way of constructing a birdhouse. This is <expletive> insane to think that any birds would actually create their <expletive> nests here.\",\n","]\n","\n","llm = FakeListLLM(responses=responses)\n","\n","chain = (\n",- " prompt \n",- " | comp_moderation_with_config \n",- " | {\"input\": (lambda x: x['output'] ) | llm}\n",- " | comp_moderation_with_config \n",- ") \n",+ " prompt\n",+ " | comp_moderation_with_config\n",+ " | {\"input\": (lambda x: x[\"output\"]) | llm}\n",+ " | comp_moderation_with_config\n",+ ")\n","\n","try:\n",- " response = chain.invoke({\"question\": \"A sample SSN number looks like this 123-456-7890. Can you give me some more samples?\"})\n",+ " response = chain.invoke(\n",+ " {\n",+ " \"question\": \"A sample SSN number looks like this 123-456-7890. Can you give me some more samples?\"\n",+ " }\n",+ " )\n","except Exception as e:\n"," print(str(e))\n","else:\n",- " print(response['output'])"+ " print(response[\"output\"])"]},{@@ -537,6 +536,7 @@"outputs": [],"source": ["import os\n",+ "\n","os.environ[\"HUGGINGFACEHUB_API_TOKEN\"] = \"<YOUR HF TOKEN HERE>\""]},@@ -550,7 +550,7 @@"outputs": [],"source": ["# See https://huggingface.co/models?pipeline_tag=text-generation&sort=downloads for some other options\n",- "repo_id = \"google/flan-t5-xxl\" "+ "repo_id = \"google/flan-t5-xxl\""]},{@@ -590,42 +590,35 @@},"outputs": [],"source": [- "\n","# define filter configs\n","pii_config = ModerationPiiConfig(\n",- " labels=[\"SSN\", \"CREDIT_DEBIT_NUMBER\"],\n",- " redact=True,\n",- " mask_character=\"X\"\n",+ " labels=[\"SSN\", \"CREDIT_DEBIT_NUMBER\"], redact=True, mask_character=\"X\"\n",")\n","\n",- "toxicity_config = ModerationToxicityConfig(\n",- " threshold=0.5\n",- ")\n",+ "toxicity_config = ModerationToxicityConfig(threshold=0.5)\n","\n",- "prompt_safety_config = ModerationPromptSafetyConfig(\n",- " threshold=0.8\n",- ")\n",+ "prompt_safety_config = ModerationPromptSafetyConfig(threshold=0.8)\n","\n","# define different moderation configs using the filter configs above\n","moderation_config_1 = BaseModerationConfig(\n"," filters=[pii_config, toxicity_config, prompt_safety_config]\n",")\n","\n",- "moderation_config_2 = BaseModerationConfig(\n",- " filters=[pii_config]\n",- ")\n",+ "moderation_config_2 = BaseModerationConfig(filters=[pii_config])\n","\n","\n","# input prompt moderation chain with callback\n",- "amazon_comp_moderation = AmazonComprehendModerationChain(moderation_config=moderation_config_1, \n",- " client=comprehend_client,\n",- " moderation_callback=my_callback,\n",- " verbose=True)\n",+ "amazon_comp_moderation = AmazonComprehendModerationChain(\n",+ " moderation_config=moderation_config_1,\n",+ " client=comprehend_client,\n",+ " moderation_callback=my_callback,\n",+ " verbose=True,\n",+ ")\n","\n","# Output from LLM moderation chain without callback\n",- "amazon_comp_moderation_out = AmazonComprehendModerationChain(moderation_config=moderation_config_2, \n",- " client=comprehend_client,\n",- " verbose=True)"+ "amazon_comp_moderation_out = AmazonComprehendModerationChain(\n",+ " moderation_config=moderation_config_2, client=comprehend_client, verbose=True\n",+ ")"]},{@@ -646,21 +639,25 @@"outputs": [],"source": ["chain = (\n",- " prompt \n",- " | amazon_comp_moderation \n",- " | { \"input\" : (lambda x: x['output']) | llm }\n",+ " prompt\n",+ " | amazon_comp_moderation\n",+ " | {\"input\": (lambda x: x[\"output\"]) | llm}\n"," | amazon_comp_moderation_out\n",")\n","\n","try:\n",- " response = chain.invoke({\"question\": \"\"\"What is John Doe's address, phone number and SSN from the following text?\n",+ " response = chain.invoke(\n",+ " {\n",+ " \"question\": \"\"\"What is John Doe's address, phone number and SSN from the following text?\n","\n","John Doe, a resident of 1234 Elm Street in Springfield, recently celebrated his birthday on January 1st. Turning 43 this year, John reflected on the years gone by. He often shares memories of his younger days with his close friends through calls on his phone, (555) 123-4567. Meanwhile, during a casual evening, he received an email at [email protected] reminding him of an old acquaintance's reunion. As he navigated through some old documents, he stumbled upon a paper that listed his SSN as 123-45-6789, reminding him to store it in a safer place.\n",- "\"\"\"})\n",+ "\"\"\"\n",+ " }\n",+ " )\n","except Exception as e:\n"," print(str(e))\n","else:\n",- " print(response['output'])"+ " print(response[\"output\"])"]},{@@ -682,7 +679,7 @@"metadata": {},"outputs": [],"source": [- "endpoint_name = \"<SAGEMAKER_ENDPOINT_NAME>\" # replace with your SageMaker Endpoint name\n",+ "endpoint_name = \"<SAGEMAKER_ENDPOINT_NAME>\" # replace with your SageMaker Endpoint name\n","region = \"<REGION>\" # replace with your SageMaker Endpoint region"]},@@ -698,17 +695,19 @@"from langchain.prompts import PromptTemplate\n","import json\n","\n",+ "\n","class ContentHandler(LLMContentHandler):\n"," content_type = \"application/json\"\n"," accepts = \"application/json\"\n","\n"," def transform_input(self, prompt: str, model_kwargs: dict) -> bytes:\n",- " input_str = json.dumps({\"text_inputs\": prompt, **model_kwargs})\n",- " return input_str.encode('utf-8')\n",- " \n",+ " input_str = json.dumps({\"text_inputs\": prompt, **model_kwargs})\n",+ " return input_str.encode(\"utf-8\")\n",+ "\n"," def transform_output(self, output: bytes) -> str:\n"," response_json = json.loads(output.read().decode(\"utf-8\"))\n",- " return response_json['generated_texts'][0]\n",+ " return response_json[\"generated_texts\"][0]\n",+ "\n","\n","content_handler = ContentHandler()\n","\n",@@ -719,20 +718,22 @@"Answer:\n","\"\"\"\n","\n",- "#prompt template for input text\n",+ "# prompt template for input text\n","llm_prompt = PromptTemplate(template=template, input_variables=[\"question\"])\n","\n",- "llm=SagemakerEndpoint(\n",- " endpoint_name=endpoint_name, \n",- " region_name=region,\n",- " model_kwargs={\"temperature\":0.95,\n",- " \"max_length\": 200,\n",- " \"num_return_sequences\": 3,\n",- " \"top_k\": 50,\n",- " \"top_p\": 0.95,\n",- " \"do_sample\": True},\n",- " content_handler=content_handler\n",- " )"+ "llm = SagemakerEndpoint(\n",+ " endpoint_name=endpoint_name,\n",+ " region_name=region,\n",+ " model_kwargs={\n",+ " \"temperature\": 0.95,\n",+ " \"max_length\": 200,\n",+ " \"num_return_sequences\": 3,\n",+ " \"top_k\": 50,\n",+ " \"top_p\": 0.95,\n",+ " \"do_sample\": True,\n",+ " },\n",+ " content_handler=content_handler,\n",+ ")"]},{@@ -753,37 +754,29 @@"outputs": [],"source": ["# define filter configs\n",- "pii_config = ModerationPiiConfig(\n",- " labels=[\"SSN\"],\n",- " redact=True,\n",- " mask_character=\"X\"\n",- ")\n",+ "pii_config = ModerationPiiConfig(labels=[\"SSN\"], redact=True, mask_character=\"X\")\n","\n",- "toxicity_config = ModerationToxicityConfig(\n",- " threshold=0.5\n",- ")\n",+ "toxicity_config = ModerationToxicityConfig(threshold=0.5)\n","\n","\n","# define different moderation configs using the filter configs above\n",- "moderation_config_1 = BaseModerationConfig(\n",- " filters=[pii_config, toxicity_config]\n",- ")\n",+ "moderation_config_1 = BaseModerationConfig(filters=[pii_config, toxicity_config])\n","\n",- "moderation_config_2 = BaseModerationConfig(\n",- " filters=[pii_config]\n",- ")\n",+ "moderation_config_2 = BaseModerationConfig(filters=[pii_config])\n","\n","\n","# input prompt moderation chain with callback\n",- "amazon_comp_moderation = AmazonComprehendModerationChain(moderation_config=moderation_config_1, \n",- " client=comprehend_client,\n",- " moderation_callback=my_callback,\n",- " verbose=True)\n",+ "amazon_comp_moderation = AmazonComprehendModerationChain(\n",+ " moderation_config=moderation_config_1,\n",+ " client=comprehend_client,\n",+ " moderation_callback=my_callback,\n",+ " verbose=True,\n",+ ")\n","\n","# Output from LLM moderation chain without callback\n",- "amazon_comp_moderation_out = AmazonComprehendModerationChain(moderation_config=moderation_config_2, \n",- " client=comprehend_client,\n",- " verbose=True)"+ "amazon_comp_moderation_out = AmazonComprehendModerationChain(\n",+ " moderation_config=moderation_config_2, client=comprehend_client, verbose=True\n",+ ")"]},{@@ -804,18 +797,20 @@"outputs": [],"source": ["chain = (\n",- " prompt \n",- " | amazon_comp_moderation \n",- " | { \"input\" : (lambda x: x['output']) | llm }\n",+ " prompt\n",+ " | amazon_comp_moderation\n",+ " | {\"input\": (lambda x: x[\"output\"]) | llm}\n"," | amazon_comp_moderation_out\n",")\n","\n","try:\n",- " response = chain.invoke({\"question\": \"What is John Doe's address, phone number and SSN?\"})\n",+ " response = chain.invoke(\n",+ " {\"question\": \"What is John Doe's address, phone number and SSN?\"}\n",+ " )\n","except Exception as e:\n"," print(str(e))\n","else:\n",- " print(response['output'])"+ " print(response[\"output\"])"]},{diff --git a/docs/docs/integrations/callbacks/confident.ipynb b/docs/docs/integrations/callbacks/confident.ipynbindex ca4c9ae062..36b92b3a6b 100644--- a/docs/docs/integrations/callbacks/confident.ipynb+++ b/docs/docs/integrations/callbacks/confident.ipynb@@ -122,8 +122,7 @@"from langchain.callbacks.confident_callback import DeepEvalCallbackHandler\n","\n","deepeval_callback = DeepEvalCallbackHandler(\n",- " implementation_name=\"langchainQuickstart\",\n",- " metrics=[answer_relevancy_metric]\n",+ " implementation_name=\"langchainQuickstart\", metrics=[answer_relevancy_metric]\n",")"]},@@ -155,6 +154,7 @@],"source": ["from langchain.llms import OpenAI\n",+ "\n","llm = OpenAI(\n"," temperature=0,\n"," callbacks=[deepeval_callback],\n",@@ -227,8 +227,8 @@"openai_api_key = \"sk-XXX\"\n","\n","with open(\"state_of_the_union.txt\", \"w\") as f:\n",- " response = requests.get(text_file_url)\n",- " f.write(response.text)\n",+ " response = requests.get(text_file_url)\n",+ " f.write(response.text)\n","\n","loader = TextLoader(\"state_of_the_union.txt\")\n","documents = loader.load()\n",@@ -239,8 +239,9 @@"docsearch = Chroma.from_documents(texts, embeddings)\n","\n","qa = RetrievalQA.from_chain_type(\n",- " llm=OpenAI(openai_api_key=openai_api_key), chain_type=\"stuff\",\n",- " retriever=docsearch.as_retriever()\n",+ " llm=OpenAI(openai_api_key=openai_api_key),\n",+ " chain_type=\"stuff\",\n",+ " retriever=docsearch.as_retriever(),\n",")\n","\n","# Providing a new question-answering pipeline\n",diff --git a/docs/docs/integrations/callbacks/infino.ipynb b/docs/docs/integrations/callbacks/infino.ipynbindex 05af3ad3f8..7d387a6eb3 100644--- a/docs/docs/integrations/callbacks/infino.ipynb+++ b/docs/docs/integrations/callbacks/infino.ipynb@@ -234,8 +234,7 @@" plt.ylabel(\"Value\")\n"," plt.title(title)\n","\n",- " plt.show()\n",- "\n"+ " plt.show()"]},{@@ -325,9 +324,11 @@" model_id=\"test_chatopenai\", model_version=\"0.1\", verbose=False\n",")\n","\n",- "urls = [\"https://lilianweng.github.io/posts/2023-06-23-agent/\",\n",- " \"https://medium.com/lyft-engineering/lyftlearn-ml-model-training-infrastructure-built-on-kubernetes-aef8218842bb\",\n",- " \"https://blog.langchain.dev/week-of-10-2-langchain-release-notes/\"]\n",+ "urls = [\n",+ " \"https://lilianweng.github.io/posts/2023-06-23-agent/\",\n",+ " \"https://medium.com/lyft-engineering/lyftlearn-ml-model-training-infrastructure-built-on-kubernetes-aef8218842bb\",\n",+ " \"https://blog.langchain.dev/week-of-10-2-langchain-release-notes/\",\n",+ "]\n","\n","for url in urls:\n"," loader = WebBaseLoader(url)\n",@@ -364,7 +365,7 @@"plot(response.text, \"Prompt Tokens\")\n","\n","response = client.search_ts(\"__name__\", \"completion_tokens\", 0, int(time.time()))\n",- "plot(response.text, \"Completion Tokens\")\n"+ "plot(response.text, \"Completion Tokens\")"]},{diff --git a/docs/docs/integrations/callbacks/labelstudio.ipynb b/docs/docs/integrations/callbacks/labelstudio.ipynbindex 927db2d639..a02a0f4be4 100644--- a/docs/docs/integrations/callbacks/labelstudio.ipynb+++ b/docs/docs/integrations/callbacks/labelstudio.ipynb@@ -97,9 +97,9 @@"source": ["import os\n","\n",- "os.environ['LABEL_STUDIO_URL'] = '<YOUR-LABEL-STUDIO-URL>' # e.g. http://localhost:8080\n",- "os.environ['LABEL_STUDIO_API_KEY'] = '<YOUR-LABEL-STUDIO-API-KEY>'\n",- "os.environ['OPENAI_API_KEY'] = '<YOUR-OPENAI-API-KEY>'"+ "os.environ[\"LABEL_STUDIO_URL\"] = \"<YOUR-LABEL-STUDIO-URL>\" # e.g. http://localhost:8080\n",+ "os.environ[\"LABEL_STUDIO_API_KEY\"] = \"<YOUR-LABEL-STUDIO-API-KEY>\"\n",+ "os.environ[\"OPENAI_API_KEY\"] = \"<YOUR-OPENAI-API-KEY>\""]},{@@ -174,11 +174,7 @@"from langchain.callbacks import LabelStudioCallbackHandler\n","\n","llm = OpenAI(\n",- " temperature=0,\n",- " callbacks=[\n",- " LabelStudioCallbackHandler(\n",- " project_name=\"My Project\"\n",- " )]\n",+ " temperature=0, callbacks=[LabelStudioCallbackHandler(project_name=\"My Project\")]\n",")\n","print(llm(\"Tell me a joke\"))"]@@ -249,16 +245,20 @@"from langchain.schema import HumanMessage, SystemMessage\n","from langchain.callbacks import LabelStudioCallbackHandler\n","\n",- "chat_llm = ChatOpenAI(callbacks=[\n",- " LabelStudioCallbackHandler(\n",- " mode=\"chat\",\n",- " project_name=\"New Project with Chat\",\n",- " )\n",- "])\n",- "llm_results = chat_llm([\n",- " SystemMessage(content=\"Always use a lot of emojis\"),\n",- " HumanMessage(content=\"Tell me a joke\")\n",- "])"+ "chat_llm = ChatOpenAI(\n",+ " callbacks=[\n",+ " LabelStudioCallbackHandler(\n",+ " mode=\"chat\",\n",+ " project_name=\"New Project with Chat\",\n",+ " )\n",+ " ]\n",+ ")\n",+ "llm_results = chat_llm(\n",+ " [\n",+ " SystemMessage(content=\"Always use a lot of emojis\"),\n",+ " HumanMessage(content=\"Tell me a joke\"),\n",+ " ]\n",+ ")"]},{@@ -304,7 +304,8 @@},"outputs": [],"source": [- "ls = LabelStudioCallbackHandler(project_config='''\n",+ "ls = LabelStudioCallbackHandler(\n",+ " project_config=\"\"\"\n","<View>\n","<Text name=\"prompt\" value=\"$prompt\"/>\n","<TextArea name=\"response\" toName=\"prompt\"/>\n",@@ -315,7 +316,8 @@" <Choice value=\"Negative\"/>\n","</Choices>\n","</View>\n",- "''')"+ "\"\"\"\n",+ ")"]},{diff --git a/docs/docs/integrations/callbacks/sagemaker_tracking.ipynb b/docs/docs/integrations/callbacks/sagemaker_tracking.ipynbindex a7678f16a3..01e69385f1 100644--- a/docs/docs/integrations/callbacks/sagemaker_tracking.ipynb+++ b/docs/docs/integrations/callbacks/sagemaker_tracking.ipynb@@ -105,19 +105,19 @@},"outputs": [],"source": [- "#LLM Hyperparameters\n",+ "# LLM Hyperparameters\n","HPARAMS = {\n"," \"temperature\": 0.1,\n"," \"model_name\": \"text-davinci-003\",\n","}\n","\n",- "#Bucket used to save prompt logs (Use `None` is used to save the default bucket or otherwise change it)\n",+ "# Bucket used to save prompt logs (Use `None` is used to save the default bucket or otherwise change it)\n","BUCKET_NAME = None\n","\n",- "#Experiment name\n",+ "# Experiment name\n","EXPERIMENT_NAME = \"langchain-sagemaker-tracker\"\n","\n",- "#Create SageMaker Session with the given bucket\n",+ "# Create SageMaker Session with the given bucket\n","session = Session(default_bucket=BUCKET_NAME)"]},@@ -150,8 +150,9 @@"metadata": {},"outputs": [],"source": [- "with Run(experiment_name=EXPERIMENT_NAME, run_name=RUN_NAME, sagemaker_session=session) as run:\n",- "\n",+ "with Run(\n",+ " experiment_name=EXPERIMENT_NAME, run_name=RUN_NAME, sagemaker_session=session\n",+ ") as run:\n"," # Create SageMaker Callback\n"," sagemaker_callback = SageMakerCallbackHandler(run)\n","\n",@@ -209,8 +210,9 @@"metadata": {},"outputs": [],"source": [- "with Run(experiment_name=EXPERIMENT_NAME, run_name=RUN_NAME, sagemaker_session=session) as run:\n",- "\n",+ "with Run(\n",+ " experiment_name=EXPERIMENT_NAME, run_name=RUN_NAME, sagemaker_session=session\n",+ ") as run:\n"," # Create SageMaker Callback\n"," sagemaker_callback = SageMakerCallbackHandler(run)\n","\n",@@ -228,7 +230,9 @@" chain2 = LLMChain(llm=llm, prompt=prompt_template2, callbacks=[sagemaker_callback])\n","\n"," # Create Sequential chain\n",- " overall_chain = SimpleSequentialChain(chains=[chain1, chain2], callbacks=[sagemaker_callback])\n",+ " overall_chain = SimpleSequentialChain(\n",+ " chains=[chain1, chain2], callbacks=[sagemaker_callback]\n",+ " )\n","\n"," # Run overall sequential chain\n"," overall_chain.run(**INPUT_VARIABLES)\n",@@ -267,8 +271,9 @@},"outputs": [],"source": [- "with Run(experiment_name=EXPERIMENT_NAME, run_name=RUN_NAME, sagemaker_session=session) as run:\n",- "\n",+ "with Run(\n",+ " experiment_name=EXPERIMENT_NAME, run_name=RUN_NAME, sagemaker_session=session\n",+ ") as run:\n"," # Create SageMaker Callback\n"," sagemaker_callback = SageMakerCallbackHandler(run)\n","\n",@@ -279,7 +284,9 @@" tools = load_tools([\"serpapi\", \"llm-math\"], llm=llm, callbacks=[sagemaker_callback])\n","\n"," # Initialize agent with all the tools\n",- " agent = initialize_agent(tools, llm, agent=\"zero-shot-react-description\", callbacks=[sagemaker_callback])\n",+ " agent = initialize_agent(\n",+ " tools, llm, agent=\"zero-shot-react-description\", callbacks=[sagemaker_callback]\n",+ " )\n","\n"," # Run agent\n"," agent.run(input=PROMPT_TEMPLATE)\n",@@ -309,10 +316,10 @@},"outputs": [],"source": [- "#Load\n",+ "# Load\n","logs = ExperimentAnalytics(experiment_name=EXPERIMENT_NAME)\n","\n",- "#Convert as pandas dataframe\n",+ "# Convert as pandas dataframe\n","df = logs.dataframe(force_refresh=True)\n","\n","print(df.shape)\n",diff --git a/docs/docs/integrations/callbacks/trubrics.ipynb b/docs/docs/integrations/callbacks/trubrics.ipynbindex 3e79996fc7..bd181b6870 100644--- a/docs/docs/integrations/callbacks/trubrics.ipynb+++ b/docs/docs/integrations/callbacks/trubrics.ipynb@@ -284,7 +284,7 @@" project=\"default\",\n"," tags=[\"chat model\"],\n"," user_id=\"user-id-1234\",\n",- " some_metadata={\"hello\": [1, 2]}\n",+ " some_metadata={\"hello\": [1, 2]},\n"," )\n"," ]\n",")"diff --git a/docs/docs/integrations/chat/anthropic_functions.ipynb b/docs/docs/integrations/chat/anthropic_functions.ipynbindex 9b63615386..5f6d116e10 100644--- a/docs/docs/integrations/chat/anthropic_functions.ipynb+++ b/docs/docs/integrations/chat/anthropic_functions.ipynb@@ -46,7 +46,7 @@"metadata": {},"outputs": [],"source": [- "model = AnthropicFunctions(model='claude-2')"+ "model = AnthropicFunctions(model=\"claude-2\")"]},{@@ -66,26 +66,23 @@"metadata": {},"outputs": [],"source": [- "functions=[\n",+ "functions = [\n"," {\n",- " \"name\": \"get_current_weather\",\n",- " \"description\": \"Get the current weather in a given location\",\n",- " \"parameters\": {\n",- " \"type\": \"object\",\n",- " \"properties\": {\n",- " \"location\": {\n",- " \"type\": \"string\",\n",- " \"description\": \"The city and state, e.g. San Francisco, CA\"\n",- " },\n",- " \"unit\": {\n",- " \"type\": \"string\",\n",- " \"enum\": [\"celsius\", \"fahrenheit\"]\n",- " }\n",+ " \"name\": \"get_current_weather\",\n",+ " \"description\": \"Get the current weather in a given location\",\n",+ " \"parameters\": {\n",+ " \"type\": \"object\",\n",+ " \"properties\": {\n",+ " \"location\": {\n",+ " \"type\": \"string\",\n",+ " \"description\": \"The city and state, e.g. San Francisco, CA\",\n",+ " },\n",+ " \"unit\": {\"type\": \"string\", \"enum\": [\"celsius\", \"fahrenheit\"]},\n",+ " },\n",+ " \"required\": [\"location\"],\n"," },\n",- " \"required\": [\"location\"]\n",- " }\n"," }\n",- " ]"+ "]"]},{@@ -106,8 +103,7 @@"outputs": [],"source": ["response = model.predict_messages(\n",- " [HumanMessage(content=\"whats the weater in boston?\")], \n",- " functions=functions\n",+ " [HumanMessage(content=\"whats the weater in boston?\")], functions=functions\n",")"]},@@ -150,6 +146,7 @@"outputs": [],"source": ["from langchain.chains import create_extraction_chain\n",+ "\n","schema = {\n"," \"properties\": {\n"," \"name\": {\"type\": \"string\"},\n",diff --git a/docs/docs/integrations/chat/anyscale.ipynb b/docs/docs/integrations/chat/anyscale.ipynbindex f23cccd5e6..ef8bc4e788 100644--- a/docs/docs/integrations/chat/anyscale.ipynb+++ b/docs/docs/integrations/chat/anyscale.ipynb@@ -102,19 +102,15 @@"from langchain.schema import SystemMessage, HumanMessage\n","\n","messages = [\n",- " SystemMessage(\n",- " content=\"You are a helpful AI that shares everything you know.\"\n",- " ),\n",+ " SystemMessage(content=\"You are a helpful AI that shares everything you know.\"),\n"," HumanMessage(\n"," content=\"Tell me technical facts about yourself. Are you a transformer model? How many billions of parameters do you have?\"\n"," ),\n","]\n","\n",+ "\n","async def get_msgs():\n",- " tasks = [\n",- " chat.apredict_messages(messages)\n",- " for chat in chats.values()\n",- " ]\n",+ " tasks = [chat.apredict_messages(messages) for chat in chats.values()]\n"," responses = await asyncio.gather(*tasks)\n"," return dict(zip(chats.keys(), responses))"]@@ -194,10 +190,10 @@"response_dict = asyncio.run(get_msgs())\n","\n","for model_name, response in response_dict.items():\n",- " print(f'\\t{model_name}')\n",+ " print(f\"\\t{model_name}\")\n"," print()\n"," print(response.content)\n",- " print('\\n---\\n')"+ " print(\"\\n---\\n\")"]}],diff --git a/docs/docs/integrations/chat/azure_chat_openai.ipynb b/docs/docs/integrations/chat/azure_chat_openai.ipynbindex a8ebf79595..6109d687d1 100644--- a/docs/docs/integrations/chat/azure_chat_openai.ipynb+++ b/docs/docs/integrations/chat/azure_chat_openai.ipynb@@ -105,7 +105,7 @@"source": ["BASE_URL = \"https://{endpoint}.openai.azure.com\"\n","API_KEY = \"...\"\n",- "DEPLOYMENT_NAME = \"gpt-35-turbo\" # in Azure, this deployment has version 0613 - input and output tokens are counted separately"+ "DEPLOYMENT_NAME = \"gpt-35-turbo\" # in Azure, this deployment has version 0613 - input and output tokens are counted separately"]},{@@ -140,7 +140,9 @@" )\n"," ]\n"," )\n",- " print(f\"Total Cost (USD): ${format(cb.total_cost, '.6f')}\") # without specifying the model version, flat-rate 0.002 USD per 1k input and output tokens is used\n"+ " print(\n",+ " f\"Total Cost (USD): ${format(cb.total_cost, '.6f')}\"\n",+ " ) # without specifying the model version, flat-rate 0.002 USD per 1k input and output tokens is used"]},{@@ -172,7 +174,7 @@" deployment_name=DEPLOYMENT_NAME,\n"," openai_api_key=API_KEY,\n"," openai_api_type=\"azure\",\n",- " model_version=\"0613\"\n",+ " model_version=\"0613\",\n",")\n","with get_openai_callback() as cb:\n"," model0613(\n",@@ -182,7 +184,7 @@" )\n"," ]\n"," )\n",- " print(f\"Total Cost (USD): ${format(cb.total_cost, '.6f')}\")\n"+ " print(f\"Total Cost (USD): ${format(cb.total_cost, '.6f')}\")"]},{diff --git a/docs/docs/integrations/chat/azureml_chat_endpoint.ipynb b/docs/docs/integrations/chat/azureml_chat_endpoint.ipynbindex 72c549a93b..0197b7a886 100644--- a/docs/docs/integrations/chat/azureml_chat_endpoint.ipynb+++ b/docs/docs/integrations/chat/azureml_chat_endpoint.ipynb@@ -67,10 +67,10 @@" endpoint_url=\"https://<your-endpoint>.<your_region>.inference.ml.azure.com/score\",\n"," endpoint_api_key=\"my-api-key\",\n"," content_formatter=LlamaContentFormatter,\n",- "))\n",- "response = chat(messages=[\n",- " HumanMessage(content=\"Will the Collatz conjecture ever be solved?\")\n",- "])\n",+ ")\n",+ "response = chat(\n",+ " messages=[HumanMessage(content=\"Will the Collatz conjecture ever be solved?\")]\n",+ ")\n","response"]}@@ -91,9 +91,9 @@"name": "python","nbconvert_exporter": "python","pygments_lexer": "ipython3",- "version": "3.10.11"+ "version": "3.9.1"}},"nbformat": 4,- "nbformat_minor": 2+ "nbformat_minor": 4}diff --git a/docs/docs/integrations/chat/baichuan.ipynb b/docs/docs/integrations/chat/baichuan.ipynbindex 9718734cb3..9f9376beee 100644--- a/docs/docs/integrations/chat/baichuan.ipynb+++ b/docs/docs/integrations/chat/baichuan.ipynb@@ -36,8 +36,7 @@"outputs": [],"source": ["chat = ChatBaichuan(\n",- " baichuan_api_key='YOUR_API_KEY',\n",- " baichuan_secret_key='YOUR_SECRET_KEY'\n",+ " baichuan_api_key=\"YOUR_API_KEY\", baichuan_secret_key=\"YOUR_SECRET_KEY\"\n",")"]},@@ -72,9 +71,7 @@}],"source": [- "chat([\n",- " HumanMessage(content='我日薪8块钱,请问在闰年的二月,我月薪多少')\n",- "])"+ "chat([HumanMessage(content=\"我日薪8块钱,请问在闰年的二月,我月薪多少\")])"]},{@@ -92,9 +89,9 @@"outputs": [],"source": ["chat = ChatBaichuan(\n",- " baichuan_api_key='YOUR_API_KEY',\n",- " baichuan_secret_key='YOUR_SECRET_KEY',\n",- " streaming=True\n",+ " baichuan_api_key=\"YOUR_API_KEY\",\n",+ " baichuan_secret_key=\"YOUR_SECRET_KEY\",\n",+ " streaming=True,\n",")"],"metadata": {@@ -119,9 +116,7 @@}],"source": [- "chat([\n",- " HumanMessage(content='我日薪8块钱,请问在闰年的二月,我月薪多少')\n",- "])"+ "chat([HumanMessage(content=\"我日薪8块钱,请问在闰年的二月,我月薪多少\")])"],"metadata": {"collapsed": false,diff --git a/docs/docs/integrations/chat/baidu_qianfan_endpoint.ipynb b/docs/docs/integrations/chat/baidu_qianfan_endpoint.ipynbindex d25a05c7aa..8bc1e68fc5 100644--- a/docs/docs/integrations/chat/baidu_qianfan_endpoint.ipynb+++ b/docs/docs/integrations/chat/baidu_qianfan_endpoint.ipynb@@ -59,16 +59,17 @@],"source": ["\"\"\"For basic init and call\"\"\"\n",- "from langchain.chat_models import QianfanChatEndpoint \n",+ "from langchain.chat_models import QianfanChatEndpoint\n","from langchain.chat_models.base import HumanMessage\n","import os\n",+ "\n","os.environ[\"QIANFAN_AK\"] = \"your_ak\"\n","os.environ[\"QIANFAN_SK\"] = \"your_sk\"\n","\n","chat = QianfanChatEndpoint(\n",- " streaming=True, \n",- " )\n",- "res = chat([HumanMessage(content=\"write a funny joke\")])\n"+ " streaming=True,\n",+ ")\n",+ "res = chat([HumanMessage(content=\"write a funny joke\")])"]},{@@ -112,7 +113,6 @@}],"source": [- " \n","from langchain.chat_models import QianfanChatEndpoint\n","from langchain.schema import HumanMessage\n","\n",@@ -125,15 +125,22 @@"\n","\n","async def run_aio_generate():\n",- " resp = await chatLLM.agenerate(messages=[[HumanMessage(content=\"write a 20 words sentence about sea.\")]])\n",+ " resp = await chatLLM.agenerate(\n",+ " messages=[[HumanMessage(content=\"write a 20 words sentence about sea.\")]]\n",+ " )\n"," print(resp)\n",- " \n",+ "\n",+ "\n","await run_aio_generate()\n","\n",+ "\n","async def run_aio_stream():\n",- " async for res in chatLLM.astream([HumanMessage(content=\"write a 20 words sentence about sea.\")]):\n",+ " async for res in chatLLM.astream(\n",+ " [HumanMessage(content=\"write a 20 words sentence about sea.\")]\n",+ " ):\n"," print(\"astream\", res)\n",- " \n",+ "\n",+ "\n","await run_aio_stream()"]},@@ -172,9 +179,9 @@],"source": ["chatBloom = QianfanChatEndpoint(\n",- " streaming=True, \n",- " model=\"BLOOMZ-7B\",\n",- " )\n",+ " streaming=True,\n",+ " model=\"BLOOMZ-7B\",\n",+ ")\n","res = chatBloom([HumanMessage(content=\"hi\")])\n","print(res)"]@@ -217,7 +224,10 @@}],"source": [- "res = chat.stream([HumanMessage(content=\"hi\")], **{'top_p': 0.4, 'temperature': 0.1, 'penalty_score': 1})\n",+ "res = chat.stream(\n",+ " [HumanMessage(content=\"hi\")],\n",+ " **{\"top_p\": 0.4, \"temperature\": 0.1, \"penalty_score\": 1}\n",+ ")\n","\n","for r in res:\n"," print(r)"diff --git a/docs/docs/integrations/chat/bedrock.ipynb b/docs/docs/integrations/chat/bedrock.ipynbindex 856fdf2045..990cc76768 100644--- a/docs/docs/integrations/chat/bedrock.ipynb+++ b/docs/docs/integrations/chat/bedrock.ipynb@@ -1,139 +1,139 @@{- "cells": [- {- "cell_type": "markdown",- "id": "bf733a38-db84-4363-89e2-de6735c37230",- "metadata": {},- "source": [- "# Bedrock Chat\n",- "\n",- "[Amazon Bedrock](https://aws.amazon.com/bedrock/) is a fully managed service that makes FMs from leading AI startups and Amazon available via an API, so you can choose from a wide range of FMs to find the model that is best suited for your use case"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "d51edc81",- "metadata": {},- "outputs": [],- "source": [- "%pip install boto3"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "d4a7c55d-b235-4ca4-a579-c90cc9570da9",- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "from langchain.chat_models import BedrockChat\n",- "from langchain.schema import HumanMessage"- ]- },- {- "cell_type": "code",- "execution_count": 2,- "id": "70cf04e8-423a-4ff6-8b09-f11fb711c817",- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "chat = BedrockChat(model_id=\"anthropic.claude-v2\", model_kwargs={\"temperature\":0.1})"- ]- },- {- "cell_type": "code",- "execution_count": 3,- "id": "8199ef8f-eb8b-4253-9ea0-6c24a013ca4c",- "metadata": {- "tags": []- },- "outputs": [- {- "data": {- "text/plain": [- "AIMessage(content=\" Voici la traduction en français : J'adore programmer.\", additional_kwargs={}, example=False)"- ]- },- "execution_count": 3,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "messages = [\n",- " HumanMessage(\n",- " content=\"Translate this sentence from English to French. I love programming.\"\n",- " )\n",- "]\n",- "chat(messages)"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "id": "a4a4f4d4",- "metadata": {},- "source": [- "### For BedrockChat with Streaming"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "c253883f",- "metadata": {},- "outputs": [],- "source": [- "from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler\n",- "\n",- "chat = BedrockChat(\n",- " model_id=\"anthropic.claude-v2\",\n",- " streaming=True,\n",- " callbacks=[StreamingStdOutCallbackHandler()],\n",- " model_kwargs={\"temperature\": 0.1},\n",- ")"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "d9e52838",- "metadata": {},- "outputs": [],- "source": [- "messages = [\n",- " HumanMessage(\n",- " content=\"Translate this sentence from English to French. I love programming.\"\n",- " )\n",- "]\n",- "chat(messages)"- ]- }- ],- "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.9"- }- },- "nbformat": 4,- "nbformat_minor": 5+ "cells": [+ {+ "cell_type": "markdown",+ "id": "bf733a38-db84-4363-89e2-de6735c37230",+ "metadata": {},+ "source": [+ "# Bedrock Chat\n",+ "\n",+ "[Amazon Bedrock](https://aws.amazon.com/bedrock/) is a fully managed service that makes FMs from leading AI startups and Amazon available via an API, so you can choose from a wide range of FMs to find the model that is best suited for your use case"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "d51edc81",+ "metadata": {},+ "outputs": [],+ "source": [+ "%pip install boto3"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "d4a7c55d-b235-4ca4-a579-c90cc9570da9",+ "metadata": {+ "tags": []+ },+ "outputs": [],+ "source": [+ "from langchain.chat_models import BedrockChat\n",+ "from langchain.schema import HumanMessage"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 2,+ "id": "70cf04e8-423a-4ff6-8b09-f11fb711c817",+ "metadata": {+ "tags": []+ },+ "outputs": [],+ "source": [+ "chat = BedrockChat(model_id=\"anthropic.claude-v2\", model_kwargs={\"temperature\": 0.1})"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 3,+ "id": "8199ef8f-eb8b-4253-9ea0-6c24a013ca4c",+ "metadata": {+ "tags": []+ },+ "outputs": [+ {+ "data": {+ "text/plain": [+ "AIMessage(content=\" Voici la traduction en français : J'adore programmer.\", additional_kwargs={}, example=False)"+ ]+ },+ "execution_count": 3,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "messages = [\n",+ " HumanMessage(\n",+ " content=\"Translate this sentence from English to French. I love programming.\"\n",+ " )\n",+ "]\n",+ "chat(messages)"+ ]+ },+ {+ "attachments": {},+ "cell_type": "markdown",+ "id": "a4a4f4d4",+ "metadata": {},+ "source": [+ "### For BedrockChat with Streaming"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "c253883f",+ "metadata": {},+ "outputs": [],+ "source": [+ "from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler\n",+ "\n",+ "chat = BedrockChat(\n",+ " model_id=\"anthropic.claude-v2\",\n",+ " streaming=True,\n",+ " callbacks=[StreamingStdOutCallbackHandler()],\n",+ " model_kwargs={\"temperature\": 0.1},\n",+ ")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "d9e52838",+ "metadata": {},+ "outputs": [],+ "source": [+ "messages = [\n",+ " HumanMessage(\n",+ " content=\"Translate this sentence from English to French. I love programming.\"\n",+ " )\n",+ "]\n",+ "chat(messages)"+ ]+ }+ ],+ "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.9"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5}diff --git a/docs/docs/integrations/chat/cohere.ipynb b/docs/docs/integrations/chat/cohere.ipynbindex e48da19d87..ec4ba64f9b 100644--- a/docs/docs/integrations/chat/cohere.ipynb+++ b/docs/docs/integrations/chat/cohere.ipynb@@ -55,11 +55,7 @@}],"source": [- "messages = [\n",- " HumanMessage(\n",- " content=\"knock knock\"\n",- " )\n",- "]\n",+ "messages = [HumanMessage(content=\"knock knock\")]\n","chat(messages)"]},diff --git a/docs/docs/integrations/chat/ernie.ipynb b/docs/docs/integrations/chat/ernie.ipynbindex b887991f57..b3ce47ba3b 100644--- a/docs/docs/integrations/chat/ernie.ipynb+++ b/docs/docs/integrations/chat/ernie.ipynb@@ -26,7 +26,9 @@"metadata": {},"outputs": [],"source": [- "chat = ErnieBotChat(ernie_client_id='YOUR_CLIENT_ID', ernie_client_secret='YOUR_CLIENT_SECRET')"+ "chat = ErnieBotChat(\n",+ " ernie_client_id=\"YOUR_CLIENT_ID\", ernie_client_secret=\"YOUR_CLIENT_SECRET\"\n",+ ")"]},{@@ -57,9 +59,7 @@}],"source": [- "chat([\n",- " HumanMessage(content='hello there, who are you?')\n",- "])"+ "chat([HumanMessage(content=\"hello there, who are you?\")])"]}],diff --git a/docs/docs/integrations/chat/everlyai.ipynb b/docs/docs/integrations/chat/everlyai.ipynbindex b75557d56b..16b5bf0d11 100644--- a/docs/docs/integrations/chat/everlyai.ipynb+++ b/docs/docs/integrations/chat/everlyai.ipynb@@ -67,15 +67,15 @@"from langchain.schema import SystemMessage, HumanMessage\n","\n","messages = [\n",- " SystemMessage(\n",- " content=\"You are a helpful AI that shares everything you know.\"\n",- " ),\n",+ " SystemMessage(content=\"You are a helpful AI that shares everything you know.\"),\n"," HumanMessage(\n"," content=\"Tell me technical facts about yourself. Are you a transformer model? How many billions of parameters do you have?\"\n"," ),\n","]\n","\n",- "chat = ChatEverlyAI(model_name=\"meta-llama/Llama-2-7b-chat-hf\", temperature=0.3, max_tokens=64)\n",+ "chat = ChatEverlyAI(\n",+ " model_name=\"meta-llama/Llama-2-7b-chat-hf\", temperature=0.3, max_tokens=64\n",+ ")\n","print(chat(messages).content)"]},@@ -121,15 +121,17 @@"from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler\n","\n","messages = [\n",- " SystemMessage(\n",- " content=\"You are a humorous AI that delights people.\"\n",- " ),\n",- " HumanMessage(\n",- " content=\"Tell me a joke?\"\n",- " ),\n",+ " SystemMessage(content=\"You are a humorous AI that delights people.\"),\n",+ " HumanMessage(content=\"Tell me a joke?\"),\n","]\n","\n",- "chat = ChatEverlyAI(model_name=\"meta-llama/Llama-2-7b-chat-hf\", temperature=0.3, max_tokens=64, streaming=True, callbacks=[StreamingStdOutCallbackHandler()])\n",+ "chat = ChatEverlyAI(\n",+ " model_name=\"meta-llama/Llama-2-7b-chat-hf\",\n",+ " temperature=0.3,\n",+ " max_tokens=64,\n",+ " streaming=True,\n",+ " callbacks=[StreamingStdOutCallbackHandler()],\n",+ ")\n","chat(messages)"]},@@ -177,15 +179,17 @@"from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler\n","\n","messages = [\n",- " SystemMessage(\n",- " content=\"You are a humorous AI that delights people.\"\n",- " ),\n",- " HumanMessage(\n",- " content=\"Tell me a joke?\"\n",- " ),\n",+ " SystemMessage(content=\"You are a humorous AI that delights people.\"),\n",+ " HumanMessage(content=\"Tell me a joke?\"),\n","]\n","\n",- "chat = ChatEverlyAI(model_name=\"meta-llama/Llama-2-13b-chat-hf-quantized\", temperature=0.3, max_tokens=128, streaming=True, callbacks=[StreamingStdOutCallbackHandler()])\n",+ "chat = ChatEverlyAI(\n",+ " model_name=\"meta-llama/Llama-2-13b-chat-hf-quantized\",\n",+ " temperature=0.3,\n",+ " max_tokens=128,\n",+ " streaming=True,\n",+ " callbacks=[StreamingStdOutCallbackHandler()],\n",+ ")\n","chat(messages)"]}diff --git a/docs/docs/integrations/chat/fireworks.ipynb b/docs/docs/integrations/chat/fireworks.ipynbindex 38326eb354..9d2524db78 100644--- a/docs/docs/integrations/chat/fireworks.ipynb+++ b/docs/docs/integrations/chat/fireworks.ipynb@@ -27,7 +27,7 @@"source": ["from langchain.chat_models.fireworks import ChatFireworks\n","from langchain.schema import SystemMessage, HumanMessage\n",- "import os\n"+ "import os"]},{@@ -56,7 +56,7 @@" os.environ[\"FIREWORKS_API_KEY\"] = getpass.getpass(\"Fireworks API Key:\")\n","\n","# Initialize a Fireworks chat model\n",- "chat = ChatFireworks(model=\"accounts/fireworks/models/llama-v2-13b-chat\")\n"+ "chat = ChatFireworks(model=\"accounts/fireworks/models/llama-v2-13b-chat\")"]},{@@ -91,7 +91,7 @@"system_message = SystemMessage(content=\"You are to chat with the user.\")\n","human_message = HumanMessage(content=\"Who are you?\")\n","\n",- "chat([system_message, human_message])\n"+ "chat([system_message, human_message])"]},{@@ -113,10 +113,13 @@],"source": ["# Setting additional parameters: temperature, max_tokens, top_p\n",- "chat = ChatFireworks(model=\"accounts/fireworks/models/llama-v2-13b-chat\", model_kwargs={\"temperature\":1, \"max_tokens\": 20, \"top_p\": 1})\n",+ "chat = ChatFireworks(\n",+ " model=\"accounts/fireworks/models/llama-v2-13b-chat\",\n",+ " model_kwargs={\"temperature\": 1, \"max_tokens\": 20, \"top_p\": 1},\n",+ ")\n","system_message = SystemMessage(content=\"You are to chat with the user.\")\n","human_message = HumanMessage(content=\"How's the weather today?\")\n",- "chat([system_message, human_message])\n"+ "chat([system_message, human_message])"]},{@@ -147,12 +150,17 @@"from langchain.schema.runnable import RunnablePassthrough\n","from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder\n","\n",- "llm = ChatFireworks(model=\"accounts/fireworks/models/llama-v2-13b-chat\", model_kwargs={\"temperature\":0, \"max_tokens\":64, \"top_p\":1.0})\n",- "prompt = ChatPromptTemplate.from_messages([\n",- " (\"system\", \"You are a helpful chatbot that speaks like a pirate.\"),\n",- " MessagesPlaceholder(variable_name=\"history\"),\n",- " (\"human\", \"{input}\")\n",- "])\n"+ "llm = ChatFireworks(\n",+ " model=\"accounts/fireworks/models/llama-v2-13b-chat\",\n",+ " model_kwargs={\"temperature\": 0, \"max_tokens\": 64, \"top_p\": 1.0},\n",+ ")\n",+ "prompt = ChatPromptTemplate.from_messages(\n",+ " [\n",+ " (\"system\", \"You are a helpful chatbot that speaks like a pirate.\"),\n",+ " MessagesPlaceholder(variable_name=\"history\"),\n",+ " (\"human\", \"{input}\"),\n",+ " ]\n",+ ")"]},{@@ -182,7 +190,7 @@],"source": ["memory = ConversationBufferMemory(return_messages=True)\n",- "memory.load_memory_variables({})\n"+ "memory.load_memory_variables({})"]},{@@ -200,9 +208,13 @@"metadata": {},"outputs": [],"source": [- "chain = RunnablePassthrough.assign(\n",- " history=memory.load_memory_variables | (lambda x: x[\"history\"])\n",- ") | prompt | llm.bind(stop=[\"\\n\\n\"])\n"+ "chain = (\n",+ " RunnablePassthrough.assign(\n",+ " history=memory.load_memory_variables | (lambda x: x[\"history\"])\n",+ " )\n",+ " | prompt\n",+ " | llm.bind(stop=[\"\\n\\n\"])\n",+ ")"]},{@@ -233,7 +245,7 @@"source": ["inputs = {\"input\": \"hi im bob\"}\n","response = chain.invoke(inputs)\n",- "response\n"+ "response"]},{@@ -264,7 +276,7 @@],"source": ["memory.save_context(inputs, {\"output\": response.content})\n",- "memory.load_memory_variables({})\n"+ "memory.load_memory_variables({})"]},{@@ -294,7 +306,7 @@],"source": ["inputs = {\"input\": \"whats my name\"}\n",- "chain.invoke(inputs)\n"+ "chain.invoke(inputs)"]}],diff --git a/docs/docs/integrations/chat/gigachat.ipynb b/docs/docs/integrations/chat/gigachat.ipynbindex c353fe75d8..00dce1c2aa 100644--- a/docs/docs/integrations/chat/gigachat.ipynb+++ b/docs/docs/integrations/chat/gigachat.ipynb@@ -40,7 +40,7 @@"import os\n","from getpass import getpass\n","\n",- "os.environ['GIGACHAT_CREDENTIALS'] = getpass()"+ "os.environ[\"GIGACHAT_CREDENTIALS\"] = getpass()"],"metadata": {"collapsed": false@@ -78,9 +78,7 @@" SystemMessage(\n"," content=\"You are a helpful AI that shares everything you know. Talk in English.\"\n"," ),\n",- " HumanMessage(\n",- " content=\"Tell me a joke\"\n",- " ),\n",+ " HumanMessage(content=\"Tell me a joke\"),\n","]\n","\n","print(chat(messages).content)"diff --git a/docs/docs/integrations/chat/google_vertex_ai_palm.ipynb b/docs/docs/integrations/chat/google_vertex_ai_palm.ipynbindex 8d194eb048..93e9f3c87e 100644--- a/docs/docs/integrations/chat/google_vertex_ai_palm.ipynb+++ b/docs/docs/integrations/chat/google_vertex_ai_palm.ipynb@@ -31,7 +31,7 @@},"outputs": [],"source": [- "#!pip install langchain google-cloud-aiplatform\n"+ "#!pip install langchain google-cloud-aiplatform"]},{@@ -41,7 +41,7 @@"outputs": [],"source": ["from langchain.chat_models import ChatVertexAI\n",- "from langchain.prompts import ChatPromptTemplate\n"+ "from langchain.prompts import ChatPromptTemplate"]},{@@ -50,7 +50,7 @@"metadata": {},"outputs": [],"source": [- "chat = ChatVertexAI()\n"+ "chat = ChatVertexAI()"]},{@@ -61,10 +61,8 @@"source": ["system = \"You are a helpful assistant who translate English to French\"\n","human = \"Translate this sentence from English to French. I love programming.\"\n",- "prompt = ChatPromptTemplate.from_messages(\n",- " [(\"system\", system), (\"human\", human)]\n",- ")\n",- "messages = prompt.format_messages()\n"+ "prompt = ChatPromptTemplate.from_messages([(\"system\", system), (\"human\", human)])\n",+ "messages = prompt.format_messages()"]},{@@ -84,7 +82,7 @@}],"source": [- "chat(messages)\n"+ "chat(messages)"]},{@@ -100,11 +98,11 @@"metadata": {},"outputs": [],"source": [- "system = \"You are a helpful assistant that translates {input_language} to {output_language}.\"\n",+ "system = (\n",+ " \"You are a helpful assistant that translates {input_language} to {output_language}.\"\n",+ ")\n","human = \"{text}\"\n",- "prompt = ChatPromptTemplate.from_messages(\n",- " [(\"system\", system), (\"human\", human)]\n",- ")\n"+ "prompt = ChatPromptTemplate.from_messages([(\"system\", system), (\"human\", human)])"]},{@@ -126,8 +124,12 @@"source": ["chain = prompt | chat\n","chain.invoke(\n",- " {\"input_language\": \"English\", \"output_language\": \"Japanese\", \"text\": \"I love programming\"}\n",- ")\n"+ " {\n",+ " \"input_language\": \"English\",\n",+ " \"output_language\": \"Japanese\",\n",+ " \"text\": \"I love programming\",\n",+ " }\n",+ ")"]},{@@ -158,10 +160,8 @@"outputs": [],"source": ["chat = ChatVertexAI(\n",- " model_name=\"codechat-bison\",\n",- " max_output_tokens=1000,\n",- " temperature=0.5\n",- ")\n"+ " model_name=\"codechat-bison\", max_output_tokens=1000, temperature=0.5\n",+ ")"]},{@@ -189,7 +189,7 @@],"source": ["# For simple string in string out usage, we can use the `predict` method:\n",- "print(chat.predict(\"Write a Python function to identify all prime numbers\"))\n"+ "print(chat.predict(\"Write a Python function to identify all prime numbers\"))"]},{@@ -208,8 +208,9 @@"outputs": [],"source": ["import asyncio\n",+ "\n","# import nest_asyncio\n",- "# nest_asyncio.apply()\n"+ "# nest_asyncio.apply()"]},{@@ -237,7 +238,7 @@" top_k=40,\n",")\n","\n",- "asyncio.run(chat.agenerate([messages]))\n"+ "asyncio.run(chat.agenerate([messages]))"]},{@@ -257,7 +258,15 @@}],"source": [- "asyncio.run(chain.ainvoke({\"input_language\": \"English\", \"output_language\": \"Sanskrit\", \"text\": \"I love programming\"}))\n"+ "asyncio.run(\n",+ " chain.ainvoke(\n",+ " {\n",+ " \"input_language\": \"English\",\n",+ " \"output_language\": \"Sanskrit\",\n",+ " \"text\": \"I love programming\",\n",+ " }\n",+ " )\n",+ ")"]},{@@ -275,7 +284,7 @@"metadata": {},"outputs": [],"source": [- "import sys\n"+ "import sys"]},{@@ -306,11 +315,13 @@}],"source": [- "prompt = ChatPromptTemplate.from_messages([(\"human\", \"List out the 15 most populous countries in the world\")])\n",+ "prompt = ChatPromptTemplate.from_messages(\n",+ " [(\"human\", \"List out the 15 most populous countries in the world\")]\n",+ ")\n","messages = prompt.format_messages()\n","for chunk in chat.stream(messages):\n"," sys.stdout.write(chunk.content)\n",- " sys.stdout.flush()\n"+ " sys.stdout.flush()"]}],diff --git a/docs/docs/integrations/chat/hunyuan.ipynb b/docs/docs/integrations/chat/hunyuan.ipynbindex 07cbe1d7d8..ebc2b9fca8 100644--- a/docs/docs/integrations/chat/hunyuan.ipynb+++ b/docs/docs/integrations/chat/hunyuan.ipynb@@ -36,9 +36,9 @@"outputs": [],"source": ["chat = ChatHunyuan(\n",- " hunyuan_app_id='YOUR_APP_ID',\n",- " hunyuan_secret_id='YOUR_SECRET_ID',\n",- " hunyuan_secret_key='YOUR_SECRET_KEY',\n",+ " hunyuan_app_id=\"YOUR_APP_ID\",\n",+ " hunyuan_secret_id=\"YOUR_SECRET_ID\",\n",+ " hunyuan_secret_key=\"YOUR_SECRET_KEY\",\n",")"]},@@ -62,9 +62,13 @@}],"source": [- "chat([\n",- " HumanMessage(content='You are a helpful assistant that translates English to French.Translate this sentence from English to French. I love programming.')\n",- "])"+ "chat(\n",+ " [\n",+ " HumanMessage(\n",+ " content=\"You are a helpful assistant that translates English to French.Translate this sentence from English to French. I love programming.\"\n",+ " )\n",+ " ]\n",+ ")"]},{@@ -82,9 +86,9 @@"outputs": [],"source": ["chat = ChatHunyuan(\n",- " hunyuan_app_id='YOUR_APP_ID',\n",- " hunyuan_secret_id='YOUR_SECRET_ID',\n",- " hunyuan_secret_key='YOUR_SECRET_KEY',\n",+ " hunyuan_app_id=\"YOUR_APP_ID\",\n",+ " hunyuan_secret_id=\"YOUR_SECRET_ID\",\n",+ " hunyuan_secret_key=\"YOUR_SECRET_KEY\",\n"," streaming=True,\n",")"],@@ -110,9 +114,13 @@}],"source": [- "chat([\n",- " HumanMessage(content='You are a helpful assistant that translates English to French.Translate this sentence from English to French. I love programming.')\n",- "])"+ "chat(\n",+ " [\n",+ " HumanMessage(\n",+ " content=\"You are a helpful assistant that translates English to French.Translate this sentence from English to French. I love programming.\"\n",+ " )\n",+ " ]\n",+ ")"],"metadata": {"collapsed": false,diff --git a/docs/docs/integrations/chat/konko.ipynb b/docs/docs/integrations/chat/konko.ipynbindex 5884ff73c5..cd2ceae0e8 100644--- a/docs/docs/integrations/chat/konko.ipynb+++ b/docs/docs/integrations/chat/konko.ipynb@@ -96,7 +96,7 @@"metadata": {},"outputs": [],"source": [- "chat = ChatKonko(max_tokens=400, model = 'meta-llama/Llama-2-13b-chat-hf')"+ "chat = ChatKonko(max_tokens=400, model=\"meta-llama/Llama-2-13b-chat-hf\")"]},{@@ -117,12 +117,8 @@],"source": ["messages = [\n",- " SystemMessage(\n",- " content=\"You are a helpful assistant.\"\n",- " ),\n",- " HumanMessage(\n",- " content=\"Explain Big Bang Theory briefly\"\n",- " ),\n",+ " SystemMessage(content=\"You are a helpful assistant.\"),\n",+ " HumanMessage(content=\"Explain Big Bang Theory briefly\"),\n","]\n","chat(messages)"]diff --git a/docs/docs/integrations/chat/llama_api.ipynb b/docs/docs/integrations/chat/llama_api.ipynbindex 0567a21d6c..329904a6bc 100644--- a/docs/docs/integrations/chat/llama_api.ipynb+++ b/docs/docs/integrations/chat/llama_api.ipynb@@ -28,7 +28,7 @@"from llamaapi import LlamaAPI\n","\n","# Replace 'Your_API_Token' with your actual API token\n",- "llama = LlamaAPI('Your_API_Token')"+ "llama = LlamaAPI(\"Your_API_Token\")"]},{@@ -71,9 +71,15 @@"\n","schema = {\n"," \"properties\": {\n",- " \"sentiment\": {\"type\": \"string\", 'description': 'the sentiment encountered in the passage'},\n",- " \"aggressiveness\": {\"type\": \"integer\", 'description': 'a 0-10 score of how aggressive the passage is'},\n",- " \"language\": {\"type\": \"string\", 'description': 'the language of the passage'},\n",+ " \"sentiment\": {\n",+ " \"type\": \"string\",\n",+ " \"description\": \"the sentiment encountered in the passage\",\n",+ " },\n",+ " \"aggressiveness\": {\n",+ " \"type\": \"integer\",\n",+ " \"description\": \"a 0-10 score of how aggressive the passage is\",\n",+ " },\n",+ " \"language\": {\"type\": \"string\", \"description\": \"the language of the passage\"},\n"," }\n","}\n","\n",diff --git a/docs/docs/integrations/chat/ollama.ipynb b/docs/docs/integrations/chat/ollama.ipynbindex dad3da2051..d2f7566fc5 100644--- a/docs/docs/integrations/chat/ollama.ipynb+++ b/docs/docs/integrations/chat/ollama.ipynb@@ -61,9 +61,12 @@"source": ["from langchain.chat_models import ChatOllama\n","from langchain.callbacks.manager import CallbackManager\n",- "from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler \n",- "chat_model = ChatOllama(model=\"llama2:7b-chat\", \n",- " callback_manager = CallbackManager([StreamingStdOutCallbackHandler()]))"+ "from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler\n",+ "\n",+ "chat_model = ChatOllama(\n",+ " model=\"llama2:7b-chat\",\n",+ " callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]),\n",+ ")"]},{@@ -112,9 +115,7 @@"source": ["from langchain.schema import HumanMessage\n","\n",- "messages = [\n",- " HumanMessage(content=\"Tell me about the history of AI\")\n",- "]\n",+ "messages = [HumanMessage(content=\"Tell me about the history of AI\")]\n","chat_model(messages)"]},@@ -151,10 +152,12 @@"outputs": [],"source": ["from langchain.document_loaders import WebBaseLoader\n",+ "\n","loader = WebBaseLoader(\"https://lilianweng.github.io/posts/2023-06-23-agent/\")\n","data = loader.load()\n","\n","from langchain.text_splitter import RecursiveCharacterTextSplitter\n",+ "\n","text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=0)\n","all_splits = text_splitter.split_documents(data)"]@@ -224,9 +227,12 @@"from langchain.chat_models import ChatOllama\n","from langchain.callbacks.manager import CallbackManager\n","from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler\n",- "chat_model = ChatOllama(model=\"llama2:13b\",\n",- " verbose=True,\n",- " callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]))"+ "\n",+ "chat_model = ChatOllama(\n",+ " model=\"llama2:13b\",\n",+ " verbose=True,\n",+ " callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]),\n",+ ")"]},{@@ -237,6 +243,7 @@"source": ["# QA chain\n","from langchain.chains import RetrievalQA\n",+ "\n","qa_chain = RetrievalQA.from_chain_type(\n"," chat_model,\n"," retriever=vectorstore.as_retriever(),\n",@@ -296,15 +303,19 @@"from langchain.schema import LLMResult\n","from langchain.callbacks.base import BaseCallbackHandler\n","\n",+ "\n","class GenerationStatisticsCallback(BaseCallbackHandler):\n"," def on_llm_end(self, response: LLMResult, **kwargs) -> None:\n"," print(response.generations[0][0].generation_info)\n",- " \n",- "callback_manager = CallbackManager([StreamingStdOutCallbackHandler(), GenerationStatisticsCallback()])\n","\n",- "chat_model = ChatOllama(model=\"llama2:13b-chat\",\n",- " verbose=True,\n",- " callback_manager=callback_manager)\n",+ "\n",+ "callback_manager = CallbackManager(\n",+ " [StreamingStdOutCallbackHandler(), GenerationStatisticsCallback()]\n",+ ")\n",+ "\n",+ "chat_model = ChatOllama(\n",+ " model=\"llama2:13b-chat\", verbose=True, callback_manager=callback_manager\n",+ ")\n","\n","qa_chain = RetrievalQA.from_chain_type(\n"," chat_model,\n",@@ -340,7 +351,7 @@}],"source": [- "98 / (3229641000/1000/1000/1000)"+ "98 / (3229641000 / 1000 / 1000 / 1000)"]}],diff --git a/docs/docs/integrations/chat/openai.ipynb b/docs/docs/integrations/chat/openai.ipynbindex d75fb6efaa..2b318bc2dc 100644--- a/docs/docs/integrations/chat/openai.ipynb+++ b/docs/docs/integrations/chat/openai.ipynb@@ -172,7 +172,9 @@}],"source": [- "fine_tuned_model = ChatOpenAI(temperature=0, model_name=\"ft:gpt-3.5-turbo-0613:langchain::7qTVM5AR\")\n",+ "fine_tuned_model = ChatOpenAI(\n",+ " temperature=0, model_name=\"ft:gpt-3.5-turbo-0613:langchain::7qTVM5AR\"\n",+ ")\n","\n","fine_tuned_model(messages)"]diff --git a/docs/docs/integrations/chat/pai_eas_chat_endpoint.ipynb b/docs/docs/integrations/chat/pai_eas_chat_endpoint.ipynbindex 321ac92a7d..716c89d724 100644--- a/docs/docs/integrations/chat/pai_eas_chat_endpoint.ipynb+++ b/docs/docs/integrations/chat/pai_eas_chat_endpoint.ipynb@@ -32,11 +32,12 @@"import os\n","from langchain.chat_models.base import HumanMessage\n","from langchain.chat_models import PaiEasChatEndpoint\n",+ "\n","os.environ[\"EAS_SERVICE_URL\"] = \"Your_EAS_Service_URL\"\n","os.environ[\"EAS_SERVICE_TOKEN\"] = \"Your_EAS_Service_Token\"\n","chat = PaiEasChatEndpoint(\n",- " eas_service_url=os.environ[\"EAS_SERVICE_URL\"], \n",- " eas_service_token=os.environ[\"EAS_SERVICE_TOKEN\"]\n",+ " eas_service_url=os.environ[\"EAS_SERVICE_URL\"],\n",+ " eas_service_token=os.environ[\"EAS_SERVICE_TOKEN\"],\n",")"]},@@ -89,7 +90,6 @@"metadata": {},"outputs": [],"source": [- "\n","outputs = chat.stream([HumanMessage(content=\"hi\")], streaming=True)\n","for output in outputs:\n"," print(\"stream output:\", output)"diff --git a/docs/docs/integrations/chat/tongyi.ipynb b/docs/docs/integrations/chat/tongyi.ipynbindex 970dd0066a..f0856d33e6 100644--- a/docs/docs/integrations/chat/tongyi.ipynb+++ b/docs/docs/integrations/chat/tongyi.ipynb@@ -120,6 +120,7 @@],"source": ["from langchain.schema import AIMessage, HumanMessage, SystemMessage\n",+ "\n","messages = [\n"," SystemMessage(\n"," content=\"You are a helpful assistant that translates English to French.\"\n",diff --git a/docs/docs/integrations/chat/yandex.ipynb b/docs/docs/integrations/chat/yandex.ipynbindex dd098cc1e7..598c937956 100644--- a/docs/docs/integrations/chat/yandex.ipynb+++ b/docs/docs/integrations/chat/yandex.ipynb@@ -77,8 +77,10 @@"source": ["answer = chat_model(\n"," [\n",- " SystemMessage(content=\"You are a helpful assistant that translates English to French.\"),\n",- " HumanMessage(content=\"I love programming.\")\n",+ " SystemMessage(\n",+ " content=\"You are a helpful assistant that translates English to French.\"\n",+ " ),\n",+ " HumanMessage(content=\"I love programming.\"),\n"," ]\n",")\n","answer"diff --git a/docs/docs/integrations/chat_loaders/discord.ipynb b/docs/docs/integrations/chat_loaders/discord.ipynbindex 59ed0d6bb2..4abd3d704a 100644--- a/docs/docs/integrations/chat_loaders/discord.ipynb+++ b/docs/docs/integrations/chat_loaders/discord.ipynb@@ -88,7 +88,6 @@"\n","\n","class DiscordChatLoader(chat_loaders.BaseChatLoader):\n",- " \n"," def __init__(self, path: str):\n"," \"\"\"\n"," Initialize the Discord chat loader.\n",@@ -175,7 +174,7 @@" Yields:\n"," A `ChatSession` object containing the loaded chat messages.\n"," \"\"\"\n",- " yield self._load_single_chat_session_from_txt(self.path)\n"+ " yield self._load_single_chat_session_from_txt(self.path)"]},{@@ -228,7 +227,9 @@"# Merge consecutive messages from the same sender into a single message\n","merged_messages = merge_chat_runs(raw_messages)\n","# Convert messages from \"talkingtower\" to AI messages\n",- "messages: List[ChatSession] = list(map_ai_messages(merged_messages, sender=\"talkingtower\"))"+ "messages: List[ChatSession] = list(\n",+ " map_ai_messages(merged_messages, sender=\"talkingtower\")\n",+ ")"]},{@@ -288,7 +289,7 @@"\n","llm = ChatOpenAI()\n","\n",- "for chunk in llm.stream(messages[0]['messages']):\n",+ "for chunk in llm.stream(messages[0][\"messages\"]):\n"," print(chunk.content, end=\"\", flush=True)"]},diff --git a/docs/docs/integrations/chat_loaders/facebook.ipynb b/docs/docs/integrations/chat_loaders/facebook.ipynbindex 053b31fc07..7a08d0a508 100644--- a/docs/docs/integrations/chat_loaders/facebook.ipynb+++ b/docs/docs/integrations/chat_loaders/facebook.ipynb@@ -50,28 +50,32 @@"import requests\n","import zipfile\n","\n",- "def download_and_unzip(url: str, output_path: str = 'file.zip') -> None:\n",- " file_id = url.split('/')[-2]\n",- " download_url = f'https://drive.google.com/uc?export=download&id={file_id}'\n",+ "\n",+ "def download_and_unzip(url: str, output_path: str = \"file.zip\") -> None:\n",+ " file_id = url.split(\"/\")[-2]\n",+ " download_url = f\"https://drive.google.com/uc?export=download&id={file_id}\"\n","\n"," response = requests.get(download_url)\n"," if response.status_code != 200:\n",- " print('Failed to download the file.')\n",+ " print(\"Failed to download the file.\")\n"," return\n","\n",- " with open(output_path, 'wb') as file:\n",+ " with open(output_path, \"wb\") as file:\n"," file.write(response.content)\n",- " print(f'File {output_path} downloaded.')\n",+ " print(f\"File {output_path} downloaded.\")\n","\n",- " with zipfile.ZipFile(output_path, 'r') as zip_ref:\n",+ " with zipfile.ZipFile(output_path, \"r\") as zip_ref:\n"," zip_ref.extractall()\n",- " print(f'File {output_path} has been unzipped.')\n",+ " print(f\"File {output_path} has been unzipped.\")\n",+ "\n","\n","# URL of the file to download\n",- "url = 'https://drive.google.com/file/d/1rh1s1o2i7B-Sk1v9o8KNgivLVGwJ-osV/view?usp=sharing'\n",+ "url = (\n",+ " \"https://drive.google.com/file/d/1rh1s1o2i7B-Sk1v9o8KNgivLVGwJ-osV/view?usp=sharing\"\n",+ ")\n","\n","# Download and unzip\n",- "download_and_unzip(url)\n"+ "download_and_unzip(url)"]},{@@ -235,7 +239,7 @@"source": ["# Now all of Harry Potter's messages will take the AI message class\n","# which maps to the 'assistant' role in OpenAI's training format\n",- "alternating_sessions[0]['messages'][:3]"+ "alternating_sessions[0][\"messages\"][:3]"]},{@@ -338,11 +342,9 @@"overlap = 2\n","\n","training_examples = [\n",- " conversation_messages[i: i + chunk_size] \n",+ " conversation_messages[i : i + chunk_size]\n"," for conversation_messages in training_data\n",- " for i in range(\n",- " 0, len(conversation_messages) - chunk_size + 1, \n",- " chunk_size - overlap)\n",+ " for i in range(0, len(conversation_messages) - chunk_size + 1, chunk_size - overlap)\n","]\n","\n","len(training_examples)"@@ -393,13 +395,10 @@"# We will write the jsonl file in memory\n","my_file = BytesIO()\n","for m in training_examples:\n",- " my_file.write((json.dumps({\"messages\": m}) + \"\\n\").encode('utf-8'))\n",+ " my_file.write((json.dumps({\"messages\": m}) + \"\\n\").encode(\"utf-8\"))\n","\n","my_file.seek(0)\n",- "training_file = openai.File.create(\n",- " file=my_file,\n",- " purpose='fine-tune'\n",- ")\n",+ "training_file = openai.File.create(file=my_file, purpose=\"fine-tune\")\n","\n","# OpenAI audits each training file for compliance reasons.\n","# This make take a few minutes\n",diff --git a/docs/docs/integrations/chat_loaders/gmail.ipynb b/docs/docs/integrations/chat_loaders/gmail.ipynbindex bf7651c587..4735634341 100644--- a/docs/docs/integrations/chat_loaders/gmail.ipynb+++ b/docs/docs/integrations/chat_loaders/gmail.ipynb@@ -47,26 +47,28 @@"import logging\n","import requests\n","\n",- "SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']\n",+ "SCOPES = [\"https://www.googleapis.com/auth/gmail.readonly\"]\n","\n","\n","creds = None\n","# The file token.json stores the user's access and refresh tokens, and is\n","# created automatically when the authorization flow completes for the first\n","# time.\n",- "if os.path.exists('email_token.json'):\n",- " creds = Credentials.from_authorized_user_file('email_token.json', SCOPES)\n",+ "if os.path.exists(\"email_token.json\"):\n",+ " creds = Credentials.from_authorized_user_file(\"email_token.json\", SCOPES)\n","# If there are no (valid) credentials available, let the user log in.\n","if not creds or not creds.valid:\n"," if creds and creds.expired and creds.refresh_token:\n"," creds.refresh(Request())\n"," else:\n",- " flow = InstalledAppFlow.from_client_secrets_file( \n",+ " flow = InstalledAppFlow.from_client_secrets_file(\n"," # your creds file here. Please create json file as here https://cloud.google.com/docs/authentication/getting-started\n",- " 'creds.json', SCOPES)\n",+ " \"creds.json\",\n",+ " SCOPES,\n",+ " )\n"," creds = flow.run_local_server(port=0)\n"," # Save the credentials for the next run\n",- " with open('email_token.json', 'w') as token:\n",+ " with open(\"email_token.json\", \"w\") as token:\n"," token.write(creds.to_json())"]},@@ -143,7 +145,9 @@"source": ["# This makes messages sent by [email protected] the AI Messages\n","# This means you will train an LLM to predict as if it's responding as hchase\n",- "training_data = list(map_ai_messages(data, sender=\"Harrison Chase <[email protected]>\"))"+ "training_data = list(\n",+ " map_ai_messages(data, sender=\"Harrison Chase <[email protected]>\")\n",+ ")"]},{diff --git a/docs/docs/integrations/chat_loaders/imessage.ipynb b/docs/docs/integrations/chat_loaders/imessage.ipynbindex ead7e28278..a547b22d37 100644--- a/docs/docs/integrations/chat_loaders/imessage.ipynb+++ b/docs/docs/integrations/chat_loaders/imessage.ipynb@@ -40,20 +40,24 @@"# This uses some example data\n","import requests\n","\n",- "def download_drive_file(url: str, output_path: str = 'chat.db') -> None:\n",- " file_id = url.split('/')[-2]\n",- " download_url = f'https://drive.google.com/uc?export=download&id={file_id}'\n",+ "\n",+ "def download_drive_file(url: str, output_path: str = \"chat.db\") -> None:\n",+ " file_id = url.split(\"/\")[-2]\n",+ " download_url = f\"https://drive.google.com/uc?export=download&id={file_id}\"\n","\n"," response = requests.get(download_url)\n"," if response.status_code != 200:\n",- " print('Failed to download the file.')\n",+ " print(\"Failed to download the file.\")\n"," return\n","\n",- " with open(output_path, 'wb') as file:\n",+ " with open(output_path, \"wb\") as file:\n"," file.write(response.content)\n",- " print(f'File {output_path} downloaded.')\n",+ " print(f\"File {output_path} downloaded.\")\n",+ "\n","\n",- "url = 'https://drive.google.com/file/d/1NebNKqTA2NXApCmeH6mu0unJD2tANZzo/view?usp=sharing'\n",+ "url = (\n",+ " \"https://drive.google.com/file/d/1NebNKqTA2NXApCmeH6mu0unJD2tANZzo/view?usp=sharing\"\n",+ ")\n","\n","# Download file to chat.db\n","download_drive_file(url)"@@ -121,7 +125,9 @@"# Merge consecutive messages from the same sender into a single message\n","merged_messages = merge_chat_runs(raw_messages)\n","# Convert messages from \"Tortoise\" to AI messages. Do you have a guess who these conversations are between?\n",- "chat_sessions: List[ChatSession] = list(map_ai_messages(merged_messages, sender=\"Tortoise\"))"+ "chat_sessions: List[ChatSession] = list(\n",+ " map_ai_messages(merged_messages, sender=\"Tortoise\")\n",+ ")"]},{@@ -146,7 +152,7 @@"source": ["# Now all of the Tortoise's messages will take the AI message class\n","# which maps to the 'assistant' role in OpenAI's training format\n",- "alternating_sessions[0]['messages'][:3]"+ "alternating_sessions[0][\"messages\"][:3]"]},{@@ -233,13 +239,10 @@"# We will write the jsonl file in memory\n","my_file = BytesIO()\n","for m in training_data:\n",- " my_file.write((json.dumps({\"messages\": m}) + \"\\n\").encode('utf-8'))\n",+ " my_file.write((json.dumps({\"messages\": m}) + \"\\n\").encode(\"utf-8\"))\n","\n","my_file.seek(0)\n",- "training_file = openai.File.create(\n",- " file=my_file,\n",- " purpose='fine-tune'\n",- ")\n",+ "training_file = openai.File.create(file=my_file, purpose=\"fine-tune\")\n","\n","# OpenAI audits each training file for compliance reasons.\n","# This make take a few minutes\n",diff --git a/docs/docs/integrations/chat_loaders/langsmith_dataset.ipynb b/docs/docs/integrations/chat_loaders/langsmith_dataset.ipynbindex 554cd298df..8f63828f77 100644--- a/docs/docs/integrations/chat_loaders/langsmith_dataset.ipynb+++ b/docs/docs/integrations/chat_loaders/langsmith_dataset.ipynb@@ -42,6 +42,7 @@"source": ["import os\n","import uuid\n",+ "\n","uid = uuid.uuid4().hex[:6]\n","os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\n","os.environ[\"LANGCHAIN_API_KEY\"] = \"YOUR API KEY\""@@ -79,6 +80,7 @@"outputs": [],"source": ["import requests\n",+ "\n","url = \"https://raw.githubusercontent.com/langchain-ai/langchain/master/docs/docs/integrations/chat_loaders/example_data/langsmith_chat_dataset.json\"\n","response = requests.get(url)\n","response.raise_for_status()\n",@@ -104,8 +106,8 @@"outputs": [],"source": ["_ = client.create_examples(\n",- " inputs = [e['inputs'] for e in data],\n",- " outputs = [e['outputs'] for e in data],\n",+ " inputs=[e[\"inputs\"] for e in data],\n",+ " outputs=[e[\"outputs\"] for e in data],\n"," dataset_id=ds.id,\n",")"]@@ -184,13 +186,10 @@"\n","my_file = BytesIO()\n","for dialog in training_data:\n",- " my_file.write((json.dumps({\"messages\": dialog}) + \"\\n\").encode('utf-8'))\n",+ " my_file.write((json.dumps({\"messages\": dialog}) + \"\\n\").encode(\"utf-8\"))\n","\n","my_file.seek(0)\n",- "training_file = openai.File.create(\n",- " file=my_file,\n",- " purpose='fine-tune'\n",- ")\n",+ "training_file = openai.File.create(file=my_file, purpose=\"fine-tune\")\n","\n","job = openai.FineTuningJob.create(\n"," training_file=training_file.id,\n",diff --git a/docs/docs/integrations/chat_loaders/langsmith_llm_runs.ipynb b/docs/docs/integrations/chat_loaders/langsmith_llm_runs.ipynbindex 2819401885..997f6c9a96 100644--- a/docs/docs/integrations/chat_loaders/langsmith_llm_runs.ipynb+++ b/docs/docs/integrations/chat_loaders/langsmith_llm_runs.ipynb@@ -42,6 +42,7 @@"source": ["import os\n","import uuid\n",+ "\n","uid = uuid.uuid4().hex[:6]\n","project_name = f\"Run Fine-tuning Walkthrough {uid}\"\n","os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\n",@@ -79,8 +80,10 @@" multiply = \"*\"\n"," divide = \"/\"\n","\n",+ "\n","class Calculator(BaseModel):\n"," \"\"\"A calculator function\"\"\"\n",+ "\n"," num1: float\n"," num2: float\n"," operation: Operation = Field(..., description=\"+,-,*,/\")\n",@@ -197,7 +200,7 @@" \"What's 60-30?\",\n"," \"What's 50-25?\",\n"," \"What's 40-20?\",\n",- " \"What's 30-15?\"\n",+ " \"What's 30-15?\",\n","]\n","results = chain.batch([{\"input\": q} for q in math_questions], return_exceptions=True)"]@@ -239,12 +242,13 @@" error=False,\n"," )\n","}\n",- " \n",+ "\n","llm_runs = [\n",- " run for run in client.list_runs(\n",+ " run\n",+ " for run in client.list_runs(\n"," project_name=project_name,\n"," run_type=\"llm\",\n",- " ) \n",+ " )\n"," if run.trace_id in successful_traces\n","]"]@@ -323,13 +327,10 @@"\n","my_file = BytesIO()\n","for dialog in training_data:\n",- " my_file.write((json.dumps({\"messages\": dialog}) + \"\\n\").encode('utf-8'))\n",+ " my_file.write((json.dumps({\"messages\": dialog}) + \"\\n\").encode(\"utf-8\"))\n","\n","my_file.seek(0)\n",- "training_file = openai.File.create(\n",- " file=my_file,\n",- " purpose='fine-tune'\n",- ")\n",+ "training_file = openai.File.create(file=my_file, purpose=\"fine-tune\")\n","\n","job = openai.FineTuningJob.create(\n"," training_file=training_file.id,\n",diff --git a/docs/docs/integrations/chat_loaders/slack.ipynb b/docs/docs/integrations/chat_loaders/slack.ipynbindex f15a015c87..39035aea3a 100644--- a/docs/docs/integrations/chat_loaders/slack.ipynb+++ b/docs/docs/integrations/chat_loaders/slack.ipynb@@ -96,7 +96,9 @@"# Merge consecutive messages from the same sender into a single message\n","merged_messages = merge_chat_runs(raw_messages)\n","# Convert messages from \"U0500003428\" to AI messages\n",- "messages: List[ChatSession] = list(map_ai_messages(merged_messages, sender=\"U0500003428\"))"+ "messages: List[ChatSession] = list(\n",+ " map_ai_messages(merged_messages, sender=\"U0500003428\")\n",+ ")"]},{@@ -134,7 +136,7 @@"\n","llm = ChatOpenAI()\n","\n",- "for chunk in llm.stream(messages[1]['messages']):\n",+ "for chunk in llm.stream(messages[1][\"messages\"]):\n"," print(chunk.content, end=\"\", flush=True)"]}diff --git a/docs/docs/integrations/chat_loaders/telegram.ipynb b/docs/docs/integrations/chat_loaders/telegram.ipynbindex 4d999d7461..960c42447f 100644--- a/docs/docs/integrations/chat_loaders/telegram.ipynb+++ b/docs/docs/integrations/chat_loaders/telegram.ipynb@@ -113,7 +113,7 @@"outputs": [],"source": ["loader = TelegramChatLoader(\n",- " path=\"./telegram_conversation.json\", \n",+ " path=\"./telegram_conversation.json\",\n",")"]},@@ -145,7 +145,9 @@"# Merge consecutive messages from the same sender into a single message\n","merged_messages = merge_chat_runs(raw_messages)\n","# Convert messages from \"Jiminy Cricket\" to AI messages\n",- "messages: List[ChatSession] = list(map_ai_messages(merged_messages, sender=\"Jiminy Cricket\"))"+ "messages: List[ChatSession] = list(\n",+ " map_ai_messages(merged_messages, sender=\"Jiminy Cricket\")\n",+ ")"]},{@@ -177,7 +179,7 @@"\n","llm = ChatOpenAI()\n","\n",- "for chunk in llm.stream(messages[0]['messages']):\n",+ "for chunk in llm.stream(messages[0][\"messages\"]):\n"," print(chunk.content, end=\"\", flush=True)"]}diff --git a/docs/docs/integrations/chat_loaders/twitter.ipynb b/docs/docs/integrations/chat_loaders/twitter.ipynbindex 1109175120..e8fb47552a 100644--- a/docs/docs/integrations/chat_loaders/twitter.ipynb+++ b/docs/docs/integrations/chat_loaders/twitter.ipynb@@ -31,7 +31,7 @@"metadata": {},"outputs": [],"source": [- "with open('example_data/dataset_twitter-scraper_2023-08-23_22-13-19-740.json') as f:\n",+ "with open(\"example_data/dataset_twitter-scraper_2023-08-23_22-13-19-740.json\") as f:\n"," data = json.load(f)"]},@@ -43,7 +43,7 @@"outputs": [],"source": ["# Filter out tweets that reference other tweets, because it's a bit weird\n",- "tweets = [d[\"full_text\"] for d in data if \"t.co\" not in d['full_text']]\n",+ "tweets = [d[\"full_text\"] for d in data if \"t.co\" not in d[\"full_text\"]]\n","# Create them as AI messages\n","messages = [AIMessage(content=t) for t in tweets]\n","# Add in a system message at the start\n",diff --git a/docs/docs/integrations/chat_loaders/wechat.ipynb b/docs/docs/integrations/chat_loaders/wechat.ipynbindex 8f6e7f2d59..ed4e958283 100644--- a/docs/docs/integrations/chat_loaders/wechat.ipynb+++ b/docs/docs/integrations/chat_loaders/wechat.ipynb@@ -85,7 +85,6 @@"\n","\n","class WeChatChatLoader(chat_loaders.BaseChatLoader):\n",- " \n"," def __init__(self, path: str):\n"," \"\"\"\n"," Initialize the Discord chat loader.\n",@@ -143,15 +142,19 @@" if re.match(self._message_line_regex, line):\n"," if current_sender and current_content:\n"," results = self._append_message_to_results(\n",- " results, current_sender, current_timestamp, current_content)\n",- " current_sender, current_timestamp = re.match(self._message_line_regex, line).groups()\n",+ " results, current_sender, current_timestamp, current_content\n",+ " )\n",+ " current_sender, current_timestamp = re.match(\n",+ " self._message_line_regex, line\n",+ " ).groups()\n"," current_content = []\n"," else:\n"," current_content.append(line.strip())\n","\n"," if current_sender and current_content:\n"," results = self._append_message_to_results(\n",- " results, current_sender, current_timestamp, current_content)\n",+ " results, current_sender, current_timestamp, current_content\n",+ " )\n","\n"," return chat_loaders.ChatSession(messages=results)\n","\n",@@ -162,7 +165,7 @@" Yields:\n"," A `ChatSession` object containing the loaded chat messages.\n"," \"\"\"\n",- " yield self._load_single_chat_session_from_txt(self.path)\n"+ " yield self._load_single_chat_session_from_txt(self.path)"]},{@@ -263,7 +266,7 @@"\n","llm = ChatOpenAI()\n","\n",- "for chunk in llm.stream(messages[0]['messages']):\n",+ "for chunk in llm.stream(messages[0][\"messages\"]):\n"," print(chunk.content, end=\"\", flush=True)"]},diff --git a/docs/docs/integrations/chat_loaders/whatsapp.ipynb b/docs/docs/integrations/chat_loaders/whatsapp.ipynbindex ef4bf06904..2086bf4ddd 100644--- a/docs/docs/integrations/chat_loaders/whatsapp.ipynb+++ b/docs/docs/integrations/chat_loaders/whatsapp.ipynb@@ -85,7 +85,7 @@"outputs": [],"source": ["loader = WhatsAppChatLoader(\n",- " path=\"./whatsapp_chat.txt\", \n",+ " path=\"./whatsapp_chat.txt\",\n",")"]},@@ -135,7 +135,9 @@"# Merge consecutive messages from the same sender into a single message\n","merged_messages = merge_chat_runs(raw_messages)\n","# Convert messages from \"Dr. Feather\" to AI messages\n",- "messages: List[ChatSession] = list(map_ai_messages(merged_messages, sender=\"Dr. Feather\"))"+ "messages: List[ChatSession] = list(\n",+ " map_ai_messages(merged_messages, sender=\"Dr. Feather\")\n",+ ")"]},{@@ -167,7 +169,7 @@"\n","llm = ChatOpenAI()\n","\n",- "for chunk in llm.stream(messages[0]['messages']):\n",+ "for chunk in llm.stream(messages[0][\"messages\"]):\n"," print(chunk.content, end=\"\", flush=True)"]},diff --git a/docs/docs/integrations/document_loaders/airbyte_cdk.ipynb b/docs/docs/integrations/document_loaders/airbyte_cdk.ipynbindex 4bada1de8f..4d0dda9bce 100644--- a/docs/docs/integrations/document_loaders/airbyte_cdk.ipynb+++ b/docs/docs/integrations/document_loaders/airbyte_cdk.ipynb@@ -97,21 +97,19 @@"metadata": {},"outputs": [],"source": [- "\n","from langchain.document_loaders.airbyte import AirbyteCDKLoader\n",- "from source_github.source import SourceGithub # plug in your own source here\n",+ "from source_github.source import SourceGithub # plug in your own source here\n","\n","config = {\n"," # your github configuration\n",- " \"credentials\": {\n",- " \"api_url\": \"api.github.com\",\n",- " \"personal_access_token\": \"<token>\"\n",- " },\n",+ " \"credentials\": {\"api_url\": \"api.github.com\", \"personal_access_token\": \"<token>\"},\n"," \"repository\": \"<repo>\",\n",- " \"start_date\": \"<date from which to start retrieving records from in ISO format, e.g. 2020-10-20T00:00:00Z>\"\n",+ " \"start_date\": \"<date from which to start retrieving records from in ISO format, e.g. 2020-10-20T00:00:00Z>\",\n","}\n","\n",- "issues_loader = AirbyteCDKLoader(source_class=SourceGithub, config=config, stream_name=\"issues\")"+ "issues_loader = AirbyteCDKLoader(\n",+ " source_class=SourceGithub, config=config, stream_name=\"issues\"\n",+ ")"]},{@@ -167,10 +165,20 @@"source": ["from langchain.docstore.document import Document\n","\n",+ "\n","def handle_record(record, id):\n",- " return Document(page_content=record.data[\"title\"] + \"\\n\" + (record.data[\"body\"] or \"\"), metadata=record.data)\n",+ " return Document(\n",+ " page_content=record.data[\"title\"] + \"\\n\" + (record.data[\"body\"] or \"\"),\n",+ " metadata=record.data,\n",+ " )\n",+ "\n","\n",- "issues_loader = AirbyteCDKLoader(source_class=SourceGithub, config=config, stream_name=\"issues\", record_handler=handle_record)\n",+ "issues_loader = AirbyteCDKLoader(\n",+ " source_class=SourceGithub,\n",+ " config=config,\n",+ " stream_name=\"issues\",\n",+ " record_handler=handle_record,\n",+ ")\n","\n","docs = issues_loader.load()"]@@ -194,9 +202,11 @@"metadata": {},"outputs": [],"source": [- "last_state = issues_loader.last_state # store safely\n",+ "last_state = issues_loader.last_state # store safely\n","\n",- "incremental_issue_loader = AirbyteCDKLoader(source_class=SourceGithub, config=config, stream_name=\"issues\", state=last_state)\n",+ "incremental_issue_loader = AirbyteCDKLoader(\n",+ " source_class=SourceGithub, config=config, stream_name=\"issues\", state=last_state\n",+ ")\n","\n","new_docs = incremental_issue_loader.load()"]diff --git a/docs/docs/integrations/document_loaders/airbyte_gong.ipynb b/docs/docs/integrations/document_loaders/airbyte_gong.ipynbindex 01f88c1261..00679a764f 100644--- a/docs/docs/integrations/document_loaders/airbyte_gong.ipynb+++ b/docs/docs/integrations/document_loaders/airbyte_gong.ipynb@@ -85,14 +85,15 @@"metadata": {},"outputs": [],"source": [- "\n","from langchain.document_loaders.airbyte import AirbyteGongLoader\n","\n","config = {\n"," # your gong configuration\n","}\n","\n",- "loader = AirbyteGongLoader(config=config, stream_name=\"calls\") # check the documentation linked above for a list of all streams"+ "loader = AirbyteGongLoader(\n",+ " config=config, stream_name=\"calls\"\n",+ ") # check the documentation linked above for a list of all streams"]},{@@ -148,10 +149,14 @@"source": ["from langchain.docstore.document import Document\n","\n",+ "\n","def handle_record(record, id):\n"," return Document(page_content=record.data[\"title\"], metadata=record.data)\n","\n",- "loader = AirbyteGongLoader(config=config, record_handler=handle_record, stream_name=\"calls\")\n",+ "\n",+ "loader = AirbyteGongLoader(\n",+ " config=config, record_handler=handle_record, stream_name=\"calls\"\n",+ ")\n","docs = loader.load()"]},@@ -174,9 +179,11 @@"metadata": {},"outputs": [],"source": [- "last_state = loader.last_state # store safely\n",+ "last_state = loader.last_state # store safely\n","\n",- "incremental_loader = AirbyteGongLoader(config=config, stream_name=\"calls\", state=last_state)\n",+ "incremental_loader = AirbyteGongLoader(\n",+ " config=config, stream_name=\"calls\", state=last_state\n",+ ")\n","\n","new_docs = incremental_loader.load()"]diff --git a/docs/docs/integrations/document_loaders/airbyte_hubspot.ipynb b/docs/docs/integrations/document_loaders/airbyte_hubspot.ipynbindex 2a95b0d7da..3b5d6c0707 100644--- a/docs/docs/integrations/document_loaders/airbyte_hubspot.ipynb+++ b/docs/docs/integrations/document_loaders/airbyte_hubspot.ipynb@@ -87,14 +87,15 @@"metadata": {},"outputs": [],"source": [- "\n","from langchain.document_loaders.airbyte import AirbyteHubspotLoader\n","\n","config = {\n"," # your hubspot configuration\n","}\n","\n",- "loader = AirbyteHubspotLoader(config=config, stream_name=\"products\") # check the documentation linked above for a list of all streams"+ "loader = AirbyteHubspotLoader(\n",+ " config=config, stream_name=\"products\"\n",+ ") # check the documentation linked above for a list of all streams"]},{@@ -150,10 +151,14 @@"source": ["from langchain.docstore.document import Document\n","\n",+ "\n","def handle_record(record, id):\n"," return Document(page_content=record.data[\"title\"], metadata=record.data)\n","\n",- "loader = AirbyteHubspotLoader(config=config, record_handler=handle_record, stream_name=\"products\")\n",+ "\n",+ "loader = AirbyteHubspotLoader(\n",+ " config=config, record_handler=handle_record, stream_name=\"products\"\n",+ ")\n","docs = loader.load()"]},@@ -176,9 +181,11 @@"metadata": {},"outputs": [],"source": [- "last_state = loader.last_state # store safely\n",+ "last_state = loader.last_state # store safely\n","\n",- "incremental_loader = AirbyteHubspotLoader(config=config, stream_name=\"products\", state=last_state)\n",+ "incremental_loader = AirbyteHubspotLoader(\n",+ " config=config, stream_name=\"products\", state=last_state\n",+ ")\n","\n","new_docs = incremental_loader.load()"]diff --git a/docs/docs/integrations/document_loaders/airbyte_salesforce.ipynb b/docs/docs/integrations/document_loaders/airbyte_salesforce.ipynbindex 409ba529e2..b336995269 100644--- a/docs/docs/integrations/document_loaders/airbyte_salesforce.ipynb+++ b/docs/docs/integrations/document_loaders/airbyte_salesforce.ipynb@@ -92,14 +92,15 @@"metadata": {},"outputs": [],"source": [- "\n","from langchain.document_loaders.airbyte import AirbyteSalesforceLoader\n","\n","config = {\n"," # your salesforce configuration\n","}\n","\n",- "loader = AirbyteSalesforceLoader(config=config, stream_name=\"asset\") # check the documentation linked above for a list of all streams"+ "loader = AirbyteSalesforceLoader(\n",+ " config=config, stream_name=\"asset\"\n",+ ") # check the documentation linked above for a list of all streams"]},{@@ -155,10 +156,14 @@"source": ["from langchain.docstore.document import Document\n","\n",+ "\n","def handle_record(record, id):\n"," return Document(page_content=record.data[\"title\"], metadata=record.data)\n","\n",- "loader = AirbyteSalesforceLoader(config=config, record_handler=handle_record, stream_name=\"asset\")\n",+ "\n",+ "loader = AirbyteSalesforceLoader(\n",+ " config=config, record_handler=handle_record, stream_name=\"asset\"\n",+ ")\n","docs = loader.load()"]},@@ -181,9 +186,11 @@"metadata": {},"outputs": [],"source": [- "last_state = loader.last_state # store safely\n",+ "last_state = loader.last_state # store safely\n","\n",- "incremental_loader = AirbyteSalesforceLoader(config=config, stream_name=\"asset\", state=last_state)\n",+ "incremental_loader = AirbyteSalesforceLoader(\n",+ " config=config, stream_name=\"asset\", state=last_state\n",+ ")\n","\n","new_docs = incremental_loader.load()"]diff --git a/docs/docs/integrations/document_loaders/airbyte_shopify.ipynb b/docs/docs/integrations/document_loaders/airbyte_shopify.ipynbindex 8281fb374f..5298ae7231 100644--- a/docs/docs/integrations/document_loaders/airbyte_shopify.ipynb+++ b/docs/docs/integrations/document_loaders/airbyte_shopify.ipynb@@ -88,14 +88,15 @@"metadata": {},"outputs": [],"source": [- "\n","from langchain.document_loaders.airbyte import AirbyteShopifyLoader\n","\n","config = {\n"," # your shopify configuration\n","}\n","\n",- "loader = AirbyteShopifyLoader(config=config, stream_name=\"orders\") # check the documentation linked above for a list of all streams"+ "loader = AirbyteShopifyLoader(\n",+ " config=config, stream_name=\"orders\"\n",+ ") # check the documentation linked above for a list of all streams"]},{@@ -151,10 +152,14 @@"source": ["from langchain.docstore.document import Document\n","\n",+ "\n","def handle_record(record, id):\n"," return Document(page_content=record.data[\"title\"], metadata=record.data)\n","\n",- "loader = AirbyteShopifyLoader(config=config, record_handler=handle_record, stream_name=\"orders\")\n",+ "\n",+ "loader = AirbyteShopifyLoader(\n",+ " config=config, record_handler=handle_record, stream_name=\"orders\"\n",+ ")\n","docs = loader.load()"]},@@ -177,9 +182,11 @@"metadata": {},"outputs": [],"source": [- "last_state = loader.last_state # store safely\n",+ "last_state = loader.last_state # store safely\n","\n",- "incremental_loader = AirbyteShopifyLoader(config=config, stream_name=\"orders\", state=last_state)\n",+ "incremental_loader = AirbyteShopifyLoader(\n",+ " config=config, stream_name=\"orders\", state=last_state\n",+ ")\n","\n","new_docs = incremental_loader.load()"]diff --git a/docs/docs/integrations/document_loaders/airbyte_stripe.ipynb b/docs/docs/integrations/document_loaders/airbyte_stripe.ipynbindex 9c84557f02..17fde5a1bd 100644--- a/docs/docs/integrations/document_loaders/airbyte_stripe.ipynb+++ b/docs/docs/integrations/document_loaders/airbyte_stripe.ipynb@@ -85,14 +85,15 @@"metadata": {},"outputs": [],"source": [- "\n","from langchain.document_loaders.airbyte import AirbyteStripeLoader\n","\n","config = {\n"," # your stripe configuration\n","}\n","\n",- "loader = AirbyteStripeLoader(config=config, stream_name=\"invoices\") # check the documentation linked above for a list of all streams"+ "loader = AirbyteStripeLoader(\n",+ " config=config, stream_name=\"invoices\"\n",+ ") # check the documentation linked above for a list of all streams"]},{@@ -148,10 +149,14 @@"source": ["from langchain.docstore.document import Document\n","\n",+ "\n","def handle_record(record, id):\n"," return Document(page_content=record.data[\"title\"], metadata=record.data)\n","\n",- "loader = AirbyteStripeLoader(config=config, record_handler=handle_record, stream_name=\"invoices\")\n",+ "\n",+ "loader = AirbyteStripeLoader(\n",+ " config=config, record_handler=handle_record, stream_name=\"invoices\"\n",+ ")\n","docs = loader.load()"]},@@ -174,9 +179,14 @@"metadata": {},"outputs": [],"source": [- "last_state = loader.last_state # store safely\n",+ "last_state = loader.last_state # store safely\n","\n",- "incremental_loader = AirbyteStripeLoader(config=config, record_handler=handle_record, stream_name=\"invoices\", state=last_state)\n",+ "incremental_loader = AirbyteStripeLoader(\n",+ " config=config,\n",+ " record_handler=handle_record,\n",+ " stream_name=\"invoices\",\n",+ " state=last_state,\n",+ ")\n","\n","new_docs = incremental_loader.load()"]diff --git a/docs/docs/integrations/document_loaders/airbyte_typeform.ipynb b/docs/docs/integrations/document_loaders/airbyte_typeform.ipynbindex 8df21fb345..ffc01e9b59 100644--- a/docs/docs/integrations/document_loaders/airbyte_typeform.ipynb+++ b/docs/docs/integrations/document_loaders/airbyte_typeform.ipynb@@ -88,14 +88,15 @@"metadata": {},"outputs": [],"source": [- "\n","from langchain.document_loaders.airbyte import AirbyteTypeformLoader\n","\n","config = {\n"," # your typeform configuration\n","}\n","\n",- "loader = AirbyteTypeformLoader(config=config, stream_name=\"forms\") # check the documentation linked above for a list of all streams"+ "loader = AirbyteTypeformLoader(\n",+ " config=config, stream_name=\"forms\"\n",+ ") # check the documentation linked above for a list of all streams"]},{@@ -151,10 +152,14 @@"source": ["from langchain.docstore.document import Document\n","\n",+ "\n","def handle_record(record, id):\n"," return Document(page_content=record.data[\"title\"], metadata=record.data)\n","\n",- "loader = AirbyteTypeformLoader(config=config, record_handler=handle_record, stream_name=\"forms\")\n",+ "\n",+ "loader = AirbyteTypeformLoader(\n",+ " config=config, record_handler=handle_record, stream_name=\"forms\"\n",+ ")\n","docs = loader.load()"]},@@ -177,9 +182,11 @@"metadata": {},"outputs": [],"source": [- "last_state = loader.last_state # store safely\n",+ "last_state = loader.last_state # store safely\n","\n",- "incremental_loader = AirbyteTypeformLoader(config=config, record_handler=handle_record, stream_name=\"forms\", state=last_state)\n",+ "incremental_loader = AirbyteTypeformLoader(\n",+ " config=config, record_handler=handle_record, stream_name=\"forms\", state=last_state\n",+ ")\n","\n","new_docs = incremental_loader.load()"]diff --git a/docs/docs/integrations/document_loaders/airbyte_zendesk_support.ipynb b/docs/docs/integrations/document_loaders/airbyte_zendesk_support.ipynbindex 9ab141e10e..5c2fd6049a 100644--- a/docs/docs/integrations/document_loaders/airbyte_zendesk_support.ipynb+++ b/docs/docs/integrations/document_loaders/airbyte_zendesk_support.ipynb@@ -89,14 +89,15 @@"metadata": {},"outputs": [],"source": [- "\n","from langchain.document_loaders.airbyte import AirbyteZendeskSupportLoader\n","\n","config = {\n"," # your zendesk-support configuration\n","}\n","\n",- "loader = AirbyteZendeskSupportLoader(config=config, stream_name=\"tickets\") # check the documentation linked above for a list of all streams"+ "loader = AirbyteZendeskSupportLoader(\n",+ " config=config, stream_name=\"tickets\"\n",+ ") # check the documentation linked above for a list of all streams"]},{@@ -152,10 +153,14 @@"source": ["from langchain.docstore.document import Document\n","\n",+ "\n","def handle_record(record, id):\n"," return Document(page_content=record.data[\"title\"], metadata=record.data)\n","\n",- "loader = AirbyteZendeskSupportLoader(config=config, record_handler=handle_record, stream_name=\"tickets\")\n",+ "\n",+ "loader = AirbyteZendeskSupportLoader(\n",+ " config=config, record_handler=handle_record, stream_name=\"tickets\"\n",+ ")\n","docs = loader.load()"]},@@ -178,9 +183,11 @@"metadata": {},"outputs": [],"source": [- "last_state = loader.last_state # store safely\n",+ "last_state = loader.last_state # store safely\n","\n",- "incremental_loader = AirbyteZendeskSupportLoader(config=config, stream_name=\"tickets\", state=last_state)\n",+ "incremental_loader = AirbyteZendeskSupportLoader(\n",+ " config=config, stream_name=\"tickets\", state=last_state\n",+ ")\n","\n","new_docs = incremental_loader.load()"]diff --git a/docs/docs/integrations/document_loaders/arcgis.ipynb b/docs/docs/integrations/document_loaders/arcgis.ipynbindex f6b3a16325..1ebf5f4b78 100644--- a/docs/docs/integrations/document_loaders/arcgis.ipynb+++ b/docs/docs/integrations/document_loaders/arcgis.ipynb@@ -305,7 +305,7 @@}],"source": [- "docs[0].metadata['geometry']"+ "docs[0].metadata[\"geometry\"]"]},{diff --git a/docs/docs/integrations/document_loaders/assemblyai.ipynb b/docs/docs/integrations/document_loaders/assemblyai.ipynbindex 80d60df48b..cb30658ff4 100644--- a/docs/docs/integrations/document_loaders/assemblyai.ipynb+++ b/docs/docs/integrations/document_loaders/assemblyai.ipynb@@ -177,15 +177,11 @@"source": ["import assemblyai as aai\n","\n",- "config = aai.TranscriptionConfig(speaker_labels=True,\n",- " auto_chapters=True,\n",- " entity_detection=True\n",+ "config = aai.TranscriptionConfig(\n",+ " speaker_labels=True, auto_chapters=True, entity_detection=True\n",")\n","\n",- "loader = AssemblyAIAudioTranscriptLoader(\n",- " file_path=\"./your_file.mp3\",\n",- " config=config\n",- ")"+ "loader = AssemblyAIAudioTranscriptLoader(file_path=\"./your_file.mp3\", config=config)"]},{@@ -204,8 +200,7 @@"outputs": [],"source": ["loader = AssemblyAIAudioTranscriptLoader(\n",- " file_path=\"./your_file.mp3\",\n",- " api_key=\"YOUR_KEY\"\n",+ " file_path=\"./your_file.mp3\", api_key=\"YOUR_KEY\"\n",")"]}diff --git a/docs/docs/integrations/document_loaders/async_chromium.ipynb b/docs/docs/integrations/document_loaders/async_chromium.ipynbindex ddb220913c..1b4db6b25d 100644--- a/docs/docs/integrations/document_loaders/async_chromium.ipynb+++ b/docs/docs/integrations/document_loaders/async_chromium.ipynb@@ -46,6 +46,7 @@],"source": ["from langchain.document_loaders import AsyncChromiumLoader\n",+ "\n","urls = [\"https://www.wsj.com\"]\n","loader = AsyncChromiumLoader(urls)\n","docs = loader.load()\n",@@ -71,6 +72,7 @@],"source": ["from langchain.document_transformers import Html2TextTransformer\n",+ "\n","html2text = Html2TextTransformer()\n","docs_transformed = html2text.transform_documents(docs)\n","docs_transformed[0].page_content[0:500]"diff --git a/docs/docs/integrations/document_loaders/aws_s3_directory.ipynb b/docs/docs/integrations/document_loaders/aws_s3_directory.ipynbindex e40a3702c6..5b112dbc48 100644--- a/docs/docs/integrations/document_loaders/aws_s3_directory.ipynb+++ b/docs/docs/integrations/document_loaders/aws_s3_directory.ipynb@@ -1,159 +1,161 @@{- "cells": [- {- "cell_type": "markdown",- "id": "a634365e",- "metadata": {},- "source": [- "# AWS S3 Directory\n",- "\n",- ">[Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-folders.html) is an object storage service\n",- "\n",- ">[AWS S3 Directory](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-folders.html)\n",- "\n",- "This covers how to load document objects from an `AWS S3 Directory` object."- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "49815096",- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "#!pip install boto3"- ]- },- {- "cell_type": "code",- "execution_count": 2,- "id": "2f0cd6a5",- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "from langchain.document_loaders import S3DirectoryLoader"- ]- },- {- "cell_type": "code",- "execution_count": 3,- "id": "321cc7f1",- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "loader = S3DirectoryLoader(\"testing-hwc\")"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "2b11d155",- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "loader.load()"- ]- },- {- "cell_type": "markdown",- "id": "0690c40a",- "metadata": {},- "source": [- "## Specifying a prefix\n",- "You can also specify a prefix for more finegrained control over what files to load."- ]- },- {- "cell_type": "code",- "execution_count": 5,- "id": "72d44781",- "metadata": {},- "outputs": [],- "source": [- "loader = S3DirectoryLoader(\"testing-hwc\", prefix=\"fake\")"- ]- },+ "cells": [+ {+ "cell_type": "markdown",+ "id": "a634365e",+ "metadata": {},+ "source": [+ "# AWS S3 Directory\n",+ "\n",+ ">[Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-folders.html) is an object storage service\n",+ "\n",+ ">[AWS S3 Directory](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-folders.html)\n",+ "\n",+ "This covers how to load document objects from an `AWS S3 Directory` object."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "49815096",+ "metadata": {+ "tags": []+ },+ "outputs": [],+ "source": [+ "#!pip install boto3"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 2,+ "id": "2f0cd6a5",+ "metadata": {+ "tags": []+ },+ "outputs": [],+ "source": [+ "from langchain.document_loaders import S3DirectoryLoader"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 3,+ "id": "321cc7f1",+ "metadata": {+ "tags": []+ },+ "outputs": [],+ "source": [+ "loader = S3DirectoryLoader(\"testing-hwc\")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "2b11d155",+ "metadata": {+ "tags": []+ },+ "outputs": [],+ "source": [+ "loader.load()"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "0690c40a",+ "metadata": {},+ "source": [+ "## Specifying a prefix\n",+ "You can also specify a prefix for more finegrained control over what files to load."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 5,+ "id": "72d44781",+ "metadata": {},+ "outputs": [],+ "source": [+ "loader = S3DirectoryLoader(\"testing-hwc\", prefix=\"fake\")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 6,+ "id": "2d3c32db",+ "metadata": {},+ "outputs": [{- "cell_type": "code",- "execution_count": 6,- "id": "2d3c32db",- "metadata": {},- "outputs": [- {- "data": {- "text/plain": [- "[Document(page_content='Lorem ipsum dolor sit amet.', lookup_str='', metadata={'source': 's3://testing-hwc/fake.docx'}, lookup_index=0)]"- ]- },- "execution_count": 6,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "loader.load()"+ "data": {+ "text/plain": [+ "[Document(page_content='Lorem ipsum dolor sit amet.', lookup_str='', metadata={'source': 's3://testing-hwc/fake.docx'}, lookup_index=0)]"]- },- {- "cell_type": "markdown",- "source": [- "## Configuring the AWS Boto3 client\n",- "You can configure the AWS [Boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) client by passing\n",- "named arguments when creating the S3DirectoryLoader.\n",- "This is useful for instance when AWS credentials can't be set as environment variables.\n",- "See the [list of parameters](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html#boto3.session.Session) that can be configured."- ],- "metadata": {},- "id": "91a7ac07"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "loader = S3DirectoryLoader(\"testing-hwc\", aws_access_key_id=\"xxxx\", aws_secret_access_key=\"yyyy\")"- ],- "metadata": {},- "id": "f485ec8c"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "loader.load()"- ],- "metadata": {},- "id": "c0fa76ae"- }- ],- "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"+ },+ "execution_count": 6,+ "metadata": {},+ "output_type": "execute_result"}+ ],+ "source": [+ "loader.load()"+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Configuring the AWS Boto3 client\n",+ "You can configure the AWS [Boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) client by passing\n",+ "named arguments when creating the S3DirectoryLoader.\n",+ "This is useful for instance when AWS credentials can't be set as environment variables.\n",+ "See the [list of parameters](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html#boto3.session.Session) that can be configured."+ ],+ "metadata": {},+ "id": "91a7ac07"+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "loader = S3DirectoryLoader(\n",+ " \"testing-hwc\", aws_access_key_id=\"xxxx\", aws_secret_access_key=\"yyyy\"\n",+ ")"+ ],+ "metadata": {},+ "id": "f485ec8c"+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "loader.load()"+ ],+ "metadata": {},+ "id": "c0fa76ae"+ }+ ],+ "metadata": {+ "kernelspec": {+ "display_name": "Python 3 (ipykernel)",+ "language": "python",+ "name": "python3"},- "nbformat": 4,- "nbformat_minor": 5+ "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}\ No newline at end of filediff --git a/docs/docs/integrations/document_loaders/aws_s3_file.ipynb b/docs/docs/integrations/document_loaders/aws_s3_file.ipynbindex a13fcf5cff..66dfad695d 100644--- a/docs/docs/integrations/document_loaders/aws_s3_file.ipynb+++ b/docs/docs/integrations/document_loaders/aws_s3_file.ipynb@@ -1,122 +1,124 @@{- "cells": [- {- "cell_type": "markdown",- "id": "66a7777e",- "metadata": {},- "source": [- "# AWS S3 File\n",- "\n",- ">[Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-folders.html) is an object storage service.\n",- "\n",- ">[AWS S3 Buckets](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingBucket.html)\n",- "\n",- "This covers how to load document objects from an `AWS S3 File` object."- ]- },- {- "cell_type": "code",- "execution_count": 1,- "id": "9ec8a3b3",- "metadata": {},- "outputs": [],- "source": [- "from langchain.document_loaders import S3FileLoader"- ]- },- {- "cell_type": "code",- "execution_count": 2,- "id": "43128d8d",- "metadata": {},- "outputs": [],- "source": [- "#!pip install boto3"- ]- },- {- "cell_type": "code",- "execution_count": 8,- "id": "35d6809a",- "metadata": {},- "outputs": [],- "source": [- "loader = S3FileLoader(\"testing-hwc\", \"fake.docx\")"- ]- },- {- "cell_type": "code",- "execution_count": 9,- "id": "efd6be84",- "metadata": {},- "outputs": [- {- "data": {- "text/plain": [- "[Document(page_content='Lorem ipsum dolor sit amet.', lookup_str='', metadata={'source': 's3://testing-hwc/fake.docx'}, lookup_index=0)]"- ]- },- "execution_count": 9,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "loader.load()"- ]- },+ "cells": [+ {+ "cell_type": "markdown",+ "id": "66a7777e",+ "metadata": {},+ "source": [+ "# AWS S3 File\n",+ "\n",+ ">[Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-folders.html) is an object storage service.\n",+ "\n",+ ">[AWS S3 Buckets](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingBucket.html)\n",+ "\n",+ "This covers how to load document objects from an `AWS S3 File` object."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 1,+ "id": "9ec8a3b3",+ "metadata": {},+ "outputs": [],+ "source": [+ "from langchain.document_loaders import S3FileLoader"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 2,+ "id": "43128d8d",+ "metadata": {},+ "outputs": [],+ "source": [+ "#!pip install boto3"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 8,+ "id": "35d6809a",+ "metadata": {},+ "outputs": [],+ "source": [+ "loader = S3FileLoader(\"testing-hwc\", \"fake.docx\")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 9,+ "id": "efd6be84",+ "metadata": {},+ "outputs": [{- "cell_type": "markdown",- "id": "93689594",- "metadata": {},- "source": [- "## Configuring the AWS Boto3 client\n",- "You can configure the AWS [Boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) client by passing\n",- "named arguments when creating the S3DirectoryLoader.\n",- "This is useful for instance when AWS credentials can't be set as environment variables.\n",- "See the [list of parameters](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html#boto3.session.Session) that can be configured."+ "data": {+ "text/plain": [+ "[Document(page_content='Lorem ipsum dolor sit amet.', lookup_str='', metadata={'source': 's3://testing-hwc/fake.docx'}, lookup_index=0)]"]- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "loader = S3FileLoader(\"testing-hwc\", \"fake.docx\", aws_access_key_id=\"xxxx\", aws_secret_access_key=\"yyyy\")"- ],- "metadata": {},- "id": "43106ee8"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "loader.load()"- ],- "metadata": {},- "id": "1764a727"- }- ],- "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"+ },+ "execution_count": 9,+ "metadata": {},+ "output_type": "execute_result"}+ ],+ "source": [+ "loader.load()"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "93689594",+ "metadata": {},+ "source": [+ "## Configuring the AWS Boto3 client\n",+ "You can configure the AWS [Boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) client by passing\n",+ "named arguments when creating the S3DirectoryLoader.\n",+ "This is useful for instance when AWS credentials can't be set as environment variables.\n",+ "See the [list of parameters](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html#boto3.session.Session) that can be configured."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "loader = S3FileLoader(\n",+ " \"testing-hwc\", \"fake.docx\", aws_access_key_id=\"xxxx\", aws_secret_access_key=\"yyyy\"\n",+ ")"+ ],+ "metadata": {},+ "id": "43106ee8"+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "loader.load()"+ ],+ "metadata": {},+ "id": "1764a727"+ }+ ],+ "metadata": {+ "kernelspec": {+ "display_name": "Python 3 (ipykernel)",+ "language": "python",+ "name": "python3"},- "nbformat": 4,- "nbformat_minor": 5+ "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}\ No newline at end of filediff --git a/docs/docs/integrations/document_loaders/azure_document_intelligence.ipynb b/docs/docs/integrations/document_loaders/azure_document_intelligence.ipynbindex b28acaebe0..390db4b5ab 100644--- a/docs/docs/integrations/document_loaders/azure_document_intelligence.ipynb+++ b/docs/docs/integrations/document_loaders/azure_document_intelligence.ipynb@@ -61,8 +61,8 @@"from azure.core.credentials import AzureKeyCredential\n","\n","document_analysis_client = DocumentAnalysisClient(\n",- " endpoint=\"<service_endpoint>\", credential=AzureKeyCredential(\"<service_key>\")\n",- " )"+ " endpoint=\"<service_endpoint>\", credential=AzureKeyCredential(\"<service_key>\")\n",+ ")"]},{@@ -80,10 +80,10 @@"outputs": [],"source": ["from langchain.document_loaders.pdf import DocumentIntelligenceLoader\n",+ "\n","loader = DocumentIntelligenceLoader(\n",- " \"<Local_filename>\",\n",- " client=document_analysis_client,\n",- " model=\"<model_name>\") # e.g. prebuilt-document\n",+ " \"<Local_filename>\", client=document_analysis_client, model=\"<model_name>\"\n",+ ") # e.g. prebuilt-document\n","\n","documents = loader.load()"]diff --git a/docs/docs/integrations/document_loaders/concurrent.ipynb b/docs/docs/integrations/document_loaders/concurrent.ipynbindex 197f0457fa..a7c5dc627b 100644--- a/docs/docs/integrations/document_loaders/concurrent.ipynb+++ b/docs/docs/integrations/document_loaders/concurrent.ipynb@@ -27,7 +27,7 @@"metadata": {},"outputs": [],"source": [- "loader = ConcurrentLoader.from_filesystem('example_data/', glob=\"**/*.txt\")"+ "loader = ConcurrentLoader.from_filesystem(\"example_data/\", glob=\"**/*.txt\")"]},{diff --git a/docs/docs/integrations/document_loaders/cube_semantic.ipynb b/docs/docs/integrations/document_loaders/cube_semantic.ipynbindex 68b1702d93..ace54a1364 100644--- a/docs/docs/integrations/document_loaders/cube_semantic.ipynb+++ b/docs/docs/integrations/document_loaders/cube_semantic.ipynb@@ -117,27 +117,27 @@"outputs": [],"source": ["# Given string containing page content\n",- "page_content = 'Users View City, None'\n",+ "page_content = \"Users View City, None\"\n","\n","# Given dictionary containing metadata\n","metadata = {\n",- " 'table_name': 'users_view',\n",- " 'column_name': 'users_view.city',\n",- " 'column_data_type': 'string',\n",- " 'column_title': 'Users View City',\n",- " 'column_description': 'None',\n",- " 'column_member_type': 'dimension',\n",- " 'column_values': [\n",- " 'Austin',\n",- " 'Chicago',\n",- " 'Los Angeles',\n",- " 'Mountain View',\n",- " 'New York',\n",- " 'Palo Alto',\n",- " 'San Francisco',\n",- " 'Seattle'\n",+ " \"table_name\": \"users_view\",\n",+ " \"column_name\": \"users_view.city\",\n",+ " \"column_data_type\": \"string\",\n",+ " \"column_title\": \"Users View City\",\n",+ " \"column_description\": \"None\",\n",+ " \"column_member_type\": \"dimension\",\n",+ " \"column_values\": [\n",+ " \"Austin\",\n",+ " \"Chicago\",\n",+ " \"Los Angeles\",\n",+ " \"Mountain View\",\n",+ " \"New York\",\n",+ " \"Palo Alto\",\n",+ " \"San Francisco\",\n",+ " \"Seattle\",\n"," ],\n",- " 'cube_data_obj_type': 'view'\n",+ " \"cube_data_obj_type\": \"view\",\n","}"]}diff --git a/docs/docs/integrations/document_loaders/dropbox.ipynb b/docs/docs/integrations/document_loaders/dropbox.ipynbindex 7533caaa1e..5c946f5eb7 100644--- a/docs/docs/integrations/document_loaders/dropbox.ipynb+++ b/docs/docs/integrations/document_loaders/dropbox.ipynb@@ -80,7 +80,7 @@"loader = DropboxLoader(\n"," dropbox_access_token=dropbox_access_token,\n"," dropbox_folder_path=dropbox_folder_path,\n",- " recursive=False\n",+ " recursive=False,\n",")"]},diff --git a/docs/docs/integrations/document_loaders/google_cloud_storage_file.ipynb b/docs/docs/integrations/document_loaders/google_cloud_storage_file.ipynbindex cc3c4b357b..3a87256cc8 100644--- a/docs/docs/integrations/document_loaders/google_cloud_storage_file.ipynb+++ b/docs/docs/integrations/document_loaders/google_cloud_storage_file.ipynb@@ -89,10 +89,15 @@"outputs": [],"source": ["from langchain.document_loaders import PyPDFLoader\n",+ "\n",+ "\n","def load_pdf(file_path):\n"," return PyPDFLoader(file_path)\n","\n",- "loader = GCSFileLoader(project_name=\"aist\", bucket=\"testing-hwc\", blob=\"fake.pdf\", loader_func=load_pdf)"+ "\n",+ "loader = GCSFileLoader(\n",+ " project_name=\"aist\", bucket=\"testing-hwc\", blob=\"fake.pdf\", loader_func=load_pdf\n",+ ")"]}],diff --git a/docs/docs/integrations/document_loaders/google_drive.ipynb b/docs/docs/integrations/document_loaders/google_drive.ipynbindex 6909301d64..2a984f5922 100644--- a/docs/docs/integrations/document_loaders/google_drive.ipynb+++ b/docs/docs/integrations/document_loaders/google_drive.ipynb@@ -97,7 +97,7 @@"loader = GoogleDriveLoader(\n"," folder_id=\"1yucgL9WGgWZdM1TOuKkeghlPizuzMYb5\",\n"," file_types=[\"document\", \"sheet\"],\n",- " recursive=False\n",+ " recursive=False,\n",")"]},@@ -238,8 +238,8 @@"metadata": {},"outputs": [],"source": [- "folder_id='root'\n",- "#folder_id='1yucgL9WGgWZdM1TOuKkeghlPizuzMYb5'"+ "folder_id = \"root\"\n",+ "# folder_id='1yucgL9WGgWZdM1TOuKkeghlPizuzMYb5'"]},{@@ -314,7 +314,7 @@"source": ["for doc in loader.load():\n"," print(\"---\")\n",- " print(doc.page_content.strip()[:60]+\"...\")"+ " print(doc.page_content.strip()[:60] + \"...\")"]},{@@ -356,12 +356,12 @@" recursive=False,\n"," template=\"gdrive-query\", # Default template to use\n"," query=\"machine learning\",\n",- " num_results=2, # Maximum number of file to load\n",+ " num_results=2, # Maximum number of file to load\n"," supportsAllDrives=False, # GDrive `list()` parameter\n",")\n","for doc in loader.load():\n"," print(\"---\")\n",- " print(doc.page_content.strip()[:60]+\"...\")"+ " print(doc.page_content.strip()[:60] + \"...\")"]},{@@ -380,20 +380,21 @@"outputs": [],"source": ["from langchain.prompts.prompt import PromptTemplate\n",+ "\n","loader = GoogleDriveLoader(\n"," folder_id=folder_id,\n"," recursive=False,\n"," template=PromptTemplate(\n"," input_variables=[\"query\", \"query_name\"],\n"," template=\"fullText contains '{query}' and name contains '{query_name}' and trashed=false\",\n",- " ), # Default template to use\n",+ " ), # Default template to use\n"," query=\"machine learning\",\n",- " query_name=\"ML\", \n",+ " query_name=\"ML\",\n"," num_results=2, # Maximum number of file to load\n",")\n","for doc in loader.load():\n"," print(\"---\")\n",- " print(doc.page_content.strip()[:60]+\"...\")"+ " print(doc.page_content.strip()[:60] + \"...\")"]},{@@ -430,13 +431,13 @@"source": ["loader = GoogleDriveLoader(\n"," template=\"gdrive-mime-type\",\n",- " mime_type=\"application/vnd.google-apps.presentation\", # Only GSlide files\n",+ " mime_type=\"application/vnd.google-apps.presentation\", # Only GSlide files\n"," gslide_mode=\"slide\",\n"," num_results=2, # Maximum number of file to load\n",")\n","for doc in loader.load():\n"," print(\"---\")\n",- " print(doc.page_content.strip()[:60]+\"...\")"+ " print(doc.page_content.strip()[:60] + \"...\")"]},{@@ -458,13 +459,13 @@"source": ["loader = GoogleDriveLoader(\n"," template=\"gdrive-mime-type\",\n",- " mime_type=\"application/vnd.google-apps.spreadsheet\", # Only GSheet files\n",+ " mime_type=\"application/vnd.google-apps.spreadsheet\", # Only GSheet files\n"," gsheet_mode=\"elements\",\n"," num_results=2, # Maximum number of file to load\n",")\n","for doc in loader.load():\n"," print(\"---\")\n",- " print(doc.page_content.strip()[:60]+\"...\")"+ " print(doc.page_content.strip()[:60] + \"...\")"]},{@@ -490,17 +491,18 @@"outputs": [],"source": ["import os\n",+ "\n","loader = GoogleDriveLoader(\n",- " gdrive_api_file=os.environ[\"GOOGLE_ACCOUNT_FILE\"],\n",- " num_results=2,\n",- " template=\"gdrive-query\",\n",- " filter=lambda search, file: \"#test\" not in file.get('description',''),\n",- " query='machine learning',\n",- " supportsAllDrives=False,\n",- " )\n",+ " gdrive_api_file=os.environ[\"GOOGLE_ACCOUNT_FILE\"],\n",+ " num_results=2,\n",+ " template=\"gdrive-query\",\n",+ " filter=lambda search, file: \"#test\" not in file.get(\"description\", \"\"),\n",+ " query=\"machine learning\",\n",+ " supportsAllDrives=False,\n",+ ")\n","for doc in loader.load():\n"," print(\"---\")\n",- " print(doc.page_content.strip()[:60]+\"...\")"+ " print(doc.page_content.strip()[:60] + \"...\")"]},{diff --git a/docs/docs/integrations/document_loaders/google_speech_to_text.ipynb b/docs/docs/integrations/document_loaders/google_speech_to_text.ipynbindex b66db9bbf6..34e36ed51d 100644--- a/docs/docs/integrations/document_loaders/google_speech_to_text.ipynb+++ b/docs/docs/integrations/document_loaders/google_speech_to_text.ipynb@@ -32,7 +32,7 @@"metadata": {},"outputs": [],"source": [- "%pip install google-cloud-speech\n"+ "%pip install google-cloud-speech"]},{@@ -60,7 +60,7 @@"\n","loader = GoogleSpeechToTextLoader(project_id=project_id, file_path=file_path)\n","\n",- "docs = loader.load()\n"+ "docs = loader.load()"]},{@@ -83,7 +83,7 @@"metadata": {},"outputs": [],"source": [- "docs[0].page_content\n"+ "docs[0].page_content"]},{@@ -108,7 +108,7 @@"metadata": {},"outputs": [],"source": [- "docs[0].metadata\n"+ "docs[0].metadata"]},{@@ -147,7 +147,11 @@"metadata": {},"outputs": [],"source": [- "from google.cloud.speech_v2 import AutoDetectDecodingConfig, RecognitionConfig, RecognitionFeatures\n",+ "from google.cloud.speech_v2 import (\n",+ " AutoDetectDecodingConfig,\n",+ " RecognitionConfig,\n",+ " RecognitionFeatures,\n",+ ")\n","from langchain.document_loaders import GoogleSpeechToTextLoader\n","\n","project_id = \"<PROJECT_ID>\"\n",@@ -156,24 +160,24 @@"file_path = \"./audio.wav\"\n","\n","config = RecognitionConfig(\n",- " auto_decoding_config=AutoDetectDecodingConfig(),\n",- " language_codes=[\"en-US\"],\n",- " model=\"long\",\n",- " features=RecognitionFeatures(\n",- " enable_automatic_punctuation=False,\n",- " profanity_filter=True,\n",- " enable_spoken_punctuation=True,\n",- " enable_spoken_emojis=True\n",- " ),\n",- " )\n",+ " auto_decoding_config=AutoDetectDecodingConfig(),\n",+ " language_codes=[\"en-US\"],\n",+ " model=\"long\",\n",+ " features=RecognitionFeatures(\n",+ " enable_automatic_punctuation=False,\n",+ " profanity_filter=True,\n",+ " enable_spoken_punctuation=True,\n",+ " enable_spoken_emojis=True,\n",+ " ),\n",+ ")\n","\n","loader = GoogleSpeechToTextLoader(\n"," project_id=project_id,\n"," location=location,\n"," recognizer_id=recognizer_id,\n"," file_path=file_path,\n",- " config=config\n",- ")\n"+ " config=config,\n",+ ")"]}],diff --git a/docs/docs/integrations/document_loaders/huawei_obs_directory.ipynb b/docs/docs/integrations/document_loaders/huawei_obs_directory.ipynbindex e2cbeef268..b6cf8c544b 100644--- a/docs/docs/integrations/document_loaders/huawei_obs_directory.ipynb+++ b/docs/docs/integrations/document_loaders/huawei_obs_directory.ipynb@@ -48,10 +48,7 @@"outputs": [],"source": ["# Configure your access credentials\\n\n",- "config = {\n",- " \"ak\": \"your-access-key\",\n",- " \"sk\": \"your-secret-key\"\n",- "}\n",+ "config = {\"ak\": \"your-access-key\", \"sk\": \"your-secret-key\"}\n","loader = OBSDirectoryLoader(\"your-bucket-name\", endpoint=endpoint, config=config)"]},@@ -81,7 +78,9 @@"metadata": {},"outputs": [],"source": [- "loader = OBSDirectoryLoader(\"your-bucket-name\", endpoint=endpoint, config=config, prefix=\"test_prefix\")"+ "loader = OBSDirectoryLoader(\n",+ " \"your-bucket-name\", endpoint=endpoint, config=config, prefix=\"test_prefix\"\n",+ ")"]},{diff --git a/docs/docs/integrations/document_loaders/huawei_obs_file.ipynb b/docs/docs/integrations/document_loaders/huawei_obs_file.ipynbindex 5617f673cd..bed63582e6 100644--- a/docs/docs/integrations/document_loaders/huawei_obs_file.ipynb+++ b/docs/docs/integrations/document_loaders/huawei_obs_file.ipynb@@ -48,7 +48,12 @@"outputs": [],"source": ["from obs import ObsClient\n",- "obs_client = ObsClient(access_key_id=\"your-access-key\", secret_access_key=\"your-secret-key\", server=endpoint)\n",+ "\n",+ "obs_client = ObsClient(\n",+ " access_key_id=\"your-access-key\",\n",+ " secret_access_key=\"your-secret-key\",\n",+ " server=endpoint,\n",+ ")\n","loader = OBSFileLoader(\"your-bucket-name\", \"your-object-key\", client=obs_client)"]},@@ -79,11 +84,10 @@"outputs": [],"source": ["# Configure your access credentials\\n\n",- "config = {\n",- " \"ak\": \"your-access-key\",\n",- " \"sk\": \"your-secret-key\"\n",- "}\n",- "loader = OBSFileLoader(\"your-bucket-name\", \"your-object-key\",endpoint=endpoint, config=config)"+ "config = {\"ak\": \"your-access-key\", \"sk\": \"your-secret-key\"}\n",+ "loader = OBSFileLoader(\n",+ " \"your-bucket-name\", \"your-object-key\", endpoint=endpoint, config=config\n",+ ")"]},{@@ -113,7 +117,9 @@"outputs": [],"source": ["config = {\"get_token_from_ecs\": True}\n",- "loader = OBSFileLoader(\"your-bucket-name\", \"your-object-key\", endpoint=endpoint, config=config)"+ "loader = OBSFileLoader(\n",+ " \"your-bucket-name\", \"your-object-key\", endpoint=endpoint, config=config\n",+ ")"]},{diff --git a/docs/docs/integrations/document_loaders/mediawikidump.ipynb b/docs/docs/integrations/document_loaders/mediawikidump.ipynbindex db13a4e811..917bac95df 100644--- a/docs/docs/integrations/document_loaders/mediawikidump.ipynb+++ b/docs/docs/integrations/document_loaders/mediawikidump.ipynb@@ -58,12 +58,12 @@],"source": ["loader = MWDumpLoader(\n",- " file_path = \"example_data/testmw_pages_current.xml\", \n",+ " file_path=\"example_data/testmw_pages_current.xml\",\n"," encoding=\"utf8\",\n",- " #namespaces = [0,2,3] Optional list to load only specific namespaces. Loads all namespaces by default.\n",- " skip_redirects = True, #will skip over pages that just redirect to other pages (or not if False)\n",- " stop_on_error = False #will skip over pages that cause parsing errors (or not if False)\n",- " )\n",+ " # namespaces = [0,2,3] Optional list to load only specific namespaces. Loads all namespaces by default.\n",+ " skip_redirects=True, # will skip over pages that just redirect to other pages (or not if False)\n",+ " stop_on_error=False, # will skip over pages that cause parsing errors (or not if False)\n",+ ")\n","documents = loader.load()\n","print(f\"You have {len(documents)} document(s) in your data \")"]diff --git a/docs/docs/integrations/document_loaders/mongodb.ipynb b/docs/docs/integrations/document_loaders/mongodb.ipynbindex 6e48620049..2a167dcd33 100644--- a/docs/docs/integrations/document_loaders/mongodb.ipynb+++ b/docs/docs/integrations/document_loaders/mongodb.ipynb@@ -65,6 +65,7 @@"source": ["# add this import for running in jupyter notebook\n","import nest_asyncio\n",+ "\n","nest_asyncio.apply()"]},@@ -83,11 +84,12 @@"metadata": {},"outputs": [],"source": [- "loader = MongodbLoader(connection_string=\"mongodb://localhost:27017/\",\n",- " db_name=\"sample_restaurants\", \n",- " collection_name=\"restaurants\",\n",- " filter_criteria={\"borough\": \"Bronx\", \"cuisine\": \"Bakery\" },\n",- " ) "+ "loader = MongodbLoader(\n",+ " connection_string=\"mongodb://localhost:27017/\",\n",+ " db_name=\"sample_restaurants\",\n",+ " collection_name=\"restaurants\",\n",+ " filter_criteria={\"borough\": \"Bronx\", \"cuisine\": \"Bakery\"},\n",+ ")"]},{diff --git a/docs/docs/integrations/document_loaders/news.ipynb b/docs/docs/integrations/document_loaders/news.ipynbindex 737e3cac4e..bc645de393 100644--- a/docs/docs/integrations/document_loaders/news.ipynb+++ b/docs/docs/integrations/document_loaders/news.ipynb@@ -131,7 +131,7 @@}],"source": [- "data[0].metadata['keywords']"+ "data[0].metadata[\"keywords\"]"],"metadata": {"collapsed": false,@@ -156,7 +156,7 @@}],"source": [- "data[0].metadata['summary']"+ "data[0].metadata[\"summary\"]"],"metadata": {"collapsed": false,diff --git a/docs/docs/integrations/document_loaders/pdf-amazonTextractPDFLoader.ipynb b/docs/docs/integrations/document_loaders/pdf-amazonTextractPDFLoader.ipynbindex b9e87d60cc..3cbaa76c76 100644--- a/docs/docs/integrations/document_loaders/pdf-amazonTextractPDFLoader.ipynb+++ b/docs/docs/integrations/document_loaders/pdf-amazonTextractPDFLoader.ipynb@@ -61,6 +61,7 @@"outputs": [],"source": ["from langchain.document_loaders import AmazonTextractPDFLoader\n",+ "\n","loader = AmazonTextractPDFLoader(\"example_data/alejandro_rosalez_sample-small.jpeg\")\n","documents = loader.load()"]@@ -116,7 +117,10 @@"outputs": [],"source": ["from langchain.document_loaders import AmazonTextractPDFLoader\n",- "loader = AmazonTextractPDFLoader(\"https://amazon-textract-public-content.s3.us-east-2.amazonaws.com/langchain/alejandro_rosalez_sample_1.jpg\")\n",+ "\n",+ "loader = AmazonTextractPDFLoader(\n",+ " \"https://amazon-textract-public-content.s3.us-east-2.amazonaws.com/langchain/alejandro_rosalez_sample_1.jpg\"\n",+ ")\n","documents = loader.load()"]},@@ -163,7 +167,8 @@"outputs": [],"source": ["import boto3\n",- "textract_client = boto3.client('textract', region_name='us-east-2')\n",+ "\n",+ "textract_client = boto3.client(\"textract\", region_name=\"us-east-2\")\n","\n","file_path = \"s3://amazon-textract-public-content/langchain/layout-parser-paper.pdf\"\n","loader = AmazonTextractPDFLoader(file_path, client=textract_client)\n",@@ -220,7 +225,7 @@"outputs": [],"source": ["# You can store your OPENAI_API_KEY in a .env file as well\n",- "# import os \n",+ "# import os\n","# from dotenv import load_dotenv\n","\n","# load_dotenv()"@@ -236,7 +241,8 @@"outputs": [],"source": ["# Or set the OpenAI key in the environment directly\n",- "import os \n",+ "import os\n",+ "\n","os.environ[\"OPENAI_API_KEY\"] = \"your-OpenAI-API-key\""]},diff --git a/docs/docs/integrations/document_loaders/recursive_url.ipynb b/docs/docs/integrations/document_loaders/recursive_url.ipynbindex f8ac5f523e..59236302da 100644--- a/docs/docs/integrations/document_loaders/recursive_url.ipynb+++ b/docs/docs/integrations/document_loaders/recursive_url.ipynb@@ -65,7 +65,9 @@"from bs4 import BeautifulSoup as Soup\n","\n","url = \"https://docs.python.org/3.9/\"\n",- "loader = RecursiveUrlLoader(url=url, max_depth=2, extractor=lambda x: Soup(x, \"html.parser\").text)\n",+ "loader = RecursiveUrlLoader(\n",+ " url=url, max_depth=2, extractor=lambda x: Soup(x, \"html.parser\").text\n",+ ")\n","docs = loader.load()"]},diff --git a/docs/docs/integrations/document_loaders/rspace.ipynb b/docs/docs/integrations/document_loaders/rspace.ipynbindex 6f8dc48ecf..4f2009ae46 100644--- a/docs/docs/integrations/document_loaders/rspace.ipynb+++ b/docs/docs/integrations/document_loaders/rspace.ipynb@@ -71,7 +71,7 @@"outputs": [],"source": ["## replace these ids with some from your own research notes.\n",- "## Make sure to use global ids (with the 2 character prefix). This helps the loader know which API calls to make \n",+ "## Make sure to use global ids (with the 2 character prefix). This helps the loader know which API calls to make\n","## to RSpace API.\n","\n","rspace_ids = [\"NB1932027\", \"FL1921314\", \"SD1932029\", \"GL1932384\"]\n",@@ -80,7 +80,7 @@" docs = loader.load()\n"," for doc in docs:\n"," ## the name and ID are added to the 'source' metadata property.\n",- " print (doc.metadata)\n",+ " print(doc.metadata)\n"," print(doc.page_content[:500])"]},@@ -99,7 +99,9 @@"metadata": {},"outputs": [],"source": [- "loader = RSpaceLoader(global_id=rs_id, api_key=\"MY_API_KEY\", url=\"https://my.researchspace.com\")"+ "loader = RSpaceLoader(\n",+ " global_id=rs_id, api_key=\"MY_API_KEY\", url=\"https://my.researchspace.com\"\n",+ ")"]}],diff --git a/docs/docs/integrations/document_loaders/rss.ipynb b/docs/docs/integrations/document_loaders/rss.ipynbindex ebb60277b8..3b6744f0ee 100644--- a/docs/docs/integrations/document_loaders/rss.ipynb+++ b/docs/docs/integrations/document_loaders/rss.ipynb@@ -182,7 +182,7 @@}],"source": [- "data[0].metadata['keywords']"+ "data[0].metadata[\"keywords\"]"]},{@@ -208,7 +208,7 @@}],"source": [- "data[0].metadata['summary']"+ "data[0].metadata[\"summary\"]"]},{diff --git a/docs/docs/integrations/document_loaders/tensorflow_datasets.ipynb b/docs/docs/integrations/document_loaders/tensorflow_datasets.ipynbindex 39de886752..5f178c6ceb 100644--- a/docs/docs/integrations/document_loaders/tensorflow_datasets.ipynb+++ b/docs/docs/integrations/document_loaders/tensorflow_datasets.ipynb@@ -81,16 +81,20 @@"source": ["# Feature structure of `mlqa/en` dataset:\n","\n",- "FeaturesDict({\n",- " 'answers': Sequence({\n",- " 'answer_start': int32,\n",- " 'text': Text(shape=(), dtype=string),\n",- " }),\n",- " 'context': Text(shape=(), dtype=string),\n",- " 'id': string,\n",- " 'question': Text(shape=(), dtype=string),\n",- " 'title': Text(shape=(), dtype=string),\n",- "})"+ "FeaturesDict(\n",+ " {\n",+ " \"answers\": Sequence(\n",+ " {\n",+ " \"answer_start\": int32,\n",+ " \"text\": Text(shape=(), dtype=string),\n",+ " }\n",+ " ),\n",+ " \"context\": Text(shape=(), dtype=string),\n",+ " \"id\": string,\n",+ " \"question\": Text(shape=(), dtype=string),\n",+ " \"title\": Text(shape=(), dtype=string),\n",+ " }\n",+ ")"]},{@@ -123,7 +127,7 @@],"source": ["# try directly access this dataset:\n",- "ds = tfds.load('mlqa/en', split='test')\n",+ "ds = tfds.load(\"mlqa/en\", split=\"test\")\n","ds = ds.take(1) # Only take a single example\n","ds"]@@ -163,7 +167,8 @@],"source": ["def decode_to_str(item: tf.Tensor) -> str:\n",- " return item.numpy().decode('utf-8')\n",+ " return item.numpy().decode(\"utf-8\")\n",+ "\n","\n","def mlqaen_example_to_document(example: dict) -> Document:\n"," return Document(\n",@@ -175,9 +180,9 @@" \"answer\": decode_to_str(example[\"answers\"][\"text\"][0]),\n"," },\n"," )\n",- " \n",- " \n",- "for example in ds: \n",+ "\n",+ "\n",+ "for example in ds:\n"," doc = mlqaen_example_to_document(example)\n"," print(doc)\n"," break"@@ -194,11 +199,11 @@"from langchain.document_loaders import TensorflowDatasetLoader\n","\n","loader = TensorflowDatasetLoader(\n",- " dataset_name=\"mlqa/en\",\n",- " split_name=\"test\",\n",- " load_max_docs=3,\n",- " sample_to_document_function=mlqaen_example_to_document,\n",- " )"+ " dataset_name=\"mlqa/en\",\n",+ " split_name=\"test\",\n",+ " load_max_docs=3,\n",+ " sample_to_document_function=mlqaen_example_to_document,\n",+ ")"]},{diff --git a/docs/docs/integrations/document_loaders/unstructured_file.ipynb b/docs/docs/integrations/document_loaders/unstructured_file.ipynbindex b72b395bdf..5882be15e6 100644--- a/docs/docs/integrations/document_loaders/unstructured_file.ipynb+++ b/docs/docs/integrations/document_loaders/unstructured_file.ipynb@@ -18,7 +18,7 @@"outputs": [],"source": ["# # Install package\n",- "!pip install \"unstructured[all-docs]\"\n"+ "!pip install \"unstructured[all-docs]\""]},{diff --git a/docs/docs/integrations/document_loaders/youtube_audio.ipynb b/docs/docs/integrations/document_loaders/youtube_audio.ipynbindex 4b96a32c75..47ade5ca52 100644--- a/docs/docs/integrations/document_loaders/youtube_audio.ipynb+++ b/docs/docs/integrations/document_loaders/youtube_audio.ipynb@@ -25,7 +25,10 @@"outputs": [],"source": ["from langchain.document_loaders.generic import GenericLoader\n",- "from langchain.document_loaders.parsers import OpenAIWhisperParser, OpenAIWhisperParserLocal\n",+ "from langchain.document_loaders.parsers import (\n",+ " OpenAIWhisperParser,\n",+ " OpenAIWhisperParserLocal,\n",+ ")\n","from langchain.document_loaders.blob_loaders.youtube_audio import YoutubeAudioLoader"]},@@ -115,7 +118,9 @@"\n","# Transcribe the videos to text\n","if local:\n",- " loader = GenericLoader(YoutubeAudioLoader(urls, save_dir), OpenAIWhisperParserLocal())\n",+ " loader = GenericLoader(\n",+ " YoutubeAudioLoader(urls, save_dir), OpenAIWhisperParserLocal()\n",+ " )\n","else:\n"," loader = GenericLoader(YoutubeAudioLoader(urls, save_dir), OpenAIWhisperParser())\n","docs = loader.load()"diff --git a/docs/docs/integrations/document_transformers/beautiful_soup.ipynb b/docs/docs/integrations/document_transformers/beautiful_soup.ipynbindex fca4e52fc4..4e71be5499 100644--- a/docs/docs/integrations/document_transformers/beautiful_soup.ipynb+++ b/docs/docs/integrations/document_transformers/beautiful_soup.ipynb@@ -51,7 +51,9 @@"source": ["# Transform\n","bs_transformer = BeautifulSoupTransformer()\n",- "docs_transformed = bs_transformer.transform_documents(html,tags_to_extract=[\"p\", \"li\", \"div\", \"a\"])"+ "docs_transformed = bs_transformer.transform_documents(\n",+ " html, tags_to_extract=[\"p\", \"li\", \"div\", \"a\"]\n",+ ")"]},{diff --git a/docs/docs/integrations/document_transformers/docai.ipynb b/docs/docs/integrations/document_transformers/docai.ipynbindex 6446e2a217..45e6524730 100644--- a/docs/docs/integrations/document_transformers/docai.ipynb+++ b/docs/docs/integrations/document_transformers/docai.ipynb@@ -40,7 +40,7 @@"outputs": [],"source": ["%pip install google-cloud-documentai\n",- "%pip install google-cloud-documentai-toolbox\n"+ "%pip install google-cloud-documentai-toolbox"]},{@@ -61,7 +61,7 @@"outputs": [],"source": ["GCS_OUTPUT_PATH = \"gs://BUCKET_NAME/FOLDER_PATH\"\n",- "PROCESSOR_NAME = \"projects/PROJECT_NUMBER/locations/LOCATION/processors/PROCESSOR_ID\"\n"+ "PROCESSOR_NAME = \"projects/PROJECT_NUMBER/locations/LOCATION/processors/PROCESSOR_ID\""]},{@@ -72,7 +72,7 @@"outputs": [],"source": ["from langchain.document_loaders.blob_loaders import Blob\n",- "from langchain.document_loaders.parsers import DocAIParser\n"+ "from langchain.document_loaders.parsers import DocAIParser"]},{@@ -91,7 +91,8 @@"outputs": [],"source": ["parser = DocAIParser(\n",- " location=\"us\", processor_name=PROCESSOR_NAME, gcs_output_path=GCS_OUTPUT_PATH)\n"+ " location=\"us\", processor_name=PROCESSOR_NAME, gcs_output_path=GCS_OUTPUT_PATH\n",+ ")"]},{@@ -113,7 +114,9 @@"metadata": {},"outputs": [],"source": [- "blob = Blob(path=\"gs://cloud-samples-data/gen-app-builder/search/alphabet-investor-pdfs/2022Q1_alphabet_earnings_release.pdf\")\n"+ "blob = Blob(\n",+ " path=\"gs://cloud-samples-data/gen-app-builder/search/alphabet-investor-pdfs/2022Q1_alphabet_earnings_release.pdf\"\n",+ ")"]},{@@ -140,7 +143,7 @@],"source": ["docs = list(parser.lazy_parse(blob))\n",- "print(len(docs))\n"+ "print(len(docs))"]},{@@ -167,7 +170,7 @@],"source": ["operations = parser.docai_parse([blob])\n",- "print([op.operation.name for op in operations])\n"+ "print([op.operation.name for op in operations])"]},{@@ -196,7 +199,7 @@}],"source": [- "parser.is_running(operations)\n"+ "parser.is_running(operations)"]},{@@ -225,7 +228,7 @@}],"source": [- "parser.is_running(operations)\n"+ "parser.is_running(operations)"]},{@@ -244,7 +247,7 @@],"source": ["results = parser.get_results(operations)\n",- "print(results[0])\n"+ "print(results[0])"]},{@@ -262,7 +265,7 @@"metadata": {},"outputs": [],"source": [- "docs = list(parser.parse_from_results(results))\n"+ "docs = list(parser.parse_from_results(results))"]},{@@ -280,7 +283,7 @@}],"source": [- "print(len(docs))\n"+ "print(len(docs))"]}],diff --git a/docs/docs/integrations/llms/anyscale.ipynb b/docs/docs/integrations/llms/anyscale.ipynbindex ddce624029..5f58e67ea8 100644--- a/docs/docs/integrations/llms/anyscale.ipynb+++ b/docs/docs/integrations/llms/anyscale.ipynb@@ -132,11 +132,13 @@"source": ["import ray\n","\n",+ "\n","@ray.remote(num_cpus=0.1)\n","def send_query(llm, prompt):\n"," resp = llm(prompt)\n"," return resp\n","\n",+ "\n","futures = [send_query.remote(llm, prompt) for prompt in prompt_list]\n","results = ray.get(futures)"]diff --git a/docs/docs/integrations/llms/arcee.ipynb b/docs/docs/integrations/llms/arcee.ipynbindex 0f0fa3461c..f035278033 100644--- a/docs/docs/integrations/llms/arcee.ipynb+++ b/docs/docs/integrations/llms/arcee.ipynb@@ -51,18 +51,18 @@"arcee = Arcee(\n"," model=\"DALM-Patent\",\n"," # arcee_api_key=\"ARCEE-API-KEY\", # if not already set in the environment\n",- " arcee_api_url=\"https://custom-api.arcee.ai\", # default is https://api.arcee.ai\n",- " arcee_app_url=\"https://custom-app.arcee.ai\", # default is https://app.arcee.ai\n",+ " arcee_api_url=\"https://custom-api.arcee.ai\", # default is https://api.arcee.ai\n",+ " arcee_app_url=\"https://custom-app.arcee.ai\", # default is https://app.arcee.ai\n"," model_kwargs={\n"," \"size\": 5,\n"," \"filters\": [\n"," {\n"," \"field_name\": \"document\",\n"," \"filter_type\": \"fuzzy_search\",\n",- " \"value\": \"Einstein\"\n",+ " \"value\": \"Einstein\",\n"," }\n",- " ]\n",- " }\n",+ " ],\n",+ " },\n",")"]},@@ -105,16 +105,8 @@"source": ["# Define filters\n","filters = [\n",- " {\n",- " \"field_name\": \"document\",\n",- " \"filter_type\": \"fuzzy_search\",\n",- " \"value\": \"Einstein\"\n",- " },\n",- " {\n",- " \"field_name\": \"year\",\n",- " \"filter_type\": \"strict_search\",\n",- " \"value\": \"1905\"\n",- " }\n",+ " {\"field_name\": \"document\", \"filter_type\": \"fuzzy_search\", \"value\": \"Einstein\"},\n",+ " {\"field_name\": \"year\", \"filter_type\": \"strict_search\", \"value\": \"1905\"},\n","]\n","\n","# Generate text with filters and size params\n",diff --git a/docs/docs/integrations/llms/baidu_qianfan_endpoint.ipynb b/docs/docs/integrations/llms/baidu_qianfan_endpoint.ipynbindex cf5e7eed01..924e1de699 100644--- a/docs/docs/integrations/llms/baidu_qianfan_endpoint.ipynb+++ b/docs/docs/integrations/llms/baidu_qianfan_endpoint.ipynb@@ -71,7 +71,6 @@}],"source": [- "\n","\"\"\"For basic init and call\"\"\"\n","from langchain.llms import QianfanLLMEndpoint\n","import os\n",@@ -81,7 +80,7 @@"\n","llm = QianfanLLMEndpoint(streaming=True)\n","res = llm(\"hi\")\n",- "print(res)\n"+ "print(res)"]},{@@ -126,14 +125,16 @@}],"source": [- "\n","\"\"\"Test for llm generate \"\"\"\n","res = llm.generate(prompts=[\"hillo?\"])\n","\"\"\"Test for llm aio generate\"\"\"\n",+ "\n",+ "\n","async def run_aio_generate():\n"," resp = await llm.agenerate(prompts=[\"Write a 20-word article about rivers.\"])\n"," print(resp)\n","\n",+ "\n","await run_aio_generate()\n","\n","\"\"\"Test for llm stream\"\"\"\n",@@ -141,11 +142,14 @@" print(res)\n","\n","\"\"\"Test for llm aio stream\"\"\"\n",+ "\n",+ "\n","async def run_aio_stream():\n"," async for res in llm.astream(\"Write a 20-word article about mountains\"):\n"," print(res)\n","\n",- "await run_aio_stream()\n"+ "\n",+ "await run_aio_stream()"]},{@@ -176,10 +180,10 @@],"source": ["llm = QianfanLLMEndpoint(\n",- " streaming=True, \n",- " model=\"ERNIE-Bot-turbo\",\n",- " endpoint=\"eb-instant\",\n",- " )\n",+ " streaming=True,\n",+ " model=\"ERNIE-Bot-turbo\",\n",+ " endpoint=\"eb-instant\",\n",+ ")\n","res = llm(\"hi\")"]},@@ -220,7 +224,11 @@}],"source": [- "res = llm.generate(prompts=[\"hi\"], streaming=True, **{'top_p': 0.4, 'temperature': 0.1, 'penalty_score': 1})\n",+ "res = llm.generate(\n",+ " prompts=[\"hi\"],\n",+ " streaming=True,\n",+ " **{\"top_p\": 0.4, \"temperature\": 0.1, \"penalty_score\": 1}\n",+ ")\n","\n","for r in res:\n"," print(r)"diff --git a/docs/docs/integrations/llms/banana.ipynb b/docs/docs/integrations/llms/banana.ipynbindex 81453babd1..76ccd6bd3a 100644--- a/docs/docs/integrations/llms/banana.ipynb+++ b/docs/docs/integrations/llms/banana.ipynb@@ -75,7 +75,7 @@"metadata": {},"outputs": [],"source": [- "# Both of these are found in your model's \n",+ "# Both of these are found in your model's\n","# detail page in https://app.banana.dev\n","llm = Banana(model_key=\"YOUR_MODEL_KEY\", model_url_slug=\"YOUR_MODEL_URL_SLUG\")"]diff --git a/docs/docs/integrations/llms/bedrock.ipynb b/docs/docs/integrations/llms/bedrock.ipynbindex 0b00cf6452..6ced4daab4 100644--- a/docs/docs/integrations/llms/bedrock.ipynb+++ b/docs/docs/integrations/llms/bedrock.ipynb@@ -34,8 +34,7 @@"from langchain.llms import Bedrock\n","\n","llm = Bedrock(\n",- " credentials_profile_name=\"bedrock-admin\",\n",- " model_id=\"amazon.titan-text-express-v1\"\n",+ " credentials_profile_name=\"bedrock-admin\", model_id=\"amazon.titan-text-express-v1\"\n",")"]},@@ -94,7 +93,6 @@"metadata": {},"outputs": [],"source": [- "\n","conversation = ConversationChain(\n"," llm=llm, verbose=True, memory=ConversationBufferMemory()\n",")\n",diff --git a/docs/docs/integrations/llms/bittensor.ipynb b/docs/docs/integrations/llms/bittensor.ipynbindex c3504f50a8..a1e47b637f 100644--- a/docs/docs/integrations/llms/bittensor.ipynb+++ b/docs/docs/integrations/llms/bittensor.ipynb@@ -96,7 +96,9 @@"prompt = PromptTemplate(template=template, input_variables=[\"question\"])\n","\n","# System parameter in NIBittensorLLM is optional but you can set whatever you want to perform with model\n",- "llm = NIBittensorLLM(system_prompt=\"Your task is to determine response based on user prompt.\")\n",+ "llm = NIBittensorLLM(\n",+ " system_prompt=\"Your task is to determine response based on user prompt.\"\n",+ ")\n","\n","llm_chain = LLMChain(prompt=prompt, llm=llm)\n","question = \"What is bittensor?\"\n",@@ -147,7 +149,9 @@" input_variables=[\"input\", \"chat_history\", \"agent_scratchpad\"],\n",")\n","\n",- "llm = NIBittensorLLM(system_prompt=\"Your task is to determine response based on user prompt\")\n",+ "llm = NIBittensorLLM(\n",+ " system_prompt=\"Your task is to determine response based on user prompt\"\n",+ ")\n","\n","llm_chain = LLMChain(llm=llm, prompt=prompt)\n","\n",diff --git a/docs/docs/integrations/llms/ctranslate2.ipynb b/docs/docs/integrations/llms/ctranslate2.ipynbindex 3612c59980..62dc7194d9 100644--- a/docs/docs/integrations/llms/ctranslate2.ipynb+++ b/docs/docs/integrations/llms/ctranslate2.ipynb@@ -69,8 +69,8 @@" device=\"cuda\",\n"," # device_index can be either single int or list or ints,\n"," # indicating the ids of GPUs to use for inference:\n",- " device_index=[0,1], \n",- " compute_type=\"bfloat16\"\n",+ " device_index=[0, 1],\n",+ " compute_type=\"bfloat16\",\n",")"]},@@ -132,7 +132,7 @@"print(\n"," llm.generate(\n"," [\"The list of top romantic songs:\\n1.\", \"The list of top rap songs:\\n1.\"],\n",- " max_length=128\n",+ " max_length=128,\n"," )\n",")"]diff --git a/docs/docs/integrations/llms/deepinfra.ipynb b/docs/docs/integrations/llms/deepinfra.ipynbindex a7970e36df..257e7ed127 100644--- a/docs/docs/integrations/llms/deepinfra.ipynb+++ b/docs/docs/integrations/llms/deepinfra.ipynb@@ -123,7 +123,7 @@"source": ["# run streaming inference\n","for chunk in llm.stream(\"Who let the dogs out?\"):\n",- " print(chunk)"+ " print(chunk)"]},{diff --git a/docs/docs/integrations/llms/deepsparse.ipynb b/docs/docs/integrations/llms/deepsparse.ipynbindex 05ac4be716..886a147ebb 100644--- a/docs/docs/integrations/llms/deepsparse.ipynb+++ b/docs/docs/integrations/llms/deepsparse.ipynb@@ -28,9 +28,11 @@"source": ["from langchain.llms import DeepSparse\n","\n",- "llm = DeepSparse(model='zoo:nlg/text_generation/codegen_mono-350m/pytorch/huggingface/bigpython_bigquery_thepile/base-none')\n",+ "llm = DeepSparse(\n",+ " model=\"zoo:nlg/text_generation/codegen_mono-350m/pytorch/huggingface/bigpython_bigquery_thepile/base-none\"\n",+ ")\n","\n",- "print(llm('def fib():'))"+ "print(llm(\"def fib():\"))"]},{@@ -48,9 +50,12 @@"metadata": {},"outputs": [],"source": [- "config = {'max_generated_tokens': 256}\n",+ "config = {\"max_generated_tokens\": 256}\n","\n",- "llm = DeepSparse(model='zoo:nlg/text_generation/codegen_mono-350m/pytorch/huggingface/bigpython_bigquery_thepile/base-none', config=config)"+ "llm = DeepSparse(\n",+ " model=\"zoo:nlg/text_generation/codegen_mono-350m/pytorch/huggingface/bigpython_bigquery_thepile/base-none\",\n",+ " config=config,\n",+ ")"]}],diff --git a/docs/docs/integrations/llms/edenai.ipynb b/docs/docs/integrations/llms/edenai.ipynbindex 031f6986d6..2e57fd9ded 100644--- a/docs/docs/integrations/llms/edenai.ipynb+++ b/docs/docs/integrations/llms/edenai.ipynb@@ -69,7 +69,7 @@"metadata": {},"outputs": [],"source": [- "llm = EdenAI(edenai_api_key=\"...\",provider=\"openai\", temperature=0.2, max_tokens=250)"+ "llm = EdenAI(edenai_api_key=\"...\", provider=\"openai\", temperature=0.2, max_tokens=250)"]},{@@ -103,8 +103,16 @@"metadata": {},"outputs": [],"source": [- "from langchain.prompts import PromptTemplate\nfrom langchain.chains import LLMChain\n",- "llm=EdenAI(feature=\"text\",provider=\"openai\",model=\"text-davinci-003\",temperature=0.2, max_tokens=250)\n",+ "from langchain.prompts import PromptTemplate\n",+ "from langchain.chains import LLMChain\n",+ "\n",+ "llm = EdenAI(\n",+ " feature=\"text\",\n",+ " provider=\"openai\",\n",+ " model=\"text-davinci-003\",\n",+ " temperature=0.2,\n",+ " max_tokens=250,\n",+ ")\n","\n","prompt = \"\"\"\n","User: Answer the following yes/no question by reasoning step by step. Can a dog drive a car?\n",@@ -131,6 +139,8 @@"from io import BytesIO\n","from PIL import Image\n","import json\n",+ "\n",+ "\n","def print_base64_image(base64_string):\n"," # Decode the base64 string into binary data\n"," decoded_data = base64.b64decode(base64_string)\n",@@ -151,11 +161,7 @@"metadata": {},"outputs": [],"source": [- "text2image = EdenAI(\n",- " feature=\"image\" ,\n",- " provider= \"openai\",\n",- " resolution=\"512x512\"\n",- ")"+ "text2image = EdenAI(feature=\"image\", provider=\"openai\", resolution=\"512x512\")"]},{@@ -194,7 +200,10 @@"\n","llm = EdenAI(\n"," callbacks=[StreamingStdOutCallbackHandler()],\n",- " feature=\"text\",provider=\"openai\", temperature=0.2,max_tokens=250\n",+ " feature=\"text\",\n",+ " provider=\"openai\",\n",+ " temperature=0.2,\n",+ " max_tokens=250,\n",")\n","prompt = \"\"\"\n","User: Answer the following yes/no question by reasoning step by step. Can a dog drive a car?\n",@@ -227,12 +236,8 @@"metadata": {},"outputs": [],"source": [- "llm = EdenAI(\n",- "feature=\"text\", provider=\"openai\", temperature=0.2, max_tokens=250\n",- ")\n",- "text2image = EdenAI(\n",- "feature=\"image\", provider=\"openai\", resolution=\"512x512\"\n",- ")"+ "llm = EdenAI(feature=\"text\", provider=\"openai\", temperature=0.2, max_tokens=250)\n",+ "text2image = EdenAI(feature=\"image\", provider=\"openai\", resolution=\"512x512\")"]},{@@ -283,9 +288,9 @@"source": ["# Run the chain specifying only the input variable for the first chain.\n","overall_chain = SimpleSequentialChain(\n",- " chains=[chain, chain_two, chain_three],verbose=True\n",+ " chains=[chain, chain_two, chain_three], verbose=True\n",")\n",- "output = overall_chain.run(\"hats\")\n"+ "output = overall_chain.run(\"hats\")"]},{@@ -294,7 +299,7 @@"metadata": {},"outputs": [],"source": [- "#print the image\n",+ "# print the image\n","print_base64_image(output)"]}diff --git a/docs/docs/integrations/llms/fireworks.ipynb b/docs/docs/integrations/llms/fireworks.ipynbindex 1573453a1e..bd29bfcdaa 100644--- a/docs/docs/integrations/llms/fireworks.ipynb+++ b/docs/docs/integrations/llms/fireworks.ipynb@@ -140,10 +140,12 @@],"source": ["# Calling multiple prompts\n",- "output = llm.generate([\n",- " \"Who's the best cricket player in 2016?\",\n",- " \"Who's the best basketball player in the league?\",\n",- "])\n",+ "output = llm.generate(\n",+ " [\n",+ " \"Who's the best cricket player in 2016?\",\n",+ " \"Who's the best basketball player in the league?\",\n",+ " ]\n",+ ")\n","print(output.generations)"]},@@ -164,7 +166,10 @@],"source": ["# Setting additional parameters: temperature, max_tokens, top_p\n",- "llm = Fireworks(model=\"accounts/fireworks/models/llama-v2-13b-chat\", model_kwargs={\"temperature\":0.7, \"max_tokens\":15, \"top_p\":1.0})\n",+ "llm = Fireworks(\n",+ " model=\"accounts/fireworks/models/llama-v2-13b-chat\",\n",+ " model_kwargs={\"temperature\": 0.7, \"max_tokens\": 15, \"top_p\": 1.0},\n",+ ")\n","print(llm(\"What's the weather like in Kansas City in December?\"))"]},@@ -207,7 +212,10 @@"from langchain.prompts import PromptTemplate\n","from langchain.llms.fireworks import Fireworks\n","\n",- "llm = Fireworks(model=\"accounts/fireworks/models/llama-v2-13b\", model_kwargs={\"temperature\":0, \"max_tokens\":100, \"top_p\":1.0})\n",+ "llm = Fireworks(\n",+ " model=\"accounts/fireworks/models/llama-v2-13b\",\n",+ " model_kwargs={\"temperature\": 0, \"max_tokens\": 100, \"top_p\": 1.0},\n",+ ")\n","prompt = PromptTemplate.from_template(\"Tell me a joke about {topic}?\")\n","chain = prompt | llm\n","\n",@@ -242,7 +250,7 @@],"source": ["for token in chain.stream({\"topic\": \"bears\"}):\n",- " print(token, end='', flush=True)"+ " print(token, end=\"\", flush=True)"]}],diff --git a/docs/docs/integrations/llms/gigachat.ipynb b/docs/docs/integrations/llms/gigachat.ipynbindex a11ea9986f..dad7dca95c 100644--- a/docs/docs/integrations/llms/gigachat.ipynb+++ b/docs/docs/integrations/llms/gigachat.ipynb@@ -40,7 +40,7 @@"import os\n","from getpass import getpass\n","\n",- "os.environ['GIGACHAT_CREDENTIALS'] = getpass()"+ "os.environ[\"GIGACHAT_CREDENTIALS\"] = getpass()"],"metadata": {"collapsed": falsediff --git a/docs/docs/integrations/llms/google_vertex_ai_palm.ipynb b/docs/docs/integrations/llms/google_vertex_ai_palm.ipynbindex 96d328f1b2..6611894f71 100644--- a/docs/docs/integrations/llms/google_vertex_ai_palm.ipynb+++ b/docs/docs/integrations/llms/google_vertex_ai_palm.ipynb@@ -41,7 +41,7 @@},"outputs": [],"source": [- "#!pip install langchain google-cloud-aiplatform\n"+ "#!pip install langchain google-cloud-aiplatform"]},{@@ -50,7 +50,7 @@"metadata": {},"outputs": [],"source": [- "from langchain.llms import VertexAI\n"+ "from langchain.llms import VertexAI"]},{@@ -74,7 +74,7 @@],"source": ["llm = VertexAI()\n",- "print(llm(\"What are some of the pros and cons of Python as a programming language?\"))\n"+ "print(llm(\"What are some of the pros and cons of Python as a programming language?\"))"]},{@@ -90,7 +90,7 @@"metadata": {},"outputs": [],"source": [- "from langchain.prompts import PromptTemplate\n"+ "from langchain.prompts import PromptTemplate"]},{@@ -102,7 +102,7 @@"template = \"\"\"Question: {question}\n","\n","Answer: Let's think step by step.\"\"\"\n",- "prompt = PromptTemplate.from_template(template)\n"+ "prompt = PromptTemplate.from_template(template)"]},{@@ -111,7 +111,7 @@"metadata": {},"outputs": [],"source": [- "chain = prompt | llm\n"+ "chain = prompt | llm"]},{@@ -130,7 +130,7 @@],"source": ["question = \"Who was the president in the year Justin Beiber was born?\"\n",- "print(chain.invoke({\"question\": question}))\n"+ "print(chain.invoke({\"question\": question}))"]},{@@ -159,7 +159,7 @@},"outputs": [],"source": [- "llm = VertexAI(model_name=\"code-bison\", max_output_tokens=1000, temperature=0.3)\n"+ "llm = VertexAI(model_name=\"code-bison\", max_output_tokens=1000, temperature=0.3)"]},{@@ -168,7 +168,7 @@"metadata": {},"outputs": [],"source": [- "question = \"Write a python function that checks if a string is a valid email address\"\n"+ "question = \"Write a python function that checks if a string is a valid email address\""]},{@@ -193,7 +193,7 @@}],"source": [- "print(llm(question))\n"+ "print(llm(question))"]},{@@ -223,7 +223,7 @@],"source": ["result = llm.generate([question])\n",- "result.generations\n"+ "result.generations"]},{@@ -243,7 +243,7 @@"source": ["# If running in a Jupyter notebook you'll need to install nest_asyncio\n","\n",- "# !pip install nest_asyncio\n"+ "# !pip install nest_asyncio"]},{@@ -253,8 +253,9 @@"outputs": [],"source": ["import asyncio\n",+ "\n","# import nest_asyncio\n",- "# nest_asyncio.apply()\n"+ "# nest_asyncio.apply()"]},{@@ -274,7 +275,7 @@}],"source": [- "asyncio.run(llm.agenerate([question]))\n"+ "asyncio.run(llm.agenerate([question]))"]},{@@ -292,7 +293,7 @@"metadata": {},"outputs": [],"source": [- "import sys\n"+ "import sys"]},{@@ -337,7 +338,7 @@"source": ["for chunk in llm.stream(question):\n"," sys.stdout.write(chunk)\n",- " sys.stdout.flush()\n"+ " sys.stdout.flush()"]},{@@ -360,7 +361,7 @@"metadata": {},"outputs": [],"source": [- "from langchain.llms import VertexAIModelGarden\n"+ "from langchain.llms import VertexAIModelGarden"]},{@@ -369,10 +370,7 @@"metadata": {},"outputs": [],"source": [- "llm = VertexAIModelGarden(\n",- " project=\"YOUR PROJECT\",\n",- " endpoint_id=\"YOUR ENDPOINT_ID\"\n",- ")\n"+ "llm = VertexAIModelGarden(project=\"YOUR PROJECT\", endpoint_id=\"YOUR ENDPOINT_ID\")"]},{@@ -381,7 +379,7 @@"metadata": {},"outputs": [],"source": [- "print(llm(\"What is the meaning of life?\"))\n"+ "print(llm(\"What is the meaning of life?\"))"]},{@@ -397,7 +395,7 @@"metadata": {},"outputs": [],"source": [- "prompt = PromptTemplate.from_template(\"What is the meaning of {thing}?\")\n"+ "prompt = PromptTemplate.from_template(\"What is the meaning of {thing}?\")"]},{@@ -407,7 +405,7 @@"outputs": [],"source": ["chian = prompt | llm\n",- "print(chain.invoke({\"thing\": \"life\"}))\n"+ "print(chain.invoke({\"thing\": \"life\"}))"]}],diff --git a/docs/docs/integrations/llms/gradient.ipynb b/docs/docs/integrations/llms/gradient.ipynbindex 9bddce8590..1085ed0346 100644--- a/docs/docs/integrations/llms/gradient.ipynb+++ b/docs/docs/integrations/llms/gradient.ipynb@@ -46,10 +46,10 @@"from getpass import getpass\n","import os\n","\n",- "if not os.environ.get(\"GRADIENT_ACCESS_TOKEN\",None):\n",+ "if not os.environ.get(\"GRADIENT_ACCESS_TOKEN\", None):\n"," # Access token under https://auth.gradient.ai/select-workspace\n"," os.environ[\"GRADIENT_ACCESS_TOKEN\"] = getpass(\"gradient.ai access token:\")\n",- "if not os.environ.get(\"GRADIENT_WORKSPACE_ID\",None):\n",+ "if not os.environ.get(\"GRADIENT_WORKSPACE_ID\", None):\n"," # `ID` listed in `$ gradient workspace list`\n"," # also displayed after login at at https://auth.gradient.ai/select-workspace\n"," os.environ[\"GRADIENT_WORKSPACE_ID\"] = getpass(\"gradient.ai workspace id:\")"@@ -153,7 +153,7 @@" # # optional: set new credentials, they default to environment variables\n"," # gradient_workspace_id=os.environ[\"GRADIENT_WORKSPACE_ID\"],\n"," # gradient_access_token=os.environ[\"GRADIENT_ACCESS_TOKEN\"],\n",- " model_kwargs=dict(max_generated_token_count=128)\n",+ " model_kwargs=dict(max_generated_token_count=128),\n",")"]},@@ -221,9 +221,7 @@"source": ["question = \"What NFL team won the Super Bowl in 1994?\"\n","\n",- "llm_chain.run(\n",- " question=question\n",- ")"+ "llm_chain.run(question=question)"]},{@@ -254,7 +252,12 @@}],"source": [- "dataset = [{\"inputs\": template.format(question=\"What NFL team won the Super Bowl in 1994?\") + \" The Dallas Cowboys!\"}]\n",+ "dataset = [\n",+ " {\n",+ " \"inputs\": template.format(question=\"What NFL team won the Super Bowl in 1994?\")\n",+ " + \" The Dallas Cowboys!\"\n",+ " }\n",+ "]\n","dataset"]},@@ -275,9 +278,7 @@}],"source": [- "new_model.fine_tune(\n",- " samples=dataset\n",- ")"+ "new_model.fine_tune(samples=dataset)"]},{@@ -298,9 +299,7 @@],"source": ["# we can keep the llm_chain, as the registered model just got refreshed on the gradient.ai servers.\n",- "llm_chain.run(\n",- " question=question\n",- ")"+ "llm_chain.run(question=question)"]},{diff --git a/docs/docs/integrations/llms/huggingface_textgen_inference.ipynb b/docs/docs/integrations/llms/huggingface_textgen_inference.ipynbindex 9b934806b5..7e9261d25b 100644--- a/docs/docs/integrations/llms/huggingface_textgen_inference.ipynb+++ b/docs/docs/integrations/llms/huggingface_textgen_inference.ipynb@@ -74,7 +74,7 @@" typical_p=0.95,\n"," temperature=0.01,\n"," repetition_penalty=1.03,\n",- " streaming=True\n",+ " streaming=True,\n",")\n","llm(\"What did foo say about bar?\", callbacks=[StreamingStdOutCallbackHandler()])"]diff --git a/docs/docs/integrations/llms/javelin.ipynb b/docs/docs/integrations/llms/javelin.ipynbindex 1201e47d6f..5f016616dd 100644--- a/docs/docs/integrations/llms/javelin.ipynb+++ b/docs/docs/integrations/llms/javelin.ipynb@@ -98,7 +98,7 @@"route_completions = \"eng_dept03\"\n","\n","gateway = JavelinAIGateway(\n",- " gateway_uri=\"http://localhost:8000\", # replace with service URL or host/port of Javelin\n",+ " gateway_uri=\"http://localhost:8000\", # replace with service URL or host/port of Javelin\n"," route=route_completions,\n"," model_name=\"text-davinci-003\",\n",")\n",@@ -108,7 +108,7 @@"llmchain = LLMChain(llm=gateway, prompt=prompt)\n","result = llmchain.run(\"podcast player\")\n","\n",- "print(result)\n"+ "print(result)"]},{@@ -144,12 +144,12 @@"from langchain.embeddings.openai import OpenAIEmbeddings\n","\n","embeddings = JavelinAIGatewayEmbeddings(\n",- " gateway_uri=\"http://localhost:8000\", # replace with service URL or host/port of Javelin\n",+ " gateway_uri=\"http://localhost:8000\", # replace with service URL or host/port of Javelin\n"," route=\"embeddings\",\n",")\n","\n","print(embeddings.embed_query(\"hello\"))\n",- "print(embeddings.embed_documents([\"hello\"]))\n"+ "print(embeddings.embed_documents([\"hello\"]))"]},{@@ -194,15 +194,13 @@"]\n","\n","chat = ChatJavelinAIGateway(\n",- " gateway_uri=\"http://localhost:8000\", # replace with service URL or host/port of Javelin\n",+ " gateway_uri=\"http://localhost:8000\", # replace with service URL or host/port of Javelin\n"," route=\"mychatbot_route\",\n"," model_name=\"gpt-3.5-turbo\",\n",- " params={\n",- " \"temperature\": 0.1\n",- " }\n",+ " params={\"temperature\": 0.1},\n",")\n","\n",- "print(chat(messages))\n"+ "print(chat(messages))"]},{diff --git a/docs/docs/integrations/llms/llamacpp.ipynb b/docs/docs/integrations/llms/llamacpp.ipynbindex cf9fa21bb5..668766f30a 100644--- a/docs/docs/integrations/llms/llamacpp.ipynb+++ b/docs/docs/integrations/llms/llamacpp.ipynb@@ -255,8 +255,8 @@" temperature=0.75,\n"," max_tokens=2000,\n"," top_p=1,\n",- " callback_manager=callback_manager, \n",- " verbose=True, # Verbose is required to pass to the callback manager\n",+ " callback_manager=callback_manager,\n",+ " verbose=True, # Verbose is required to pass to the callback manager\n",")"]},@@ -420,7 +420,7 @@" n_gpu_layers=n_gpu_layers,\n"," n_batch=n_batch,\n"," callback_manager=callback_manager,\n",- " verbose=True, # Verbose is required to pass to the callback manager\n",+ " verbose=True, # Verbose is required to pass to the callback manager\n",")"]},@@ -506,7 +506,7 @@" n_batch=n_batch,\n"," f16_kv=True, # MUST set to True, otherwise you will run into problem after a couple of calls\n"," callback_manager=callback_manager,\n",- " verbose=True, # Verbose is required to pass to the callback manager\n",+ " verbose=True, # Verbose is required to pass to the callback manager\n",")"]},@@ -564,7 +564,7 @@" n_batch=n_batch,\n"," f16_kv=True, # MUST set to True, otherwise you will run into problem after a couple of calls\n"," callback_manager=callback_manager,\n",- " verbose=True, # Verbose is required to pass to the callback manager\n",+ " verbose=True, # Verbose is required to pass to the callback manager\n"," grammar_path=\"/Users/rlm/Desktop/Code/langchain-main/langchain/libs/langchain/langchain/llms/grammars/json.gbnf\",\n",")"]@@ -614,7 +614,7 @@],"source": ["%%capture captured --no-stdout\n",- "result=llm(\"Describe a person in JSON format:\")"+ "result = llm(\"Describe a person in JSON format:\")"]},{@@ -630,7 +630,7 @@"metadata": {},"outputs": [],"source": [- "n_gpu_layers = 1 \n",+ "n_gpu_layers = 1\n","n_batch = 512\n","llm = LlamaCpp(\n"," model_path=\"/Users/rlm/Desktop/Code/llama.cpp/models/openorca-platypus2-13b.gguf.q4_0.bin\",\n",@@ -670,7 +670,7 @@],"source": ["%%capture captured --no-stdout\n",- "result=llm(\"List of top-3 my favourite books:\")"+ "result = llm(\"List of top-3 my favourite books:\")"]}],diff --git a/docs/docs/integrations/llms/llm_caching.ipynb b/docs/docs/integrations/llms/llm_caching.ipynbindex 45bccb916b..806b046ce0 100644--- a/docs/docs/integrations/llms/llm_caching.ipynb+++ b/docs/docs/integrations/llms/llm_caching.ipynb@@ -420,9 +420,7 @@"\n","\n","set_llm_cache(\n",- " RedisSemanticCache(\n",- " redis_url=\"redis://localhost:6379\", embedding=OpenAIEmbeddings()\n",- " )\n",+ " RedisSemanticCache(redis_url=\"redis://localhost:6379\", embedding=OpenAIEmbeddings())\n",")"]},@@ -1065,7 +1063,7 @@"source": ["from langchain.embeddings import OpenAIEmbeddings\n","\n",- "embedding=OpenAIEmbeddings()"+ "embedding = OpenAIEmbeddings()"]},{@@ -1079,7 +1077,10 @@"\n","set_llm_cache(\n"," CassandraSemanticCache(\n",- " session=session, keyspace=keyspace, embedding=embedding, table_name=\"cass_sem_cache\"\n",+ " session=session,\n",+ " keyspace=keyspace,\n",+ " embedding=embedding,\n",+ " table_name=\"cass_sem_cache\",\n"," )\n",")"]diff --git a/docs/docs/integrations/llms/ollama.ipynb b/docs/docs/integrations/llms/ollama.ipynbindex e395603138..30addf32db 100644--- a/docs/docs/integrations/llms/ollama.ipynb+++ b/docs/docs/integrations/llms/ollama.ipynb@@ -57,9 +57,11 @@"source": ["from langchain.llms import Ollama\n","from langchain.callbacks.manager import CallbackManager\n",- "from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler \n",- "llm = Ollama(model=\"llama2\", \n",- " callback_manager = CallbackManager([StreamingStdOutCallbackHandler()]))"+ "from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler\n",+ "\n",+ "llm = Ollama(\n",+ " model=\"llama2\", callback_manager=CallbackManager([StreamingStdOutCallbackHandler()])\n",+ ")"]},{@@ -92,6 +94,7 @@"outputs": [],"source": ["from langchain.embeddings import OllamaEmbeddings\n",+ "\n","oembed = OllamaEmbeddings(base_url=\"http://localhost:11434\", model=\"llama2\")\n","oembed.embed_query(\"Llamas are social animals and live with others as a herd.\")"]@@ -130,6 +133,7 @@"source": ["# Load web page\n","from langchain.document_loaders import WebBaseLoader\n",+ "\n","loader = WebBaseLoader(\"https://lilianweng.github.io/posts/2023-06-23-agent/\")\n","data = loader.load()"]@@ -140,8 +144,9 @@"metadata": {},"outputs": [],"source": [- "# Split into chunks \n",+ "# Split into chunks\n","from langchain.text_splitter import RecursiveCharacterTextSplitter\n",+ "\n","text_splitter = RecursiveCharacterTextSplitter(chunk_size=1500, chunk_overlap=100)\n","all_splits = text_splitter.split_documents(data)"]@@ -170,9 +175,9 @@"# Embed and store\n","from langchain.vectorstores import Chroma\n","from langchain.embeddings import GPT4AllEmbeddings\n",- "from langchain.embeddings import OllamaEmbeddings # We can also try Ollama embeddings\n",- "vectorstore = Chroma.from_documents(documents=all_splits,\n",- " embedding=GPT4AllEmbeddings())"+ "from langchain.embeddings import OllamaEmbeddings # We can also try Ollama embeddings\n",+ "\n",+ "vectorstore = Chroma.from_documents(documents=all_splits, embedding=GPT4AllEmbeddings())"]},{@@ -206,6 +211,7 @@"source": ["# RAG prompt\n","from langchain import hub\n",+ "\n","QA_CHAIN_PROMPT = hub.pull(\"rlm/rag-prompt-llama\")"]},@@ -219,9 +225,12 @@"from langchain.llms import Ollama\n","from langchain.callbacks.manager import CallbackManager\n","from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler\n",- "llm = Ollama(model=\"llama2\",\n",- " verbose=True,\n",- " callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]))"+ "\n",+ "llm = Ollama(\n",+ " model=\"llama2\",\n",+ " verbose=True,\n",+ " callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]),\n",+ ")"]},{@@ -232,6 +241,7 @@"source": ["# QA chain\n","from langchain.chains import RetrievalQA\n",+ "\n","qa_chain = RetrievalQA.from_chain_type(\n"," llm,\n"," retriever=vectorstore.as_retriever(),\n",@@ -280,16 +290,22 @@"from langchain.schema import LLMResult\n","from langchain.callbacks.base import BaseCallbackHandler\n","\n",+ "\n","class GenerationStatisticsCallback(BaseCallbackHandler):\n"," def on_llm_end(self, response: LLMResult, **kwargs) -> None:\n"," print(response.generations[0][0].generation_info)\n",- " \n",- "callback_manager = CallbackManager([StreamingStdOutCallbackHandler(), GenerationStatisticsCallback()])\n","\n",- "llm = Ollama(base_url=\"http://localhost:11434\",\n",- " model=\"llama2\",\n",- " verbose=True,\n",- " callback_manager=callback_manager)\n",+ "\n",+ "callback_manager = CallbackManager(\n",+ " [StreamingStdOutCallbackHandler(), GenerationStatisticsCallback()]\n",+ ")\n",+ "\n",+ "llm = Ollama(\n",+ " base_url=\"http://localhost:11434\",\n",+ " model=\"llama2\",\n",+ " verbose=True,\n",+ " callback_manager=callback_manager,\n",+ ")\n","\n","qa_chain = RetrievalQA.from_chain_type(\n"," llm,\n",@@ -325,7 +341,7 @@}],"source": [- "62 / (1313002000/1000/1000/1000)"+ "62 / (1313002000 / 1000 / 1000 / 1000)"]},{@@ -351,9 +367,12 @@"from langchain.llms import Ollama\n","from langchain.callbacks.manager import CallbackManager\n","from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler\n",- "llm = Ollama(model=\"mistral:7b-instruct\",\n",- " verbose=True,\n",- " callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]))"+ "\n",+ "llm = Ollama(\n",+ " model=\"mistral:7b-instruct\",\n",+ " verbose=True,\n",+ " callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]),\n",+ ")"]},{@@ -363,10 +382,12 @@"outputs": [],"source": ["from langchain import hub\n",+ "\n","QA_CHAIN_PROMPT = hub.pull(\"rlm/rag-prompt-mistral\")\n","\n","# QA chain\n","from langchain.chains import RetrievalQA\n",+ "\n","qa_chain = RetrievalQA.from_chain_type(\n"," llm,\n"," retriever=vectorstore.as_retriever(),\n",diff --git a/docs/docs/integrations/llms/opaqueprompts.ipynb b/docs/docs/integrations/llms/opaqueprompts.ipynbindex 037f15fe59..1e7c835212 100644--- a/docs/docs/integrations/llms/opaqueprompts.ipynb+++ b/docs/docs/integrations/llms/opaqueprompts.ipynb@@ -19,7 +19,7 @@"outputs": [],"source": ["# install the opaqueprompts and langchain packages\n",- "! pip install opaqueprompts langchain\n"+ "! pip install opaqueprompts langchain"]},{@@ -39,8 +39,8 @@"\n","# Set API keys\n","\n",- "os.environ['OPAQUEPROMPTS_API_KEY'] = \"<OPAQUEPROMPTS_API_KEY>\"\n",- "os.environ['OPENAI_API_KEY'] = \"<OPENAI_API_KEY>\"\n"+ "os.environ[\"OPAQUEPROMPTS_API_KEY\"] = \"<OPAQUEPROMPTS_API_KEY>\"\n",+ "os.environ[\"OPENAI_API_KEY\"] = \"<OPENAI_API_KEY>\""]},{@@ -116,10 +116,12 @@"\n","print(\n"," chain.run(\n",- " {\"question\": \"\"\"Write a message to remind John to do password reset for his website to stay secure.\"\"\"},\n",+ " {\n",+ " \"question\": \"\"\"Write a message to remind John to do password reset for his website to stay secure.\"\"\"\n",+ " },\n"," callbacks=[StdOutCallbackHandler()],\n"," )\n",- ")\n"+ ")"]},{@@ -179,20 +181,22 @@"from langchain.schema.output_parser import StrOutputParser\n","\n","\n",- "prompt=PromptTemplate.from_template(prompt_template), \n",+ "prompt = (PromptTemplate.from_template(prompt_template),)\n","llm = OpenAI()\n","pg_chain = (\n"," op.sanitize\n"," | RunnablePassthrough.assign(\n",- " response=(lambda x: x[\"sanitized_input\"])\n",- " | prompt\n",- " | llm\n",- " | StrOutputParser(),\n",+ " response=(lambda x: x[\"sanitized_input\"]) | prompt | llm | StrOutputParser(),\n"," )\n"," | (lambda x: op.desanitize(x[\"response\"], x[\"secure_context\"]))\n",")\n","\n",- "pg_chain.invoke({\"question\": \"Write a text message to remind John to do password reset for his website through his email to stay secure.\", \"history\": \"\"})\n"+ "pg_chain.invoke(\n",+ " {\n",+ " \"question\": \"Write a text message to remind John to do password reset for his website through his email to stay secure.\",\n",+ " \"history\": \"\",\n",+ " }\n",+ ")"]}],diff --git a/docs/docs/integrations/llms/pai_eas_endpoint.ipynb b/docs/docs/integrations/llms/pai_eas_endpoint.ipynbindex 4f5344a04e..ed7f388b19 100644--- a/docs/docs/integrations/llms/pai_eas_endpoint.ipynb+++ b/docs/docs/integrations/llms/pai_eas_endpoint.ipynb@@ -39,9 +39,13 @@"outputs": [],"source": ["import os\n",+ "\n","os.environ[\"EAS_SERVICE_URL\"] = \"Your_EAS_Service_URL\"\n","os.environ[\"EAS_SERVICE_TOKEN\"] = \"Your_EAS_Service_Token\"\n",- "llm = PaiEasEndpoint(eas_service_url=os.environ[\"EAS_SERVICE_URL\"], eas_service_token=os.environ[\"EAS_SERVICE_TOKEN\"])"+ "llm = PaiEasEndpoint(\n",+ " eas_service_url=os.environ[\"EAS_SERVICE_URL\"],\n",+ " eas_service_token=os.environ[\"EAS_SERVICE_TOKEN\"],\n",+ ")"]},{diff --git a/docs/docs/integrations/llms/sagemaker.ipynb b/docs/docs/integrations/llms/sagemaker.ipynbindex 32659dd2aa..43103e1a86 100644--- a/docs/docs/integrations/llms/sagemaker.ipynb+++ b/docs/docs/integrations/llms/sagemaker.ipynb@@ -121,19 +121,21 @@" template=prompt_template, input_variables=[\"context\", \"question\"]\n",")\n","\n",- "roleARN = 'arn:aws:iam::123456789:role/cross-account-role'\n",- "sts_client = boto3.client('sts')\n",- "response = sts_client.assume_role(RoleArn=roleARN, \n",- " RoleSessionName='CrossAccountSession')\n",+ "roleARN = \"arn:aws:iam::123456789:role/cross-account-role\"\n",+ "sts_client = boto3.client(\"sts\")\n",+ "response = sts_client.assume_role(\n",+ " RoleArn=roleARN, RoleSessionName=\"CrossAccountSession\"\n",+ ")\n","\n","client = boto3.client(\n"," \"sagemaker-runtime\",\n",- " region_name=\"us-west-2\", \n",- " aws_access_key_id=response['Credentials']['AccessKeyId'],\n",- " aws_secret_access_key=response['Credentials']['SecretAccessKey'],\n",- " aws_session_token = response['Credentials']['SessionToken']\n",+ " region_name=\"us-west-2\",\n",+ " aws_access_key_id=response[\"Credentials\"][\"AccessKeyId\"],\n",+ " aws_secret_access_key=response[\"Credentials\"][\"SecretAccessKey\"],\n",+ " aws_session_token=response[\"Credentials\"][\"SessionToken\"],\n",")\n","\n",+ "\n","class ContentHandler(LLMContentHandler):\n"," content_type = \"application/json\"\n"," accepts = \"application/json\"\n",diff --git a/docs/docs/integrations/llms/symblai_nebula.ipynb b/docs/docs/integrations/llms/symblai_nebula.ipynbindex 3faab38216..23efe08fa1 100644--- a/docs/docs/integrations/llms/symblai_nebula.ipynb+++ b/docs/docs/integrations/llms/symblai_nebula.ipynb@@ -32,7 +32,7 @@"source": ["from langchain.llms.symblai_nebula import Nebula\n","\n",- "llm = Nebula(nebula_api_key='<your_api_key>')"+ "llm = Nebula(nebula_api_key=\"<your_api_key>\")"],"metadata": {"collapsed": falsediff --git a/docs/docs/integrations/llms/textgen.ipynb b/docs/docs/integrations/llms/textgen.ipynbindex 1d3d0589f6..e27ac5f468 100644--- a/docs/docs/integrations/llms/textgen.ipynb+++ b/docs/docs/integrations/llms/textgen.ipynb@@ -107,7 +107,9 @@"\n","\n","prompt = PromptTemplate(template=template, input_variables=[\"question\"])\n",- "llm = TextGen(model_url=model_url, streaming=True, callbacks=[StreamingStdOutCallbackHandler()])\n",+ "llm = TextGen(\n",+ " model_url=model_url, streaming=True, callbacks=[StreamingStdOutCallbackHandler()]\n",+ ")\n","llm_chain = LLMChain(prompt=prompt, llm=llm)\n","question = \"What NFL team won the Super Bowl in the year Justin Bieber was born?\"\n","\n",@@ -120,13 +122,9 @@"metadata": {},"outputs": [],"source": [- "llm = TextGen(\n",- " model_url = model_url,\n",- " streaming=True\n",- ")\n",- "for chunk in llm.stream(\"Ask 'Hi, how are you?' like a pirate:'\",\n",- " stop=[\"'\",\"\\n\"]):\n",- " print(chunk, end='', flush=True)"+ "llm = TextGen(model_url=model_url, streaming=True)\n",+ "for chunk in llm.stream(\"Ask 'Hi, how are you?' like a pirate:'\", stop=[\"'\", \"\\n\"]):\n",+ " print(chunk, end=\"\", flush=True)"]}],diff --git a/docs/docs/integrations/llms/titan_takeoff.ipynb b/docs/docs/integrations/llms/titan_takeoff.ipynbindex e1b9a2f0fa..64b78f5529 100644--- a/docs/docs/integrations/llms/titan_takeoff.ipynb+++ b/docs/docs/integrations/llms/titan_takeoff.ipynb@@ -108,9 +108,7 @@"from langchain.llms import TitanTakeoff\n","\n","llm = TitanTakeoff(\n",- " base_url=\"http://localhost:8000\",\n",- " generate_max_length=128,\n",- " temperature=1.0\n",+ " base_url=\"http://localhost:8000\", generate_max_length=128, temperature=1.0\n",")\n","\n","prompt = \"What is the largest planet in the solar system?\"\n",@@ -137,7 +135,9 @@"from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler\n","from langchain.callbacks.manager import CallbackManager\n","\n",- "llm = TitanTakeoff(callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]), streaming=True)\n",+ "llm = TitanTakeoff(\n",+ " callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]), streaming=True\n",+ ")\n","\n","prompt = \"What is the capital of France?\"\n","\n",diff --git a/docs/docs/integrations/llms/titan_takeoff_pro.ipynb b/docs/docs/integrations/llms/titan_takeoff_pro.ipynbindex 12eb6c3094..8f2096d902 100644--- a/docs/docs/integrations/llms/titan_takeoff_pro.ipynb+++ b/docs/docs/integrations/llms/titan_takeoff_pro.ipynb@@ -47,11 +47,11 @@" min_new_tokens=128,\n"," max_new_tokens=512,\n"," no_repeat_ngram_size=2,\n",- " sampling_topk= 1,\n",- " sampling_topp= 1.0,\n",- " sampling_temperature= 1.0,\n",- " repetition_penalty= 1.0,\n",- " regex_string= \"\",\n",+ " sampling_topk=1,\n",+ " sampling_topp=1.0,\n",+ " sampling_temperature=1.0,\n",+ " repetition_penalty=1.0,\n",+ " regex_string=\"\",\n",")\n","output = llm(\"What is the largest rainforest in the world?\")\n","print(output)\n",@@ -64,7 +64,9 @@"\n","\n","# Example 4: Streaming output\n",- "llm = TitanTakeoffPro(streaming=True, callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]))\n",+ "llm = TitanTakeoffPro(\n",+ " streaming=True, callback_manager=CallbackManager([StreamingStdOutCallbackHandler()])\n",+ ")\n","prompt = \"What is the capital of France?\"\n","llm(prompt)\n","\n",diff --git a/docs/docs/integrations/llms/vllm.ipynb b/docs/docs/integrations/llms/vllm.ipynbindex b4f491f47a..c828d378af 100644--- a/docs/docs/integrations/llms/vllm.ipynb+++ b/docs/docs/integrations/llms/vllm.ipynb@@ -72,12 +72,13 @@"source": ["from langchain.llms import VLLM\n","\n",- "llm = VLLM(model=\"mosaicml/mpt-7b\",\n",- " trust_remote_code=True, # mandatory for hf models\n",- " max_new_tokens=128,\n",- " top_k=10,\n",- " top_p=0.95,\n",- " temperature=0.8,\n",+ "llm = VLLM(\n",+ " model=\"mosaicml/mpt-7b\",\n",+ " trust_remote_code=True, # mandatory for hf models\n",+ " max_new_tokens=128,\n",+ " top_k=10,\n",+ " top_p=0.95,\n",+ " temperature=0.8,\n",")\n","\n","print(llm(\"What is the capital of France ?\"))"@@ -163,9 +164,10 @@"source": ["from langchain.llms import VLLM\n","\n",- "llm = VLLM(model=\"mosaicml/mpt-30b\",\n",- " tensor_parallel_size=4,\n",- " trust_remote_code=True, # mandatory for hf models\n",+ "llm = VLLM(\n",+ " model=\"mosaicml/mpt-30b\",\n",+ " tensor_parallel_size=4,\n",+ " trust_remote_code=True, # mandatory for hf models\n",")\n","\n","llm(\"What is the future of AI?\")"@@ -211,7 +213,7 @@" openai_api_key=\"EMPTY\",\n"," openai_api_base=\"http://localhost:8000/v1\",\n"," model_name=\"tiiuae/falcon-7b\",\n",- " model_kwargs={\"stop\": [\".\"]}\n",+ " model_kwargs={\"stop\": [\".\"]},\n",")\n","print(llm(\"Rome is\"))"]diff --git a/docs/docs/integrations/llms/xinference.ipynb b/docs/docs/integrations/llms/xinference.ipynbindex 037470e8a0..bfa1cd300c 100644--- a/docs/docs/integrations/llms/xinference.ipynb+++ b/docs/docs/integrations/llms/xinference.ipynb@@ -90,8 +90,7 @@"from langchain.llms import Xinference\n","\n","llm = Xinference(\n",- " server_url=\"http://0.0.0.0:9997\",\n",- " model_uid = \"7167b2b0-2a04-11ee-83f0-d29396a3f064\"\n",+ " server_url=\"http://0.0.0.0:9997\", model_uid=\"7167b2b0-2a04-11ee-83f0-d29396a3f064\"\n",")\n","\n","llm(\n",diff --git a/docs/docs/integrations/memory/aws_dynamodb.ipynb b/docs/docs/integrations/memory/aws_dynamodb.ipynbindex d593ece83c..2890dbb859 100644--- a/docs/docs/integrations/memory/aws_dynamodb.ipynb+++ b/docs/docs/integrations/memory/aws_dynamodb.ipynb@@ -198,8 +198,14 @@"\n","composite_table = dynamodb.create_table(\n"," TableName=\"CompositeTable\",\n",- " KeySchema=[{\"AttributeName\": \"PK\", \"KeyType\": \"HASH\"}, {\"AttributeName\": \"SK\", \"KeyType\": \"RANGE\"}],\n",- " AttributeDefinitions=[{\"AttributeName\": \"PK\", \"AttributeType\": \"S\"}, {\"AttributeName\": \"SK\", \"AttributeType\": \"S\"}],\n",+ " KeySchema=[\n",+ " {\"AttributeName\": \"PK\", \"KeyType\": \"HASH\"},\n",+ " {\"AttributeName\": \"SK\", \"KeyType\": \"RANGE\"},\n",+ " ],\n",+ " AttributeDefinitions=[\n",+ " {\"AttributeName\": \"PK\", \"AttributeType\": \"S\"},\n",+ " {\"AttributeName\": \"SK\", \"AttributeType\": \"S\"},\n",+ " ],\n"," BillingMode=\"PAY_PER_REQUEST\",\n",")\n","\n",@@ -211,7 +217,7 @@"\n","my_key = {\n"," \"PK\": \"session_id::0\",\n",- " \"SK\": \"langchain_history\",\n",+ " \"SK\": \"langchain_history\",\n","}\n","\n","composite_key_history = DynamoDBChatMessageHistory(\n",@@ -336,7 +342,7 @@"metadata": {},"outputs": [],"source": [- "agent_chain.run(input=\"Who am I?\")\n"+ "agent_chain.run(input=\"Who am I?\")"]}],diff --git a/docs/docs/integrations/memory/elasticsearch_chat_message_history.ipynb b/docs/docs/integrations/memory/elasticsearch_chat_message_history.ipynbindex 8c2da128fe..886ee24fd5 100644--- a/docs/docs/integrations/memory/elasticsearch_chat_message_history.ipynb+++ b/docs/docs/integrations/memory/elasticsearch_chat_message_history.ipynb@@ -72,9 +72,7 @@"# Note: see Authentication section for various authentication methods\n","\n","history = ElasticsearchChatMessageHistory(\n",- " es_url=es_url,\n",- " index=\"test-history\",\n",- " session_id=\"test-session\"\n",+ " es_url=es_url, index=\"test-history\", session_id=\"test-session\"\n",")"]},diff --git a/docs/docs/integrations/memory/rockset_chat_message_history.ipynb b/docs/docs/integrations/memory/rockset_chat_message_history.ipynbindex 16fda530a6..c6a2adeef1 100644--- a/docs/docs/integrations/memory/rockset_chat_message_history.ipynb+++ b/docs/docs/integrations/memory/rockset_chat_message_history.ipynb@@ -58,11 +58,10 @@"history = RocksetChatMessageHistory(\n"," session_id=\"MySession\",\n"," client=RocksetClient(\n",- " api_key=\"YOUR API KEY\", \n",- " host=Regions.usw2a1 # us-west-2 Oregon\n",+ " api_key=\"YOUR API KEY\", host=Regions.usw2a1 # us-west-2 Oregon\n"," ),\n"," collection=\"langchain_demo\",\n",- " sync=True\n",+ " sync=True,\n",")\n","history.add_user_message(\"hi!\")\n","history.add_ai_message(\"whats up?\")\n",diff --git a/docs/docs/integrations/memory/singlestoredb_chat_message_history.ipynb b/docs/docs/integrations/memory/singlestoredb_chat_message_history.ipynbindex 3f102199fa..852733fa56 100644--- a/docs/docs/integrations/memory/singlestoredb_chat_message_history.ipynb+++ b/docs/docs/integrations/memory/singlestoredb_chat_message_history.ipynb@@ -1,65 +1,64 @@{- "cells": [- {- "attachments": {},- "cell_type": "markdown",- "id": "91c6a7ef",- "metadata": {},- "source": [- "# SingleStoreDB\n",- "\n",- "This notebook goes over how to use SingleStoreDB to store chat message history."- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "d15e3302",- "metadata": {},- "outputs": [],- "source": [- "from langchain.memory import SingleStoreDBChatMessageHistory\n",- "\n",- "history = SingleStoreDBChatMessageHistory(\n",- " session_id=\"foo\",\n",- " host=\"root:pass@localhost:3306/db\"\n",- ")\n",- "\n",- "history.add_user_message(\"hi!\")\n",- "\n",- "history.add_ai_message(\"whats up?\")"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "64fc465e",- "metadata": {},- "outputs": [],- "source": [- "history.messages"- ]- }- ],- "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.11.2"- }- },- "nbformat": 4,- "nbformat_minor": 5+ "cells": [+ {+ "attachments": {},+ "cell_type": "markdown",+ "id": "91c6a7ef",+ "metadata": {},+ "source": [+ "# SingleStoreDB\n",+ "\n",+ "This notebook goes over how to use SingleStoreDB to store chat message history."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "d15e3302",+ "metadata": {},+ "outputs": [],+ "source": [+ "from langchain.memory import SingleStoreDBChatMessageHistory\n",+ "\n",+ "history = SingleStoreDBChatMessageHistory(\n",+ " session_id=\"foo\", host=\"root:pass@localhost:3306/db\"\n",+ ")\n",+ "\n",+ "history.add_user_message(\"hi!\")\n",+ "\n",+ "history.add_ai_message(\"whats up?\")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "64fc465e",+ "metadata": {},+ "outputs": [],+ "source": [+ "history.messages"+ ]+ }+ ],+ "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.11.2"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5}\ No newline at end of filediff --git a/docs/docs/integrations/memory/sql_chat_message_history.ipynb b/docs/docs/integrations/memory/sql_chat_message_history.ipynbindex 37cedfe4c9..5d1e40c069 100644--- a/docs/docs/integrations/memory/sql_chat_message_history.ipynb+++ b/docs/docs/integrations/memory/sql_chat_message_history.ipynb@@ -59,12 +59,11 @@"from langchain.memory.chat_message_histories import SQLChatMessageHistory\n","\n","chat_message_history = SQLChatMessageHistory(\n",- "\tsession_id='test_session',\n",- "\tconnection_string='sqlite:///sqlite.db'\n",+ " session_id=\"test_session\", connection_string=\"sqlite:///sqlite.db\"\n",")\n","\n",- "chat_message_history.add_user_message('Hello')\n",- "chat_message_history.add_ai_message('Hi')"+ "chat_message_history.add_user_message(\"Hello\")\n",+ "chat_message_history.add_ai_message(\"Hi\")"]},{@@ -140,60 +139,58 @@"\n","\n","class CustomMessage(Base):\n",- "\t__tablename__ = 'custom_message_store'\n",+ " __tablename__ = \"custom_message_store\"\n","\n",- "\tid = Column(Integer, primary_key=True)\n",- "\tsession_id = Column(Text)\n",- "\ttype = Column(Text)\n",- "\tcontent = Column(Text)\n",- "\tcreated_at = Column(DateTime)\n",- "\tauthor_email = Column(Text)\n",+ " id = Column(Integer, primary_key=True)\n",+ " session_id = Column(Text)\n",+ " type = Column(Text)\n",+ " content = Column(Text)\n",+ " created_at = Column(DateTime)\n",+ " author_email = Column(Text)\n","\n","\n","class CustomMessageConverter(BaseMessageConverter):\n",- "\tdef __init__(self, author_email: str):\n",- "\t\tself.author_email = author_email\n",- "\t\n",- "\tdef from_sql_model(self, sql_message: Any) -> BaseMessage:\n",- "\t\tif sql_message.type == 'human':\n",- "\t\t\treturn HumanMessage(\n",- "\t\t\t\tcontent=sql_message.content,\n",- "\t\t\t)\n",- "\t\telif sql_message.type == 'ai':\n",- "\t\t\treturn AIMessage(\n",- "\t\t\t\tcontent=sql_message.content,\n",- "\t\t\t)\n",- "\t\telif sql_message.type == 'system':\n",- "\t\t\treturn SystemMessage(\n",- "\t\t\t\tcontent=sql_message.content,\n",- "\t\t\t)\n",- "\t\telse:\n",- "\t\t\traise ValueError(f'Unknown message type: {sql_message.type}')\n",- "\t\n",- "\tdef to_sql_model(self, message: BaseMessage, session_id: str) -> Any:\n",- "\t\tnow = datetime.now()\n",- "\t\treturn CustomMessage(\n",- "\t\t\tsession_id=session_id,\n",- "\t\t\ttype=message.type,\n",- "\t\t\tcontent=message.content,\n",- "\t\t\tcreated_at=now,\n",- "\t\t\tauthor_email=self.author_email\n",- "\t\t)\n",- "\t\n",- "\tdef get_sql_model_class(self) -> Any:\n",- "\t\treturn CustomMessage\n",+ " def __init__(self, author_email: str):\n",+ " self.author_email = author_email\n",+ "\n",+ " def from_sql_model(self, sql_message: Any) -> BaseMessage:\n",+ " if sql_message.type == \"human\":\n",+ " return HumanMessage(\n",+ " content=sql_message.content,\n",+ " )\n",+ " elif sql_message.type == \"ai\":\n",+ " return AIMessage(\n",+ " content=sql_message.content,\n",+ " )\n",+ " elif sql_message.type == \"system\":\n",+ " return SystemMessage(\n",+ " content=sql_message.content,\n",+ " )\n",+ " else:\n",+ " raise ValueError(f\"Unknown message type: {sql_message.type}\")\n",+ "\n",+ " def to_sql_model(self, message: BaseMessage, session_id: str) -> Any:\n",+ " now = datetime.now()\n",+ " return CustomMessage(\n",+ " session_id=session_id,\n",+ " type=message.type,\n",+ " content=message.content,\n",+ " created_at=now,\n",+ " author_email=self.author_email,\n",+ " )\n",+ "\n",+ " def get_sql_model_class(self) -> Any:\n",+ " return CustomMessage\n","\n","\n","chat_message_history = SQLChatMessageHistory(\n",- "\tsession_id='test_session',\n",- "\tconnection_string='sqlite:///sqlite.db',\n",- "\tcustom_message_converter=CustomMessageConverter(\n",- "\t\tauthor_email='[email protected]'\n",- " )\n",+ " session_id=\"test_session\",\n",+ " connection_string=\"sqlite:///sqlite.db\",\n",+ " custom_message_converter=CustomMessageConverter(author_email=\"[email protected]\"),\n",")\n","\n",- "chat_message_history.add_user_message('Hello')\n",- "chat_message_history.add_ai_message('Hi')"+ "chat_message_history.add_user_message(\"Hello\")\n",+ "chat_message_history.add_ai_message(\"Hi\")"]},{diff --git a/docs/docs/integrations/memory/streamlit_chat_message_history.ipynb b/docs/docs/integrations/memory/streamlit_chat_message_history.ipynbindex 0df6e4293e..8c865f921d 100644--- a/docs/docs/integrations/memory/streamlit_chat_message_history.ipynb+++ b/docs/docs/integrations/memory/streamlit_chat_message_history.ipynb@@ -64,7 +64,6 @@"metadata": {},"outputs": [],"source": [- "\n","from langchain.memory import ConversationBufferMemory\n","from langchain.memory.chat_message_histories import StreamlitChatMessageHistory\n","\n",@@ -73,7 +72,7 @@"\n","memory = ConversationBufferMemory(memory_key=\"history\", chat_memory=msgs)\n","if len(msgs.messages) == 0:\n",- " msgs.add_ai_message(\"How can I help you?\")\n"+ " msgs.add_ai_message(\"How can I help you?\")"]},{@@ -86,6 +85,7 @@"from langchain.chains import LLMChain\n","from langchain.llms import OpenAI\n","from langchain.prompts import PromptTemplate\n",+ "\n","template = \"\"\"You are an AI chatbot having a conversation with a human.\n","\n","{history}\n",diff --git a/docs/docs/integrations/memory/upstash_redis_chat_message_history.ipynb b/docs/docs/integrations/memory/upstash_redis_chat_message_history.ipynbindex bf87de7d38..4a44ebfeeb 100644--- a/docs/docs/integrations/memory/upstash_redis_chat_message_history.ipynb+++ b/docs/docs/integrations/memory/upstash_redis_chat_message_history.ipynb@@ -15,12 +15,16 @@"metadata": {},"outputs": [],"source": [- "from langchain.memory.chat_message_histories.upstash_redis import UpstashRedisChatMessageHistory\n",+ "from langchain.memory.chat_message_histories.upstash_redis import (\n",+ " UpstashRedisChatMessageHistory,\n",+ ")\n","\n","URL = \"<UPSTASH_REDIS_REST_URL>\"\n","TOKEN = \"<UPSTASH_REDIS_REST_TOKEN>\"\n","\n",- "history = UpstashRedisChatMessageHistory(url=URL, token=TOKEN, ttl=10, session_id=\"my-test-session\")\n",+ "history = UpstashRedisChatMessageHistory(\n",+ " url=URL, token=TOKEN, ttl=10, session_id=\"my-test-session\"\n",+ ")\n","\n","history.add_user_message(\"hello llm!\")\n","history.add_ai_message(\"hello user!\")"diff --git a/docs/docs/integrations/memory/xata_chat_message_history.ipynb b/docs/docs/integrations/memory/xata_chat_message_history.ipynbindex ef65a20d89..e95f7b4040 100644--- a/docs/docs/integrations/memory/xata_chat_message_history.ipynb+++ b/docs/docs/integrations/memory/xata_chat_message_history.ipynb@@ -78,10 +78,7 @@"from langchain.memory import XataChatMessageHistory\n","\n","history = XataChatMessageHistory(\n",- " session_id=\"session-1\",\n",- " api_key=api_key,\n",- " db_url=db_url,\n",- " table_name=\"memory\"\n",+ " session_id=\"session-1\", api_key=api_key, db_url=db_url, table_name=\"memory\"\n",")\n","\n","history.add_user_message(\"hi!\")\n",@@ -165,10 +162,12 @@"texts = [\n"," \"Xata is a Serverless Data platform based on PostgreSQL\",\n"," \"Xata offers a built-in vector type that can be used to store and query vectors\",\n",- " \"Xata includes similarity search\"\n",+ " \"Xata includes similarity search\",\n","]\n","\n",- "vector_store = XataVectorStore.from_texts(texts, embeddings, api_key=api_key, db_url=db_url, table_name=\"docs\")"+ "vector_store = XataVectorStore.from_texts(\n",+ " texts, embeddings, api_key=api_key, db_url=db_url, table_name=\"docs\"\n",+ ")"]},{@@ -195,12 +194,14 @@"from uuid import uuid4\n","\n","chat_memory = XataChatMessageHistory(\n",- " session_id=str(uuid4()), # needs to be unique per user session\n",+ " session_id=str(uuid4()), # needs to be unique per user session\n"," api_key=api_key,\n"," db_url=db_url,\n",- " table_name=\"memory\"\n",+ " table_name=\"memory\",\n",")\n",- "memory = ConversationBufferMemory(memory_key=\"chat_history\", chat_memory=chat_memory, return_messages=True)"+ "memory = ConversationBufferMemory(\n",+ " memory_key=\"chat_history\", chat_memory=chat_memory, return_messages=True\n",+ ")"]},{@@ -221,9 +222,9 @@"from langchain.chat_models import ChatOpenAI\n","\n","tool = create_retriever_tool(\n",- " vector_store.as_retriever(), \n",+ " vector_store.as_retriever(),\n"," \"search_docs\",\n",- " \"Searches and returns documents from the Xata manual. Useful when you need to answer questions about Xata.\"\n",+ " \"Searches and returns documents from the Xata manual. Useful when you need to answer questions about Xata.\",\n",")\n","tools = [tool]\n","\n",@@ -234,7 +235,8 @@" llm,\n"," agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION,\n"," verbose=True,\n",- " memory=memory)"+ " memory=memory,\n",+ ")"]},{diff --git a/docs/docs/integrations/retrievers/arcee.ipynb b/docs/docs/integrations/retrievers/arcee.ipynbindex 3cf1b62db3..0869098f37 100644--- a/docs/docs/integrations/retrievers/arcee.ipynb+++ b/docs/docs/integrations/retrievers/arcee.ipynb@@ -50,18 +50,18 @@"retriever = ArceeRetriever(\n"," model=\"DALM-PubMed\",\n"," # arcee_api_key=\"ARCEE-API-KEY\", # if not already set in the environment\n",- " arcee_api_url=\"https://custom-api.arcee.ai\", # default is https://api.arcee.ai\n",- " arcee_app_url=\"https://custom-app.arcee.ai\", # default is https://app.arcee.ai\n",+ " arcee_api_url=\"https://custom-api.arcee.ai\", # default is https://api.arcee.ai\n",+ " arcee_app_url=\"https://custom-app.arcee.ai\", # default is https://app.arcee.ai\n"," model_kwargs={\n"," \"size\": 5,\n"," \"filters\": [\n"," {\n"," \"field_name\": \"document\",\n"," \"filter_type\": \"fuzzy_search\",\n",- " \"value\": \"Einstein\"\n",+ " \"value\": \"Einstein\",\n"," }\n",- " ]\n",- " }\n",+ " ],\n",+ " },\n",")"]},@@ -100,16 +100,8 @@"source": ["# Define filters\n","filters = [\n",- " {\n",- " \"field_name\": \"document\",\n",- " \"filter_type\": \"fuzzy_search\",\n",- " \"value\": \"Music\"\n",- " },\n",- " {\n",- " \"field_name\": \"year\",\n",- " \"filter_type\": \"strict_search\",\n",- " \"value\": \"1905\"\n",- " }\n",+ " {\"field_name\": \"document\", \"filter_type\": \"fuzzy_search\", \"value\": \"Music\"},\n",+ " {\"field_name\": \"year\", \"filter_type\": \"strict_search\", \"value\": \"1905\"},\n","]\n","\n","# Retrieve documents with filters and size params\n",diff --git a/docs/docs/integrations/retrievers/cohere.ipynb b/docs/docs/integrations/retrievers/cohere.ipynbindex c7c769c163..f8be6ceb0f 100644--- a/docs/docs/integrations/retrievers/cohere.ipynb+++ b/docs/docs/integrations/retrievers/cohere.ipynb@@ -157,7 +157,7 @@}],"source": [- "_pretty_print(await rag.aget_relevant_documents(\"What is cohere ai?\")) # async version"+ "_pretty_print(await rag.aget_relevant_documents(\"What is cohere ai?\")) # async version"]},{@@ -184,9 +184,12 @@],"source": ["docs = rag.get_relevant_documents(\n",- " \"Does langchain support cohere RAG?\",\n",- " source_documents=[Document(page_content=\"Langchain supports cohere RAG!\"), Document(page_content=\"The sky is blue!\")]\n",- " )\n",+ " \"Does langchain support cohere RAG?\",\n",+ " source_documents=[\n",+ " Document(page_content=\"Langchain supports cohere RAG!\"),\n",+ " Document(page_content=\"The sky is blue!\"),\n",+ " ],\n",+ ")\n","_pretty_print(docs)"]},diff --git a/docs/docs/integrations/retrievers/google_drive.ipynb b/docs/docs/integrations/retrievers/google_drive.ipynbindex d22fb501b1..0d60730f12 100644--- a/docs/docs/integrations/retrievers/google_drive.ipynb+++ b/docs/docs/integrations/retrievers/google_drive.ipynb@@ -53,8 +53,8 @@"source": ["from langchain_googledrive.retrievers import GoogleDriveRetriever\n","\n",- "folder_id=\"root\"\n",- "#folder_id='1yucgL9WGgWZdM1TOuKkeghlPizuzMYb5'\n",+ "folder_id = \"root\"\n",+ "# folder_id='1yucgL9WGgWZdM1TOuKkeghlPizuzMYb5'\n","\n","retriever = GoogleDriveRetriever(\n"," num_results=2,\n",@@ -143,12 +143,12 @@"outputs": [],"source": ["retriever = GoogleDriveRetriever(\n",- " template=\"gdrive-query\", # Search everywhere\n",+ " template=\"gdrive-query\", # Search everywhere\n"," num_results=2, # But take only 2 documents\n",")\n","for doc in retriever.get_relevant_documents(\"machine learning\"):\n"," print(\"---\")\n",- " print(doc.page_content.strip()[:60]+\"...\")"+ " print(doc.page_content.strip()[:60] + \"...\")"]},{@@ -169,13 +169,16 @@"outputs": [],"source": ["from langchain.prompts import PromptTemplate\n",+ "\n","retriever = GoogleDriveRetriever(\n",- " template=PromptTemplate(input_variables=['query'],\n",- " # See https://developers.google.com/drive/api/guides/search-files\n",- " template=\"(fullText contains '{query}') \"\n",- " \"and mimeType='application/vnd.google-apps.document' \"\n",- " \"and modifiedTime > '2000-01-01T00:00:00' \"\n",- " \"and trashed=false\"),\n",+ " template=PromptTemplate(\n",+ " input_variables=[\"query\"],\n",+ " # See https://developers.google.com/drive/api/guides/search-files\n",+ " template=\"(fullText contains '{query}') \"\n",+ " \"and mimeType='application/vnd.google-apps.document' \"\n",+ " \"and modifiedTime > '2000-01-01T00:00:00' \"\n",+ " \"and trashed=false\",\n",+ " ),\n"," num_results=2,\n"," # See https://developers.google.com/drive/api/v3/reference/files/list\n"," includeItemsFromAllDrives=False,\n",@@ -184,7 +187,7 @@"for doc in retriever.get_relevant_documents(\"machine learning\"):\n"," print(f\"{doc.metadata['name']}:\")\n"," print(\"---\")\n",- " print(doc.page_content.strip()[:60]+\"...\")"+ " print(doc.page_content.strip()[:60] + \"...\")"]},{@@ -208,11 +211,11 @@"outputs": [],"source": ["retriever = GoogleDriveRetriever(\n",- " template='gdrive-mime-type-in-folder',\n",+ " template=\"gdrive-mime-type-in-folder\",\n"," folder_id=folder_id,\n",- " mime_type='application/vnd.google-apps.document', # Only Google Docs\n",+ " mime_type=\"application/vnd.google-apps.document\", # Only Google Docs\n"," num_results=2,\n",- " mode='snippets',\n",+ " mode=\"snippets\",\n"," includeItemsFromAllDrives=False,\n"," supportsAllDrives=False,\n",")\n",diff --git a/docs/docs/integrations/retrievers/google_vertex_ai_search.ipynb b/docs/docs/integrations/retrievers/google_vertex_ai_search.ipynbindex 0de3eedb3c..143d5b9c81 100644--- a/docs/docs/integrations/retrievers/google_vertex_ai_search.ipynb+++ b/docs/docs/integrations/retrievers/google_vertex_ai_search.ipynb@@ -30,7 +30,7 @@"metadata": {},"outputs": [],"source": [- "! pip install google-cloud-discoveryengine\n"+ "! pip install google-cloud-discoveryengine"]},{@@ -80,7 +80,7 @@"if \"google.colab\" in sys.modules:\n"," from google.colab import auth as google_auth\n","\n",- " google_auth.authenticate_user()\n"+ " google_auth.authenticate_user()"]},{@@ -163,11 +163,14 @@"metadata": {},"outputs": [],"source": [- "from langchain.retrievers import GoogleVertexAISearchRetriever, GoogleVertexAIMultiTurnSearchRetriever\n",+ "from langchain.retrievers import (\n",+ " GoogleVertexAISearchRetriever,\n",+ " GoogleVertexAIMultiTurnSearchRetriever,\n",+ ")\n","\n","PROJECT_ID = \"<YOUR PROJECT ID>\" # Set to your Project ID\n","LOCATION_ID = \"<YOUR LOCATION>\" # Set to your data store location\n",- "DATA_STORE_ID = \"<YOUR DATA STORE ID>\" # Set to your data store ID\n"+ "DATA_STORE_ID = \"<YOUR DATA STORE ID>\" # Set to your data store ID"]},{@@ -181,7 +184,7 @@" location_id=LOCATION_ID,\n"," data_store_id=DATA_STORE_ID,\n"," max_documents=3,\n",- ")\n"+ ")"]},{@@ -194,7 +197,7 @@"\n","result = retriever.get_relevant_documents(query)\n","for doc in result:\n",- " print(doc)\n"+ " print(doc)"]},{@@ -221,7 +224,7 @@"\n","result = retriever.get_relevant_documents(query)\n","for doc in result:\n",- " print(doc)\n"+ " print(doc)"]},{@@ -247,7 +250,7 @@"\n","result = retriever.get_relevant_documents(query)\n","for doc in result:\n",- " print(doc)\n"+ " print(doc)"]},{@@ -275,7 +278,7 @@"\n","result = retriever.get_relevant_documents(query)\n","for doc in result:\n",- " print(doc)\n"+ " print(doc)"]},{@@ -294,14 +297,12 @@"outputs": [],"source": ["retriever = GoogleVertexAIMultiTurnSearchRetriever(\n",- " project_id=PROJECT_ID,\n",- " location_id=LOCATION_ID,\n",- " data_store_id=DATA_STORE_ID\n",+ " project_id=PROJECT_ID, location_id=LOCATION_ID, data_store_id=DATA_STORE_ID\n",")\n","\n","result = retriever.get_relevant_documents(query)\n","for doc in result:\n",- " print(doc)\n"+ " print(doc)"]}],diff --git a/docs/docs/integrations/retrievers/kay.ipynb b/docs/docs/integrations/retrievers/kay.ipynbindex 9278b4f109..6e7ac153bf 100644--- a/docs/docs/integrations/retrievers/kay.ipynb+++ b/docs/docs/integrations/retrievers/kay.ipynb@@ -59,6 +59,7 @@"source": ["# Setup API key\n","from getpass import getpass\n",+ "\n","KAY_API_KEY = getpass()"]},@@ -72,9 +73,14 @@"import os\n","from langchain.retrievers import KayAiRetriever\n","from kay.rag.retrievers import KayRetriever\n",+ "\n","os.environ[\"KAY_API_KEY\"] = KAY_API_KEY\n",- "retriever = KayAiRetriever.create(dataset_id=\"company\", data_types=[\"10-K\", \"10-Q\", \"PressRelease\"], num_contexts=3)\n",- "docs = retriever.get_relevant_documents(\"What were the biggest strategy changes and partnerships made by Roku in 2023??\")"+ "retriever = KayAiRetriever.create(\n",+ " dataset_id=\"company\", data_types=[\"10-K\", \"10-Q\", \"PressRelease\"], num_contexts=3\n",+ ")\n",+ "docs = retriever.get_relevant_documents(\n",+ " \"What were the biggest strategy changes and partnerships made by Roku in 2023??\"\n",+ ")"]},{diff --git a/docs/docs/integrations/retrievers/sec_filings.ipynb b/docs/docs/integrations/retrievers/sec_filings.ipynbindex 77523a9d3c..3edd9d6ca1 100644--- a/docs/docs/integrations/retrievers/sec_filings.ipynb+++ b/docs/docs/integrations/retrievers/sec_filings.ipynb@@ -44,6 +44,7 @@"source": ["# Setup API keys for Kay and OpenAI\n","from getpass import getpass\n",+ "\n","KAY_API_KEY = getpass()\n","OPENAI_API_KEY = getpass()"]@@ -56,6 +57,7 @@"outputs": [],"source": ["import os\n",+ "\n","os.environ[\"KAY_API_KEY\"] = KAY_API_KEY\n","os.environ[\"OPENAI_API_KEY\"] = OPENAI_API_KEY"]@@ -80,7 +82,9 @@"from langchain.retrievers import KayAiRetriever\n","\n","model = ChatOpenAI(model_name=\"gpt-3.5-turbo\")\n",- "retriever = KayAiRetriever.create(dataset_id=\"company\", data_types=[\"10-K\", \"10-Q\"], num_contexts=6)\n",+ "retriever = KayAiRetriever.create(\n",+ " dataset_id=\"company\", data_types=[\"10-K\", \"10-Q\"], num_contexts=6\n",+ ")\n","qa = ConversationalRetrievalChain.from_llm(model, retriever=retriever)"]},@@ -127,7 +131,7 @@"source": ["questions = [\n"," \"What are patterns in Nvidia's spend over the past three quarters?\",\n",- " #\"What are some recent challenges faced by the renewable energy sector?\",\n",+ " # \"What are some recent challenges faced by the renewable energy sector?\",\n","]\n","chat_history = []\n","\n",diff --git a/docs/docs/integrations/retrievers/self_query/activeloop_deeplake_self_query.ipynb b/docs/docs/integrations/retrievers/self_query/activeloop_deeplake_self_query.ipynbindex 6ec8e29dcf..0c70d7d020 100644--- a/docs/docs/integrations/retrievers/self_query/activeloop_deeplake_self_query.ipynb+++ b/docs/docs/integrations/retrievers/self_query/activeloop_deeplake_self_query.ipynb@@ -169,7 +169,10 @@"]\n","username_or_org = \"<USERNAME_OR_ORG>\"\n","vectorstore = DeepLake.from_documents(\n",- " docs, embeddings, dataset_path=f\"hub://{username_or_org}/self_queery\", overwrite=True,\n",+ " docs,\n",+ " embeddings,\n",+ " dataset_path=f\"hub://{username_or_org}/self_queery\",\n",+ " overwrite=True,\n",")"]},diff --git a/docs/docs/integrations/retrievers/self_query/dashvector.ipynb b/docs/docs/integrations/retrievers/self_query/dashvector.ipynbindex 16884df33d..60d6c11c9a 100644--- a/docs/docs/integrations/retrievers/self_query/dashvector.ipynb+++ b/docs/docs/integrations/retrievers/self_query/dashvector.ipynb@@ -383,7 +383,9 @@],"source": ["# This example specifies a composite filter\n",- "retriever.get_relevant_documents(\"What's a highly rated (above 8.5) science fiction film?\")"+ "retriever.get_relevant_documents(\n",+ " \"What's a highly rated (above 8.5) science fiction film?\"\n",+ ")"]},{diff --git a/docs/docs/integrations/retrievers/self_query/elasticsearch_self_query.ipynb b/docs/docs/integrations/retrievers/self_query/elasticsearch_self_query.ipynbindex 00aaf80cb3..183da98575 100644--- a/docs/docs/integrations/retrievers/self_query/elasticsearch_self_query.ipynb+++ b/docs/docs/integrations/retrievers/self_query/elasticsearch_self_query.ipynb@@ -110,7 +110,10 @@" ),\n","]\n","vectorstore = ElasticsearchStore.from_documents(\n",- " docs, embeddings, index_name=\"elasticsearch-self-query-demo\", es_url=\"http://localhost:9200\"\n",+ " docs,\n",+ " embeddings,\n",+ " index_name=\"elasticsearch-self-query-demo\",\n",+ " es_url=\"http://localhost:9200\",\n",")"]},@@ -302,7 +305,9 @@}],"source": [- "retriever.get_relevant_documents(\"what animated or comedy movies have been released in the last 30 years about animated toys?\")"+ "retriever.get_relevant_documents(\n",+ " \"what animated or comedy movies have been released in the last 30 years about animated toys?\"\n",+ ")"]},{diff --git a/docs/docs/integrations/retrievers/self_query/milvus_self_query.ipynb b/docs/docs/integrations/retrievers/self_query/milvus_self_query.ipynbindex eb7cc2e9d3..2a779fc6a9 100644--- a/docs/docs/integrations/retrievers/self_query/milvus_self_query.ipynb+++ b/docs/docs/integrations/retrievers/self_query/milvus_self_query.ipynb@@ -81,21 +81,36 @@"outputs": [],"source": ["docs = [\n",- " Document(page_content=\"A bunch of scientists bring back dinosaurs and mayhem breaks loose\", metadata={\"year\": 1993, \"rating\": 7.7, \"genre\": \"action\"}),\n",- " Document(page_content=\"Leo DiCaprio gets lost in a dream within a dream within a dream within a ...\", metadata={\"year\": 2010,\"genre\": \"thriller\", \"rating\": 8.2}),\n",- " Document(page_content=\"A bunch of normal-sized women are supremely wholesome and some men pine after them\", metadata={\"year\": 2019, \"rating\": 8.3, \"genre\": \"drama\"}),\n",- " Document(page_content=\"Three men walk into the Zone, three men walk out of the Zone\", metadata={\"year\": 1979, \"rating\": 9.9, \"genre\": \"science fiction\"}),\n"," Document(\n",- " page_content='A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea',\n",- " metadata={\"year\": 2006, \"genre\": \"thriller\", 'rating': 9.0},\n",+ " page_content=\"A bunch of scientists bring back dinosaurs and mayhem breaks loose\",\n",+ " metadata={\"year\": 1993, \"rating\": 7.7, \"genre\": \"action\"},\n",+ " ),\n",+ " Document(\n",+ " page_content=\"Leo DiCaprio gets lost in a dream within a dream within a dream within a ...\",\n",+ " metadata={\"year\": 2010, \"genre\": \"thriller\", \"rating\": 8.2},\n",+ " ),\n",+ " Document(\n",+ " page_content=\"A bunch of normal-sized women are supremely wholesome and some men pine after them\",\n",+ " metadata={\"year\": 2019, \"rating\": 8.3, \"genre\": \"drama\"},\n",+ " ),\n",+ " Document(\n",+ " page_content=\"Three men walk into the Zone, three men walk out of the Zone\",\n",+ " metadata={\"year\": 1979, \"rating\": 9.9, \"genre\": \"science fiction\"},\n",+ " ),\n",+ " Document(\n",+ " page_content=\"A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea\",\n",+ " metadata={\"year\": 2006, \"genre\": \"thriller\", \"rating\": 9.0},\n",+ " ),\n",+ " Document(\n",+ " page_content=\"Toys come alive and have a blast doing so\",\n",+ " metadata={\"year\": 1995, \"genre\": \"animated\", \"rating\": 9.3},\n"," ),\n",- " Document(page_content=\"Toys come alive and have a blast doing so\", metadata={\"year\": 1995, \"genre\": \"animated\", \"rating\": 9.3 }),\n","]\n","\n","vector_store = Milvus.from_documents(\n"," docs,\n"," embedding=embeddings,\n",- " connection_args={\"uri\": 'Use your uri:)', \"token\":'Use your token:)'}\n",+ " connection_args={\"uri\": \"Use your uri:)\", \"token\": \"Use your token:)\"},\n",")"]},@@ -233,7 +248,9 @@],"source": ["# This example only specifies a query and a filter\n",- "retriever.get_relevant_documents(\"I want to watch a movie about toys rated higher than 9\")"+ "retriever.get_relevant_documents(\n",+ " \"I want to watch a movie about toys rated higher than 9\"\n",+ ")"]},{@@ -261,7 +278,9 @@],"source": ["# This example specifies a composite filter\n",- "retriever.get_relevant_documents(\"What's a highly rated (above or equal 9) thriller film?\")"+ "retriever.get_relevant_documents(\n",+ " \"What's a highly rated (above or equal 9) thriller film?\"\n",+ ")"]},{@@ -313,12 +332,12 @@"outputs": [],"source": ["retriever = SelfQueryRetriever.from_llm(\n",- " llm, \n",- " vector_store, \n",- " document_content_description, \n",- " metadata_field_info, \n",+ " llm,\n",+ " vector_store,\n",+ " document_content_description,\n",+ " metadata_field_info,\n"," verbose=True,\n",- " enable_limit=True\n",+ " enable_limit=True,\n",")"]},diff --git a/docs/docs/integrations/retrievers/self_query/opensearch_self_query.ipynb b/docs/docs/integrations/retrievers/self_query/opensearch_self_query.ipynbindex 0045176faa..4ffc98b96e 100644--- a/docs/docs/integrations/retrievers/self_query/opensearch_self_query.ipynb+++ b/docs/docs/integrations/retrievers/self_query/opensearch_self_query.ipynb@@ -1,440 +1,447 @@{- "cells": [- {- "cell_type": "markdown",- "id": "13afcae7",- "metadata": {},- "source": [- "# OpenSearch\n",- "\n",- "> [OpenSearch](https://opensearch.org/) is a scalable, flexible, and extensible open-source software suite for search, analytics, and observability applications licensed under Apache 2.0. `OpenSearch` is a distributed search and analytics engine based on `Apache Lucene`.\n",- "\n",- "In this notebook, we'll demo the `SelfQueryRetriever` with an `OpenSearch` vector store."- ]- },- {- "cell_type": "markdown",- "id": "68e75fb9",- "metadata": {},- "source": [- "## Creating an OpenSearch vector store\n",- "\n",- "First, we'll want to create an `OpenSearch` vector store and seed it with some data. We've created a small demo set of documents that contain summaries of movies.\n",- "\n",- "**Note:** The self-query retriever requires you to have `lark` installed (`pip install lark`). We also need the `opensearch-py` package."- ]- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "!pip install lark opensearch-py"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "id": "6078a74d"- },+ "cells": [+ {+ "cell_type": "markdown",+ "id": "13afcae7",+ "metadata": {},+ "source": [+ "# OpenSearch\n",+ "\n",+ "> [OpenSearch](https://opensearch.org/) is a scalable, flexible, and extensible open-source software suite for search, analytics, and observability applications licensed under Apache 2.0. `OpenSearch` is a distributed search and analytics engine based on `Apache Lucene`.\n",+ "\n",+ "In this notebook, we'll demo the `SelfQueryRetriever` with an `OpenSearch` vector store."+ ]+ },+ {+ "cell_type": "markdown",+ "id": "68e75fb9",+ "metadata": {},+ "source": [+ "## Creating an OpenSearch vector store\n",+ "\n",+ "First, we'll want to create an `OpenSearch` vector store and seed it with some data. We've created a small demo set of documents that contain summaries of movies.\n",+ "\n",+ "**Note:** The self-query retriever requires you to have `lark` installed (`pip install lark`). We also need the `opensearch-py` package."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "!pip install lark opensearch-py"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "id": "6078a74d"+ },+ {+ "cell_type": "code",+ "execution_count": 3,+ "id": "cb4a5787",+ "metadata": {+ "tags": []+ },+ "outputs": [{- "cell_type": "code",- "execution_count": 3,- "id": "cb4a5787",- "metadata": {- "tags": []- },- "outputs": [- {- "name": "stdin",- "output_type": "stream",- "text": [- "OpenAI API Key: \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\n"- ]- }- ],- "source": [- "from langchain.schema import Document\n",- "from langchain.embeddings.openai import OpenAIEmbeddings\n",- "from langchain.vectorstores import OpenSearchVectorSearch\n",- "import os\n",- "import getpass\n",- "\n",- "os.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"OpenAI API Key:\")\n",- "\n",- "embeddings = OpenAIEmbeddings()"- ]- },+ "name": "stdin",+ "output_type": "stream",+ "text": [+ "OpenAI API Key: ········\n"+ ]+ }+ ],+ "source": [+ "from langchain.schema import Document\n",+ "from langchain.embeddings.openai import OpenAIEmbeddings\n",+ "from langchain.vectorstores import OpenSearchVectorSearch\n",+ "import os\n",+ "import getpass\n",+ "\n",+ "os.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"OpenAI API Key:\")\n",+ "\n",+ "embeddings = OpenAIEmbeddings()"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 8,+ "id": "bcbe04d9",+ "metadata": {+ "tags": []+ },+ "outputs": [],+ "source": [+ "docs = [\n",+ " Document(\n",+ " page_content=\"A bunch of scientists bring back dinosaurs and mayhem breaks loose\",\n",+ " metadata={\"year\": 1993, \"rating\": 7.7, \"genre\": \"science fiction\"},\n",+ " ),\n",+ " Document(\n",+ " page_content=\"Leo DiCaprio gets lost in a dream within a dream within a dream within a ...\",\n",+ " metadata={\"year\": 2010, \"director\": \"Christopher Nolan\", \"rating\": 8.2},\n",+ " ),\n",+ " Document(\n",+ " page_content=\"A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea\",\n",+ " metadata={\"year\": 2006, \"director\": \"Satoshi Kon\", \"rating\": 8.6},\n",+ " ),\n",+ " Document(\n",+ " page_content=\"A bunch of normal-sized women are supremely wholesome and some men pine after them\",\n",+ " metadata={\"year\": 2019, \"director\": \"Greta Gerwig\", \"rating\": 8.3},\n",+ " ),\n",+ " Document(\n",+ " page_content=\"Toys come alive and have a blast doing so\",\n",+ " metadata={\"year\": 1995, \"genre\": \"animated\"},\n",+ " ),\n",+ " Document(\n",+ " page_content=\"Three men walk into the Zone, three men walk out of the Zone\",\n",+ " metadata={\n",+ " \"year\": 1979,\n",+ " \"rating\": 9.9,\n",+ " \"director\": \"Andrei Tarkovsky\",\n",+ " \"genre\": \"science fiction\",\n",+ " },\n",+ " ),\n",+ "]\n",+ "vectorstore = OpenSearchVectorSearch.from_documents(\n",+ " docs,\n",+ " embeddings,\n",+ " index_name=\"opensearch-self-query-demo\",\n",+ " opensearch_url=\"http://localhost:9200\",\n",+ ")"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "5ecaab6d",+ "metadata": {},+ "source": [+ "## Creating our self-querying retriever\n",+ "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."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 9,+ "id": "86e34dbf",+ "metadata": {+ "tags": []+ },+ "outputs": [],+ "source": [+ "from langchain.llms import OpenAI\n",+ "from langchain.retrievers.self_query.base import SelfQueryRetriever\n",+ "from langchain.chains.query_constructor.base import AttributeInfo\n",+ "\n",+ "metadata_field_info = [\n",+ " AttributeInfo(\n",+ " name=\"genre\",\n",+ " description=\"The genre of the movie\",\n",+ " type=\"string or list[string]\",\n",+ " ),\n",+ " AttributeInfo(\n",+ " name=\"year\",\n",+ " description=\"The year the movie was released\",\n",+ " type=\"integer\",\n",+ " ),\n",+ " AttributeInfo(\n",+ " name=\"director\",\n",+ " description=\"The name of the movie director\",\n",+ " type=\"string\",\n",+ " ),\n",+ " AttributeInfo(\n",+ " name=\"rating\", description=\"A 1-10 rating for the movie\", type=\"float\"\n",+ " ),\n",+ "]\n",+ "document_content_description = \"Brief summary of a movie\"\n",+ "llm = OpenAI(temperature=0)\n",+ "retriever = SelfQueryRetriever.from_llm(\n",+ " llm, vectorstore, document_content_description, metadata_field_info, verbose=True\n",+ ")"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "ea9df8d4",+ "metadata": {},+ "source": [+ "## Testing it out\n",+ "And now we can try actually using our retriever!"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 10,+ "id": "38a126e9",+ "metadata": {},+ "outputs": [{- "cell_type": "code",- "execution_count": 8,- "id": "bcbe04d9",- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "docs = [\n",- " Document(\n",- " page_content=\"A bunch of scientists bring back dinosaurs and mayhem breaks loose\",\n",- " metadata={\"year\": 1993, \"rating\": 7.7, \"genre\": \"science fiction\"},\n",- " ),\n",- " Document(\n",- " page_content=\"Leo DiCaprio gets lost in a dream within a dream within a dream within a ...\",\n",- " metadata={\"year\": 2010, \"director\": \"Christopher Nolan\", \"rating\": 8.2},\n",- " ),\n",- " Document(\n",- " page_content=\"A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea\",\n",- " metadata={\"year\": 2006, \"director\": \"Satoshi Kon\", \"rating\": 8.6},\n",- " ),\n",- " Document(\n",- " page_content=\"A bunch of normal-sized women are supremely wholesome and some men pine after them\",\n",- " metadata={\"year\": 2019, \"director\": \"Greta Gerwig\", \"rating\": 8.3},\n",- " ),\n",- " Document(\n",- " page_content=\"Toys come alive and have a blast doing so\",\n",- " metadata={\"year\": 1995, \"genre\": \"animated\"},\n",- " ),\n",- " Document(\n",- " page_content=\"Three men walk into the Zone, three men walk out of the Zone\",\n",- " metadata={\n",- " \"year\": 1979,\n",- " \"rating\": 9.9,\n",- " \"director\": \"Andrei Tarkovsky\",\n",- " \"genre\": \"science fiction\",\n",- " },\n",- " ),\n",- "]\n",- "vectorstore = OpenSearchVectorSearch.from_documents(\n",- " docs, embeddings, index_name=\"opensearch-self-query-demo\", opensearch_url=\"http://localhost:9200\"\n",- ")"- ]+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "query='dinosaur' filter=None limit=None\n"+ ]},{- "cell_type": "markdown",- "id": "5ecaab6d",- "metadata": {},- "source": [- "## Creating our self-querying retriever\n",- "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."+ "data": {+ "text/plain": [+ "[Document(page_content='A bunch of scientists bring back dinosaurs and mayhem breaks loose', metadata={'year': 1993, 'rating': 7.7, 'genre': 'science fiction'}),\n",+ " Document(page_content='Toys come alive and have a blast doing so', metadata={'year': 1995, 'genre': 'animated'}),\n",+ " 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}),\n",+ " 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'})]"]- },+ },+ "execution_count": 10,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "# This example only specifies a relevant query\n",+ "retriever.get_relevant_documents(\"What are some movies about dinosaurs\")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 11,+ "id": "60bf0074-e65e-4558-a4f2-8190f3e4e2f9",+ "metadata": {},+ "outputs": [{- "cell_type": "code",- "execution_count": 9,- "id": "86e34dbf",- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "from langchain.llms import OpenAI\n",- "from langchain.retrievers.self_query.base import SelfQueryRetriever\n",- "from langchain.chains.query_constructor.base import AttributeInfo\n",- "\n",- "metadata_field_info = [\n",- " AttributeInfo(\n",- " name=\"genre\",\n",- " description=\"The genre of the movie\",\n",- " type=\"string or list[string]\",\n",- " ),\n",- " AttributeInfo(\n",- " name=\"year\",\n",- " description=\"The year the movie was released\",\n",- " type=\"integer\",\n",- " ),\n",- " AttributeInfo(\n",- " name=\"director\",\n",- " description=\"The name of the movie director\",\n",- " type=\"string\",\n",- " ),\n",- " AttributeInfo(\n",- " name=\"rating\", description=\"A 1-10 rating for the movie\", type=\"float\"\n",- " ),\n",- "]\n",- "document_content_description = \"Brief summary of a movie\"\n",- "llm = OpenAI(temperature=0)\n",- "retriever = SelfQueryRetriever.from_llm(\n",- " llm, vectorstore, document_content_description, metadata_field_info, verbose=True\n",- ")"- ]+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "query=' ' filter=Comparison(comparator=<Comparator.GT: 'gt'>, attribute='rating', value=8.5) limit=None\n"+ ]},{- "cell_type": "markdown",- "id": "ea9df8d4",- "metadata": {},- "source": [- "## Testing it out\n",- "And now we can try actually using our retriever!"+ "data": {+ "text/plain": [+ "[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'}),\n",+ " 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})]"]- },- {- "cell_type": "code",- "execution_count": 10,- "id": "38a126e9",- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "query='dinosaur' filter=None limit=None\n"- ]- },- {- "data": {- "text/plain": [- "[Document(page_content='A bunch of scientists bring back dinosaurs and mayhem breaks loose', metadata={'year': 1993, 'rating': 7.7, 'genre': 'science fiction'}),\n",- " Document(page_content='Toys come alive and have a blast doing so', metadata={'year': 1995, 'genre': 'animated'}),\n",- " 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}),\n",- " 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'})]"- ]- },- "execution_count": 10,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "# This example only specifies a relevant query\n",- "retriever.get_relevant_documents(\"What are some movies about dinosaurs\")"- ]- },+ },+ "execution_count": 11,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "# This example only specifies a filter\n",+ "retriever.get_relevant_documents(\"I want to watch a movie rated higher than 8.5\")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 12,+ "id": "b19d4da0",+ "metadata": {},+ "outputs": [{- "cell_type": "code",- "execution_count": 11,- "id": "60bf0074-e65e-4558-a4f2-8190f3e4e2f9",- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "query=' ' filter=Comparison(comparator=<Comparator.GT: 'gt'>, attribute='rating', value=8.5) limit=None\n"- ]- },- {- "data": {- "text/plain": [- "[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'}),\n",- " 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})]"- ]- },- "execution_count": 11,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "# This example only specifies a filter\n",- "retriever.get_relevant_documents(\"I want to watch a movie rated higher than 8.5\")\n"- ]+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "query='women' filter=Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='director', value='Greta Gerwig') limit=None\n"+ ]},{- "cell_type": "code",- "execution_count": 12,- "id": "b19d4da0",- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "query='women' filter=Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='director', value='Greta Gerwig') limit=None\n"- ]- },- {- "data": {- "text/plain": [- "[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})]"- ]- },- "execution_count": 12,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "# This example specifies a query and a filter\n",- "retriever.get_relevant_documents(\"Has Greta Gerwig directed any movies about women\")"+ "data": {+ "text/plain": [+ "[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})]"]- },+ },+ "execution_count": 12,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "# This example specifies a query and a filter\n",+ "retriever.get_relevant_documents(\"Has Greta Gerwig directed any movies about women\")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 13,+ "id": "a59f946b-78a1-4d3e-9942-63834c7d7589",+ "metadata": {},+ "outputs": [{- "cell_type": "code",- "execution_count": 13,- "id": "a59f946b-78a1-4d3e-9942-63834c7d7589",- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "query=' ' filter=Operation(operator=<Operator.AND: 'and'>, arguments=[Comparison(comparator=<Comparator.GTE: 'gte'>, attribute='rating', value=8.5), Comparison(comparator=<Comparator.CONTAIN: 'contain'>, attribute='genre', value='science fiction')]) limit=None\n"- ]- },- {- "data": {- "text/plain": [- "[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'})]"- ]- },- "execution_count": 13,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "# This example specifies a composite filter\n",- "retriever.get_relevant_documents(\"What's a highly rated (above 8.5) science fiction film?\")"- ]+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "query=' ' filter=Operation(operator=<Operator.AND: 'and'>, arguments=[Comparison(comparator=<Comparator.GTE: 'gte'>, attribute='rating', value=8.5), Comparison(comparator=<Comparator.CONTAIN: 'contain'>, attribute='genre', value='science fiction')]) limit=None\n"+ ]},{- "cell_type": "markdown",- "id": "39bd1de1-b9fe-4a98-89da-58d8a7a6ae51",- "metadata": {},- "source": [- "## Filter k\n",- "\n",- "We can also use the self query retriever to specify `k`: the number of documents to fetch.\n",- "\n",- "We can do this by passing `enable_limit=True` to the constructor."+ "data": {+ "text/plain": [+ "[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'})]"]- },+ },+ "execution_count": 13,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "# This example specifies a composite filter\n",+ "retriever.get_relevant_documents(\n",+ " \"What's a highly rated (above 8.5) science fiction film?\"\n",+ ")"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "39bd1de1-b9fe-4a98-89da-58d8a7a6ae51",+ "metadata": {},+ "source": [+ "## Filter k\n",+ "\n",+ "We can also use the self query retriever to specify `k`: the number of documents to fetch.\n",+ "\n",+ "We can do this by passing `enable_limit=True` to the constructor."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 14,+ "id": "bff36b88-b506-4877-9c63-e5a1a8d78e64",+ "metadata": {+ "tags": []+ },+ "outputs": [],+ "source": [+ "retriever = SelfQueryRetriever.from_llm(\n",+ " llm,\n",+ " vectorstore,\n",+ " document_content_description,\n",+ " metadata_field_info,\n",+ " enable_limit=True,\n",+ " verbose=True,\n",+ ")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 15,+ "id": "2758d229-4f97-499c-819f-888acaf8ee10",+ "metadata": {+ "tags": []+ },+ "outputs": [{- "cell_type": "code",- "execution_count": 14,- "id": "bff36b88-b506-4877-9c63-e5a1a8d78e64",- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "retriever = SelfQueryRetriever.from_llm(\n",- " llm,\n",- " vectorstore,\n",- " document_content_description,\n",- " metadata_field_info,\n",- " enable_limit=True,\n",- " verbose=True,\n",- ")"- ]+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "query='dinosaur' filter=None limit=2\n"+ ]},{- "cell_type": "code",- "execution_count": 15,- "id": "2758d229-4f97-499c-819f-888acaf8ee10",- "metadata": {- "tags": []- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "query='dinosaur' filter=None limit=2\n"- ]- },- {- "data": {- "text/plain": [- "[Document(page_content='A bunch of scientists bring back dinosaurs and mayhem breaks loose', metadata={'year': 1993, 'rating': 7.7, 'genre': 'science fiction'}),\n",- " Document(page_content='Toys come alive and have a blast doing so', metadata={'year': 1995, 'genre': 'animated'})]"- ]- },- "execution_count": 15,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "# This example only specifies a relevant query\n",- "retriever.get_relevant_documents(\"what are two movies about dinosaurs\")"+ "data": {+ "text/plain": [+ "[Document(page_content='A bunch of scientists bring back dinosaurs and mayhem breaks loose', metadata={'year': 1993, 'rating': 7.7, 'genre': 'science fiction'}),\n",+ " Document(page_content='Toys come alive and have a blast doing so', metadata={'year': 1995, 'genre': 'animated'})]"]- },+ },+ "execution_count": 15,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "# This example only specifies a relevant query\n",+ "retriever.get_relevant_documents(\"what are two movies about dinosaurs\")"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "61a10294",+ "metadata": {},+ "source": [+ "## Complex queries in Action!\n",+ "We've tried out some simple queries, but what about more complex ones? Let's try out a few more complex queries that utilize the full power of OpenSearch."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 16,+ "id": "e460da93",+ "metadata": {},+ "outputs": [{- "cell_type": "markdown",- "id": "61a10294",- "metadata": {},- "source": [- "## Complex queries in Action!\n",- "We've tried out some simple queries, but what about more complex ones? Let's try out a few more complex queries that utilize the full power of OpenSearch."- ]+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "query='animated toys' filter=Operation(operator=<Operator.AND: 'and'>, arguments=[Operation(operator=<Operator.OR: 'or'>, arguments=[Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='genre', value='animated'), Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='genre', value='comedy')]), Comparison(comparator=<Comparator.GTE: 'gte'>, attribute='year', value=1990)]) limit=None\n"+ ]},{- "cell_type": "code",- "execution_count": 16,- "id": "e460da93",- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "query='animated toys' filter=Operation(operator=<Operator.AND: 'and'>, arguments=[Operation(operator=<Operator.OR: 'or'>, arguments=[Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='genre', value='animated'), Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='genre', value='comedy')]), Comparison(comparator=<Comparator.GTE: 'gte'>, attribute='year', value=1990)]) limit=None\n"- ]- },- {- "data": {- "text/plain": [- "[Document(page_content='Toys come alive and have a blast doing so', metadata={'year': 1995, 'genre': 'animated'})]"- ]- },- "execution_count": 16,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "retriever.get_relevant_documents(\"what animated or comedy movies have been released in the last 30 years about animated toys?\")"+ "data": {+ "text/plain": [+ "[Document(page_content='Toys come alive and have a blast doing so', metadata={'year': 1995, 'genre': 'animated'})]"]- },+ },+ "execution_count": 16,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "retriever.get_relevant_documents(\n",+ " \"what animated or comedy movies have been released in the last 30 years about animated toys?\"\n",+ ")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 17,+ "id": "0851fc42",+ "metadata": {+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "outputs": [{- "cell_type": "code",- "execution_count": 17,- "id": "0851fc42",- "metadata": {- "pycharm": {- "name": "#%%\n"- }- },- "outputs": [- {- "data": {- "text/plain": [- "{'acknowledged': True}"- ]- },- "execution_count": 17,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "vectorstore.client.indices.delete(index=\"opensearch-self-query-demo\")\n"+ "data": {+ "text/plain": [+ "{'acknowledged': True}"]+ },+ "execution_count": 17,+ "metadata": {},+ "output_type": "execute_result"}- ],- "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.9.18"- }+ ],+ "source": [+ "vectorstore.client.indices.delete(index=\"opensearch-self-query-demo\")"+ ]+ }+ ],+ "metadata": {+ "kernelspec": {+ "display_name": "Python 3 (ipykernel)",+ "language": "python",+ "name": "python3"},- "nbformat": 4,- "nbformat_minor": 5+ "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.9.18"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5}\ No newline at end of filediff --git a/docs/docs/integrations/retrievers/self_query/redis_self_query.ipynb b/docs/docs/integrations/retrievers/self_query/redis_self_query.ipynbindex 95d9d39a6e..984eb40739 100644--- a/docs/docs/integrations/retrievers/self_query/redis_self_query.ipynb+++ b/docs/docs/integrations/retrievers/self_query/redis_self_query.ipynb@@ -86,23 +86,48 @@"docs = [\n"," Document(\n"," page_content=\"A bunch of scientists bring back dinosaurs and mayhem breaks loose\",\n",- " metadata={\"year\": 1993, \"rating\": 7.7, \"director\": \"Steven Spielberg\", \"genre\": \"science fiction\"},\n",+ " metadata={\n",+ " \"year\": 1993,\n",+ " \"rating\": 7.7,\n",+ " \"director\": \"Steven Spielberg\",\n",+ " \"genre\": \"science fiction\",\n",+ " },\n"," ),\n"," Document(\n"," page_content=\"Leo DiCaprio gets lost in a dream within a dream within a dream within a ...\",\n",- " metadata={\"year\": 2010, \"director\": \"Christopher Nolan\", \"genre\": \"science fiction\", \"rating\": 8.2},\n",+ " metadata={\n",+ " \"year\": 2010,\n",+ " \"director\": \"Christopher Nolan\",\n",+ " \"genre\": \"science fiction\",\n",+ " \"rating\": 8.2,\n",+ " },\n"," ),\n"," Document(\n"," page_content=\"A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea\",\n",- " metadata={\"year\": 2006, \"director\": \"Satoshi Kon\", \"genre\": \"science fiction\", \"rating\": 8.6},\n",+ " metadata={\n",+ " \"year\": 2006,\n",+ " \"director\": \"Satoshi Kon\",\n",+ " \"genre\": \"science fiction\",\n",+ " \"rating\": 8.6,\n",+ " },\n"," ),\n"," Document(\n"," page_content=\"A bunch of normal-sized women are supremely wholesome and some men pine after them\",\n",- " metadata={\"year\": 2019, \"director\": \"Greta Gerwig\", \"genre\": \"drama\", \"rating\": 8.3},\n",+ " metadata={\n",+ " \"year\": 2019,\n",+ " \"director\": \"Greta Gerwig\",\n",+ " \"genre\": \"drama\",\n",+ " \"rating\": 8.3,\n",+ " },\n"," ),\n"," Document(\n"," page_content=\"Toys come alive and have a blast doing so\",\n",- " metadata={\"year\": 1995, \"director\": \"John Lasseter\", \"genre\": \"animated\", \"rating\": 9.1,},\n",+ " metadata={\n",+ " \"year\": 1995,\n",+ " \"director\": \"John Lasseter\",\n",+ " \"genre\": \"animated\",\n",+ " \"rating\": 9.1,\n",+ " },\n"," ),\n"," Document(\n"," page_content=\"Three men walk into the Zone, three men walk out of the Zone\",\n",@@ -142,8 +167,8 @@"}\n","\n","vectorstore = Redis.from_documents(\n",- " docs, \n",- " embeddings, \n",+ " docs,\n",+ " embeddings,\n"," redis_url=\"redis://localhost:6379\",\n"," index_name=\"movie_reviews\",\n"," index_schema=index_schema,\n",@@ -192,7 +217,7 @@" name=\"rating\", description=\"A 1-10 rating for the movie\", type=\"float\"\n"," ),\n","]\n",- "document_content_description = \"Brief summary of a movie\"\n"+ "document_content_description = \"Brief summary of a movie\""]},{@@ -204,11 +229,7 @@"source": ["llm = OpenAI(temperature=0)\n","retriever = SelfQueryRetriever.from_llm(\n",- " llm, \n",- " vectorstore, \n",- " document_content_description, \n",- " metadata_field_info, \n",- " verbose=True\n",+ " llm, vectorstore, document_content_description, metadata_field_info, verbose=True\n",")"]},diff --git a/docs/docs/integrations/retrievers/self_query/supabase_self_query.ipynb b/docs/docs/integrations/retrievers/self_query/supabase_self_query.ipynbindex 165e1a3dc1..947d0bfeac 100644--- a/docs/docs/integrations/retrievers/self_query/supabase_self_query.ipynb+++ b/docs/docs/integrations/retrievers/self_query/supabase_self_query.ipynb@@ -278,7 +278,13 @@" ),\n","]\n","\n",- "vectorstore = SupabaseVectorStore.from_documents(docs, embeddings, client=supabase, table_name=\"documents\", query_name=\"match_documents\")"+ "vectorstore = SupabaseVectorStore.from_documents(\n",+ " docs,\n",+ " embeddings,\n",+ " client=supabase,\n",+ " table_name=\"documents\",\n",+ " query_name=\"match_documents\",\n",+ ")"]},{diff --git a/docs/docs/integrations/retrievers/self_query/timescalevector_self_query.ipynb b/docs/docs/integrations/retrievers/self_query/timescalevector_self_query.ipynbindex dcf4e01b8e..75e36eb656 100644--- a/docs/docs/integrations/retrievers/self_query/timescalevector_self_query.ipynb+++ b/docs/docs/integrations/retrievers/self_query/timescalevector_self_query.ipynb@@ -67,7 +67,7 @@},"outputs": [],"source": [- "#!pip install timescale-vector "+ "#!pip install timescale-vector"]},{@@ -92,13 +92,14 @@"# The .env file should contain a line starting with `OPENAI_API_KEY=sk-`\n","import os\n","from dotenv import load_dotenv, find_dotenv\n",+ "\n","_ = load_dotenv(find_dotenv())\n","\n",- "OPENAI_API_KEY = os.environ['OPENAI_API_KEY']\n",+ "OPENAI_API_KEY = os.environ[\"OPENAI_API_KEY\"]\n","# Alternatively, use getpass to enter the key in a prompt\n",- "#import os\n",- "#import getpass\n",- "#os.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"OpenAI API Key:\")"+ "# import os\n",+ "# import getpass\n",+ "# os.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"OpenAI API Key:\")"]},{@@ -127,9 +128,9 @@"TIMESCALE_SERVICE_URL = os.environ[\"TIMESCALE_SERVICE_URL\"]\n","\n","# Alternatively, use getpass to enter the key in a prompt\n",- "#import os\n",- "#import getpass\n",- "#TIMESCALE_SERVICE_URL = getpass.getpass(\"Timescale Service URL:\")"+ "# import os\n",+ "# import getpass\n",+ "# TIMESCALE_SERVICE_URL = getpass.getpass(\"Timescale Service URL:\")"]},{diff --git a/docs/docs/integrations/retrievers/self_query/vectara_self_query.ipynb b/docs/docs/integrations/retrievers/self_query/vectara_self_query.ipynbindex 72eb71478f..23eec58916 100644--- a/docs/docs/integrations/retrievers/self_query/vectara_self_query.ipynb+++ b/docs/docs/integrations/retrievers/self_query/vectara_self_query.ipynb@@ -84,7 +84,7 @@"from langchain.llms import OpenAI\n","from langchain.chains import ConversationalRetrievalChain\n","from langchain.retrievers.self_query.base import SelfQueryRetriever\n",- "from langchain.chains.query_constructor.base import AttributeInfo\n"+ "from langchain.chains.query_constructor.base import AttributeInfo"]},{@@ -130,7 +130,11 @@"\n","vectara = Vectara()\n","for doc in docs:\n",- " vectara.add_texts([doc.page_content], embedding=FakeEmbeddings(size=768), doc_metadata=doc.metadata)"+ " vectara.add_texts(\n",+ " [doc.page_content],\n",+ " embedding=FakeEmbeddings(size=768),\n",+ " doc_metadata=doc.metadata,\n",+ " )"]},{diff --git a/docs/docs/integrations/retrievers/singlestoredb.ipynb b/docs/docs/integrations/retrievers/singlestoredb.ipynbindex 2737a579f4..ec69b04030 100644--- a/docs/docs/integrations/retrievers/singlestoredb.ipynb+++ b/docs/docs/integrations/retrievers/singlestoredb.ipynb@@ -91,7 +91,9 @@"metadata": {},"outputs": [],"source": [- "result = retriever.get_relevant_documents(\"What did the president say about Ketanji Brown Jackson\")\n",+ "result = retriever.get_relevant_documents(\n",+ " \"What did the president say about Ketanji Brown Jackson\"\n",+ ")\n","print(docs[0].page_content)"]}diff --git a/docs/docs/integrations/retrievers/you-retriever.ipynb b/docs/docs/integrations/retrievers/you-retriever.ipynbindex 208ae70adb..68648f316a 100644--- a/docs/docs/integrations/retrievers/you-retriever.ipynb+++ b/docs/docs/integrations/retrievers/you-retriever.ipynb@@ -23,7 +23,7 @@"from langchain.llms import OpenAI\n","\n","yr = YouRetriever()\n",- "qa = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type=\"map_reduce\", retriever=yr)\n"+ "qa = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type=\"map_reduce\", retriever=yr)"]},{diff --git a/docs/docs/integrations/text_embedding/baidu_qianfan_endpoint.ipynb b/docs/docs/integrations/text_embedding/baidu_qianfan_endpoint.ipynbindex e971b03891..270aed78da 100644--- a/docs/docs/integrations/text_embedding/baidu_qianfan_endpoint.ipynb+++ b/docs/docs/integrations/text_embedding/baidu_qianfan_endpoint.ipynb@@ -60,31 +60,37 @@],"source": ["\"\"\"For basic init and call\"\"\"\n",- "from langchain.embeddings import QianfanEmbeddingsEndpoint \n",+ "from langchain.embeddings import QianfanEmbeddingsEndpoint\n","\n","import os\n",+ "\n","os.environ[\"QIANFAN_AK\"] = \"your_ak\"\n","os.environ[\"QIANFAN_SK\"] = \"your_sk\"\n","\n","embed = QianfanEmbeddingsEndpoint(\n",- " # qianfan_ak='xxx', \n",+ " # qianfan_ak='xxx',\n"," # qianfan_sk='xxx'\n",")\n","res = embed.embed_documents([\"hi\", \"world\"])\n","\n",+ "\n","async def aioEmbed():\n"," res = await embed.aembed_query(\"qianfan\")\n"," print(res[:8])\n",+ "\n",+ "\n","await aioEmbed()\n","\n","import asyncio\n",+ "\n",+ "\n","async def aioEmbedDocs():\n"," res = await embed.aembed_documents([\"hi\", \"world\"])\n"," for r in res:\n"," print(\"\", r[:8])\n",- "await aioEmbedDocs()\n","\n",- "\n"+ "\n",+ "await aioEmbedDocs()"]},{@@ -122,13 +128,10 @@}],"source": [- "embed = QianfanEmbeddingsEndpoint(\n",- " model=\"bge_large_zh\",\n",- " endpoint=\"bge_large_zh\"\n",- " )\n",+ "embed = QianfanEmbeddingsEndpoint(model=\"bge_large_zh\", endpoint=\"bge_large_zh\")\n","\n","res = embed.embed_documents([\"hi\", \"world\"])\n",- "for r in res :\n",+ "for r in res:\n"," print(r[:8])"]}diff --git a/docs/docs/integrations/text_embedding/bedrock.ipynb b/docs/docs/integrations/text_embedding/bedrock.ipynbindex 0dbbcd080f..84edf31d14 100644--- a/docs/docs/integrations/text_embedding/bedrock.ipynb+++ b/docs/docs/integrations/text_embedding/bedrock.ipynb@@ -51,7 +51,9 @@"metadata": {},"outputs": [],"source": [- "embeddings.embed_documents([\"This is a content of the document\", \"This is another document\"])"+ "embeddings.embed_documents(\n",+ " [\"This is a content of the document\", \"This is another document\"]\n",+ ")"]},{@@ -73,7 +75,9 @@"outputs": [],"source": ["# async embed documents\n",- "await embeddings.aembed_documents([\"This is a content of the document\", \"This is another document\"])"+ "await embeddings.aembed_documents(\n",+ " [\"This is a content of the document\", \"This is another document\"]\n",+ ")"]}],diff --git a/docs/docs/integrations/text_embedding/bge_huggingface.ipynb b/docs/docs/integrations/text_embedding/bge_huggingface.ipynbindex e42f11df9e..4695370d56 100644--- a/docs/docs/integrations/text_embedding/bge_huggingface.ipynb+++ b/docs/docs/integrations/text_embedding/bge_huggingface.ipynb@@ -35,12 +35,10 @@"from langchain.embeddings import HuggingFaceBgeEmbeddings\n","\n","model_name = \"BAAI/bge-small-en\"\n",- "model_kwargs = {'device': 'cpu'}\n",- "encode_kwargs = {'normalize_embeddings': True}\n",+ "model_kwargs = {\"device\": \"cpu\"}\n",+ "encode_kwargs = {\"normalize_embeddings\": True}\n","hf = HuggingFaceBgeEmbeddings(\n",- " model_name=model_name,\n",- " model_kwargs=model_kwargs,\n",- " encode_kwargs=encode_kwargs\n",+ " model_name=model_name, model_kwargs=model_kwargs, encode_kwargs=encode_kwargs\n",")"]},diff --git a/docs/docs/integrations/text_embedding/edenai.ipynb b/docs/docs/integrations/text_embedding/edenai.ipynbindex e99833782a..d7f813a639 100644--- a/docs/docs/integrations/text_embedding/edenai.ipynb+++ b/docs/docs/integrations/text_embedding/edenai.ipynb@@ -69,7 +69,7 @@"metadata": {},"outputs": [],"source": [- "embeddings = EdenAiEmbeddings(edenai_api_key=\"...\",provider=\"...\")"+ "embeddings = EdenAiEmbeddings(edenai_api_key=\"...\", provider=\"...\")"]},{diff --git a/docs/docs/integrations/text_embedding/gradient.ipynb b/docs/docs/integrations/text_embedding/gradient.ipynbindex fa8e192958..f6ecef779a 100644--- a/docs/docs/integrations/text_embedding/gradient.ipynb+++ b/docs/docs/integrations/text_embedding/gradient.ipynb@@ -44,10 +44,10 @@"from getpass import getpass\n","import os\n","\n",- "if not os.environ.get(\"GRADIENT_ACCESS_TOKEN\",None):\n",+ "if not os.environ.get(\"GRADIENT_ACCESS_TOKEN\", None):\n"," # Access token under https://auth.gradient.ai/select-workspace\n"," os.environ[\"GRADIENT_ACCESS_TOKEN\"] = getpass(\"gradient.ai access token:\")\n",- "if not os.environ.get(\"GRADIENT_WORKSPACE_ID\",None):\n",+ "if not os.environ.get(\"GRADIENT_WORKSPACE_ID\", None):\n"," # `ID` listed in `$ gradient workspace list`\n"," # also displayed after login at at https://auth.gradient.ai/select-workspace\n"," os.environ[\"GRADIENT_WORKSPACE_ID\"] = getpass(\"gradient.ai workspace id:\")"@@ -82,7 +82,11 @@"metadata": {},"outputs": [],"source": [- "documents = [\"Pizza is a dish.\",\"Paris is the capital of France\", \"numpy is a lib for linear algebra\"]\n",+ "documents = [\n",+ " \"Pizza is a dish.\",\n",+ " \"Paris is the capital of France\",\n",+ " \"numpy is a lib for linear algebra\",\n",+ "]\n","query = \"Where is Paris?\""]},@@ -92,12 +96,10 @@"metadata": {},"outputs": [],"source": [- "embeddings = GradientEmbeddings(\n",- " model=\"bge-large\"\n",- ")\n",+ "embeddings = GradientEmbeddings(model=\"bge-large\")\n","\n","documents_embedded = embeddings.embed_documents(documents)\n",- "query_result = embeddings.embed_query(query)\n"+ "query_result = embeddings.embed_query(query)"]},{diff --git a/docs/docs/integrations/text_embedding/huggingfacehub.ipynb b/docs/docs/integrations/text_embedding/huggingfacehub.ipynbindex cb897f8693..4c3b1ed2c7 100644--- a/docs/docs/integrations/text_embedding/huggingfacehub.ipynb+++ b/docs/docs/integrations/text_embedding/huggingfacehub.ipynb@@ -142,8 +142,7 @@"from langchain.embeddings import HuggingFaceInferenceAPIEmbeddings\n","\n","embeddings = HuggingFaceInferenceAPIEmbeddings(\n",- " api_key=inference_api_key,\n",- " model_name=\"sentence-transformers/all-MiniLM-l6-v2\"\n",+ " api_key=inference_api_key, model_name=\"sentence-transformers/all-MiniLM-l6-v2\"\n",")\n","\n","query_result = embeddings.embed_query(text)\n",diff --git a/docs/docs/integrations/text_embedding/johnsnowlabs_embedding.ipynb b/docs/docs/integrations/text_embedding/johnsnowlabs_embedding.ipynbindex 0fdc7ac3b0..8230a29f18 100644--- a/docs/docs/integrations/text_embedding/johnsnowlabs_embedding.ipynb+++ b/docs/docs/integrations/text_embedding/johnsnowlabs_embedding.ipynb@@ -89,7 +89,7 @@"execution_count": null,"outputs": [],"source": [- "embedder = JohnSnowLabsEmbeddings('en.embed_sentence.biobert.clinical_base_cased')"+ "embedder = JohnSnowLabsEmbeddings(\"en.embed_sentence.biobert.clinical_base_cased\")"],"metadata": {"collapsed": falsediff --git a/docs/docs/integrations/text_embedding/llm_rails.ipynb b/docs/docs/integrations/text_embedding/llm_rails.ipynbindex e92d3ec09a..e5e45beb05 100644--- a/docs/docs/integrations/text_embedding/llm_rails.ipynb+++ b/docs/docs/integrations/text_embedding/llm_rails.ipynb@@ -30,7 +30,7 @@"metadata": {},"outputs": [],"source": [- "embeddings = LLMRailsEmbeddings(model='embedding-english-v1') # or embedding-multi-v1"+ "embeddings = LLMRailsEmbeddings(model=\"embedding-english-v1\") # or embedding-multi-v1"]},{diff --git a/docs/docs/integrations/text_embedding/localai.ipynb b/docs/docs/integrations/text_embedding/localai.ipynbindex 6294b65ff9..e14e4ef566 100644--- a/docs/docs/integrations/text_embedding/localai.ipynb+++ b/docs/docs/integrations/text_embedding/localai.ipynb@@ -28,7 +28,9 @@"metadata": {},"outputs": [],"source": [- "embeddings = LocalAIEmbeddings(openai_api_base=\"http://localhost:8080\", model=\"embedding-model-name\")"+ "embeddings = LocalAIEmbeddings(\n",+ " openai_api_base=\"http://localhost:8080\", model=\"embedding-model-name\"\n",+ ")"]},{@@ -87,7 +89,9 @@"metadata": {},"outputs": [],"source": [- "embeddings = LocalAIEmbeddings(openai_api_base=\"http://localhost:8080\", model=\"embedding-model-name\")"+ "embeddings = LocalAIEmbeddings(\n",+ " openai_api_base=\"http://localhost:8080\", model=\"embedding-model-name\"\n",+ ")"]},{diff --git a/docs/docs/integrations/text_embedding/sagemaker-endpoint.ipynb b/docs/docs/integrations/text_embedding/sagemaker-endpoint.ipynbindex 98d423890d..8bb72f4159 100644--- a/docs/docs/integrations/text_embedding/sagemaker-endpoint.ipynb+++ b/docs/docs/integrations/text_embedding/sagemaker-endpoint.ipynb@@ -45,6 +45,7 @@"import json\n","import boto3\n","\n",+ "\n","class ContentHandler(EmbeddingsContentHandler):\n"," content_type = \"application/json\"\n"," accepts = \"application/json\"\n",@@ -59,7 +60,7 @@" The transformed bytes input.\n"," \"\"\"\n"," # Example: inference.py expects a JSON string with a \"inputs\" key:\n",- " input_str = json.dumps({\"inputs\": inputs, **model_kwargs}) \n",+ " input_str = json.dumps({\"inputs\": inputs, **model_kwargs})\n"," return input_str.encode(\"utf-8\")\n","\n"," def transform_output(self, output: bytes) -> List[List[float]]:\n",@@ -92,10 +93,10 @@"\n","# client = boto3.client(\n","# \"sagemaker-runtime\",\n",- "# region_name=\"us-west-2\" \n",+ "# region_name=\"us-west-2\"\n","# )\n","# embeddings = SagemakerEndpointEmbeddings(\n",- "# endpoint_name=\"huggingface-pytorch-inference-2023-03-21-16-14-03-834\", \n",+ "# endpoint_name=\"huggingface-pytorch-inference-2023-03-21-16-14-03-834\",\n","# client=client\n","# content_handler=content_handler,\n","# )"diff --git a/docs/docs/integrations/text_embedding/xinference.ipynb b/docs/docs/integrations/text_embedding/xinference.ipynbindex e8a79be16b..dd4f0ee39e 100644--- a/docs/docs/integrations/text_embedding/xinference.ipynb+++ b/docs/docs/integrations/text_embedding/xinference.ipynb@@ -79,8 +79,7 @@"from langchain.embeddings import XinferenceEmbeddings\n","\n","xinference = XinferenceEmbeddings(\n",- " server_url=\"http://0.0.0.0:9997\",\n",- " model_uid = \"915845ee-2a04-11ee-8ed4-d29396a3f064\"\n",+ " server_url=\"http://0.0.0.0:9997\", model_uid=\"915845ee-2a04-11ee-8ed4-d29396a3f064\"\n",")"]},diff --git a/docs/docs/integrations/toolkits/airbyte_structured_qa.ipynb b/docs/docs/integrations/toolkits/airbyte_structured_qa.ipynbindex e9139ee16c..0c8b48854a 100644--- a/docs/docs/integrations/toolkits/airbyte_structured_qa.ipynb+++ b/docs/docs/integrations/toolkits/airbyte_structured_qa.ipynb@@ -39,9 +39,11 @@" \"start_date\": \"2023-01-20T00:00:00Z\",\n","}\n","\n",+ "\n","def handle_record(record: dict, _id: str):\n"," return record.data\n","\n",+ "\n","loader = AirbyteStripeLoader(\n"," config=config,\n"," record_handler=handle_record,\n",diff --git a/docs/docs/integrations/toolkits/clickup.ipynb b/docs/docs/integrations/toolkits/clickup.ipynbindex 3b85660674..c0eb7e026f 100644--- a/docs/docs/integrations/toolkits/clickup.ipynb+++ b/docs/docs/integrations/toolkits/clickup.ipynb@@ -21,7 +21,7 @@"\n","from langchain.agents import AgentType, initialize_agent\n","from langchain.llms import OpenAI\n",- "from langchain.utilities.clickup import ClickupAPIWrapper\n"+ "from langchain.utilities.clickup import ClickupAPIWrapper"]},{@@ -62,7 +62,7 @@"oauth_client_secret = \"123...\"\n","redirect_uri = \"https://google.com\"\n","\n",- "print('Click this link, select your workspace, click `Connect Workspace`')\n",+ "print(\"Click this link, select your workspace, click `Connect Workspace`\")\n","print(ClickupAPIWrapper.get_access_code_url(oauth_client_id, redirect_uri))"]},@@ -111,10 +111,12 @@}],"source": [- "access_token = ClickupAPIWrapper.get_access_token(oauth_client_id, oauth_client_secret, code)\n",+ "access_token = ClickupAPIWrapper.get_access_token(\n",+ " oauth_client_id, oauth_client_secret, code\n",+ ")\n","\n","if access_token is not None:\n",- " print('Copy/paste this code, into the next cell so you can reuse it!')\n",+ " print(\"Copy/paste this code, into the next cell so you can reuse it!\")\n"," print(access_token)"]},@@ -142,13 +144,17 @@],"source": ["# Set your access token here\n",- "access_token = '12345678_myaccesstokengoeshere123'\n",- "access_token = '81928627_c009bf122ccf36ec3ba3e0ef748b07042c5e4217260042004a5934540cb61527'\n",+ "access_token = \"12345678_myaccesstokengoeshere123\"\n",+ "access_token = (\n",+ " \"81928627_c009bf122ccf36ec3ba3e0ef748b07042c5e4217260042004a5934540cb61527\"\n",+ ")\n","\n","# Init toolkit\n","clickup_api_wrapper = ClickupAPIWrapper(access_token=access_token)\n","toolkit = ClickupToolkit.from_clickup_api_wrapper(clickup_api_wrapper)\n",- "print(f'Found team_id: {clickup_api_wrapper.team_id}.\\nMost request require the team id, so we store it for you in the toolkit, we assume the first team in your list is the one you want. \\nNote: If you know this is the wrong ID, you can pass it at initialization.')"+ "print(\n",+ " f\"Found team_id: {clickup_api_wrapper.team_id}.\\nMost request require the team id, so we store it for you in the toolkit, we assume the first team in your list is the one you want. \\nNote: If you know this is the wrong ID, you can pass it at initialization.\"\n",+ ")"]},{@@ -186,13 +192,12 @@"source": ["# helper function for demo\n","def print_and_run(command):\n",- " print('\\033[94m$ COMMAND\\033[0m')\n",+ " print(\"\\033[94m$ COMMAND\\033[0m\")\n"," print(command)\n",- " print('\\n\\033[94m$ AGENT\\033[0m')\n",+ " print(\"\\n\\033[94m$ AGENT\\033[0m\")\n"," response = agent.run(command)\n",- " print(''.join(['-']*80))\n",- " return response\n",- " "+ " print(\"\".join([\"-\"] * 80))\n",+ " return response"]},{@@ -293,7 +298,7 @@"metadata": {},"outputs": [],"source": [- "task_id = '8685mb5fn'"+ "task_id = \"8685mb5fn\""]},{@@ -410,14 +415,20 @@"print_and_run(f\"Get task with id {task_id}\")\n","\n","# We can get a specific attribute from a task\n",- "previous_description = print_and_run(f\"What is the description of task with id {task_id}\")\n",+ "previous_description = print_and_run(\n",+ " f\"What is the description of task with id {task_id}\"\n",+ ")\n","\n","# We can even update it!\n",- "print_and_run(f\"For task with id {task_id}, change the description to 'A cool task descriptiont changed by AI!'\")\n",+ "print_and_run(\n",+ " f\"For task with id {task_id}, change the description to 'A cool task descriptiont changed by AI!'\"\n",+ ")\n","print_and_run(f\"What is the description of task with id {task_id}\")\n","\n","# Undo what we did\n",- "print_and_run(f\"For task with id {task_id}, change the description to '{previous_description}'\")"+ "print_and_run(\n",+ " f\"For task with id {task_id}, change the description to '{previous_description}'\"\n",+ ")"]},{@@ -577,7 +588,7 @@"print_and_run(f\"What are the assignees of task id {task_id}?\")\n","print_and_run(f\"Remove user {user_id} from the assignees of task id {task_id}\")\n","print_and_run(f\"What are the assignees of task id {task_id}?\")\n",- "print_and_run(f\"Add user {user_id} from the assignees of task id {task_id}\")\n"+ "print_and_run(f\"Add user {user_id} from the assignees of task id {task_id}\")"]},{@@ -628,7 +639,9 @@],"source": ["time_str = datetime.now().strftime(\"%d/%m/%Y-%H:%M:%S\")\n",- "print_and_run(f\"Create a task called 'Test Task - {time_str}' with description 'This is a Test'\")"+ "print_and_run(\n",+ " f\"Create a task called 'Test Task - {time_str}' with description 'This is a Test'\"\n",+ ")"]},{@@ -671,7 +684,7 @@],"source": ["time_str = datetime.now().strftime(\"%d/%m/%Y-%H:%M:%S\")\n",- "print_and_run(f\"Create a list called Test List - {time_str}\")\n"+ "print_and_run(f\"Create a list called Test List - {time_str}\")"]},{@@ -714,7 +727,7 @@],"source": ["time_str = datetime.now().strftime(\"%d/%m/%Y-%H:%M:%S\")\n",- "print_and_run(f\"Create a folder called 'Test Folder - {time_str}'\")\n"+ "print_and_run(f\"Create a folder called 'Test Folder - {time_str}'\")"]},{@@ -757,7 +770,9 @@],"source": ["time_str = datetime.now().strftime(\"%d/%m/%Y-%H:%M:%S\")\n",- "print_and_run(f\"Create a list called 'Test List - {time_str}' with content My test list with high priority and status red\")\n"+ "print_and_run(\n",+ " f\"Create a list called 'Test List - {time_str}' with content My test list with high priority and status red\"\n",+ ")"]},{@@ -826,7 +841,9 @@}],"source": [- "print_and_run(\"Figure out what user ID Rodrigo is, create a task called 'Rod's task', assign it to Rodrigo\")"+ "print_and_run(\n",+ " \"Figure out what user ID Rodrigo is, create a task called 'Rod's task', assign it to Rodrigo\"\n",+ ")"]}],diff --git a/docs/docs/integrations/toolkits/github.ipynb b/docs/docs/integrations/toolkits/github.ipynbindex 3eb7a18aec..939618e256 100644--- a/docs/docs/integrations/toolkits/github.ipynb+++ b/docs/docs/integrations/toolkits/github.ipynb@@ -125,8 +125,7 @@"os.environ[\"GITHUB_BASE_BRANCH\"] = \"main\"\n","\n","# This example also requires an OpenAI API key\n",- "os.environ[\"OPENAI_API_KEY\"] = \"\"\n",- "\n"+ "os.environ[\"OPENAI_API_KEY\"] = \"\""]},{@@ -248,23 +247,24 @@"from langchain.chat_models import ChatOpenAI\n","\n","tools = []\n",- "unwanted_tools = ['Get Issue','Delete File', 'Create File', 'Create Pull Request']\n",+ "unwanted_tools = [\"Get Issue\", \"Delete File\", \"Create File\", \"Create Pull Request\"]\n","\n","for tool in toolkit.get_tools():\n"," if tool.name not in unwanted_tools:\n"," tools.append(tool)\n",- "tools+= [\n",+ "tools += [\n"," Tool(\n",- " name = \"Search\",\n",- " func = DuckDuckGoSearchRun().run,\n",- " description = \"useful for when you need to search the web\"\n",- " )]\n",- " \n",+ " name=\"Search\",\n",+ " func=DuckDuckGoSearchRun().run,\n",+ " description=\"useful for when you need to search the web\",\n",+ " )\n",+ "]\n",+ "\n","agent = initialize_agent(\n",- " tools = tools,\n",- " llm = ChatOpenAI(temperature=0.1),\n",- " agent = AgentType.ZERO_SHOT_REACT_DESCRIPTION,\n",- " verbose = True\n",+ " tools=tools,\n",+ " llm=ChatOpenAI(temperature=0.1),\n",+ " agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,\n",+ " verbose=True,\n",")"]},@@ -363,7 +363,7 @@"Issue Description: {issue['body']}\n","Comments: {issue['comments']}\"\"\"\n","\n",- "agent.run(prompt)\n"+ "agent.run(prompt)"]}],diff --git a/docs/docs/integrations/toolkits/gitlab.ipynb b/docs/docs/integrations/toolkits/gitlab.ipynbindex cabf3dae7e..3c9a955e38 100644--- a/docs/docs/integrations/toolkits/gitlab.ipynb+++ b/docs/docs/integrations/toolkits/gitlab.ipynb@@ -117,8 +117,7 @@"os.environ[\"GITLAB_BASE_BRANCH\"] = \"main\"\n","\n","# This example also requires an OpenAI API key\n",- "os.environ[\"OPENAI_API_KEY\"] = \"\"\n",- "\n"+ "os.environ[\"OPENAI_API_KEY\"] = \"\""]},{diff --git a/docs/docs/integrations/toolkits/google_drive.ipynb b/docs/docs/integrations/toolkits/google_drive.ipynbindex 7e5bc413d2..49875b4d42 100644--- a/docs/docs/integrations/toolkits/google_drive.ipynb+++ b/docs/docs/integrations/toolkits/google_drive.ipynb@@ -50,8 +50,8 @@"metadata": {},"outputs": [],"source": [- "folder_id=\"root\"\n",- "#folder_id='1yucgL9WGgWZdM1TOuKkeghlPizuzMYb5'"+ "folder_id = \"root\"\n",+ "# folder_id='1yucgL9WGgWZdM1TOuKkeghlPizuzMYb5'"]},{@@ -106,7 +106,7 @@" api_wrapper=GoogleDriveAPIWrapper(\n"," folder_id=folder_id,\n"," num_results=2,\n",- " template=\"gdrive-query-in-folder\", # Search in the body of documents\n",+ " template=\"gdrive-query-in-folder\", # Search in the body of documents\n"," )\n",")"]@@ -118,6 +118,7 @@"outputs": [],"source": ["import logging\n",+ "\n","logging.basicConfig(level=logging.INFO)"]},@@ -146,10 +147,12 @@"outputs": [],"source": ["from langchain.agents import load_tools\n",- "tools = load_tools([\"google-drive-search\"],\n",- " folder_id=folder_id,\n",- " template=\"gdrive-query-in-folder\",\n",- " )"+ "\n",+ "tools = load_tools(\n",+ " [\"google-drive-search\"],\n",+ " folder_id=folder_id,\n",+ " template=\"gdrive-query-in-folder\",\n",+ ")"]},{@@ -169,6 +172,7 @@"source": ["from langchain.llms import OpenAI\n","from langchain.agents import initialize_agent, AgentType\n",+ "\n","llm = OpenAI(temperature=0)\n","agent = initialize_agent(\n"," tools=tools,\n",@@ -185,9 +189,7 @@},"outputs": [],"source": [- "agent.run(\n",- " \"Search in google drive, who is 'Yann LeCun' ?\"\n",- ")"+ "agent.run(\"Search in google drive, who is 'Yann LeCun' ?\")"]}],diff --git a/docs/docs/integrations/toolkits/multion.ipynb b/docs/docs/integrations/toolkits/multion.ipynbindex 7f168d001b..de4098fa00 100644--- a/docs/docs/integrations/toolkits/multion.ipynb+++ b/docs/docs/integrations/toolkits/multion.ipynb@@ -62,8 +62,8 @@"source": ["# Authorize connection to your Browser extention\n","import multion\n",- "multion.login()\n",- "\n"+ "\n",+ "multion.login()"]},{@@ -83,15 +83,17 @@"source": ["from langchain.llms import OpenAI\n","from langchain.agents import initialize_agent, AgentType\n",+ "\n","llm = OpenAI(temperature=0)\n","from langchain.agents.agent_toolkits import MultionToolkit\n",+ "\n","toolkit = MultionToolkit()\n",- "tools=toolkit.get_tools()\n",+ "tools = toolkit.get_tools()\n","agent = initialize_agent(\n"," tools=toolkit.get_tools(),\n"," llm=llm,\n"," agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,\n",- " verbose = True\n",+ " verbose=True,\n",")"]},@@ -103,9 +105,7 @@},"outputs": [],"source": [- "agent.run(\n",- " \"Tweet 'Hi from MultiOn'\"\n",- ")"+ "agent.run(\"Tweet 'Hi from MultiOn'\")"]}],diff --git a/docs/docs/integrations/tools/bearly.ipynb b/docs/docs/integrations/tools/bearly.ipynbindex 7301f8736f..02fc5795bd 100644--- a/docs/docs/integrations/tools/bearly.ipynb+++ b/docs/docs/integrations/tools/bearly.ipynb@@ -66,14 +66,10 @@"outputs": [],"source": ["bearly_tool.add_file(\n",- " source_path=\"sample_data/Bristol.pdf\", \n",- " target_path=\"Bristol.pdf\", \n",- " description=\"\"\n",+ " source_path=\"sample_data/Bristol.pdf\", target_path=\"Bristol.pdf\", description=\"\"\n",")\n","bearly_tool.add_file(\n",- " source_path=\"sample_data/US_GDP.csv\", \n",- " target_path=\"US_GDP.csv\", \n",- " description=\"\"\n",+ " source_path=\"sample_data/US_GDP.csv\", target_path=\"US_GDP.csv\", description=\"\"\n",")"]},@@ -161,7 +157,11 @@"source": ["llm = ChatOpenAI(model=\"gpt-4\", temperature=0)\n","agent = initialize_agent(\n",- " tools, llm, agent=AgentType.OPENAI_FUNCTIONS, verbose=True, handle_parsing_errors=True\n",+ " tools,\n",+ " llm,\n",+ " agent=AgentType.OPENAI_FUNCTIONS,\n",+ " verbose=True,\n",+ " handle_parsing_errors=True,\n",")"]},diff --git a/docs/docs/integrations/tools/dalle_image_generator.ipynb b/docs/docs/integrations/tools/dalle_image_generator.ipynbindex ba01e52df3..e0430436e7 100644--- a/docs/docs/integrations/tools/dalle_image_generator.ipynb+++ b/docs/docs/integrations/tools/dalle_image_generator.ipynb@@ -30,6 +30,7 @@"source": ["from langchain.llms import OpenAI\n","import os\n",+ "\n","os.environ[\"OPENAI_API_KEY\"] = \"<your-key-here>\""]},@@ -95,29 +96,30 @@"metadata": {},"outputs": [],"source": [- "# You can click on the link above to display the image \n",+ "# You can click on the link above to display the image\n","# Or you can try the options below to display the image inline in this notebook\n","\n","try:\n"," import google.colab\n",+ "\n"," IN_COLAB = True\n","except:\n"," IN_COLAB = False\n","\n","if IN_COLAB:\n",- " from google.colab.patches import cv2_imshow # for image display\n",+ " from google.colab.patches import cv2_imshow # for image display\n"," from skimage import io\n","\n",- " image = io.imread(image_url) \n",+ " image = io.imread(image_url)\n"," cv2_imshow(image)\n","else:\n"," import cv2\n"," from skimage import io\n","\n",- " image = io.imread(image_url) \n",- " cv2.imshow('image', image)\n",- " cv2.waitKey(0) #wait for a keyboard input\n",- " cv2.destroyAllWindows()\n"+ " image = io.imread(image_url)\n",+ " cv2.imshow(\"image\", image)\n",+ " cv2.waitKey(0) # wait for a keyboard input\n",+ " cv2.destroyAllWindows()"]},{@@ -156,7 +158,7 @@"from langchain.agents import load_tools\n","from langchain.agents import initialize_agent\n","\n",- "tools = load_tools(['dalle-image-generator'])\n",+ "tools = load_tools([\"dalle-image-generator\"])\n","agent = initialize_agent(tools, llm, agent=\"zero-shot-react-description\", verbose=True)\n","output = agent.run(\"Create an image of a halloween night at a haunted museum\")"]diff --git a/docs/docs/integrations/tools/e2b_data_analysis.ipynb b/docs/docs/integrations/tools/e2b_data_analysis.ipynbindex 371dd65bed..16ac42cd3a 100644--- a/docs/docs/integrations/tools/e2b_data_analysis.ipynb+++ b/docs/docs/integrations/tools/e2b_data_analysis.ipynb@@ -80,14 +80,15 @@"source": ["# Artifacts are charts created by matplotlib when `plt.show()` is called\n","def save_artifact(artifact):\n",- " print(\"New matplotlib chart generated:\", artifact.name)\n",- " # Download the artifact as `bytes` and leave it up to the user to display them (on frontend, for example)\n",- " file = artifact.download()\n",- " basename = os.path.basename(artifact.name)\n",+ " print(\"New matplotlib chart generated:\", artifact.name)\n",+ " # Download the artifact as `bytes` and leave it up to the user to display them (on frontend, for example)\n",+ " file = artifact.download()\n",+ " basename = os.path.basename(artifact.name)\n",+ "\n",+ " # Save the chart to the `charts` directory\n",+ " with open(f\"./charts/{basename}\", \"wb\") as f:\n",+ " f.write(file)\n","\n",- " # Save the chart to the `charts` directory\n",- " with open(f\"./charts/{basename}\", \"wb\") as f:\n",- " f.write(file)\n","\n","e2b_data_analysis_tool = E2BDataAnalysisTool(\n"," # Pass environment variables to the sandbox\n",@@ -122,8 +123,8 @@"source": ["with open(\"./netflix.csv\") as f:\n"," remote_path = e2b_data_analysis_tool.upload_file(\n",- " file=f,\n",- " description=\"Data about Netflix tv shows including their title, category, director, release date, casting, age rating, etc.\",\n",+ " file=f,\n",+ " description=\"Data about Netflix tv shows including their title, category, director, release date, casting, age rating, etc.\",\n"," )\n"," print(remote_path)"]@@ -142,13 +143,15 @@"metadata": {},"outputs": [],"source": [- "\n",- "\n","tools = [e2b_data_analysis_tool.as_tool()]\n","\n","llm = ChatOpenAI(model=\"gpt-4\", temperature=0)\n","agent = initialize_agent(\n",- " tools, llm, agent=AgentType.OPENAI_FUNCTIONS, verbose=True, handle_parsing_errors=True\n",+ " tools,\n",+ " llm,\n",+ " agent=AgentType.OPENAI_FUNCTIONS,\n",+ " verbose=True,\n",+ " handle_parsing_errors=True,\n",")"]},@@ -209,7 +212,9 @@}],"source": [- "agent.run(\"What are the 5 longest movies on netflix released between 2000 and 2010? Create a chart with their lengths.\")"+ "agent.run(\n",+ " \"What are the 5 longest movies on netflix released between 2000 and 2010? Create a chart with their lengths.\"\n",+ ")"]},{@@ -240,7 +245,7 @@],"source": ["# Install Python package\n",- "e2b_data_analysis_tool.install_python_packages('pandas')"+ "e2b_data_analysis_tool.install_python_packages(\"pandas\")"]},{@@ -258,7 +263,7 @@"outputs": [],"source": ["# The path is a remote path in the sandbox\n",- "files_in_bytes = e2b_data_analysis_tool.download_file('/home/user/netflix.csv')"+ "files_in_bytes = e2b_data_analysis_tool.download_file(\"/home/user/netflix.csv\")"]},{diff --git a/docs/docs/integrations/tools/edenai_tools.ipynb b/docs/docs/integrations/tools/edenai_tools.ipynbindex 2abd509a64..ea8a6e6afb 100644--- a/docs/docs/integrations/tools/edenai_tools.ipynb+++ b/docs/docs/integrations/tools/edenai_tools.ipynb@@ -68,16 +68,18 @@"from langchain.llms import EdenAI\n","from langchain.agents import initialize_agent, AgentType\n","\n",- "llm=EdenAI(feature=\"text\",provider=\"openai\", params={\"temperature\" : 0.2,\"max_tokens\" : 250})\n",+ "llm = EdenAI(\n",+ " feature=\"text\", provider=\"openai\", params={\"temperature\": 0.2, \"max_tokens\": 250}\n",+ ")\n","\n","tools = [\n",- " EdenAiTextModerationTool(providers=[\"openai\"],language=\"en\"),\n",- " EdenAiObjectDetectionTool(providers=[\"google\",\"api4ai\"]),\n",- " EdenAiTextToSpeechTool(providers=[\"amazon\"],language=\"en\",voice=\"MALE\"),\n",- " EdenAiExplicitImageTool(providers=[\"amazon\",\"google\"]),\n",+ " EdenAiTextModerationTool(providers=[\"openai\"], language=\"en\"),\n",+ " EdenAiObjectDetectionTool(providers=[\"google\", \"api4ai\"]),\n",+ " EdenAiTextToSpeechTool(providers=[\"amazon\"], language=\"en\", voice=\"MALE\"),\n",+ " EdenAiExplicitImageTool(providers=[\"amazon\", \"google\"]),\n"," EdenAiSpeechToTextTool(providers=[\"amazon\"]),\n",- " EdenAiParsingIDTool(providers=[\"amazon\",\"klippa\"],language=\"en\"),\n",- " EdenAiParsingInvoiceTool(providers=[\"amazon\",\"google\"],language=\"en\"),\n",+ " EdenAiParsingIDTool(providers=[\"amazon\", \"klippa\"], language=\"en\"),\n",+ " EdenAiParsingInvoiceTool(providers=[\"amazon\", \"google\"], language=\"en\"),\n","]\n","agent_chain = initialize_agent(\n"," tools,\n",@@ -169,7 +171,7 @@}],"source": [- "result['output']"+ "result[\"output\"]"]},{@@ -295,7 +297,7 @@}],"source": [- "result['output']"+ "result[\"output\"]"]},{@@ -414,7 +416,7 @@}],"source": [- "result['output']"+ "result[\"output\"]"]},{@@ -465,7 +467,7 @@"who is the customer ?\n","what is the company name ? \n","\"\"\"\n",- "result=agent_chain()"+ "result = agent_chain()"]},{@@ -485,7 +487,7 @@}],"source": [- "result['output']"+ "result[\"output\"]"]}],diff --git a/docs/docs/integrations/tools/google_drive.ipynb b/docs/docs/integrations/tools/google_drive.ipynbindex 6dbd337c3b..3a820e548d 100644--- a/docs/docs/integrations/tools/google_drive.ipynb+++ b/docs/docs/integrations/tools/google_drive.ipynb@@ -50,8 +50,8 @@"metadata": {},"outputs": [],"source": [- "folder_id=\"root\"\n",- "#folder_id='1yucgL9WGgWZdM1TOuKkeghlPizuzMYb5'"+ "folder_id = \"root\"\n",+ "# folder_id='1yucgL9WGgWZdM1TOuKkeghlPizuzMYb5'"]},{@@ -106,7 +106,7 @@" api_wrapper=GoogleDriveAPIWrapper(\n"," folder_id=folder_id,\n"," num_results=2,\n",- " template=\"gdrive-query-in-folder\", # Search in the body of documents\n",+ " template=\"gdrive-query-in-folder\", # Search in the body of documents\n"," )\n",")"]@@ -118,6 +118,7 @@"outputs": [],"source": ["import logging\n",+ "\n","logging.basicConfig(level=logging.INFO)"]},@@ -146,10 +147,12 @@"outputs": [],"source": ["from langchain.agents import load_tools\n",- "tools = load_tools([\"google-drive-search\"],\n",- " folder_id=folder_id,\n",- " template=\"gdrive-query-in-folder\",\n",- " )"+ "\n",+ "tools = load_tools(\n",+ " [\"google-drive-search\"],\n",+ " folder_id=folder_id,\n",+ " template=\"gdrive-query-in-folder\",\n",+ ")"]},{@@ -169,6 +172,7 @@"source": ["from langchain.llms import OpenAI\n","from langchain.agents import initialize_agent, AgentType\n",+ "\n","llm = OpenAI(temperature=0)\n","agent = initialize_agent(\n"," tools=tools,\n",@@ -185,9 +189,7 @@},"outputs": [],"source": [- "agent.run(\n",- " \"Search in google drive, who is 'Yann LeCun' ?\"\n",- ")"+ "agent.run(\"Search in google drive, who is 'Yann LeCun' ?\")"]}],diff --git a/docs/docs/integrations/tools/metaphor_search.ipynb b/docs/docs/integrations/tools/metaphor_search.ipynbindex d17081b608..54e832f09d 100644--- a/docs/docs/integrations/tools/metaphor_search.ipynb+++ b/docs/docs/integrations/tools/metaphor_search.ipynb@@ -81,18 +81,20 @@" \"\"\"Call search engine with a query.\"\"\"\n"," return client.search(query, use_autoprompt=True, num_results=5)\n","\n",+ "\n","@tool\n","def get_contents(ids: List[str]):\n"," \"\"\"Get contents of a webpage.\n",- " \n",+ "\n"," The ids passed in should be a list of ids as fetched from `search`.\n"," \"\"\"\n"," return client.get_contents(ids)\n","\n",+ "\n","@tool\n","def find_similar(url: str):\n"," \"\"\"Get search results similar to a given URL.\n",- " \n",+ "\n"," The url passed in should be a URL returned from `search`\n"," \"\"\"\n"," return client.find_similar(url, num_results=5)"@@ -121,6 +123,7 @@"outputs": [],"source": ["from langchain.chat_models import ChatOpenAI\n",+ "\n","llm = ChatOpenAI(temperature=0)"]},@@ -132,7 +135,10 @@"source": ["from langchain.agents import OpenAIFunctionsAgent\n","from langchain.schema import SystemMessage\n",- "system_message = SystemMessage(content=\"You are a web researcher who uses search engines to look up information.\")\n",+ "\n",+ "system_message = SystemMessage(\n",+ " content=\"You are a web researcher who uses search engines to look up information.\"\n",+ ")\n","prompt = OpenAIFunctionsAgent.create_prompt(system_message=system_message)\n","agent = OpenAIFunctionsAgent(llm=llm, tools=tools, prompt=prompt)"]@@ -144,6 +150,7 @@"outputs": [],"source": ["from langchain.agents import AgentExecutor\n",+ "\n","agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)"]},diff --git a/docs/docs/integrations/tools/searchapi.ipynb b/docs/docs/integrations/tools/searchapi.ipynbindex ce7982ac04..5aac68eb66 100644--- a/docs/docs/integrations/tools/searchapi.ipynb+++ b/docs/docs/integrations/tools/searchapi.ipynb@@ -135,11 +135,13 @@" Tool(\n"," name=\"Intermediate Answer\",\n"," func=search.run,\n",- " description=\"useful for when you need to ask with search\"\n",+ " description=\"useful for when you need to ask with search\",\n"," )\n","]\n","\n",- "self_ask_with_search = initialize_agent(tools, llm, agent=AgentType.SELF_ASK_WITH_SEARCH, verbose=True)\n",+ "self_ask_with_search = initialize_agent(\n",+ " tools, llm, agent=AgentType.SELF_ASK_WITH_SEARCH, verbose=True\n",+ ")\n","self_ask_with_search.run(\"Who lived longer: Plato, Socrates, or Aristotle?\")"]},diff --git a/docs/docs/integrations/tools/tavily_search.ipynb b/docs/docs/integrations/tools/tavily_search.ipynbindex 11b86ebe77..1ffc1d254d 100644--- a/docs/docs/integrations/tools/tavily_search.ipynb+++ b/docs/docs/integrations/tools/tavily_search.ipynb@@ -104,7 +104,7 @@"# run the agent\n","agent_chain.run(\n"," \"What happened in the latest burning man floods?\",\n",- ")\n"+ ")"]},{diff --git a/docs/docs/integrations/tools/yahoo_finance_news.ipynb b/docs/docs/integrations/tools/yahoo_finance_news.ipynbindex 0c9494448c..4c0797d496 100644--- a/docs/docs/integrations/tools/yahoo_finance_news.ipynb+++ b/docs/docs/integrations/tools/yahoo_finance_news.ipynb@@ -55,7 +55,7 @@"from langchain.chat_models import ChatOpenAI\n","from langchain.agents import initialize_agent, AgentType\n","from langchain.tools.yahoo_finance_news import YahooFinanceNewsTool\n",- " \n",+ "\n","\n","llm = ChatOpenAI(temperature=0.0)\n","tools = [YahooFinanceNewsTool()]\n",diff --git a/docs/docs/integrations/vectorstores/activeloop_deeplake.ipynb b/docs/docs/integrations/vectorstores/activeloop_deeplake.ipynbindex 27d5c92c18..95062b4fa8 100644--- a/docs/docs/integrations/vectorstores/activeloop_deeplake.ipynb+++ b/docs/docs/integrations/vectorstores/activeloop_deeplake.ipynb@@ -101,9 +101,7 @@"metadata": {},"outputs": [],"source": [- "db = DeepLake(\n",- " dataset_path=\"./my_deeplake/\", embedding=embeddings, overwrite=True\n",- ")\n",+ "db = DeepLake(dataset_path=\"./my_deeplake/\", embedding=embeddings, overwrite=True)\n","db.add_documents(docs)\n","# or shorter\n","# db = DeepLake.from_documents(docs, dataset_path=\"./my_deeplake/\", embedding=embeddings, overwrite=True)"@@ -202,9 +200,7 @@}],"source": [- "db = DeepLake(\n",- " dataset_path=\"./my_deeplake/\", embedding=embeddings, read_only=True\n",- ")\n",+ "db = DeepLake(dataset_path=\"./my_deeplake/\", embedding=embeddings, read_only=True)\n","docs = db.similarity_search(query)"]},diff --git a/docs/docs/integrations/vectorstores/alibabacloud_opensearch.ipynb b/docs/docs/integrations/vectorstores/alibabacloud_opensearch.ipynbindex 709420e9ca..4b290682cb 100644--- a/docs/docs/integrations/vectorstores/alibabacloud_opensearch.ipynb+++ b/docs/docs/integrations/vectorstores/alibabacloud_opensearch.ipynb@@ -264,9 +264,11 @@},"outputs": [],"source": [- "metadatas = [{'string_field': \"value1\", \"int_field\": 1, 'float_field': 1.0, 'double_field': 2.0},\n",- " {'string_field': \"value2\", \"int_field\": 2, 'float_field': 3.0, 'double_field': 4.0},\n",- " {'string_field': \"value3\", \"int_field\": 3, 'float_field': 5.0, 'double_field': 6.0}]\n",+ "metadatas = [\n",+ " {\"string_field\": \"value1\", \"int_field\": 1, \"float_field\": 1.0, \"double_field\": 2.0},\n",+ " {\"string_field\": \"value2\", \"int_field\": 2, \"float_field\": 3.0, \"double_field\": 4.0},\n",+ " {\"string_field\": \"value3\", \"int_field\": 3, \"float_field\": 5.0, \"double_field\": 6.0},\n",+ "]\n","# the key of metadatas must match field_name_mapping in settings.\n","opensearch.add_texts(texts=docs, ids=[], metadatas=metadatas)"]@@ -319,7 +321,12 @@"outputs": [],"source": ["query = \"What did the president say about Ketanji Brown Jackson\"\n",- "metadata = {'string_field': \"value1\", \"int_field\": 1, 'float_field': 1.0, 'double_field': 2.0}\n",+ "metadata = {\n",+ " \"string_field\": \"value1\",\n",+ " \"int_field\": 1,\n",+ " \"float_field\": 1.0,\n",+ " \"double_field\": 2.0,\n",+ "}\n","docs = opensearch.similarity_search(query, filter=metadata)\n","print(docs[0].page_content)"]diff --git a/docs/docs/integrations/vectorstores/azure_cosmos_db.ipynb b/docs/docs/integrations/vectorstores/azure_cosmos_db.ipynbindex ea2197ae05..7cb420c524 100644--- a/docs/docs/integrations/vectorstores/azure_cosmos_db.ipynb+++ b/docs/docs/integrations/vectorstores/azure_cosmos_db.ipynb@@ -88,10 +88,14 @@"# Set up the OpenAI Environment Variables\n","os.environ[\"OPENAI_API_TYPE\"] = \"azure\"\n","os.environ[\"OPENAI_API_VERSION\"] = \"2023-05-15\"\n",- "os.environ[\"OPENAI_API_BASE\"] = \"YOUR_OPEN_AI_ENDPOINT\" # https://example.openai.azure.com/\n",+ "os.environ[\n",+ " \"OPENAI_API_BASE\"\n",+ "] = \"YOUR_OPEN_AI_ENDPOINT\" # https://example.openai.azure.com/\n","os.environ[\"OPENAI_API_KEY\"] = \"YOUR_OPEN_AI_KEY\"\n",- "os.environ[\"OPENAI_EMBEDDINGS_DEPLOYMENT\"] = \"smart-agent-embedding-ada\" # the deployment name for the embedding model\n",- "os.environ[\"OPENAI_EMBEDDINGS_MODEL_NAME\"] = \"text-embedding-ada-002\" # the model name\n"+ "os.environ[\n",+ " \"OPENAI_EMBEDDINGS_DEPLOYMENT\"\n",+ "] = \"smart-agent-embedding-ada\" # the deployment name for the embedding model\n",+ "os.environ[\"OPENAI_EMBEDDINGS_MODEL_NAME\"] = \"text-embedding-ada-002\" # the model name"],"metadata": {"collapsed": false,@@ -122,7 +126,10 @@"from langchain.docstore.document import Document\n","from langchain.embeddings import OpenAIEmbeddings\n","from langchain.schema.embeddings import Embeddings\n",- "from langchain.vectorstores.azure_cosmos_db_vector_search import AzureCosmosDBVectorSearch, CosmosDBSimilarityType\n",+ "from langchain.vectorstores.azure_cosmos_db_vector_search import (\n",+ " AzureCosmosDBVectorSearch,\n",+ " CosmosDBSimilarityType,\n",+ ")\n","from langchain.text_splitter import CharacterTextSplitter\n","from langchain.document_loaders import TextLoader\n","\n",@@ -134,11 +141,15 @@"docs = text_splitter.split_documents(documents)\n","\n","# OpenAI Settings\n",- "model_deployment = os.getenv(\"OPENAI_EMBEDDINGS_DEPLOYMENT\", \"smart-agent-embedding-ada\")\n",+ "model_deployment = os.getenv(\n",+ " \"OPENAI_EMBEDDINGS_DEPLOYMENT\", \"smart-agent-embedding-ada\"\n",+ ")\n","model_name = os.getenv(\"OPENAI_EMBEDDINGS_MODEL_NAME\", \"text-embedding-ada-002\")\n","\n","\n",- "openai_embeddings: OpenAIEmbeddings = OpenAIEmbeddings(deployment=model_deployment, model=model_name, chunk_size=1)"+ "openai_embeddings: OpenAIEmbeddings = OpenAIEmbeddings(\n",+ " deployment=model_deployment, model=model_name, chunk_size=1\n",+ ")"],"metadata": {"collapsed": false,@@ -172,21 +183,23 @@"client: MongoClient = MongoClient(CONNECTION_STRING)\n","collection = client[DB_NAME][COLLECTION_NAME]\n","\n",- "model_deployment = os.getenv(\"OPENAI_EMBEDDINGS_DEPLOYMENT\", \"smart-agent-embedding-ada\")\n",+ "model_deployment = os.getenv(\n",+ " \"OPENAI_EMBEDDINGS_DEPLOYMENT\", \"smart-agent-embedding-ada\"\n",+ ")\n","model_name = os.getenv(\"OPENAI_EMBEDDINGS_MODEL_NAME\", \"text-embedding-ada-002\")\n","\n","vectorstore = AzureCosmosDBVectorSearch.from_documents(\n",- " docs,\n",- " openai_embeddings,\n",- " collection=collection,\n",- " index_name=INDEX_NAME,\n",+ " docs,\n",+ " openai_embeddings,\n",+ " collection=collection,\n",+ " index_name=INDEX_NAME,\n",")\n","\n","num_lists = 100\n","dimensions = 1536\n","similarity_algorithm = CosmosDBSimilarityType.COS\n","\n",- "vectorstore.create_index(num_lists, dimensions, similarity_algorithm)\n"+ "vectorstore.create_index(num_lists, dimensions, similarity_algorithm)"],"metadata": {"collapsed": false,@@ -274,7 +287,9 @@}],"source": [- "vectorstore = AzureCosmosDBVectorSearch.from_connection_string(CONNECTION_STRING, NAMESPACE, openai_embeddings, index_name=INDEX_NAME)\n",+ "vectorstore = AzureCosmosDBVectorSearch.from_connection_string(\n",+ " CONNECTION_STRING, NAMESPACE, openai_embeddings, index_name=INDEX_NAME\n",+ ")\n","\n","# perform a similarity search between a query and the ingested documents\n","query = \"What did the president say about Ketanji Brown Jackson\"\n",@@ -310,7 +325,9 @@}],"source": [- "vectorstore = AzureCosmosDBVectorSearch(collection, openai_embeddings, index_name=INDEX_NAME)\n",+ "vectorstore = AzureCosmosDBVectorSearch(\n",+ " collection, openai_embeddings, index_name=INDEX_NAME\n",+ ")\n","\n","# perform a similarity search between a query and the ingested documents\n","query = \"What did the president say about Ketanji Brown Jackson\"\n",diff --git a/docs/docs/integrations/vectorstores/azuresearch.ipynb b/docs/docs/integrations/vectorstores/azuresearch.ipynbindex 54c028e177..78a53dba3c 100644--- a/docs/docs/integrations/vectorstores/azuresearch.ipynb+++ b/docs/docs/integrations/vectorstores/azuresearch.ipynb@@ -212,8 +212,13 @@}],"source": [- "docs_and_scores = vector_store.similarity_search_with_relevance_scores(query=\"What did the president say about Ketanji Brown Jackson\", k=4, score_threshold=0.80)\n",+ "docs_and_scores = vector_store.similarity_search_with_relevance_scores(\n",+ " query=\"What did the president say about Ketanji Brown Jackson\",\n",+ " k=4,\n",+ " score_threshold=0.80,\n",+ ")\n","from pprint import pprint\n",+ "\n","pprint(docs_and_scores)"]},@@ -250,8 +255,8 @@"# Perform a hybrid search\n","docs = vector_store.similarity_search(\n"," query=\"What did the president say about Ketanji Brown Jackson\",\n",- " k=3, \n",- " search_type=\"hybrid\"\n",+ " k=3,\n",+ " search_type=\"hybrid\",\n",")\n","print(docs[0].page_content)"]@@ -278,8 +283,7 @@"source": ["# Perform a hybrid search\n","docs = vector_store.hybrid_search(\n",- " query=\"What did the president say about Ketanji Brown Jackson\", \n",- " k=3\n",+ " query=\"What did the president say about Ketanji Brown Jackson\", k=3\n",")\n","print(docs[0].page_content)"]@@ -355,7 +359,7 @@" index_name=index_name,\n"," embedding_function=embedding_function,\n"," fields=fields,\n",- ")\n"+ ")"]},{@@ -382,7 +386,7 @@" {\"title\": \"Title 2\", \"source\": \"A\", \"random\": \"48392\"},\n"," {\"title\": \"Title 3\", \"source\": \"B\", \"random\": \"32893\"},\n"," ],\n",- ")\n"+ ")"]},{@@ -426,7 +430,9 @@}],"source": [- "res = vector_store.similarity_search(query=\"Test 3 source1\", k=3, search_type=\"hybrid\", filters=\"source eq 'A'\")\n",+ "res = vector_store.similarity_search(\n",+ " query=\"Test 3 source1\", k=3, search_type=\"hybrid\", filters=\"source eq 'A'\"\n",+ ")\n","res"]},@@ -452,7 +458,7 @@" TextWeights,\n"," ScoringFunction,\n"," FreshnessScoringFunction,\n",- " FreshnessScoringParameters\n",+ " FreshnessScoringParameters,\n",")\n","\n","embeddings: OpenAIEmbeddings = OpenAIEmbeddings(deployment=model, chunk_size=1)\n",@@ -499,8 +505,8 @@" name=\"last_update\",\n"," type=SearchFieldDataType.DateTimeOffset,\n"," searchable=True,\n",- " filterable=True\n",- " )\n",+ " filterable=True,\n",+ " ),\n","]\n","# Adding a custom scoring profile with a freshness function\n","sc_name = \"scoring_profile\"\n",@@ -513,9 +519,9 @@" field_name=\"last_update\",\n"," boost=100,\n"," parameters=FreshnessScoringParameters(boosting_duration=\"P2D\"),\n",- " interpolation=\"linear\"\n",+ " interpolation=\"linear\",\n"," )\n",- " ]\n",+ " ],\n",")\n","\n","index_name = \"langchain-vector-demo-custom-scoring-profile\"\n",@@ -526,8 +532,8 @@" index_name=index_name,\n"," embedding_function=embeddings.embed_query,\n"," fields=fields,\n",- " scoring_profiles = [sc],\n",- " default_scoring_profile = sc_name\n",+ " scoring_profiles=[sc],\n",+ " default_scoring_profile=sc_name,\n",")"]},@@ -553,18 +559,35 @@"# Adding same data with different last_update to show Scoring Profile effect\n","from datetime import datetime, timedelta\n","\n",- "today = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S-00:00')\n",- "yesterday = (datetime.utcnow() - timedelta(days=1)).strftime('%Y-%m-%dT%H:%M:%S-00:00')\n",- "one_month_ago = (datetime.utcnow() - timedelta(days=30)).strftime('%Y-%m-%dT%H:%M:%S-00:00')\n",+ "today = datetime.utcnow().strftime(\"%Y-%m-%dT%H:%M:%S-00:00\")\n",+ "yesterday = (datetime.utcnow() - timedelta(days=1)).strftime(\"%Y-%m-%dT%H:%M:%S-00:00\")\n",+ "one_month_ago = (datetime.utcnow() - timedelta(days=30)).strftime(\n",+ " \"%Y-%m-%dT%H:%M:%S-00:00\"\n",+ ")\n","\n","vector_store.add_texts(\n"," [\"Test 1\", \"Test 1\", \"Test 1\"],\n"," [\n",- " {\"title\": \"Title 1\", \"source\": \"source1\", \"random\": \"10290\", \"last_update\": today},\n",- " {\"title\": \"Title 1\", \"source\": \"source1\", \"random\": \"48392\", \"last_update\": yesterday},\n",- " {\"title\": \"Title 1\", \"source\": \"source1\", \"random\": \"32893\", \"last_update\": one_month_ago},\n",+ " {\n",+ " \"title\": \"Title 1\",\n",+ " \"source\": \"source1\",\n",+ " \"random\": \"10290\",\n",+ " \"last_update\": today,\n",+ " },\n",+ " {\n",+ " \"title\": \"Title 1\",\n",+ " \"source\": \"source1\",\n",+ " \"random\": \"48392\",\n",+ " \"last_update\": yesterday,\n",+ " },\n",+ " {\n",+ " \"title\": \"Title 1\",\n",+ " \"source\": \"source1\",\n",+ " \"random\": \"32893\",\n",+ " \"last_update\": one_month_ago,\n",+ " },\n"," ],\n",- ")\n"+ ")"]},{diff --git a/docs/docs/integrations/vectorstores/chroma.ipynb b/docs/docs/integrations/vectorstores/chroma.ipynbindex a87d1ef55d..7266476425 100644--- a/docs/docs/integrations/vectorstores/chroma.ipynb+++ b/docs/docs/integrations/vectorstores/chroma.ipynb@@ -269,7 +269,11 @@" )\n","\n","# tell LangChain to use our client and collection name\n",- "db4 = Chroma(client=client, collection_name=\"my_collection\", embedding_function=embedding_function)\n",+ "db4 = Chroma(\n",+ " client=client,\n",+ " collection_name=\"my_collection\",\n",+ " embedding_function=embedding_function,\n",+ ")\n","query = \"What did the president say about Ketanji Brown Jackson\"\n","docs = db4.similarity_search(query)\n","print(docs[0].page_content)"diff --git a/docs/docs/integrations/vectorstores/clarifai.ipynb b/docs/docs/integrations/vectorstores/clarifai.ipynbindex 42dfbdd00e..5b2756c537 100644--- a/docs/docs/integrations/vectorstores/clarifai.ipynb+++ b/docs/docs/integrations/vectorstores/clarifai.ipynb@@ -133,7 +133,10 @@" \"I love playing soccer with my friends\",\n","]\n","\n",- "metadatas = [{\"id\": i, \"text\": text, \"source\": \"book 1\", \"category\": [\"books\", \"modern\"]} for i, text in enumerate(texts)]"+ "metadatas = [\n",+ " {\"id\": i, \"text\": text, \"source\": \"book 1\", \"category\": [\"books\", \"modern\"]}\n",+ " for i, text in enumerate(texts)\n",+ "]"]},{@@ -183,12 +186,16 @@"metadata": {},"outputs": [],"source": [- "# There is lots powerful filtering you can do within an app by leveraging metadata filters. \n",+ "# There is lots powerful filtering you can do within an app by leveraging metadata filters.\n","# This one will limit the similarity query to only the texts that have key of \"source\" matching value of \"book 1\"\n",- "book1_similar_docs = clarifai_vector_db.similarity_search(\"I would love to see you\", filter={\"source\": \"book 1\"})\n",+ "book1_similar_docs = clarifai_vector_db.similarity_search(\n",+ " \"I would love to see you\", filter={\"source\": \"book 1\"}\n",+ ")\n","\n","# you can also use lists in the input's metadata and then select things that match an item in the list. This is useful for categories like below:\n",- "book_category_similar_docs = clarifai_vector_db.similarity_search(\"I would love to see you\", filter={\"category\": [\"books\"]})"+ "book_category_similar_docs = clarifai_vector_db.similarity_search(\n",+ " \"I would love to see you\", filter={\"category\": [\"books\"]}\n",+ ")"]},{@@ -322,7 +329,7 @@"source": ["clarifai_vector_db = Clarifai(\n"," user_id=USER_ID,\n",- " app_id=APP_ID,\n",+ " app_id=APP_ID,\n"," pat=CLARIFAI_PAT,\n"," number_of_docs=NUMBER_OF_DOCS,\n",")"diff --git a/docs/docs/integrations/vectorstores/dingo.ipynb b/docs/docs/integrations/vectorstores/dingo.ipynbindex 37b4f04e74..05fc615f0b 100644--- a/docs/docs/integrations/vectorstores/dingo.ipynb+++ b/docs/docs/integrations/vectorstores/dingo.ipynb@@ -111,14 +111,13 @@"if index_name not in dingo_client.get_index():\n"," # we create a new index, modify to your own\n"," dingo_client.create_index(\n",- " index_name=index_name,\n",- " dimension=1536,\n",- " metric_type='cosine',\n",- " auto_id=False\n",- ")\n",+ " index_name=index_name, dimension=1536, metric_type=\"cosine\", auto_id=False\n",+ " )\n","\n","# The OpenAI embedding model `text-embedding-ada-002 uses 1536 dimensions`\n",- "docsearch = Dingo.from_documents(docs, embeddings, client=dingo_client, index_name=index_name)\n"+ "docsearch = Dingo.from_documents(\n",+ " docs, embeddings, client=dingo_client, index_name=index_name\n",+ ")"]},{diff --git a/docs/docs/integrations/vectorstores/elasticsearch.ipynb b/docs/docs/integrations/vectorstores/elasticsearch.ipynbindex 1717cb5576..cc772b4d6c 100644--- a/docs/docs/integrations/vectorstores/elasticsearch.ipynb+++ b/docs/docs/integrations/vectorstores/elasticsearch.ipynb@@ -223,16 +223,18 @@}],"source": [- "\n","db = ElasticsearchStore.from_documents(\n",- " docs, embeddings, es_url=\"http://localhost:9200\", index_name=\"test-basic\", \n",+ " docs,\n",+ " embeddings,\n",+ " es_url=\"http://localhost:9200\",\n",+ " index_name=\"test-basic\",\n",")\n","\n","db.client.indices.refresh(index=\"test-basic\")\n","\n","query = \"What did the president say about Ketanji Brown Jackson\"\n","results = db.similarity_search(query)\n",- "print(results)\n"+ "print(results)"]},{@@ -260,11 +262,10 @@}],"source": [- "\n","# Adding metadata to documents\n","for i, doc in enumerate(docs):\n"," doc.metadata[\"date\"] = f\"{range(2010, 2020)[i % 10]}-01-01\"\n",- " doc.metadata[\"rating\"] = range(1, 6)[i % 5] \n",+ " doc.metadata[\"rating\"] = range(1, 6)[i % 5]\n"," doc.metadata[\"author\"] = [\"John Doe\", \"Jane Doe\"][i % 2]\n","\n","db = ElasticsearchStore.from_documents(\n",@@ -303,7 +304,9 @@}],"source": [- "docs = db.similarity_search(query, filter=[{ \"term\": { \"metadata.author.keyword\": \"John Doe\"}}])\n",+ "docs = db.similarity_search(\n",+ " query, filter=[{\"term\": {\"metadata.author.keyword\": \"John Doe\"}}]\n",+ ")\n","print(docs[0].metadata)"]},@@ -333,7 +336,10 @@}],"source": [- "docs = db.similarity_search(query, filter=[{ \"match\": { \"metadata.author\": { \"query\": \"Jon\", \"fuzziness\": \"AUTO\" } }}])\n",+ "docs = db.similarity_search(\n",+ " query,\n",+ " filter=[{\"match\": {\"metadata.author\": {\"query\": \"Jon\", \"fuzziness\": \"AUTO\"}}}],\n",+ ")\n","print(docs[0].metadata)"]},@@ -360,7 +366,10 @@}],"source": [- "docs = db.similarity_search(\"Any mention about Fred?\", filter=[{ \"range\": { \"metadata.date\": { \"gte\": \"2010-01-01\" }}}])\n",+ "docs = db.similarity_search(\n",+ " \"Any mention about Fred?\",\n",+ " filter=[{\"range\": {\"metadata.date\": {\"gte\": \"2010-01-01\"}}}],\n",+ ")\n","print(docs[0].metadata)"]},@@ -387,7 +396,9 @@}],"source": [- "docs = db.similarity_search(\"Any mention about Fred?\", filter=[{ \"range\": { \"metadata.rating\": { \"gte\": 2 }}}])\n",+ "docs = db.similarity_search(\n",+ " \"Any mention about Fred?\", filter=[{\"range\": {\"metadata.rating\": {\"gte\": 2}}}]\n",+ ")\n","print(docs[0].metadata)"]},@@ -407,7 +418,17 @@"metadata": {},"outputs": [],"source": [- "docs = db.similarity_search(\"Any mention about Fred?\", filter=[{ \"geo_distance\": { \"distance\": \"200km\", \"metadata.geo_location\": { \"lat\": 40, \"lon\": -70 } } }])\n",+ "docs = db.similarity_search(\n",+ " \"Any mention about Fred?\",\n",+ " filter=[\n",+ " {\n",+ " \"geo_distance\": {\n",+ " \"distance\": \"200km\",\n",+ " \"metadata.geo_location\": {\"lat\": 40, \"lon\": -70},\n",+ " }\n",+ " }\n",+ " ],\n",+ ")\n","print(docs[0].metadata)"]},@@ -477,14 +498,16 @@"outputs": [],"source": ["db = ElasticsearchStore.from_documents(\n",- " docs, \n",- " embeddings, \n",- " es_url=\"http://localhost:9200\", \n",+ " docs,\n",+ " embeddings,\n",+ " es_url=\"http://localhost:9200\",\n"," index_name=\"test\",\n",- " strategy=ElasticsearchStore.ApproxRetrievalStrategy()\n",+ " strategy=ElasticsearchStore.ApproxRetrievalStrategy(),\n",")\n","\n",- "docs = db.similarity_search(query=\"What did the president say about Ketanji Brown Jackson?\", k=10)"+ "docs = db.similarity_search(\n",+ " query=\"What did the president say about Ketanji Brown Jackson?\", k=10\n",+ ")"]},{@@ -556,16 +579,16 @@"\n","# Note: This does not have an embedding function specified\n","# Instead, we will use the embedding model deployed in Elasticsearch\n",- "db = ElasticsearchStore( \n",+ "db = ElasticsearchStore(\n"," es_cloud_id=\"<your cloud id>\",\n"," es_user=\"elastic\",\n",- " es_password=\"<your password>\", \n",+ " es_password=\"<your password>\",\n"," index_name=APPROX_SELF_DEPLOYED_INDEX_NAME,\n"," query_field=\"text_field\",\n"," vector_query_field=\"vector_query_field.predicted_value\",\n"," strategy=ElasticsearchStore.ApproxRetrievalStrategy(\n",- " query_model_id=\"sentence-transformers__all-minilm-l6-v2\"\n",- " )\n",+ " query_model_id=\"sentence-transformers__all-minilm-l6-v2\"\n",+ " ),\n",")\n","\n","# Setup a Ingest Pipeline to perform the embedding\n",@@ -605,16 +628,18 @@" settings={\"index\": {\"default_pipeline\": \"test_pipeline\"}},\n",")\n","\n",- "db.from_texts([\"hello world\"], \n",+ "db.from_texts(\n",+ " [\"hello world\"],\n"," es_cloud_id=\"<cloud id>\",\n"," es_user=\"elastic\",\n",- " es_password=\"<cloud password>\", \n",+ " es_password=\"<cloud password>\",\n"," index_name=APPROX_SELF_DEPLOYED_INDEX_NAME,\n"," query_field=\"text_field\",\n"," vector_query_field=\"vector_query_field.predicted_value\",\n"," strategy=ElasticsearchStore.ApproxRetrievalStrategy(\n",- " query_model_id=\"sentence-transformers__all-minilm-l6-v2\"\n",- " ))\n",+ " query_model_id=\"sentence-transformers__all-minilm-l6-v2\"\n",+ " ),\n",+ ")\n","\n","# Perform search\n","db.similarity_search(\"hello world\", k=10)"@@ -648,21 +673,22 @@}],"source": [- "\n",- "# Note that this example doesn't have an embedding function. This is because we infer the tokens at index time and at query time within Elasticsearch. \n",+ "# Note that this example doesn't have an embedding function. This is because we infer the tokens at index time and at query time within Elasticsearch.\n","# This requires the ELSER model to be loaded and running in Elasticsearch.\n","db = ElasticsearchStore.from_documents(\n",- " docs, \n",+ " docs,\n"," es_cloud_id=\"My_deployment:dXMtY2VudHJhbDEuZ2NwLmNsb3VkLmVzLmlvOjQ0MyQ2OGJhMjhmNDc1M2Y0MWVjYTk2NzI2ZWNkMmE5YzRkNyQ3NWI4ODRjNWQ2OTU0MTYzODFjOTkxNmQ1YzYxMGI1Mw==\",\n"," es_user=\"elastic\",\n"," es_password=\"GgUPiWKwEzgHIYdHdgPk1Lwi\",\n"," index_name=\"test-elser\",\n",- " strategy=ElasticsearchStore.SparseVectorRetrievalStrategy()\n",+ " strategy=ElasticsearchStore.SparseVectorRetrievalStrategy(),\n",")\n","\n","db.client.indices.refresh(index=\"test-elser\")\n","\n",- "results = db.similarity_search(\"What did the president say about Ketanji Brown Jackson\", k=4)\n",+ "results = db.similarity_search(\n",+ " \"What did the president say about Ketanji Brown Jackson\", k=4\n",+ ")\n","print(results[0])"]},@@ -732,13 +758,7 @@" print(query_body)\n"," print()\n","\n",- " new_query_body = {\n",- " \"query\": {\n",- " \"match\": {\n",- " \"text\": query\n",- " }\n",- " }\n",- " }\n",+ " new_query_body = {\"query\": {\"match\": {\"text\": query}}}\n","\n"," print(\"Query thats actually used in Elasticsearch:\")\n"," print(new_query_body)\n",@@ -746,7 +766,12 @@"\n"," return new_query_body\n","\n",- "results = db.similarity_search(\"What did the president say about Ketanji Brown Jackson\", k=4, custom_query=custom_query)\n",+ "\n",+ "results = db.similarity_search(\n",+ " \"What did the president say about Ketanji Brown Jackson\",\n",+ " k=4,\n",+ " custom_query=custom_query,\n",+ ")\n","print(\"Results:\")\n","print(results[0])"]@@ -877,7 +902,11 @@}],"source": [- "db.client.indices.delete(index='test-metadata, test-elser, test-basic', ignore_unavailable=True, allow_no_indices=True)"+ "db.client.indices.delete(\n",+ " index=\"test-metadata, test-elser, test-basic\",\n",+ " ignore_unavailable=True,\n",+ " allow_no_indices=True,\n",+ ")"]}],diff --git a/docs/docs/integrations/vectorstores/epsilla.ipynb b/docs/docs/integrations/vectorstores/epsilla.ipynbindex fca5294418..25e081a47a 100644--- a/docs/docs/integrations/vectorstores/epsilla.ipynb+++ b/docs/docs/integrations/vectorstores/epsilla.ipynb@@ -73,7 +73,9 @@"loader = TextLoader(\"../../modules/state_of_the_union.txt\")\n","documents = loader.load()\n","\n",- "documents = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0).split_documents(documents)\n",+ "documents = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0).split_documents(\n",+ " documents\n",+ ")\n","\n","embeddings = OpenAIEmbeddings()"]@@ -101,7 +103,7 @@" client,\n"," db_path=\"/tmp/mypath\",\n"," db_name=\"MyDB\",\n",- " collection_name=\"MyCollection\"\n",+ " collection_name=\"MyCollection\",\n",")"]},diff --git a/docs/docs/integrations/vectorstores/faiss.ipynb b/docs/docs/integrations/vectorstores/faiss.ipynbindex 1dd14edd47..d960a32b23 100644--- a/docs/docs/integrations/vectorstores/faiss.ipynb+++ b/docs/docs/integrations/vectorstores/faiss.ipynb@@ -266,7 +266,7 @@"metadata": {},"outputs": [],"source": [- "pkl = db.serialize_to_bytes() # serializes the faiss index"+ "pkl = db.serialize_to_bytes() # serializes the faiss index"]},{@@ -290,7 +290,9 @@"metadata": {},"outputs": [],"source": [- "db = FAISS.deserialize_from_bytes(embeddings = embeddings, serialized = pkl) # Load the index"+ "db = FAISS.deserialize_from_bytes(\n",+ " embeddings=embeddings, serialized=pkl\n",+ ") # Load the index"]},{diff --git a/docs/docs/integrations/vectorstores/llm_rails.ipynb b/docs/docs/integrations/vectorstores/llm_rails.ipynbindex a703c2136d..24870d9176 100644--- a/docs/docs/integrations/vectorstores/llm_rails.ipynb+++ b/docs/docs/integrations/vectorstores/llm_rails.ipynb@@ -76,10 +76,10 @@"from langchain.vectorstores import LLMRails\n","import os\n","\n",- "os.environ['LLM_RAILS_DATASTORE_ID'] = 'Your datastore id '\n",- "os.environ['LLM_RAILS_API_KEY'] = 'Your API Key'\n",+ "os.environ[\"LLM_RAILS_DATASTORE_ID\"] = \"Your datastore id \"\n",+ "os.environ[\"LLM_RAILS_API_KEY\"] = \"Your API Key\"\n","\n",- "llm_rails = LLMRails.from_texts(['Your text here'])"+ "llm_rails = LLMRails.from_texts([\"Your text here\"])"]},{@@ -111,9 +111,7 @@"outputs": [],"source": ["query = \"What do you plan to do about national security?\"\n",- "found_docs = llm_rails.similarity_search(\n",- " query, k=5\n",- ")"+ "found_docs = llm_rails.similarity_search(query, k=5)"]},{@@ -186,7 +184,8 @@"source": ["query = \"What is your approach to national defense\"\n","found_docs = llm_rails.similarity_search_with_score(\n",- " query, k=5,\n",+ " query,\n",+ " k=5,\n",")"]},diff --git a/docs/docs/integrations/vectorstores/matchingengine.ipynb b/docs/docs/integrations/vectorstores/matchingengine.ipynbindex a086be2cf0..4e2629ad72 100644--- a/docs/docs/integrations/vectorstores/matchingengine.ipynb+++ b/docs/docs/integrations/vectorstores/matchingengine.ipynb@@ -29,7 +29,7 @@"metadata": {},"outputs": [],"source": [- "from langchain.vectorstores import MatchingEngine\n"+ "from langchain.vectorstores import MatchingEngine"]},{@@ -61,7 +61,7 @@"\n","vector_store.add_texts(texts=texts)\n","\n",- "vector_store.similarity_search(\"lunch\", k=2)\n"+ "vector_store.similarity_search(\"lunch\", k=2)"]},{@@ -108,7 +108,7 @@"\n","from google.cloud import aiplatform\n","import tensorflow_hub as hub\n",- "import tensorflow_text\n"+ "import tensorflow_text"]},{@@ -137,7 +137,7 @@"VPC_NETWORK_FULL = f\"projects/{PROJECT_NUMBER}/global/networks/{VPC_NETWORK}\"\n","\n","# Change this if you need the VPC to be created.\n",- "CREATE_VPC = False\n"+ "CREATE_VPC = False"]},{@@ -148,7 +148,7 @@"outputs": [],"source": ["# Set the project id\n",- "! gcloud config set project {PROJECT_ID}\n"+ "! gcloud config set project {PROJECT_ID}"]},{@@ -177,7 +177,7 @@"\n"," # Set up peering with service networking\n"," # Your account must have the \"Compute Network Admin\" role to run the following.\n",- " ! gcloud services vpc-peerings connect --service=servicenetworking.googleapis.com --network={VPC_NETWORK} --ranges={PEERING_RANGE_NAME} --project={PROJECT_ID}\n"+ " ! gcloud services vpc-peerings connect --service=servicenetworking.googleapis.com --network={VPC_NETWORK} --ranges={PEERING_RANGE_NAME} --project={PROJECT_ID}"]},{@@ -188,7 +188,7 @@"outputs": [],"source": ["# Creating bucket.\n",- "! gsutil mb -l $REGION -p $PROJECT_ID $BUCKET_URI\n"+ "! gsutil mb -l $REGION -p $PROJECT_ID $BUCKET_URI"]},{@@ -208,7 +208,7 @@"source": ["# Load the Universal Sentence Encoder module\n","module_url = \"https://tfhub.dev/google/universal-sentence-encoder-multilingual/3\"\n",- "model = hub.load(module_url)\n"+ "model = hub.load(module_url)"]},{@@ -219,7 +219,7 @@"outputs": [],"source": ["# Generate embeddings for each word\n",- "embeddings = model([\"banana\"])\n"+ "embeddings = model([\"banana\"])"]},{@@ -245,7 +245,7 @@"with open(\"data.json\", \"w\") as f:\n"," json.dump(initial_config, f)\n","\n",- "!gsutil cp data.json {EMBEDDING_DIR}/file.json\n"+ "!gsutil cp data.json {EMBEDDING_DIR}/file.json"]},{@@ -255,7 +255,7 @@"metadata": {},"outputs": [],"source": [- "aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=BUCKET_URI)\n"+ "aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=BUCKET_URI)"]},{@@ -279,7 +279,7 @@" dimensions=DIMENSIONS,\n"," approximate_neighbors_count=150,\n"," distance_measure_type=\"DOT_PRODUCT_DISTANCE\",\n",- ")\n"+ ")"]},{@@ -300,7 +300,7 @@"my_index_endpoint = aiplatform.MatchingEngineIndexEndpoint.create(\n"," display_name=f\"{DISPLAY_NAME}-endpoint\",\n"," network=VPC_NETWORK_FULL,\n",- ")\n"+ ")"]},{@@ -322,7 +322,7 @@" index=my_index, deployed_index_id=DEPLOYED_INDEX_ID\n",")\n","\n",- "my_index_endpoint.deployed_indexes\n"+ "my_index_endpoint.deployed_indexes"]}],diff --git a/docs/docs/integrations/vectorstores/milvus.ipynb b/docs/docs/integrations/vectorstores/milvus.ipynbindex a932d68221..040fa5fdcc 100644--- a/docs/docs/integrations/vectorstores/milvus.ipynb+++ b/docs/docs/integrations/vectorstores/milvus.ipynb@@ -167,7 +167,7 @@"vector_db = Milvus.from_documents(\n"," docs,\n"," embeddings,\n",- " collection_name = 'collection_1',\n",+ " collection_name=\"collection_1\",\n"," connection_args={\"host\": \"127.0.0.1\", \"port\": \"19530\"},\n",")"]@@ -188,10 +188,10 @@"outputs": [],"source": ["vector_db = Milvus(\n",- " embeddings,\n",- " connection_args={\"host\": \"127.0.0.1\", \"port\": \"19530\"},\n",- " collection_name = 'collection_1'\n",- " )"+ " embeddings,\n",+ " connection_args={\"host\": \"127.0.0.1\", \"port\": \"19530\"},\n",+ " collection_name=\"collection_1\",\n",+ ")"]},{diff --git a/docs/docs/integrations/vectorstores/momento_vector_index.ipynb b/docs/docs/integrations/vectorstores/momento_vector_index.ipynbindex e35633e79c..161f482f00 100644--- a/docs/docs/integrations/vectorstores/momento_vector_index.ipynb+++ b/docs/docs/integrations/vectorstores/momento_vector_index.ipynb@@ -48,7 +48,7 @@},"outputs": [],"source": [- "!pip install momento openai tiktoken\n"+ "!pip install momento openai tiktoken"]},{@@ -67,7 +67,7 @@"outputs": [],"source": ["import os\n",- "import getpass\n"+ "import getpass"]},{@@ -93,7 +93,7 @@"metadata": {},"outputs": [],"source": [- "os.environ[\"MOMENTO_API_KEY\"] = getpass.getpass(\"Momento API Key:\")\n"+ "os.environ[\"MOMENTO_API_KEY\"] = getpass.getpass(\"Momento API Key:\")"]},{@@ -113,7 +113,7 @@},"outputs": [],"source": [- "os.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"OpenAI API Key:\")\n"+ "os.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"OpenAI API Key:\")"]},{@@ -146,7 +146,7 @@"from langchain.embeddings.openai import OpenAIEmbeddings\n","from langchain.text_splitter import CharacterTextSplitter\n","from langchain.vectorstores import MomentoVectorIndex\n",- "from langchain.document_loaders import TextLoader\n"+ "from langchain.document_loaders import TextLoader"]},{@@ -179,7 +179,7 @@"source": ["loader = TextLoader(\"../../modules/state_of_the_union.txt\")\n","documents = loader.load()\n",- "len(documents)\n"+ "len(documents)"]},{@@ -208,7 +208,7 @@}],"source": [- "len(documents[0].page_content)\n"+ "len(documents[0].page_content)"]},{@@ -239,7 +239,7 @@"source": ["text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)\n","docs = text_splitter.split_documents(documents)\n",- "len(docs)\n"+ "len(docs)"]},{@@ -268,10 +268,8 @@"outputs": [],"source": ["vector_db = MomentoVectorIndex.from_documents(\n",- " docs,\n",- " OpenAIEmbeddings(),\n",- " index_name=\"sotu\"\n",- ")\n"+ " docs, OpenAIEmbeddings(), index_name=\"sotu\"\n",+ ")"]},{@@ -314,7 +312,7 @@"outputs": [],"source": ["query = \"What did the president say about Ketanji Brown Jackson\"\n",- "docs = vector_db.similarity_search(query)\n"+ "docs = vector_db.similarity_search(query)"]},{@@ -335,7 +333,7 @@}],"source": [- "docs[0].page_content\n"+ "docs[0].page_content"]},{@@ -378,7 +376,7 @@"outputs": [],"source": ["from langchain.chat_models import ChatOpenAI\n",- "from langchain.chains import RetrievalQA\n"+ "from langchain.chains import RetrievalQA"]},{@@ -397,7 +395,7 @@"outputs": [],"source": ["llm = ChatOpenAI(model_name=\"gpt-3.5-turbo\", temperature=0)\n",- "qa_chain = RetrievalQA.from_chain_type(llm, retriever=vector_db.as_retriever())\n"+ "qa_chain = RetrievalQA.from_chain_type(llm, retriever=vector_db.as_retriever())"]},{@@ -419,7 +417,7 @@}],"source": [- "qa_chain({\"query\": \"What did the president say about Ketanji Brown Jackson?\"})\n"+ "qa_chain({\"query\": \"What did the president say about Ketanji Brown Jackson?\"})"]},{diff --git a/docs/docs/integrations/vectorstores/mongodb_atlas.ipynb b/docs/docs/integrations/vectorstores/mongodb_atlas.ipynbindex eacbfcd94b..7e9c7d4e7e 100644--- a/docs/docs/integrations/vectorstores/mongodb_atlas.ipynb+++ b/docs/docs/integrations/vectorstores/mongodb_atlas.ipynb@@ -158,7 +158,7 @@"source": ["from langchain.document_loaders import PyPDFLoader\n","\n",- "# Load the PDF \n",+ "# Load the PDF\n","loader = PyPDFLoader(\"https://arxiv.org/pdf/2303.08774.pdf\")\n","data = loader.load()"]@@ -172,7 +172,7 @@"source": ["from langchain.text_splitter import RecursiveCharacterTextSplitter\n","\n",- "text_splitter = RecursiveCharacterTextSplitter(chunk_size = 1000, chunk_overlap = 150)\n",+ "text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150)\n","docs = text_splitter.split_documents(data)"]},@@ -198,7 +198,10 @@"\n","# insert the documents in MongoDB Atlas with their embedding\n","vector_search = MongoDBAtlasVectorSearch.from_documents(\n",- " documents=docs, embedding=OpenAIEmbeddings(disallowed_special=()), collection=MONGODB_COLLECTION, index_name=ATLAS_VECTOR_SEARCH_INDEX_NAME\n",+ " documents=docs,\n",+ " embedding=OpenAIEmbeddings(disallowed_special=()),\n",+ " collection=MONGODB_COLLECTION,\n",+ " index_name=ATLAS_VECTOR_SEARCH_INDEX_NAME,\n",")"]},@@ -246,7 +249,7 @@" MONGODB_ATLAS_CLUSTER_URI,\n"," DB_NAME + \".\" + COLLECTION_NAME,\n"," OpenAIEmbeddings(disallowed_special=()),\n",- " index_name=ATLAS_VECTOR_SEARCH_INDEX_NAME\n",+ " index_name=ATLAS_VECTOR_SEARCH_INDEX_NAME,\n",")"]},@@ -294,10 +297,7 @@"source": ["qa_retriever = vector_search.as_retriever(\n"," search_type=\"similarity\",\n",- " search_kwargs={\n",- " \"k\": 100,\n",- " \"post_filter_pipeline\": [{\"$limit\": 25}]\n",- " }\n",+ " search_kwargs={\"k\": 100, \"post_filter_pipeline\": [{\"$limit\": 25}]},\n",")"]},@@ -309,6 +309,7 @@"outputs": [],"source": ["from langchain.prompts import PromptTemplate\n",+ "\n","prompt_template = \"\"\"Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.\n","\n","{context}\n",@@ -331,12 +332,18 @@"from langchain.chat_models import ChatOpenAI\n","from langchain.llms import OpenAI\n","\n",- "qa = RetrievalQA.from_chain_type(llm=OpenAI(),chain_type=\"stuff\", retriever=qa_retriever, return_source_documents=True, chain_type_kwargs={\"prompt\": PROMPT})\n",+ "qa = RetrievalQA.from_chain_type(\n",+ " llm=OpenAI(),\n",+ " chain_type=\"stuff\",\n",+ " retriever=qa_retriever,\n",+ " return_source_documents=True,\n",+ " chain_type_kwargs={\"prompt\": PROMPT},\n",+ ")\n","\n","docs = qa({\"query\": \"gpt-4 compute requirements\"})\n","\n","print(docs[\"result\"])\n",- "print(docs['source_documents'])"+ "print(docs[\"source_documents\"])"]},{diff --git a/docs/docs/integrations/vectorstores/neo4jvector.ipynb b/docs/docs/integrations/vectorstores/neo4jvector.ipynbindex db5ca55639..36bd298f99 100644--- a/docs/docs/integrations/vectorstores/neo4jvector.ipynb+++ b/docs/docs/integrations/vectorstores/neo4jvector.ipynb@@ -107,9 +107,9 @@"password = \"pleaseletmein\"\n","\n","# You can also use environment variables instead of directly passing named parameters\n",- "#os.environ[\"NEO4J_URI\"] = \"bolt://localhost:7687\"\n",- "#os.environ[\"NEO4J_USERNAME\"] = \"neo4j\"\n",- "#os.environ[\"NEO4J_PASSWORD\"] = \"pleaseletmein\""+ "# os.environ[\"NEO4J_URI\"] = \"bolt://localhost:7687\"\n",+ "# os.environ[\"NEO4J_USERNAME\"] = \"neo4j\"\n",+ "# os.environ[\"NEO4J_PASSWORD\"] = \"pleaseletmein\""]},{@@ -252,9 +252,7 @@],"source": ["# First we create sample data in graph\n",- "store.query(\n",- " \"CREATE (p:Person {name: 'Tomaz', location:'Slovenia', hobby:'Bicycle'})\"\n",- ")"+ "store.query(\"CREATE (p:Person {name: 'Tomaz', location:'Slovenia', hobby:'Bicycle'})\")"]},{@@ -274,16 +272,16 @@"source": ["# Now we initialize from existing graph\n","existing_graph = Neo4jVector.from_existing_graph(\n",- " embedding=OpenAIEmbeddings(),\n",- " url=url,\n",- " username=username,\n",- " password=password,\n",- " index_name=\"person_index\",\n",- " node_label=\"Person\",\n",- " text_node_properties=[\"name\", \"location\"],\n",- " embedding_node_property=\"embedding\",\n",- " )\n",- "result = existing_graph.similarity_search(\"Slovenia\", k = 1)"+ " embedding=OpenAIEmbeddings(),\n",+ " url=url,\n",+ " username=username,\n",+ " password=password,\n",+ " index_name=\"person_index\",\n",+ " node_label=\"Person\",\n",+ " text_node_properties=[\"name\", \"location\"],\n",+ " embedding_node_property=\"embedding\",\n",+ ")\n",+ "result = existing_graph.similarity_search(\"Slovenia\", k=1)"]},{@@ -391,12 +389,12 @@"source": ["# The Neo4jVector Module will connect to Neo4j and create a vector and keyword indices if needed.\n","hybrid_db = Neo4jVector.from_documents(\n",- " docs, \n",- " OpenAIEmbeddings(), \n",- " url=url, \n",- " username=username, \n",+ " docs,\n",+ " OpenAIEmbeddings(),\n",+ " url=url,\n",+ " username=username,\n"," password=password,\n",- " search_type=\"hybrid\"\n",+ " search_type=\"hybrid\",\n",")"]},@@ -423,7 +421,7 @@],"source": ["index_name = \"vector\" # default index name\n",- "keyword_index_name = \"keyword\" #default keyword index name\n",+ "keyword_index_name = \"keyword\" # default keyword index name\n","\n","store = Neo4jVector.from_existing_index(\n"," OpenAIEmbeddings(),\n",@@ -432,7 +430,7 @@" password=password,\n"," index_name=index_name,\n"," keyword_index_name=keyword_index_name,\n",- " search_type=\"hybrid\"\n",+ " search_type=\"hybrid\",\n",")"]},diff --git a/docs/docs/integrations/vectorstores/nucliadb.ipynb b/docs/docs/integrations/vectorstores/nucliadb.ipynbindex f5fe2299c8..913db5a79b 100644--- a/docs/docs/integrations/vectorstores/nucliadb.ipynb+++ b/docs/docs/integrations/vectorstores/nucliadb.ipynb@@ -34,6 +34,7 @@"outputs": [],"source": ["from langchain.vectorstores.nucliadb import NucliaDB\n",+ "\n","API_KEY = \"YOUR_API_KEY\"\n","\n","ndb = NucliaDB(knowledge_box=\"YOUR_KB_ID\", local=False, api_key=API_KEY)"diff --git a/docs/docs/integrations/vectorstores/opensearch.ipynb b/docs/docs/integrations/vectorstores/opensearch.ipynbindex 935a37b4c5..08dd2920ae 100644--- a/docs/docs/integrations/vectorstores/opensearch.ipynb+++ b/docs/docs/integrations/vectorstores/opensearch.ipynb@@ -1,440 +1,444 @@{- "cells": [- {- "cell_type": "markdown",- "id": "683953b3",- "metadata": {},- "source": [- "# OpenSearch\n",- "\n",- "> [OpenSearch](https://opensearch.org/) is a scalable, flexible, and extensible open-source software suite for search, analytics, and observability applications licensed under Apache 2.0. `OpenSearch` is a distributed search and analytics engine based on `Apache Lucene`.\n",- "\n",- "\n",- "This notebook shows how to use functionality related to the `OpenSearch` database.\n",- "\n",- "To run, you should have an OpenSearch instance up and running: [see here for an easy Docker installation](https://hub.docker.com/r/opensearchproject/opensearch).\n",- "\n",- "`similarity_search` by default performs the Approximate k-NN Search which uses one of the several algorithms like lucene, nmslib, faiss recommended for\n",- "large datasets. To perform brute force search we have other search methods known as Script Scoring and Painless Scripting.\n",- "Check [this](https://opensearch.org/docs/latest/search-plugins/knn/index/) for more details."- ]- },- {- "cell_type": "markdown",- "id": "94963977-9dfc-48b7-872a-53f2947f46c6",- "metadata": {},- "source": [- "## Installation\n",- "Install the Python client."- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "6e606066-9386-4427-8a87-1b93f435c57e",- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "!pip install opensearch-py"- ]- },- {- "cell_type": "markdown",- "id": "b1fa637e-4fbf-4d5a-9188-2cad826a193e",- "metadata": {},- "source": [- "We want to use OpenAIEmbeddings so we have to get the OpenAI API Key."- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "28e5455e-322d-4010-9e3b-491d522ef5db",- "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": "aac9563e",- "metadata": {},- "outputs": [],- "source": [- "from langchain.embeddings.openai import OpenAIEmbeddings\n",- "from langchain.text_splitter import CharacterTextSplitter\n",- "from langchain.vectorstores import OpenSearchVectorSearch\n",- "from langchain.document_loaders import TextLoader"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "a3c3999a",- "metadata": {},- "outputs": [],- "source": [- "from langchain.document_loaders import TextLoader\n",- "\n",- "loader = TextLoader(\"../../modules/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": "markdown",- "id": "01a9a035",- "metadata": {},- "source": [- "## similarity_search using Approximate k-NN\n",- "\n",- "`similarity_search` using `Approximate k-NN` Search with Custom Parameters"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "803fe12b",- "metadata": {},- "outputs": [],- "source": [- "docsearch = OpenSearchVectorSearch.from_documents(\n",- " docs, embeddings, opensearch_url=\"http://localhost:9200\"\n",- ")\n",- "\n",- "# If using the default Docker installation, use this instantiation instead:\n",- "# docsearch = OpenSearchVectorSearch.from_documents(\n",- "# docs,\n",- "# embeddings,\n",- "# opensearch_url=\"https://localhost:9200\",\n",- "# http_auth=(\"admin\", \"admin\"),\n",- "# use_ssl = False,\n",- "# verify_certs = False,\n",- "# ssl_assert_hostname = False,\n",- "# ssl_show_warn = False,\n",- "# )"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "db3fa309",- "metadata": {},- "outputs": [],- "source": [- "query = \"What did the president say about Ketanji Brown Jackson\"\n",- "docs = docsearch.similarity_search(query, k=10)"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "c160d5bb",- "metadata": {},- "outputs": [],- "source": [- "print(docs[0].page_content)"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "96215c90",- "metadata": {},- "outputs": [],- "source": [- "docsearch = OpenSearchVectorSearch.from_documents(\n",- " docs,\n",- " embeddings,\n",- " opensearch_url=\"http://localhost:9200\",\n",- " engine=\"faiss\",\n",- " space_type=\"innerproduct\",\n",- " ef_construction=256,\n",- " m=48,\n",- ")\n",- "\n",- "query = \"What did the president say about Ketanji Brown Jackson\"\n",- "docs = docsearch.similarity_search(query)"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "62a7cea0",- "metadata": {},- "outputs": [],- "source": [- "print(docs[0].page_content)"- ]- },- {- "cell_type": "markdown",- "id": "0d0cd877",- "metadata": {},- "source": [- "## similarity_search using Script Scoring\n",- "\n",- "`similarity_search` using `Script Scoring` with Custom Parameters"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "0a8e3c0e",- "metadata": {},- "outputs": [],- "source": [- "docsearch = OpenSearchVectorSearch.from_documents(\n",- " docs, embeddings, opensearch_url=\"http://localhost:9200\", is_appx_search=False\n",- ")\n",- "\n",- "query = \"What did the president say about Ketanji Brown Jackson\"\n",- "docs = docsearch.similarity_search(\n",- " \"What did the president say about Ketanji Brown Jackson\",\n",- " k=1,\n",- " search_type=\"script_scoring\",\n",- ")"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "92bc40db",- "metadata": {},- "outputs": [],- "source": [- "print(docs[0].page_content)"- ]- },- {- "cell_type": "markdown",- "id": "a4af96cc",- "metadata": {},- "source": [- "## similarity_search using Painless Scripting\n",- "\n",- "`similarity_search` using `Painless Scripting` with Custom Parameters"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "6d9f436e",- "metadata": {},- "outputs": [],- "source": [- "docsearch = OpenSearchVectorSearch.from_documents(\n",- " docs, embeddings, opensearch_url=\"http://localhost:9200\", is_appx_search=False\n",- ")\n",- "filter = {\"bool\": {\"filter\": {\"term\": {\"text\": \"smuggling\"}}}}\n",- "query = \"What did the president say about Ketanji Brown Jackson\"\n",- "docs = docsearch.similarity_search(\n",- " \"What did the president say about Ketanji Brown Jackson\",\n",- " search_type=\"painless_scripting\",\n",- " space_type=\"cosineSimilarity\",\n",- " pre_filter=filter,\n",- ")"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "8ca50bce",- "metadata": {},- "outputs": [],- "source": [- "print(docs[0].page_content)"- ]- },- {- "cell_type": "markdown",- "id": "4f8fb0d0",- "metadata": {},- "source": [- "## Maximum marginal relevance search (MMR)\n",- "If you\u2019d like to look up for some similar documents, but you\u2019d also like to receive diverse results, MMR is method you should consider. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents."- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "ba85e092",- "metadata": {- "collapsed": false,- "jupyter": {- "outputs_hidden": false- }- },- "outputs": [],- "source": [- "query = \"What did the president say about Ketanji Brown Jackson\"\n",- "docs = docsearch.max_marginal_relevance_search(query, k=2, fetch_k=10, lambda_param=0.5)"- ]- },- {- "cell_type": "markdown",- "id": "73264864",- "metadata": {},- "source": [- "## Using a preexisting OpenSearch instance\n",- "\n",- "It's also possible to use a preexisting OpenSearch instance with documents that already have vectors present."- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "82a23440",- "metadata": {},- "outputs": [],- "source": [- "# this is just an example, you would need to change these values to point to another opensearch instance\n",- "docsearch = OpenSearchVectorSearch(\n",- " index_name=\"index-*\",\n",- " embedding_function=embeddings,\n",- " opensearch_url=\"http://localhost:9200\",\n",- ")\n",- "\n",- "# you can specify custom field names to match the fields you're using to store your embedding, document text value, and metadata\n",- "docs = docsearch.similarity_search(\n",- " \"Who was asking about getting lunch today?\",\n",- " search_type=\"script_scoring\",\n",- " space_type=\"cosinesimil\",\n",- " vector_field=\"message_embedding\",\n",- " text_field=\"message\",\n",- " metadata_field=\"message_metadata\",\n",- ")"- ]- },- {- "cell_type": "markdown",- "source": [- "## Using AOSS (Amazon OpenSearch Service Serverless)"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- },- "id": "5f590d35"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "# This is just an example to show how to use AOSS with faiss engine and efficient_filter, you need to set proper values.\n",- "\n",- "service = 'aoss' # must set the service as 'aoss'\n",- "region = 'us-east-2'\n",- "credentials = boto3.Session(aws_access_key_id='xxxxxx',aws_secret_access_key='xxxxx').get_credentials()\n",- "awsauth = AWS4Auth('xxxxx', 'xxxxxx', region,service, session_token=credentials.token)\n",- "\n",- "docsearch = OpenSearchVectorSearch.from_documents(\n",- " docs,\n",- " embeddings,\n",- " opensearch_url=\"host url\",\n",- " http_auth=awsauth,\n",- " timeout = 300,\n",- " use_ssl = True,\n",- " verify_certs = True,\n",- " connection_class = RequestsHttpConnection,\n",- " index_name=\"test-index-using-aoss\",\n",- " engine=\"faiss\",\n",- ")\n",- "\n",- "docs = docsearch.similarity_search(\n",- " \"What is feature selection\",\n",- " efficient_filter=filter,\n",- " k=200,\n",- ")"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "id": "de397be7"- },- {- "cell_type": "markdown",- "source": [- "## Using AOS (Amazon OpenSearch Service)"- ],- "metadata": {- "collapsed": false- },- "id": "0aa012c8"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "# This is just an example to show how to use AOS , you need to set proper values.\n",- "\n",- "service = 'es' # must set the service as 'es'\n",- "region = 'us-east-2'\n",- "credentials = boto3.Session(aws_access_key_id='xxxxxx',aws_secret_access_key='xxxxx').get_credentials()\n",- "awsauth = AWS4Auth('xxxxx', 'xxxxxx', region,service, session_token=credentials.token)\n",- "\n",- "docsearch = OpenSearchVectorSearch.from_documents(\n",- " docs,\n",- " embeddings,\n",- " opensearch_url=\"host url\",\n",- " http_auth=awsauth,\n",- " timeout = 300,\n",- " use_ssl = True,\n",- " verify_certs = True,\n",- " connection_class = RequestsHttpConnection,\n",- " index_name=\"test-index\",\n",- ")\n",- "\n",- "docs = docsearch.similarity_search(\n",- " \"What is feature selection\",\n",- " k=200,\n",- ")"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "id": "2c47e408"+ "cells": [+ {+ "cell_type": "markdown",+ "id": "683953b3",+ "metadata": {},+ "source": [+ "# OpenSearch\n",+ "\n",+ "> [OpenSearch](https://opensearch.org/) is a scalable, flexible, and extensible open-source software suite for search, analytics, and observability applications licensed under Apache 2.0. `OpenSearch` is a distributed search and analytics engine based on `Apache Lucene`.\n",+ "\n",+ "\n",+ "This notebook shows how to use functionality related to the `OpenSearch` database.\n",+ "\n",+ "To run, you should have an OpenSearch instance up and running: [see here for an easy Docker installation](https://hub.docker.com/r/opensearchproject/opensearch).\n",+ "\n",+ "`similarity_search` by default performs the Approximate k-NN Search which uses one of the several algorithms like lucene, nmslib, faiss recommended for\n",+ "large datasets. To perform brute force search we have other search methods known as Script Scoring and Painless Scripting.\n",+ "Check [this](https://opensearch.org/docs/latest/search-plugins/knn/index/) for more details."+ ]+ },+ {+ "cell_type": "markdown",+ "id": "94963977-9dfc-48b7-872a-53f2947f46c6",+ "metadata": {},+ "source": [+ "## Installation\n",+ "Install the Python client."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "6e606066-9386-4427-8a87-1b93f435c57e",+ "metadata": {+ "tags": []+ },+ "outputs": [],+ "source": [+ "!pip install opensearch-py"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "b1fa637e-4fbf-4d5a-9188-2cad826a193e",+ "metadata": {},+ "source": [+ "We want to use OpenAIEmbeddings so we have to get the OpenAI API Key."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "28e5455e-322d-4010-9e3b-491d522ef5db",+ "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": "aac9563e",+ "metadata": {},+ "outputs": [],+ "source": [+ "from langchain.embeddings.openai import OpenAIEmbeddings\n",+ "from langchain.text_splitter import CharacterTextSplitter\n",+ "from langchain.vectorstores import OpenSearchVectorSearch\n",+ "from langchain.document_loaders import TextLoader"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "a3c3999a",+ "metadata": {},+ "outputs": [],+ "source": [+ "from langchain.document_loaders import TextLoader\n",+ "\n",+ "loader = TextLoader(\"../../modules/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": "markdown",+ "id": "01a9a035",+ "metadata": {},+ "source": [+ "## similarity_search using Approximate k-NN\n",+ "\n",+ "`similarity_search` using `Approximate k-NN` Search with Custom Parameters"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "803fe12b",+ "metadata": {},+ "outputs": [],+ "source": [+ "docsearch = OpenSearchVectorSearch.from_documents(\n",+ " docs, embeddings, opensearch_url=\"http://localhost:9200\"\n",+ ")\n",+ "\n",+ "# If using the default Docker installation, use this instantiation instead:\n",+ "# docsearch = OpenSearchVectorSearch.from_documents(\n",+ "# docs,\n",+ "# embeddings,\n",+ "# opensearch_url=\"https://localhost:9200\",\n",+ "# http_auth=(\"admin\", \"admin\"),\n",+ "# use_ssl = False,\n",+ "# verify_certs = False,\n",+ "# ssl_assert_hostname = False,\n",+ "# ssl_show_warn = False,\n",+ "# )"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "db3fa309",+ "metadata": {},+ "outputs": [],+ "source": [+ "query = \"What did the president say about Ketanji Brown Jackson\"\n",+ "docs = docsearch.similarity_search(query, k=10)"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "c160d5bb",+ "metadata": {},+ "outputs": [],+ "source": [+ "print(docs[0].page_content)"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "96215c90",+ "metadata": {},+ "outputs": [],+ "source": [+ "docsearch = OpenSearchVectorSearch.from_documents(\n",+ " docs,\n",+ " embeddings,\n",+ " opensearch_url=\"http://localhost:9200\",\n",+ " engine=\"faiss\",\n",+ " space_type=\"innerproduct\",\n",+ " ef_construction=256,\n",+ " m=48,\n",+ ")\n",+ "\n",+ "query = \"What did the president say about Ketanji Brown Jackson\"\n",+ "docs = docsearch.similarity_search(query)"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "62a7cea0",+ "metadata": {},+ "outputs": [],+ "source": [+ "print(docs[0].page_content)"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "0d0cd877",+ "metadata": {},+ "source": [+ "## similarity_search using Script Scoring\n",+ "\n",+ "`similarity_search` using `Script Scoring` with Custom Parameters"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "0a8e3c0e",+ "metadata": {},+ "outputs": [],+ "source": [+ "docsearch = OpenSearchVectorSearch.from_documents(\n",+ " docs, embeddings, opensearch_url=\"http://localhost:9200\", is_appx_search=False\n",+ ")\n",+ "\n",+ "query = \"What did the president say about Ketanji Brown Jackson\"\n",+ "docs = docsearch.similarity_search(\n",+ " \"What did the president say about Ketanji Brown Jackson\",\n",+ " k=1,\n",+ " search_type=\"script_scoring\",\n",+ ")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "92bc40db",+ "metadata": {},+ "outputs": [],+ "source": [+ "print(docs[0].page_content)"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "a4af96cc",+ "metadata": {},+ "source": [+ "## similarity_search using Painless Scripting\n",+ "\n",+ "`similarity_search` using `Painless Scripting` with Custom Parameters"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "6d9f436e",+ "metadata": {},+ "outputs": [],+ "source": [+ "docsearch = OpenSearchVectorSearch.from_documents(\n",+ " docs, embeddings, opensearch_url=\"http://localhost:9200\", is_appx_search=False\n",+ ")\n",+ "filter = {\"bool\": {\"filter\": {\"term\": {\"text\": \"smuggling\"}}}}\n",+ "query = \"What did the president say about Ketanji Brown Jackson\"\n",+ "docs = docsearch.similarity_search(\n",+ " \"What did the president say about Ketanji Brown Jackson\",\n",+ " search_type=\"painless_scripting\",\n",+ " space_type=\"cosineSimilarity\",\n",+ " pre_filter=filter,\n",+ ")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "8ca50bce",+ "metadata": {},+ "outputs": [],+ "source": [+ "print(docs[0].page_content)"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "4f8fb0d0",+ "metadata": {},+ "source": [+ "## Maximum marginal relevance search (MMR)\n",+ "If you’d like to look up for some similar documents, but you’d also like to receive diverse results, MMR is method you should consider. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "ba85e092",+ "metadata": {+ "collapsed": false,+ "jupyter": {+ "outputs_hidden": false+ }+ },+ "outputs": [],+ "source": [+ "query = \"What did the president say about Ketanji Brown Jackson\"\n",+ "docs = docsearch.max_marginal_relevance_search(query, k=2, fetch_k=10, lambda_param=0.5)"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "73264864",+ "metadata": {},+ "source": [+ "## Using a preexisting OpenSearch instance\n",+ "\n",+ "It's also possible to use a preexisting OpenSearch instance with documents that already have vectors present."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "82a23440",+ "metadata": {},+ "outputs": [],+ "source": [+ "# this is just an example, you would need to change these values to point to another opensearch instance\n",+ "docsearch = OpenSearchVectorSearch(\n",+ " index_name=\"index-*\",\n",+ " embedding_function=embeddings,\n",+ " opensearch_url=\"http://localhost:9200\",\n",+ ")\n",+ "\n",+ "# you can specify custom field names to match the fields you're using to store your embedding, document text value, and metadata\n",+ "docs = docsearch.similarity_search(\n",+ " \"Who was asking about getting lunch today?\",\n",+ " search_type=\"script_scoring\",\n",+ " space_type=\"cosinesimil\",\n",+ " vector_field=\"message_embedding\",\n",+ " text_field=\"message\",\n",+ " metadata_field=\"message_metadata\",\n",+ ")"+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Using AOSS (Amazon OpenSearch Service Serverless)"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"}- ],- "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"+ },+ "id": "5f590d35"+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "# This is just an example to show how to use AOSS with faiss engine and efficient_filter, you need to set proper values.\n",+ "\n",+ "service = \"aoss\" # must set the service as 'aoss'\n",+ "region = \"us-east-2\"\n",+ "credentials = boto3.Session(\n",+ " aws_access_key_id=\"xxxxxx\", aws_secret_access_key=\"xxxxx\"\n",+ ").get_credentials()\n",+ "awsauth = AWS4Auth(\"xxxxx\", \"xxxxxx\", region, service, session_token=credentials.token)\n",+ "\n",+ "docsearch = OpenSearchVectorSearch.from_documents(\n",+ " docs,\n",+ " embeddings,\n",+ " opensearch_url=\"host url\",\n",+ " http_auth=awsauth,\n",+ " timeout=300,\n",+ " use_ssl=True,\n",+ " verify_certs=True,\n",+ " connection_class=RequestsHttpConnection,\n",+ " index_name=\"test-index-using-aoss\",\n",+ " engine=\"faiss\",\n",+ ")\n",+ "\n",+ "docs = docsearch.similarity_search(\n",+ " \"What is feature selection\",\n",+ " efficient_filter=filter,\n",+ " k=200,\n",+ ")"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "id": "de397be7"+ },+ {+ "cell_type": "markdown",+ "source": [+ "## Using AOS (Amazon OpenSearch Service)"+ ],+ "metadata": {+ "collapsed": false+ },+ "id": "0aa012c8"+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "# This is just an example to show how to use AOS , you need to set proper values.\n",+ "\n",+ "service = \"es\" # must set the service as 'es'\n",+ "region = \"us-east-2\"\n",+ "credentials = boto3.Session(\n",+ " aws_access_key_id=\"xxxxxx\", aws_secret_access_key=\"xxxxx\"\n",+ ").get_credentials()\n",+ "awsauth = AWS4Auth(\"xxxxx\", \"xxxxxx\", region, service, session_token=credentials.token)\n",+ "\n",+ "docsearch = OpenSearchVectorSearch.from_documents(\n",+ " docs,\n",+ " embeddings,\n",+ " opensearch_url=\"host url\",\n",+ " http_auth=awsauth,\n",+ " timeout=300,\n",+ " use_ssl=True,\n",+ " verify_certs=True,\n",+ " connection_class=RequestsHttpConnection,\n",+ " index_name=\"test-index\",\n",+ ")\n",+ "\n",+ "docs = docsearch.similarity_search(\n",+ " \"What is feature selection\",\n",+ " k=200,\n",+ ")"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"}+ },+ "id": "2c47e408"+ }+ ],+ "metadata": {+ "kernelspec": {+ "display_name": "Python 3 (ipykernel)",+ "language": "python",+ "name": "python3"},- "nbformat": 4,- "nbformat_minor": 5+ "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}\ No newline at end of filediff --git a/docs/docs/integrations/vectorstores/pinecone.ipynb b/docs/docs/integrations/vectorstores/pinecone.ipynbindex 2f10711479..f960eb382a 100644--- a/docs/docs/integrations/vectorstores/pinecone.ipynb+++ b/docs/docs/integrations/vectorstores/pinecone.ipynb@@ -122,11 +122,7 @@"# First, check if our index already exists. If it doesn't, we create it\n","if index_name not in pinecone.list_indexes():\n"," # we create a new index\n",- " pinecone.create_index(\n",- " name=index_name,\n",- " metric='cosine',\n",- " dimension=1536 \n",- ")\n",+ " pinecone.create_index(name=index_name, metric=\"cosine\", dimension=1536)\n","# The OpenAI embedding model `text-embedding-ada-002 uses 1536 dimensions`\n","docsearch = Pinecone.from_documents(docs, embeddings, index_name=index_name)\n","\n",diff --git a/docs/docs/integrations/vectorstores/redis.ipynb b/docs/docs/integrations/vectorstores/redis.ipynbindex 475c744073..4061c2a5f3 100644--- a/docs/docs/integrations/vectorstores/redis.ipynb+++ b/docs/docs/integrations/vectorstores/redis.ipynb@@ -256,7 +256,7 @@" embeddings,\n"," metadatas=metadata,\n"," redis_url=\"redis://localhost:6379\",\n",- " index_name=\"users\"\n",+ " index_name=\"users\",\n",")"]},@@ -567,12 +567,7 @@"source": ["# you can also add new documents as follows\n","new_document = [\"baz\"]\n",- "new_metadata = [{\n",- " \"user\": \"sam\",\n",- " \"age\": 50,\n",- " \"job\": \"janitor\",\n",- " \"credit_score\": \"high\"\n",- "}]\n",+ "new_metadata = [{\"user\": \"sam\", \"age\": 50, \"job\": \"janitor\", \"credit_score\": \"high\"}]\n","# both the document and metadata must be lists\n","rds.add_texts(new_document, new_metadata)"]@@ -704,7 +699,7 @@" embeddings,\n"," index_name=\"users\",\n"," redis_url=\"redis://localhost:6379\",\n",- " schema=\"redis_schema.yaml\"\n",+ " schema=\"redis_schema.yaml\",\n",")\n","results = new_rds.similarity_search(\"foo\", k=3)\n","print(results[0].metadata)"@@ -800,8 +795,8 @@" metadatas=metadata,\n"," redis_url=\"redis://localhost:6379\",\n"," index_name=\"users_modified\",\n",- " index_schema=index_schema, # pass in the new index schema\n",- ")\n"+ " index_schema=index_schema, # pass in the new index schema\n",+ ")"]},{@@ -998,7 +993,7 @@"results = rds.similarity_search_with_score(query, k=3, return_metadata=True)\n","\n","for result in results:\n",- " print(\"Content:\", result[0].page_content, \" --- Score: \", result[1])\n"+ " print(\"Content:\", result[0].page_content, \" --- Score: \", result[1])"]},{@@ -1047,7 +1042,10 @@"metadata": {},"outputs": [],"source": [- "retriever = rds.as_retriever(search_type=\"similarity_distance_threshold\", search_kwargs={\"k\": 4, \"distance_threshold\": 0.1})"+ "retriever = rds.as_retriever(\n",+ " search_type=\"similarity_distance_threshold\",\n",+ " search_kwargs={\"k\": 4, \"distance_threshold\": 0.1},\n",+ ")"]},{@@ -1086,7 +1084,10 @@"metadata": {},"outputs": [],"source": [- "retriever = rds.as_retriever(search_type=\"similarity_score_threshold\", search_kwargs={\"score_threshold\": 0.9, \"k\": 10})"+ "retriever = rds.as_retriever(\n",+ " search_type=\"similarity_score_threshold\",\n",+ " search_kwargs={\"score_threshold\": 0.9, \"k\": 10},\n",+ ")"]},{@@ -1117,7 +1118,9 @@"metadata": {},"outputs": [],"source": [- "retriever = rds.as_retriever(search_type=\"mmr\", search_kwargs={\"fetch_k\": 20, \"k\": 4, \"lambda_mult\": 0.1})"+ "retriever = rds.as_retriever(\n",+ " search_type=\"mmr\", search_kwargs={\"fetch_k\": 20, \"k\": 4, \"lambda_mult\": 0.1}\n",+ ")"]},{@@ -1197,8 +1200,14 @@],"source": ["# delete the indices too\n",- "Redis.drop_index(index_name=\"users\", delete_documents=True, redis_url=\"redis://localhost:6379\")\n",- "Redis.drop_index(index_name=\"users_modified\", delete_documents=True, redis_url=\"redis://localhost:6379\")"+ "Redis.drop_index(\n",+ " index_name=\"users\", delete_documents=True, redis_url=\"redis://localhost:6379\"\n",+ ")\n",+ "Redis.drop_index(\n",+ " index_name=\"users_modified\",\n",+ " delete_documents=True,\n",+ " redis_url=\"redis://localhost:6379\",\n",+ ")"]},{diff --git a/docs/docs/integrations/vectorstores/rockset.ipynb b/docs/docs/integrations/vectorstores/rockset.ipynbindex 497c3657d5..09c4299983 100644--- a/docs/docs/integrations/vectorstores/rockset.ipynb+++ b/docs/docs/integrations/vectorstores/rockset.ipynb@@ -28,26 +28,21 @@]},{- "cell_type": "code",- "execution_count": null,- "id": "aac58387",+ "attachments": {},+ "cell_type": "markdown",+ "id": "382952d8-6bbd-447f-903c-4437ddbeec0c","metadata": {"vscode": {"languageId": "sql"}},- "outputs": [],"source": [+ "```\n","SELECT _input.* EXCEPT(_meta), \n","VECTOR_ENFORCE(_input.description_embedding, #length_of_vector_embedding, 'float') as description_embedding \n",- "FROM _input"- ]- },- {- "cell_type": "markdown",- "id": "df380e1c",- "metadata": {},- "source": [+ "FROM _input\n",+ "```\n",+ "\n","2. After creating your collection, use the console to retrieve an [API key](https://rockset.com/docs/iam/#users-api-keys-and-roles). For the purpose of this notebook, we assume you are using the `Oregon(us-west-2)` region.\n","\n","3. Install the [rockset-python-client](https://github.com/rockset/rockset-python-client) to enable LangChain to communicate directly with `Rockset`."@@ -60,7 +55,7 @@"metadata": {},"outputs": [],"source": [- "pip install rockset"+ "!pip install rockset"]},{@@ -86,13 +81,15 @@"import os\n","import rockset\n","\n",- "ROCKSET_API_KEY = os.environ.get(\"ROCKSET_API_KEY\") # Verify ROCKSET_API_KEY environment variable\n",- "ROCKSET_API_SERVER = rockset.Regions.usw2a1 # Verify Rockset region\n",+ "ROCKSET_API_KEY = os.environ.get(\n",+ " \"ROCKSET_API_KEY\"\n",+ ") # Verify ROCKSET_API_KEY environment variable\n",+ "ROCKSET_API_SERVER = rockset.Regions.usw2a1 # Verify Rockset region\n","rockset_client = rockset.RocksetClient(ROCKSET_API_SERVER, ROCKSET_API_KEY)\n","\n",- "COLLECTION_NAME='langchain_demo'\n",- "TEXT_KEY='description'\n",- "EMBEDDING_KEY='description_embedding'"+ "COLLECTION_NAME = \"langchain_demo\"\n",+ "TEXT_KEY = \"description\"\n",+ "EMBEDDING_KEY = \"description_embedding\""]},{@@ -115,7 +112,7 @@"from langchain.document_loaders import TextLoader\n","from langchain.vectorstores import Rockset\n","\n",- "loader = TextLoader('../../modules/state_of_the_union.txt')\n",+ "loader = TextLoader(\"../../modules/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)"@@ -136,7 +133,7 @@"metadata": {},"outputs": [],"source": [- "embeddings = OpenAIEmbeddings() # Verify OPENAI_API_KEY environment variable\n",+ "embeddings = OpenAIEmbeddings() # Verify OPENAI_API_KEY environment variable\n","\n","docsearch = Rockset(\n"," client=rockset_client,\n",@@ -146,7 +143,7 @@" embedding_key=EMBEDDING_KEY,\n",")\n","\n",- "ids=docsearch.add_texts(\n",+ "ids = docsearch.add_texts(\n"," texts=[d.page_content for d in docs],\n"," metadatas=[d.metadata for d in docs],\n",")"@@ -173,7 +170,7 @@")\n","print(\"output length:\", len(output))\n","for d, dist in output:\n",- " print(dist, d.metadata, d.page_content[:20] + '...')\n",+ " print(dist, d.metadata, d.page_content[:20] + \"...\")\n","\n","##\n","# output length: 4\n",@@ -206,7 +203,7 @@")\n","print(\"output length:\", len(output))\n","for d, dist in output:\n",- " print(dist, d.metadata, d.page_content[:20] + '...')\n",+ " print(dist, d.metadata, d.page_content[:20] + \"...\")\n","\n","##\n","# output length: 4\n",@@ -251,6 +248,14 @@"\n","Keep an eye on https://rockset.com/ for future updates in this space."]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "054de494-e6c0-453a-becd-ebfb2fdf541a",+ "metadata": {},+ "outputs": [],+ "source": []}],"metadata": {@@ -269,7 +274,7 @@"name": "python","nbconvert_exporter": "python","pygments_lexer": "ipython3",- "version": "3.10.12"+ "version": "3.9.1"}},"nbformat": 4,diff --git a/docs/docs/integrations/vectorstores/scann.ipynb b/docs/docs/integrations/vectorstores/scann.ipynbindex 4d63bd2883..6fd218745b 100644--- a/docs/docs/integrations/vectorstores/scann.ipynb+++ b/docs/docs/integrations/vectorstores/scann.ipynb@@ -70,6 +70,7 @@"docs = text_splitter.split_documents(documents)\n","\n","from langchain.embeddings import TensorflowHubEmbeddings\n",+ "\n","embeddings = HuggingFaceEmbeddings()\n","\n","db = ScaNN.from_documents(docs, embeddings)\n",@@ -101,12 +102,12 @@"from langchain.chains import RetrievalQA\n","from langchain.chat_models import google_palm\n","\n",- "palm_client = google_palm.ChatGooglePalm(google_api_key='YOUR_GOOGLE_PALM_API_KEY')\n",+ "palm_client = google_palm.ChatGooglePalm(google_api_key=\"YOUR_GOOGLE_PALM_API_KEY\")\n","\n","qa = RetrievalQA.from_chain_type(\n"," llm=palm_client,\n"," chain_type=\"stuff\",\n",- " retriever=db.as_retriever(search_kwargs={'k': 10})\n",+ " retriever=db.as_retriever(search_kwargs={\"k\": 10}),\n",")"]},@@ -125,7 +126,7 @@}],"source": [- "print(qa.run('What did the president say about Ketanji Brown Jackson?'))"+ "print(qa.run(\"What did the president say about Ketanji Brown Jackson?\"))"]},{@@ -143,7 +144,7 @@}],"source": [- "print(qa.run('What did the president say about Michael Phelps?'))"+ "print(qa.run(\"What did the president say about Michael Phelps?\"))"]},{@@ -161,8 +162,8 @@"metadata": {},"outputs": [],"source": [- "db.save_local('/tmp/db', 'state_of_union')\n",- "restored_db = ScaNN.load_local('/tmp/db', embeddings, index_name='state_of_union')"+ "db.save_local(\"/tmp/db\", \"state_of_union\")\n",+ "restored_db = ScaNN.load_local(\"/tmp/db\", embeddings, index_name=\"state_of_union\")"]}],diff --git a/docs/docs/integrations/vectorstores/sqlitevss.ipynb b/docs/docs/integrations/vectorstores/sqlitevss.ipynbindex 0d1e7b97e3..3a35f782ac 100644--- a/docs/docs/integrations/vectorstores/sqlitevss.ipynb+++ b/docs/docs/integrations/vectorstores/sqlitevss.ipynb@@ -83,7 +83,7 @@" texts=texts,\n"," embedding=embedding_function,\n"," table=\"state_union\",\n",- " db_file=\"/tmp/vss.db\"\n",+ " db_file=\"/tmp/vss.db\",\n",")\n","\n","# query it\n",@@ -146,9 +146,7 @@"connection = SQLiteVSS.create_connection(db_file=\"/tmp/vss.db\")\n","\n","db1 = SQLiteVSS(\n",- " table=\"state_union\",\n",- " embedding=embedding_function,\n",- " connection=connection\n",+ " table=\"state_union\", embedding=embedding_function, connection=connection\n",")\n","\n","db1.add_texts([\"Ketanji Brown Jackson is awesome\"])\n",@@ -174,6 +172,7 @@"source": ["# Cleaning up\n","import os\n",+ "\n","os.remove(\"/tmp/vss.db\")"]},diff --git a/docs/docs/integrations/vectorstores/supabase.ipynb b/docs/docs/integrations/vectorstores/supabase.ipynbindex 033a5d381f..e6f0431c9d 100644--- a/docs/docs/integrations/vectorstores/supabase.ipynb+++ b/docs/docs/integrations/vectorstores/supabase.ipynb@@ -182,7 +182,6 @@},"outputs": [],"source": [- "\n","from langchain.text_splitter import CharacterTextSplitter\n","from langchain.document_loaders import TextLoader\n","\n",@@ -207,8 +206,14 @@"metadata": {},"outputs": [],"source": [- "\n",- "vector_store = SupabaseVectorStore.from_documents(docs, embeddings, client=supabase, table_name=\"documents\", query_name=\"match_documents\", chunk_size=500)"+ "vector_store = SupabaseVectorStore.from_documents(\n",+ " docs,\n",+ " embeddings,\n",+ " client=supabase,\n",+ " table_name=\"documents\",\n",+ " query_name=\"match_documents\",\n",+ " chunk_size=500,\n",+ ")"]},{@@ -226,7 +231,12 @@"metadata": {},"outputs": [],"source": [- "vector_store = SupabaseVectorStore(embedding=embeddings, client=supabase, table_name=\"documents\", query_name=\"match_documents\")"+ "vector_store = SupabaseVectorStore(\n",+ " embedding=embeddings,\n",+ " client=supabase,\n",+ " table_name=\"documents\",\n",+ " query_name=\"match_documents\",\n",+ ")"]},{diff --git a/docs/docs/integrations/vectorstores/tair.ipynb b/docs/docs/integrations/vectorstores/tair.ipynbindex 5012d9e61a..361a1da7d7 100644--- a/docs/docs/integrations/vectorstores/tair.ipynb+++ b/docs/docs/integrations/vectorstores/tair.ipynb@@ -66,7 +66,7 @@"# drop first if index already exists\n","Tair.drop_index(tair_url=tair_url)\n","\n",- "vector_store = Tair.from_documents(docs, embeddings, tair_url=tair_url)\n"+ "vector_store = Tair.from_documents(docs, embeddings, tair_url=tair_url)"]},{@@ -103,7 +103,9 @@"# drop first if index already exists\n","Tair.drop_index(tair_url=tair_url)\n","\n",- "vector_store = Tair.from_documents(docs, embeddings, tair_url=tair_url, index_params={\"lexical_algorithm\":\"bm25\"})"+ "vector_store = Tair.from_documents(\n",+ " docs, embeddings, tair_url=tair_url, index_params={\"lexical_algorithm\": \"bm25\"}\n",+ ")"]},{@@ -121,7 +123,7 @@"source": ["query = \"What did the president say about Ketanji Brown Jackson\"\n","# hybrid_ratio: 0.5 hybrid search, 0.9999 vector search, 0.0001 text search\n",- "kwargs = {\"TEXT\" : query, \"hybrid_ratio\" : 0.5}\n",+ "kwargs = {\"TEXT\": query, \"hybrid_ratio\": 0.5}\n","docs = vector_store.similarity_search(query, **kwargs)\n","docs[0]"]diff --git a/docs/docs/integrations/vectorstores/tencentvectordb.ipynb b/docs/docs/integrations/vectorstores/tencentvectordb.ipynbindex 66090f2de7..fc0b867ac1 100644--- a/docs/docs/integrations/vectorstores/tencentvectordb.ipynb+++ b/docs/docs/integrations/vectorstores/tencentvectordb.ipynb@@ -59,10 +59,12 @@"metadata": {},"outputs": [],"source": [- "conn_params = ConnectionParams(url=\"http://10.0.X.X\", \n",- " key=\"eC4bLRy2va******************************\", \n",- " username=\"root\", \n",- " timeout=20)\n",+ "conn_params = ConnectionParams(\n",+ " url=\"http://10.0.X.X\",\n",+ " key=\"eC4bLRy2va******************************\",\n",+ " username=\"root\",\n",+ " timeout=20,\n",+ ")\n","\n","vector_db = TencentVectorDB.from_documents(\n"," docs,\n",diff --git a/docs/docs/integrations/vectorstores/timescalevector.ipynb b/docs/docs/integrations/vectorstores/timescalevector.ipynbindex 8fcf2a9a36..f4009e7e03 100644--- a/docs/docs/integrations/vectorstores/timescalevector.ipynb+++ b/docs/docs/integrations/vectorstores/timescalevector.ipynb@@ -70,11 +70,13 @@"outputs": [],"source": ["import os\n",+ "\n","# Run export OPENAI_API_KEY=sk-YOUR_OPENAI_API_KEY...\n","# Get openAI api key by reading local .env file\n","from dotenv import load_dotenv, find_dotenv\n",+ "\n","_ = load_dotenv(find_dotenv())\n",- "OPENAI_API_KEY = os.environ['OPENAI_API_KEY']"+ "OPENAI_API_KEY = os.environ[\"OPENAI_API_KEY\"]"]},{@@ -84,9 +86,9 @@"outputs": [],"source": ["# Get the API key and save it as an environment variable\n",- "#import os\n",- "#import getpass\n",- "#os.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"OpenAI API Key:\")"+ "# import os\n",+ "# import getpass\n",+ "# os.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"OpenAI API Key:\")"]},{@@ -171,12 +173,12 @@"metadata": {},"outputs": [],"source": [- "# Timescale Vector needs the service url to your cloud database. You can see this as soon as you create the \n",+ "# Timescale Vector needs the service url to your cloud database. You can see this as soon as you create the\n","# service in the cloud UI or in your credentials.sql file\n",- "SERVICE_URL = os.environ['TIMESCALE_SERVICE_URL']\n",+ "SERVICE_URL = os.environ[\"TIMESCALE_SERVICE_URL\"]\n","\n","# Specify directly if testing\n",- "#SERVICE_URL = \"postgres://tsdbadmin:<password>@<id>.tsdb.cloud.timescale.com:<port>/tsdb?sslmode=require\"\n",+ "# SERVICE_URL = \"postgres://tsdbadmin:<password>@<id>.tsdb.cloud.timescale.com:<port>/tsdb?sslmode=require\"\n","\n","# # You can get also it from an enviornment variables. We suggest using a .env file.\n","# import os\n",@@ -353,13 +355,15 @@"source": ["# Initialize GPT3.5 model\n","from langchain.chat_models import ChatOpenAI\n",- "llm = ChatOpenAI(temperature = 0.1, model = 'gpt-3.5-turbo-16k')\n",+ "\n",+ "llm = ChatOpenAI(temperature=0.1, model=\"gpt-3.5-turbo-16k\")\n","\n","# Initialize a RetrievalQA class from a stuff chain\n","from langchain.chains import RetrievalQA\n",+ "\n","qa_stuff = RetrievalQA.from_chain_type(\n",- " llm=llm, \n",- " chain_type=\"stuff\", \n",+ " llm=llm,\n",+ " chain_type=\"stuff\",\n"," retriever=retriever,\n"," verbose=True,\n",")"@@ -456,11 +460,13 @@"outputs": [],"source": ["from timescale_vector import client\n",+ "\n",+ "\n","# Function to take in a date string in the past and return a uuid v1\n","def create_uuid(date_string: str):\n"," if date_string is None:\n"," return None\n",- " time_format = '%a %b %d %H:%M:%S %Y %z'\n",+ " time_format = \"%a %b %d %H:%M:%S %Y %z\"\n"," datetime_obj = datetime.strptime(date_string, time_format)\n"," uuid = client.uuid_from_time(datetime_obj)\n"," return str(uuid)"@@ -487,9 +493,10 @@" start = input_string.find(\"<\")\n"," end = input_string.find(\">\")\n"," name = input_string[:start].strip()\n",- " email = input_string[start+1:end].strip()\n",+ " email = input_string[start + 1 : end].strip()\n"," return name, email\n","\n",+ "\n","# Helper function to transform a date string into a timestamp_tz string\n","def create_date(input_string: str) -> datetime:\n"," if input_string is None:\n",@@ -521,9 +528,12 @@" timezone_hours = timezone_offset_minutes // 60 # Calculate the hours\n"," timezone_minutes = timezone_offset_minutes % 60 # Calculate the remaining minutes\n"," # Create a formatted string for the timestamptz in PostgreSQL format\n",- " timestamp_tz_str = f\"{year}-{month}-{day} {time}+{timezone_hours:02}{timezone_minutes:02}\"\n",+ " timestamp_tz_str = (\n",+ " f\"{year}-{month}-{day} {time}+{timezone_hours:02}{timezone_minutes:02}\"\n",+ " )\n"," return timestamp_tz_str\n","\n",+ "\n","# Metadata extraction function to extract metadata from a JSON record\n","def extract_metadata(record: dict, metadata: dict) -> dict:\n"," record_name, record_email = split_name(record[\"author\"])\n",@@ -581,9 +591,9 @@"# Load data from JSON file and extract metadata\n","loader = JSONLoader(\n"," file_path=FILE_PATH,\n",- " jq_schema='.commit_history[]',\n",+ " jq_schema=\".commit_history[]\",\n"," text_content=False,\n",- " metadata_func=extract_metadata\n",+ " metadata_func=extract_metadata,\n",")\n","documents = loader.load()\n","\n",@@ -646,7 +656,8 @@"# Split the documents into chunks for embedding\n","text_splitter = CharacterTextSplitter(\n"," chunk_size=1000,\n",- " chunk_overlap=200,)\n",+ " chunk_overlap=200,\n",+ ")\n","docs = text_splitter.split_documents(documents)"]},@@ -676,12 +687,13 @@"\n","# Create a Timescale Vector instance from the collection of documents\n","db = TimescaleVector.from_documents(\n",- " embedding=embeddings,\n",- " ids = [doc.metadata[\"id\"] for doc in docs],\n",- " documents=docs,\n",- " collection_name=COLLECTION_NAME,\n",- " service_url=SERVICE_URL,\n",- " time_partition_interval=timedelta(days = 7),)"+ " embedding=embeddings,\n",+ " ids=[doc.metadata[\"id\"] for doc in docs],\n",+ " documents=docs,\n",+ " collection_name=COLLECTION_NAME,\n",+ " service_url=SERVICE_URL,\n",+ " time_partition_interval=timedelta(days=7),\n",+ ")"]},{@@ -705,9 +717,9 @@"outputs": [],"source": ["# Time filter variables\n",- "start_dt = datetime(2023, 8, 1, 22, 10, 35) # Start date = 1 August 2023, 22:10:35\n",- "end_dt = datetime(2023, 8, 30, 22, 10, 35) # End date = 30 August 2023, 22:10:35\n",- "td = timedelta(days=7) # Time delta = 7 days\n",+ "start_dt = datetime(2023, 8, 1, 22, 10, 35) # Start date = 1 August 2023, 22:10:35\n",+ "end_dt = datetime(2023, 8, 30, 22, 10, 35) # End date = 30 August 2023, 22:10:35\n",+ "td = timedelta(days=7) # Time delta = 7 days\n","\n","query = \"What's new with TimescaleDB functions?\""]@@ -754,7 +766,9 @@],"source": ["# Method 1: Query for vectors between start_date and end_date\n",- "docs_with_score = db.similarity_search_with_score(query, start_date=start_dt, end_date=end_dt)\n",+ "docs_with_score = db.similarity_search_with_score(\n",+ " query, start_date=start_dt, end_date=end_dt\n",+ ")\n","\n","for doc, score in docs_with_score:\n"," print(\"-\" * 80)\n",@@ -815,14 +829,16 @@"source": ["# Method 2: Query for vectors between start_dt and a time delta td later\n","# Most relevant vectors between 1 August and 7 days later\n",- "docs_with_score = db.similarity_search_with_score(query, start_date=start_dt, time_delta=td)\n",+ "docs_with_score = db.similarity_search_with_score(\n",+ " query, start_date=start_dt, time_delta=td\n",+ ")\n","\n","for doc, score in docs_with_score:\n"," print(\"-\" * 80)\n"," print(\"Score: \", score)\n"," print(\"Date: \", doc.metadata[\"date\"])\n"," print(doc.page_content)\n",- " print(\"-\" * 80)\n"+ " print(\"-\" * 80)"]},{@@ -930,7 +946,7 @@],"source": ["# Method 4: Query all vectors after start_date\n",- "docs_with_score = db.similarity_search_with_score(query,start_date=start_dt)\n",+ "docs_with_score = db.similarity_search_with_score(query, start_date=start_dt)\n","\n","for doc, score in docs_with_score:\n"," print(\"-\" * 80)\n",@@ -1035,17 +1051,21 @@],"source": ["from langchain.chat_models import ChatOpenAI\n",- "llm = ChatOpenAI(temperature = 0.1, model = 'gpt-3.5-turbo-16k')\n",+ "\n",+ "llm = ChatOpenAI(temperature=0.1, model=\"gpt-3.5-turbo-16k\")\n","\n","from langchain.chains import RetrievalQA\n",+ "\n","qa_stuff = RetrievalQA.from_chain_type(\n",- " llm=llm, \n",- " chain_type=\"stuff\", \n",+ " llm=llm,\n",+ " chain_type=\"stuff\",\n"," retriever=retriever,\n"," verbose=True,\n",")\n","\n",- "query = \"What's new with the timescaledb functions? Tell me when these changes were made.\"\n",+ "query = (\n",+ " \"What's new with the timescaledb functions? Tell me when these changes were made.\"\n",+ ")\n","response = qa_stuff.run(query)\n","print(response)"]@@ -1128,12 +1148,12 @@"metadata": {},"outputs": [],"source": [- "#drop the old index\n",+ "# drop the old index\n","db.drop_index()\n","\n","# create an index\n",- "# Note: You don't need to specify m and ef_construction parameters as we set smart defaults. \n",- "db.create_index(index_type=\"tsv\", max_alpha=1.0, num_neighbors=50) "+ "# Note: You don't need to specify m and ef_construction parameters as we set smart defaults.\n",+ "db.create_index(index_type=\"tsv\", max_alpha=1.0, num_neighbors=50)"]},{@@ -1151,11 +1171,11 @@"metadata": {},"outputs": [],"source": [- "#drop the old index\n",+ "# drop the old index\n","db.drop_index()\n","\n","# Create an HNSW index\n",- "# Note: You don't need to specify m and ef_construction parameters as we set smart defaults. \n",+ "# Note: You don't need to specify m and ef_construction parameters as we set smart defaults.\n","db.create_index(index_type=\"hnsw\", m=16, ef_construction=64)"]},@@ -1165,7 +1185,7 @@"metadata": {},"outputs": [],"source": [- "#drop the old index\n",+ "# drop the old index\n","db.drop_index()\n","\n","# Create an IVFFLAT index\n",@@ -1187,7 +1207,7 @@"metadata": {},"outputs": [],"source": [- "#drop the old index\n",+ "# drop the old index\n","db.drop_index()\n","# Create a new timescale vector index\n","db.create_index()"@@ -1266,14 +1286,19 @@" name=\"author_email\",\n"," description=\"The email address of the author of the commit\",\n"," type=\"string\",\n",- " )\n",+ " ),\n","]\n","document_content_description = \"The git log commit summary containing the commit hash, author, date of commit, change summary and change details\"\n","\n","# Instantiate the self-query retriever from an LLM\n","llm = OpenAI(temperature=0)\n","retriever = SelfQueryRetriever.from_llm(\n",- " llm, vectorstore, document_content_description, metadata_field_info, enable_limit=True, verbose=True\n",+ " llm,\n",+ " vectorstore,\n",+ " document_content_description,\n",+ " metadata_field_info,\n",+ " enable_limit=True,\n",+ " verbose=True,\n",")"]},@@ -1387,7 +1412,9 @@],"source": ["# This example specifies a query and filter\n",- "retriever.get_relevant_documents(\"What commits about timescaledb_functions did Sven Klemm add?\")"+ "retriever.get_relevant_documents(\n",+ " \"What commits about timescaledb_functions did Sven Klemm add?\"\n",+ ")"]},{@@ -1447,7 +1474,9 @@],"source": ["# This example specifies a query and a LIMIT value\n",- "retriever.get_relevant_documents(\"What are two commits about hierarchical continuous aggregates?\")"+ "retriever.get_relevant_documents(\n",+ " \"What are two commits about hierarchical continuous aggregates?\"\n",+ ")"]},{@@ -1620,12 +1649,23 @@}],"source": [- "vectorstore.add_documents([Document(page_content=\"Hello World\", metadata={\"source\": \"www.example.com/hello\"})])\n",- "vectorstore.add_documents([Document(page_content=\"Adios\", metadata={\"source\": \"www.example.com/adios\"})])\n",+ "vectorstore.add_documents(\n",+ " [Document(page_content=\"Hello World\", metadata={\"source\": \"www.example.com/hello\"})]\n",+ ")\n",+ "vectorstore.add_documents(\n",+ " [Document(page_content=\"Adios\", metadata={\"source\": \"www.example.com/adios\"})]\n",+ ")\n","\n","vectorstore.delete_by_metadata({\"source\": \"www.example.com/adios\"})\n","\n",- "vectorstore.add_documents([Document(page_content=\"Adios, but newer!\", metadata={\"source\": \"www.example.com/adios\"})])"+ "vectorstore.add_documents(\n",+ " [\n",+ " Document(\n",+ " page_content=\"Adios, but newer!\",\n",+ " metadata={\"source\": \"www.example.com/adios\"},\n",+ " )\n",+ " ]\n",+ ")"]},{diff --git a/docs/docs/integrations/vectorstores/vald.ipynb b/docs/docs/integrations/vectorstores/vald.ipynbindex 878f8c55a6..c726f7cf4b 100644--- a/docs/docs/integrations/vectorstores/vald.ipynb+++ b/docs/docs/integrations/vectorstores/vald.ipynb@@ -47,7 +47,7 @@"from langchain.text_splitter import CharacterTextSplitter\n","from langchain.vectorstores import Vald\n","\n",- "raw_documents = TextLoader('state_of_the_union.txt').load()\n",+ "raw_documents = TextLoader(\"state_of_the_union.txt\").load()\n","text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)\n","documents = text_splitter.split_documents(raw_documents)\n","embeddings = HuggingFaceEmbeddings()\n",diff --git a/docs/docs/integrations/vectorstores/vearch.ipynb b/docs/docs/integrations/vectorstores/vearch.ipynbindex eca0218a4f..b4965ccafe 100644--- a/docs/docs/integrations/vectorstores/vearch.ipynb+++ b/docs/docs/integrations/vectorstores/vearch.ipynb@@ -23,7 +23,7 @@"from langchain.vectorstores.vearch import Vearch\n","\n","# repalce to your local model path\n",- "model_path =\"/data/zhx/zhx/langchain-ChatGLM_new/chatglm2-6b\" \n",+ "model_path = \"/data/zhx/zhx/langchain-ChatGLM_new/chatglm2-6b\"\n","\n","tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)\n","model = AutoModel.from_pretrained(model_path, trust_remote_code=True).half().cuda(0)"@@ -71,17 +71,17 @@],"source": ["# Add your local knowledge files\n",- "file_path = \"/data/zhx/zhx/langchain-ChatGLM_new/knowledge_base/天龙八部/lingboweibu.txt\"#Your local file path\"\n",- "loader = TextLoader(file_path,encoding=\"utf-8\")\n",+ "file_path = \"/data/zhx/zhx/langchain-ChatGLM_new/knowledge_base/天龙八部/lingboweibu.txt\" # Your local file path\"\n",+ "loader = TextLoader(file_path, encoding=\"utf-8\")\n","documents = loader.load()\n","\n","# split text into sentences and embedding the sentences\n","text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100)\n","texts = text_splitter.split_documents(documents)\n","\n",- "#replace to your model path\n",- "embedding_path = '/data/zhx/zhx/langchain-ChatGLM_new/text2vec/text2vec-large-chinese'\n",- "embeddings = HuggingFaceEmbeddings(model_name=embedding_path)\n"+ "# replace to your model path\n",+ "embedding_path = \"/data/zhx/zhx/langchain-ChatGLM_new/text2vec/text2vec-large-chinese\"\n",+ "embeddings = HuggingFaceEmbeddings(model_name=embedding_path)"]},{@@ -100,14 +100,25 @@}],"source": [- "#first add your document into vearch vectorstore\n",+ "# first add your document into vearch vectorstore\n","vearch_standalone = Vearch.from_documents(\n",- " texts,embeddings,path_or_url=\"/data/zhx/zhx/langchain-ChatGLM_new/knowledge_base/localdb_new_test\",table_name=\"localdb_new_test\",flag=0)\n",+ " texts,\n",+ " embeddings,\n",+ " path_or_url=\"/data/zhx/zhx/langchain-ChatGLM_new/knowledge_base/localdb_new_test\",\n",+ " table_name=\"localdb_new_test\",\n",+ " flag=0,\n",+ ")\n","\n","print(\"***************after is cluster res*****************\")\n","\n","vearch_cluster = Vearch.from_documents(\n",- " texts,embeddings,path_or_url=\"http://test-vearch-langchain-router.vectorbase.svc.ht1.n.jd.local\",db_name=\"vearch_cluster_langchian\",table_name=\"tobenumone\",flag=1)\n"+ " texts,\n",+ " embeddings,\n",+ " path_or_url=\"http://test-vearch-langchain-router.vectorbase.svc.ht1.n.jd.local\",\n",+ " db_name=\"vearch_cluster_langchian\",\n",+ " table_name=\"tobenumone\",\n",+ " flag=1,\n",+ ")"]},{@@ -195,11 +206,11 @@],"source": ["query = \"你知道凌波微步吗,你知道都有谁会凌波微步?\"\n",- "vearch_standalone_res=vearch_standalone.similarity_search(query, 3)\n",- "for idx,tmp in enumerate(vearch_standalone_res): \n",+ "vearch_standalone_res = vearch_standalone.similarity_search(query, 3)\n",+ "for idx, tmp in enumerate(vearch_standalone_res):\n"," print(f\"{'#'*20}第{idx+1}段相关文档{'#'*20}\\n\\n{tmp.page_content}\\n\")\n","\n",- "# combine your local knowleadge and query \n",+ "# combine your local knowleadge and query\n","context = \"\".join([tmp.page_content for tmp in vearch_standalone_res])\n","new_query = f\"基于以下信息,尽可能准确的来回答用户的问题。背景信息:\\n {context} \\n 回答用户这个问题:{query}\\n\\n\"\n","response, history = model.chat(tokenizer, new_query, history=[])\n",@@ -208,11 +219,11 @@"print(\"***************************after is cluster res******************************\")\n","\n","query_c = \"你知道凌波微步吗,你知道都有谁会凌波微步?\"\n",- "cluster_res=vearch_cluster.similarity_search(query_c, 3)\n",- "for idx,tmp in enumerate(cluster_res): \n",+ "cluster_res = vearch_cluster.similarity_search(query_c, 3)\n",+ "for idx, tmp in enumerate(cluster_res):\n"," print(f\"{'#'*20}第{idx+1}段相关文档{'#'*20}\\n\\n{tmp.page_content}\\n\")\n","\n",- "# combine your local knowleadge and query \n",+ "# combine your local knowleadge and query\n","context_c = \"\".join([tmp.page_content for tmp in cluster_res])\n","new_query_c = f\"基于以下信息,尽可能准确的来回答用户的问题。背景信息:\\n {context_c} \\n 回答用户这个问题:{query_c}\\n\\n\"\n","response_c, history_c = model.chat(tokenizer, new_query_c, history=[])\n",@@ -252,17 +263,27 @@"response, history = model.chat(tokenizer, query, history=history)\n","print(f\"Human: {query}\\nChatGLM:{response}\\n\")\n","\n",- "vearch_info = [\"Vearch 是一款存储大语言模型数据的向量数据库,用于存储和快速搜索模型embedding后的向量,可用于基于个人知识库的大模型应用\",\n",- " \"Vearch 支持OpenAI, Llama, ChatGLM等模型,以及LangChain库\",\n",- " \"vearch 是基于C语言,go语言开发的,并提供python接口,可以直接通过pip安装\"]\n",- "vearch_source=[{'source': '/data/zhx/zhx/langchain-ChatGLM_new/knowledge_base/tlbb/three_body.txt'},{'source': '/data/zhx/zhx/langchain-ChatGLM_new/knowledge_base/tlbb/three_body.txt'},{'source': '/data/zhx/zhx/langchain-ChatGLM_new/knowledge_base/tlbb/three_body.txt'}]\n",- "vearch_standalone.add_texts(vearch_info,vearch_source)\n",+ "vearch_info = [\n",+ " \"Vearch 是一款存储大语言模型数据的向量数据库,用于存储和快速搜索模型embedding后的向量,可用于基于个人知识库的大模型应用\",\n",+ " \"Vearch 支持OpenAI, Llama, ChatGLM等模型,以及LangChain库\",\n",+ " \"vearch 是基于C语言,go语言开发的,并提供python接口,可以直接通过pip安装\",\n",+ "]\n",+ "vearch_source = [\n",+ " {\n",+ " \"source\": \"/data/zhx/zhx/langchain-ChatGLM_new/knowledge_base/tlbb/three_body.txt\"\n",+ " },\n",+ " {\n",+ " \"source\": \"/data/zhx/zhx/langchain-ChatGLM_new/knowledge_base/tlbb/three_body.txt\"\n",+ " },\n",+ " {\n",+ " \"source\": \"/data/zhx/zhx/langchain-ChatGLM_new/knowledge_base/tlbb/three_body.txt\"\n",+ " },\n",+ "]\n",+ "vearch_standalone.add_texts(vearch_info, vearch_source)\n","\n","print(\"*****************after is cluster res********************\")\n","\n",- "vearch_cluster.add_texts(vearch_info,vearch_source)\n",- "\n",- "\n"+ "vearch_cluster.add_texts(vearch_info, vearch_source)"]},{@@ -309,7 +330,7 @@"source": ["query3 = \"你知道vearch是什么吗?\"\n","res1 = vearch_standalone.similarity_search(query3, 3)\n",- "for idx,tmp in enumerate(res1): \n",+ "for idx, tmp in enumerate(res1):\n"," print(f\"{'#'*20}第{idx+1}段相关文档{'#'*20}\\n\\n{tmp.page_content}\\n\")\n","\n","context1 = \"\".join([tmp.page_content for tmp in res1])\n",@@ -321,7 +342,7 @@"\n","query3_c = \"你知道vearch是什么吗?\"\n","res1_c = vearch_standalone.similarity_search(query3_c, 3)\n",- "for idx,tmp in enumerate(res1_c): \n",+ "for idx, tmp in enumerate(res1_c):\n"," print(f\"{'#'*20}第{idx+1}段相关文档{'#'*20}\\n\\n{tmp.page_content}\\n\")\n","\n","context1_C = \"\".join([tmp.page_content for tmp in res1_c])\n",@@ -362,31 +383,61 @@}],"source": [- "##delete and get function need to maintian docids \n",+ "##delete and get function need to maintian docids\n","##your docid\n","\n",- "res_d=vearch_standalone.delete(['eee5e7468434427eb49829374c1e8220', '2776754da8fc4bb58d3e482006010716', '9223acd6d89d4c2c84ff42677ac0d47c'])\n",- "print(\"delete vearch standalone docid\",res_d)\n",+ "res_d = vearch_standalone.delete(\n",+ " [\n",+ " \"eee5e7468434427eb49829374c1e8220\",\n",+ " \"2776754da8fc4bb58d3e482006010716\",\n",+ " \"9223acd6d89d4c2c84ff42677ac0d47c\",\n",+ " ]\n",+ ")\n",+ "print(\"delete vearch standalone docid\", res_d)\n","query = \"你知道vearch是什么吗?\"\n","response, history = model.chat(tokenizer, query, history=[])\n","print(f\"Human: {query}\\nChatGLM:{response}\\n\")\n","\n",- "res_cluster=vearch_cluster.delete(['-4311783201092343475', '-2899734009733762895', '1342026762029067927'])\n",- "print(\"delete vearch cluster docid\",res_cluster)\n",+ "res_cluster = vearch_cluster.delete(\n",+ " [\"-4311783201092343475\", \"-2899734009733762895\", \"1342026762029067927\"]\n",+ ")\n",+ "print(\"delete vearch cluster docid\", res_cluster)\n","query_c = \"你知道vearch是什么吗?\"\n","response_c, history = model.chat(tokenizer, query_c, history=[])\n","print(f\"Human: {query}\\nChatGLM:{response_c}\\n\")\n","\n","\n",- "get_delet_doc=vearch_standalone.get(['eee5e7468434427eb49829374c1e8220', '2776754da8fc4bb58d3e482006010716', '9223acd6d89d4c2c84ff42677ac0d47c'])\n",- "print(\"after delete docid to query again:\",get_delet_doc)\n",- "get_id_doc=vearch_standalone.get(['18ce6747dca04a2c833e60e8dfd83c04', 'aafacb0e46574b378a9f433877ab06a8', '9776bccfdd8643a8b219ccee0596f370','9223acd6d89d4c2c84ff42677ac0d47c'])\n",- "print(\"get existed docid\",get_id_doc)\n",+ "get_delet_doc = vearch_standalone.get(\n",+ " [\n",+ " \"eee5e7468434427eb49829374c1e8220\",\n",+ " \"2776754da8fc4bb58d3e482006010716\",\n",+ " \"9223acd6d89d4c2c84ff42677ac0d47c\",\n",+ " ]\n",+ ")\n",+ "print(\"after delete docid to query again:\", get_delet_doc)\n",+ "get_id_doc = vearch_standalone.get(\n",+ " [\n",+ " \"18ce6747dca04a2c833e60e8dfd83c04\",\n",+ " \"aafacb0e46574b378a9f433877ab06a8\",\n",+ " \"9776bccfdd8643a8b219ccee0596f370\",\n",+ " \"9223acd6d89d4c2c84ff42677ac0d47c\",\n",+ " ]\n",+ ")\n",+ "print(\"get existed docid\", get_id_doc)\n","\n",- "get_delet_doc=vearch_cluster.get(['-4311783201092343475', '-2899734009733762895', '1342026762029067927'])\n",- "print(\"after delete docid to query again:\",get_delet_doc)\n",- "get_id_doc=vearch_cluster.get(['1841638988191686991', '-4519586577642625749', '5028230008472292907','1342026762029067927'])\n",- "print(\"get existed docid\",get_id_doc)\n"+ "get_delet_doc = vearch_cluster.get(\n",+ " [\"-4311783201092343475\", \"-2899734009733762895\", \"1342026762029067927\"]\n",+ ")\n",+ "print(\"after delete docid to query again:\", get_delet_doc)\n",+ "get_id_doc = vearch_cluster.get(\n",+ " [\n",+ " \"1841638988191686991\",\n",+ " \"-4519586577642625749\",\n",+ " \"5028230008472292907\",\n",+ " \"1342026762029067927\",\n",+ " ]\n",+ ")\n",+ "print(\"get existed docid\", get_id_doc)"]},{@@ -394,18 +445,14 @@"execution_count": null,"metadata": {},"outputs": [],- "source": [- "\n"- ]+ "source": []},{"cell_type": "code","execution_count": null,"metadata": {},"outputs": [],- "source": [- "\n"- ]+ "source": []},{"cell_type": "code",diff --git a/docs/docs/integrations/vectorstores/vectara.ipynb b/docs/docs/integrations/vectorstores/vectara.ipynbindex 284a62a26c..a7e920f935 100644--- a/docs/docs/integrations/vectorstores/vectara.ipynb+++ b/docs/docs/integrations/vectorstores/vectara.ipynb@@ -156,12 +156,12 @@" [\n"," \"https://www.gilderlehrman.org/sites/default/files/inline-pdfs/king.dreamspeech.excerpts.pdf\",\n"," \"I-have-a-dream\",\n",- " \"Dr. King\"\n",+ " \"Dr. King\",\n"," ],\n"," [\n"," \"https://www.parkwayschools.net/cms/lib/MO01931486/Centricity/Domain/1578/Churchill_Beaches_Speech.pdf\",\n"," \"we shall fight on the beaches\",\n",- " \"Churchil\"\n",+ " \"Churchil\",\n"," ],\n","]\n","files_list = []\n",@@ -173,7 +173,9 @@"docsearch: Vectara = Vectara.from_files(\n"," files=files_list,\n"," embedding=FakeEmbeddings(size=768),\n",- " metadatas=[{\"url\": url, \"speech\": title, \"author\": author} for url, title, author in urls],\n",+ " metadatas=[\n",+ " {\"url\": url, \"speech\": title, \"author\": author} for url, title, author in urls\n",+ " ],\n",")"]},@@ -259,7 +261,9 @@"source": ["query = \"What did the president say about Ketanji Brown Jackson\"\n","found_docs = vectara.similarity_search_with_score(\n",- " query, filter=\"doc.speech = 'state-of-the-union'\", score_threshold=0.2,\n",+ " query,\n",+ " filter=\"doc.speech = 'state-of-the-union'\",\n",+ " score_threshold=0.2,\n",")"]},@@ -316,7 +320,9 @@"query = \"We must forever conduct our struggle\"\n","min_score = 1.2\n","found_docs = vectara.similarity_search_with_score(\n",- " query, filter=\"doc.speech = 'I-have-a-dream'\", score_threshold=min_score,\n",+ " query,\n",+ " filter=\"doc.speech = 'I-have-a-dream'\",\n",+ " score_threshold=min_score,\n",")\n","print(f\"With this threshold of {min_score} we have {len(found_docs)} documents\")"]@@ -339,9 +345,11 @@"query = \"We must forever conduct our struggle\"\n","min_score = 0.2\n","found_docs = vectara.similarity_search_with_score(\n",- " query, filter=\"doc.speech = 'I-have-a-dream'\", score_threshold=min_score,\n",+ " query,\n",+ " filter=\"doc.speech = 'I-have-a-dream'\",\n",+ " score_threshold=min_score,\n",")\n",- "print(f\"With this threshold of {min_score} we have {len(found_docs)} documents\")\n"+ "print(f\"With this threshold of {min_score} we have {len(found_docs)} documents\")"]},{@@ -439,9 +447,9 @@"\n","vectordb = Vectara()\n","llm = OpenAI(temperature=0)\n",- "retriever = SelfQueryRetriever.from_llm(llm, vectara, \n",- " document_content_description, metadata_field_info, \n",- " verbose=True)"+ "retriever = SelfQueryRetriever.from_llm(\n",+ " llm, vectara, document_content_description, metadata_field_info, verbose=True\n",+ ")"]},{diff --git a/docs/docs/integrations/vectorstores/vectorstores/semadb.ipynb b/docs/docs/integrations/vectorstores/vectorstores/semadb.ipynbindex f354e82f29..93a392f359 100644--- a/docs/docs/integrations/vectorstores/vectorstores/semadb.ipynb+++ b/docs/docs/integrations/vectorstores/vectorstores/semadb.ipynb@@ -99,7 +99,7 @@"import getpass\n","import os\n","\n",- "os.environ['SEMADB_API_KEY'] = getpass.getpass(\"SemaDB API Key:\")"+ "os.environ[\"SEMADB_API_KEY\"] = getpass.getpass(\"SemaDB API Key:\")"]},{diff --git a/docs/docs/integrations/vectorstores/vespa.ipynb b/docs/docs/integrations/vectorstores/vespa.ipynbindex 62e2bd7679..72318091c6 100644--- a/docs/docs/integrations/vectorstores/vespa.ipynb+++ b/docs/docs/integrations/vectorstores/vespa.ipynb@@ -1,922 +1,944 @@{- "cells": [- {- "cell_type": "markdown",- "id": "ce0f17b9",- "metadata": {},- "source": [- "# Vespa\n",- "\n",- ">[Vespa](https://vespa.ai/) is a fully featured search engine and vector database. It supports vector search (ANN), lexical search, and search in structured data, all in the same query.\n",- "\n",- "This notebook shows how to use `Vespa.ai` as a LangChain vector store.\n",- "\n",- "In order to create the vector store, we use\n",- "[pyvespa](https://pyvespa.readthedocs.io/en/latest/index.html) to create a\n",- "connection a `Vespa` service."- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "7e6a11ab-38bd-4920-ba11-60cb2f075754",- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "#!pip install pyvespa"- ]- },- {- "cell_type": "markdown",- "source": [- "Using the `pyvespa` package, you can either connect to a\n",- "[Vespa Cloud instance](https://pyvespa.readthedocs.io/en/latest/deploy-vespa-cloud.html)\n",- "or a local\n",- "[Docker instance](https://pyvespa.readthedocs.io/en/latest/deploy-docker.html).\n",- "Here, we will create a new Vespa application and deploy that using Docker.\n",- "\n",- "#### Creating a Vespa application\n",- "\n",- "First, we need to create an application package:"- ],- "metadata": {- "collapsed": false- },- "id": "283b49c9"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "from vespa.package import ApplicationPackage, Field, RankProfile\n",- "\n",- "app_package = ApplicationPackage(name=\"testapp\")\n",- "app_package.schema.add_fields(\n",- " Field(name=\"text\", type=\"string\", indexing=[\"index\", \"summary\"], index=\"enable-bm25\"),\n",- " Field(name=\"embedding\", type=\"tensor<float>(x[384])\",\n",- " indexing=[\"attribute\", \"summary\"],\n",- " attribute=[f\"distance-metric: angular\"]),\n",- ")\n",- "app_package.schema.add_rank_profile(\n",- " RankProfile(name=\"default\",\n",- " first_phase=\"closeness(field, embedding)\",\n",- " inputs=[(\"query(query_embedding)\", \"tensor<float>(x[384])\")]\n",- " )\n",- ")"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "id": "91150665"- },- {- "cell_type": "markdown",- "source": [- "This sets up a Vespa application with a schema for each document that contains\n",- "two fields: `text` for holding the document text and `embedding` for holding\n",- "the embedding vector. The `text` field is set up to use a BM25 index for\n",- "efficient text retrieval, and we'll see how to use this and hybrid search a\n",- "bit later.\n",- "\n",- "The `embedding` field is set up with a vector of length 384 to hold the\n",- "embedding representation of the text. See\n",- "[Vespa's Tensor Guide](https://docs.vespa.ai/en/tensor-user-guide.html)\n",- "for more on tensors in Vespa.\n",- "\n",- "Lastly, we add a [rank profile](https://docs.vespa.ai/en/ranking.html) to\n",- "instruct Vespa how to order documents. Here we set this up with a\n",- "[nearest neighbor search](https://docs.vespa.ai/en/nearest-neighbor-search.html).\n",- "\n",- "Now we can deploy this application locally:"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- },- "id": "15477106"- },- {- "cell_type": "code",- "execution_count": 2,- "id": "c10dd962",- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "from vespa.deployment import VespaDocker\n",- "\n",- "vespa_docker = VespaDocker()\n",- "vespa_app = vespa_docker.deploy(application_package=app_package)"- ]- },- {- "cell_type": "markdown",- "id": "3df4ce53",- "metadata": {},- "source": [- "This deploys and creates a connection to a `Vespa` service. In case you\n",- "already have a Vespa application running, for instance in the cloud,\n",- "please refer to the PyVespa application for how to connect.\n",- "\n",- "#### Creating a Vespa vector store\n",- "\n",- "Now, let's load some documents:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "from langchain.document_loaders import TextLoader\n",- "from langchain.text_splitter import CharacterTextSplitter\n",- "\n",- "loader = TextLoader(\"../../modules/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",- "from langchain.embeddings.sentence_transformer import SentenceTransformerEmbeddings\n",- "\n",- "embedding_function = SentenceTransformerEmbeddings(model_name=\"all-MiniLM-L6-v2\")"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "id": "7abde491"- },- {- "cell_type": "markdown",- "source": [- "Here, we also set up local sentence embedder to transform the text to embedding\n",- "vectors. One could also use OpenAI embeddings, but the vector length needs to\n",- "be updated to `1536` to reflect the larger size of that embedding.\n",- "\n",- "To feed these to Vespa, we need to configure how the vector store should map to\n",- "fields in the Vespa application. Then we create the vector store directly from\n",- "this set of documents:"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- },- "id": "d42365c7"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "vespa_config = dict(\n",- " page_content_field=\"text\",\n",- " embedding_field=\"embedding\",\n",- " input_field=\"query_embedding\"\n",- ")\n",- "\n",- "from langchain.vectorstores import VespaStore\n",- "\n",- "db = VespaStore.from_documents(docs, embedding_function, app=vespa_app, **vespa_config)"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "id": "0b647878"- },- {- "cell_type": "markdown",- "source": [- "This creates a Vespa vector store and feeds that set of documents to Vespa.\n",- "The vector store takes care of calling the embedding function for each document\n",- "and inserts them into the database.\n",- "\n",- "We can now query the vector store:"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- },- "id": "d6bd0aab"- },- {- "cell_type": "code",- "execution_count": null,- "id": "7ccca1f4",- "metadata": {- "pycharm": {- "name": "#%%\n"- }- },- "outputs": [],- "source": [- "query = \"What did the president say about Ketanji Brown Jackson\"\n",- "results = db.similarity_search(query)\n",- "\n",- "print(results[0].page_content)"- ]- },- {- "cell_type": "markdown",- "id": "1e7e34e1",- "metadata": {- "pycharm": {- "name": "#%% md\n"- }- },- "source": [- "This will use the embedding function given above to create a representation\n",- "for the query and use that to search Vespa. Note that this will use the\n",- "`default` ranking function, which we set up in the application package\n",- "above. You can use the `ranking` argument to `similarity_search` to\n",- "specify which ranking function to use.\n",- "\n",- "Please refer to the [pyvespa documentation](https://pyvespa.readthedocs.io/en/latest/getting-started-pyvespa.html#Query)\n",- "for more information.\n",- "\n",- "This covers the basic usage of the Vespa store in LangChain.\n",- "Now you can return the results and continue using these in LangChain.\n",- "\n",- "#### Updating documents\n",- "\n",- "An alternative to calling `from_documents`, you can create the vector\n",- "store directly and call `add_texts` from that. This can also be used to update\n",- "documents:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "query = \"What did the president say about Ketanji Brown Jackson\"\n",- "results = db.similarity_search(query)\n",- "result = results[0]\n",- "\n",- "result.page_content = \"UPDATED: \" + result.page_content\n",- "db.add_texts([result.page_content], [result.metadata], result.metadata[\"id\"])\n",- "\n",- "results = db.similarity_search(query)\n",- "print(results[0].page_content)"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "id": "a5256284"- },- {- "cell_type": "markdown",- "source": [- "However, the `pyvespa` library contains methods to manipulate\n",- "content on Vespa which you can use directly.\n",- "\n",- "#### Deleting documents\n",- "\n",- "You can delete documents using the `delete` function:"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- },- "id": "2526b50e"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "result = db.similarity_search(query)\n",- "# docs[0].metadata[\"id\"] == \"id:testapp:testapp::32\"\n",- "\n",- "db.delete([\"32\"])\n",- "result = db.similarity_search(query)\n",- "# docs[0].metadata[\"id\"] != \"id:testapp:testapp::32\""- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "id": "52cab87e"- },- {- "cell_type": "markdown",- "source": [- "Again, the `pyvespa` connection contains methods to delete documents as well.\n",- "\n",- "### Returning with scores\n",- "\n",- "The `similarity_search` method only returns the documents in order of\n",- "relevancy. To retrieve the actual scores:"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- },- "id": "deffaba5"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "results = db.similarity_search_with_score(query)\n",- "result = results[0]\n",- "# result[1] ~= 0.463"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "id": "cd9ae173"- },- {- "cell_type": "markdown",- "source": [- "This is a result of using the `\"all-MiniLM-L6-v2\"` embedding model using the\n",- "cosine distance function (as given by the argument `angular` in the\n",- "application function).\n",- "\n",- "Different embedding functions need different distance functions, and Vespa\n",- "needs to know which distance function to use when orderings documents.\n",- "Please refer to the\n",- "[documentation on distance functions](https://docs.vespa.ai/en/reference/schema-reference.html#distance-metric)\n",- "for more information.\n",- "\n",- "### As retriever\n",- "\n",- "To use this vector store as a\n",- "[LangChain retriever](https://python.langchain.com/docs/modules/data_connection/retrievers/)\n",- "simply call the `as_retriever` function, which is a standard vector store\n",- "method:"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- },- "id": "7257d67a"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "db = VespaStore.from_documents(docs, embedding_function, app=vespa_app, **vespa_config)\n",- "retriever = db.as_retriever()\n",- "query = \"What did the president say about Ketanji Brown Jackson\"\n",- "results = retriever.get_relevant_documents(query)\n",- "\n",- "# results[0].metadata[\"id\"] == \"id:testapp:testapp::32\""- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "id": "7fb717a9"- },- {- "cell_type": "markdown",- "source": [- "This allows for more general, unstructured, retrieval from the vector store.\n",- "\n",- "### Metadata\n",- "\n",- "In the example so far, we've only used the text and the embedding for that\n",- "text. Documents usually contain additional information, which in LangChain\n",- "is referred to as metadata.\n",- "\n",- "Vespa can contain many fields with different types by adding them to the application\n",- "package:"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- },- "id": "fba7f07e"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "app_package.schema.add_fields(\n",- " # ...\n",- " Field(name=\"date\", type=\"string\", indexing=[\"attribute\", \"summary\"]),\n",- " Field(name=\"rating\", type=\"int\", indexing=[\"attribute\", \"summary\"]),\n",- " Field(name=\"author\", type=\"string\", indexing=[\"attribute\", \"summary\"]),\n",- " # ...\n",- ")\n",- "vespa_app = vespa_docker.deploy(application_package=app_package)"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "id": "59cffcf2"- },- {- "cell_type": "markdown",- "source": [- "We can add some metadata fields in the documents:"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- },- "id": "eebef70c"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "# Add metadata\n",- "for i, doc in enumerate(docs):\n",- " doc.metadata[\"date\"] = f\"2023-{(i % 12)+1}-{(i % 28)+1}\"\n",- " doc.metadata[\"rating\"] = range(1, 6)[i % 5]\n",- " doc.metadata[\"author\"] = [\"Joe Biden\", \"Unknown\"][min(i, 1)]"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "id": "b21efbfa"- },- {- "cell_type": "markdown",- "source": [- "And let the Vespa vector store know about these fields:"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- },- "id": "9b42bd4d"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "vespa_config.update(dict(metadata_fields=[\"date\", \"rating\", \"author\"]))"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "id": "6bb272f6"- },- {- "cell_type": "markdown",- "source": [- "Now, when searching for these documents, these fields will be returned.\n",- "Also, these fields can be filtered on:"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- },- "id": "43818655"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "db = VespaStore.from_documents(docs, embedding_function, app=vespa_app, **vespa_config)\n",- "query = \"What did the president say about Ketanji Brown Jackson\"\n",- "results = db.similarity_search(query, filter=\"rating > 3\")\n",- "# results[0].metadata[\"id\"] == \"id:testapp:testapp::34\"\n",- "# results[0].metadata[\"author\"] == \"Unknown\""- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "id": "831759f3"- },- {- "cell_type": "markdown",- "source": [- "### Custom query\n",- "\n",- "If the default behavior of the similarity search does not fit your\n",- "requirements, you can always provide your own query. Thus, you don't\n",- "need to provide all of the configuration to the vector store, but\n",- "rather just write this yourself.\n",- "\n",- "First, let's add a BM25 ranking function to our application:"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- },- "id": "a49aad6e"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "from vespa.package import FieldSet\n",- "\n",- "app_package.schema.add_field_set(FieldSet(name=\"default\", fields=[\"text\"]))\n",- "app_package.schema.add_rank_profile(RankProfile(name=\"bm25\", first_phase=\"bm25(text)\"))\n",- "vespa_app = vespa_docker.deploy(application_package=app_package)\n",- "db = VespaStore.from_documents(docs, embedding_function, app=vespa_app, **vespa_config)"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "id": "d0fb0562"- },- {- "cell_type": "markdown",- "source": [- "Then, to perform a regular text search based on BM25:"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- },- "id": "fe607747"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "query = \"What did the president say about Ketanji Brown Jackson\"\n",- "custom_query = {\n",- " \"yql\": f\"select * from sources * where userQuery()\",\n",- " \"query\": query,\n",- " \"type\": \"weakAnd\",\n",- " \"ranking\": \"bm25\",\n",- " \"hits\": 4\n",- "}\n",- "results = db.similarity_search_with_score(query, custom_query=custom_query)\n",- "# results[0][0].metadata[\"id\"] == \"id:testapp:testapp::32\"\n",- "# results[0][1] ~= 14.384"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "id": "cee245c3"- },- {- "cell_type": "markdown",- "source": [- "All of the powerful search and query capabilities of Vespa can be used\n",- "by using a custom query. Please refer to the Vespa documentation on it's\n",- "[Query API](https://docs.vespa.ai/en/query-api.html) for more details.\n",- "\n",- "### Hybrid search\n",- "\n",- "Hybrid search means using both a classic term-based search such as\n",- "BM25 and a vector search and combining the results. We need to create\n",- "a new rank profile for hybrid search on Vespa:"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- },- "id": "41a4c081"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "app_package.schema.add_rank_profile(\n",- " RankProfile(name=\"hybrid\",\n",- " first_phase=\"log(bm25(text)) + 0.5 * closeness(field, embedding)\",\n",- " inputs=[(\"query(query_embedding)\", \"tensor<float>(x[384])\")]\n",- " )\n",- ")\n",- "vespa_app = vespa_docker.deploy(application_package=app_package)\n",- "db = VespaStore.from_documents(docs, embedding_function, app=vespa_app, **vespa_config)"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "id": "bf73efc1"- },- {- "cell_type": "markdown",- "source": [- "Here, we score each document as a combination of it's BM25 score and its\n",- "distance score. We can query using a custom query:"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- },- "id": "40f48711"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "query = \"What did the president say about Ketanji Brown Jackson\"\n",- "query_embedding = embedding_function.embed_query(query)\n",- "nearest_neighbor_expression = \"{targetHits: 4}nearestNeighbor(embedding, query_embedding)\"\n",- "custom_query = {\n",- " \"yql\": f\"select * from sources * where {nearest_neighbor_expression} and userQuery()\",\n",- " \"query\": query,\n",- " \"type\": \"weakAnd\",\n",- " \"input.query(query_embedding)\": query_embedding,\n",- " \"ranking\": \"hybrid\",\n",- " \"hits\": 4\n",- "}\n",- "results = db.similarity_search_with_score(query, custom_query=custom_query)\n",- "# results[0][0].metadata[\"id\"], \"id:testapp:testapp::32\")\n",- "# results[0][1] ~= 2.897"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "id": "d2e289f0"- },- {- "cell_type": "markdown",- "source": [- "### Native embedders in Vespa\n",- "\n",- "Up until this point we've used an embedding function in Python to provide\n",- "embeddings for the texts. Vespa supports embedding function natively, so\n",- "you can defer this calculation in to Vespa. One benefit is the ability to use\n",- "GPUs when embedding documents if you have a large collections.\n",- "\n",- "Please refer to [Vespa embeddings](https://docs.vespa.ai/en/embedding.html)\n",- "for more information.\n",- "\n",- "First, we need to modify our application package:"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- },- "id": "958e269f"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "from vespa.package import Component, Parameter\n",- "\n",- "app_package.components = [\n",- " Component(id=\"hf-embedder\", type=\"hugging-face-embedder\",\n",- " parameters=[\n",- " Parameter(\"transformer-model\", {\"path\": \"...\"}),\n",- " Parameter(\"tokenizer-model\", {\"url\": \"...\"}),\n",- " ]\n",- " )\n",- "]\n",- "Field(name=\"hfembedding\", type=\"tensor<float>(x[384])\",\n",- " is_document_field=False,\n",- " indexing=[\"input text\", \"embed hf-embedder\", \"attribute\", \"summary\"],\n",- " attribute=[f\"distance-metric: angular\"],\n",- " )\n",- "app_package.schema.add_rank_profile(\n",- " RankProfile(name=\"hf_similarity\",\n",- " first_phase=\"closeness(field, hfembedding)\",\n",- " inputs=[(\"query(query_embedding)\", \"tensor<float>(x[384])\")]\n",- " )\n",- ")"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "id": "56b9686c"- },- {- "cell_type": "markdown",- "source": [- "Please refer to the embeddings documentation on adding embedder models\n",- "and tokenizers to the application. Note that the `hfembedding` field\n",- "includes instructions for embedding using the `hf-embedder`.\n",- "\n",- "Now we can query with a custom query:"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- },- "id": "5cd721a8"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "query = \"What did the president say about Ketanji Brown Jackson\"\n",- "nearest_neighbor_expression = \"{targetHits: 4}nearestNeighbor(internalembedding, query_embedding)\"\n",- "custom_query = {\n",- " \"yql\": f\"select * from sources * where {nearest_neighbor_expression}\",\n",- " \"input.query(query_embedding)\": f\"embed(hf-embedder, \\\"{query}\\\")\",\n",- " \"ranking\": \"internal_similarity\",\n",- " \"hits\": 4\n",- "}\n",- "results = db.similarity_search_with_score(query, custom_query=custom_query)\n",- "# results[0][0].metadata[\"id\"], \"id:testapp:testapp::32\")\n",- "# results[0][1] ~= 0.630"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "id": "da631d13"- },- {- "cell_type": "markdown",- "source": [- "Note that the query here includes an `embed` instruction to embed the query\n",- "using the same model as for the documents.\n",- "\n",- "### Approximate nearest neighbor\n",- "\n",- "In all of the above examples, we've used exact nearest neighbor to\n",- "find results. However, for large collections of documents this is\n",- "not feasible as one has to scan through all documents to find the\n",- "best matches. To avoid this, we can use\n",- "[approximate nearest neighbors](https://docs.vespa.ai/en/approximate-nn-hnsw.html).\n",- "\n",- "First, we can change the embedding field to create a HNSW index:"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- },- "id": "a333b553"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "from vespa.package import HNSW\n",- "\n",- "app_package.schema.add_fields(\n",- " Field(name=\"embedding\", type=\"tensor<float>(x[384])\",\n",- " indexing=[\"attribute\", \"summary\", \"index\"],\n",- " ann=HNSW(distance_metric=\"angular\", max_links_per_node=16, neighbors_to_explore_at_insert=200)\n",- " )\n",- ")\n"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "id": "9ee955c8"- },- {- "cell_type": "markdown",- "source": [- "This creates a HNSW index on the embedding data which allows for efficient\n",- "searching. With this set, we can easily search using ANN by setting\n",- "the `approximate` argument to `True`:"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- },- "id": "2ed1c224"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "query = \"What did the president say about Ketanji Brown Jackson\"\n",- "results = db.similarity_search(query, approximate=True)\n",- "# results[0][0].metadata[\"id\"], \"id:testapp:testapp::32\")"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "id": "7981739a"- },- {- "cell_type": "markdown",- "source": [- "This covers most of the functionality in the Vespa vector store in LangChain.\n",- "\n"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- },- "id": "24791204"- }- ],- "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+ "cells": [+ {+ "cell_type": "markdown",+ "id": "ce0f17b9",+ "metadata": {},+ "source": [+ "# Vespa\n",+ "\n",+ ">[Vespa](https://vespa.ai/) is a fully featured search engine and vector database. It supports vector search (ANN), lexical search, and search in structured data, all in the same query.\n",+ "\n",+ "This notebook shows how to use `Vespa.ai` as a LangChain vector store.\n",+ "\n",+ "In order to create the vector store, we use\n",+ "[pyvespa](https://pyvespa.readthedocs.io/en/latest/index.html) to create a\n",+ "connection a `Vespa` service."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "7e6a11ab-38bd-4920-ba11-60cb2f075754",+ "metadata": {+ "tags": []+ },+ "outputs": [],+ "source": [+ "#!pip install pyvespa"+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "Using the `pyvespa` package, you can either connect to a\n",+ "[Vespa Cloud instance](https://pyvespa.readthedocs.io/en/latest/deploy-vespa-cloud.html)\n",+ "or a local\n",+ "[Docker instance](https://pyvespa.readthedocs.io/en/latest/deploy-docker.html).\n",+ "Here, we will create a new Vespa application and deploy that using Docker.\n",+ "\n",+ "#### Creating a Vespa application\n",+ "\n",+ "First, we need to create an application package:"+ ],+ "metadata": {+ "collapsed": false+ },+ "id": "283b49c9"+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "from vespa.package import ApplicationPackage, Field, RankProfile\n",+ "\n",+ "app_package = ApplicationPackage(name=\"testapp\")\n",+ "app_package.schema.add_fields(\n",+ " Field(\n",+ " name=\"text\", type=\"string\", indexing=[\"index\", \"summary\"], index=\"enable-bm25\"\n",+ " ),\n",+ " Field(\n",+ " name=\"embedding\",\n",+ " type=\"tensor<float>(x[384])\",\n",+ " indexing=[\"attribute\", \"summary\"],\n",+ " attribute=[f\"distance-metric: angular\"],\n",+ " ),\n",+ ")\n",+ "app_package.schema.add_rank_profile(\n",+ " RankProfile(\n",+ " name=\"default\",\n",+ " first_phase=\"closeness(field, embedding)\",\n",+ " inputs=[(\"query(query_embedding)\", \"tensor<float>(x[384])\")],\n",+ " )\n",+ ")"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "id": "91150665"+ },+ {+ "cell_type": "markdown",+ "source": [+ "This sets up a Vespa application with a schema for each document that contains\n",+ "two fields: `text` for holding the document text and `embedding` for holding\n",+ "the embedding vector. The `text` field is set up to use a BM25 index for\n",+ "efficient text retrieval, and we'll see how to use this and hybrid search a\n",+ "bit later.\n",+ "\n",+ "The `embedding` field is set up with a vector of length 384 to hold the\n",+ "embedding representation of the text. See\n",+ "[Vespa's Tensor Guide](https://docs.vespa.ai/en/tensor-user-guide.html)\n",+ "for more on tensors in Vespa.\n",+ "\n",+ "Lastly, we add a [rank profile](https://docs.vespa.ai/en/ranking.html) to\n",+ "instruct Vespa how to order documents. Here we set this up with a\n",+ "[nearest neighbor search](https://docs.vespa.ai/en/nearest-neighbor-search.html).\n",+ "\n",+ "Now we can deploy this application locally:"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"+ }+ },+ "id": "15477106"+ },+ {+ "cell_type": "code",+ "execution_count": 2,+ "id": "c10dd962",+ "metadata": {+ "tags": []+ },+ "outputs": [],+ "source": [+ "from vespa.deployment import VespaDocker\n",+ "\n",+ "vespa_docker = VespaDocker()\n",+ "vespa_app = vespa_docker.deploy(application_package=app_package)"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "3df4ce53",+ "metadata": {},+ "source": [+ "This deploys and creates a connection to a `Vespa` service. In case you\n",+ "already have a Vespa application running, for instance in the cloud,\n",+ "please refer to the PyVespa application for how to connect.\n",+ "\n",+ "#### Creating a Vespa vector store\n",+ "\n",+ "Now, let's load some documents:"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "from langchain.document_loaders import TextLoader\n",+ "from langchain.text_splitter import CharacterTextSplitter\n",+ "\n",+ "loader = TextLoader(\"../../modules/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",+ "from langchain.embeddings.sentence_transformer import SentenceTransformerEmbeddings\n",+ "\n",+ "embedding_function = SentenceTransformerEmbeddings(model_name=\"all-MiniLM-L6-v2\")"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "id": "7abde491"+ },+ {+ "cell_type": "markdown",+ "source": [+ "Here, we also set up local sentence embedder to transform the text to embedding\n",+ "vectors. One could also use OpenAI embeddings, but the vector length needs to\n",+ "be updated to `1536` to reflect the larger size of that embedding.\n",+ "\n",+ "To feed these to Vespa, we need to configure how the vector store should map to\n",+ "fields in the Vespa application. Then we create the vector store directly from\n",+ "this set of documents:"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"+ }+ },+ "id": "d42365c7"+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "vespa_config = dict(\n",+ " page_content_field=\"text\",\n",+ " embedding_field=\"embedding\",\n",+ " input_field=\"query_embedding\",\n",+ ")\n",+ "\n",+ "from langchain.vectorstores import VespaStore\n",+ "\n",+ "db = VespaStore.from_documents(docs, embedding_function, app=vespa_app, **vespa_config)"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "id": "0b647878"+ },+ {+ "cell_type": "markdown",+ "source": [+ "This creates a Vespa vector store and feeds that set of documents to Vespa.\n",+ "The vector store takes care of calling the embedding function for each document\n",+ "and inserts them into the database.\n",+ "\n",+ "We can now query the vector store:"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"+ }+ },+ "id": "d6bd0aab"+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "7ccca1f4",+ "metadata": {+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "outputs": [],+ "source": [+ "query = \"What did the president say about Ketanji Brown Jackson\"\n",+ "results = db.similarity_search(query)\n",+ "\n",+ "print(results[0].page_content)"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "1e7e34e1",+ "metadata": {+ "pycharm": {+ "name": "#%% md\n"+ }+ },+ "source": [+ "This will use the embedding function given above to create a representation\n",+ "for the query and use that to search Vespa. Note that this will use the\n",+ "`default` ranking function, which we set up in the application package\n",+ "above. You can use the `ranking` argument to `similarity_search` to\n",+ "specify which ranking function to use.\n",+ "\n",+ "Please refer to the [pyvespa documentation](https://pyvespa.readthedocs.io/en/latest/getting-started-pyvespa.html#Query)\n",+ "for more information.\n",+ "\n",+ "This covers the basic usage of the Vespa store in LangChain.\n",+ "Now you can return the results and continue using these in LangChain.\n",+ "\n",+ "#### Updating documents\n",+ "\n",+ "An alternative to calling `from_documents`, you can create the vector\n",+ "store directly and call `add_texts` from that. This can also be used to update\n",+ "documents:"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "query = \"What did the president say about Ketanji Brown Jackson\"\n",+ "results = db.similarity_search(query)\n",+ "result = results[0]\n",+ "\n",+ "result.page_content = \"UPDATED: \" + result.page_content\n",+ "db.add_texts([result.page_content], [result.metadata], result.metadata[\"id\"])\n",+ "\n",+ "results = db.similarity_search(query)\n",+ "print(results[0].page_content)"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "id": "a5256284"+ },+ {+ "cell_type": "markdown",+ "source": [+ "However, the `pyvespa` library contains methods to manipulate\n",+ "content on Vespa which you can use directly.\n",+ "\n",+ "#### Deleting documents\n",+ "\n",+ "You can delete documents using the `delete` function:"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"+ }+ },+ "id": "2526b50e"+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "result = db.similarity_search(query)\n",+ "# docs[0].metadata[\"id\"] == \"id:testapp:testapp::32\"\n",+ "\n",+ "db.delete([\"32\"])\n",+ "result = db.similarity_search(query)\n",+ "# docs[0].metadata[\"id\"] != \"id:testapp:testapp::32\""+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "id": "52cab87e"+ },+ {+ "cell_type": "markdown",+ "source": [+ "Again, the `pyvespa` connection contains methods to delete documents as well.\n",+ "\n",+ "### Returning with scores\n",+ "\n",+ "The `similarity_search` method only returns the documents in order of\n",+ "relevancy. To retrieve the actual scores:"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"+ }+ },+ "id": "deffaba5"+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "results = db.similarity_search_with_score(query)\n",+ "result = results[0]\n",+ "# result[1] ~= 0.463"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "id": "cd9ae173"+ },+ {+ "cell_type": "markdown",+ "source": [+ "This is a result of using the `\"all-MiniLM-L6-v2\"` embedding model using the\n",+ "cosine distance function (as given by the argument `angular` in the\n",+ "application function).\n",+ "\n",+ "Different embedding functions need different distance functions, and Vespa\n",+ "needs to know which distance function to use when orderings documents.\n",+ "Please refer to the\n",+ "[documentation on distance functions](https://docs.vespa.ai/en/reference/schema-reference.html#distance-metric)\n",+ "for more information.\n",+ "\n",+ "### As retriever\n",+ "\n",+ "To use this vector store as a\n",+ "[LangChain retriever](https://python.langchain.com/docs/modules/data_connection/retrievers/)\n",+ "simply call the `as_retriever` function, which is a standard vector store\n",+ "method:"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"+ }+ },+ "id": "7257d67a"+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "db = VespaStore.from_documents(docs, embedding_function, app=vespa_app, **vespa_config)\n",+ "retriever = db.as_retriever()\n",+ "query = \"What did the president say about Ketanji Brown Jackson\"\n",+ "results = retriever.get_relevant_documents(query)\n",+ "\n",+ "# results[0].metadata[\"id\"] == \"id:testapp:testapp::32\""+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "id": "7fb717a9"+ },+ {+ "cell_type": "markdown",+ "source": [+ "This allows for more general, unstructured, retrieval from the vector store.\n",+ "\n",+ "### Metadata\n",+ "\n",+ "In the example so far, we've only used the text and the embedding for that\n",+ "text. Documents usually contain additional information, which in LangChain\n",+ "is referred to as metadata.\n",+ "\n",+ "Vespa can contain many fields with different types by adding them to the application\n",+ "package:"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"+ }+ },+ "id": "fba7f07e"+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "app_package.schema.add_fields(\n",+ " # ...\n",+ " Field(name=\"date\", type=\"string\", indexing=[\"attribute\", \"summary\"]),\n",+ " Field(name=\"rating\", type=\"int\", indexing=[\"attribute\", \"summary\"]),\n",+ " Field(name=\"author\", type=\"string\", indexing=[\"attribute\", \"summary\"]),\n",+ " # ...\n",+ ")\n",+ "vespa_app = vespa_docker.deploy(application_package=app_package)"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "id": "59cffcf2"+ },+ {+ "cell_type": "markdown",+ "source": [+ "We can add some metadata fields in the documents:"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"+ }+ },+ "id": "eebef70c"+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "# Add metadata\n",+ "for i, doc in enumerate(docs):\n",+ " doc.metadata[\"date\"] = f\"2023-{(i % 12)+1}-{(i % 28)+1}\"\n",+ " doc.metadata[\"rating\"] = range(1, 6)[i % 5]\n",+ " doc.metadata[\"author\"] = [\"Joe Biden\", \"Unknown\"][min(i, 1)]"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "id": "b21efbfa"+ },+ {+ "cell_type": "markdown",+ "source": [+ "And let the Vespa vector store know about these fields:"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"+ }+ },+ "id": "9b42bd4d"+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "vespa_config.update(dict(metadata_fields=[\"date\", \"rating\", \"author\"]))"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "id": "6bb272f6"+ },+ {+ "cell_type": "markdown",+ "source": [+ "Now, when searching for these documents, these fields will be returned.\n",+ "Also, these fields can be filtered on:"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"+ }+ },+ "id": "43818655"+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "db = VespaStore.from_documents(docs, embedding_function, app=vespa_app, **vespa_config)\n",+ "query = \"What did the president say about Ketanji Brown Jackson\"\n",+ "results = db.similarity_search(query, filter=\"rating > 3\")\n",+ "# results[0].metadata[\"id\"] == \"id:testapp:testapp::34\"\n",+ "# results[0].metadata[\"author\"] == \"Unknown\""+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "id": "831759f3"+ },+ {+ "cell_type": "markdown",+ "source": [+ "### Custom query\n",+ "\n",+ "If the default behavior of the similarity search does not fit your\n",+ "requirements, you can always provide your own query. Thus, you don't\n",+ "need to provide all of the configuration to the vector store, but\n",+ "rather just write this yourself.\n",+ "\n",+ "First, let's add a BM25 ranking function to our application:"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"+ }+ },+ "id": "a49aad6e"+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "from vespa.package import FieldSet\n",+ "\n",+ "app_package.schema.add_field_set(FieldSet(name=\"default\", fields=[\"text\"]))\n",+ "app_package.schema.add_rank_profile(RankProfile(name=\"bm25\", first_phase=\"bm25(text)\"))\n",+ "vespa_app = vespa_docker.deploy(application_package=app_package)\n",+ "db = VespaStore.from_documents(docs, embedding_function, app=vespa_app, **vespa_config)"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "id": "d0fb0562"+ },+ {+ "cell_type": "markdown",+ "source": [+ "Then, to perform a regular text search based on BM25:"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"+ }+ },+ "id": "fe607747"+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "query = \"What did the president say about Ketanji Brown Jackson\"\n",+ "custom_query = {\n",+ " \"yql\": f\"select * from sources * where userQuery()\",\n",+ " \"query\": query,\n",+ " \"type\": \"weakAnd\",\n",+ " \"ranking\": \"bm25\",\n",+ " \"hits\": 4,\n",+ "}\n",+ "results = db.similarity_search_with_score(query, custom_query=custom_query)\n",+ "# results[0][0].metadata[\"id\"] == \"id:testapp:testapp::32\"\n",+ "# results[0][1] ~= 14.384"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "id": "cee245c3"+ },+ {+ "cell_type": "markdown",+ "source": [+ "All of the powerful search and query capabilities of Vespa can be used\n",+ "by using a custom query. Please refer to the Vespa documentation on it's\n",+ "[Query API](https://docs.vespa.ai/en/query-api.html) for more details.\n",+ "\n",+ "### Hybrid search\n",+ "\n",+ "Hybrid search means using both a classic term-based search such as\n",+ "BM25 and a vector search and combining the results. We need to create\n",+ "a new rank profile for hybrid search on Vespa:"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"+ }+ },+ "id": "41a4c081"+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "app_package.schema.add_rank_profile(\n",+ " RankProfile(\n",+ " name=\"hybrid\",\n",+ " first_phase=\"log(bm25(text)) + 0.5 * closeness(field, embedding)\",\n",+ " inputs=[(\"query(query_embedding)\", \"tensor<float>(x[384])\")],\n",+ " )\n",+ ")\n",+ "vespa_app = vespa_docker.deploy(application_package=app_package)\n",+ "db = VespaStore.from_documents(docs, embedding_function, app=vespa_app, **vespa_config)"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "id": "bf73efc1"+ },+ {+ "cell_type": "markdown",+ "source": [+ "Here, we score each document as a combination of it's BM25 score and its\n",+ "distance score. We can query using a custom query:"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"+ }+ },+ "id": "40f48711"+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "query = \"What did the president say about Ketanji Brown Jackson\"\n",+ "query_embedding = embedding_function.embed_query(query)\n",+ "nearest_neighbor_expression = (\n",+ " \"{targetHits: 4}nearestNeighbor(embedding, query_embedding)\"\n",+ ")\n",+ "custom_query = {\n",+ " \"yql\": f\"select * from sources * where {nearest_neighbor_expression} and userQuery()\",\n",+ " \"query\": query,\n",+ " \"type\": \"weakAnd\",\n",+ " \"input.query(query_embedding)\": query_embedding,\n",+ " \"ranking\": \"hybrid\",\n",+ " \"hits\": 4,\n",+ "}\n",+ "results = db.similarity_search_with_score(query, custom_query=custom_query)\n",+ "# results[0][0].metadata[\"id\"], \"id:testapp:testapp::32\")\n",+ "# results[0][1] ~= 2.897"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "id": "d2e289f0"+ },+ {+ "cell_type": "markdown",+ "source": [+ "### Native embedders in Vespa\n",+ "\n",+ "Up until this point we've used an embedding function in Python to provide\n",+ "embeddings for the texts. Vespa supports embedding function natively, so\n",+ "you can defer this calculation in to Vespa. One benefit is the ability to use\n",+ "GPUs when embedding documents if you have a large collections.\n",+ "\n",+ "Please refer to [Vespa embeddings](https://docs.vespa.ai/en/embedding.html)\n",+ "for more information.\n",+ "\n",+ "First, we need to modify our application package:"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"+ }+ },+ "id": "958e269f"+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "from vespa.package import Component, Parameter\n",+ "\n",+ "app_package.components = [\n",+ " Component(\n",+ " id=\"hf-embedder\",\n",+ " type=\"hugging-face-embedder\",\n",+ " parameters=[\n",+ " Parameter(\"transformer-model\", {\"path\": \"...\"}),\n",+ " Parameter(\"tokenizer-model\", {\"url\": \"...\"}),\n",+ " ],\n",+ " )\n",+ "]\n",+ "Field(\n",+ " name=\"hfembedding\",\n",+ " type=\"tensor<float>(x[384])\",\n",+ " is_document_field=False,\n",+ " indexing=[\"input text\", \"embed hf-embedder\", \"attribute\", \"summary\"],\n",+ " attribute=[f\"distance-metric: angular\"],\n",+ ")\n",+ "app_package.schema.add_rank_profile(\n",+ " RankProfile(\n",+ " name=\"hf_similarity\",\n",+ " first_phase=\"closeness(field, hfembedding)\",\n",+ " inputs=[(\"query(query_embedding)\", \"tensor<float>(x[384])\")],\n",+ " )\n",+ ")"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "id": "56b9686c"+ },+ {+ "cell_type": "markdown",+ "source": [+ "Please refer to the embeddings documentation on adding embedder models\n",+ "and tokenizers to the application. Note that the `hfembedding` field\n",+ "includes instructions for embedding using the `hf-embedder`.\n",+ "\n",+ "Now we can query with a custom query:"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"+ }+ },+ "id": "5cd721a8"+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "query = \"What did the president say about Ketanji Brown Jackson\"\n",+ "nearest_neighbor_expression = (\n",+ " \"{targetHits: 4}nearestNeighbor(internalembedding, query_embedding)\"\n",+ ")\n",+ "custom_query = {\n",+ " \"yql\": f\"select * from sources * where {nearest_neighbor_expression}\",\n",+ " \"input.query(query_embedding)\": f'embed(hf-embedder, \"{query}\")',\n",+ " \"ranking\": \"internal_similarity\",\n",+ " \"hits\": 4,\n",+ "}\n",+ "results = db.similarity_search_with_score(query, custom_query=custom_query)\n",+ "# results[0][0].metadata[\"id\"], \"id:testapp:testapp::32\")\n",+ "# results[0][1] ~= 0.630"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "id": "da631d13"+ },+ {+ "cell_type": "markdown",+ "source": [+ "Note that the query here includes an `embed` instruction to embed the query\n",+ "using the same model as for the documents.\n",+ "\n",+ "### Approximate nearest neighbor\n",+ "\n",+ "In all of the above examples, we've used exact nearest neighbor to\n",+ "find results. However, for large collections of documents this is\n",+ "not feasible as one has to scan through all documents to find the\n",+ "best matches. To avoid this, we can use\n",+ "[approximate nearest neighbors](https://docs.vespa.ai/en/approximate-nn-hnsw.html).\n",+ "\n",+ "First, we can change the embedding field to create a HNSW index:"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"+ }+ },+ "id": "a333b553"+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "from vespa.package import HNSW\n",+ "\n",+ "app_package.schema.add_fields(\n",+ " Field(\n",+ " name=\"embedding\",\n",+ " type=\"tensor<float>(x[384])\",\n",+ " indexing=[\"attribute\", \"summary\", \"index\"],\n",+ " ann=HNSW(\n",+ " distance_metric=\"angular\",\n",+ " max_links_per_node=16,\n",+ " neighbors_to_explore_at_insert=200,\n",+ " ),\n",+ " )\n",+ ")"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "id": "9ee955c8"+ },+ {+ "cell_type": "markdown",+ "source": [+ "This creates a HNSW index on the embedding data which allows for efficient\n",+ "searching. With this set, we can easily search using ANN by setting\n",+ "the `approximate` argument to `True`:"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"+ }+ },+ "id": "2ed1c224"+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "outputs": [],+ "source": [+ "query = \"What did the president say about Ketanji Brown Jackson\"\n",+ "results = db.similarity_search(query, approximate=True)\n",+ "# results[0][0].metadata[\"id\"], \"id:testapp:testapp::32\")"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%%\n"+ }+ },+ "id": "7981739a"+ },+ {+ "cell_type": "markdown",+ "source": [+ "This covers most of the functionality in the Vespa vector store in LangChain.\n",+ "\n"+ ],+ "metadata": {+ "collapsed": false,+ "pycharm": {+ "name": "#%% md\n"+ }+ },+ "id": "24791204"+ }+ ],+ "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}\ No newline at end of filediff --git a/docs/docs/integrations/vectorstores/weaviate.ipynb b/docs/docs/integrations/vectorstores/weaviate.ipynbindex 98f09e996d..788cf66237 100644--- a/docs/docs/integrations/vectorstores/weaviate.ipynb+++ b/docs/docs/integrations/vectorstores/weaviate.ipynb@@ -201,7 +201,9 @@"source": ["import weaviate\n","\n",- "client = weaviate.Client(url=WEAVIATE_URL, auth_client_secret=weaviate.AuthApiKey(WEAVIATE_API_KEY))\n",+ "client = weaviate.Client(\n",+ " url=WEAVIATE_URL, auth_client_secret=weaviate.AuthApiKey(WEAVIATE_API_KEY)\n",+ ")\n","\n","# client = weaviate.Client(\n","# url=WEAVIATE_URL,\n",@@ -211,7 +213,9 @@"# ),\n","# )\n","\n",- "vectorstore = Weaviate.from_documents(documents, embeddings, client=client, by_text=False)"+ "vectorstore = Weaviate.from_documents(\n",+ " documents, embeddings, client=client, by_text=False\n",+ ")"]},{diff --git a/docs/docs/integrations/vectorstores/xata.ipynb b/docs/docs/integrations/vectorstores/xata.ipynbindex 4648d5218d..4561708867 100644--- a/docs/docs/integrations/vectorstores/xata.ipynb+++ b/docs/docs/integrations/vectorstores/xata.ipynb@@ -110,7 +110,7 @@"from langchain.embeddings.openai import OpenAIEmbeddings\n","from langchain.text_splitter import CharacterTextSplitter\n","from langchain.document_loaders import TextLoader\n",- "from langchain.vectorstores.xata import XataVectorStore\n"+ "from langchain.vectorstores.xata import XataVectorStore"]},{@@ -158,7 +158,9 @@},"outputs": [],"source": [- "vector_store = XataVectorStore.from_documents(docs, embeddings, api_key=api_key, db_url=db_url, table_name=\"vectors\")"+ "vector_store = XataVectorStore.from_documents(\n",+ " docs, embeddings, api_key=api_key, db_url=db_url, table_name=\"vectors\"\n",+ ")"]},{diff --git a/docs/docs/integrations/vectorstores/zep.ipynb b/docs/docs/integrations/vectorstores/zep.ipynbindex b8a3e5fdfb..e66cb4825a 100644--- a/docs/docs/integrations/vectorstores/zep.ipynb+++ b/docs/docs/integrations/vectorstores/zep.ipynb@@ -71,7 +71,7 @@" description=\"<optional description>\",\n"," metadata={\"optional_metadata\": \"associated with the collection\"},\n"," is_auto_embedded=True, # we'll have Zep embed our documents using its low-latency embedder\n",- " embedding_dimensions=1536 # this should match the model you've configured Zep to use.\n",+ " embedding_dimensions=1536, # this should match the model you've configured Zep to use.\n",")\n","\n","# load the document\n",@@ -85,12 +85,13 @@"\n","# Instantiate the VectorStore. Since the collection does not already exist in Zep,\n","# it will be created and populated with the documents we pass in.\n",- "vs = ZepVectorStore.from_documents(docs,\n",- " collection_name=collection_name,\n",- " config=config,\n",- " api_url=ZEP_API_URL,\n",- " api_key=ZEP_API_KEY\n",- " )"+ "vs = ZepVectorStore.from_documents(\n",+ " docs,\n",+ " collection_name=collection_name,\n",+ " config=config,\n",+ " api_url=ZEP_API_URL,\n",+ " api_key=ZEP_API_KEY,\n",+ ")"],"metadata": {"collapsed": false,@@ -118,6 +119,7 @@"source": ["# wait for the collection embedding to complete\n","\n",+ "\n","async def wait_for_ready(collection_name: str) -> None:\n"," from zep_python import ZepClient\n"," import time\n",@@ -452,7 +454,9 @@],"source": ["filter = {\n",- " \"where\": {\"jsonpath\": \"$[*] ? (@.source == 'https://www.gutenberg.org/files/48320/48320-0.txt')\"},\n",+ " \"where\": {\n",+ " \"jsonpath\": \"$[*] ? (@.source == 'https://www.gutenberg.org/files/48320/48320-0.txt')\"\n",+ " },\n","}\n","\n","docs = await vs.asearch(query, search_type=\"similarity\", metadata=filter, k=3)\n",diff --git a/docs/docs/modules/agents/agent_types/chat_conversation_agent.ipynb b/docs/docs/modules/agents/agent_types/chat_conversation_agent.ipynbindex c12cf6043d..347b6a4b91 100644--- a/docs/docs/modules/agents/agent_types/chat_conversation_agent.ipynb+++ b/docs/docs/modules/agents/agent_types/chat_conversation_agent.ipynb@@ -40,7 +40,7 @@" Tool(\n"," name=\"Current Search\",\n"," func=search.run,\n",- " description=\"useful for when you need to answer questions about current events or the current state of the world\"\n",+ " description=\"useful for when you need to answer questions about current events or the current state of the world\",\n"," ),\n","]"]@@ -52,7 +52,7 @@"metadata": {},"outputs": [],"source": [- "llm=OpenAI(temperature=0)"+ "llm = OpenAI(temperature=0)"]},{@@ -118,11 +118,16 @@"metadata": {},"outputs": [],"source": [- "agent = {\n",- " \"input\": lambda x: x[\"input\"],\n",- " \"agent_scratchpad\": lambda x: format_log_to_str(x['intermediate_steps']),\n",- " \"chat_history\": lambda x: x[\"chat_history\"]\n",- "} | prompt | llm_with_stop | ReActSingleInputOutputParser()"+ "agent = (\n",+ " {\n",+ " \"input\": lambda x: x[\"input\"],\n",+ " \"agent_scratchpad\": lambda x: format_log_to_str(x[\"intermediate_steps\"]),\n",+ " \"chat_history\": lambda x: x[\"chat_history\"],\n",+ " }\n",+ " | prompt\n",+ " | llm_with_stop\n",+ " | ReActSingleInputOutputParser()\n",+ ")"]},{@@ -180,7 +185,7 @@}],"source": [- "agent_executor.invoke({\"input\": \"hi, i am bob\"})['output']"+ "agent_executor.invoke({\"input\": \"hi, i am bob\"})[\"output\"]"]},{@@ -215,7 +220,7 @@}],"source": [- "agent_executor.invoke({\"input\": \"whats my name?\"})['output']"+ "agent_executor.invoke({\"input\": \"whats my name?\"})[\"output\"]"]},{@@ -252,7 +257,7 @@}],"source": [- "agent_executor.invoke({\"input\": \"what are some movies showing 9/21/2023?\"})['output']"+ "agent_executor.invoke({\"input\": \"what are some movies showing 9/21/2023?\"})[\"output\"]"]},{@@ -272,7 +277,13 @@"metadata": {},"outputs": [],"source": [- "agent_executor = initialize_agent(tools, llm, agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION, verbose=True, memory=memory)"+ "agent_executor = initialize_agent(\n",+ " tools,\n",+ " llm,\n",+ " agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION,\n",+ " verbose=True,\n",+ " memory=memory,\n",+ ")"]},{@@ -304,7 +315,7 @@"outputs": [],"source": ["prompt = hub.pull(\"hwchase17/react-chat-json\")\n",- "chat_model = ChatOpenAI(temperature=0, model='gpt-4')"+ "chat_model = ChatOpenAI(temperature=0, model=\"gpt-4\")"]},{@@ -358,11 +369,18 @@"\n","Okay, so what is the response to my last comment? If using information obtained from the tools you must mention it explicitly without mentioning the tool names - I have forgotten all TOOL RESPONSES! Remember to respond with a markdown code snippet of a json blob with a single action, and NOTHING else - even if you just want to respond to the user. Do NOT respond with anything except a JSON snippet no matter what!\"\"\"\n","\n",- "agent = {\n",- " \"input\": lambda x: x[\"input\"],\n",- " \"agent_scratchpad\": lambda x: format_log_to_messages(x['intermediate_steps'], template_tool_response=TEMPLATE_TOOL_RESPONSE),\n",- " \"chat_history\": lambda x: x[\"chat_history\"],\n",- "} | prompt | chat_model_with_stop | JSONAgentOutputParser()"+ "agent = (\n",+ " {\n",+ " \"input\": lambda x: x[\"input\"],\n",+ " \"agent_scratchpad\": lambda x: format_log_to_messages(\n",+ " x[\"intermediate_steps\"], template_tool_response=TEMPLATE_TOOL_RESPONSE\n",+ " ),\n",+ " \"chat_history\": lambda x: x[\"chat_history\"],\n",+ " }\n",+ " | prompt\n",+ " | chat_model_with_stop\n",+ " | JSONAgentOutputParser()\n",+ ")"]},{@@ -421,7 +439,7 @@}],"source": [- "agent_executor.invoke({\"input\": \"hi, i am bob\"})['output']"+ "agent_executor.invoke({\"input\": \"hi, i am bob\"})[\"output\"]"]},{@@ -459,7 +477,7 @@}],"source": [- "agent_executor.invoke({\"input\": \"whats my name?\"})['output']"+ "agent_executor.invoke({\"input\": \"whats my name?\"})[\"output\"]"]},{@@ -502,7 +520,7 @@}],"source": [- "agent_executor.invoke({\"input\": \"what are some movies showing 9/21/2023?\"})['output']"+ "agent_executor.invoke({\"input\": \"what are some movies showing 9/21/2023?\"})[\"output\"]"]},{@@ -533,7 +551,13 @@"source": ["memory = ConversationBufferMemory(memory_key=\"chat_history\", return_messages=True)\n","llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY, temperature=0)\n",- "agent_chain = initialize_agent(tools, llm, agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION, verbose=True, memory=memory)"+ "agent_chain = initialize_agent(\n",+ " tools,\n",+ " llm,\n",+ " agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION,\n",+ " verbose=True,\n",+ " memory=memory,\n",+ ")"]}],diff --git a/docs/docs/modules/agents/agent_types/openai_functions_agent.ipynb b/docs/docs/modules/agents/agent_types/openai_functions_agent.ipynbindex 55745352f9..a1cae388f0 100644--- a/docs/docs/modules/agents/agent_types/openai_functions_agent.ipynb+++ b/docs/docs/modules/agents/agent_types/openai_functions_agent.ipynb@@ -65,18 +65,18 @@" Tool(\n"," name=\"Search\",\n"," func=search.run,\n",- " description=\"useful for when you need to answer questions about current events. You should ask targeted questions\"\n",+ " description=\"useful for when you need to answer questions about current events. You should ask targeted questions\",\n"," ),\n"," Tool(\n"," name=\"Calculator\",\n"," func=llm_math_chain.run,\n",- " description=\"useful for when you need to answer questions about math\"\n",+ " description=\"useful for when you need to answer questions about math\",\n"," ),\n"," Tool(\n"," name=\"FooBar-DB\",\n"," func=db_chain.run,\n",- " description=\"useful for when you need to answer questions about FooBar. Input should be in the form of a question containing full context\"\n",- " )\n",+ " description=\"useful for when you need to answer questions about FooBar. Input should be in the form of a question containing full context\",\n",+ " ),\n","]"]},@@ -107,11 +107,13 @@"metadata": {},"outputs": [],"source": [- "prompt = ChatPromptTemplate.from_messages([\n",- " (\"system\", \"You are a helpful assistant\"),\n",- " (\"user\", \"{input}\"),\n",- " MessagesPlaceholder(variable_name=\"agent_scratchpad\"),\n",- "])"+ "prompt = ChatPromptTemplate.from_messages(\n",+ " [\n",+ " (\"system\", \"You are a helpful assistant\"),\n",+ " (\"user\", \"{input}\"),\n",+ " MessagesPlaceholder(variable_name=\"agent_scratchpad\"),\n",+ " ]\n",+ ")"]},{@@ -131,9 +133,7 @@"metadata": {},"outputs": [],"source": [- "llm_with_tools = llm.bind(\n",- " functions=[format_tool_to_openai_function(t) for t in tools]\n",- ")"+ "llm_with_tools = llm.bind(functions=[format_tool_to_openai_function(t) for t in tools])"]},{@@ -154,10 +154,17 @@"metadata": {},"outputs": [],"source": [- "agent = {\n",- " \"input\": lambda x: x[\"input\"],\n",- " \"agent_scratchpad\": lambda x: format_to_openai_functions(x['intermediate_steps'])\n",- "} | prompt | llm_with_tools | OpenAIFunctionsAgentOutputParser()"+ "agent = (\n",+ " {\n",+ " \"input\": lambda x: x[\"input\"],\n",+ " \"agent_scratchpad\": lambda x: format_to_openai_functions(\n",+ " x[\"intermediate_steps\"]\n",+ " ),\n",+ " }\n",+ " | prompt\n",+ " | llm_with_tools\n",+ " | OpenAIFunctionsAgentOutputParser()\n",+ ")"]},{@@ -229,7 +236,11 @@}],"source": [- "agent_executor.invoke({\"input\": \"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?\"})"+ "agent_executor.invoke(\n",+ " {\n",+ " \"input\": \"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?\"\n",+ " }\n",+ ")"]},{@@ -249,7 +260,9 @@"metadata": {},"outputs": [],"source": [- "agent_executor = initialize_agent(tools, llm, agent=AgentType.OPENAI_FUNCTIONS, verbose=True)"+ "agent_executor = initialize_agent(\n",+ " tools, llm, agent=AgentType.OPENAI_FUNCTIONS, verbose=True\n",+ ")"]},{@@ -259,7 +272,11 @@"metadata": {},"outputs": [],"source": [- "agent_executor.invoke({\"input\": \"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?\"})"+ "agent_executor.invoke(\n",+ " {\n",+ " \"input\": \"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?\"\n",+ " }\n",+ ")"]},{diff --git a/docs/docs/modules/agents/agent_types/react.ipynb b/docs/docs/modules/agents/agent_types/react.ipynbindex 2b5091773f..15710bd53c 100644--- a/docs/docs/modules/agents/agent_types/react.ipynb+++ b/docs/docs/modules/agents/agent_types/react.ipynb@@ -113,10 +113,15 @@"metadata": {},"outputs": [],"source": [- "agent = {\n",- " \"input\": lambda x: x[\"input\"],\n",- " \"agent_scratchpad\": lambda x: format_log_to_str(x['intermediate_steps'])\n",- "} | prompt | llm_with_stop | ReActSingleInputOutputParser()"+ "agent = (\n",+ " {\n",+ " \"input\": lambda x: x[\"input\"],\n",+ " \"agent_scratchpad\": lambda x: format_log_to_str(x[\"intermediate_steps\"]),\n",+ " }\n",+ " | prompt\n",+ " | llm_with_stop\n",+ " | ReActSingleInputOutputParser()\n",+ ")"]},{@@ -177,7 +182,11 @@}],"source": [- "agent_executor.invoke({\"input\": \"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?\"})"+ "agent_executor.invoke(\n",+ " {\n",+ " \"input\": \"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?\"\n",+ " }\n",+ ")"]},{@@ -197,7 +206,9 @@"metadata": {},"outputs": [],"source": [- "agent_executor = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)"+ "agent_executor = initialize_agent(\n",+ " tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True\n",+ ")"]},{@@ -244,7 +255,11 @@}],"source": [- "agent_executor.invoke({\"input\": \"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?\"})"+ "agent_executor.invoke(\n",+ " {\n",+ " \"input\": \"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?\"\n",+ " }\n",+ ")"]},{@@ -320,10 +335,15 @@"metadata": {},"outputs": [],"source": [- "agent = {\n",- " \"input\": lambda x: x[\"input\"],\n",- " \"agent_scratchpad\": lambda x: format_log_to_str(x['intermediate_steps'])\n",- "} | prompt | chat_model_with_stop | ReActJsonSingleInputOutputParser()"+ "agent = (\n",+ " {\n",+ " \"input\": lambda x: x[\"input\"],\n",+ " \"agent_scratchpad\": lambda x: format_log_to_str(x[\"intermediate_steps\"]),\n",+ " }\n",+ " | prompt\n",+ " | chat_model_with_stop\n",+ " | ReActJsonSingleInputOutputParser()\n",+ ")"]},{@@ -343,7 +363,11 @@"metadata": {},"outputs": [],"source": [- "agent_executor.invoke({\"input\": \"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?\"})"+ "agent_executor.invoke(\n",+ " {\n",+ " \"input\": \"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?\"\n",+ " }\n",+ ")"]},{@@ -361,9 +385,12 @@"metadata": {},"outputs": [],"source": [- "\n",- "agent = initialize_agent(tools, chat_model, agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)\n",- "agent.run(\"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?\")"+ "agent = initialize_agent(\n",+ " tools, chat_model, agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True\n",+ ")\n",+ "agent.run(\n",+ " \"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?\"\n",+ ")"]}],diff --git a/docs/docs/modules/agents/agent_types/self_ask_with_search.ipynb b/docs/docs/modules/agents/agent_types/self_ask_with_search.ipynbindex da4135e204..f253be7a5c 100644--- a/docs/docs/modules/agents/agent_types/self_ask_with_search.ipynb+++ b/docs/docs/modules/agents/agent_types/self_ask_with_search.ipynb@@ -82,15 +82,20 @@"metadata": {},"outputs": [],"source": [- "agent = {\n",- " \"input\": lambda x: x[\"input\"],\n",- " # Use some custom observation_prefix/llm_prefix for formatting\n",- " \"agent_scratchpad\": lambda x: format_log_to_str(\n",- " x['intermediate_steps'], \n",- " observation_prefix=\"\\nIntermediate answer: \",\n",- " llm_prefix=\"\",\n",- " ),\n",- "} | prompt | llm_with_stop | SelfAskOutputParser()"+ "agent = (\n",+ " {\n",+ " \"input\": lambda x: x[\"input\"],\n",+ " # Use some custom observation_prefix/llm_prefix for formatting\n",+ " \"agent_scratchpad\": lambda x: format_log_to_str(\n",+ " x[\"intermediate_steps\"],\n",+ " observation_prefix=\"\\nIntermediate answer: \",\n",+ " llm_prefix=\"\",\n",+ " ),\n",+ " }\n",+ " | prompt\n",+ " | llm_with_stop\n",+ " | SelfAskOutputParser()\n",+ ")"]},{@@ -147,7 +152,9 @@}],"source": [- "agent_executor.invoke({\"input\": \"What is the hometown of the reigning men's U.S. Open champion?\"})"+ "agent_executor.invoke(\n",+ " {\"input\": \"What is the hometown of the reigning men's U.S. Open champion?\"}\n",+ ")"]},{diff --git a/docs/docs/modules/agents/agent_types/structured_chat.ipynb b/docs/docs/modules/agents/agent_types/structured_chat.ipynbindex 92a7229fca..2ba9ca9b56 100644--- a/docs/docs/modules/agents/agent_types/structured_chat.ipynb+++ b/docs/docs/modules/agents/agent_types/structured_chat.ipynb@@ -44,11 +44,12 @@"from langchain.agents.agent_toolkits import PlayWrightBrowserToolkit\n","from langchain.tools.playwright.utils import (\n"," create_async_playwright_browser,\n",- " create_sync_playwright_browser, # A synchronous browser is available, though it isn't compatible with jupyter.\n",+ " create_sync_playwright_browser, # A synchronous browser is available, though it isn't compatible with jupyter.\n",")\n","\n","# This import is required only for jupyter notebooks, since they have their own eventloop\n","import nest_asyncio\n",+ "\n","nest_asyncio.apply()"]},@@ -158,10 +159,15 @@"metadata": {},"outputs": [],"source": [- "agent = {\n",- " \"input\": lambda x: x[\"input\"],\n",- " \"agent_scratchpad\": lambda x: format_log_to_str(x['intermediate_steps']),\n",- "} | prompt | llm_with_stop | JSONAgentOutputParser()"+ "agent = (\n",+ " {\n",+ " \"input\": lambda x: x[\"input\"],\n",+ " \"agent_scratchpad\": lambda x: format_log_to_str(x[\"intermediate_steps\"]),\n",+ " }\n",+ " | prompt\n",+ " | llm_with_stop\n",+ " | JSONAgentOutputParser()\n",+ ")"]},{@@ -230,8 +236,10 @@}],"source": [- "response = await agent_executor.ainvoke({\"input\": \"Browse to blog.langchain.dev and summarize the text, please.\"})\n",- "print(response['output'])"+ "response = await agent_executor.ainvoke(\n",+ " {\"input\": \"Browse to blog.langchain.dev and summarize the text, please.\"}\n",+ ")\n",+ "print(response[\"output\"])"]},{@@ -249,8 +257,13 @@"metadata": {},"outputs": [],"source": [- "llm = ChatOpenAI(temperature=0) # Also works well with Anthropic models\n",- "agent_chain = initialize_agent(tools, llm, agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)"+ "llm = ChatOpenAI(temperature=0) # Also works well with Anthropic models\n",+ "agent_chain = initialize_agent(\n",+ " tools,\n",+ " llm,\n",+ " agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,\n",+ " verbose=True,\n",+ ")"]},{@@ -293,8 +306,10 @@}],"source": [- "response = await agent_chain.ainvoke({\"input\": \"Browse to blog.langchain.dev and summarize the text, please.\"})\n",- "print(response['output'])"+ "response = await agent_chain.ainvoke(\n",+ " {\"input\": \"Browse to blog.langchain.dev and summarize the text, please.\"}\n",+ ")\n",+ "print(response[\"output\"])"]},{diff --git a/docs/docs/modules/agents/agent_types/xml_agent.ipynb b/docs/docs/modules/agents/agent_types/xml_agent.ipynbindex 38fe3f589d..c5a945722e 100644--- a/docs/docs/modules/agents/agent_types/xml_agent.ipynb+++ b/docs/docs/modules/agents/agent_types/xml_agent.ipynb@@ -29,6 +29,7 @@"source": ["from langchain.agents import tool\n","\n",+ "\n","@tool\n","def search(query: str) -> str:\n"," \"\"\"Search things about current events.\"\"\"\n",@@ -53,6 +54,7 @@"outputs": [],"source": ["from langchain.chat_models import ChatAnthropic\n",+ "\n","model = ChatAnthropic(model=\"claude-2\")"]},@@ -119,10 +121,15 @@"metadata": {},"outputs": [],"source": [- "agent = {\n",- " \"question\": lambda x: x[\"question\"],\n",- " \"agent_scratchpad\": lambda x: format_xml(x['intermediate_steps']),\n",- "} | prompt | llm_with_stop | XMLAgentOutputParser()"+ "agent = (\n",+ " {\n",+ " \"question\": lambda x: x[\"question\"],\n",+ " \"agent_scratchpad\": lambda x: format_xml(x[\"intermediate_steps\"]),\n",+ " }\n",+ " | prompt\n",+ " | llm_with_stop\n",+ " | XMLAgentOutputParser()\n",+ ")"]},{@@ -212,7 +219,7 @@"chain = LLMChain(\n"," llm=model,\n"," prompt=XMLAgent.get_default_prompt(),\n",- " output_parser=XMLAgent.get_default_output_parser()\n",+ " output_parser=XMLAgent.get_default_output_parser(),\n",")\n","agent = XMLAgent(tools=tools, llm_chain=chain)"]diff --git a/docs/docs/modules/agents/how_to/agent_structured.ipynb b/docs/docs/modules/agents/how_to/agent_structured.ipynbindex 2db9674db6..40bad3aeda 100644--- a/docs/docs/modules/agents/how_to/agent_structured.ipynb+++ b/docs/docs/modules/agents/how_to/agent_structured.ipynb@@ -57,7 +57,7 @@"outputs": [],"source": ["# Load in document to retrieve over\n",- "loader = TextLoader('../../state_of_the_union.txt')\n",+ "loader = TextLoader(\"../../state_of_the_union.txt\")\n","documents = loader.load()\n","\n","# Split document into chunks\n",@@ -66,7 +66,7 @@"\n","# Here is where we add in the fake source information\n","for i, doc in enumerate(texts):\n",- " doc.metadata['page_chunk'] = i\n",+ " doc.metadata[\"page_chunk\"] = i\n","\n","# Create our retriever\n","embeddings = OpenAIEmbeddings()\n",@@ -91,12 +91,14 @@"metadata": {},"outputs": [],"source": [- "from langchain.agents.agent_toolkits.conversational_retrieval.tool import create_retriever_tool\n",+ "from langchain.agents.agent_toolkits.conversational_retrieval.tool import (\n",+ " create_retriever_tool,\n",+ ")\n","\n","retriever_tool = create_retriever_tool(\n"," retriever,\n"," \"state-of-union-retriever\",\n",- " \"Query a retriever to get information about state of the union address\"\n",+ " \"Query a retriever to get information about state of the union address\",\n",")"]},@@ -121,10 +123,14 @@"from typing import List\n","from langchain.utils.openai_functions import convert_pydantic_to_openai_function\n","\n",+ "\n","class Response(BaseModel):\n"," \"\"\"Final response to the question being asked\"\"\"\n",- " answer: str = Field(description = \"The final answer to respond to the user\")\n",- " sources: List[int] = Field(description=\"List of page chunks that contain answer to the question. Only include a page chunk if it contains relevant information\")"+ "\n",+ " answer: str = Field(description=\"The final answer to respond to the user\")\n",+ " sources: List[int] = Field(\n",+ " description=\"List of page chunks that contain answer to the question. Only include a page chunk if it contains relevant information\"\n",+ " )"]},{@@ -172,18 +178,20 @@" # If no function was invoked, return to user\n"," if \"function_call\" not in output.additional_kwargs:\n"," return AgentFinish(return_values={\"output\": output.content}, log=output.content)\n",- " \n",+ "\n"," # Parse out the function call\n"," function_call = output.additional_kwargs[\"function_call\"]\n",- " name = function_call['name']\n",- " inputs = json.loads(function_call['arguments'])\n",- " \n",+ " name = function_call[\"name\"]\n",+ " inputs = json.loads(function_call[\"arguments\"])\n",+ "\n"," # If the Response function was invoked, return to the user with the function inputs\n"," if name == \"Response\":\n"," return AgentFinish(return_values=inputs, log=str(function_call))\n"," # Otherwise, return an agent action\n"," else:\n",- " return AgentActionMessageLog(tool=name, tool_input=inputs, log=\"\", message_log=[output])"+ " return AgentActionMessageLog(\n",+ " tool=name, tool_input=inputs, log=\"\", message_log=[output]\n",+ " )"]},{@@ -223,11 +231,13 @@"metadata": {},"outputs": [],"source": [- "prompt = ChatPromptTemplate.from_messages([\n",- " (\"system\", \"You are a helpful assistant\"),\n",- " (\"user\", \"{input}\"),\n",- " MessagesPlaceholder(variable_name=\"agent_scratchpad\"),\n",- "])"+ "prompt = ChatPromptTemplate.from_messages(\n",+ " [\n",+ " (\"system\", \"You are a helpful assistant\"),\n",+ " (\"user\", \"{input}\"),\n",+ " MessagesPlaceholder(variable_name=\"agent_scratchpad\"),\n",+ " ]\n",+ ")"]},{@@ -250,9 +260,9 @@"llm_with_tools = llm.bind(\n"," functions=[\n"," # The retriever tool\n",- " format_tool_to_openai_function(retriever_tool), \n",+ " format_tool_to_openai_function(retriever_tool),\n"," # Response schema\n",- " convert_pydantic_to_openai_function(Response)\n",+ " convert_pydantic_to_openai_function(Response),\n"," ]\n",")"]@@ -264,11 +274,18 @@"metadata": {},"outputs": [],"source": [- "agent = {\n",- " \"input\": lambda x: x[\"input\"],\n",- " # Format agent scratchpad from intermediate steps\n",- " \"agent_scratchpad\": lambda x: format_to_openai_functions(x['intermediate_steps'])\n",- "} | prompt | llm_with_tools | parse"+ "agent = (\n",+ " {\n",+ " \"input\": lambda x: x[\"input\"],\n",+ " # Format agent scratchpad from intermediate steps\n",+ " \"agent_scratchpad\": lambda x: format_to_openai_functions(\n",+ " x[\"intermediate_steps\"]\n",+ " ),\n",+ " }\n",+ " | prompt\n",+ " | llm_with_tools\n",+ " | parse\n",+ ")"]},{@@ -322,7 +339,10 @@}],"source": [- "agent_executor.invoke({\"input\": \"what did the president say about kentaji brown jackson\"}, return_only_outputs=True)"+ "agent_executor.invoke(\n",+ " {\"input\": \"what did the president say about kentaji brown jackson\"},\n",+ " return_only_outputs=True,\n",+ ")"]},{diff --git a/docs/docs/modules/chains/document/map_reduce.ipynb b/docs/docs/modules/chains/document/map_reduce.ipynbindex 46d58e2e62..d186993c18 100644--- a/docs/docs/modules/chains/document/map_reduce.ipynb+++ b/docs/docs/modules/chains/document/map_reduce.ipynb@@ -64,17 +64,17 @@"# The chain we'll apply to each individual document.\n","# Returns a summary of the document.\n","map_chain = (\n",- " {\"context\": partial_format_document} \n",- " | PromptTemplate.from_template(\"Summarize this content:\\n\\n{context}\") \n",- " | llm \n",+ " {\"context\": partial_format_document}\n",+ " | PromptTemplate.from_template(\"Summarize this content:\\n\\n{context}\")\n",+ " | llm\n"," | StrOutputParser()\n",")\n","\n","# A wrapper chain to keep the original Document metadata\n","map_as_doc_chain = (\n",- " RunnableParallel({\"doc\": RunnablePassthrough(), \"content\": map_chain}) \n",+ " RunnableParallel({\"doc\": RunnablePassthrough(), \"content\": map_chain})\n"," | (lambda x: Document(page_content=x[\"content\"], metadata=x[\"doc\"].metadata))\n",- ").with_config(run_name=\"Summarize (return doc)\")\n"+ ").with_config(run_name=\"Summarize (return doc)\")"]},{@@ -84,12 +84,13 @@"metadata": {},"outputs": [],"source": [- "# The chain we'll repeatedly apply to collapse subsets of the documents \n",- "# into a consolidate document until the total token size of our \n",+ "# The chain we'll repeatedly apply to collapse subsets of the documents\n",+ "# into a consolidate document until the total token size of our\n","# documents is below some max size.\n","def format_docs(docs):\n"," return \"\\n\\n\".join(partial_format_document(doc) for doc in docs)\n",- " \n",+ "\n",+ "\n","collapse_chain = (\n"," {\"context\": format_docs}\n"," | PromptTemplate.from_template(\"Collapse this content:\\n\\n{context}\")\n",@@ -97,11 +98,13 @@" | StrOutputParser()\n",")\n","\n",+ "\n","def get_num_tokens(docs):\n"," return llm.get_num_tokens(format_docs(docs))\n","\n",+ "\n","def collapse(\n",- " docs, \n",+ " docs,\n"," config,\n"," token_max=4000,\n","):\n",@@ -142,7 +145,9 @@"outputs": [],"source": ["# The final full chain\n",- "map_reduce = (map_as_doc_chain.map() | collapse | reduce_chain).with_config(run_name=\"Map reduce\")"+ "map_reduce = (map_as_doc_chain.map() | collapse | reduce_chain).with_config(\n",+ " run_name=\"Map reduce\"\n",+ ")"]},{@@ -191,9 +196,9 @@"\n","docs = [\n"," Document(\n",- " page_content=split, \n",- " metadata={\"source\": \"https://en.wikipedia.org/wiki/Nuclear_power_in_space\"}\n",- " ) \n",+ " page_content=split,\n",+ " metadata={\"source\": \"https://en.wikipedia.org/wiki/Nuclear_power_in_space\"},\n",+ " )\n"," for split in text.split(\"\\n\\n\")\n","]"]diff --git a/docs/docs/modules/chains/document/map_rerank.ipynb b/docs/docs/modules/chains/document/map_rerank.ipynbindex a2c431c4c0..1367b7abee 100644--- a/docs/docs/modules/chains/document/map_rerank.ipynb+++ b/docs/docs/modules/chains/document/map_rerank.ipynb@@ -53,15 +53,24 @@" \"\\n\\nContext:\\n\\n{context}\\n\\nQuestion: {question}\"\n",")\n","\n",+ "\n","class AnswerAndScore(BaseModel):\n"," \"\"\"Return the answer to the question and a relevance score.\"\"\"\n",- " answer: str = Field(description=\"The answer to the question, which is based ONLY on the provided context.\")\n",- " score: float = Field(decsription=\"A 0.0-1.0 relevance score, where 1.0 indicates the provided context answers the question completely and 0.0 indicates the provided context does not answer the question at all.\")\n",+ "\n",+ " answer: str = Field(\n",+ " description=\"The answer to the question, which is based ONLY on the provided context.\"\n",+ " )\n",+ " score: float = Field(\n",+ " decsription=\"A 0.0-1.0 relevance score, where 1.0 indicates the provided context answers the question completely and 0.0 indicates the provided context does not answer the question at all.\"\n",+ " )\n",+ "\n","\n","function = convert_pydantic_to_openai_function(AnswerAndScore)\n","map_chain = (\n",- " map_prompt \n",- " | ChatOpenAI().bind(temperature=0, functions=[function], function_call={\"name\": \"AnswerAndScore\"})\n",+ " map_prompt\n",+ " | ChatOpenAI().bind(\n",+ " temperature=0, functions=[function], function_call={\"name\": \"AnswerAndScore\"}\n",+ " )\n"," | PydanticOutputFunctionsParser(pydantic_schema=AnswerAndScore)\n",").with_config(run_name=\"Map\")"]@@ -76,12 +85,22 @@"# Final chain, which after answer and scoring based on\n","# each doc return the answer with the highest score.\n","\n",+ "\n","def top_answer(scored_answers):\n"," return max(scored_answers, key=lambda x: x.score).answer\n","\n",+ "\n","document_prompt = PromptTemplate.from_template(\"{page_content}\")\n","map_rerank_chain = (\n",- " (lambda x: [{\"context\": format_document(doc, document_prompt), \"question\": x[\"question\"]} for doc in x[\"docs\"]])\n",+ " (\n",+ " lambda x: [\n",+ " {\n",+ " \"context\": format_document(doc, document_prompt),\n",+ " \"question\": x[\"question\"],\n",+ " }\n",+ " for doc in x[\"docs\"]\n",+ " ]\n",+ " )\n"," | map_chain.map()\n"," | top_answer\n",").with_config(run_name=\"Map rerank\")"@@ -133,9 +152,9 @@"\n","docs = [\n"," Document(\n",- " page_content=split, \n",- " metadata={\"source\": \"https://en.wikipedia.org/wiki/Nuclear_power_in_space\"}\n",- " ) \n",+ " page_content=split,\n",+ " metadata={\"source\": \"https://en.wikipedia.org/wiki/Nuclear_power_in_space\"},\n",+ " )\n"," for split in text.split(\"\\n\\n\")\n","]"]@@ -155,7 +174,9 @@}],"source": [- "print(map_rerank_chain.invoke({\"docs\": docs, \"question\": \"How were the vikings powered\"}))"+ "print(\n",+ " map_rerank_chain.invoke({\"docs\": docs, \"question\": \"How were the vikings powered\"})\n",+ ")"]}],diff --git a/docs/docs/modules/chains/document/refine.ipynb b/docs/docs/modules/chains/document/refine.ipynbindex c8a9b69026..6869336021 100644--- a/docs/docs/modules/chains/document/refine.ipynb+++ b/docs/docs/modules/chains/document/refine.ipynb@@ -86,10 +86,11 @@")\n","refine_chain = (\n"," {\n",- " \"prev_response\": itemgetter(\"prev_response\"), \n",- " \"context\": lambda x: partial_format_doc(x[\"doc\"])\n",- " } | refine_prompt\n",- " | llm \n",+ " \"prev_response\": itemgetter(\"prev_response\"),\n",+ " \"context\": lambda x: partial_format_doc(x[\"doc\"]),\n",+ " }\n",+ " | refine_prompt\n",+ " | llm\n"," | StrOutputParser()\n",")"]@@ -104,16 +105,16 @@"# The final refine loop, which generates an initial summary\n","# then iteratively refines it based on each of the rest of the documents\n","\n",+ "\n","def refine_loop(docs):\n"," with trace_as_chain_group(\"refine loop\", inputs={\"input\": docs}) as manager:\n"," summary = summary_chain.invoke(\n",- " docs[0], \n",- " config={\"callbacks\": manager, \"run_name\": \"initial summary\"}\n",+ " docs[0], config={\"callbacks\": manager, \"run_name\": \"initial summary\"}\n"," )\n"," for i, doc in enumerate(docs[1:]):\n"," summary = refine_chain.invoke(\n",- " {\"prev_response\": summary, \"doc\": doc}, \n",- " config={\"callbacks\": manager, \"run_name\": f\"refine {i}\"}\n",+ " {\"prev_response\": summary, \"doc\": doc},\n",+ " config={\"callbacks\": manager, \"run_name\": f\"refine {i}\"},\n"," )\n"," manager.on_chain_end({\"output\": summary})\n"," return summary"@@ -165,9 +166,9 @@"\n","docs = [\n"," Document(\n",- " page_content=split, \n",- " metadata={\"source\": \"https://en.wikipedia.org/wiki/Nuclear_power_in_space\"}\n",- " ) \n",+ " page_content=split,\n",+ " metadata={\"source\": \"https://en.wikipedia.org/wiki/Nuclear_power_in_space\"},\n",+ " )\n"," for split in text.split(\"\\n\\n\")\n","]"]diff --git a/docs/docs/modules/chains/document/stuff.ipynb b/docs/docs/modules/chains/document/stuff.ipynbindex 68298ad620..e97da5bceb 100644--- a/docs/docs/modules/chains/document/stuff.ipynb+++ b/docs/docs/modules/chains/document/stuff.ipynb@@ -54,9 +54,13 @@"outputs": [],"source": ["doc_prompt = PromptTemplate.from_template(\"{page_content}\")\n",- " \n",+ "\n","chain = (\n",- " {\"content\": lambda docs: \"\\n\\n\".join(format_document(doc, doc_prompt) for doc in docs)}\n",+ " {\n",+ " \"content\": lambda docs: \"\\n\\n\".join(\n",+ " format_document(doc, doc_prompt) for doc in docs\n",+ " )\n",+ " }\n"," | PromptTemplate.from_template(\"Summarize the following content:\\n\\n{content}\")\n"," | ChatAnthropic()\n"," | StrOutputParser()\n",@@ -111,9 +115,9 @@"\n","docs = [\n"," Document(\n",- " page_content=split, \n",- " metadata={\"source\": \"https://en.wikipedia.org/wiki/Nuclear_power_in_space\"}\n",- " ) \n",+ " page_content=split,\n",+ " metadata={\"source\": \"https://en.wikipedia.org/wiki/Nuclear_power_in_space\"},\n",+ " )\n"," for split in text.split()\n","]"]diff --git a/docs/docs/modules/chains/foundational/llm_chain.ipynb b/docs/docs/modules/chains/foundational/llm_chain.ipynbindex 38ac14b0b6..f8c5ecb0af 100644--- a/docs/docs/modules/chains/foundational/llm_chain.ipynb+++ b/docs/docs/modules/chains/foundational/llm_chain.ipynb@@ -44,7 +44,9 @@"from langchain.chat_models import ChatOpenAI\n","from langchain.schema import StrOutputParser\n","\n",- "prompt = PromptTemplate.from_template(\"What is a good name for a company that makes {product}?\")\n",+ "prompt = PromptTemplate.from_template(\n",+ " \"What is a good name for a company that makes {product}?\"\n",+ ")\n","runnable = prompt | ChatOpenAI() | StrOutputParser()\n","runnable.invoke({\"product\": \"colorful socks\"})"]@@ -98,10 +100,7 @@"prompt_template = \"What is a good name for a company that makes {product}?\"\n","\n","llm = OpenAI(temperature=0)\n",- "llm_chain = LLMChain(\n",- " llm=llm,\n",- " prompt=PromptTemplate.from_template(prompt_template)\n",- ")\n",+ "llm_chain = LLMChain(llm=llm, prompt=PromptTemplate.from_template(prompt_template))\n","llm_chain(\"colorful socks\")"]},@@ -137,11 +136,7 @@}],"source": [- "input_list = [\n",- " {\"product\": \"socks\"},\n",- " {\"product\": \"computer\"},\n",- " {\"product\": \"shoes\"}\n",- "]\n",+ "input_list = [{\"product\": \"socks\"}, {\"product\": \"computer\"}, {\"product\": \"shoes\"}]\n","llm_chain.apply(input_list)"]},@@ -264,7 +259,9 @@"\n","output_parser = CommaSeparatedListOutputParser()\n","template = \"\"\"List all the colors in a rainbow\"\"\"\n",- "prompt = PromptTemplate(template=template, input_variables=[], output_parser=output_parser)\n",+ "prompt = PromptTemplate(\n",+ " template=template, input_variables=[], output_parser=output_parser\n",+ ")\n","llm_chain = LLMChain(prompt=prompt, llm=llm)\n","\n","llm_chain.predict()"diff --git a/docs/docs/modules/chains/foundational/router.ipynb b/docs/docs/modules/chains/foundational/router.ipynbindex 1857eab3e0..2228a9f2d5 100644--- a/docs/docs/modules/chains/foundational/router.ipynb+++ b/docs/docs/modules/chains/foundational/router.ipynb@@ -74,9 +74,9 @@" \"You are a helpful assistant. Answer the question as accurately as you can.\\n\\n{input}\"\n",")\n","prompt_branch = RunnableBranch(\n",- " (lambda x: x[\"topic\"] == \"math\", math_prompt),\n",- " (lambda x: x[\"topic\"] == \"physics\", physics_prompt),\n",- " general_prompt\n",+ " (lambda x: x[\"topic\"] == \"math\", math_prompt),\n",+ " (lambda x: x[\"topic\"] == \"physics\", physics_prompt),\n",+ " general_prompt,\n",")"]},@@ -96,14 +96,18 @@"\n","class TopicClassifier(BaseModel):\n"," \"Classify the topic of the user question\"\n",- " \n",+ "\n"," topic: Literal[\"math\", \"physics\", \"general\"]\n"," \"The topic of the user question. One of 'math', 'phsyics' or 'general'.\"\n","\n","\n","classifier_function = convert_pydantic_to_openai_function(TopicClassifier)\n",- "llm = ChatOpenAI().bind(functions=[classifier_function], function_call={\"name\": \"TopicClassifier\"}) \n",- "parser = PydanticAttrOutputFunctionsParser(pydantic_schema=TopicClassifier, attr_name=\"topic\")\n",+ "llm = ChatOpenAI().bind(\n",+ " functions=[classifier_function], function_call={\"name\": \"TopicClassifier\"}\n",+ ")\n",+ "parser = PydanticAttrOutputFunctionsParser(\n",+ " pydantic_schema=TopicClassifier, attr_name=\"topic\"\n",+ ")\n","classifier_chain = llm | parser"]},@@ -121,8 +125,8 @@"\n","\n","final_chain = (\n",- " RunnablePassthrough.assign(topic=itemgetter(\"input\") | classifier_chain) \n",- " | prompt_branch \n",+ " RunnablePassthrough.assign(topic=itemgetter(\"input\") | classifier_chain)\n",+ " | prompt_branch\n"," | ChatOpenAI()\n"," | StrOutputParser()\n",")"@@ -147,7 +151,9 @@],"source": ["final_chain.invoke(\n",- " {\"input\": \"What is the first prime number greater than 40 such that one plus the prime number is divisible by 3?\"}\n",+ " {\n",+ " \"input\": \"What is the first prime number greater than 40 such that one plus the prime number is divisible by 3?\"\n",+ " }\n",")"]},diff --git a/docs/docs/modules/chains/foundational/sequential_chains.ipynb b/docs/docs/modules/chains/foundational/sequential_chains.ipynbindex 37fc725f95..d0e6d49974 100644--- a/docs/docs/modules/chains/foundational/sequential_chains.ipynb+++ b/docs/docs/modules/chains/foundational/sequential_chains.ipynb@@ -71,7 +71,12 @@"from langchain.schema import StrOutputParser\n","\n","llm = ChatOpenAI()\n",- "chain = {\"synopsis\": synopsis_prompt | llm | StrOutputParser()} | review_prompt | llm | StrOutputParser()\n",+ "chain = (\n",+ " {\"synopsis\": synopsis_prompt | llm | StrOutputParser()}\n",+ " | review_prompt\n",+ " | llm\n",+ " | StrOutputParser()\n",+ ")\n","chain.invoke({\"title\": \"Tragedy at sunset on the beach\"})"]},@@ -104,7 +109,7 @@"source": ["from langchain.schema.runnable import RunnablePassthrough\n","\n",- "synopsis_chain = synopsis_prompt | llm | StrOutputParser() \n",+ "synopsis_chain = synopsis_prompt | llm | StrOutputParser()\n","review_chain = review_prompt | llm | StrOutputParser()\n","chain = {\"synopsis\": synopsis_chain} | RunnablePassthrough.assign(review=review_chain)\n","chain.invoke({\"title\": \"Tragedy at sunset on the beach\"})"@@ -153,7 +158,7 @@"from langchain.prompts import PromptTemplate\n","\n","# This is an LLMChain to write a synopsis given a title of a play.\n",- "llm = OpenAI(temperature=.7)\n",+ "llm = OpenAI(temperature=0.7)\n","synopsis_chain = LLMChain(llm=llm, prompt=synopsis_prompt)"]},@@ -165,7 +170,7 @@"outputs": [],"source": ["# This is an LLMChain to write a review of a play given a synopsis.\n",- "llm = OpenAI(temperature=.7)\n",+ "llm = OpenAI(temperature=0.7)\n","review_chain = LLMChain(llm=llm, prompt=review_prompt)"]},@@ -205,7 +210,9 @@"# This is the overall chain where we run these two chains in sequence.\n","from langchain.chains import SimpleSequentialChain\n","\n",- "overall_chain = SimpleSequentialChain(chains=[synopsis_chain, review_chain], verbose=True)\n",+ "overall_chain = SimpleSequentialChain(\n",+ " chains=[synopsis_chain, review_chain], verbose=True\n",+ ")\n","\n","review = overall_chain.run(\"Tragedy at sunset on the beach\")"]@@ -253,14 +260,18 @@"outputs": [],"source": ["# This is an LLMChain to write a synopsis given a title of a play and the era it is set in.\n",- "llm = OpenAI(temperature=.7)\n",+ "llm = OpenAI(temperature=0.7)\n","synopsis_template = \"\"\"You are a playwright. Given the title of play and the era it is set in, it is your job to write a synopsis for that title.\n","\n","Title: {title}\n","Era: {era}\n","Playwright: This is a synopsis for the above play:\"\"\"\n",- "synopsis_prompt_template = PromptTemplate(input_variables=[\"title\", \"era\"], template=synopsis_template)\n",- "synopsis_chain = LLMChain(llm=llm, prompt=synopsis_prompt_template, output_key=\"synopsis\")"+ "synopsis_prompt_template = PromptTemplate(\n",+ " input_variables=[\"title\", \"era\"], template=synopsis_template\n",+ ")\n",+ "synopsis_chain = LLMChain(\n",+ " llm=llm, prompt=synopsis_prompt_template, output_key=\"synopsis\"\n",+ ")"]},{@@ -296,7 +307,7 @@],"source": ["# This is an LLMChain to write a review of a play given a synopsis.\n",- "llm = OpenAI(temperature=.7)\n",+ "llm = OpenAI(temperature=0.7)\n","template = \"\"\"You are a play critic from the New York Times. Given the synopsis of play, it is your job to write a review for that play.\n","\n","Play Synopsis:\n",@@ -307,15 +318,17 @@"\n","# This is the overall chain where we run these two chains in sequence.\n","from langchain.chains import SequentialChain\n",+ "\n","overall_chain = SequentialChain(\n"," chains=[synopsis_chain, review_chain],\n"," input_variables=[\"era\", \"title\"],\n"," # Here we return multiple variables\n"," output_variables=[\"synopsis\", \"review\"],\n",- " verbose=True)\n",+ " verbose=True,\n",+ ")\n","\n","\n",- "overall_chain({\"title\":\"Tragedy at sunset on the beach\", \"era\": \"Victorian England\"})"+ "overall_chain({\"title\": \"Tragedy at sunset on the beach\", \"era\": \"Victorian England\"})"]},{@@ -365,7 +378,7 @@"from langchain.chains import SequentialChain\n","from langchain.memory import SimpleMemory\n","\n",- "llm = OpenAI(temperature=.7)\n",+ "llm = OpenAI(temperature=0.7)\n","template = \"\"\"You are a social media manager for a theater company. Given the title of play, the era it is set in, the date,time and location, the synopsis of the play, and the review of the play, it is your job to write a social media post for that play.\n","\n","Here is some context about the time and location of the play:\n",@@ -379,18 +392,23 @@"\n","Social Media Post:\n","\"\"\"\n",- "prompt_template = PromptTemplate(input_variables=[\"synopsis\", \"review\", \"time\", \"location\"], template=template)\n",+ "prompt_template = PromptTemplate(\n",+ " input_variables=[\"synopsis\", \"review\", \"time\", \"location\"], template=template\n",+ ")\n","social_chain = LLMChain(llm=llm, prompt=prompt_template, output_key=\"social_post_text\")\n","\n","overall_chain = SequentialChain(\n",- " memory=SimpleMemory(memories={\"time\": \"December 25th, 8pm PST\", \"location\": \"Theater in the Park\"}),\n",+ " memory=SimpleMemory(\n",+ " memories={\"time\": \"December 25th, 8pm PST\", \"location\": \"Theater in the Park\"}\n",+ " ),\n"," chains=[synopsis_chain, review_chain, social_chain],\n"," input_variables=[\"era\", \"title\"],\n"," # Here we return multiple variables\n"," output_variables=[\"social_post_text\"],\n",- " verbose=True)\n",+ " verbose=True,\n",+ ")\n","\n",- "overall_chain({\"title\":\"Tragedy at sunset on the beach\", \"era\": \"Victorian England\"})"+ "overall_chain({\"title\": \"Tragedy at sunset on the beach\", \"era\": \"Victorian England\"})"]}],diff --git a/docs/docs/modules/chains/foundational/transformation.ipynb b/docs/docs/modules/chains/foundational/transformation.ipynbindex 2ef01a92c4..4335c86915 100644--- a/docs/docs/modules/chains/foundational/transformation.ipynb+++ b/docs/docs/modules/chains/foundational/transformation.ipynb@@ -72,7 +72,12 @@"from langchain.chat_models import ChatOpenAI\n","from langchain.schema import StrOutputParser\n","\n",- "runnable = {\"output_text\": lambda text: \"\\n\\n\".join(text.split(\"\\n\\n\")[:3])} | prompt | ChatOpenAI() | StrOutputParser()\n",+ "runnable = (\n",+ " {\"output_text\": lambda text: \"\\n\\n\".join(text.split(\"\\n\\n\")[:3])}\n",+ " | prompt\n",+ " | ChatOpenAI()\n",+ " | StrOutputParser()\n",+ ")\n","runnable.invoke(state_of_the_union)"]},@@ -96,7 +101,7 @@"outputs": [],"source": ["from langchain.chains import TransformChain, LLMChain, SimpleSequentialChain\n",- "from langchain.llms import OpenAI\n"+ "from langchain.llms import OpenAI"]},{@@ -111,6 +116,7 @@" shortened_text = \"\\n\\n\".join(text.split(\"\\n\\n\")[:3])\n"," return {\"output_text\": shortened_text}\n","\n",+ "\n","transform_chain = TransformChain(\n"," input_variables=[\"text\"], output_variables=[\"output_text\"], transform=transform_func\n",")"diff --git a/docs/docs/modules/chains/how_to/openai_functions.ipynb b/docs/docs/modules/chains/how_to/openai_functions.ipynbindex 675457ec41..f0c8ccd6f6 100644--- a/docs/docs/modules/chains/how_to/openai_functions.ipynb+++ b/docs/docs/modules/chains/how_to/openai_functions.ipynb@@ -89,8 +89,14 @@"llm = ChatOpenAI(model=\"gpt-4\", temperature=0)\n","prompt = ChatPromptTemplate.from_messages(\n"," [\n",- " (\"system\", \"You are a world class algorithm for extracting information in structured formats.\"),\n",- " (\"human\", \"Use the given format to extract information from the following input: {input}\"),\n",+ " (\n",+ " \"system\",\n",+ " \"You are a world class algorithm for extracting information in structured formats.\",\n",+ " ),\n",+ " (\n",+ " \"human\",\n",+ " \"Use the given format to extract information from the following input: {input}\",\n",+ " ),\n"," (\"human\", \"Tip: Make sure to answer in the correct format\"),\n"," ]\n",")\n",@@ -136,7 +142,9 @@"\n","runnable = create_structured_output_runnable(People, llm, prompt)\n","runnable.invoke(\n",- " {\"input\": \"Sally is 13, Joey just turned 12 and loves spinach. Caroline is 10 years older than Sally.\"}\n",+ " {\n",+ " \"input\": \"Sally is 13, Joey just turned 12 and loves spinach. Caroline is 10 years older than Sally.\"\n",+ " }\n",")"]},@@ -293,12 +301,18 @@"metadata": {},"outputs": [],"source": [- "from langchain.chains.openai_functions import convert_to_openai_function, get_openai_output_parser\n",+ "from langchain.chains.openai_functions import (\n",+ " convert_to_openai_function,\n",+ " get_openai_output_parser,\n",+ ")\n","\n","prompt = ChatPromptTemplate.from_messages(\n"," [\n"," (\"system\", \"You are a world class algorithm for recording entities.\"),\n",- " (\"human\", \"Make calls to the relevant function to record the entities in the following input: {input}\"),\n",+ " (\n",+ " \"human\",\n",+ " \"Make calls to the relevant function to record the entities in the following input: {input}\",\n",+ " ),\n"," (\"human\", \"Tip: Make sure to answer in the correct format\"),\n"," ]\n",")\n",@@ -308,7 +322,7 @@"if len(openai_functions) == 1:\n"," llm_kwargs[\"function_call\"] = {\"name\": openai_functions[0][\"name\"]}\n","output_parser = get_openai_output_parser((RecordPerson, RecordDog))\n",- "runnable = prompt | llm.bind(**llm_kwargs) | output_parser\n"+ "runnable = prompt | llm.bind(**llm_kwargs) | output_parser"]},{@@ -413,7 +427,9 @@"\n","runnable = create_openai_fn_runnable([record_person], llm, prompt)\n","runnable.invoke(\n",- " {\"input\": \"The most important thing to remember about Tommy, my 12 year old, is that he'll do anything for apple pie.\"}\n",+ " {\n",+ " \"input\": \"The most important thing to remember about Tommy, my 12 year old, is that he'll do anything for apple pie.\"\n",+ " }\n",")"]},@@ -460,7 +476,9 @@"\n","runnable = create_openai_fn_runnable([record_person, record_dog], llm, prompt)\n","runnable.invoke(\n",- " {\"input\": \"I can't find my dog Henry anywhere, he's a small brown beagle. Could you send a message about him?\"}\n",+ " {\n",+ " \"input\": \"I can't find my dog Henry anywhere, he's a small brown beagle. Could you send a message about him?\"\n",+ " }\n",")"]},diff --git a/docs/docs/modules/chains/index.ipynb b/docs/docs/modules/chains/index.ipynbindex d80fb87b72..52b4ad10c8 100644--- a/docs/docs/modules/chains/index.ipynb+++ b/docs/docs/modules/chains/index.ipynb@@ -53,10 +53,15 @@"from langchain.schema import StrOutputParser\n","\n","model = ChatAnthropic()\n",- "prompt = ChatPromptTemplate.from_messages([\n",- " (\"system\", \"You're a very knowledgeable historian who provides accurate and eloquent answers to historical questions.\"),\n",- " (\"human\", \"{question}\"),\n",- "])\n",+ "prompt = ChatPromptTemplate.from_messages(\n",+ " [\n",+ " (\n",+ " \"system\",\n",+ " \"You're a very knowledgeable historian who provides accurate and eloquent answers to historical questions.\",\n",+ " ),\n",+ " (\"human\", \"{question}\"),\n",+ " ]\n",+ ")\n","runnable = prompt | model | StrOutputParser()"]},diff --git a/docs/docs/modules/data_connection/document_transformers/text_splitters/HTML_header_metadata.ipynb b/docs/docs/modules/data_connection/document_transformers/text_splitters/HTML_header_metadata.ipynbindex f192dcc229..806ee87fa9 100644--- a/docs/docs/modules/data_connection/document_transformers/text_splitters/HTML_header_metadata.ipynb+++ b/docs/docs/modules/data_connection/document_transformers/text_splitters/HTML_header_metadata.ipynb@@ -54,7 +54,7 @@"source": ["from langchain.text_splitter import HTMLHeaderTextSplitter\n","\n",- "html_string =\"\"\"\n",+ "html_string = \"\"\"\n","<!DOCTYPE html>\n","<html>\n","<body>\n",@@ -148,7 +148,7 @@"\n","html_splitter = HTMLHeaderTextSplitter(headers_to_split_on=headers_to_split_on)\n","\n",- "#for local file use html_splitter.split_text_from_file(<path_to_file>)\n",+ "# for local file use html_splitter.split_text_from_file(<path_to_file>)\n","html_header_splits = html_splitter.split_text_from_url(url)\n","\n","chunk_size = 500\n",diff --git a/docs/docs/modules/data_connection/indexing.ipynb b/docs/docs/modules/data_connection/indexing.ipynbindex a015358949..056d23ff06 100644--- a/docs/docs/modules/data_connection/indexing.ipynb+++ b/docs/docs/modules/data_connection/indexing.ipynb@@ -277,9 +277,7 @@}],"source": [- "index(\n",- " [doc1, doc2], record_manager, vectorstore, cleanup=None, source_id_key=\"source\"\n",- ")"+ "index([doc1, doc2], record_manager, vectorstore, cleanup=None, source_id_key=\"source\")"]},{@@ -308,9 +306,7 @@}],"source": [- "index(\n",- " [doc1, doc2], record_manager, vectorstore, cleanup=None, source_id_key=\"source\"\n",- ")"+ "index([doc1, doc2], record_manager, vectorstore, cleanup=None, source_id_key=\"source\")"]},{@@ -419,9 +415,7 @@}],"source": [- "index(\n",- " [], record_manager, vectorstore, cleanup=\"incremental\", source_id_key=\"source\"\n",- ")"+ "index([], record_manager, vectorstore, cleanup=\"incremental\", source_id_key=\"source\")"]},{diff --git a/docs/docs/modules/data_connection/retrievers/ensemble.ipynb b/docs/docs/modules/data_connection/retrievers/ensemble.ipynbindex 24417ea3c8..f17250709e 100644--- a/docs/docs/modules/data_connection/retrievers/ensemble.ipynb+++ b/docs/docs/modules/data_connection/retrievers/ensemble.ipynb@@ -44,7 +44,9 @@"faiss_retriever = faiss_vectorstore.as_retriever(search_kwargs={\"k\": 2})\n","\n","# initialize the ensemble retriever\n",- "ensemble_retriever = EnsembleRetriever(retrievers=[bm25_retriever, faiss_retriever], weights=[0.5, 0.5])"+ "ensemble_retriever = EnsembleRetriever(\n",+ " retrievers=[bm25_retriever, faiss_retriever], weights=[0.5, 0.5]\n",+ ")"]},{diff --git a/docs/docs/modules/data_connection/retrievers/index.ipynb b/docs/docs/modules/data_connection/retrievers/index.ipynbindex 49ec807954..fc626e134e 100644--- a/docs/docs/modules/data_connection/retrievers/index.ipynb+++ b/docs/docs/modules/data_connection/retrievers/index.ipynb@@ -91,7 +91,9 @@}],"source": [- "retrieved_docs = retriever.invoke(\"What did the president say about Ketanji Brown Jackson?\")\n",+ "retrieved_docs = retriever.invoke(\n",+ " \"What did the president say about Ketanji Brown Jackson?\"\n",+ ")\n","print(retrieved_docs[0].page_content)"]},@@ -127,9 +129,11 @@"prompt = ChatPromptTemplate.from_template(template)\n","model = ChatOpenAI()\n","\n",+ "\n","def format_docs(docs):\n"," return \"\\n\\n\".join([d.page_content for d in docs])\n","\n",+ "\n","chain = (\n"," {\"context\": retriever | format_docs, \"question\": RunnablePassthrough()}\n"," | prompt\n",diff --git a/docs/docs/modules/data_connection/retrievers/multi_vector.ipynb b/docs/docs/modules/data_connection/retrievers/multi_vector.ipynbindex 3097d63767..3433ea2997 100644--- a/docs/docs/modules/data_connection/retrievers/multi_vector.ipynb+++ b/docs/docs/modules/data_connection/retrievers/multi_vector.ipynb@@ -51,8 +51,8 @@"outputs": [],"source": ["loaders = [\n",- " TextLoader('../../paul_graham_essay.txt'),\n",- " TextLoader('../../state_of_the_union.txt'),\n",+ " TextLoader(\"../../paul_graham_essay.txt\"),\n",+ " TextLoader(\"../../state_of_the_union.txt\"),\n","]\n","docs = []\n","for l in loaders:\n",@@ -80,19 +80,19 @@"source": ["# The vectorstore to use to index the child chunks\n","vectorstore = Chroma(\n",- " collection_name=\"full_documents\",\n",- " embedding_function=OpenAIEmbeddings()\n",+ " collection_name=\"full_documents\", embedding_function=OpenAIEmbeddings()\n",")\n","# The storage layer for the parent documents\n","store = InMemoryStore()\n","id_key = \"doc_id\"\n","# The retriever (empty to start)\n","retriever = MultiVectorRetriever(\n",- " vectorstore=vectorstore, \n",- " docstore=store, \n",+ " vectorstore=vectorstore,\n",+ " docstore=store,\n"," id_key=id_key,\n",")\n","import uuid\n",+ "\n","doc_ids = [str(uuid.uuid4()) for _ in docs]"]},@@ -235,17 +235,14 @@"outputs": [],"source": ["# The vectorstore to use to index the child chunks\n",- "vectorstore = Chroma(\n",- " collection_name=\"summaries\",\n",- " embedding_function=OpenAIEmbeddings()\n",- ")\n",+ "vectorstore = Chroma(collection_name=\"summaries\", embedding_function=OpenAIEmbeddings())\n","# The storage layer for the parent documents\n","store = InMemoryStore()\n","id_key = \"doc_id\"\n","# The retriever (empty to start)\n","retriever = MultiVectorRetriever(\n",- " vectorstore=vectorstore, \n",- " docstore=store, \n",+ " vectorstore=vectorstore,\n",+ " docstore=store,\n"," id_key=id_key,\n",")\n","doc_ids = [str(uuid.uuid4()) for _ in docs]"@@ -258,7 +255,10 @@"metadata": {},"outputs": [],"source": [- "summary_docs = [Document(page_content=s,metadata={id_key: doc_ids[i]}) for i, s in enumerate(summaries)]"+ "summary_docs = [\n",+ " Document(page_content=s, metadata={id_key: doc_ids[i]})\n",+ " for i, s in enumerate(summaries)\n",+ "]"]},{@@ -366,22 +366,20 @@"source": ["functions = [\n"," {\n",- " \"name\": \"hypothetical_questions\",\n",- " \"description\": \"Generate hypothetical questions\",\n",- " \"parameters\": {\n",- " \"type\": \"object\",\n",- " \"properties\": {\n",- " \"questions\": {\n",- " \"type\": \"array\",\n",- " \"items\": {\n",- " \"type\": \"string\"\n",- " },\n",- " },\n",+ " \"name\": \"hypothetical_questions\",\n",+ " \"description\": \"Generate hypothetical questions\",\n",+ " \"parameters\": {\n",+ " \"type\": \"object\",\n",+ " \"properties\": {\n",+ " \"questions\": {\n",+ " \"type\": \"array\",\n",+ " \"items\": {\"type\": \"string\"},\n",+ " },\n",+ " },\n",+ " \"required\": [\"questions\"],\n"," },\n",- " \"required\": [\"questions\"]\n",- " }\n"," }\n",- " ]"+ "]"]},{@@ -392,11 +390,16 @@"outputs": [],"source": ["from langchain.output_parsers.openai_functions import JsonKeyOutputFunctionsParser\n",+ "\n","chain = (\n"," {\"doc\": lambda x: x.page_content}\n"," # Only asking for 3 hypothetical questions, but this could be adjusted\n",- " | ChatPromptTemplate.from_template(\"Generate a list of 3 hypothetical questions that the below document could be used to answer:\\n\\n{doc}\")\n",- " | ChatOpenAI(max_retries=0, model=\"gpt-4\").bind(functions=functions, function_call={\"name\": \"hypothetical_questions\"})\n",+ " | ChatPromptTemplate.from_template(\n",+ " \"Generate a list of 3 hypothetical questions that the below document could be used to answer:\\n\\n{doc}\"\n",+ " )\n",+ " | ChatOpenAI(max_retries=0, model=\"gpt-4\").bind(\n",+ " functions=functions, function_call={\"name\": \"hypothetical_questions\"}\n",+ " )\n"," | JsonKeyOutputFunctionsParser(key_name=\"questions\")\n",")"]@@ -443,16 +446,15 @@"source": ["# The vectorstore to use to index the child chunks\n","vectorstore = Chroma(\n",- " collection_name=\"hypo-questions\",\n",- " embedding_function=OpenAIEmbeddings()\n",+ " collection_name=\"hypo-questions\", embedding_function=OpenAIEmbeddings()\n",")\n","# The storage layer for the parent documents\n","store = InMemoryStore()\n","id_key = \"doc_id\"\n","# The retriever (empty to start)\n","retriever = MultiVectorRetriever(\n",- " vectorstore=vectorstore, \n",- " docstore=store, \n",+ " vectorstore=vectorstore,\n",+ " docstore=store,\n"," id_key=id_key,\n",")\n","doc_ids = [str(uuid.uuid4()) for _ in docs]"@@ -467,7 +469,9 @@"source": ["question_docs = []\n","for i, question_list in enumerate(hypothetical_questions):\n",- " question_docs.extend([Document(page_content=s,metadata={id_key: doc_ids[i]}) for s in question_list])"+ " question_docs.extend(\n",+ " [Document(page_content=s, metadata={id_key: doc_ids[i]}) for s in question_list]\n",+ " )"]},{diff --git a/docs/docs/modules/data_connection/retrievers/parent_document_retriever.ipynb b/docs/docs/modules/data_connection/retrievers/parent_document_retriever.ipynbindex db710610a1..519c3eb9fe 100644--- a/docs/docs/modules/data_connection/retrievers/parent_document_retriever.ipynb+++ b/docs/docs/modules/data_connection/retrievers/parent_document_retriever.ipynb@@ -57,8 +57,8 @@"outputs": [],"source": ["loaders = [\n",- " TextLoader('../../paul_graham_essay.txt'),\n",- " TextLoader('../../state_of_the_union.txt'),\n",+ " TextLoader(\"../../paul_graham_essay.txt\"),\n",+ " TextLoader(\"../../state_of_the_union.txt\"),\n","]\n","docs = []\n","for l in loaders:\n",@@ -86,14 +86,13 @@"child_splitter = RecursiveCharacterTextSplitter(chunk_size=400)\n","# The vectorstore to use to index the child chunks\n","vectorstore = Chroma(\n",- " collection_name=\"full_documents\",\n",- " embedding_function=OpenAIEmbeddings()\n",+ " collection_name=\"full_documents\", embedding_function=OpenAIEmbeddings()\n",")\n","# The storage layer for the parent documents\n","store = InMemoryStore()\n","retriever = ParentDocumentRetriever(\n",- " vectorstore=vectorstore, \n",- " docstore=store, \n",+ " vectorstore=vectorstore,\n",+ " docstore=store,\n"," child_splitter=child_splitter,\n",")"]@@ -238,7 +237,9 @@"# It should create documents smaller than the parent\n","child_splitter = RecursiveCharacterTextSplitter(chunk_size=400)\n","# The vectorstore to use to index the child chunks\n",- "vectorstore = Chroma(collection_name=\"split_parents\", embedding_function=OpenAIEmbeddings())\n",+ "vectorstore = Chroma(\n",+ " collection_name=\"split_parents\", embedding_function=OpenAIEmbeddings()\n",+ ")\n","# The storage layer for the parent documents\n","store = InMemoryStore()"]@@ -251,8 +252,8 @@"outputs": [],"source": ["retriever = ParentDocumentRetriever(\n",- " vectorstore=vectorstore, \n",- " docstore=store, \n",+ " vectorstore=vectorstore,\n",+ " docstore=store,\n"," child_splitter=child_splitter,\n"," parent_splitter=parent_splitter,\n",")"diff --git a/docs/docs/modules/data_connection/retrievers/self_query.ipynb b/docs/docs/modules/data_connection/retrievers/self_query.ipynbindex 16804081e3..c043a4eced 100644--- a/docs/docs/modules/data_connection/retrievers/self_query.ipynb+++ b/docs/docs/modules/data_connection/retrievers/self_query.ipynb@@ -45,29 +45,35 @@"\n","docs = [\n"," Document(\n",- " page_content=\"A bunch of scientists bring back dinosaurs and mayhem breaks loose\", \n",- " metadata={\"year\": 1993, \"rating\": 7.7, \"genre\": \"science fiction\"})\n",- " ,\n",+ " page_content=\"A bunch of scientists bring back dinosaurs and mayhem breaks loose\",\n",+ " metadata={\"year\": 1993, \"rating\": 7.7, \"genre\": \"science fiction\"},\n",+ " ),\n"," Document(\n",- " page_content=\"Leo DiCaprio gets lost in a dream within a dream within a dream within a ...\", \n",- " metadata={\"year\": 2010, \"director\": \"Christopher Nolan\", \"rating\": 8.2}\n",+ " page_content=\"Leo DiCaprio gets lost in a dream within a dream within a dream within a ...\",\n",+ " metadata={\"year\": 2010, \"director\": \"Christopher Nolan\", \"rating\": 8.2},\n"," ),\n"," Document(\n",- " page_content=\"A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea\", \n",- " metadata={\"year\": 2006, \"director\": \"Satoshi Kon\", \"rating\": 8.6}\n",+ " page_content=\"A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea\",\n",+ " metadata={\"year\": 2006, \"director\": \"Satoshi Kon\", \"rating\": 8.6},\n"," ),\n"," Document(\n",- " page_content=\"A bunch of normal-sized women are supremely wholesome and some men pine after them\", \n",- " metadata={\"year\": 2019, \"director\": \"Greta Gerwig\", \"rating\": 8.3}\n",+ " page_content=\"A bunch of normal-sized women are supremely wholesome and some men pine after them\",\n",+ " metadata={\"year\": 2019, \"director\": \"Greta Gerwig\", \"rating\": 8.3},\n"," ),\n"," Document(\n",- " page_content=\"Toys come alive and have a blast doing so\", \n",- " metadata={\"year\": 1995, \"genre\": \"animated\"}\n",+ " page_content=\"Toys come alive and have a blast doing so\",\n",+ " metadata={\"year\": 1995, \"genre\": \"animated\"},\n"," ),\n"," Document(\n",- " page_content=\"Three men walk into the Zone, three men walk out of the Zone\", \n",- " metadata={\"year\": 1979, \"rating\": 9.9, \"director\": \"Andrei Tarkovsky\", \"genre\": \"thriller\", \"rating\": 9.9}\n",- " )\n",+ " page_content=\"Three men walk into the Zone, three men walk out of the Zone\",\n",+ " metadata={\n",+ " \"year\": 1979,\n",+ " \"rating\": 9.9,\n",+ " \"director\": \"Andrei Tarkovsky\",\n",+ " \"genre\": \"thriller\",\n",+ " \"rating\": 9.9,\n",+ " },\n",+ " ),\n","]\n","vectorstore = Chroma.from_documents(docs, OpenAIEmbeddings())"]@@ -94,7 +100,7 @@"from langchain.retrievers.self_query.base import SelfQueryRetriever\n","\n","\n",- "metadata_field_info=[\n",+ "metadata_field_info = [\n"," AttributeInfo(\n"," name=\"genre\",\n"," description=\"The genre of the movie. One of ['science fiction', 'comedy', 'drama', 'thriller', 'romance', 'action', 'animated']\",\n",@@ -111,18 +117,16 @@" type=\"string\",\n"," ),\n"," AttributeInfo(\n",- " name=\"rating\",\n",- " description=\"A 1-10 rating for the movie\",\n",- " type=\"float\"\n",+ " name=\"rating\", description=\"A 1-10 rating for the movie\", type=\"float\"\n"," ),\n","]\n","document_content_description = \"Brief summary of a movie\"\n","llm = ChatOpenAI(temperature=0)\n","retriever = SelfQueryRetriever.from_llm(\n",- " llm, \n",- " vectorstore, \n",- " document_content_description, \n",- " metadata_field_info, \n",+ " llm,\n",+ " vectorstore,\n",+ " document_content_description,\n",+ " metadata_field_info,\n",")"]},@@ -223,7 +227,9 @@],"source": ["# This example specifies a query and composite filter\n",- "retriever.invoke(\"What's a movie after 1990 but before 2005 that's all about toys, and preferably is animated\")"+ "retriever.invoke(\n",+ " \"What's a movie after 1990 but before 2005 that's all about toys, and preferably is animated\"\n",+ ")"]},{@@ -293,7 +299,10 @@" StructuredQueryOutputParser,\n",")\n","\n",- "prompt = get_query_constructor_prompt(document_content_description, metadata_field_info,)\n",+ "prompt = get_query_constructor_prompt(\n",+ " document_content_description,\n",+ " metadata_field_info,\n",+ ")\n","output_parser = StructuredQueryOutputParser.from_components()\n","query_constructor = prompt | llm | output_parser"]@@ -480,7 +489,11 @@}],"source": [- "query_constructor.invoke({\"query\": \"What are some sci-fi movies from the 90's directed by Luc Besson about taxi drivers\"})"+ "query_constructor.invoke(\n",+ " {\n",+ " \"query\": \"What are some sci-fi movies from the 90's directed by Luc Besson about taxi drivers\"\n",+ " }\n",+ ")"]},{@@ -503,8 +516,8 @@"from langchain.retrievers.self_query.chroma import ChromaTranslator\n","\n","retriever = SelfQueryRetriever(\n",- " query_constructor=query_constructor, \n",- " vectorstore=vectorstore, \n",+ " query_constructor=query_constructor,\n",+ " vectorstore=vectorstore,\n"," structured_query_translator=ChromaTranslator(),\n",")"]@@ -527,7 +540,9 @@}],"source": [- "retriever.invoke(\"What's a movie after 1990 but before 2005 that's all about toys, and preferably is animated\")"+ "retriever.invoke(\n",+ " \"What's a movie after 1990 but before 2005 that's all about toys, and preferably is animated\"\n",+ ")"]}],diff --git a/docs/docs/modules/data_connection/retrievers/web_research.ipynb b/docs/docs/modules/data_connection/retrievers/web_research.ipynbindex d016e8e4d4..192c3484f4 100644--- a/docs/docs/modules/data_connection/retrievers/web_research.ipynb+++ b/docs/docs/modules/data_connection/retrievers/web_research.ipynb@@ -49,12 +49,14 @@"from langchain.utilities import GoogleSearchAPIWrapper\n","\n","# Vectorstore\n",- "vectorstore = Chroma(embedding_function=OpenAIEmbeddings(),persist_directory=\"./chroma_db_oai\")\n",+ "vectorstore = Chroma(\n",+ " embedding_function=OpenAIEmbeddings(), persist_directory=\"./chroma_db_oai\"\n",+ ")\n","\n","# LLM\n","llm = ChatOpenAI(temperature=0)\n","\n",- "# Search \n",+ "# Search\n","os.environ[\"GOOGLE_CSE_ID\"] = \"xxx\"\n","os.environ[\"GOOGLE_API_KEY\"] = \"xxx\"\n","search = GoogleSearchAPIWrapper()"@@ -70,8 +72,8 @@"# Initialize\n","web_research_retriever = WebResearchRetriever.from_llm(\n"," vectorstore=vectorstore,\n",- " llm=llm, \n",- " search=search, \n",+ " llm=llm,\n",+ " search=search,\n",")"]},@@ -115,8 +117,11 @@],"source": ["from langchain.chains import RetrievalQAWithSourcesChain\n",+ "\n","user_input = \"How do LLM Powered Autonomous Agents work?\"\n",- "qa_chain = RetrievalQAWithSourcesChain.from_chain_type(llm,retriever=web_research_retriever)\n",+ "qa_chain = RetrievalQAWithSourcesChain.from_chain_type(\n",+ " llm, retriever=web_research_retriever\n",+ ")\n","result = qa_chain({\"question\": user_input})\n","result"]@@ -160,6 +165,7 @@"source": ["# Run\n","import logging\n",+ "\n","logging.basicConfig()\n","logging.getLogger(\"langchain.retrievers.web_research\").setLevel(logging.INFO)\n","user_input = \"What is Task Decomposition in LLM Powered Autonomous Agents?\"\n",@@ -195,9 +201,12 @@],"source": ["from langchain.chains.question_answering import load_qa_chain\n",+ "\n","chain = load_qa_chain(llm, chain_type=\"stuff\")\n",- "output = chain({\"input_documents\": docs, \"question\": user_input},return_only_outputs=True)\n",- "output['output_text']"+ "output = chain(\n",+ " {\"input_documents\": docs, \"question\": user_input}, return_only_outputs=True\n",+ ")\n",+ "output[\"output_text\"]"]},{@@ -234,11 +243,13 @@" should have a question mark at the end: {question}\"\"\",\n",")\n","\n",+ "\n","class LineList(BaseModel):\n"," \"\"\"List of questions.\"\"\"\n","\n"," lines: List[str] = Field(description=\"Questions\")\n","\n",+ "\n","class QuestionListOutputParser(PydanticOutputParser):\n"," \"\"\"Output parser for a list of numbered questions.\"\"\"\n","\n",@@ -248,12 +259,13 @@" def parse(self, text: str) -> LineList:\n"," lines = re.findall(r\"\\d+\\..*?\\n\", text)\n"," return LineList(lines=lines)\n",- " \n",+ "\n",+ "\n","llm_chain = LLMChain(\n",- " llm=llm,\n",- " prompt=search_prompt,\n",- " output_parser=QuestionListOutputParser(),\n",- " )"+ " llm=llm,\n",+ " prompt=search_prompt,\n",+ " output_parser=QuestionListOutputParser(),\n",+ ")"]},{@@ -290,8 +302,8 @@"# Initialize\n","web_research_retriever_llm_chain = WebResearchRetriever(\n"," vectorstore=vectorstore,\n",- " llm_chain=llm_chain, \n",- " search=search, \n",+ " llm_chain=llm_chain,\n",+ " search=search,\n",")\n","\n","# Run\n",@@ -439,7 +451,9 @@" verbose=True,\n",")\n","\n",- "vectorstore_llama = Chroma(embedding_function=GPT4AllEmbeddings(),persist_directory=\"./chroma_db_llama\")"+ "vectorstore_llama = Chroma(\n",+ " embedding_function=GPT4AllEmbeddings(), persist_directory=\"./chroma_db_llama\"\n",+ ")"]},{@@ -541,16 +555,19 @@],"source": ["from langchain.chains import RetrievalQAWithSourcesChain\n",+ "\n","# Initialize\n","web_research_retriever = WebResearchRetriever.from_llm(\n"," vectorstore=vectorstore_llama,\n",- " llm=llama, \n",- " search=search, \n",+ " llm=llama,\n",+ " search=search,\n",")\n","\n","# Run\n","user_input = \"What is Task Decomposition in LLM Powered Autonomous Agents?\"\n",- "qa_chain = RetrievalQAWithSourcesChain.from_chain_type(llama,retriever=web_research_retriever)\n",+ "qa_chain = RetrievalQAWithSourcesChain.from_chain_type(\n",+ " llama, retriever=web_research_retriever\n",+ ")\n","result = qa_chain({\"question\": user_input})\n","result"]diff --git a/docs/docs/modules/data_connection/text_embedding/caching_embeddings.ipynb b/docs/docs/modules/data_connection/text_embedding/caching_embeddings.ipynbindex c9bbb3fe6c..34498fd422 100644--- a/docs/docs/modules/data_connection/text_embedding/caching_embeddings.ipynb+++ b/docs/docs/modules/data_connection/text_embedding/caching_embeddings.ipynb@@ -30,7 +30,12 @@},"outputs": [],"source": [- "from langchain.storage import InMemoryStore, LocalFileStore, RedisStore, UpstashRedisStore\n",+ "from langchain.storage import (\n",+ " InMemoryStore,\n",+ " LocalFileStore,\n",+ " RedisStore,\n",+ " UpstashRedisStore,\n",+ ")\n","from langchain.embeddings import OpenAIEmbeddings, CacheBackedEmbeddings"]},@@ -470,6 +475,7 @@"outputs": [],"source": ["from upstash_redis import Redis\n",+ "\n","URL = \"<UPSTASH_REDIS_REST_URL>\"\n","TOKEN = \"<UPSTASH_REDIS_REST_TOKEN>\"\n","\n",@@ -552,7 +558,11 @@"source": ["# For cache isolation can use a separate DB\n","# Or additional namepace\n",- "store = RedisStore(redis_url=\"redis://localhost:6379\", client_kwargs={'db': 2}, namespace='embedding_caches')\n",+ "store = RedisStore(\n",+ " redis_url=\"redis://localhost:6379\",\n",+ " client_kwargs={\"db\": 2},\n",+ " namespace=\"embedding_caches\",\n",+ ")\n","\n","underlying_embeddings = OpenAIEmbeddings()\n","embedder = CacheBackedEmbeddings.from_bytes_store(\n",diff --git a/docs/docs/modules/memory/adding_memory.ipynb b/docs/docs/modules/memory/adding_memory.ipynbindex b341abc733..ee2fb83267 100644--- a/docs/docs/modules/memory/adding_memory.ipynb+++ b/docs/docs/modules/memory/adding_memory.ipynb@@ -9,7 +9,6 @@"source": ["# Memory in LLMChain\n","\n",-"This notebook goes over how to use the Memory class with an `LLMChain`. \n","\n","We will add the [ConversationBufferMemory](https://api.python.langchain.com/en/latest/memory/langchain.memory.buffer.ConversationBufferMemory.html#langchain.memory.buffer.ConversationBufferMemory) class, although this can be any memory class."@@ -179,7 +178,11 @@"source": ["from langchain.chat_models import ChatOpenAI\n","from langchain.schema import SystemMessage\n",- "from langchain.prompts import ChatPromptTemplate, HumanMessagePromptTemplate, MessagesPlaceholder"+ "from langchain.prompts import (\n",+ " ChatPromptTemplate,\n",+ " HumanMessagePromptTemplate,\n",+ " MessagesPlaceholder,\n",+ ")"]},{@@ -203,12 +206,20 @@},"outputs": [],"source": [- "prompt = ChatPromptTemplate.from_messages([\n",- " SystemMessage(content=\"You are a chatbot having a conversation with a human.\"), # The persistent system prompt\n",- " MessagesPlaceholder(variable_name=\"chat_history\"), # Where the memory will be stored.\n",- " HumanMessagePromptTemplate.from_template(\"{human_input}\"), # Where the human input will injected\n",- "])\n",- " \n",+ "prompt = ChatPromptTemplate.from_messages(\n",+ " [\n",+ " SystemMessage(\n",+ " content=\"You are a chatbot having a conversation with a human.\"\n",+ " ), # The persistent system prompt\n",+ " MessagesPlaceholder(\n",+ " variable_name=\"chat_history\"\n",+ " ), # Where the memory will be stored.\n",+ " HumanMessagePromptTemplate.from_template(\n",+ " \"{human_input}\"\n",+ " ), # Where the human input will injected\n",+ " ]\n",+ ")\n",+ "\n","memory = ConversationBufferMemory(memory_key=\"chat_history\", return_messages=True)"]},diff --git a/docs/docs/modules/model_io/models/chat/index.ipynb b/docs/docs/modules/model_io/models/chat/index.ipynbindex cc5ecd6dde..3a06074521 100644--- a/docs/docs/modules/model_io/models/chat/index.ipynb+++ b/docs/docs/modules/model_io/models/chat/index.ipynb@@ -107,8 +107,8 @@"from langchain.schema.messages import HumanMessage, SystemMessage\n","\n","messages = [\n",- " SystemMessage(content=\"You're a helpful assistant\"), \n",- " HumanMessage(content=\"What is the purpose of model regularization?\")\n",+ " SystemMessage(content=\"You're a helpful assistant\"),\n",+ " HumanMessage(content=\"What is the purpose of model regularization?\"),\n","]"]},@@ -619,13 +619,15 @@}],"source": [- "from langchain.schema import (\n",- " AIMessage,\n",- " HumanMessage,\n",- " SystemMessage\n",- ")\n",+ "from langchain.schema import AIMessage, HumanMessage, SystemMessage\n","\n",- "chat([HumanMessage(content=\"Translate this sentence from English to French: I love programming.\")])"+ "chat(\n",+ " [\n",+ " HumanMessage(\n",+ " content=\"Translate this sentence from English to French: I love programming.\"\n",+ " )\n",+ " ]\n",+ ")"]},{@@ -655,10 +657,12 @@],"source": ["messages = [\n",- " SystemMessage(content=\"You are a helpful assistant that translates English to French.\"),\n",- " HumanMessage(content=\"I love programming.\")\n",+ " SystemMessage(\n",+ " content=\"You are a helpful assistant that translates English to French.\"\n",+ " ),\n",+ " HumanMessage(content=\"I love programming.\"),\n","]\n",- "chat(messages)\n"+ "chat(messages)"]},{@@ -692,12 +696,16 @@"source": ["batch_messages = [\n"," [\n",- " SystemMessage(content=\"You are a helpful assistant that translates English to French.\"),\n",- " HumanMessage(content=\"I love programming.\")\n",+ " SystemMessage(\n",+ " content=\"You are a helpful assistant that translates English to French.\"\n",+ " ),\n",+ " HumanMessage(content=\"I love programming.\"),\n"," ],\n"," [\n",- " SystemMessage(content=\"You are a helpful assistant that translates English to French.\"),\n",- " HumanMessage(content=\"I love artificial intelligence.\")\n",+ " SystemMessage(\n",+ " content=\"You are a helpful assistant that translates English to French.\"\n",+ " ),\n",+ " HumanMessage(content=\"I love artificial intelligence.\"),\n"," ],\n","]\n","result = chat.generate(batch_messages)\n",diff --git a/docs/docs/modules/model_io/models/llms/index.ipynb b/docs/docs/modules/model_io/models/llms/index.ipynbindex 6a78ec7ac6..ed0fecc38b 100644--- a/docs/docs/modules/model_io/models/llms/index.ipynb+++ b/docs/docs/modules/model_io/models/llms/index.ipynb@@ -111,7 +111,9 @@}],"source": [- "llm.invoke(\"What are some theories about the relationship between unemployment and inflation?\")"+ "llm.invoke(\n",+ " \"What are some theories about the relationship between unemployment and inflation?\"\n",+ ")"]},{@@ -137,7 +139,9 @@}],"source": [- "for chunk in llm.stream(\"What are some theories about the relationship between unemployment and inflation?\"):\n",+ "for chunk in llm.stream(\n",+ " \"What are some theories about the relationship between unemployment and inflation?\"\n",+ "):\n"," print(chunk, end=\"\", flush=True)"]},@@ -159,7 +163,11 @@}],"source": [- "llm.batch([\"What are some theories about the relationship between unemployment and inflation?\"])"+ "llm.batch(\n",+ " [\n",+ " \"What are some theories about the relationship between unemployment and inflation?\"\n",+ " ]\n",+ ")"]},{@@ -180,7 +188,9 @@}],"source": [- "await llm.ainvoke(\"What are some theories about the relationship between unemployment and inflation?\")"+ "await llm.ainvoke(\n",+ " \"What are some theories about the relationship between unemployment and inflation?\"\n",+ ")"]},{@@ -206,7 +216,9 @@}],"source": [- "async for chunk in llm.astream(\"What are some theories about the relationship between unemployment and inflation?\"):\n",+ "async for chunk in llm.astream(\n",+ " \"What are some theories about the relationship between unemployment and inflation?\"\n",+ "):\n"," print(chunk, end=\"\", flush=True)"]},@@ -228,7 +240,11 @@}],"source": [- "await llm.abatch([\"What are some theories about the relationship between unemployment and inflation?\"])"+ "await llm.abatch(\n",+ " [\n",+ " \"What are some theories about the relationship between unemployment and inflation?\"\n",+ " ]\n",+ ")"]},{@@ -433,7 +449,9 @@}],"source": [- "async for chunk in llm.astream_log(\"What are some theories about the relationship between unemployment and inflation?\"):\n",+ "async for chunk in llm.astream_log(\n",+ " \"What are some theories about the relationship between unemployment and inflation?\"\n",+ "):\n"," print(chunk)"]},@@ -495,7 +513,7 @@}],"source": [- "llm_result = llm.generate([\"Tell me a joke\", \"Tell me a poem\"]*15)\n",+ "llm_result = llm.generate([\"Tell me a joke\", \"Tell me a poem\"] * 15)\n","len(llm_result.generations)"]},diff --git a/docs/docs/modules/model_io/output_parsers/index.ipynb b/docs/docs/modules/model_io/output_parsers/index.ipynbindex 8e445eb08c..ed84793301 100644--- a/docs/docs/modules/model_io/output_parsers/index.ipynb+++ b/docs/docs/modules/model_io/output_parsers/index.ipynb@@ -58,7 +58,8 @@"from langchain.pydantic_v1 import BaseModel, Field, validator\n","\n","\n",- "model = OpenAI(model_name='text-davinci-003', temperature=0.0)\n",+ "model = OpenAI(model_name=\"text-davinci-003\", temperature=0.0)\n",+ "\n","\n","# Define your desired data structure.\n","class Joke(BaseModel):\n",@@ -66,19 +67,20 @@" punchline: str = Field(description=\"answer to resolve the joke\")\n","\n"," # You can add custom validation logic easily with Pydantic.\n",- " @validator('setup')\n",+ " @validator(\"setup\")\n"," def question_ends_with_question_mark(cls, field):\n",- " if field[-1] != '?':\n",+ " if field[-1] != \"?\":\n"," raise ValueError(\"Badly formed question!\")\n"," return field\n","\n",+ "\n","# Set up a parser + inject instructions into the prompt template.\n","parser = PydanticOutputParser(pydantic_object=Joke)\n","\n","prompt = PromptTemplate(\n"," template=\"Answer the user query.\\n{format_instructions}\\n{query}\\n\",\n"," input_variables=[\"query\"],\n",- " partial_variables={\"format_instructions\": parser.get_format_instructions()}\n",+ " partial_variables={\"format_instructions\": parser.get_format_instructions()},\n",")\n","\n","# And a query intended to prompt a language model to populate the data structure.\n",@@ -169,7 +171,9 @@"source": ["from langchain.output_parsers.json import SimpleJsonOutputParser\n","\n",- "json_prompt = PromptTemplate.from_template(\"Return a JSON object with an `answer` key that answers the following question: {question}\")\n",+ "json_prompt = PromptTemplate.from_template(\n",+ " \"Return a JSON object with an `answer` key that answers the following question: {question}\"\n",+ ")\n","json_parser = SimpleJsonOutputParser()\n","json_chain = json_prompt | model | json_parser"]diff --git a/docs/docs/modules/model_io/prompts/prompt_templates/connecting_to_a_feature_store.ipynb b/docs/docs/modules/model_io/prompts/prompt_templates/connecting_to_a_feature_store.ipynbindex 24610e16de..e4626a9d1d 100644--- a/docs/docs/modules/model_io/prompts/prompt_templates/connecting_to_a_feature_store.ipynb+++ b/docs/docs/modules/model_io/prompts/prompt_templates/connecting_to_a_feature_store.ipynb@@ -640,7 +640,8 @@"outputs": [],"source": ["import os\n",- "os.environ['AZURE_ML_CLI_PRIVATE_FEATURES_ENABLED'] = 'True'"+ "\n",+ "os.environ[\"AZURE_ML_CLI_PRIVATE_FEATURES_ENABLED\"] = \"True\""]},{@@ -655,11 +656,21 @@"from pydantic import Extra\n","from langchain.prompts import PromptTemplate, StringPromptTemplate\n","from azure.identity import AzureCliCredential\n",- "from azureml.featurestore import FeatureStoreClient, init_online_lookup, get_online_features\n",+ "from azureml.featurestore import (\n",+ " FeatureStoreClient,\n",+ " init_online_lookup,\n",+ " get_online_features,\n",+ ")\n","\n",- "class AzureMLFeatureStorePromptTemplate(StringPromptTemplate, extra=Extra.allow):\n","\n",- " def __init__(self, subscription_id: str, resource_group: str, feature_store_name: str, **kwargs):\n",+ "class AzureMLFeatureStorePromptTemplate(StringPromptTemplate, extra=Extra.allow):\n",+ " def __init__(\n",+ " self,\n",+ " subscription_id: str,\n",+ " resource_group: str,\n",+ " feature_store_name: str,\n",+ " **kwargs\n",+ " ):\n"," # this is an example template for proof of concept and can be changed to suit the developer needs\n"," template = \"\"\"\n"," {query}\n",@@ -670,8 +681,10 @@" payment rejects 1d per user = {payment_rejects_1d_per_user}\n"," ###\n"," \"\"\"\n",- " prompt_template=PromptTemplate.from_template(template)\n",- " super().__init__(prompt=prompt_template, input_variables=[\"account_id\", \"query\"])\n",+ " prompt_template = PromptTemplate.from_template(template)\n",+ " super().__init__(\n",+ " prompt=prompt_template, input_variables=[\"account_id\", \"query\"]\n",+ " )\n","\n"," # use AzureMLOnBehalfOfCredential() in spark context\n"," credential = AzureCliCredential()\n",@@ -680,27 +693,27 @@" credential=credential,\n"," subscription_id=subscription_id,\n"," resource_group_name=resource_group,\n",- " name=feature_store_name)\n",- " \n",+ " name=feature_store_name,\n",+ " )\n",+ "\n"," self._feature_set = self._fs_client.feature_sets.get(name=\"accounts\", version=1)\n","\n"," init_online_lookup(self._feature_set.features, credential, force=True)\n",- " \n","\n",- " def format(self, **kwargs) -> str: \n",+ " def format(self, **kwargs) -> str:\n"," if \"account_id\" not in kwargs:\n"," raise \"account_id needed to fetch details from feature store\"\n",- " account_id = kwargs.pop(\"account_id\") \n",+ " account_id = kwargs.pop(\"account_id\")\n","\n",- " query=\"\"\n",+ " query = \"\"\n"," if \"query\" in kwargs:\n"," query = kwargs.pop(\"query\")\n","\n"," # feature set is registered with accountID as entity index column.\n",- " obs = pandas.DataFrame({'accountID': [account_id]})\n",+ " obs = pandas.DataFrame({\"accountID\": [account_id]})\n","\n"," # get the feature details for the input entity from feature store.\n",- " df = get_online_features(self._feature_set.features, obs) \n",+ " df = get_online_features(self._feature_set.features, obs)\n","\n"," # populate prompt template output using the fetched feature values.\n"," kwargs[\"query\"] = query\n",@@ -709,7 +722,7 @@" kwargs[\"account_country\"] = df[\"accountCountry\"][0]\n"," kwargs[\"payment_rejects_1d_per_user\"] = df[\"numPaymentRejects1dPerUser\"][0]\n","\n",- " return self.prompt.format(**kwargs)\n"+ " return self.prompt.format(**kwargs)"]},{@@ -730,9 +743,8 @@"# Replace the place holders below with actual details of feature store that was created in previous steps\n","\n","prompt_template = AzureMLFeatureStorePromptTemplate(\n",- " subscription_id=\"\",\n",- " resource_group=\"\",\n",- " feature_store_name=\"\")"+ " subscription_id=\"\", resource_group=\"\", feature_store_name=\"\"\n",+ ")"]},{@@ -778,7 +790,7 @@"metadata": {},"outputs": [],"source": [- "os.environ[\"OPENAI_API_KEY\"]=\"\" # Fill the open ai key here\n",+ "os.environ[\"OPENAI_API_KEY\"] = \"\" # Fill the open ai key here\n","\n","from langchain.chat_models import ChatOpenAI\n","from langchain.chains import LLMChain\n",@@ -806,7 +818,10 @@"source": ["# NOTE: developer's can further fine tune AzureMLFeatureStorePromptTemplate\n","# for getting even more accurate results for the input query\n",- "chain.predict(account_id=\"A1829581630230790\", query =\"write a small thank you note within 20 words if account age > 10 using the account stats\")"+ "chain.predict(\n",+ " account_id=\"A1829581630230790\",\n",+ " query=\"write a small thank you note within 20 words if account age > 10 using the account stats\",\n",+ ")"]}],diff --git a/docs/docs/modules/model_io/prompts/prompt_templates/index.ipynb b/docs/docs/modules/model_io/prompts/prompt_templates/index.ipynbindex d2d0e1b82a..0cb5997b7b 100644--- a/docs/docs/modules/model_io/prompts/prompt_templates/index.ipynb+++ b/docs/docs/modules/model_io/prompts/prompt_templates/index.ipynb@@ -90,9 +90,7 @@"source": ["from langchain.prompts import PromptTemplate\n","\n",- "prompt_template = PromptTemplate.from_template(\n",- "\"Tell me a joke\"\n",- ")\n",+ "prompt_template = PromptTemplate.from_template(\"Tell me a joke\")\n","prompt_template.format()"]},@@ -131,7 +129,7 @@"\n","invalid_prompt = PromptTemplate(\n"," input_variables=[\"adjective\"],\n",- " template=\"Tell me a {adjective} joke about {content}.\"\n",+ " template=\"Tell me a {adjective} joke about {content}.\",\n",")"]},@@ -162,17 +160,16 @@"source": ["from langchain.prompts import ChatPromptTemplate\n","\n",- "chat_template = ChatPromptTemplate.from_messages([\n",- " (\"system\", \"You are a helpful AI bot. Your name is {name}.\"),\n",- " (\"human\", \"Hello, how are you doing?\"),\n",- " (\"ai\", \"I'm doing well, thanks!\"),\n",- " (\"human\", \"{user_input}\"),\n",- "])\n",+ "chat_template = ChatPromptTemplate.from_messages(\n",+ " [\n",+ " (\"system\", \"You are a helpful AI bot. Your name is {name}.\"),\n",+ " (\"human\", \"Hello, how are you doing?\"),\n",+ " (\"ai\", \"I'm doing well, thanks!\"),\n",+ " (\"human\", \"{user_input}\"),\n",+ " ]\n",+ ")\n","\n",- "messages = chat_template.format_messages(\n",- " name=\"Bob\",\n",- " user_input=\"What is your name?\"\n",- ")"+ "messages = chat_template.format_messages(name=\"Bob\", user_input=\"What is your name?\")"]},{@@ -221,7 +218,7 @@")\n","\n","llm = ChatOpenAI()\n",- "llm(chat_template.format_messages(text='i dont like eating tasty things.'))"+ "llm(chat_template.format_messages(text=\"i dont like eating tasty things.\"))"]},{@@ -315,7 +312,7 @@"metadata": {},"outputs": [],"source": [- "chat_val = chat_template.invoke({\"text\": 'i dont like eating tasty things.'})"+ "chat_val = chat_template.invoke({\"text\": \"i dont like eating tasty things.\"})"]},{diff --git a/docs/docs/modules/model_io/prompts/prompt_templates/prompts_pipelining.ipynb b/docs/docs/modules/model_io/prompts/prompt_templates/prompts_pipelining.ipynbindex c2233c4629..9276506999 100644--- a/docs/docs/modules/model_io/prompts/prompt_templates/prompts_pipelining.ipynb+++ b/docs/docs/modules/model_io/prompts/prompt_templates/prompts_pipelining.ipynb@@ -208,10 +208,7 @@"outputs": [],"source": ["new_prompt = (\n",- " prompt\n",- " + HumanMessage(content=\"hi\")\n",- " + AIMessage(content=\"what?\")\n",- " + \"{input}\"\n",+ " prompt + HumanMessage(content=\"hi\") + AIMessage(content=\"what?\") + \"{input}\"\n",")"]},diff --git a/docs/docs/use_cases/apis.ipynb b/docs/docs/use_cases/apis.ipynbindex 0072909e58..11e2e8e825 100644--- a/docs/docs/use_cases/apis.ipynb+++ b/docs/docs/use_cases/apis.ipynb@@ -141,7 +141,10 @@],"source": ["from langchain.chains.openai_functions.openapi import get_openapi_chain\n",- "chain = get_openapi_chain(\"https://www.klarna.com/us/shopping/public/openai/v0/api-docs/\")\n",+ "\n",+ "chain = get_openapi_chain(\n",+ " \"https://www.klarna.com/us/shopping/public/openai/v0/api-docs/\"\n",+ ")\n","chain(\"What are some options for a men's large blue button down shirt\")"]},@@ -234,9 +237,14 @@"from langchain.llms import OpenAI\n","from langchain.chains import APIChain\n","from langchain.chains.api import open_meteo_docs\n",+ "\n","llm = OpenAI(temperature=0)\n",- "chain = APIChain.from_llm_and_api_docs(llm, open_meteo_docs.OPEN_METEO_DOCS, verbose=True)\n",- "chain.run('What is the weather like right now in Munich, Germany in degrees Fahrenheit?')"+ "chain = APIChain.from_llm_and_api_docs(\n",+ " llm, open_meteo_docs.OPEN_METEO_DOCS, verbose=True\n",+ ")\n",+ "chain.run(\n",+ " \"What is the weather like right now in Munich, Germany in degrees Fahrenheit?\"\n",+ ")"]},{@@ -308,10 +316,14 @@"outputs": [],"source": ["import os\n",- "os.environ['TMDB_BEARER_TOKEN'] = \"\"\n",+ "\n",+ "os.environ[\"TMDB_BEARER_TOKEN\"] = \"\"\n","from langchain.chains.api import tmdb_docs\n",+ "\n","headers = {\"Authorization\": f\"Bearer {os.environ['TMDB_BEARER_TOKEN']}\"}\n",- "chain = APIChain.from_llm_and_api_docs(llm, tmdb_docs.TMDB_DOCS, headers=headers, verbose=True)\n",+ "chain = APIChain.from_llm_and_api_docs(\n",+ " llm, tmdb_docs.TMDB_DOCS, headers=headers, verbose=True\n",+ ")\n","chain.run(\"Search for 'Avatar'\")"]},@@ -326,12 +338,16 @@"from langchain.llms import OpenAI\n","from langchain.chains.api import podcast_docs\n","from langchain.chains import APIChain\n",- " \n",- "listen_api_key = 'xxx' # Get api key here: https://www.listennotes.com/api/pricing/\n",+ "\n",+ "listen_api_key = \"xxx\" # Get api key here: https://www.listennotes.com/api/pricing/\n","llm = OpenAI(temperature=0)\n","headers = {\"X-ListenAPI-Key\": listen_api_key}\n",- "chain = APIChain.from_llm_and_api_docs(llm, podcast_docs.PODCAST_DOCS, headers=headers, verbose=True)\n",- "chain.run(\"Search for 'silicon valley bank' podcast episodes, audio length is more than 30 minutes, return only 1 results\")"+ "chain = APIChain.from_llm_and_api_docs(\n",+ " llm, podcast_docs.PODCAST_DOCS, headers=headers, verbose=True\n",+ ")\n",+ "chain.run(\n",+ " \"Search for 'silicon valley bank' podcast episodes, audio length is more than 30 minutes, return only 1 results\"\n",+ ")"]},{diff --git a/docs/docs/use_cases/chatbots.ipynb b/docs/docs/use_cases/chatbots.ipynbindex 0af38db7e6..f2e268dc4e 100644--- a/docs/docs/use_cases/chatbots.ipynb+++ b/docs/docs/use_cases/chatbots.ipynb@@ -59,7 +59,7 @@"metadata": {},"outputs": [],"source": [- "!pip install langchain openai \n",+ "!pip install langchain openai\n","\n","# Set env var OPENAI_API_KEY or load from a .env file:\n","# import dotenv\n",@@ -94,15 +94,17 @@}],"source": [- "from langchain.schema import (\n",- " AIMessage,\n",- " HumanMessage,\n",- " SystemMessage\n",- ")\n",+ "from langchain.schema import AIMessage, HumanMessage, SystemMessage\n","from langchain.chat_models import ChatOpenAI\n","\n","chat = ChatOpenAI()\n",- "chat([HumanMessage(content=\"Translate this sentence from English to French: I love programming.\")])"+ "chat(\n",+ " [\n",+ " HumanMessage(\n",+ " content=\"Translate this sentence from English to French: I love programming.\"\n",+ " )\n",+ " ]\n",+ ")"]},{@@ -132,8 +134,10 @@],"source": ["messages = [\n",- " SystemMessage(content=\"You are a helpful assistant that translates English to French.\"),\n",- " HumanMessage(content=\"I love programming.\")\n",+ " SystemMessage(\n",+ " content=\"You are a helpful assistant that translates English to French.\"\n",+ " ),\n",+ " HumanMessage(content=\"I love programming.\"),\n","]\n","chat(messages)"]@@ -164,10 +168,10 @@}],"source": [- "from langchain.chains import ConversationChain \n",- " \n",- "conversation = ConversationChain(llm=chat) \n",- "conversation.run(\"Translate this sentence from English to French: I love programming.\") "+ "from langchain.chains import ConversationChain\n",+ "\n",+ "conversation = ConversationChain(llm=chat)\n",+ "conversation.run(\"Translate this sentence from English to French: I love programming.\")"]},{@@ -188,7 +192,7 @@}],"source": [- "conversation.run(\"Translate it to German.\") "+ "conversation.run(\"Translate it to German.\")"]},{@@ -310,9 +314,15 @@"\n","llm = OpenAI(temperature=0)\n","memory = ConversationSummaryMemory(llm=llm)\n",- "memory.save_context({\"input\": \"hi\"},{\"output\": \"whats up\"})\n",- "memory.save_context({\"input\": \"im working on better docs for chatbots\"},{\"output\": \"oh, that sounds like a lot of work\"})\n",- "memory.save_context({\"input\": \"yes, but it's worth the effort\"},{\"output\": \"agreed, good docs are important!\"})"+ "memory.save_context({\"input\": \"hi\"}, {\"output\": \"whats up\"})\n",+ "memory.save_context(\n",+ " {\"input\": \"im working on better docs for chatbots\"},\n",+ " {\"output\": \"oh, that sounds like a lot of work\"},\n",+ ")\n",+ "memory.save_context(\n",+ " {\"input\": \"yes, but it's worth the effort\"},\n",+ " {\"output\": \"agreed, good docs are important!\"},\n",+ ")"]},{@@ -354,6 +364,7 @@"outputs": [],"source": ["from langchain.memory import ConversationSummaryBufferMemory\n",+ "\n","memory = ConversationSummaryBufferMemory(llm=llm, max_token_limit=10)\n","memory.save_context({\"input\": \"hi\"}, {\"output\": \"whats up\"})\n","memory.save_context({\"input\": \"not much you\"}, {\"output\": \"not much\"})"@@ -417,7 +428,7 @@"# LLM\n","llm = ChatOpenAI()\n","\n",- "# Prompt \n",+ "# Prompt\n","prompt = ChatPromptTemplate(\n"," messages=[\n"," SystemMessagePromptTemplate.from_template(\n",@@ -425,19 +436,14 @@" ),\n"," # The `variable_name` here is what must align with memory\n"," MessagesPlaceholder(variable_name=\"chat_history\"),\n",- " HumanMessagePromptTemplate.from_template(\"{question}\")\n",+ " HumanMessagePromptTemplate.from_template(\"{question}\"),\n"," ]\n",")\n","\n","# Notice that we `return_messages=True` to fit into the MessagesPlaceholder\n","# Notice that `\"chat_history\"` aligns with the MessagesPlaceholder name\n",- "memory = ConversationBufferMemory(memory_key=\"chat_history\",return_messages=True)\n",- "conversation = LLMChain(\n",- " llm=llm,\n",- " prompt=prompt,\n",- " verbose=True,\n",- " memory=memory\n",- ")\n",+ "memory = ConversationBufferMemory(memory_key=\"chat_history\", return_messages=True)\n",+ "conversation = LLMChain(llm=llm, prompt=prompt, verbose=True, memory=memory)\n","\n","# Notice that we just pass in the `question` variables - `chat_history` gets populated by memory\n","conversation({\"question\": \"hi\"})"@@ -482,7 +488,9 @@}],"source": [- "conversation({\"question\": \"Translate this sentence from English to French: I love programming.\"})"+ "conversation(\n",+ " {\"question\": \"Translate this sentence from English to French: I love programming.\"}\n",+ ")"]},{@@ -627,7 +635,9 @@"metadata": {},"outputs": [],"source": [- "memory = ConversationSummaryMemory(llm=llm,memory_key=\"chat_history\",return_messages=True)"+ "memory = ConversationSummaryMemory(\n",+ " llm=llm, memory_key=\"chat_history\", return_messages=True\n",+ ")"]},{diff --git a/docs/docs/use_cases/data_generation.ipynb b/docs/docs/use_cases/data_generation.ipynbindex 9b543d1a03..7ffc49a550 100644--- a/docs/docs/use_cases/data_generation.ipynb+++ b/docs/docs/use_cases/data_generation.ipynb@@ -68,8 +68,14 @@"from langchain.chat_models import ChatOpenAI\n","from langchain.pydantic_v1 import BaseModel\n","from langchain_experimental.tabular_synthetic_data.base import SyntheticDataGenerator\n",- "from langchain_experimental.tabular_synthetic_data.openai import create_openai_data_generator, OPENAI_TEMPLATE\n",- "from langchain_experimental.tabular_synthetic_data.prompts import SYNTHETIC_FEW_SHOT_SUFFIX, SYNTHETIC_FEW_SHOT_PREFIX\n"+ "from langchain_experimental.tabular_synthetic_data.openai import (\n",+ " create_openai_data_generator,\n",+ " OPENAI_TEMPLATE,\n",+ ")\n",+ "from langchain_experimental.tabular_synthetic_data.prompts import (\n",+ " SYNTHETIC_FEW_SHOT_SUFFIX,\n",+ " SYNTHETIC_FEW_SHOT_PREFIX,\n",+ ")"]},{@@ -95,7 +101,7 @@" diagnosis_code: str\n"," procedure_code: str\n"," total_charge: float\n",- " insurance_claim_amount: float\n"+ " insurance_claim_amount: float"]},{@@ -120,13 +126,19 @@"outputs": [],"source": ["examples = [\n",- " {\"example\": \"\"\"Patient ID: 123456, Patient Name: John Doe, Diagnosis Code: \n",- " J20.9, Procedure Code: 99203, Total Charge: $500, Insurance Claim Amount: $350\"\"\"},\n",- " {\"example\": \"\"\"Patient ID: 789012, Patient Name: Johnson Smith, Diagnosis \n",- " Code: M54.5, Procedure Code: 99213, Total Charge: $150, Insurance Claim Amount: $120\"\"\"},\n",- " {\"example\": \"\"\"Patient ID: 345678, Patient Name: Emily Stone, Diagnosis Code: \n",- " E11.9, Procedure Code: 99214, Total Charge: $300, Insurance Claim Amount: $250\"\"\"},\n",- "]\n"+ " {\n",+ " \"example\": \"\"\"Patient ID: 123456, Patient Name: John Doe, Diagnosis Code: \n",+ " J20.9, Procedure Code: 99203, Total Charge: $500, Insurance Claim Amount: $350\"\"\"\n",+ " },\n",+ " {\n",+ " \"example\": \"\"\"Patient ID: 789012, Patient Name: Johnson Smith, Diagnosis \n",+ " Code: M54.5, Procedure Code: 99213, Total Charge: $150, Insurance Claim Amount: $120\"\"\"\n",+ " },\n",+ " {\n",+ " \"example\": \"\"\"Patient ID: 345678, Patient Name: Emily Stone, Diagnosis Code: \n",+ " E11.9, Procedure Code: 99214, Total Charge: $300, Insurance Claim Amount: $250\"\"\"\n",+ " },\n",+ "]"]},{@@ -154,7 +166,7 @@" suffix=SYNTHETIC_FEW_SHOT_SUFFIX,\n"," input_variables=[\"subject\", \"extra\"],\n"," example_prompt=OPENAI_TEMPLATE,\n",- ")\n"+ ")"]},{@@ -183,9 +195,11 @@"source": ["synthetic_data_generator = create_openai_data_generator(\n"," output_schema=MedicalBilling,\n",- " llm=ChatOpenAI(temperature=1), # You'll need to replace with your actual Language Model instance\n",+ " llm=ChatOpenAI(\n",+ " temperature=1\n",+ " ), # You'll need to replace with your actual Language Model instance\n"," prompt=prompt_template,\n",- ")\n"+ ")"]},{@@ -209,7 +223,7 @@" subject=\"medical_billing\",\n"," extra=\"the name must be chosen at random. Make it something you wouldn't normally choose.\",\n"," runs=10,\n",- ")\n"+ ")"]},{@@ -240,7 +254,10 @@"outputs": [],"source": ["from langchain.chat_models import ChatOpenAI\n",- "from langchain_experimental.synthetic_data import create_data_generation_chain, DatasetGenerator"+ "from langchain_experimental.synthetic_data import (\n",+ " create_data_generation_chain,\n",+ " DatasetGenerator,\n",+ ")"]},{@@ -300,7 +317,12 @@}],"source": [- "chain({\"fields\": {\"colors\": [\"blue\", \"yellow\"]}, \"preferences\": {\"style\": \"Make it in a style of a weather forecast.\"}})"+ "chain(\n",+ " {\n",+ " \"fields\": {\"colors\": [\"blue\", \"yellow\"]},\n",+ " \"preferences\": {\"style\": \"Make it in a style of a weather forecast.\"},\n",+ " }\n",+ ")"]},{@@ -323,7 +345,12 @@}],"source": [- "chain({\"fields\": {\"actor\": \"Tom Hanks\", \"movies\": [\"Forrest Gump\", \"Green Mile\"]}, \"preferences\": None})"+ "chain(\n",+ " {\n",+ " \"fields\": {\"actor\": \"Tom Hanks\", \"movies\": [\"Forrest Gump\", \"Green Mile\"]},\n",+ " \"preferences\": None,\n",+ " }\n",+ ")"]},{@@ -353,9 +380,9 @@" {\n"," \"fields\": [\n"," {\"actor\": \"Tom Hanks\", \"movies\": [\"Forrest Gump\", \"Green Mile\"]},\n",- " {\"actor\": \"Mads Mikkelsen\", \"movies\": [\"Hannibal\", \"Another round\"]}\n",+ " {\"actor\": \"Mads Mikkelsen\", \"movies\": [\"Hannibal\", \"Another round\"]},\n"," ],\n",- " \"preferences\": {\"minimum_length\": 200, \"style\": \"gossip\"}\n",+ " \"preferences\": {\"minimum_length\": 200, \"style\": \"gossip\"},\n"," }\n",")"]@@ -385,24 +412,25 @@"source": ["inp = [\n"," {\n",- " 'Actor': 'Tom Hanks',\n",- " 'Film': [\n",- " 'Forrest Gump',\n",- " 'Saving Private Ryan',\n",- " 'The Green Mile',\n",- " 'Toy Story',\n",- " 'Catch Me If You Can']\n",+ " \"Actor\": \"Tom Hanks\",\n",+ " \"Film\": [\n",+ " \"Forrest Gump\",\n",+ " \"Saving Private Ryan\",\n",+ " \"The Green Mile\",\n",+ " \"Toy Story\",\n",+ " \"Catch Me If You Can\",\n",+ " ],\n"," },\n"," {\n",- " 'Actor': 'Tom Hardy',\n",- " 'Film': [\n",- " 'Inception',\n",- " 'The Dark Knight Rises',\n",- " 'Mad Max: Fury Road',\n",- " 'The Revenant',\n",- " 'Dunkirk'\n",- " ]\n",- " }\n",+ " \"Actor\": \"Tom Hardy\",\n",+ " \"Film\": [\n",+ " \"Inception\",\n",+ " \"The Dark Knight Rises\",\n",+ " \"Mad Max: Fury Road\",\n",+ " \"The Revenant\",\n",+ " \"Dunkirk\",\n",+ " ],\n",+ " },\n","]\n","\n","generator = DatasetGenerator(model, {\"style\": \"informal\", \"minimal length\": 500})\n",diff --git a/docs/docs/use_cases/extraction.ipynb b/docs/docs/use_cases/extraction.ipynbindex 9e87e09f0a..143ce5c265 100644--- a/docs/docs/use_cases/extraction.ipynb+++ b/docs/docs/use_cases/extraction.ipynb@@ -117,7 +117,7 @@" \"required\": [\"name\", \"height\"],\n","}\n","\n",- "# Input \n",+ "# Input\n","inp = \"\"\"Alex is 5 feet tall. Claudia is 1 feet taller Alex and jumps higher than him. Claudia is a brunette and Alex is blonde.\"\"\"\n","\n","# Run chain\n",@@ -383,6 +383,7 @@"from langchain.pydantic_v1 import BaseModel\n","from langchain.chains import create_extraction_chain_pydantic\n","\n",+ "\n","# Pydantic data class\n","class Properties(BaseModel):\n"," person_name: str\n",@@ -390,11 +391,12 @@" person_hair_color: str\n"," dog_breed: Optional[str]\n"," dog_name: Optional[str]\n",- " \n",+ "\n",+ "\n","# Extraction\n","chain = create_extraction_chain_pydantic(pydantic_schema=Properties, llm=llm)\n","\n",- "# Run \n",+ "# Run\n","inp = \"\"\"Alex is 5 feet tall. Claudia is 1 feet taller Alex and jumps higher than him. Claudia is a brunette and Alex is blonde.\"\"\"\n","chain.run(inp)"]@@ -453,6 +455,7 @@"from pydantic import BaseModel, Field, validator\n","from langchain.output_parsers import PydanticOutputParser\n","\n",+ "\n","class Person(BaseModel):\n"," person_name: str\n"," person_height: int\n",@@ -460,12 +463,14 @@" dog_breed: Optional[str]\n"," dog_name: Optional[str]\n","\n",+ "\n","class People(BaseModel):\n"," \"\"\"Identifying information about all people in a text.\"\"\"\n",+ "\n"," people: Sequence[Person]\n","\n",- " \n",- "# Run \n",+ "\n",+ "# Run\n","query = \"\"\"Alex is 5 feet tall. Claudia is 1 feet taller Alex and jumps higher than him. Claudia is a brunette and Alex is blonde.\"\"\"\n","\n","# Set up a parser + inject instructions into the prompt template.\n",@@ -531,6 +536,7 @@"from pydantic import BaseModel, Field, validator\n","from langchain.output_parsers import PydanticOutputParser\n","\n",+ "\n","# Define your desired data structure.\n","class Joke(BaseModel):\n"," setup: str = Field(description=\"question to set up a joke\")\n",@@ -543,6 +549,7 @@" raise ValueError(\"Badly formed question!\")\n"," return field\n","\n",+ "\n","# And a query intended to prompt a language model to populate the data structure.\n","joke_query = \"Tell me a joke.\"\n","\n",diff --git a/docs/docs/use_cases/graph/diffbot_graphtransformer.ipynb b/docs/docs/use_cases/graph/diffbot_graphtransformer.ipynbindex 30144d0330..26023a8bbb 100644--- a/docs/docs/use_cases/graph/diffbot_graphtransformer.ipynb+++ b/docs/docs/use_cases/graph/diffbot_graphtransformer.ipynb@@ -125,15 +125,11 @@"source": ["from langchain.graphs import Neo4jGraph\n","\n",- "url=\"bolt://localhost:7687\"\n",- "username=\"neo4j\"\n",- "password=\"pleaseletmein\"\n",+ "url = \"bolt://localhost:7687\"\n",+ "username = \"neo4j\"\n",+ "password = \"pleaseletmein\"\n","\n",- "graph = Neo4jGraph(\n",- " url=url,\n",- " username=username, \n",- " password=password\n",- ")"+ "graph = Neo4jGraph(url=url, username=username, password=password)"]},{@@ -195,10 +191,9 @@"chain = GraphCypherQAChain.from_llm(\n"," cypher_llm=ChatOpenAI(temperature=0, model_name=\"gpt-4\"),\n"," qa_llm=ChatOpenAI(temperature=0, model_name=\"gpt-3.5-turbo\"),\n",- " graph=graph, verbose=True,\n",- " \n",- ")\n",- " "+ " graph=graph,\n",+ " verbose=True,\n",+ ")"]},{diff --git a/docs/docs/use_cases/graph/graph_cypher_qa.ipynb b/docs/docs/use_cases/graph/graph_cypher_qa.ipynbindex 2a49e7b033..b33e3d10d8 100644--- a/docs/docs/use_cases/graph/graph_cypher_qa.ipynb+++ b/docs/docs/use_cases/graph/graph_cypher_qa.ipynb@@ -417,7 +417,10 @@")\n","\n","chain = GraphCypherQAChain.from_llm(\n",- " ChatOpenAI(temperature=0), graph=graph, verbose=True, cypher_prompt=CYPHER_GENERATION_PROMPT\n",+ " ChatOpenAI(temperature=0),\n",+ " graph=graph,\n",+ " verbose=True,\n",+ " cypher_prompt=CYPHER_GENERATION_PROMPT,\n",")"]},@@ -475,10 +478,10 @@"outputs": [],"source": ["chain = GraphCypherQAChain.from_llm(\n",- " graph=graph,\n",- " cypher_llm=ChatOpenAI(temperature=0, model=\"gpt-3.5-turbo\"),\n",- " qa_llm=ChatOpenAI(temperature=0, model=\"gpt-3.5-turbo-16k\"),\n",- " verbose=True,\n",+ " graph=graph,\n",+ " cypher_llm=ChatOpenAI(temperature=0, model=\"gpt-3.5-turbo\"),\n",+ " qa_llm=ChatOpenAI(temperature=0, model=\"gpt-3.5-turbo-16k\"),\n",+ " verbose=True,\n",")"]},@@ -536,11 +539,11 @@"outputs": [],"source": ["chain = GraphCypherQAChain.from_llm(\n",- " graph=graph,\n",- " cypher_llm=ChatOpenAI(temperature=0, model=\"gpt-3.5-turbo\"),\n",- " qa_llm=ChatOpenAI(temperature=0, model=\"gpt-3.5-turbo-16k\"),\n",- " verbose=True,\n",- " exclude_types=['Movie']\n",+ " graph=graph,\n",+ " cypher_llm=ChatOpenAI(temperature=0, model=\"gpt-3.5-turbo\"),\n",+ " qa_llm=ChatOpenAI(temperature=0, model=\"gpt-3.5-turbo-16k\"),\n",+ " verbose=True,\n",+ " exclude_types=[\"Movie\"],\n",")"]},@@ -585,10 +588,10 @@"outputs": [],"source": ["chain = GraphCypherQAChain.from_llm(\n",- " llm=ChatOpenAI(temperature=0, model=\"gpt-3.5-turbo\"),\n",- " graph=graph,\n",- " verbose=True,\n",- " validate_cypher=True\n",+ " llm=ChatOpenAI(temperature=0, model=\"gpt-3.5-turbo\"),\n",+ " graph=graph,\n",+ " verbose=True,\n",+ " validate_cypher=True,\n",")"]},diff --git a/docs/docs/use_cases/graph/graph_falkordb_qa.ipynb b/docs/docs/use_cases/graph/graph_falkordb_qa.ipynbindex 9edb18785f..38be4c0bd2 100644--- a/docs/docs/use_cases/graph/graph_falkordb_qa.ipynb+++ b/docs/docs/use_cases/graph/graph_falkordb_qa.ipynb@@ -66,7 +66,8 @@}],"source": [- "graph.query(\"\"\"\n",+ "graph.query(\n",+ " \"\"\"\n"," CREATE \n"," (al:Person {name: 'Al Pacino', birthDate: '1940-04-25'}),\n"," (robert:Person {name: 'Robert De Niro', birthDate: '1943-08-17'}),\n",@@ -88,7 +89,8 @@" (val)-[:ACTED_IN]->(top),\n"," (anthony)-[:ACTED_IN]->(top),\n"," (meg)-[:ACTED_IN]->(top)\n",- "\"\"\")"+ "\"\"\"\n",+ ")"]},{@@ -119,7 +121,8 @@"print(graph.schema)\n","\n","import os\n",- "os.environ['OPENAI_API_KEY']='API_KEY_HERE'"+ "\n",+ "os.environ[\"OPENAI_API_KEY\"] = \"API_KEY_HERE\""]},{@@ -128,9 +131,7 @@"metadata": {},"outputs": [],"source": [- "chain = FalkorDBQAChain.from_llm(\n",- " ChatOpenAI(temperature=0), graph=graph, verbose=True\n",- ")"+ "chain = FalkorDBQAChain.from_llm(ChatOpenAI(temperature=0), graph=graph, verbose=True)"]},{diff --git a/docs/docs/use_cases/graph/graph_memgraph_qa.ipynb b/docs/docs/use_cases/graph/graph_memgraph_qa.ipynbindex 9044f95810..e896e8eea0 100644--- a/docs/docs/use_cases/graph/graph_memgraph_qa.ipynb+++ b/docs/docs/use_cases/graph/graph_memgraph_qa.ipynb@@ -89,7 +89,7 @@"metadata": {},"outputs": [],"source": [- "memgraph = Memgraph(host='127.0.0.1', port=7687)"+ "memgraph = Memgraph(host=\"127.0.0.1\", port=7687)"]},{@@ -253,7 +253,7 @@"outputs": [],"source": ["chain = GraphCypherQAChain.from_llm(\n",- " ChatOpenAI(temperature=0), graph=graph, verbose=True, model_name='gpt-3.5-turbo'\n",+ " ChatOpenAI(temperature=0), graph=graph, verbose=True, model_name=\"gpt-3.5-turbo\"\n",")"]},@@ -524,7 +524,7 @@"outputs": [],"source": ["chain = GraphCypherQAChain.from_llm(\n",- " ChatOpenAI(temperature=0), graph=graph, verbose=True, model_name='gpt-3.5-turbo'\n",+ " ChatOpenAI(temperature=0), graph=graph, verbose=True, model_name=\"gpt-3.5-turbo\"\n",")"]},@@ -617,11 +617,11 @@"outputs": [],"source": ["chain = GraphCypherQAChain.from_llm(\n",- " ChatOpenAI(temperature=0), \n",+ " ChatOpenAI(temperature=0),\n"," cypher_prompt=CYPHER_GENERATION_PROMPT,\n",- " graph=graph, \n",- " verbose=True, \n",- " model_name='gpt-3.5-turbo'\n",+ " graph=graph,\n",+ " verbose=True,\n",+ " model_name=\"gpt-3.5-turbo\",\n",")"]},diff --git a/docs/docs/use_cases/qa_structured/sql.ipynb b/docs/docs/use_cases/qa_structured/sql.ipynbindex ad1b0974dd..45ab7d9561 100644--- a/docs/docs/use_cases/qa_structured/sql.ipynb+++ b/docs/docs/use_cases/qa_structured/sql.ipynb@@ -186,7 +186,7 @@],"source": ["chain = create_sql_query_chain(ChatOpenAI(temperature=0), db)\n",- "response = chain.invoke({\"question\":\"How many employees are there\"})\n",+ "response = chain.invoke({\"question\": \"How many employees are there\"})\n","print(response)"]},@@ -282,7 +282,8 @@"Question: {input}\"\"\"\n","\n","CUSTOM_PROMPT = PromptTemplate(\n",- " input_variables=[\"input\", \"few_shot_examples\", \"table_info\", \"dialect\"], template=TEMPLATE\n",+ " input_variables=[\"input\", \"few_shot_examples\", \"table_info\", \"dialect\"],\n",+ " template=TEMPLATE,\n",")"]},@@ -302,6 +303,7 @@"outputs": [],"source": ["from langchain import hub\n",+ "\n","CUSTOM_PROMPT = hub.pull(\"rlm/text-to-sql\")"]},@@ -431,8 +433,11 @@"source": ["db = SQLDatabase.from_uri(\n"," \"sqlite:///Chinook.db\",\n",- " include_tables=['Track'], # we include only one table to save tokens in the prompt :)\n",- " sample_rows_in_table_info=2)"+ " include_tables=[\n",+ " \"Track\"\n",+ " ], # we include only one table to save tokens in the prompt :)\n",+ " sample_rows_in_table_info=2,\n",+ ")"]},{@@ -514,6 +519,7 @@"source": ["from langchain.agents import create_sql_agent\n","from langchain.agents.agent_toolkits import SQLDatabaseToolkit\n",+ "\n","# from langchain.agents import AgentExecutor\n","from langchain.agents.agent_types import AgentType\n","\n",@@ -782,7 +788,10 @@"\n","embeddings = OpenAIEmbeddings()\n","\n",- "few_shot_docs = [Document(page_content=question, metadata={'sql_query': few_shots[question]}) for question in few_shots.keys()]\n",+ "few_shot_docs = [\n",+ " Document(page_content=question, metadata={\"sql_query\": few_shots[question]})\n",+ " for question in few_shots.keys()\n",+ "]\n","vector_db = FAISS.from_documents(few_shot_docs, embeddings)\n","retriever = vector_db.as_retriever()"]@@ -808,10 +817,8 @@"\"\"\"\n","\n","retriever_tool = create_retriever_tool(\n",- " retriever,\n",- " name='sql_get_similar_examples',\n",- " description=tool_description\n",- " )\n",+ " retriever, name=\"sql_get_similar_examples\", description=tool_description\n",+ ")\n","custom_tool_list = [retriever_tool]"]},@@ -834,7 +841,7 @@"from langchain.chat_models import ChatOpenAI\n","\n","db = SQLDatabase.from_uri(\"sqlite:///Chinook.db\")\n",- "llm = ChatOpenAI(model_name='gpt-4',temperature=0)\n",+ "llm = ChatOpenAI(model_name=\"gpt-4\", temperature=0)\n","\n","toolkit = SQLDatabaseToolkit(db=db, llm=llm)\n","\n",@@ -845,13 +852,14 @@"Then I should query the schema of the most relevant tables\n","\"\"\"\n","\n",- "agent = create_sql_agent(llm=llm,\n",- " toolkit=toolkit,\n",- " verbose=True,\n",- " agent_type=AgentType.OPENAI_FUNCTIONS,\n",- " extra_tools=custom_tool_list,\n",- " suffix=custom_suffix\n",- " )"+ "agent = create_sql_agent(\n",+ " llm=llm,\n",+ " toolkit=toolkit,\n",+ " verbose=True,\n",+ " agent_type=AgentType.OPENAI_FUNCTIONS,\n",+ " extra_tools=custom_tool_list,\n",+ " suffix=custom_suffix,\n",+ ")"]},{@@ -936,12 +944,14 @@"import ast\n","import re\n","\n",+ "\n","def run_query_save_results(db, query):\n"," res = db.run(query)\n"," res = [el for sub in ast.literal_eval(res) for el in sub if el]\n",- " res = [re.sub(r'\\b\\d+\\b', '', string).strip() for string in res]\n",+ " res = [re.sub(r\"\\b\\d+\\b\", \"\", string).strip() for string in res]\n"," return res\n","\n",+ "\n","artists = run_query_save_results(db, \"SELECT Name FROM Artist\")\n","albums = run_query_save_results(db, \"SELECT Title FROM Album\")"]@@ -964,17 +974,17 @@"from langchain.vectorstores import FAISS\n","\n","\n",- "texts = (artists + albums)\n",+ "texts = artists + albums\n","\n","embeddings = OpenAIEmbeddings()\n","vector_db = FAISS.from_texts(texts, embeddings)\n","retriever = vector_db.as_retriever()\n","\n","retriever_tool = create_retriever_tool(\n",- " retriever,\n",- " name='name_search',\n",- " description='use to learn how a piece of data is actually written, can be from names, surnames addresses etc'\n",- " )\n",+ " retriever,\n",+ " name=\"name_search\",\n",+ " description=\"use to learn how a piece of data is actually written, can be from names, surnames addresses etc\",\n",+ ")\n","\n","custom_tool_list = [retriever_tool]"]@@ -991,7 +1001,7 @@"from langchain.chat_models import ChatOpenAI\n","\n","# db = SQLDatabase.from_uri(\"sqlite:///Chinook.db\")\n",- "llm = ChatOpenAI(model_name='gpt-4', temperature=0)\n",+ "llm = ChatOpenAI(model_name=\"gpt-4\", temperature=0)\n","\n","toolkit = SQLDatabaseToolkit(db=db, llm=llm)\n","\n",@@ -1001,13 +1011,14 @@"Then I should query the schema of the most relevant tables\n","\"\"\"\n","\n",- "agent = create_sql_agent(llm=llm,\n",- " toolkit=toolkit,\n",- " verbose=True,\n",- " agent_type=AgentType.OPENAI_FUNCTIONS,\n",- " extra_tools=custom_tool_list,\n",- " suffix=custom_suffix\n",- " )"+ "agent = create_sql_agent(\n",+ " llm=llm,\n",+ " toolkit=toolkit,\n",+ " verbose=True,\n",+ " agent_type=AgentType.OPENAI_FUNCTIONS,\n",+ " extra_tools=custom_tool_list,\n",+ " suffix=custom_suffix,\n",+ ")"]},{diff --git a/docs/docs/use_cases/question_answering/code_understanding.ipynb b/docs/docs/use_cases/question_answering/code_understanding.ipynbindex 0b072019c4..569a704f97 100644--- a/docs/docs/use_cases/question_answering/code_understanding.ipynb+++ b/docs/docs/use_cases/question_answering/code_understanding.ipynb@@ -125,10 +125,10 @@"source": ["# Load\n","loader = GenericLoader.from_filesystem(\n",- " repo_path+\"/libs/langchain/langchain\",\n",+ " repo_path + \"/libs/langchain/langchain\",\n"," glob=\"**/*\",\n"," suffixes=[\".py\"],\n",- " parser=LanguageParser(language=Language.PYTHON, parser_threshold=500)\n",+ " parser=LanguageParser(language=Language.PYTHON, parser_threshold=500),\n",")\n","documents = loader.load()\n","len(documents)"@@ -163,9 +163,10 @@],"source": ["from langchain.text_splitter import RecursiveCharacterTextSplitter\n",- "python_splitter = RecursiveCharacterTextSplitter.from_language(language=Language.PYTHON, \n",- " chunk_size=2000, \n",- " chunk_overlap=200)\n",+ "\n",+ "python_splitter = RecursiveCharacterTextSplitter.from_language(\n",+ " language=Language.PYTHON, chunk_size=2000, chunk_overlap=200\n",+ ")\n","texts = python_splitter.split_documents(documents)\n","len(texts)"]@@ -201,9 +202,10 @@"source": ["from langchain.vectorstores import Chroma\n","from langchain.embeddings.openai import OpenAIEmbeddings\n",+ "\n","db = Chroma.from_documents(texts, OpenAIEmbeddings(disallowed_special=()))\n","retriever = db.as_retriever(\n",- " search_type=\"mmr\", # Also test \"similarity\"\n",+ " search_type=\"mmr\", # Also test \"similarity\"\n"," search_kwargs={\"k\": 8},\n",")"]@@ -232,8 +234,11 @@"from langchain.chat_models import ChatOpenAI\n","from langchain.memory import ConversationSummaryMemory\n","from langchain.chains import ConversationalRetrievalChain\n",- "llm = ChatOpenAI(model_name=\"gpt-4\") \n",- "memory = ConversationSummaryMemory(llm=llm,memory_key=\"chat_history\",return_messages=True)\n",+ "\n",+ "llm = ChatOpenAI(model_name=\"gpt-4\")\n",+ "memory = ConversationSummaryMemory(\n",+ " llm=llm, memory_key=\"chat_history\", return_messages=True\n",+ ")\n","qa = ConversationalRetrievalChain.from_llm(llm, retriever=retriever, memory=memory)"]},@@ -256,7 +261,7 @@"source": ["question = \"How can I initialize a ReAct agent?\"\n","result = qa(question)\n",- "result['answer']"+ "result[\"answer\"]"]},{@@ -365,7 +370,7 @@"from langchain.chains import LLMChain\n","from langchain.callbacks.manager import CallbackManager\n","from langchain.memory import ConversationSummaryMemory\n",- "from langchain.chains import ConversationalRetrievalChain \n",+ "from langchain.chains import ConversationalRetrievalChain\n","from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler"]},@@ -927,7 +932,9 @@}],"source": [- "llm(\"Question: In bash, how do I list all the text files in the current directory that have been modified in the last month? Answer:\")"+ "llm(\n",+ " \"Question: In bash, how do I list all the text files in the current directory that have been modified in the last month? Answer:\"\n",+ ")"]},{@@ -969,6 +976,7 @@"outputs": [],"source": ["from langchain import hub\n",+ "\n","QA_CHAIN_PROMPT = hub.pull(\"rlm/rag-prompt-default\")"]},diff --git a/docs/docs/use_cases/question_answering/conversational_retrieval_agents.ipynb b/docs/docs/use_cases/question_answering/conversational_retrieval_agents.ipynbindex 6f1e6615a6..59f5cac935 100644--- a/docs/docs/use_cases/question_answering/conversational_retrieval_agents.ipynb+++ b/docs/docs/use_cases/question_answering/conversational_retrieval_agents.ipynb@@ -30,7 +30,8 @@"outputs": [],"source": ["from langchain.document_loaders import TextLoader\n",- "loader = TextLoader('../../../../../docs/docs/modules/state_of_the_union.txt')"+ "\n",+ "loader = TextLoader(\"../../../../../docs/docs/modules/state_of_the_union.txt\")"]},{@@ -89,9 +90,9 @@"outputs": [],"source": ["tool = create_retriever_tool(\n",- " retriever, \n",+ " retriever,\n"," \"search_state_of_union\",\n",- " \"Searches and returns documents regarding the state-of-the-union.\"\n",+ " \"Searches and returns documents regarding the state-of-the-union.\",\n",")\n","tools = [tool]"]@@ -116,7 +117,7 @@"metadata": {},"outputs": [],"source": [- "from langchain.agents.agent_toolkits import create_conversational_retrieval_agent "+ "from langchain.agents.agent_toolkits import create_conversational_retrieval_agent"]},{@@ -127,7 +128,8 @@"outputs": [],"source": ["from langchain.chat_models import ChatOpenAI\n",- "llm = ChatOpenAI(temperature = 0)"+ "\n",+ "llm = ChatOpenAI(temperature=0)"]},{@@ -276,7 +278,11 @@}],"source": [- "result = agent_executor({\"input\": \"what did the president say about kentaji brown jackson in the most recent state of the union?\"})"+ "result = agent_executor(\n",+ " {\n",+ " \"input\": \"what did the president say about kentaji brown jackson in the most recent state of the union?\"\n",+ " }\n",+ ")"]},{@@ -397,7 +403,9 @@"metadata": {},"outputs": [],"source": [- "from langchain.agents.openai_functions_agent.agent_token_buffer_memory import AgentTokenBufferMemory\n",+ "from langchain.agents.openai_functions_agent.agent_token_buffer_memory import (\n",+ " AgentTokenBufferMemory,\n",+ ")\n","\n","memory = AgentTokenBufferMemory(memory_key=memory_key, llm=llm)"]@@ -432,11 +440,11 @@"outputs": [],"source": ["system_message = SystemMessage(\n",- " content=(\n",- " \"Do your best to answer the questions. \"\n",- " \"Feel free to use any tools available to look up \"\n",- " \"relevant information, only if necessary\"\n",- " )\n",+ " content=(\n",+ " \"Do your best to answer the questions. \"\n",+ " \"Feel free to use any tools available to look up \"\n",+ " \"relevant information, only if necessary\"\n",+ " )\n",")"]},@@ -448,9 +456,9 @@"outputs": [],"source": ["prompt = OpenAIFunctionsAgent.create_prompt(\n",- " system_message=system_message,\n",- " extra_prompt_messages=[MessagesPlaceholder(variable_name=memory_key)]\n",- " )"+ " system_message=system_message,\n",+ " extra_prompt_messages=[MessagesPlaceholder(variable_name=memory_key)],\n",+ ")"]},{@@ -500,8 +508,13 @@"metadata": {},"outputs": [],"source": [- "agent_executor = AgentExecutor(agent=agent, tools=tools, memory=memory, verbose=True,\n",- " return_intermediate_steps=True)"+ "agent_executor = AgentExecutor(\n",+ " agent=agent,\n",+ " tools=tools,\n",+ " memory=memory,\n",+ " verbose=True,\n",+ " return_intermediate_steps=True,\n",+ ")"]},{diff --git a/docs/docs/use_cases/question_answering/index.ipynb b/docs/docs/use_cases/question_answering/index.ipynbindex 4669f69061..09dbcd85d6 100644--- a/docs/docs/use_cases/question_answering/index.ipynb+++ b/docs/docs/use_cases/question_answering/index.ipynb@@ -66,6 +66,7 @@"# Load documents\n","\n","from langchain.document_loaders import WebBaseLoader\n",+ "\n","loader = WebBaseLoader(\"https://lilianweng.github.io/posts/2023-06-23-agent/\")"]},@@ -79,7 +80,8 @@"# Split documents\n","\n","from langchain.text_splitter import RecursiveCharacterTextSplitter\n",- "text_splitter = RecursiveCharacterTextSplitter(chunk_size = 500, chunk_overlap = 0)\n",+ "\n",+ "text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=0)\n","splits = text_splitter.split_documents(loader.load())"]},@@ -94,7 +96,8 @@"\n","from langchain.vectorstores import Chroma\n","from langchain.embeddings import OpenAIEmbeddings\n",- "vectorstore = Chroma.from_documents(documents=splits,embedding=OpenAIEmbeddings())\n",+ "\n",+ "vectorstore = Chroma.from_documents(documents=splits, embedding=OpenAIEmbeddings())\n","retriever = vectorstore.as_retriever()"]},@@ -105,10 +108,11 @@"metadata": {},"outputs": [],"source": [- "# Prompt \n",+ "# Prompt\n","# https://smith.langchain.com/hub/rlm/rag-prompt\n","\n","from langchain import hub\n",+ "\n","rag_prompt = hub.pull(\"rlm/rag-prompt\")"]},@@ -122,6 +126,7 @@"# LLM\n","\n","from langchain.chat_models import ChatOpenAI\n",+ "\n","llm = ChatOpenAI(model_name=\"gpt-3.5-turbo\", temperature=0)"]},@@ -132,14 +137,11 @@"metadata": {},"outputs": [],"source": [- "# RAG chain \n",+ "# RAG chain\n","\n","from langchain.schema.runnable import RunnablePassthrough\n",- "rag_chain = (\n",- " {\"context\": retriever, \"question\": RunnablePassthrough()} \n",- " | rag_prompt \n",- " | llm \n",- ")"+ "\n",+ "rag_chain = {\"context\": retriever, \"question\": RunnablePassthrough()} | rag_prompt | llm"]},{@@ -221,7 +223,7 @@"source": ["from langchain.text_splitter import RecursiveCharacterTextSplitter\n","\n",- "text_splitter = RecursiveCharacterTextSplitter(chunk_size = 500, chunk_overlap = 0)\n",+ "text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=0)\n","all_splits = text_splitter.split_documents(data)"]},@@ -340,8 +342,8 @@"source": ["from langchain.retrievers import SVMRetriever\n","\n",- "svm_retriever = SVMRetriever.from_documents(all_splits,OpenAIEmbeddings())\n",- "docs_svm=svm_retriever.get_relevant_documents(question)\n",+ "svm_retriever = SVMRetriever.from_documents(all_splits, OpenAIEmbeddings())\n",+ "docs_svm = svm_retriever.get_relevant_documents(question)\n","len(docs_svm)"]},@@ -368,10 +370,11 @@"from langchain.retrievers.multi_query import MultiQueryRetriever\n","\n","logging.basicConfig()\n",- "logging.getLogger('langchain.retrievers.multi_query').setLevel(logging.INFO)\n",+ "logging.getLogger(\"langchain.retrievers.multi_query\").setLevel(logging.INFO)\n","\n",- "retriever_from_llm = MultiQueryRetriever.from_llm(retriever=vectorstore.as_retriever(),\n",- " llm=ChatOpenAI(temperature=0))\n",+ "retriever_from_llm = MultiQueryRetriever.from_llm(\n",+ " retriever=vectorstore.as_retriever(), llm=ChatOpenAI(temperature=0)\n",+ ")\n","unique_docs = retriever_from_llm.get_relevant_documents(query=question)\n","len(unique_docs)"]@@ -425,14 +428,12 @@],"source": ["from langchain.chat_models import ChatOpenAI\n",+ "\n","llm = ChatOpenAI(model_name=\"gpt-3.5-turbo\", temperature=0)\n","\n","from langchain.schema.runnable import RunnablePassthrough\n",- "rag_chain = (\n",- " {\"context\": retriever, \"question\": RunnablePassthrough()} \n",- " | rag_prompt \n",- " | llm \n",- ")\n",+ "\n",+ "rag_chain = {\"context\": retriever, \"question\": RunnablePassthrough()} | rag_prompt | llm\n","\n","rag_chain.invoke(\"What is Task Decomposition?\")"]@@ -492,9 +493,7 @@"rag_prompt_custom = PromptTemplate.from_template(template)\n","\n","rag_chain = (\n",- " {\"context\": retriever, \"question\": RunnablePassthrough()} \n",- " | rag_prompt_custom \n",- " | llm \n",+ " {\"context\": retriever, \"question\": RunnablePassthrough()} | rag_prompt_custom | llm\n",")\n","\n","rag_chain.invoke(\"What is Task Decomposition?\")"diff --git a/docs/docs/use_cases/question_answering/local_retrieval_qa.ipynb b/docs/docs/use_cases/question_answering/local_retrieval_qa.ipynbindex 92834808d2..b32315a910 100644--- a/docs/docs/use_cases/question_answering/local_retrieval_qa.ipynb+++ b/docs/docs/use_cases/question_answering/local_retrieval_qa.ipynb@@ -512,10 +512,12 @@}],"source": [- "# Prompt \n",+ "# Prompt\n","from langchain import hub\n",+ "\n","rag_prompt = hub.pull(\"rlm/rag-prompt\")\n","from langchain.chains.question_answering import load_qa_chain\n",+ "\n","# Chain\n","chain = load_qa_chain(llm, chain_type=\"stuff\", prompt=rag_prompt)\n","# Run\n",diff --git a/docs/docs/use_cases/question_answering/multiple_retrieval.ipynb b/docs/docs/use_cases/question_answering/multiple_retrieval.ipynbindex 8847a2b79e..53fcb51186 100644--- a/docs/docs/use_cases/question_answering/multiple_retrieval.ipynb+++ b/docs/docs/use_cases/question_answering/multiple_retrieval.ipynb@@ -63,6 +63,7 @@"source": ["from langchain.indexes import VectorstoreIndexCreator\n","from langchain.schema.document import Document\n",+ "\n","index_creator = VectorstoreIndexCreator()\n","index = index_creator.from_documents([Document(page_content=\"Foo\")])\n","retriever = index.vectorstore.as_retriever()"@@ -98,7 +99,9 @@"</source2>\n","\"\"\"\n","\n",- "prompt = ChatPromptTemplate.from_messages([(\"system\", system_message), (\"human\", \"{question}\")])"+ "prompt = ChatPromptTemplate.from_messages(\n",+ " [(\"system\", system_message), (\"human\", \"{question}\")]\n",+ ")"]},{@@ -108,11 +111,15 @@"metadata": {},"outputs": [],"source": [- "full_chain = {\n",- " \"source1\": {\"question\": lambda x: x[\"question\"]} | query_chain | db.run,\n",- " \"source2\": (lambda x: x['question']) | retriever,\n",- " \"question\": lambda x: x['question'],\n",- "} | prompt | ChatOpenAI()"+ "full_chain = (\n",+ " {\n",+ " \"source1\": {\"question\": lambda x: x[\"question\"]} | query_chain | db.run,\n",+ " \"source2\": (lambda x: x[\"question\"]) | retriever,\n",+ " \"question\": lambda x: x[\"question\"],\n",+ " }\n",+ " | prompt\n",+ " | ChatOpenAI()\n",+ ")"]},{@@ -137,7 +144,7 @@}],"source": [- "response = full_chain.invoke({\"question\":\"How many Employees are there\"})\n",+ "response = full_chain.invoke({\"question\": \"How many Employees are there\"})\n","print(response)"]}diff --git a/docs/docs/use_cases/summarization.ipynb b/docs/docs/use_cases/summarization.ipynbindex 5f68eba78a..3d108d4746 100644--- a/docs/docs/use_cases/summarization.ipynb+++ b/docs/docs/use_cases/summarization.ipynb@@ -260,9 +260,7 @@"llm_chain = LLMChain(llm=llm, prompt=prompt)\n","\n","# Define StuffDocumentsChain\n",- "stuff_chain = StuffDocumentsChain(\n",- " llm_chain=llm_chain, document_variable_name=\"text\"\n",- ")\n",+ "stuff_chain = StuffDocumentsChain(llm_chain=llm_chain, document_variable_name=\"text\")\n","\n","docs = loader.load()\n","print(stuff_chain.run(docs))"@@ -335,6 +333,7 @@"outputs": [],"source": ["from langchain import hub\n",+ "\n","map_prompt = hub.pull(\"rlm/map-prompt\")\n","map_chain = LLMChain(llm=llm, prompt=map_prompt)"]@@ -671,7 +670,9 @@"source": ["from langchain.chains import AnalyzeDocumentChain\n","\n",- "summarize_document_chain = AnalyzeDocumentChain(combine_docs_chain=chain, text_splitter=text_splitter)\n",+ "summarize_document_chain = AnalyzeDocumentChain(\n",+ " combine_docs_chain=chain, text_splitter=text_splitter\n",+ ")\n","summarize_document_chain.run(docs[0])"]},diff --git a/docs/docs/use_cases/tagging.ipynb b/docs/docs/use_cases/tagging.ipynbindex 7b6b5280d9..db12093db5 100644--- a/docs/docs/use_cases/tagging.ipynb+++ b/docs/docs/use_cases/tagging.ipynb@@ -49,7 +49,7 @@"metadata": {},"outputs": [],"source": [- "!pip install langchain openai \n",+ "!pip install langchain openai\n","\n","# Set env var OPENAI_API_KEY or load from a .env file:\n","# import dotenv\n",diff --git a/docs/docs/use_cases/web_scraping.ipynb b/docs/docs/use_cases/web_scraping.ipynbindex da53e4bf6f..ef4329aa1a 100644--- a/docs/docs/use_cases/web_scraping.ipynb+++ b/docs/docs/use_cases/web_scraping.ipynb@@ -1,664 +1,678 @@{- "cells": [- {- "cell_type": "raw",- "id": "e254cf03-49fc-4051-a4df-3a8e4e7d2688",- "metadata": {},- "source": [- "---\n",- "sidebar_position: 1\n",- "title: Web scraping\n",- "---"- ]- },- {- "cell_type": "markdown",- "id": "6605e7f7",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/langchain-ai/langchain/blob/master/docs/docs/use_cases/web_scraping.ipynb)\n",- "\n",- "## Use case\n",- "\n",- "[Web research](https://blog.langchain.dev/automating-web-research/) is one of the killer LLM applications:\n",- "\n",- "* Users have [highlighted it](https://twitter.com/GregKamradt/status/1679913813297225729?s=20) as one of his top desired AI tools. \n",- "* OSS repos like [gpt-researcher](https://github.com/assafelovic/gpt-researcher) are growing in popularity. \n",- " \n",- "\n",- " \n",- "## Overview\n",- "\n",- "Gathering content from the web has a few components:\n",- "\n",- "* `Search`: Query to url (e.g., using `GoogleSearchAPIWrapper`).\n",- "* `Loading`: Url to HTML (e.g., using `AsyncHtmlLoader`, `AsyncChromiumLoader`, etc).\n",- "* `Transforming`: HTML to formatted text (e.g., using `HTML2Text` or `Beautiful Soup`).\n",- "\n",- "## Quickstart"- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "1803c182",- "metadata": {},- "outputs": [],- "source": [- "pip install -q openai langchain playwright beautifulsoup4\n",- "playwright install\n",- "\n",- "# Set env var OPENAI_API_KEY or load from a .env file:\n",- "# import dotenv\n",- "# dotenv.load_dotenv()"- ]- },- {- "cell_type": "markdown",- "id": "50741083",- "metadata": {},- "source": [- "Scraping HTML content using a headless instance of Chromium.\n",- "\n",- "* The async nature of the scraping process is handled using Python's asyncio library.\n",- "* The actual interaction with the web pages is handled by Playwright."- ]- },- {- "cell_type": "code",- "execution_count": 2,- "id": "cd457cb1",- "metadata": {},- "outputs": [],- "source": [- "from langchain.document_loaders import AsyncChromiumLoader\n",- "from langchain.document_transformers import BeautifulSoupTransformer\n",- "\n",- "# Load HTML\n",- "loader = AsyncChromiumLoader([\"https://www.wsj.com\"])\n",- "html = loader.load()"- ]- },- {- "cell_type": "markdown",- "id": "2a879806",- "metadata": {},- "source": [- "Scrape text content tags such as `<p>, <li>, <div>, and <a>` tags from the HTML content:\n",- "\n",- "* `<p>`: The paragraph tag. It defines a paragraph in HTML and is used to group together related sentences and/or phrases.\n",- " \n",- "* `<li>`: The list item tag. It is used within ordered (`<ol>`) and unordered (`<ul>`) lists to define individual items within the list.\n",- " \n",- "* `<div>`: The division tag. It is a block-level element used to group other inline or block-level elements.\n",- " \n",- "* `<a>`: The anchor tag. It is used to define hyperlinks.\n",- "\n",- "* `<span>`: an inline container used to mark up a part of a text, or a part of a document. \n",- "\n",- "For many news websites (e.g., WSJ, CNN), headlines and summaries are all in `<span>` tags."- ]- },- {- "cell_type": "code",- "execution_count": 3,- "id": "141f206b",- "metadata": {},- "outputs": [],- "source": [- "# Transform\n",- "bs_transformer = BeautifulSoupTransformer()\n",- "docs_transformed = bs_transformer.transform_documents(html,tags_to_extract=[\"span\"])"- ]- },- {- "cell_type": "code",- "execution_count": 4,- "id": "73ddb234",- "metadata": {},- "outputs": [- {- "data": {- "text/plain": [- "'English EditionEnglish\u4e2d\u6587 (Chinese)\u65e5\u672c\u8a9e (Japanese) More Other Products from WSJBuy Side from WSJWSJ ShopWSJ Wine Other Products from WSJ Search Quotes and Companies Search Quotes and Companies 0.15% 0.03% 0.12% -0.42% 4.102% -0.69% -0.25% -0.15% -1.82% 0.24% 0.19% -1.10% About Evan His Family Reflects His Reporting How You Can Help Write a Message Life in Detention Latest News Get Email Updates Four Americans Released From Iranian Prison The Americans will remain under house arrest until they are '"- ]- },- "execution_count": 4,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "# Result\n",- "docs_transformed[0].page_content[0:500]"- ]- },- {- "cell_type": "markdown",- "id": "7d26d185",- "metadata": {},- "source": [- "These `Documents` now are staged for downstream usage in various LLM apps, as discussed below.\n",- "\n",- "## Loader\n",- "\n",- "### AsyncHtmlLoader\n",- "\n",- "The [AsyncHtmlLoader](docs/integrations/document_loaders/async_html) uses the `aiohttp` library to make asynchronous HTTP requests, suitable for simpler and lightweight scraping.\n",- "\n",- "### AsyncChromiumLoader\n",- "\n",- "The [AsyncChromiumLoader](docs/integrations/document_loaders/async_chromium) uses Playwright to launch a Chromium instance, which can handle JavaScript rendering and more complex web interactions.\n",- "\n",- "Chromium is one of the browsers supported by Playwright, a library used to control browser automation. \n",- "\n",- "Headless mode means that the browser is running without a graphical user interface, which is commonly used for web scraping."- ]- },- {- "cell_type": "code",- "execution_count": null,- "id": "8941e855",- "metadata": {},- "outputs": [],- "source": [- "from langchain.document_loaders import AsyncHtmlLoader\n",- "urls = [\"https://www.espn.com\",\"https://lilianweng.github.io/posts/2023-06-23-agent/\"]\n",- "loader = AsyncHtmlLoader(urls)\n",- "docs = loader.load()"- ]- },- {- "cell_type": "markdown",- "id": "e47f4bf0",- "metadata": {},- "source": [- "## Transformer\n",- "\n",- "### HTML2Text\n",- "\n",- "[HTML2Text](docs/integrations/document_transformers/html2text) provides a straightforward conversion of HTML content into plain text (with markdown-like formatting) without any specific tag manipulation. \n",- "\n",- "It's best suited for scenarios where the goal is to extract human-readable text without needing to manipulate specific HTML elements.\n",- "\n",- "### Beautiful Soup\n",- " \n",- "Beautiful Soup offers more fine-grained control over HTML content, enabling specific tag extraction, removal, and content cleaning. \n",- "\n",- "It's suited for cases where you want to extract specific information and clean up the HTML content according to your needs."- ]- },- {- "cell_type": "code",- "execution_count": 5,- "id": "99a7e2a8",- "metadata": {},- "outputs": [- {- "name": "stderr",- "output_type": "stream",- "text": [- "Fetching pages: 100%|#############################################################################################################| 2/2 [00:00<00:00, 7.01it/s]\n"- ]- }- ],- "source": [- "from langchain.document_loaders import AsyncHtmlLoader\n",- "urls = [\"https://www.espn.com\", \"https://lilianweng.github.io/posts/2023-06-23-agent/\"]\n",- "loader = AsyncHtmlLoader(urls)\n",- "docs = loader.load()"- ]- },- {- "cell_type": "code",- "execution_count": 7,- "id": "a2cd3e8d",- "metadata": {},- "outputs": [- {- "data": {- "text/plain": [- "\"Skip to main content Skip to navigation\\n\\n<\\n\\n>\\n\\nMenu\\n\\n## ESPN\\n\\n * Search\\n\\n * * scores\\n\\n * NFL\\n * MLB\\n * NBA\\n * NHL\\n * Soccer\\n * NCAAF\\n * \u2026\\n\\n * Women's World Cup\\n * LLWS\\n * NCAAM\\n * NCAAW\\n * Sports Betting\\n * Boxing\\n * CFL\\n * NCAA\\n * Cricket\\n * F1\\n * Golf\\n * Horse\\n * MMA\\n * NASCAR\\n * NBA G League\\n * Olympic Sports\\n * PLL\\n * Racing\\n * RN BB\\n * RN FB\\n * Rugby\\n * Tennis\\n * WNBA\\n * WWE\\n * X Games\\n * XFL\\n\\n * More\""- ]- },- "execution_count": 7,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "from langchain.document_transformers import Html2TextTransformer\n",- "html2text = Html2TextTransformer()\n",- "docs_transformed = html2text.transform_documents(docs)\n",- "docs_transformed[0].page_content[0:500]"- ]- },- {- "cell_type": "markdown",- "id": "8aef9861",- "metadata": {},- "source": [- "## Scraping with extraction\n",- "\n",- "### LLM with function calling\n",- "\n",- "Web scraping is challenging for many reasons. \n",- "\n",- "One of them is the changing nature of modern websites' layouts and content, which requires modifying scraping scripts to accommodate the changes.\n",- "\n",- "Using Function (e.g., OpenAI) with an extraction chain, we avoid having to change your code constantly when websites change. \n",- "\n",- "We're using `gpt-3.5-turbo-0613` to guarantee access to OpenAI Functions feature (although this might be available to everyone by time of writing). \n",- "\n",- "We're also keeping `temperature` at `0` to keep randomness of the LLM down."- ]- },- {- "cell_type": "code",- "execution_count": 5,- "id": "52d49f6f",- "metadata": {},- "outputs": [],- "source": [- "from langchain.chat_models import ChatOpenAI\n",- "llm = ChatOpenAI(temperature=0, model=\"gpt-3.5-turbo-0613\")"- ]- },- {- "cell_type": "markdown",- "id": "fc5757ce",- "metadata": {},- "source": [- "### Define a schema\n",- "\n",- "Next, you define a schema to specify what kind of data you want to extract. \n",- "\n",- "Here, the key names matter as they tell the LLM what kind of information they want. \n",- "\n",- "So, be as detailed as possible. \n",- "\n",- "In this example, we want to scrape only news article's name and summary from The Wall Street Journal website."- ]- },- {- "cell_type": "code",- "execution_count": 6,- "id": "95506f8e",- "metadata": {},- "outputs": [],- "source": [- "from langchain.chains import create_extraction_chain\n",- "\n",- "schema = {\n",- " \"properties\": {\n",- " \"news_article_title\": {\"type\": \"string\"},\n",- " \"news_article_summary\": {\"type\": \"string\"},\n",- " },\n",- " \"required\": [\"news_article_title\", \"news_article_summary\"],\n",- "}\n",- "\n",- "def extract(content: str, schema: dict):\n",- " return create_extraction_chain(schema=schema, llm=llm).run(content)"- ]- },- {- "cell_type": "markdown",- "id": "97f7de42",- "metadata": {},- "source": [- "### Run the web scraper w/ BeautifulSoup\n",- "\n",- "As shown above, we'll be using `BeautifulSoupTransformer`."- ]- },- {- "cell_type": "code",- "execution_count": 7,- "id": "977560ba",- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "Extracting content with LLM\n",- "[{'news_article_summary': 'The Americans will remain under house arrest until '\n",- " 'they are allowed to return to the U.S. in coming '\n",- " 'weeks, following a monthslong diplomatic push by '\n",- " 'the Biden administration.',\n",- " 'news_article_title': 'Four Americans Released From Iranian Prison'},\n",- " {'news_article_summary': 'Price pressures continued cooling last month, with '\n",- " 'the CPI rising a mild 0.2% from June, likely '\n",- " 'deterring the Federal Reserve from raising interest '\n",- " 'rates at its September meeting.',\n",- " 'news_article_title': 'Cooler July Inflation Opens Door to Fed Pause on '\n",- " 'Rates'},\n",- " {'news_article_summary': 'The company has decided to eliminate 27 of its 30 '\n",- " 'clothing labels, such as Lark & Ro and Goodthreads, '\n",- " 'as it works to fend off antitrust scrutiny and cut '\n",- " 'costs.',\n",- " 'news_article_title': 'Amazon Cuts Dozens of House Brands'},\n",- " {'news_article_summary': 'President Biden\u2019s order comes on top of a slowing '\n",- " 'Chinese economy, Covid lockdowns and rising '\n",- " 'tensions between the two powers.',\n",- " 'news_article_title': 'U.S. Investment Ban on China Poised to Deepen Divide'},\n",- " {'news_article_summary': 'The proposed trial date in the '\n",- " 'election-interference case comes on the same day as '\n",- " 'the former president\u2019s not guilty plea on '\n",- " 'additional Mar-a-Lago charges.',\n",- " 'news_article_title': 'Trump Should Be Tried in January, Prosecutors Tell '\n",- " 'Judge'},\n",- " {'news_article_summary': 'The CEO who started in June says the platform has '\n",- " '\u201can entirely different road map\u201d for the future.',\n",- " 'news_article_title': 'Yaccarino Says X Is Watching Threads but Has Its Own '\n",- " 'Vision'},\n",- " {'news_article_summary': 'Students foot the bill for flagship state '\n",- " 'universities that pour money into new buildings and '\n",- " 'programs with little pushback.',\n",- " 'news_article_title': 'Colleges Spend Like There\u2019s No Tomorrow. \u2018These '\n",- " 'Places Are Just Devouring Money.\u2019'},\n",- " {'news_article_summary': 'Wildfires fanned by hurricane winds have torn '\n",- " 'through parts of the Hawaiian island, devastating '\n",- " 'the popular tourist town of Lahaina.',\n",- " 'news_article_title': 'Maui Wildfires Leave at Least 36 Dead'},\n",- " {'news_article_summary': 'After its large armored push stalled, Kyiv has '\n",- " 'fallen back on the kind of tactics that brought it '\n",- " 'success earlier in the war.',\n",- " 'news_article_title': 'Ukraine Uses Small-Unit Tactics to Retake Captured '\n",- " 'Territory'},\n",- " {'news_article_summary': 'President Guillermo Lasso says the Aug. 20 election '\n",- " 'will proceed, as the Andean country grapples with '\n",- " 'rising drug gang violence.',\n",- " 'news_article_title': 'Ecuador Declares State of Emergency After '\n",- " 'Presidential Hopeful Killed'},\n",- " {'news_article_summary': 'This year\u2019s hurricane season, which typically runs '\n",- " 'from June to the end of November, has been '\n",- " 'difficult to predict, climate scientists said.',\n",- " 'news_article_title': 'Atlantic Hurricane Season Prediction Increased to '\n",- " '\u2018Above Normal,\u2019 NOAA Says'},\n",- " {'news_article_summary': 'The NFL is raising the price of its NFL+ streaming '\n",- " 'packages as it adds the NFL Network and RedZone.',\n",- " 'news_article_title': 'NFL to Raise Price of NFL+ Streaming Packages as It '\n",- " 'Adds NFL Network, RedZone'},\n",- " {'news_article_summary': 'Russia is planning a moon mission as part of the '\n",- " 'new space race.',\n",- " 'news_article_title': 'Russia\u2019s Moon Mission and the New Space Race'},\n",- " {'news_article_summary': 'Tapestry\u2019s $8.5 billion acquisition of Capri would '\n",- " 'create a conglomerate with more than $12 billion in '\n",- " 'annual sales, but it would still lack the '\n",- " 'high-wattage labels and diversity that have fueled '\n",- " 'LVMH\u2019s success.',\n",- " 'news_article_title': \"Why the Coach and Kors Marriage Doesn't Scare LVMH\"},\n",- " {'news_article_summary': 'The Supreme Court has blocked Purdue Pharma\u2019s $6 '\n",- " 'billion Sackler opioid settlement.',\n",- " 'news_article_title': 'Supreme Court Blocks Purdue Pharma\u2019s $6 Billion '\n",- " 'Sackler Opioid Settlement'},\n",- " {'news_article_summary': 'The Social Security COLA is expected to rise in '\n",- " '2024, but not by a lot.',\n",- " 'news_article_title': 'Social Security COLA Expected to Rise in 2024, but '\n",- " 'Not by a Lot'}]\n"- ]- }- ],- "source": [- "import pprint\n",- "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",- "\n",- "def scrape_with_playwright(urls, schema):\n",- " \n",- " loader = AsyncChromiumLoader(urls)\n",- " docs = loader.load()\n",- " bs_transformer = BeautifulSoupTransformer()\n",- " docs_transformed = bs_transformer.transform_documents(docs,tags_to_extract=[\"span\"])\n",- " print(\"Extracting content with LLM\")\n",- " \n",- " # Grab the first 1000 tokens of the site\n",- " splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(chunk_size=1000, \n",- " chunk_overlap=0)\n",- " splits = splitter.split_documents(docs_transformed)\n",- " \n",- " # Process the first split \n",- " extracted_content = extract(\n",- " schema=schema, content=splits[0].page_content\n",- " )\n",- " pprint.pprint(extracted_content)\n",- " return extracted_content\n",- "\n",- "urls = [\"https://www.wsj.com\"]\n",- "extracted_content = scrape_with_playwright(urls, schema=schema)"- ]- },- {- "cell_type": "markdown",- "id": "b08a8cef",- "metadata": {},- "source": [- "We can compare the headlines scraped to the page:\n",- "\n",- "\n",- "\n",- "Looking at the [LangSmith trace](https://smith.langchain.com/public/c3070198-5b13-419b-87bf-3821cdf34fa6/r), we can see what is going on under the hood:\n",- "\n",- "* It's following what is explained in the [extraction](docs/use_cases/extraction).\n",- "* We call the `information_extraction` function on the input text.\n",- "* It will attempt to populate the provided schema from the url content."- ]- },- {- "cell_type": "markdown",- "id": "a5a6f11e",- "metadata": {},- "source": [- "## Research automation\n",- "\n",- "Related to scraping, we may want to answer specific questions using searched content.\n",- "\n",- "We can automate the process of [web research](https://blog.langchain.dev/automating-web-research/) using a retriever, such as the `WebResearchRetriever` ([docs](https://python.langchain.com/docs/modules/data_connection/retrievers/web_research)).\n",- "\n",- "\n",- "\n",- "Copy requirements [from here](https://github.com/langchain-ai/web-explorer/blob/main/requirements.txt):\n",- "\n",- "`pip install -r requirements.txt`\n",- " \n",- "Set `GOOGLE_CSE_ID` and `GOOGLE_API_KEY`."- ]- },- {- "cell_type": "code",- "execution_count": 8,- "id": "414f0d41",- "metadata": {},- "outputs": [],- "source": [- "from langchain.vectorstores import Chroma\n",- "from langchain.embeddings import OpenAIEmbeddings\n",- "from langchain.chat_models.openai import ChatOpenAI\n",- "from langchain.utilities import GoogleSearchAPIWrapper\n",- "from langchain.retrievers.web_research import WebResearchRetriever"- ]- },- {- "cell_type": "code",- "execution_count": 41,- "id": "5d1ce098",- "metadata": {},- "outputs": [],- "source": [- "# Vectorstore\n",- "vectorstore = Chroma(embedding_function=OpenAIEmbeddings(),persist_directory=\"./chroma_db_oai\")\n",- "\n",- "# LLM\n",- "llm = ChatOpenAI(temperature=0)\n",- "\n",- "# Search \n",- "search = GoogleSearchAPIWrapper()"- ]- },+ "cells": [+ {+ "cell_type": "raw",+ "id": "e254cf03-49fc-4051-a4df-3a8e4e7d2688",+ "metadata": {},+ "source": [+ "---\n",+ "sidebar_position: 1\n",+ "title: Web scraping\n",+ "---"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "6605e7f7",+ "metadata": {},+ "source": [+ "[](https://colab.research.google.com/github/langchain-ai/langchain/blob/master/docs/docs/use_cases/web_scraping.ipynb)\n",+ "\n",+ "## Use case\n",+ "\n",+ "[Web research](https://blog.langchain.dev/automating-web-research/) is one of the killer LLM applications:\n",+ "\n",+ "* Users have [highlighted it](https://twitter.com/GregKamradt/status/1679913813297225729?s=20) as one of his top desired AI tools. \n",+ "* OSS repos like [gpt-researcher](https://github.com/assafelovic/gpt-researcher) are growing in popularity. \n",+ " \n",+ "\n",+ " \n",+ "## Overview\n",+ "\n",+ "Gathering content from the web has a few components:\n",+ "\n",+ "* `Search`: Query to url (e.g., using `GoogleSearchAPIWrapper`).\n",+ "* `Loading`: Url to HTML (e.g., using `AsyncHtmlLoader`, `AsyncChromiumLoader`, etc).\n",+ "* `Transforming`: HTML to formatted text (e.g., using `HTML2Text` or `Beautiful Soup`).\n",+ "\n",+ "## Quickstart"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "1803c182",+ "metadata": {},+ "outputs": [],+ "source": [+ "pip install -q openai langchain playwright beautifulsoup4\n",+ "playwright install\n",+ "\n",+ "# Set env var OPENAI_API_KEY or load from a .env file:\n",+ "# import dotenv\n",+ "# dotenv.load_dotenv()"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "50741083",+ "metadata": {},+ "source": [+ "Scraping HTML content using a headless instance of Chromium.\n",+ "\n",+ "* The async nature of the scraping process is handled using Python's asyncio library.\n",+ "* The actual interaction with the web pages is handled by Playwright."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 2,+ "id": "cd457cb1",+ "metadata": {},+ "outputs": [],+ "source": [+ "from langchain.document_loaders import AsyncChromiumLoader\n",+ "from langchain.document_transformers import BeautifulSoupTransformer\n",+ "\n",+ "# Load HTML\n",+ "loader = AsyncChromiumLoader([\"https://www.wsj.com\"])\n",+ "html = loader.load()"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "2a879806",+ "metadata": {},+ "source": [+ "Scrape text content tags such as `<p>, <li>, <div>, and <a>` tags from the HTML content:\n",+ "\n",+ "* `<p>`: The paragraph tag. It defines a paragraph in HTML and is used to group together related sentences and/or phrases.\n",+ " \n",+ "* `<li>`: The list item tag. It is used within ordered (`<ol>`) and unordered (`<ul>`) lists to define individual items within the list.\n",+ " \n",+ "* `<div>`: The division tag. It is a block-level element used to group other inline or block-level elements.\n",+ " \n",+ "* `<a>`: The anchor tag. It is used to define hyperlinks.\n",+ "\n",+ "* `<span>`: an inline container used to mark up a part of a text, or a part of a document. \n",+ "\n",+ "For many news websites (e.g., WSJ, CNN), headlines and summaries are all in `<span>` tags."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 3,+ "id": "141f206b",+ "metadata": {},+ "outputs": [],+ "source": [+ "# Transform\n",+ "bs_transformer = BeautifulSoupTransformer()\n",+ "docs_transformed = bs_transformer.transform_documents(html, tags_to_extract=[\"span\"])"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 4,+ "id": "73ddb234",+ "metadata": {},+ "outputs": [{- "cell_type": "markdown",- "id": "6d808b9d",- "metadata": {},- "source": [- "Initialize retriever with the above tools to:\n",- " \n",- "* Use an LLM to generate multiple relevant search queries (one LLM call)\n",- "* Execute a search for each query\n",- "* Choose the top K links per query (multiple search calls in parallel)\n",- "* Load the information from all chosen links (scrape pages in parallel)\n",- "* Index those documents into a vectorstore\n",- "* Find the most relevant documents for each original generated search query"+ "data": {+ "text/plain": [+ "'English EditionEnglish中文 (Chinese)日本語 (Japanese) More Other Products from WSJBuy Side from WSJWSJ ShopWSJ Wine Other Products from WSJ Search Quotes and Companies Search Quotes and Companies 0.15% 0.03% 0.12% -0.42% 4.102% -0.69% -0.25% -0.15% -1.82% 0.24% 0.19% -1.10% About Evan His Family Reflects His Reporting How You Can Help Write a Message Life in Detention Latest News Get Email Updates Four Americans Released From Iranian Prison The Americans will remain under house arrest until they are '"]- },+ },+ "execution_count": 4,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "# Result\n",+ "docs_transformed[0].page_content[0:500]"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "7d26d185",+ "metadata": {},+ "source": [+ "These `Documents` now are staged for downstream usage in various LLM apps, as discussed below.\n",+ "\n",+ "## Loader\n",+ "\n",+ "### AsyncHtmlLoader\n",+ "\n",+ "The [AsyncHtmlLoader](docs/integrations/document_loaders/async_html) uses the `aiohttp` library to make asynchronous HTTP requests, suitable for simpler and lightweight scraping.\n",+ "\n",+ "### AsyncChromiumLoader\n",+ "\n",+ "The [AsyncChromiumLoader](docs/integrations/document_loaders/async_chromium) uses Playwright to launch a Chromium instance, which can handle JavaScript rendering and more complex web interactions.\n",+ "\n",+ "Chromium is one of the browsers supported by Playwright, a library used to control browser automation. \n",+ "\n",+ "Headless mode means that the browser is running without a graphical user interface, which is commonly used for web scraping."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "8941e855",+ "metadata": {},+ "outputs": [],+ "source": [+ "from langchain.document_loaders import AsyncHtmlLoader\n",+ "\n",+ "urls = [\"https://www.espn.com\", \"https://lilianweng.github.io/posts/2023-06-23-agent/\"]\n",+ "loader = AsyncHtmlLoader(urls)\n",+ "docs = loader.load()"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "e47f4bf0",+ "metadata": {},+ "source": [+ "## Transformer\n",+ "\n",+ "### HTML2Text\n",+ "\n",+ "[HTML2Text](docs/integrations/document_transformers/html2text) provides a straightforward conversion of HTML content into plain text (with markdown-like formatting) without any specific tag manipulation. \n",+ "\n",+ "It's best suited for scenarios where the goal is to extract human-readable text without needing to manipulate specific HTML elements.\n",+ "\n",+ "### Beautiful Soup\n",+ " \n",+ "Beautiful Soup offers more fine-grained control over HTML content, enabling specific tag extraction, removal, and content cleaning. \n",+ "\n",+ "It's suited for cases where you want to extract specific information and clean up the HTML content according to your needs."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 5,+ "id": "99a7e2a8",+ "metadata": {},+ "outputs": [{- "cell_type": "code",- "execution_count": 42,- "id": "e3e3a589",- "metadata": {},- "outputs": [],- "source": [- "# Initialize\n",- "web_research_retriever = WebResearchRetriever.from_llm(\n",- " vectorstore=vectorstore,\n",- " llm=llm, \n",- " search=search)"- ]- },+ "name": "stderr",+ "output_type": "stream",+ "text": [+ "Fetching pages: 100%|#############################################################################################################| 2/2 [00:00<00:00, 7.01it/s]\n"+ ]+ }+ ],+ "source": [+ "from langchain.document_loaders import AsyncHtmlLoader\n",+ "\n",+ "urls = [\"https://www.espn.com\", \"https://lilianweng.github.io/posts/2023-06-23-agent/\"]\n",+ "loader = AsyncHtmlLoader(urls)\n",+ "docs = loader.load()"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 7,+ "id": "a2cd3e8d",+ "metadata": {},+ "outputs": [{- "cell_type": "code",- "execution_count": 44,- "id": "20655b74",- "metadata": {},- "outputs": [- {- "name": "stderr",- "output_type": "stream",- "text": [- "INFO:langchain.retrievers.web_research:Generating questions for Google Search ...\n",- "INFO:langchain.retrievers.web_research:Questions for Google Search (raw): {'question': 'How do LLM Powered Autonomous Agents work?', 'text': LineList(lines=['1. What is the functioning principle of LLM Powered Autonomous Agents?\\n', '2. How do LLM Powered Autonomous Agents operate?\\n'])}\n",- "INFO:langchain.retrievers.web_research:Questions for Google Search: ['1. What is the functioning principle of LLM Powered Autonomous Agents?\\n', '2. How do LLM Powered Autonomous Agents operate?\\n']\n",- "INFO:langchain.retrievers.web_research:Searching for relevant urls ...\n",- "INFO:langchain.retrievers.web_research:Searching for relevant urls ...\n",- "INFO:langchain.retrievers.web_research:Search results: [{'title': 'LLM Powered Autonomous Agents | Hacker News', 'link': 'https://news.ycombinator.com/item?id=36488871', 'snippet': 'Jun 26, 2023 ... Exactly. A temperature of 0 means you always pick the highest probability token (i.e. the \"max\" function), while a temperature of 1 means you\\xa0...'}]\n",- "INFO:langchain.retrievers.web_research:Searching for relevant urls ...\n",- "INFO:langchain.retrievers.web_research:Search results: [{'title': \"LLM Powered Autonomous Agents | Lil'Log\", 'link': 'https://lilianweng.github.io/posts/2023-06-23-agent/', 'snippet': 'Jun 23, 2023 ... Task decomposition can be done (1) by LLM with simple prompting like \"Steps for XYZ.\\\\n1.\" , \"What are the subgoals for achieving XYZ?\" , (2) by\\xa0...'}]\n",- "INFO:langchain.retrievers.web_research:New URLs to load: []\n",- "INFO:langchain.retrievers.web_research:Grabbing most relevant splits from urls...\n"- ]- },- {- "data": {- "text/plain": [- "{'question': 'How do LLM Powered Autonomous Agents work?',\n",- " 'answer': \"LLM-powered autonomous agents work by using LLM as the agent's brain, complemented by several key components such as planning, memory, and tool use. In terms of planning, the agent breaks down large tasks into smaller subgoals and can reflect and refine its actions based on past experiences. Memory is divided into short-term memory, which is used for in-context learning, and long-term memory, which allows the agent to retain and recall information over extended periods. Tool use involves the agent calling external APIs for additional information. These agents have been used in various applications, including scientific discovery and generative agents simulation.\",\n",- " 'sources': ''}"- ]- },- "execution_count": 44,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "# Run\n",- "import logging\n",- "logging.basicConfig()\n",- "logging.getLogger(\"langchain.retrievers.web_research\").setLevel(logging.INFO)\n",- "from langchain.chains import RetrievalQAWithSourcesChain\n",- "user_input = \"How do LLM Powered Autonomous Agents work?\"\n",- "qa_chain = RetrievalQAWithSourcesChain.from_chain_type(llm,retriever=web_research_retriever)\n",- "result = qa_chain({\"question\": user_input})\n",- "result"+ "data": {+ "text/plain": [+ "\"Skip to main content Skip to navigation\\n\\n<\\n\\n>\\n\\nMenu\\n\\n## ESPN\\n\\n * Search\\n\\n * * scores\\n\\n * NFL\\n * MLB\\n * NBA\\n * NHL\\n * Soccer\\n * NCAAF\\n * …\\n\\n * Women's World Cup\\n * LLWS\\n * NCAAM\\n * NCAAW\\n * Sports Betting\\n * Boxing\\n * CFL\\n * NCAA\\n * Cricket\\n * F1\\n * Golf\\n * Horse\\n * MMA\\n * NASCAR\\n * NBA G League\\n * Olympic Sports\\n * PLL\\n * Racing\\n * RN BB\\n * RN FB\\n * Rugby\\n * Tennis\\n * WNBA\\n * WWE\\n * X Games\\n * XFL\\n\\n * More\""]- },+ },+ "execution_count": 7,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "from langchain.document_transformers import Html2TextTransformer\n",+ "\n",+ "html2text = Html2TextTransformer()\n",+ "docs_transformed = html2text.transform_documents(docs)\n",+ "docs_transformed[0].page_content[0:500]"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "8aef9861",+ "metadata": {},+ "source": [+ "## Scraping with extraction\n",+ "\n",+ "### LLM with function calling\n",+ "\n",+ "Web scraping is challenging for many reasons. \n",+ "\n",+ "One of them is the changing nature of modern websites' layouts and content, which requires modifying scraping scripts to accommodate the changes.\n",+ "\n",+ "Using Function (e.g., OpenAI) with an extraction chain, we avoid having to change your code constantly when websites change. \n",+ "\n",+ "We're using `gpt-3.5-turbo-0613` to guarantee access to OpenAI Functions feature (although this might be available to everyone by time of writing). \n",+ "\n",+ "We're also keeping `temperature` at `0` to keep randomness of the LLM down."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 5,+ "id": "52d49f6f",+ "metadata": {},+ "outputs": [],+ "source": [+ "from langchain.chat_models import ChatOpenAI\n",+ "\n",+ "llm = ChatOpenAI(temperature=0, model=\"gpt-3.5-turbo-0613\")"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "fc5757ce",+ "metadata": {},+ "source": [+ "### Define a schema\n",+ "\n",+ "Next, you define a schema to specify what kind of data you want to extract. \n",+ "\n",+ "Here, the key names matter as they tell the LLM what kind of information they want. \n",+ "\n",+ "So, be as detailed as possible. \n",+ "\n",+ "In this example, we want to scrape only news article's name and summary from The Wall Street Journal website."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 6,+ "id": "95506f8e",+ "metadata": {},+ "outputs": [],+ "source": [+ "from langchain.chains import create_extraction_chain\n",+ "\n",+ "schema = {\n",+ " \"properties\": {\n",+ " \"news_article_title\": {\"type\": \"string\"},\n",+ " \"news_article_summary\": {\"type\": \"string\"},\n",+ " },\n",+ " \"required\": [\"news_article_title\", \"news_article_summary\"],\n",+ "}\n",+ "\n",+ "\n",+ "def extract(content: str, schema: dict):\n",+ " return create_extraction_chain(schema=schema, llm=llm).run(content)"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "97f7de42",+ "metadata": {},+ "source": [+ "### Run the web scraper w/ BeautifulSoup\n",+ "\n",+ "As shown above, we'll be using `BeautifulSoupTransformer`."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 7,+ "id": "977560ba",+ "metadata": {},+ "outputs": [{- "cell_type": "markdown",- "metadata": {},- "source": [- "### Going deeper \n",- "\n",- "* Here's a [app](https://github.com/langchain-ai/web-explorer/tree/main) that wraps this retriever with a lighweight UI."- ],- "id": "7a940df1"- },+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Extracting content with LLM\n",+ "[{'news_article_summary': 'The Americans will remain under house arrest until '\n",+ " 'they are allowed to return to the U.S. in coming '\n",+ " 'weeks, following a monthslong diplomatic push by '\n",+ " 'the Biden administration.',\n",+ " 'news_article_title': 'Four Americans Released From Iranian Prison'},\n",+ " {'news_article_summary': 'Price pressures continued cooling last month, with '\n",+ " 'the CPI rising a mild 0.2% from June, likely '\n",+ " 'deterring the Federal Reserve from raising interest '\n",+ " 'rates at its September meeting.',\n",+ " 'news_article_title': 'Cooler July Inflation Opens Door to Fed Pause on '\n",+ " 'Rates'},\n",+ " {'news_article_summary': 'The company has decided to eliminate 27 of its 30 '\n",+ " 'clothing labels, such as Lark & Ro and Goodthreads, '\n",+ " 'as it works to fend off antitrust scrutiny and cut '\n",+ " 'costs.',\n",+ " 'news_article_title': 'Amazon Cuts Dozens of House Brands'},\n",+ " {'news_article_summary': 'President Biden’s order comes on top of a slowing '\n",+ " 'Chinese economy, Covid lockdowns and rising '\n",+ " 'tensions between the two powers.',\n",+ " 'news_article_title': 'U.S. Investment Ban on China Poised to Deepen Divide'},\n",+ " {'news_article_summary': 'The proposed trial date in the '\n",+ " 'election-interference case comes on the same day as '\n",+ " 'the former president’s not guilty plea on '\n",+ " 'additional Mar-a-Lago charges.',\n",+ " 'news_article_title': 'Trump Should Be Tried in January, Prosecutors Tell '\n",+ " 'Judge'},\n",+ " {'news_article_summary': 'The CEO who started in June says the platform has '\n",+ " '“an entirely different road map” for the future.',\n",+ " 'news_article_title': 'Yaccarino Says X Is Watching Threads but Has Its Own '\n",+ " 'Vision'},\n",+ " {'news_article_summary': 'Students foot the bill for flagship state '\n",+ " 'universities that pour money into new buildings and '\n",+ " 'programs with little pushback.',\n",+ " 'news_article_title': 'Colleges Spend Like There’s No Tomorrow. ‘These '\n",+ " 'Places Are Just Devouring Money.’'},\n",+ " {'news_article_summary': 'Wildfires fanned by hurricane winds have torn '\n",+ " 'through parts of the Hawaiian island, devastating '\n",+ " 'the popular tourist town of Lahaina.',\n",+ " 'news_article_title': 'Maui Wildfires Leave at Least 36 Dead'},\n",+ " {'news_article_summary': 'After its large armored push stalled, Kyiv has '\n",+ " 'fallen back on the kind of tactics that brought it '\n",+ " 'success earlier in the war.',\n",+ " 'news_article_title': 'Ukraine Uses Small-Unit Tactics to Retake Captured '\n",+ " 'Territory'},\n",+ " {'news_article_summary': 'President Guillermo Lasso says the Aug. 20 election '\n",+ " 'will proceed, as the Andean country grapples with '\n",+ " 'rising drug gang violence.',\n",+ " 'news_article_title': 'Ecuador Declares State of Emergency After '\n",+ " 'Presidential Hopeful Killed'},\n",+ " {'news_article_summary': 'This year’s hurricane season, which typically runs '\n",+ " 'from June to the end of November, has been '\n",+ " 'difficult to predict, climate scientists said.',\n",+ " 'news_article_title': 'Atlantic Hurricane Season Prediction Increased to '\n",+ " '‘Above Normal,’ NOAA Says'},\n",+ " {'news_article_summary': 'The NFL is raising the price of its NFL+ streaming '\n",+ " 'packages as it adds the NFL Network and RedZone.',\n",+ " 'news_article_title': 'NFL to Raise Price of NFL+ Streaming Packages as It '\n",+ " 'Adds NFL Network, RedZone'},\n",+ " {'news_article_summary': 'Russia is planning a moon mission as part of the '\n",+ " 'new space race.',\n",+ " 'news_article_title': 'Russia’s Moon Mission and the New Space Race'},\n",+ " {'news_article_summary': 'Tapestry’s $8.5 billion acquisition of Capri would '\n",+ " 'create a conglomerate with more than $12 billion in '\n",+ " 'annual sales, but it would still lack the '\n",+ " 'high-wattage labels and diversity that have fueled '\n",+ " 'LVMH’s success.',\n",+ " 'news_article_title': \"Why the Coach and Kors Marriage Doesn't Scare LVMH\"},\n",+ " {'news_article_summary': 'The Supreme Court has blocked Purdue Pharma’s $6 '\n",+ " 'billion Sackler opioid settlement.',\n",+ " 'news_article_title': 'Supreme Court Blocks Purdue Pharma’s $6 Billion '\n",+ " 'Sackler Opioid Settlement'},\n",+ " {'news_article_summary': 'The Social Security COLA is expected to rise in '\n",+ " '2024, but not by a lot.',\n",+ " 'news_article_title': 'Social Security COLA Expected to Rise in 2024, but '\n",+ " 'Not by a Lot'}]\n"+ ]+ }+ ],+ "source": [+ "import pprint\n",+ "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",+ "\n",+ "\n",+ "def scrape_with_playwright(urls, schema):\n",+ " loader = AsyncChromiumLoader(urls)\n",+ " docs = loader.load()\n",+ " bs_transformer = BeautifulSoupTransformer()\n",+ " docs_transformed = bs_transformer.transform_documents(\n",+ " docs, tags_to_extract=[\"span\"]\n",+ " )\n",+ " print(\"Extracting content with LLM\")\n",+ "\n",+ " # Grab the first 1000 tokens of the site\n",+ " splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(\n",+ " chunk_size=1000, chunk_overlap=0\n",+ " )\n",+ " splits = splitter.split_documents(docs_transformed)\n",+ "\n",+ " # Process the first split\n",+ " extracted_content = extract(schema=schema, content=splits[0].page_content)\n",+ " pprint.pprint(extracted_content)\n",+ " return extracted_content\n",+ "\n",+ "\n",+ "urls = [\"https://www.wsj.com\"]\n",+ "extracted_content = scrape_with_playwright(urls, schema=schema)"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "b08a8cef",+ "metadata": {},+ "source": [+ "We can compare the headlines scraped to the page:\n",+ "\n",+ "\n",+ "\n",+ "Looking at the [LangSmith trace](https://smith.langchain.com/public/c3070198-5b13-419b-87bf-3821cdf34fa6/r), we can see what is going on under the hood:\n",+ "\n",+ "* It's following what is explained in the [extraction](docs/use_cases/extraction).\n",+ "* We call the `information_extraction` function on the input text.\n",+ "* It will attempt to populate the provided schema from the url content."+ ]+ },+ {+ "cell_type": "markdown",+ "id": "a5a6f11e",+ "metadata": {},+ "source": [+ "## Research automation\n",+ "\n",+ "Related to scraping, we may want to answer specific questions using searched content.\n",+ "\n",+ "We can automate the process of [web research](https://blog.langchain.dev/automating-web-research/) using a retriever, such as the `WebResearchRetriever` ([docs](https://python.langchain.com/docs/modules/data_connection/retrievers/web_research)).\n",+ "\n",+ "\n",+ "\n",+ "Copy requirements [from here](https://github.com/langchain-ai/web-explorer/blob/main/requirements.txt):\n",+ "\n",+ "`pip install -r requirements.txt`\n",+ " \n",+ "Set `GOOGLE_CSE_ID` and `GOOGLE_API_KEY`."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 8,+ "id": "414f0d41",+ "metadata": {},+ "outputs": [],+ "source": [+ "from langchain.vectorstores import Chroma\n",+ "from langchain.embeddings import OpenAIEmbeddings\n",+ "from langchain.chat_models.openai import ChatOpenAI\n",+ "from langchain.utilities import GoogleSearchAPIWrapper\n",+ "from langchain.retrievers.web_research import WebResearchRetriever"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 41,+ "id": "5d1ce098",+ "metadata": {},+ "outputs": [],+ "source": [+ "# Vectorstore\n",+ "vectorstore = Chroma(\n",+ " embedding_function=OpenAIEmbeddings(), persist_directory=\"./chroma_db_oai\"\n",+ ")\n",+ "\n",+ "# LLM\n",+ "llm = ChatOpenAI(temperature=0)\n",+ "\n",+ "# Search\n",+ "search = GoogleSearchAPIWrapper()"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "6d808b9d",+ "metadata": {},+ "source": [+ "Initialize retriever with the above tools to:\n",+ " \n",+ "* Use an LLM to generate multiple relevant search queries (one LLM call)\n",+ "* Execute a search for each query\n",+ "* Choose the top K links per query (multiple search calls in parallel)\n",+ "* Load the information from all chosen links (scrape pages in parallel)\n",+ "* Index those documents into a vectorstore\n",+ "* Find the most relevant documents for each original generated search query"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 42,+ "id": "e3e3a589",+ "metadata": {},+ "outputs": [],+ "source": [+ "# Initialize\n",+ "web_research_retriever = WebResearchRetriever.from_llm(\n",+ " vectorstore=vectorstore, llm=llm, search=search\n",+ ")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 44,+ "id": "20655b74",+ "metadata": {},+ "outputs": [{- "cell_type": "markdown",- "id": "312c399e",- "metadata": {},- "source": [- "## Question answering over a website\n",- "\n",- "To answer questions over a specific website, you can use Apify's [Website Content Crawler](https://apify.com/apify/website-content-crawler) Actor, which can deeply crawl websites such as documentation, knowledge bases, help centers, or blogs,\n",- "and extract text content from the web pages.\n",- "\n",- "In the example below, we will deeply crawl the Python documentation of LangChain's Chat LLM models and answer a question over it.\n",- "\n",- "First, install the requirements\n",- "`pip install apify-client openai langchain chromadb tiktoken`\n",- " \n",- "Next, set `OPENAI_API_KEY` and `APIFY_API_TOKEN` in your environment variables.\n",- "\n",- "The full code follows:"- ]+ "name": "stderr",+ "output_type": "stream",+ "text": [+ "INFO:langchain.retrievers.web_research:Generating questions for Google Search ...\n",+ "INFO:langchain.retrievers.web_research:Questions for Google Search (raw): {'question': 'How do LLM Powered Autonomous Agents work?', 'text': LineList(lines=['1. What is the functioning principle of LLM Powered Autonomous Agents?\\n', '2. How do LLM Powered Autonomous Agents operate?\\n'])}\n",+ "INFO:langchain.retrievers.web_research:Questions for Google Search: ['1. What is the functioning principle of LLM Powered Autonomous Agents?\\n', '2. How do LLM Powered Autonomous Agents operate?\\n']\n",+ "INFO:langchain.retrievers.web_research:Searching for relevant urls ...\n",+ "INFO:langchain.retrievers.web_research:Searching for relevant urls ...\n",+ "INFO:langchain.retrievers.web_research:Search results: [{'title': 'LLM Powered Autonomous Agents | Hacker News', 'link': 'https://news.ycombinator.com/item?id=36488871', 'snippet': 'Jun 26, 2023 ... Exactly. A temperature of 0 means you always pick the highest probability token (i.e. the \"max\" function), while a temperature of 1 means you\\xa0...'}]\n",+ "INFO:langchain.retrievers.web_research:Searching for relevant urls ...\n",+ "INFO:langchain.retrievers.web_research:Search results: [{'title': \"LLM Powered Autonomous Agents | Lil'Log\", 'link': 'https://lilianweng.github.io/posts/2023-06-23-agent/', 'snippet': 'Jun 23, 2023 ... Task decomposition can be done (1) by LLM with simple prompting like \"Steps for XYZ.\\\\n1.\" , \"What are the subgoals for achieving XYZ?\" , (2) by\\xa0...'}]\n",+ "INFO:langchain.retrievers.web_research:New URLs to load: []\n",+ "INFO:langchain.retrievers.web_research:Grabbing most relevant splits from urls...\n"+ ]},{- "cell_type": "code",- "execution_count": 2,- "id": "9b08da5e",- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- " Yes, LangChain offers integration with OpenAI chat models. You can use the ChatOpenAI class to interact with OpenAI models.\n"- ]- }- ],- "source": [- "from langchain.docstore.document import Document\n",- "from langchain.indexes import VectorstoreIndexCreator\n",- "from langchain.utilities import ApifyWrapper\n",- "\n",- "apify = ApifyWrapper()\n",- "# Call the Actor to obtain text from the crawled webpages\n",- "loader = apify.call_actor(\n",- " actor_id=\"apify/website-content-crawler\",\n",- " run_input={\"startUrls\": [{\"url\": \"https://python.langchain.com/docs/integrations/chat/\"}]},\n",- " dataset_mapping_function=lambda item: Document(\n",- " page_content=item[\"text\"] or \"\", metadata={\"source\": item[\"url\"]}\n",- " ),\n",- ")\n",- "\n",- "# Create a vector store based on the crawled data\n",- "index = VectorstoreIndexCreator().from_loaders([loader])\n",- "\n",- "# Query the vector store\n",- "query = \"Are any OpenAI chat models integrated in LangChain?\"\n",- "result = index.query(query)\n",- "print(result)"+ "data": {+ "text/plain": [+ "{'question': 'How do LLM Powered Autonomous Agents work?',\n",+ " 'answer': \"LLM-powered autonomous agents work by using LLM as the agent's brain, complemented by several key components such as planning, memory, and tool use. In terms of planning, the agent breaks down large tasks into smaller subgoals and can reflect and refine its actions based on past experiences. Memory is divided into short-term memory, which is used for in-context learning, and long-term memory, which allows the agent to retain and recall information over extended periods. Tool use involves the agent calling external APIs for additional information. These agents have been used in various applications, including scientific discovery and generative agents simulation.\",\n",+ " 'sources': ''}"]+ },+ "execution_count": 44,+ "metadata": {},+ "output_type": "execute_result"}- ],- "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.9.16"+ ],+ "source": [+ "# Run\n",+ "import logging\n",+ "\n",+ "logging.basicConfig()\n",+ "logging.getLogger(\"langchain.retrievers.web_research\").setLevel(logging.INFO)\n",+ "from langchain.chains import RetrievalQAWithSourcesChain\n",+ "\n",+ "user_input = \"How do LLM Powered Autonomous Agents work?\"\n",+ "qa_chain = RetrievalQAWithSourcesChain.from_chain_type(\n",+ " llm, retriever=web_research_retriever\n",+ ")\n",+ "result = qa_chain({\"question\": user_input})\n",+ "result"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "### Going deeper \n",+ "\n",+ "* Here's a [app](https://github.com/langchain-ai/web-explorer/tree/main) that wraps this retriever with a lighweight UI."+ ],+ "id": "7a940df1"+ },+ {+ "cell_type": "markdown",+ "id": "312c399e",+ "metadata": {},+ "source": [+ "## Question answering over a website\n",+ "\n",+ "To answer questions over a specific website, you can use Apify's [Website Content Crawler](https://apify.com/apify/website-content-crawler) Actor, which can deeply crawl websites such as documentation, knowledge bases, help centers, or blogs,\n",+ "and extract text content from the web pages.\n",+ "\n",+ "In the example below, we will deeply crawl the Python documentation of LangChain's Chat LLM models and answer a question over it.\n",+ "\n",+ "First, install the requirements\n",+ "`pip install apify-client openai langchain chromadb tiktoken`\n",+ " \n",+ "Next, set `OPENAI_API_KEY` and `APIFY_API_TOKEN` in your environment variables.\n",+ "\n",+ "The full code follows:"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 2,+ "id": "9b08da5e",+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ " Yes, LangChain offers integration with OpenAI chat models. You can use the ChatOpenAI class to interact with OpenAI models.\n"+ ]}+ ],+ "source": [+ "from langchain.docstore.document import Document\n",+ "from langchain.indexes import VectorstoreIndexCreator\n",+ "from langchain.utilities import ApifyWrapper\n",+ "\n",+ "apify = ApifyWrapper()\n",+ "# Call the Actor to obtain text from the crawled webpages\n",+ "loader = apify.call_actor(\n",+ " actor_id=\"apify/website-content-crawler\",\n",+ " run_input={\n",+ " \"startUrls\": [{\"url\": \"https://python.langchain.com/docs/integrations/chat/\"}]\n",+ " },\n",+ " dataset_mapping_function=lambda item: Document(\n",+ " page_content=item[\"text\"] or \"\", metadata={\"source\": item[\"url\"]}\n",+ " ),\n",+ ")\n",+ "\n",+ "# Create a vector store based on the crawled data\n",+ "index = VectorstoreIndexCreator().from_loaders([loader])\n",+ "\n",+ "# Query the vector store\n",+ "query = \"Are any OpenAI chat models integrated in LangChain?\"\n",+ "result = index.query(query)\n",+ "print(result)"+ ]+ }+ ],+ "metadata": {+ "kernelspec": {+ "display_name": "Python 3 (ipykernel)",+ "language": "python",+ "name": "python3"},- "nbformat": 4,- "nbformat_minor": 5+ "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.9.16"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5}diff --git a/docs/scripts/generate_api_reference_links.py b/docs/scripts/generate_api_reference_links.pyindex cc994ad06e..a9a38629b9 100644--- a/docs/scripts/generate_api_reference_links.py+++ b/docs/scripts/generate_api_reference_links.py@@ -1,3 +1,4 @@+import argparseimport importlibimport inspectimport json@@ -5,7 +6,6 @@ import loggingimport osimport refrom pathlib import Path-import argparselogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)diff --git a/docs/scripts/model_feat_table.py b/docs/scripts/model_feat_table.pyindex 3ff5be4f80..82f30766b0 100644--- a/docs/scripts/model_feat_table.py+++ b/docs/scripts/model_feat_table.py@@ -3,13 +3,9 @@ from pathlib import Pathfrom langchain import chat_models, llmsfrom langchain.chat_models.base import BaseChatModel, SimpleChatModel-from langchain.llms.base import BaseLLM, LLM+from langchain.llms.base import LLM, BaseLLM-INTEGRATIONS_DIR = (- Path(os.path.abspath(__file__)).parents[1]- / "docs"- / "integrations"-)+INTEGRATIONS_DIR = Path(os.path.abspath(__file__)).parents[1] / "docs" / "integrations"LLM_IGNORE = ("FakeListLLM", "OpenAIChat", "PromptLayerOpenAIChat")LLM_FEAT_TABLE_CORRECTION = {"TextGen": {"_astream": False, "_agenerate": False},@@ -43,7 +39,7 @@ Each LLM integration can optionally provide native implementations for async, st{table}-"""+""" # noqa: E501CHAT_MODEL_TEMPLATE = """\---@@ -64,7 +60,7 @@ The table shows, for each integration, which features have been implemented with{table}-"""+""" # noqa: E501def get_llm_table():diff --git a/poetry.lock b/poetry.lockindex 08715bfaee..d61a37d6e2 100644--- a/poetry.lock+++ b/poetry.lock@@ -383,33 +383,29 @@ lxml = ["lxml"][[package]]name = "black"-version = "23.9.1"+version = "23.10.1"description = "The uncompromising code formatter."optional = falsepython-versions = ">=3.8"files = [- {file = "black-23.9.1-cp310-cp310-macosx_10_16_arm64.whl", hash = "sha256:d6bc09188020c9ac2555a498949401ab35bb6bf76d4e0f8ee251694664df6301"},- {file = "black-23.9.1-cp310-cp310-macosx_10_16_universal2.whl", hash = "sha256:13ef033794029b85dfea8032c9d3b92b42b526f1ff4bf13b2182ce4e917f5100"},- {file = "black-23.9.1-cp310-cp310-macosx_10_16_x86_64.whl", hash = "sha256:75a2dc41b183d4872d3a500d2b9c9016e67ed95738a3624f4751a0cb4818fe71"},- {file = "black-23.9.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:13a2e4a93bb8ca74a749b6974925c27219bb3df4d42fc45e948a5d9feb5122b7"},- {file = "black-23.9.1-cp310-cp310-win_amd64.whl", hash = "sha256:adc3e4442eef57f99b5590b245a328aad19c99552e0bdc7f0b04db6656debd80"},- {file = "black-23.9.1-cp311-cp311-macosx_10_16_arm64.whl", hash = "sha256:8431445bf62d2a914b541da7ab3e2b4f3bc052d2ccbf157ebad18ea126efb91f"},- {file = "black-23.9.1-cp311-cp311-macosx_10_16_universal2.whl", hash = "sha256:8fc1ddcf83f996247505db6b715294eba56ea9372e107fd54963c7553f2b6dfe"},- {file = "black-23.9.1-cp311-cp311-macosx_10_16_x86_64.whl", hash = "sha256:7d30ec46de88091e4316b17ae58bbbfc12b2de05e069030f6b747dfc649ad186"},- {file = "black-23.9.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:031e8c69f3d3b09e1aa471a926a1eeb0b9071f80b17689a655f7885ac9325a6f"},- {file = "black-23.9.1-cp311-cp311-win_amd64.whl", hash = "sha256:538efb451cd50f43aba394e9ec7ad55a37598faae3348d723b59ea8e91616300"},- {file = "black-23.9.1-cp38-cp38-macosx_10_16_arm64.whl", hash = "sha256:638619a559280de0c2aa4d76f504891c9860bb8fa214267358f0a20f27c12948"},- {file = "black-23.9.1-cp38-cp38-macosx_10_16_universal2.whl", hash = "sha256:a732b82747235e0542c03bf352c126052c0fbc458d8a239a94701175b17d4855"},- {file = "black-23.9.1-cp38-cp38-macosx_10_16_x86_64.whl", hash = "sha256:cf3a4d00e4cdb6734b64bf23cd4341421e8953615cba6b3670453737a72ec204"},- {file = "black-23.9.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cf99f3de8b3273a8317681d8194ea222f10e0133a24a7548c73ce44ea1679377"},- {file = "black-23.9.1-cp38-cp38-win_amd64.whl", hash = "sha256:14f04c990259576acd093871e7e9b14918eb28f1866f91968ff5524293f9c573"},- {file = "black-23.9.1-cp39-cp39-macosx_10_16_arm64.whl", hash = "sha256:c619f063c2d68f19b2d7270f4cf3192cb81c9ec5bc5ba02df91471d0b88c4c5c"},- {file = "black-23.9.1-cp39-cp39-macosx_10_16_universal2.whl", hash = "sha256:6a3b50e4b93f43b34a9d3ef00d9b6728b4a722c997c99ab09102fd5efdb88325"},- {file = "black-23.9.1-cp39-cp39-macosx_10_16_x86_64.whl", hash = "sha256:c46767e8df1b7beefb0899c4a95fb43058fa8500b6db144f4ff3ca38eb2f6393"},- {file = "black-23.9.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:50254ebfa56aa46a9fdd5d651f9637485068a1adf42270148cd101cdf56e0ad9"},- {file = "black-23.9.1-cp39-cp39-win_amd64.whl", hash = "sha256:403397c033adbc45c2bd41747da1f7fc7eaa44efbee256b53842470d4ac5a70f"},- {file = "black-23.9.1-py3-none-any.whl", hash = "sha256:6ccd59584cc834b6d127628713e4b6b968e5f79572da66284532525a042549f9"},- {file = "black-23.9.1.tar.gz", hash = "sha256:24b6b3ff5c6d9ea08a8888f6977eae858e1f340d7260cf56d70a49823236b62d"},+ {file = "black-23.10.1-cp310-cp310-macosx_10_16_arm64.whl", hash = "sha256:ec3f8e6234c4e46ff9e16d9ae96f4ef69fa328bb4ad08198c8cee45bb1f08c69"},+ {file = "black-23.10.1-cp310-cp310-macosx_10_16_x86_64.whl", hash = "sha256:1b917a2aa020ca600483a7b340c165970b26e9029067f019e3755b56e8dd5916"},+ {file = "black-23.10.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9c74de4c77b849e6359c6f01987e94873c707098322b91490d24296f66d067dc"},+ {file = "black-23.10.1-cp310-cp310-win_amd64.whl", hash = "sha256:7b4d10b0f016616a0d93d24a448100adf1699712fb7a4efd0e2c32bbb219b173"},+ {file = "black-23.10.1-cp311-cp311-macosx_10_16_arm64.whl", hash = "sha256:b15b75fc53a2fbcac8a87d3e20f69874d161beef13954747e053bca7a1ce53a0"},+ {file = "black-23.10.1-cp311-cp311-macosx_10_16_x86_64.whl", hash = "sha256:e293e4c2f4a992b980032bbd62df07c1bcff82d6964d6c9496f2cd726e246ace"},+ {file = "black-23.10.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7d56124b7a61d092cb52cce34182a5280e160e6aff3137172a68c2c2c4b76bcb"},+ {file = "black-23.10.1-cp311-cp311-win_amd64.whl", hash = "sha256:3f157a8945a7b2d424da3335f7ace89c14a3b0625e6593d21139c2d8214d55ce"},+ {file = "black-23.10.1-cp38-cp38-macosx_10_16_arm64.whl", hash = "sha256:cfcce6f0a384d0da692119f2d72d79ed07c7159879d0bb1bb32d2e443382bf3a"},+ {file = "black-23.10.1-cp38-cp38-macosx_10_16_x86_64.whl", hash = "sha256:33d40f5b06be80c1bbce17b173cda17994fbad096ce60eb22054da021bf933d1"},+ {file = "black-23.10.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:840015166dbdfbc47992871325799fd2dc0dcf9395e401ada6d88fe11498abad"},+ {file = "black-23.10.1-cp38-cp38-win_amd64.whl", hash = "sha256:037e9b4664cafda5f025a1728c50a9e9aedb99a759c89f760bd83730e76ba884"},+ {file = "black-23.10.1-cp39-cp39-macosx_10_16_arm64.whl", hash = "sha256:7cb5936e686e782fddb1c73f8aa6f459e1ad38a6a7b0e54b403f1f05a1507ee9"},+ {file = "black-23.10.1-cp39-cp39-macosx_10_16_x86_64.whl", hash = "sha256:7670242e90dc129c539e9ca17665e39a146a761e681805c54fbd86015c7c84f7"},+ {file = "black-23.10.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5ed45ac9a613fb52dad3b61c8dea2ec9510bf3108d4db88422bacc7d1ba1243d"},+ {file = "black-23.10.1-cp39-cp39-win_amd64.whl", hash = "sha256:6d23d7822140e3fef190734216cefb262521789367fbdc0b3f22af6744058982"},+ {file = "black-23.10.1-py3-none-any.whl", hash = "sha256:d431e6739f727bb2e0495df64a6c7a5310758e87505f5f8cde9ff6c0f2d7e4fe"},+ {file = "black-23.10.1.tar.gz", hash = "sha256:1f8ce316753428ff68749c65a5f7844631aa18c8679dfd3ca9dc1a289979c258"},][package.dependencies]@@ -991,7 +987,7 @@ files = [{file = "greenlet-3.0.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:0b72b802496cccbd9b31acea72b6f87e7771ccfd7f7927437d592e5c92ed703c"},{file = "greenlet-3.0.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:527cd90ba3d8d7ae7dceb06fda619895768a46a1b4e423bdb24c1969823b8362"},{file = "greenlet-3.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:37f60b3a42d8b5499be910d1267b24355c495064f271cfe74bf28b17b099133c"},- {file = "greenlet-3.0.0-cp311-universal2-macosx_10_9_universal2.whl", hash = "sha256:c3692ecf3fe754c8c0f2c95ff19626584459eab110eaab66413b1e7425cd84e9"},+ {file = "greenlet-3.0.0-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:1482fba7fbed96ea7842b5a7fc11d61727e8be75a077e603e8ab49d24e234383"},{file = "greenlet-3.0.0-cp312-cp312-macosx_13_0_arm64.whl", hash = "sha256:be557119bf467d37a8099d91fbf11b2de5eb1fd5fc5b91598407574848dc910f"},{file = "greenlet-3.0.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:73b2f1922a39d5d59cc0e597987300df3396b148a9bd10b76a058a2f2772fc04"},{file = "greenlet-3.0.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d1e22c22f7826096ad503e9bb681b05b8c1f5a8138469b255eb91f26a76634f2"},@@ -1001,7 +997,6 @@ files = [{file = "greenlet-3.0.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:952256c2bc5b4ee8df8dfc54fc4de330970bf5d79253c863fb5e6761f00dda35"},{file = "greenlet-3.0.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:269d06fa0f9624455ce08ae0179430eea61085e3cf6457f05982b37fd2cefe17"},{file = "greenlet-3.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:9adbd8ecf097e34ada8efde9b6fec4dd2a903b1e98037adf72d12993a1c80b51"},- {file = "greenlet-3.0.0-cp312-universal2-macosx_10_9_universal2.whl", hash = "sha256:553d6fb2324e7f4f0899e5ad2c427a4579ed4873f42124beba763f16032959af"},{file = "greenlet-3.0.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c6b5ce7f40f0e2f8b88c28e6691ca6806814157ff05e794cdd161be928550f4c"},{file = "greenlet-3.0.0-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ecf94aa539e97a8411b5ea52fc6ccd8371be9550c4041011a091eb8b3ca1d810"},{file = "greenlet-3.0.0-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:80dcd3c938cbcac986c5c92779db8e8ce51a89a849c135172c88ecbdc8c056b7"},@@ -1034,6 +1029,7 @@ files = [{file = "greenlet-3.0.0-cp39-cp39-win32.whl", hash = "sha256:0d3f83ffb18dc57243e0151331e3c383b05e5b6c5029ac29f754745c800f8ed9"},{file = "greenlet-3.0.0-cp39-cp39-win_amd64.whl", hash = "sha256:831d6f35037cf18ca5e80a737a27d822d87cd922521d18ed3dbc8a6967be50ce"},{file = "greenlet-3.0.0-cp39-universal2-macosx_11_0_x86_64.whl", hash = "sha256:a048293392d4e058298710a54dfaefcefdf49d287cd33fb1f7d63d55426e4355"},+ {file = "greenlet-3.0.0.tar.gz", hash = "sha256:19834e3f91f485442adc1ee440171ec5d9a4840a1f7bd5ed97833544719ce10b"},][package.extras]@@ -1631,7 +1627,7 @@ files = [[[package]]name = "langchain"-version = "0.0.306"+version = "0.0.325"description = "Building applications with LLMs through composability"optional = falsepython-versions = ">=3.8.1,<4.0"@@ -1644,7 +1640,7 @@ anyio = "<4.0"async-timeout = {version = "^4.0.0", markers = "python_version < \"3.11\""}dataclasses-json = ">= 0.5.7, < 0.7"jsonpatch = "^1.33"-langsmith = "~0.0.40"+langsmith = "~0.0.52"numpy = "^1"pydantic = ">=1,<3"PyYAML = ">=5.3"@@ -1653,13 +1649,14 @@ SQLAlchemy = ">=1.4,<3"tenacity = "^8.1.0"[package.extras]-all = ["O365 (>=2.0.26,<3.0.0)", "aleph-alpha-client (>=2.15.0,<3.0.0)", "amadeus (>=8.1.0)", "arxiv (>=1.4,<2.0)", "atlassian-python-api (>=3.36.0,<4.0.0)", "awadb (>=0.3.9,<0.4.0)", "azure-ai-formrecognizer (>=3.2.1,<4.0.0)", "azure-ai-vision (>=0.11.1b1,<0.12.0)", "azure-cognitiveservices-speech (>=1.28.0,<2.0.0)", "azure-cosmos (>=4.4.0b1,<5.0.0)", "azure-identity (>=1.12.0,<2.0.0)", "beautifulsoup4 (>=4,<5)", "clarifai (>=9.1.0)", "clickhouse-connect (>=0.5.14,<0.6.0)", "cohere (>=4,<5)", "deeplake (>=3.6.8,<4.0.0)", "docarray[hnswlib] (>=0.32.0,<0.33.0)", "duckduckgo-search (>=3.8.3,<4.0.0)", "elasticsearch (>=8,<9)", "esprima (>=4.0.1,<5.0.0)", "faiss-cpu (>=1,<2)", "google-api-python-client (==2.70.0)", "google-auth (>=2.18.1,<3.0.0)", "google-search-results (>=2,<3)", "gptcache (>=0.1.7)", "html2text (>=2020.1.16,<2021.0.0)", "huggingface_hub (>=0,<1)", "jinja2 (>=3,<4)", "jq (>=1.4.1,<2.0.0)", "lancedb (>=0.1,<0.2)", "langkit (>=0.0.6,<0.1.0)", "lark (>=1.1.5,<2.0.0)", "libdeeplake (>=0.0.60,<0.0.61)", "librosa (>=0.10.0.post2,<0.11.0)", "lxml (>=4.9.2,<5.0.0)", "manifest-ml (>=0.0.1,<0.0.2)", "marqo (>=1.2.4,<2.0.0)", "momento (>=1.5.0,<2.0.0)", "nebula3-python (>=3.4.0,<4.0.0)", "neo4j (>=5.8.1,<6.0.0)", "networkx (>=2.6.3,<4)", "nlpcloud (>=1,<2)", "nltk (>=3,<4)", "nomic (>=1.0.43,<2.0.0)", "openai (>=0,<1)", "openlm (>=0.0.5,<0.0.6)", "opensearch-py (>=2.0.0,<3.0.0)", "pdfminer-six (>=20221105,<20221106)", "pexpect (>=4.8.0,<5.0.0)", "pgvector (>=0.1.6,<0.2.0)", "pinecone-client (>=2,<3)", "pinecone-text (>=0.4.2,<0.5.0)", "psycopg2-binary (>=2.9.5,<3.0.0)", "pymongo (>=4.3.3,<5.0.0)", "pyowm (>=3.3.0,<4.0.0)", "pypdf (>=3.4.0,<4.0.0)", "pytesseract (>=0.3.10,<0.4.0)", "python-arango (>=7.5.9,<8.0.0)", "pyvespa (>=0.33.0,<0.34.0)", "qdrant-client (>=1.3.1,<2.0.0)", "rdflib (>=6.3.2,<7.0.0)", "redis (>=4,<5)", "requests-toolbelt (>=1.0.0,<2.0.0)", "sentence-transformers (>=2,<3)", "singlestoredb (>=0.7.1,<0.8.0)", "tensorflow-text (>=2.11.0,<3.0.0)", "tigrisdb (>=1.0.0b6,<2.0.0)", "tiktoken (>=0.3.2,<0.6.0)", "torch (>=1,<3)", "transformers (>=4,<5)", "weaviate-client (>=3,<4)", "wikipedia (>=1,<2)", "wolframalpha (==5.0.0)"]+all = ["O365 (>=2.0.26,<3.0.0)", "aleph-alpha-client (>=2.15.0,<3.0.0)", "amadeus (>=8.1.0)", "arxiv (>=1.4,<2.0)", "atlassian-python-api (>=3.36.0,<4.0.0)", "awadb (>=0.3.9,<0.4.0)", "azure-ai-formrecognizer (>=3.2.1,<4.0.0)", "azure-ai-vision (>=0.11.1b1,<0.12.0)", "azure-cognitiveservices-speech (>=1.28.0,<2.0.0)", "azure-cosmos (>=4.4.0b1,<5.0.0)", "azure-identity (>=1.12.0,<2.0.0)", "beautifulsoup4 (>=4,<5)", "clarifai (>=9.1.0)", "clickhouse-connect (>=0.5.14,<0.6.0)", "cohere (>=4,<5)", "deeplake (>=3.6.8,<4.0.0)", "docarray[hnswlib] (>=0.32.0,<0.33.0)", "duckduckgo-search (>=3.8.3,<4.0.0)", "elasticsearch (>=8,<9)", "esprima (>=4.0.1,<5.0.0)", "faiss-cpu (>=1,<2)", "google-api-python-client (==2.70.0)", "google-auth (>=2.18.1,<3.0.0)", "google-search-results (>=2,<3)", "gptcache (>=0.1.7)", "html2text (>=2020.1.16,<2021.0.0)", "huggingface_hub (>=0,<1)", "jinja2 (>=3,<4)", "jq (>=1.4.1,<2.0.0)", "lancedb (>=0.1,<0.2)", "langkit (>=0.0.6,<0.1.0)", "lark (>=1.1.5,<2.0.0)", "libdeeplake (>=0.0.60,<0.0.61)", "librosa (>=0.10.0.post2,<0.11.0)", "lxml (>=4.9.2,<5.0.0)", "manifest-ml (>=0.0.1,<0.0.2)", "marqo (>=1.2.4,<2.0.0)", "momento (>=1.10.1,<2.0.0)", "nebula3-python (>=3.4.0,<4.0.0)", "neo4j (>=5.8.1,<6.0.0)", "networkx (>=2.6.3,<4)", "nlpcloud (>=1,<2)", "nltk (>=3,<4)", "nomic (>=1.0.43,<2.0.0)", "openai (>=0,<1)", "openlm (>=0.0.5,<0.0.6)", "opensearch-py (>=2.0.0,<3.0.0)", "pdfminer-six (>=20221105,<20221106)", "pexpect (>=4.8.0,<5.0.0)", "pgvector (>=0.1.6,<0.2.0)", "pinecone-client (>=2,<3)", "pinecone-text (>=0.4.2,<0.5.0)", "psycopg2-binary (>=2.9.5,<3.0.0)", "pymongo (>=4.3.3,<5.0.0)", "pyowm (>=3.3.0,<4.0.0)", "pypdf (>=3.4.0,<4.0.0)", "pytesseract (>=0.3.10,<0.4.0)", "python-arango (>=7.5.9,<8.0.0)", "pyvespa (>=0.33.0,<0.34.0)", "qdrant-client (>=1.3.1,<2.0.0)", "rdflib (>=6.3.2,<7.0.0)", "redis (>=4,<5)", "requests-toolbelt (>=1.0.0,<2.0.0)", "sentence-transformers (>=2,<3)", "singlestoredb (>=0.7.1,<0.8.0)", "tensorflow-text (>=2.11.0,<3.0.0)", "tigrisdb (>=1.0.0b6,<2.0.0)", "tiktoken (>=0.3.2,<0.6.0)", "torch (>=1,<3)", "transformers (>=4,<5)", "weaviate-client (>=3,<4)", "wikipedia (>=1,<2)", "wolframalpha (==5.0.0)"]azure = ["azure-ai-formrecognizer (>=3.2.1,<4.0.0)", "azure-ai-vision (>=0.11.1b1,<0.12.0)", "azure-cognitiveservices-speech (>=1.28.0,<2.0.0)", "azure-core (>=1.26.4,<2.0.0)", "azure-cosmos (>=4.4.0b1,<5.0.0)", "azure-identity (>=1.12.0,<2.0.0)", "azure-search-documents (==11.4.0b8)", "openai (>=0,<1)"]clarifai = ["clarifai (>=9.1.0)"]+cli = ["typer (>=0.9.0,<0.10.0)"]cohere = ["cohere (>=4,<5)"]docarray = ["docarray[hnswlib] (>=0.32.0,<0.33.0)"]embeddings = ["sentence-transformers (>=2,<3)"]-extended-testing = ["amazon-textract-caller (<2)", "anthropic (>=0.3.11,<0.4.0)", "arxiv (>=1.4,<2.0)", "assemblyai (>=0.17.0,<0.18.0)", "atlassian-python-api (>=3.36.0,<4.0.0)", "beautifulsoup4 (>=4,<5)", "bibtexparser (>=1.4.0,<2.0.0)", "cassio (>=0.1.0,<0.2.0)", "chardet (>=5.1.0,<6.0.0)", "dashvector (>=1.0.1,<2.0.0)", "esprima (>=4.0.1,<5.0.0)", "faiss-cpu (>=1,<2)", "feedparser (>=6.0.10,<7.0.0)", "geopandas (>=0.13.1,<0.14.0)", "gitpython (>=3.1.32,<4.0.0)", "gql (>=3.4.1,<4.0.0)", "html2text (>=2020.1.16,<2021.0.0)", "jinja2 (>=3,<4)", "jq (>=1.4.1,<2.0.0)", "lxml (>=4.9.2,<5.0.0)", "markdownify (>=0.11.6,<0.12.0)", "motor (>=3.3.1,<4.0.0)", "mwparserfromhell (>=0.6.4,<0.7.0)", "mwxml (>=0.3.3,<0.4.0)", "newspaper3k (>=0.2.8,<0.3.0)", "numexpr (>=2.8.6,<3.0.0)", "openai (>=0,<1)", "openai (>=0,<1)", "openapi-schema-pydantic (>=1.2,<2.0)", "pandas (>=2.0.1,<3.0.0)", "pdfminer-six (>=20221105,<20221106)", "pgvector (>=0.1.6,<0.2.0)", "psychicapi (>=0.8.0,<0.9.0)", "py-trello (>=0.19.0,<0.20.0)", "pymupdf (>=1.22.3,<2.0.0)", "pypdf (>=3.4.0,<4.0.0)", "pypdfium2 (>=4.10.0,<5.0.0)", "pyspark (>=3.4.0,<4.0.0)", "rank-bm25 (>=0.2.2,<0.3.0)", "rapidfuzz (>=3.1.1,<4.0.0)", "requests-toolbelt (>=1.0.0,<2.0.0)", "scikit-learn (>=1.2.2,<2.0.0)", "sqlite-vss (>=0.1.2,<0.2.0)", "streamlit (>=1.18.0,<2.0.0)", "sympy (>=1.12,<2.0)", "telethon (>=1.28.5,<2.0.0)", "timescale-vector (>=0.0.1,<0.0.2)", "tqdm (>=4.48.0)", "xata (>=1.0.0a7,<2.0.0)", "xmltodict (>=0.13.0,<0.14.0)"]+extended-testing = ["aiosqlite (>=0.19.0,<0.20.0)", "aleph-alpha-client (>=2.15.0,<3.0.0)", "amazon-textract-caller (<2)", "anthropic (>=0.3.11,<0.4.0)", "arxiv (>=1.4,<2.0)", "assemblyai (>=0.17.0,<0.18.0)", "atlassian-python-api (>=3.36.0,<4.0.0)", "beautifulsoup4 (>=4,<5)", "bibtexparser (>=1.4.0,<2.0.0)", "cassio (>=0.1.0,<0.2.0)", "chardet (>=5.1.0,<6.0.0)", "dashvector (>=1.0.1,<2.0.0)", "esprima (>=4.0.1,<5.0.0)", "faiss-cpu (>=1,<2)", "feedparser (>=6.0.10,<7.0.0)", "geopandas (>=0.13.1,<0.14.0)", "gitpython (>=3.1.32,<4.0.0)", "google-cloud-documentai (>=2.20.1,<3.0.0)", "gql (>=3.4.1,<4.0.0)", "html2text (>=2020.1.16,<2021.0.0)", "jinja2 (>=3,<4)", "jq (>=1.4.1,<2.0.0)", "jsonschema (>1)", "lxml (>=4.9.2,<5.0.0)", "markdownify (>=0.11.6,<0.12.0)", "motor (>=3.3.1,<4.0.0)", "mwparserfromhell (>=0.6.4,<0.7.0)", "mwxml (>=0.3.3,<0.4.0)", "newspaper3k (>=0.2.8,<0.3.0)", "numexpr (>=2.8.6,<3.0.0)", "openai (>=0,<1)", "openai (>=0,<1)", "openapi-pydantic (>=0.3.2,<0.4.0)", "pandas (>=2.0.1,<3.0.0)", "pdfminer-six (>=20221105,<20221106)", "pgvector (>=0.1.6,<0.2.0)", "psychicapi (>=0.8.0,<0.9.0)", "py-trello (>=0.19.0,<0.20.0)", "pymupdf (>=1.22.3,<2.0.0)", "pypdf (>=3.4.0,<4.0.0)", "pypdfium2 (>=4.10.0,<5.0.0)", "pyspark (>=3.4.0,<4.0.0)", "rank-bm25 (>=0.2.2,<0.3.0)", "rapidfuzz (>=3.1.1,<4.0.0)", "rapidocr-onnxruntime (>=1.3.2,<2.0.0)", "requests-toolbelt (>=1.0.0,<2.0.0)", "rspace_client (>=2.5.0,<3.0.0)", "scikit-learn (>=1.2.2,<2.0.0)", "sqlite-vss (>=0.1.2,<0.2.0)", "streamlit (>=1.18.0,<2.0.0)", "sympy (>=1.12,<2.0)", "telethon (>=1.28.5,<2.0.0)", "timescale-vector (>=0.0.1,<0.0.2)", "tqdm (>=4.48.0)", "upstash-redis (>=0.15.0,<0.16.0)", "xata (>=1.0.0a7,<2.0.0)", "xmltodict (>=0.13.0,<0.14.0)"]javascript = ["esprima (>=4.0.1,<5.0.0)"]llms = ["clarifai (>=9.1.0)", "cohere (>=4,<5)", "huggingface_hub (>=0,<1)", "manifest-ml (>=0.0.1,<0.0.2)", "nlpcloud (>=1,<2)", "openai (>=0,<1)", "openlm (>=0.0.5,<0.0.6)", "torch (>=1,<3)", "transformers (>=4,<5)"]openai = ["openai (>=0,<1)", "tiktoken (>=0.3.2,<0.6.0)"]@@ -1672,13 +1669,13 @@ url = "libs/langchain"[[package]]name = "langsmith"-version = "0.0.41"+version = "0.0.53"description = "Client library to connect to the LangSmith LLM Tracing and Evaluation Platform."optional = falsepython-versions = ">=3.8.1,<4.0"files = [- {file = "langsmith-0.0.41-py3-none-any.whl", hash = "sha256:a555bef3d51e37bce284090b155e2148ec4098efa96ee918b3092c43c4bfaa77"},- {file = "langsmith-0.0.41.tar.gz", hash = "sha256:ea05649bb140d6e58614e171df6539410b77ce393c23545453278677e916e351"},+ {file = "langsmith-0.0.53-py3-none-any.whl", hash = "sha256:a090b1c7d7968fb8d2476ddd608a5171f0e812a82b1bca29ca136cdea375a74e"},+ {file = "langsmith-0.0.53.tar.gz", hash = "sha256:a426a1d39843207a5dd3d72787b5304376541eb818509ee7909bbb696b072488"},][package.dependencies]@@ -1767,6 +1764,16 @@ files = [{file = "MarkupSafe-2.1.3-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:5bbe06f8eeafd38e5d0a4894ffec89378b6c6a625ff57e3028921f8ff59318ac"},{file = "MarkupSafe-2.1.3-cp311-cp311-win32.whl", hash = "sha256:dd15ff04ffd7e05ffcb7fe79f1b98041b8ea30ae9234aed2a9168b5797c3effb"},{file = "MarkupSafe-2.1.3-cp311-cp311-win_amd64.whl", hash = "sha256:134da1eca9ec0ae528110ccc9e48041e0828d79f24121a1a146161103c76e686"},+ {file = "MarkupSafe-2.1.3-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:f698de3fd0c4e6972b92290a45bd9b1536bffe8c6759c62471efaa8acb4c37bc"},+ {file = "MarkupSafe-2.1.3-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:aa57bd9cf8ae831a362185ee444e15a93ecb2e344c8e52e4d721ea3ab6ef1823"},+ {file = "MarkupSafe-2.1.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ffcc3f7c66b5f5b7931a5aa68fc9cecc51e685ef90282f4a82f0f5e9b704ad11"},+ {file = "MarkupSafe-2.1.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:47d4f1c5f80fc62fdd7777d0d40a2e9dda0a05883ab11374334f6c4de38adffd"},+ {file = "MarkupSafe-2.1.3-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1f67c7038d560d92149c060157d623c542173016c4babc0c1913cca0564b9939"},+ {file = "MarkupSafe-2.1.3-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:9aad3c1755095ce347e26488214ef77e0485a3c34a50c5a5e2471dff60b9dd9c"},+ {file = "MarkupSafe-2.1.3-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:14ff806850827afd6b07a5f32bd917fb7f45b046ba40c57abdb636674a8b559c"},+ {file = "MarkupSafe-2.1.3-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:8f9293864fe09b8149f0cc42ce56e3f0e54de883a9de90cd427f191c346eb2e1"},+ {file = "MarkupSafe-2.1.3-cp312-cp312-win32.whl", hash = "sha256:715d3562f79d540f251b99ebd6d8baa547118974341db04f5ad06d5ea3eb8007"},+ {file = "MarkupSafe-2.1.3-cp312-cp312-win_amd64.whl", hash = "sha256:1b8dd8c3fd14349433c79fa8abeb573a55fc0fdd769133baac1f5e07abf54aeb"},{file = "MarkupSafe-2.1.3-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:8e254ae696c88d98da6555f5ace2279cf7cd5b3f52be2b5cf97feafe883b58d2"},{file = "MarkupSafe-2.1.3-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cb0932dc158471523c9637e807d9bfb93e06a95cbf010f1a38b98623b929ef2b"},{file = "MarkupSafe-2.1.3-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9402b03f1a1b4dc4c19845e5c749e3ab82d5078d16a2a4c2cd2df62d57bb0707"},@@ -2742,6 +2749,7 @@ files = [{file = "PyYAML-6.0.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:69b023b2b4daa7548bcfbd4aa3da05b3a74b772db9e23b982788168117739938"},{file = "PyYAML-6.0.1-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:81e0b275a9ecc9c0c0c07b4b90ba548307583c125f54d5b6946cfee6360c733d"},{file = "PyYAML-6.0.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ba336e390cd8e4d1739f42dfe9bb83a3cc2e80f567d8805e11b46f4a943f5515"},+ {file = "PyYAML-6.0.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:326c013efe8048858a6d312ddd31d56e468118ad4cdeda36c719bf5bb6192290"},{file = "PyYAML-6.0.1-cp310-cp310-win32.whl", hash = "sha256:bd4af7373a854424dabd882decdc5579653d7868b8fb26dc7d0e99f823aa5924"},{file = "PyYAML-6.0.1-cp310-cp310-win_amd64.whl", hash = "sha256:fd1592b3fdf65fff2ad0004b5e363300ef59ced41c2e6b3a99d4089fa8c5435d"},{file = "PyYAML-6.0.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:6965a7bc3cf88e5a1c3bd2e0b5c22f8d677dc88a455344035f03399034eb3007"},@@ -2749,8 +2757,15 @@ files = [{file = "PyYAML-6.0.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:42f8152b8dbc4fe7d96729ec2b99c7097d656dc1213a3229ca5383f973a5ed6d"},{file = "PyYAML-6.0.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:062582fca9fabdd2c8b54a3ef1c978d786e0f6b3a1510e0ac93ef59e0ddae2bc"},{file = "PyYAML-6.0.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d2b04aac4d386b172d5b9692e2d2da8de7bfb6c387fa4f801fbf6fb2e6ba4673"},+ {file = "PyYAML-6.0.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:e7d73685e87afe9f3b36c799222440d6cf362062f78be1013661b00c5c6f678b"},{file = "PyYAML-6.0.1-cp311-cp311-win32.whl", hash = "sha256:1635fd110e8d85d55237ab316b5b011de701ea0f29d07611174a1b42f1444741"},{file = "PyYAML-6.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:bf07ee2fef7014951eeb99f56f39c9bb4af143d8aa3c21b1677805985307da34"},+ {file = "PyYAML-6.0.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:855fb52b0dc35af121542a76b9a84f8d1cd886ea97c84703eaa6d88e37a2ad28"},+ {file = "PyYAML-6.0.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:40df9b996c2b73138957fe23a16a4f0ba614f4c0efce1e9406a184b6d07fa3a9"},+ {file = "PyYAML-6.0.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6c22bec3fbe2524cde73d7ada88f6566758a8f7227bfbf93a408a9d86bcc12a0"},+ {file = "PyYAML-6.0.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:8d4e9c88387b0f5c7d5f281e55304de64cf7f9c0021a3525bd3b1c542da3b0e4"},+ {file = "PyYAML-6.0.1-cp312-cp312-win32.whl", hash = "sha256:d483d2cdf104e7c9fa60c544d92981f12ad66a457afae824d146093b8c294c54"},+ {file = "PyYAML-6.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:0d3304d8c0adc42be59c5f8a4d9e3d7379e6955ad754aa9d6ab7a398b59dd1df"},{file = "PyYAML-6.0.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:50550eb667afee136e9a77d6dc71ae76a44df8b3e51e41b77f6de2932bfe0f47"},{file = "PyYAML-6.0.1-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1fe35611261b29bd1de0070f0b2f47cb6ff71fa6595c077e42bd0c419fa27b98"},{file = "PyYAML-6.0.1-cp36-cp36m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:704219a11b772aea0d8ecd7058d0082713c3562b4e271b849ad7dc4a5c90c13c"},@@ -2767,6 +2782,7 @@ files = [{file = "PyYAML-6.0.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a0cd17c15d3bb3fa06978b4e8958dcdc6e0174ccea823003a106c7d4d7899ac5"},{file = "PyYAML-6.0.1-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:28c119d996beec18c05208a8bd78cbe4007878c6dd15091efb73a30e90539696"},{file = "PyYAML-6.0.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7e07cbde391ba96ab58e532ff4803f79c4129397514e1413a7dc761ccd755735"},+ {file = "PyYAML-6.0.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:49a183be227561de579b4a36efbb21b3eab9651dd81b1858589f796549873dd6"},{file = "PyYAML-6.0.1-cp38-cp38-win32.whl", hash = "sha256:184c5108a2aca3c5b3d3bf9395d50893a7ab82a38004c8f61c258d4428e80206"},{file = "PyYAML-6.0.1-cp38-cp38-win_amd64.whl", hash = "sha256:1e2722cc9fbb45d9b87631ac70924c11d3a401b2d7f410cc0e3bbf249f2dca62"},{file = "PyYAML-6.0.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:9eb6caa9a297fc2c2fb8862bc5370d0303ddba53ba97e71f08023b6cd73d16a8"},@@ -2774,6 +2790,7 @@ files = [{file = "PyYAML-6.0.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5773183b6446b2c99bb77e77595dd486303b4faab2b086e7b17bc6bef28865f6"},{file = "PyYAML-6.0.1-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b786eecbdf8499b9ca1d697215862083bd6d2a99965554781d0d8d1ad31e13a0"},{file = "PyYAML-6.0.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bc1bf2925a1ecd43da378f4db9e4f799775d6367bdb94671027b73b393a7c42c"},+ {file = "PyYAML-6.0.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:04ac92ad1925b2cff1db0cfebffb6ffc43457495c9b3c39d3fcae417d7125dc5"},{file = "PyYAML-6.0.1-cp39-cp39-win32.whl", hash = "sha256:faca3bdcf85b2fc05d06ff3fbc1f83e1391b3e724afa3feba7d13eeab355484c"},{file = "PyYAML-6.0.1-cp39-cp39-win_amd64.whl", hash = "sha256:510c9deebc5c0225e8c96813043e62b680ba2f9c50a08d3724c7f28a747d1486"},{file = "PyYAML-6.0.1.tar.gz", hash = "sha256:bfdf460b1736c775f2ba9f6a92bca30bc2095067b8a9d77876d1fad6cc3b4a43"},@@ -3094,6 +3111,32 @@ files = [{file = "rpds_py-0.10.3.tar.gz", hash = "sha256:fcc1ebb7561a3e24a6588f7c6ded15d80aec22c66a070c757559b57b17ffd1cb"},]+[[package]]+name = "ruff"+version = "0.1.3"+description = "An extremely fast Python linter, written in Rust."+optional = false+python-versions = ">=3.7"+files = [+ {file = "ruff-0.1.3-py3-none-macosx_10_7_x86_64.whl", hash = "sha256:b46d43d51f7061652eeadb426a9e3caa1e0002470229ab2fc19de8a7b0766901"},+ {file = "ruff-0.1.3-py3-none-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl", hash = "sha256:b8afeb9abd26b4029c72adc9921b8363374f4e7edb78385ffaa80278313a15f9"},+ {file = "ruff-0.1.3-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ca3cf365bf32e9ba7e6db3f48a4d3e2c446cd19ebee04f05338bc3910114528b"},+ {file = "ruff-0.1.3-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4874c165f96c14a00590dcc727a04dca0cfd110334c24b039458c06cf78a672e"},+ {file = "ruff-0.1.3-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:eec2dd31eed114e48ea42dbffc443e9b7221976554a504767ceaee3dd38edeb8"},+ {file = "ruff-0.1.3-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:dc3ec4edb3b73f21b4aa51337e16674c752f1d76a4a543af56d7d04e97769613"},+ {file = "ruff-0.1.3-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2e3de9ed2e39160800281848ff4670e1698037ca039bda7b9274f849258d26ce"},+ {file = "ruff-0.1.3-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:1c595193881922cc0556a90f3af99b1c5681f0c552e7a2a189956141d8666fe8"},+ {file = "ruff-0.1.3-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0f75e670d529aa2288cd00fc0e9b9287603d95e1536d7a7e0cafe00f75e0dd9d"},+ {file = "ruff-0.1.3-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:76dd49f6cd945d82d9d4a9a6622c54a994689d8d7b22fa1322983389b4892e20"},+ {file = "ruff-0.1.3-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:918b454bc4f8874a616f0d725590277c42949431ceb303950e87fef7a7d94cb3"},+ {file = "ruff-0.1.3-py3-none-musllinux_1_2_i686.whl", hash = "sha256:d8859605e729cd5e53aa38275568dbbdb4fe882d2ea2714c5453b678dca83784"},+ {file = "ruff-0.1.3-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:0b6c55f5ef8d9dd05b230bb6ab80bc4381ecb60ae56db0330f660ea240cb0d4a"},+ {file = "ruff-0.1.3-py3-none-win32.whl", hash = "sha256:3e7afcbdcfbe3399c34e0f6370c30f6e529193c731b885316c5a09c9e4317eef"},+ {file = "ruff-0.1.3-py3-none-win_amd64.whl", hash = "sha256:7a18df6638cec4a5bd75350639b2bb2a2366e01222825562c7346674bdceb7ea"},+ {file = "ruff-0.1.3-py3-none-win_arm64.whl", hash = "sha256:12fd53696c83a194a2db7f9a46337ce06445fb9aa7d25ea6f293cf75b21aca9f"},+ {file = "ruff-0.1.3.tar.gz", hash = "sha256:3ba6145369a151401d5db79f0a47d50e470384d0d89d0d6f7fab0b589ad07c34"},+]+[[package]]name = "send2trash"version = "1.8.2"@@ -3872,4 +3915,4 @@ testing = ["big-O", "jaraco.functools", "jaraco.itertools", "more-itertools", "p[metadata]lock-version = "2.0"python-versions = ">=3.8.1,<4.0"-content-hash = "eeeb245db6de8d353cbfc59842821a31f6759344834b116df27f3b517ef55d32"+content-hash = "00e7c3ba52c8c852a7470838a48244da94f3b2074f5a122f6cb9f78953489e82"diff --git a/pyproject.toml b/pyproject.tomlindex be315d42e6..1794c515c2 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -28,6 +28,10 @@ linkchecker = "^10.2.1"sphinx-copybutton = "^0.5.1"nbdoc = "^0.0.82"+[tool.poetry.group.lint.dependencies]+ruff = "^0.1"+black = "^23.10.0"+[tool.poetry.group.codespell.dependencies]codespell = "^2.2.0"diff --git a/templates/anthropic-iterative-search/anthropic_iterative_search/agent_scratchpad.py b/templates/anthropic-iterative-search/anthropic_iterative_search/agent_scratchpad.pyindex 209576943f..051253f811 100644--- a/templates/anthropic-iterative-search/anthropic_iterative_search/agent_scratchpad.py+++ b/templates/anthropic-iterative-search/anthropic_iterative_search/agent_scratchpad.py@@ -7,9 +7,10 @@ def _format_docs(docs):)return result+def format_agent_scratchpad(intermediate_steps):thoughts = ""for action, observation in intermediate_steps:thoughts += action.log- thoughts += '</search_query>' + _format_docs(observation)+ thoughts += "</search_query>" + _format_docs(observation)return thoughtsdiff --git a/templates/anthropic-iterative-search/anthropic_iterative_search/chain.py b/templates/anthropic-iterative-search/anthropic_iterative_search/chain.pyindex 7b29a932b5..8299c1e6c7 100644--- a/templates/anthropic-iterative-search/anthropic_iterative_search/chain.py+++ b/templates/anthropic-iterative-search/anthropic_iterative_search/chain.py@@ -10,16 +10,18 @@ prompt = ChatPromptTemplate.from_template(answer_prompt)model = ChatAnthropic(model="claude-2", temperature=0, max_tokens_to_sample=1000)-chain = {- "query": lambda x: x["query"],- "information": executor | (lambda x: x["output"])-} | prompt | model | StrOutputParser()+chain = (+ {"query": lambda x: x["query"], "information": executor | (lambda x: x["output"])}+ | prompt+ | model+ | StrOutputParser()+)# Add typing for the inputs to be used in the playgroundclass Inputs(BaseModel):- query: str+ query: strchain = chain.with_types(input_type=Inputs)diff --git a/templates/anthropic-iterative-search/anthropic_iterative_search/retriever_agent.py b/templates/anthropic-iterative-search/anthropic_iterative_search/retriever_agent.pyindex 1ee01f34c7..81d4fb3cbb 100644--- a/templates/anthropic-iterative-search/anthropic_iterative_search/retriever_agent.py+++ b/templates/anthropic-iterative-search/anthropic_iterative_search/retriever_agent.py@@ -9,21 +9,33 @@ from .output_parser import parse_outputfrom .prompts import retrieval_promptfrom .retriever import retriever_description, search-prompt = ChatPromptTemplate.from_messages([- ("user", retrieval_prompt),- ("ai", "{agent_scratchpad}"),-])+prompt = ChatPromptTemplate.from_messages(+ [+ ("user", retrieval_prompt),+ ("ai", "{agent_scratchpad}"),+ ]+)prompt = prompt.partial(retriever_description=retriever_description)model = ChatAnthropic(model="claude-2", temperature=0, max_tokens_to_sample=1000)-chain = RunnablePassthrough.assign(- agent_scratchpad=lambda x: format_agent_scratchpad(x['intermediate_steps'])-) | prompt | model.bind( stop_sequences=['</search_query>']) | StrOutputParser()+chain = (+ RunnablePassthrough.assign(+ agent_scratchpad=lambda x: format_agent_scratchpad(x["intermediate_steps"])+ )+ | prompt+ | model.bind(stop_sequences=["</search_query>"])+ | StrOutputParser()+)-agent_chain = RunnableMap({- "partial_completion": chain,- "intermediate_steps": lambda x: x['intermediate_steps']-}) | parse_output+agent_chain = (+ RunnableMap(+ {+ "partial_completion": chain,+ "intermediate_steps": lambda x: x["intermediate_steps"],+ }+ )+ | parse_output+)-executor = AgentExecutor(agent=agent_chain, tools = [search], verbose=True)+executor = AgentExecutor(agent=agent_chain, tools=[search], verbose=True)diff --git a/templates/cassandra-entomology-rag/cassandra_entomology_rag/__init__.py b/templates/cassandra-entomology-rag/cassandra_entomology_rag/__init__.pyindex 6af8acd87d..79846e4cc8 100644--- a/templates/cassandra-entomology-rag/cassandra_entomology_rag/__init__.py+++ b/templates/cassandra-entomology-rag/cassandra_entomology_rag/__init__.py@@ -11,6 +11,7 @@ from langchain.vectorstores import Cassandrause_cassandra = int(os.environ.get("USE_CASSANDRA_CLUSTER", "0"))if use_cassandra:from .cassandra_cluster_init import get_cassandra_connection+session, keyspace = get_cassandra_connection()cassio.init(session=session,@@ -33,7 +34,7 @@ vector_store = Cassandra(embedding=embeddings,table_name="langserve_rag_demo",)-retriever = vector_store.as_retriever(search_kwargs={'k': 3})+retriever = vector_store.as_retriever(search_kwargs={"k": 3})entomology_template = """You are an expert entomologist, tasked with answering enthusiast biologists' questions.@@ -53,8 +54,8 @@ YOUR ANSWER:"""entomology_prompt = ChatPromptTemplate.from_template(entomology_template)chain = (- {"context": retriever, "question": RunnablePassthrough()}- | entomology_prompt- | llm+ {"context": retriever, "question": RunnablePassthrough()}+ | entomology_prompt+ | llm| StrOutputParser()-)\ No newline at end of file+)diff --git a/templates/cassandra-synonym-caching/cassandra_synonym_caching/__init__.py b/templates/cassandra-synonym-caching/cassandra_synonym_caching/__init__.pyindex 575ea10879..cbb666ae4f 100644--- a/templates/cassandra-synonym-caching/cassandra_synonym_caching/__init__.py+++ b/templates/cassandra-synonym-caching/cassandra_synonym_caching/__init__.py@@ -11,6 +11,7 @@ from langchain.schema.runnable import RunnableLambdause_cassandra = int(os.environ.get("USE_CASSANDRA_CLUSTER", "0"))if use_cassandra:from .cassandra_cluster_init import get_cassandra_connection+session, keyspace = get_cassandra_connection()cassio.init(session=session,@@ -27,13 +28,11 @@ else:langchain.llm_cache = CassandraCache(session=None, keyspace=None)llm = ChatOpenAI()+# custom runnablesdef msg_splitter(msg: BaseMessage):- return [- w.strip()- for w in msg.content.split(",")- if w.strip()- ]+ return [w.strip() for w in msg.content.split(",") if w.strip()]+# synonym-route preparationsynonym_prompt = ChatPromptTemplate.from_template(diff --git a/templates/csv-agent/csv_agent/agent.py b/templates/csv-agent/csv_agent/agent.pyindex 6927cd7806..4aa4694b89 100644--- a/templates/csv-agent/csv_agent/agent.py+++ b/templates/csv-agent/csv_agent/agent.py@@ -72,7 +72,7 @@ agent = OpenAIFunctionsAgent()agent_executor = AgentExecutor(agent=agent, tools=tools, max_iterations=5, early_stopping_method="generate"-)| (lambda x: x["output"])+) | (lambda x: x["output"])# Typing for playground inputsdiff --git a/templates/csv-agent/ingest.py b/templates/csv-agent/ingest.pyindex 7da5942f17..8cc99a9a8a 100644--- a/templates/csv-agent/ingest.py+++ b/templates/csv-agent/ingest.py@@ -2,7 +2,7 @@ from langchain.document_loaders import CSVLoaderfrom langchain.indexes import VectorstoreIndexCreatorfrom langchain.vectorstores import FAISS-loader = CSVLoader('/Users/harrisonchase/Downloads/titanic.csv')+loader = CSVLoader("/Users/harrisonchase/Downloads/titanic.csv")docs = loader.load()index_creator = VectorstoreIndexCreator(vectorstore_cls=FAISS)diff --git a/templates/elastic-query-generator/elastic_query_generator/chain.py b/templates/elastic-query-generator/elastic_query_generator/chain.pyindex 0e29b35967..f72a6c3007 100644--- a/templates/elastic-query-generator/elastic_query_generator/chain.py+++ b/templates/elastic-query-generator/elastic_query_generator/chain.py@@ -16,10 +16,7 @@ ELASTIC_PASSWORD = "..."CLOUD_ID = "..."# Create the client instance-db = Elasticsearch(- cloud_id=CLOUD_ID,- basic_auth=("elastic", ELASTIC_PASSWORD)-)+db = Elasticsearch(cloud_id=CLOUD_ID, basic_auth=("elastic", ELASTIC_PASSWORD))# Specify indices to include# If you want to use on your own indices, you will need to change this.@@ -29,13 +26,20 @@ INCLUDE_INDICES = ["customers"]_model = ChatOpenAI(temperature=0, model="gpt-4")-chain = {- "input": lambda x: x["input"],- # This line only get index info for "customers" index.- # If you are running this on your own data, you will want to change.- "indices_info": lambda _: get_indices_infos(db, include_indices=INCLUDE_INDICES),- "top_k": lambda x: x.get("top_k", 5),-} | DSL_PROMPT | _model | SimpleJsonOutputParser()+chain = (+ {+ "input": lambda x: x["input"],+ # This line only get index info for "customers" index.+ # If you are running this on your own data, you will want to change.+ "indices_info": lambda _: get_indices_infos(+ db, include_indices=INCLUDE_INDICES+ ),+ "top_k": lambda x: x.get("top_k", 5),+ }+ | DSL_PROMPT+ | _model+ | SimpleJsonOutputParser()+)# Nicely typed inputs for playgrounddiff --git a/templates/elastic-query-generator/elastic_query_generator/elastic_index_info.py b/templates/elastic-query-generator/elastic_query_generator/elastic_index_info.pyindex 91c33ca8df..15884f476e 100644--- a/templates/elastic-query-generator/elastic_query_generator/elastic_index_info.py+++ b/templates/elastic-query-generator/elastic_query_generator/elastic_index_info.py@@ -2,9 +2,7 @@ from typing import Listdef _list_indices(database, include_indices=None, ignore_indices=None) -> List[str]:- all_indices = [- index["index"] for index in database.cat.indices(format="json")- ]+ all_indices = [index["index"] for index in database.cat.indices(format="json")]if include_indices:all_indices = [i for i in all_indices if i in include_indices]@@ -15,15 +13,13 @@ def _list_indices(database, include_indices=None, ignore_indices=None) -> List[sdef get_indices_infos(- database,- sample_documents_in_index_info=5,- include_indices=None,- ignore_indices=None+ database,+ sample_documents_in_index_info=5,+ include_indices=None,+ ignore_indices=None,) -> str:indices = _list_indices(- database,- include_indices=include_indices,- ignore_indices=ignore_indices+ database, include_indices=include_indices, ignore_indices=ignore_indices)mappings = database.indices.get_mapping(index=",".join(indices))if sample_documents_in_index_info > 0:@@ -40,4 +36,4 @@ def get_indices_infos("Mapping for index {}:\n{}".format(index, mappings[index]["mappings"])for index in mappings]- )\ No newline at end of file+ )diff --git a/templates/elastic-query-generator/ingest.py b/templates/elastic-query-generator/ingest.pyindex a3b64938c7..7f8dabd3cd 100644--- a/templates/elastic-query-generator/ingest.py+++ b/templates/elastic-query-generator/ingest.py@@ -10,17 +10,14 @@ ELASTIC_PASSWORD = "..."CLOUD_ID = "..."# Create the client instance-db = Elasticsearch(- cloud_id=CLOUD_ID,- basic_auth=("elastic", ELASTIC_PASSWORD)-)+db = Elasticsearch(cloud_id=CLOUD_ID, basic_auth=("elastic", ELASTIC_PASSWORD))customers = [{"firstname": "Jennifer", "lastname": "Walters"},- {"firstname": "Monica","lastname":"Rambeau"},- {"firstname": "Carol","lastname":"Danvers"},- {"firstname": "Wanda","lastname":"Maximoff"},- {"firstname": "Jennifer","lastname":"Takeda"},+ {"firstname": "Monica", "lastname": "Rambeau"},+ {"firstname": "Carol", "lastname": "Danvers"},+ {"firstname": "Wanda", "lastname": "Maximoff"},+ {"firstname": "Jennifer", "lastname": "Takeda"},]for i, customer in enumerate(customers):db.create(index="customers", document=customer, id=i)diff --git a/templates/extraction-anthropic-functions/extraction_anthropic_functions.ipynb b/templates/extraction-anthropic-functions/extraction_anthropic_functions.ipynbindex 2204b91ff6..23f300ec6c 100644--- a/templates/extraction-anthropic-functions/extraction_anthropic_functions.ipynb+++ b/templates/extraction-anthropic-functions/extraction_anthropic_functions.ipynb@@ -18,6 +18,7 @@"outputs": [],"source": ["from langchain.document_loaders import WebBaseLoader\n",+ "\n","loader = WebBaseLoader(\"https://lilianweng.github.io/posts/2023-06-23-agent/\")\n","text = loader.load()"]@@ -54,7 +55,10 @@"outputs": [],"source": ["from langserve.client import RemoteRunnable\n",- "anthropic_function_model = RemoteRunnable('http://localhost:8000/extraction-anthropic-functions')\n",+ "\n",+ "anthropic_function_model = RemoteRunnable(\n",+ " \"http://localhost:8000/extraction-anthropic-functions\"\n",+ ")\n","anthropic_function_model.invoke(text[0].page_content[0:1500])"]}diff --git a/templates/extraction-anthropic-functions/extraction_anthropic_functions/chain.py b/templates/extraction-anthropic-functions/extraction_anthropic_functions/chain.pyindex ff43134630..4aab096651 100644--- a/templates/extraction-anthropic-functions/extraction_anthropic_functions/chain.py+++ b/templates/extraction-anthropic-functions/extraction_anthropic_functions/chain.py@@ -33,6 +33,8 @@ class Info(BaseModel):model = AnthropicFunctions()function = [convert_pydantic_to_openai_function(Info)]-chain = prompt | model.bind(- functions=function, function_call={"name": "Info"}-) | JsonKeyOutputFunctionsParser(key_name="papers")+chain = (+ prompt+ | model.bind(functions=function, function_call={"name": "Info"})+ | JsonKeyOutputFunctionsParser(key_name="papers")+)diff --git a/templates/extraction-openai-functions/extraction_openai_functions.ipynb b/templates/extraction-openai-functions/extraction_openai_functions.ipynbindex a69a767c1f..8544f41366 100644--- a/templates/extraction-openai-functions/extraction_openai_functions.ipynb+++ b/templates/extraction-openai-functions/extraction_openai_functions.ipynb@@ -18,6 +18,7 @@"outputs": [],"source": ["from langchain.document_loaders import WebBaseLoader\n",+ "\n","loader = WebBaseLoader(\"https://lilianweng.github.io/posts/2023-06-23-agent/\")\n","text = loader.load()"]@@ -43,7 +44,8 @@"outputs": [],"source": ["from langserve.client import RemoteRunnable\n",- "oai_function = RemoteRunnable('http://0.0.0.0:8001/extraction_openai_functions')"+ "\n",+ "oai_function = RemoteRunnable(\"http://0.0.0.0:8001/extraction_openai_functions\")"]},{@@ -74,7 +76,7 @@}],"source": [- "oai_function.invoke({\"input\":text[0].page_content[0:4000]})"+ "oai_function.invoke({\"input\": text[0].page_content[0:4000]})"]}],diff --git a/templates/llama2-functions/llama2-functions.ipynb b/templates/llama2-functions/llama2-functions.ipynbindex 1a99cd01d0..e84c60a149 100644--- a/templates/llama2-functions/llama2-functions.ipynb+++ b/templates/llama2-functions/llama2-functions.ipynb@@ -19,6 +19,7 @@"outputs": [],"source": ["from langchain.document_loaders import WebBaseLoader\n",+ "\n","loader = WebBaseLoader(\"https://lilianweng.github.io/posts/2023-06-23-agent/\")\n","text = loader.load()"]@@ -45,8 +46,9 @@"outputs": [],"source": ["from langserve.client import RemoteRunnable\n",- "llama2_function = RemoteRunnable('http://0.0.0.0:8001/llama2_functions')\n",- "llama2_function.invoke({\"input\":text[0].page_content[0:1500]})"+ "\n",+ "llama2_function = RemoteRunnable(\"http://0.0.0.0:8001/llama2_functions\")\n",+ "llama2_function.invoke({\"input\": text[0].page_content[0:1500]})"]}],diff --git a/templates/llama2-functions/llama2_functions/__init__.py b/templates/llama2-functions/llama2_functions/__init__.pyindex 9bc6a86a2c..6b64bab82b 100644--- a/templates/llama2-functions/llama2_functions/__init__.py+++ b/templates/llama2-functions/llama2_functions/__init__.py@@ -1,3 +1,3 @@from llama2_functions.chain import chain-__all__ = ["chain"]\ No newline at end of file+__all__ = ["chain"]diff --git a/templates/llama2-functions/llama2_functions/chain.py b/templates/llama2-functions/llama2_functions/chain.pyindex 0a377f8a08..9dd66e9e1c 100644--- a/templates/llama2-functions/llama2_functions/chain.py+++ b/templates/llama2-functions/llama2_functions/chain.py@@ -5,9 +5,7 @@ from langchain.prompts import ChatPromptTemplatereplicate_id = "andreasjansson/llama-2-13b-chat-gguf:60ec5dda9ff9ee0b6f786c9d1157842e6ab3cc931139ad98fe99e08a35c5d4d4" # noqa: E501model = Replicate(model=replicate_id,- model_kwargs={"temperature": 0.8,- "max_length": 500,- "top_p": 0.95},+ model_kwargs={"temperature": 0.8, "max_length": 500, "top_p": 0.95},)# Prompt with output schema specification@@ -39,7 +37,4 @@ Respond with json that adheres to the following jsonschema:prompt = ChatPromptTemplate.from_messages([("system", template), ("human", "{input}")])# Chain-chain = (- prompt- | model-)\ No newline at end of file+chain = prompt | modeldiff --git a/templates/neo4j-cypher-ft/ingest.py b/templates/neo4j-cypher-ft/ingest.pyindex 98f43aff40..5668604fa2 100644--- a/templates/neo4j-cypher-ft/ingest.py+++ b/templates/neo4j-cypher-ft/ingest.py@@ -2,7 +2,7 @@ from langchain.graphs import Neo4jGraphgraph = Neo4jGraph()-# Import sample data+# Import sample datagraph.query("""MERGE (m:Movie {name:"Top Gun"})diff --git a/templates/neo4j-parent/main.py b/templates/neo4j-parent/main.pyindex 1c1b772d52..ac52947e3f 100644--- a/templates/neo4j-parent/main.py+++ b/templates/neo4j-parent/main.py@@ -1,5 +1,5 @@from neo4j_parent.chain import chainif __name__ == "__main__":- original_query = "What is the plot of the Dune?"- print(chain.invoke(original_query))+ original_query = "What is the plot of the Dune?"+ print(chain.invoke(original_query))diff --git a/templates/neo4j-parent/neo4j_parent/chain.py b/templates/neo4j-parent/neo4j_parent/chain.pyindex 60ed5fed53..ca38c565a3 100644--- a/templates/neo4j-parent/neo4j_parent/chain.py+++ b/templates/neo4j-parent/neo4j_parent/chain.py@@ -16,8 +16,7 @@ vectorstore = Neo4jVector.from_existing_index(index_name="retrieval",node_label="Child",embedding_node_property="embedding",- retrieval_query=retrieval_query-+ retrieval_query=retrieval_query,)retriever = vectorstore.as_retriever()@@ -37,8 +36,10 @@ chain = (| StrOutputParser())+# Add typing for inputclass Question(BaseModel):__root__: str+chain = chain.with_types(input_type=Question)diff --git a/templates/plate-chain/plate_chain/__init__.py b/templates/plate-chain/plate_chain/__init__.pyindex fca5d6ef21..f4e66c6f09 100644--- a/templates/plate-chain/plate_chain/__init__.py+++ b/templates/plate-chain/plate_chain/__init__.py@@ -1,2 +1 @@-__ALL__ = ["chain"]diff --git a/templates/plate-chain/plate_chain/chain.py b/templates/plate-chain/plate_chain/chain.pyindex f8042af228..7a0aa0edcc 100644--- a/templates/plate-chain/plate_chain/chain.py+++ b/templates/plate-chain/plate_chain/chain.py@@ -40,15 +40,16 @@ class FileProcessingRequest(CustomUserType):def _load_file(request: FileProcessingRequest):- return base64.b64decode(request.file.encode("utf-8")).decode('utf-8')+ return base64.b64decode(request.file.encode("utf-8")).decode("utf-8")def _load_prompt(request: FileProcessingRequest):return create_prompt(- num_plates=request.num_plates,- num_rows=request.num_rows,- num_cols=request.num_cols,- )+ num_plates=request.num_plates,+ num_rows=request.num_rows,+ num_cols=request.num_cols,+ )+def _get_col_range_str(request: FileProcessingRequest):if request.num_cols:@@ -70,6 +71,7 @@ def _get_json_format(request: FileProcessingRequest):])+chain = ({# Should add validation to ensure numeric indices@@ -77,12 +79,8 @@ chain = ("hint": _load_prompt,"col_range_str": _get_col_range_str,"json_format": _get_json_format,- "user_example": lambda x: USER_EXAMPLE_DICT[- x.num_rows * x.num_cols- ],- "ai_response": lambda x: AI_REPONSE_DICT[- x.num_rows * x.num_cols- ],+ "user_example": lambda x: USER_EXAMPLE_DICT[x.num_rows * x.num_cols],+ "ai_response": lambda x: AI_REPONSE_DICT[x.num_rows * x.num_cols],}| prompt| llmdiff --git a/templates/rag-aws-bedrock/main.py b/templates/rag-aws-bedrock/main.pyindex 081f5c5d98..d0a3c2f48c 100644--- a/templates/rag-aws-bedrock/main.py+++ b/templates/rag-aws-bedrock/main.py@@ -3,4 +3,4 @@ from rag_aws_bedrock.chain import chainif __name__ == "__main__":query = "What is this data about?"- print(chain.invoke(query))\ No newline at end of file+ print(chain.invoke(query))diff --git a/templates/rag-aws-bedrock/rag_aws_bedrock.ipynb b/templates/rag-aws-bedrock/rag_aws_bedrock.ipynbindex 349a38dc10..0cb2d628fb 100644--- a/templates/rag-aws-bedrock/rag_aws_bedrock.ipynb+++ b/templates/rag-aws-bedrock/rag_aws_bedrock.ipynb@@ -21,7 +21,8 @@"outputs": [],"source": ["from langserve.client import RemoteRunnable\n",- "rag_app_pinecone = RemoteRunnable('http://0.0.0.0:8001/rag_aws_bedrock')\n",+ "\n",+ "rag_app_pinecone = RemoteRunnable(\"http://0.0.0.0:8001/rag_aws_bedrock\")\n","rag_app_pinecone.invoke(\"What are the different types of agent memory\")"]}diff --git a/templates/rag-aws-bedrock/rag_aws_bedrock/chain.py b/templates/rag-aws-bedrock/rag_aws_bedrock/chain.pyindex d2a5e02ffa..6ff1c18502 100644--- a/templates/rag-aws-bedrock/rag_aws_bedrock/chain.py+++ b/templates/rag-aws-bedrock/rag_aws_bedrock/chain.py@@ -17,16 +17,13 @@ model = Bedrock(model_id="anthropic.claude-v2",region_name=region,credentials_profile_name=profile,- model_kwargs={'max_tokens_to_sample':200}-)-bedrock_embeddings = BedrockEmbeddings(- model_id="amazon.titan-embed-text-v1"+ model_kwargs={"max_tokens_to_sample": 200},)+bedrock_embeddings = BedrockEmbeddings(model_id="amazon.titan-embed-text-v1")# Add to vectorDBvectorstore = FAISS.from_texts(- ["harrison worked at kensho"],- embedding=bedrock_embeddings+ ["harrison worked at kensho"], embedding=bedrock_embeddings)retriever = vectorstore.as_retriever()@@ -49,8 +46,10 @@ chain = (| StrOutputParser())+# Add typing for inputclass Question(BaseModel):__root__: str+chain = chain.with_types(input_type=Question)diff --git a/templates/rag-aws-kendra/main.py b/templates/rag-aws-kendra/main.pyindex 66a070eb80..ceb1daa7af 100644--- a/templates/rag-aws-kendra/main.py+++ b/templates/rag-aws-kendra/main.py@@ -3,4 +3,4 @@ from rag_aws_kendra.chain import chainif __name__ == "__main__":query = "Does Kendra support table extraction?"- print(chain.invoke(query))\ No newline at end of file+ print(chain.invoke(query))diff --git a/templates/rag-aws-kendra/rag_aws_kendra/chain.py b/templates/rag-aws-kendra/rag_aws_kendra/chain.pyindex f4be90a6d1..d07a2a4539 100644--- a/templates/rag-aws-kendra/rag_aws_kendra/chain.py+++ b/templates/rag-aws-kendra/rag_aws_kendra/chain.py@@ -23,15 +23,11 @@ model = Bedrock(model_id="anthropic.claude-v2",region_name=region,credentials_profile_name=profile,- model_kwargs={'max_tokens_to_sample': 200}+ model_kwargs={"max_tokens_to_sample": 200},)# Create Kendra retriever-retriever = AmazonKendraRetriever(- index_id=kendra_index,- top_k=5,- region_name=region-)+retriever = AmazonKendraRetriever(index_id=kendra_index, top_k=5, region_name=region)# RAG prompttemplate = """Answer the question based only on the following context:@@ -49,8 +45,10 @@ chain = (| StrOutputParser())+# Add typing for inputclass Question(BaseModel):__root__: str+chain = chain.with_types(input_type=Question)diff --git a/templates/rag-chroma-private/rag_chroma_private.ipynb b/templates/rag-chroma-private/rag_chroma_private.ipynbindex 8903cb1156..b3a969c721 100644--- a/templates/rag-chroma-private/rag_chroma_private.ipynb+++ b/templates/rag-chroma-private/rag_chroma_private.ipynb@@ -21,7 +21,8 @@"outputs": [],"source": ["from langserve.client import RemoteRunnable\n",- "rag_app = RemoteRunnable('http://0.0.0.0:8001/rag_chroma_private/')\n",+ "\n",+ "rag_app = RemoteRunnable(\"http://0.0.0.0:8001/rag_chroma_private/\")\n","for item in rag_app.stream(\"How does agent memory work?\"):\n"," print(item)"]diff --git a/templates/rag-chroma-private/rag_chroma_private/chain.py b/templates/rag-chroma-private/rag_chroma_private/chain.pyindex b207d06033..9a5d4d70b0 100644--- a/templates/rag-chroma-private/rag_chroma_private/chain.py+++ b/templates/rag-chroma-private/rag_chroma_private/chain.py@@ -51,8 +51,10 @@ chain = (| StrOutputParser())+# Add typing for inputclass Question(BaseModel):__root__: str+chain = chain.with_types(input_type=Question)diff --git a/templates/rag-chroma/rag_chroma.ipynb b/templates/rag-chroma/rag_chroma.ipynbindex 5e0b45d5d4..a9c458b5ba 100644--- a/templates/rag-chroma/rag_chroma.ipynb+++ b/templates/rag-chroma/rag_chroma.ipynb@@ -32,7 +32,8 @@"outputs": [],"source": ["from langserve.client import RemoteRunnable\n",- "rag_app = RemoteRunnable('http://localhost:8000/rag-chroma')\n",+ "\n",+ "rag_app = RemoteRunnable(\"http://localhost:8000/rag-chroma\")\n","rag_app.invoke(\"Where id Harrison work\")"]}diff --git a/templates/rag-chroma/rag_chroma/chain.py b/templates/rag-chroma/rag_chroma/chain.pyindex 5e4b0aa8e1..dd6f319ef8 100644--- a/templates/rag-chroma/rag_chroma/chain.py+++ b/templates/rag-chroma/rag_chroma/chain.py@@ -8,7 +8,7 @@ from langchain.vectorstores import Chroma# Example for document loading (from url), splitting, and creating vectostore-'''+"""# Loadfrom langchain.document_loaders import WebBaseLoaderloader = WebBaseLoader("https://lilianweng.github.io/posts/2023-06-23-agent/")@@ -25,13 +25,13 @@ vectorstore = Chroma.from_documents(documents=all_splits,embedding=OpenAIEmbeddings(),)retriever = vectorstore.as_retriever()-'''+"""# Embed a single document as a testvectorstore = Chroma.from_texts(- ["harrison worked at kensho"],+ ["harrison worked at kensho"],collection_name="rag-chroma",- embedding=OpenAIEmbeddings()+ embedding=OpenAIEmbeddings(),)retriever = vectorstore.as_retriever()@@ -54,9 +54,10 @@ chain = (| StrOutputParser())+# Add typing for inputclass Question(BaseModel):__root__: str-chain = chain.with_types(input_type=Question)+chain = chain.with_types(input_type=Question)diff --git a/templates/rag-conversation/rag_conversation.ipynb b/templates/rag-conversation/rag_conversation.ipynbindex 49fbec7fec..f07b9dab12 100644--- a/templates/rag-conversation/rag_conversation.ipynb+++ b/templates/rag-conversation/rag_conversation.ipynb@@ -21,7 +21,8 @@"outputs": [],"source": ["from langserve.client import RemoteRunnable\n",- "rag_app = RemoteRunnable('http://0.0.0.0:8001/rag_conversation')"+ "\n",+ "rag_app = RemoteRunnable(\"http://0.0.0.0:8001/rag_conversation\")"]},{@@ -32,10 +33,12 @@"outputs": [],"source": ["question = \"How does agent memory work?\"\n",- "answer = rag_app.invoke({\n",- " \"question\": question,\n",- " \"chat_history\": [],\n",- "})"+ "answer = rag_app.invoke(\n",+ " {\n",+ " \"question\": question,\n",+ " \"chat_history\": [],\n",+ " }\n",+ ")"]},{@@ -67,10 +70,12 @@"outputs": [],"source": ["chat_history = [(question, answer)]\n",- "answer = rag_app.invoke({\n",- " \"question\": \"What are the different types?\",\n",- " \"chat_history\": chat_history,\n",- "})"+ "answer = rag_app.invoke(\n",+ " {\n",+ " \"question\": \"What are the different types?\",\n",+ " \"chat_history\": chat_history,\n",+ " }\n",+ ")"]},{diff --git a/templates/rag-fusion/main.py b/templates/rag-fusion/main.pyindex 642b48eaa3..ed32889561 100644--- a/templates/rag-fusion/main.py+++ b/templates/rag-fusion/main.py@@ -1,5 +1,5 @@from rag_fusion.chain import chainif __name__ == "__main__":- original_query = "impact of climate change"- print(chain.invoke(original_query))+ original_query = "impact of climate change"+ print(chain.invoke(original_query))diff --git a/templates/rag-pinecone-multi-query/rag_pinecone_multi_query.ipynb b/templates/rag-pinecone-multi-query/rag_pinecone_multi_query.ipynbindex 3f54f3e199..b1474820ad 100644--- a/templates/rag-pinecone-multi-query/rag_pinecone_multi_query.ipynb+++ b/templates/rag-pinecone-multi-query/rag_pinecone_multi_query.ipynb@@ -33,7 +33,8 @@],"source": ["from langserve.client import RemoteRunnable\n",- "rag_app_pinecone = RemoteRunnable('http://0.0.0.0:8001/rag_pinecone_multi_query')\n",+ "\n",+ "rag_app_pinecone = RemoteRunnable(\"http://0.0.0.0:8001/rag_pinecone_multi_query\")\n","rag_app_pinecone.invoke(\"What are the different types of agent memory\")"]}diff --git a/templates/rag-pinecone-rerank/rag_pinecone_rerank.ipynb b/templates/rag-pinecone-rerank/rag_pinecone_rerank.ipynbindex f61b47c358..3ddccd24ea 100644--- a/templates/rag-pinecone-rerank/rag_pinecone_rerank.ipynb+++ b/templates/rag-pinecone-rerank/rag_pinecone_rerank.ipynb@@ -28,7 +28,8 @@],"source": ["from langserve.client import RemoteRunnable\n",- "rag_app_pinecone = RemoteRunnable('http://localhost:8001/rag_pinecone_rerank')\n",+ "\n",+ "rag_app_pinecone = RemoteRunnable(\"http://localhost:8001/rag_pinecone_rerank\")\n","rag_app_pinecone.invoke(\"How does agent memory work?\")"]}diff --git a/templates/rag-pinecone/rag_pinecone.ipynb b/templates/rag-pinecone/rag_pinecone.ipynbindex e6f1f5dca1..3361f28bad 100644--- a/templates/rag-pinecone/rag_pinecone.ipynb+++ b/templates/rag-pinecone/rag_pinecone.ipynb@@ -21,7 +21,8 @@"outputs": [],"source": ["from langserve.client import RemoteRunnable\n",- "rag_app_pinecone = RemoteRunnable('http://0.0.0.0:8001/rag_pinecone')\n",+ "\n",+ "rag_app_pinecone = RemoteRunnable(\"http://0.0.0.0:8001/rag_pinecone\")\n","rag_app_pinecone.invoke(\"How does agent memory work?\")"]}diff --git a/templates/rag-redis/ingest.py b/templates/rag-redis/ingest.pyindex 5d84182723..6e056c10fa 100644--- a/templates/rag-redis/ingest.py+++ b/templates/rag-redis/ingest.py@@ -15,9 +15,7 @@ def ingest_documents():# Load list of pdfscompany_name = "Nike"data_path = "data/"- doc = [- os.path.join(data_path, file) for file in os.listdir(data_path)- ][0]+ doc = [os.path.join(data_path, file) for file in os.listdir(data_path)][0]print("Parsing 10k filing doc for NIKE", doc)@@ -29,9 +27,7 @@ def ingest_documents():print("Done preprocessing. Created", len(chunks), "chunks of the original pdf")# Create vectorstore- embedder = HuggingFaceEmbeddings(- model_name=EMBED_MODEL- )+ embedder = HuggingFaceEmbeddings(model_name=EMBED_MODEL)_ = Redis.from_texts(# appending this little bit can sometimes help with semantic retrieval@@ -41,7 +37,7 @@ def ingest_documents():embedding=embedder,index_name=INDEX_NAME,index_schema=INDEX_SCHEMA,- redis_url=REDIS_URL+ redis_url=REDIS_URL,)diff --git a/templates/rag-redis/rag_redis.ipynb b/templates/rag-redis/rag_redis.ipynbindex 941b4241f0..bb3f87a8c6 100644--- a/templates/rag-redis/rag_redis.ipynb+++ b/templates/rag-redis/rag_redis.ipynb@@ -32,7 +32,7 @@"source": ["from langserve.client import RemoteRunnable\n","\n",- "rag_redis = RemoteRunnable('http://localhost:8000/rag-redis')\n",+ "rag_redis = RemoteRunnable(\"http://localhost:8000/rag-redis\")\n","\n","print(rag_redis.invoke(\"What was Nike's revenue in 2023?\"))"]diff --git a/templates/rag-redis/rag_redis/chain.py b/templates/rag-redis/rag_redis/chain.pyindex a7a0445292..df78737a2e 100644--- a/templates/rag-redis/rag_redis/chain.py+++ b/templates/rag-redis/rag_redis/chain.py@@ -1,4 +1,3 @@-from langchain.chat_models import ChatOpenAIfrom langchain.embeddings import HuggingFaceEmbeddingsfrom langchain.prompts import ChatPromptTemplate@@ -26,10 +25,7 @@ embedder = HuggingFaceEmbeddings(model_name=EMBED_MODEL)# Connect to pre-loaded vectorstore# run the ingest.py script to populate thisvectorstore = Redis.from_existing_index(- embedding=embedder,- index_name=INDEX_NAME,- schema=INDEX_SCHEMA,- redis_url=REDIS_URL+ embedding=embedder, index_name=INDEX_NAME, schema=INDEX_SCHEMA, redis_url=REDIS_URL)# TODO allow user to change parametersretriever = vectorstore.as_retriever(search_type="mmr")@@ -60,8 +56,7 @@ prompt = ChatPromptTemplate.from_template(template)# RAG Chainmodel = ChatOpenAI(model_name="gpt-3.5-turbo-16k")chain = (- RunnableParallel({"context": retriever,- "question": RunnablePassthrough()})+ RunnableParallel({"context": retriever, "question": RunnablePassthrough()})| prompt| model| StrOutputParser()diff --git a/templates/rag-redis/rag_redis/config.py b/templates/rag-redis/rag_redis/config.pyindex ba6818d86c..306448b817 100644--- a/templates/rag-redis/rag_redis/config.py+++ b/templates/rag-redis/rag_redis/config.py@@ -12,11 +12,11 @@ def get_boolean_env_var(var_name, default_value=False):Returns:bool: The value of the environment variable, interpreted as a boolean."""- true_values = {'true', '1', 't', 'y', 'yes'}- false_values = {'false', '0', 'f', 'n', 'no'}+ true_values = {"true", "1", "t", "y", "yes"}+ false_values = {"false", "0", "f", "n", "no"}# Retrieve the environment variable's value- value = os.getenv(var_name, '').lower()+ value = os.getenv(var_name, "").lower()# Decide the boolean value based on the content of the stringif value in true_values:@@ -37,17 +37,18 @@ DEBUG = get_boolean_env_var("DEBUG", False)# Set DEBUG env var to "true" if you wish to enable LC debugging moduleif DEBUG:import langchain- langchain.debug=True++ langchain.debug = True# Embedding model-EMBED_MODEL = os.getenv("EMBED_MODEL",- "sentence-transformers/all-MiniLM-L6-v2")+EMBED_MODEL = os.getenv("EMBED_MODEL", "sentence-transformers/all-MiniLM-L6-v2")# Redis Connection InformationREDIS_HOST = os.getenv("REDIS_HOST", "localhost")REDIS_PORT = int(os.getenv("REDIS_PORT", 6379))+def format_redis_conn_from_env():redis_url = os.getenv("REDIS_URL", None)if redis_url:@@ -64,6 +65,7 @@ def format_redis_conn_from_env():return start + f"{REDIS_HOST}:{REDIS_PORT}"+REDIS_URL = format_redis_conn_from_env()# Vector Index Configuration@@ -72,5 +74,5 @@ INDEX_NAME = os.getenv("INDEX_NAME", "rag-redis")current_file_path = os.path.abspath(__file__)parent_dir = os.path.dirname(current_file_path)-schema_path = os.path.join(parent_dir, 'schema.yml')+schema_path = os.path.join(parent_dir, "schema.yml")INDEX_SCHEMA = schema_pathdiff --git a/templates/rag-semi-structured/rag_semi_structured.ipynb b/templates/rag-semi-structured/rag_semi_structured.ipynbindex 3d66ab75f8..9760547616 100644--- a/templates/rag-semi-structured/rag_semi_structured.ipynb+++ b/templates/rag-semi-structured/rag_semi_structured.ipynb@@ -32,7 +32,8 @@"outputs": [],"source": ["from langserve.client import RemoteRunnable\n",- "rag_app = RemoteRunnable('http://localhost:8000/rag-chroma-private')\n",+ "\n",+ "rag_app = RemoteRunnable(\"http://localhost:8000/rag-chroma-private\")\n","rag_app.invoke(\"How does agent memory work?\")"]}diff --git a/templates/rag-weaviate/rag_weaviate.ipynb b/templates/rag-weaviate/rag_weaviate.ipynbindex efbf039abb..11416f01b1 100644--- a/templates/rag-weaviate/rag_weaviate.ipynb+++ b/templates/rag-weaviate/rag_weaviate.ipynb@@ -22,6 +22,7 @@"outputs": [],"source": ["from langserve.client import RemoteRunnable\n",+ "\n","rag_app_weaviate = RemoteRunnable(\"http://localhost:8000/rag-weaviate\")\n","rag_app_weaviate.invoke(\"How does agent memory work?\")"]diff --git a/templates/rag-weaviate/rag_weaviate/__init__.py b/templates/rag-weaviate/rag_weaviate/__init__.pyindex e0360502fb..a1483502d6 100644--- a/templates/rag-weaviate/rag_weaviate/__init__.py+++ b/templates/rag-weaviate/rag_weaviate/__init__.py@@ -1,3 +1,3 @@from rag_weaviate.chain import chain-__all__ = ["chain"]\ No newline at end of file+__all__ = ["chain"]diff --git a/templates/rag-weaviate/rag_weaviate/chain.py b/templates/rag-weaviate/rag_weaviate/chain.pyindex b8b45cd649..fef8019730 100644--- a/templates/rag-weaviate/rag_weaviate/chain.py+++ b/templates/rag-weaviate/rag_weaviate/chain.py@@ -28,7 +28,7 @@ all_splits = text_splitter.split_documents(data)# # Add to vectorDBvectorstore = Weaviate.from_documents(- documents=all_splits, embedding=OpenAIEmbeddings(), index_name=WEAVIATE_INDEX_NAME+ documents=all_splits, embedding=OpenAIEmbeddings(), index_name=WEAVIATE_INDEX_NAME)retriever = vectorstore.as_retriever()@@ -49,4 +49,4 @@ chain = (| prompt| model| StrOutputParser()-)\ No newline at end of file+)diff --git a/templates/rewrite-retrieve-read/rewrite_retrieve_read/chain.py b/templates/rewrite-retrieve-read/rewrite_retrieve_read/chain.pyindex 4b8d06d16c..1ead011f0d 100644--- a/templates/rewrite-retrieve-read/rewrite_retrieve_read/chain.py+++ b/templates/rewrite-retrieve-read/rewrite_retrieve_read/chain.py@@ -23,6 +23,7 @@ search = DuckDuckGoSearchAPIWrapper()def retriever(query):return search.run(query)+template = """Provide a better search query for \web search engine to answer the given question, end \the queries with ’**’. Question: \@@ -31,19 +32,28 @@ rewrite_prompt = ChatPromptTemplate.from_template(template)# Parser to remove the `**`+def _parse(text):return text.strip("**")+rewriter = rewrite_prompt | ChatOpenAI(temperature=0) | StrOutputParser() | _parse-chain = {- "context": {"x": RunnablePassthrough()} | rewriter | retriever,- "question": RunnablePassthrough()- } | prompt | model | StrOutputParser()+chain = (+ {+ "context": {"x": RunnablePassthrough()} | rewriter | retriever,+ "question": RunnablePassthrough(),+ }+ | prompt+ | model+ | StrOutputParser()+)# Add input type for playground+class Question(BaseModel):__root__: str+chain = chain.with_types(input_type=Question)diff --git a/templates/sql-llama2/sql_llama2.ipynb b/templates/sql-llama2/sql_llama2.ipynbindex a8991bf946..51c0d76410 100644--- a/templates/sql-llama2/sql_llama2.ipynb+++ b/templates/sql-llama2/sql_llama2.ipynb@@ -36,7 +36,8 @@],"source": ["from langserve.client import RemoteRunnable\n",- "sql_app = RemoteRunnable('http://0.0.0.0:8001/sql_llama2')\n",+ "\n",+ "sql_app = RemoteRunnable(\"http://0.0.0.0:8001/sql_llama2\")\n","sql_app.invoke({\"question\": \"What team is Klay Thompson on?\"})"]}diff --git a/templates/sql-llama2/sql_llama2/__init__.py b/templates/sql-llama2/sql_llama2/__init__.pyindex efd92085ab..a1340c49ff 100644--- a/templates/sql-llama2/sql_llama2/__init__.py+++ b/templates/sql-llama2/sql_llama2/__init__.py@@ -1,3 +1,3 @@from sql_llama2.chain import chain-__all__ = ["chain"]\ No newline at end of file+__all__ = ["chain"]diff --git a/templates/sql-llama2/sql_llama2/chain.py b/templates/sql-llama2/sql_llama2/chain.pyindex 7651cc3701..d81bed0dc4 100644--- a/templates/sql-llama2/sql_llama2/chain.py+++ b/templates/sql-llama2/sql_llama2/chain.py@@ -20,6 +20,7 @@ rel = db_path.relative_to(Path.cwd())db_string = f"sqlite:///{rel}"db = SQLDatabase.from_uri(db_string, sample_rows_in_table_info=0)+def get_schema(_):return db.get_table_info()@@ -27,6 +28,7 @@ def get_schema(_):def run_query(query):return db.run(query)+template_query = """Based on the table schema below, write a SQL query that would answer the user's question:{schema}@@ -64,10 +66,12 @@ prompt_response = ChatPromptTemplate.from_messages(])-# Supply the input types to the prompt++# Supply the input types to the promptclass InputType(BaseModel):question: str+chain = (RunnablePassthrough.assign(query=sql_response).with_types(input_type=InputType)| RunnablePassthrough.assign(diff --git a/templates/sql-llamacpp/sql-llamacpp.ipynb b/templates/sql-llamacpp/sql-llamacpp.ipynbindex 412177f9c1..deb3fe2d84 100644--- a/templates/sql-llamacpp/sql-llamacpp.ipynb+++ b/templates/sql-llamacpp/sql-llamacpp.ipynb@@ -36,7 +36,8 @@],"source": ["from langserve.client import RemoteRunnable\n",- "sql_app = RemoteRunnable('http://0.0.0.0:8001/sql_llamacpp')\n",+ "\n",+ "sql_app = RemoteRunnable(\"http://0.0.0.0:8001/sql_llamacpp\")\n","sql_app.invoke({\"question\": \"What team is Klay Thompson on?\"})"]}diff --git a/templates/sql-llamacpp/sql_llamacpp/__init__.py b/templates/sql-llamacpp/sql_llamacpp/__init__.pyindex 7a48c32848..ce4ab36435 100644--- a/templates/sql-llamacpp/sql_llamacpp/__init__.py+++ b/templates/sql-llamacpp/sql_llamacpp/__init__.py@@ -1,3 +1,3 @@from sql_llamacpp.chain import chain-__all__ = ["chain"]\ No newline at end of file+__all__ = ["chain"]diff --git a/templates/sql-llamacpp/sql_llamacpp/chain.py b/templates/sql-llamacpp/sql_llamacpp/chain.pyindex e7ff025f4f..9a62faf396 100644--- a/templates/sql-llamacpp/sql_llamacpp/chain.py+++ b/templates/sql-llamacpp/sql_llamacpp/chain.py@@ -13,8 +13,10 @@ from langchain.utilities import SQLDatabase# File name and URLfile_name = "mistral-7b-instruct-v0.1.Q4_K_M.gguf"-url = ("https://huggingface.co/TheBloke/Mistral-7B-Instruct-v0.1-GGUF/resolve/main/"- "mistral-7b-instruct-v0.1.Q4_K_M.gguf")+url = (+ "https://huggingface.co/TheBloke/Mistral-7B-Instruct-v0.1-GGUF/resolve/main/"+ "mistral-7b-instruct-v0.1.Q4_K_M.gguf"+)# Check if file is present in the current directoryif not os.path.exists(file_name):print(f"'{file_name}' not found. Downloading...")@@ -114,12 +116,17 @@ prompt_response = ChatPromptTemplate.from_messages(("human", template),])-# Supply the input types to the prompt+++# Supply the input types to the promptclass InputType(BaseModel):question: str+chain = (- RunnablePassthrough.assign(query=sql_response_memory).with_types(input_type=InputType)+ RunnablePassthrough.assign(query=sql_response_memory).with_types(+ input_type=InputType+ )| RunnablePassthrough.assign(schema=get_schema,response=lambda x: db.run(x["query"]),diff --git a/templates/sql-ollama/sql-ollama.ipynb b/templates/sql-ollama/sql-ollama.ipynbindex 6498e051c7..0c086a20d1 100644--- a/templates/sql-ollama/sql-ollama.ipynb+++ b/templates/sql-ollama/sql-ollama.ipynb@@ -36,7 +36,8 @@],"source": ["from langserve.client import RemoteRunnable\n",- "sql_app = RemoteRunnable('http://0.0.0.0:8001/sql_ollama')\n",+ "\n",+ "sql_app = RemoteRunnable(\"http://0.0.0.0:8001/sql_ollama\")\n","sql_app.invoke({\"question\": \"What team is Klay Thompson on?\"})"]}diff --git a/templates/sql-ollama/sql_ollama/__init__.py b/templates/sql-ollama/sql_ollama/__init__.pyindex 25bdf9683f..c3d1ef029b 100644--- a/templates/sql-ollama/sql_ollama/__init__.py+++ b/templates/sql-ollama/sql_ollama/__init__.py@@ -1,3 +1,3 @@from sql_ollama.chain import chain-__all__ = ["chain"]\ No newline at end of file+__all__ = ["chain"]diff --git a/templates/sql-ollama/sql_ollama/chain.py b/templates/sql-ollama/sql_ollama/chain.pyindex 45e5b2b3e4..a2dfd71626 100644--- a/templates/sql-ollama/sql_ollama/chain.py+++ b/templates/sql-ollama/sql_ollama/chain.py@@ -83,12 +83,16 @@ prompt_response = ChatPromptTemplate.from_messages(])-# Supply the input types to the prompt++# Supply the input types to the promptclass InputType(BaseModel):question: str+chain = (- RunnablePassthrough.assign(query=sql_response_memory).with_types(input_type=InputType)+ RunnablePassthrough.assign(query=sql_response_memory).with_types(+ input_type=InputType+ )| RunnablePassthrough.assign(schema=get_schema,response=lambda x: db.run(x["query"]),diff --git a/templates/summarize-anthropic/summarize_anthropic.ipynb b/templates/summarize-anthropic/summarize_anthropic.ipynbindex 008b6f74b0..95d7c20bdc 100644--- a/templates/summarize-anthropic/summarize_anthropic.ipynb+++ b/templates/summarize-anthropic/summarize_anthropic.ipynb@@ -53,6 +53,7 @@"import arxiv\n","from langchain.chat_models import ChatAnthropic\n","from langchain.document_loaders import ArxivLoader, UnstructuredPDFLoader\n",+ "\n","# Load a paper to use\n","paper = next(arxiv.Search(query=\"Visual Instruction Tuning\").results())\n","paper.download_pdf(filename=\"downloaded-paper.pdf\")\n",@@ -76,6 +77,7 @@"outputs": [],"source": ["from langchain.document_loaders import WebBaseLoader\n",+ "\n","loader = WebBaseLoader(\"https://lilianweng.github.io/posts/2023-06-23-agent/\")\n","text = loader.load()"]@@ -151,8 +153,9 @@],"source": ["from langserve.client import RemoteRunnable\n",- "summarization = RemoteRunnable('http://localhost:8000/summarize-anthropic')\n",- "summarization.invoke({\"text\":doc.page_content})"+ "\n",+ "summarization = RemoteRunnable(\"http://localhost:8000/summarize-anthropic\")\n",+ "summarization.invoke({\"text\": doc.page_content})"]}],diff --git a/templates/summarize-anthropic/summarize_anthropic/chain.py b/templates/summarize-anthropic/summarize_anthropic/chain.pyindex e2b6dae385..80a809c637 100644--- a/templates/summarize-anthropic/summarize_anthropic/chain.py+++ b/templates/summarize-anthropic/summarize_anthropic/chain.py@@ -5,4 +5,4 @@ from langchain.schema.output_parser import StrOutputParser# Create chainprompt = hub.pull("hwchase17/anthropic-paper-qa")model = ChatAnthropic(model="claude-2", max_tokens=10000)-chain = prompt | model | StrOutputParser()\ No newline at end of file+chain = prompt | model | StrOutputParser()