Skip to main content
Ctrl+K

🦜🔗 LangChain 0.0.139

Getting Started

  • 入门指南

Modules

  • Models(模型)
    • LLMs (大语言模型)
      • Getting Started
      • 通用功能
        • 如何使用 LLM 的异步 API
        • 如何写一个自定义的LLM包装器
        • How (and why) to use the fake LLM
        • How to cache LLM calls
        • How to serialize LLM classes
        • 如何实现 LLM 和 Chat Model 的流式响应
        • How to track token usage
      • Integrations
        • AI21
        • Aleph Alpha
        • Anthropic
        • Azure OpenAI LLM Example
        • Banana
        • CerebriumAI LLM Example
        • Cohere
        • DeepInfra LLM Example
        • ForefrontAI LLM Example
        • GooseAI LLM Example
        • GPT4All
        • Hugging Face Hub
        • Llama-cpp
        • Manifest
        • Modal
        • OpenAI
        • Petals LLM Example
        • PromptLayer OpenAI
        • Replicate
        • SageMakerEndpoint
        • Self-Hosted Models via Runhouse
        • StochasticAI
        • Writer
      • Reference
    • Chat Models
      • Getting Started
      • How-To Guides
        • How to use few shot examples
        • How to stream responses
      • Integrations
        • Azure
        • OpenAI
        • PromptLayer ChatOpenAI
    • Text Embedding Models
      • Aleph Alpha
      • AzureOpenAI
      • Cohere
      • Fake Embeddings
      • Hugging Face Hub
      • InstructEmbeddings
      • Jina
      • Llama-cpp
      • OpenAI
      • SageMaker Endpoint Embeddings
      • Self Hosted Embeddings
      • TensorflowHub
  • Prompts
    • Prompt Templates
      • Getting Started
      • How-To Guides
        • How to create a custom prompt template
        • How to create a prompt template that uses few shot examples
        • How to work with partial Prompt Templates
        • How to serialize prompts
      • Reference
        • PromptTemplates
        • Example Selector
    • Chat Prompt Template
    • Example Selectors
      • How to create a custom example selector
      • LengthBased ExampleSelector
      • Maximal Marginal Relevance ExampleSelector
      • NGram Overlap ExampleSelector
      • Similarity ExampleSelector
    • Output Parsers
      • Output Parsers
      • CommaSeparatedListOutputParser
      • OutputFixingParser
      • PydanticOutputParser
      • RetryOutputParser
      • Structured Output Parser
  • Indexes
    • Getting Started
    • Document Loaders
      • CoNLL-U
      • Airbyte JSON
      • Apify Dataset
      • AZLyrics
      • Azure Blob Storage Container
      • Azure Blob Storage File
      • BigQuery Loader
      • Bilibili
      • Blackboard
      • College Confidential
      • Copy Paste
      • CSV Loader
      • DataFrame Loader
      • Directory Loader
      • DuckDB Loader
      • Email
      • EPubs
      • EverNote
      • Facebook Chat
      • Figma
      • GCS Directory
      • GCS File Storage
      • Git
      • GitBook
      • Google Drive
      • Gutenberg
      • Hacker News
      • HTML
      • iFixit
      • Images
      • IMSDb
      • Markdown
      • Notebook
      • Notion
      • Notion DB Loader
      • Obsidian
      • PDF
      • PowerPoint
      • ReadTheDocs Documentation
      • Roam
      • s3 Directory
      • s3 File
      • Sitemap Loader
      • Slack (Local Exported Zipfile)
      • Subtitle Files
      • Telegram
      • Unstructured File Loader
      • URL
      • Web Base
      • WhatsApp Chat
      • Word Documents
      • YouTube
    • Text Splitters
      • Getting Started
      • Character Text Splitter
      • Hugging Face Length Function
      • Latex Text Splitter
      • Markdown Text Splitter
      • NLTK Text Splitter
      • Python Code Text Splitter
      • RecursiveCharacterTextSplitter
      • Spacy Text Splitter
      • tiktoken (OpenAI) Length Function
      • TiktokenText Splitter
    • Vectorstores
      • Getting Started
      • AtlasDB
      • Chroma
      • Deep Lake
      • ElasticSearch
      • FAISS
      • Milvus
      • OpenSearch
      • PGVector
      • Pinecone
      • Qdrant
      • Redis
      • Weaviate
      • Zilliz
    • Retrievers
      • ChatGPT Plugin Retriever
      • Databerry
      • ElasticSearch BM25
      • Metal
      • Pinecone Hybrid Search
      • TF-IDF Retriever
      • VectorStore Retriever
      • Weaviate Hybrid Search
  • Memory
    • Getting Started
    • How-To Guides
      • ConversationBufferMemory
      • ConversationBufferWindowMemory
      • Entity Memory
      • Conversation Knowledge Graph Memory
      • ConversationSummaryMemory
      • ConversationSummaryBufferMemory
      • ConversationTokenBufferMemory
      • VectorStore-Backed Memory
      • 如何给 LLM Chain(大语言模型链)添加 Memeory(记忆)
      • How to add memory to a Multi-Input Chain
      • How to add Memory to an Agent
      • 给Agent(代理)添加由数据库支持的消息存储
      • How to customize conversational memory
      • How to create a custom Memory class
      • Motörhead Memory
      • How to use multiple memory classes in the same chain
      • Postgres Chat Message History
      • Redis Chat Message History
  • Chains
    • Getting Started
    • How-To Guides
      • Async API for Chain
      • Loading from LangChainHub
      • LLM Chain
      • Sequential Chains
      • Serialization
      • Transformation Chain
      • Analyze Document
      • Chat Over Documents with Chat History
      • Graph QA
      • Hypothetical Document Embeddings
      • Question Answering with Sources
      • Question Answering
      • Summarization
      • Retrieval Question/Answering
      • Retrieval Question Answering with Sources
      • Vector DB Text Generation
      • API Chains
      • Self-Critique Chain with Constitutional AI
      • BashChain
      • LLMCheckerChain
      • LLM Math
      • LLMRequestsChain
      • LLMSummarizationCheckerChain
      • Moderation
      • OpenAPI Chain
      • PAL
      • SQL Chain example
    • Reference
  • Agents
    • Getting Started
    • Tools
      • Getting Started
      • Defining Custom Tools
      • Multi-Input Tools
      • Apify
      • Bash
      • Bing Search
      • ChatGPT Plugins
      • Google Search
      • Google Serper API
      • Human as a tool
      • IFTTT WebHooks
      • OpenWeatherMap API
      • Python REPL
      • Requests
      • Search Tools
      • SearxNG Search API
      • SerpAPI
      • Wikipedia API
      • Wolfram Alpha
      • Zapier Natural Language Actions API
    • Agents
      • Agent Types
      • Custom Agent
      • Custom LLM Agent
      • Custom LLM Agent (with a ChatModel)
      • Custom MRKL Agent
      • Custom MultiAction Agent
      • Custom Agent with Tool Retrieval
      • Conversation Agent (for Chat Models)
      • Conversation Agent
      • MRKL
      • MRKL Chat
      • ReAct
      • Self Ask With Search
    • Toolkits
      • CSV Agent
      • JSON Agent
      • OpenAPI agents
      • Natural Language APIs
      • Pandas Dataframe Agent
      • Python Agent
      • SQL Database Agent
      • Vectorstore Agent
    • Agent Executors
      • How to combine agents and vectorstores
      • How to use the async API for Agents
      • How to create ChatGPT Clone
      • How to access intermediate steps
      • How to cap the max number of iterations
      • How to use a timeout for the agent
      • How to add SharedMemory to an Agent and its Tools

Use Cases

  • Personal Assistants (Agents)
  • Question Answering over Docs
  • Chatbots
  • Querying Tabular Data
  • Code Understanding
  • Interacting with APIs
  • Summarization
  • Extraction
  • Evaluation
    • Agent Benchmarking: Search + Calculator
    • Agent VectorDB Question Answering Benchmarking
    • Benchmarking Template
    • Data Augmented Question Answering
    • Using Hugging Face Datasets
    • LLM Math
    • Evaluating an OpenAPI Chain
    • Question Answering Benchmarking: Paul Graham Essay
    • Question Answering Benchmarking: State of the Union Address
    • QA Generation
    • Question Answering
    • SQL Question Answering Benchmarking: Chinook

Reference

  • Installation
  • Integrations
  • API References
    • Prompts
      • PromptTemplates
      • Example Selector
    • Utilities
      • Python REPL
      • SerpAPI
      • SearxNG Search
      • Docstore
      • Text Splitter
      • Embeddings
      • VectorStores
    • Chains
    • Agents

Ecosystem

  • LangChain Ecosystem
    • AI21 Labs
    • Aim
    • Apify
    • AtlasDB
    • Banana
    • CerebriumAI
    • Chroma
    • ClearML Integration
    • Cohere
    • Comet
    • Databerry
    • DeepInfra
    • Deep Lake
    • ForefrontAI
    • Google Search Wrapper
    • Google Serper Wrapper
    • GooseAI
    • GPT4All
    • Graphsignal
    • Hazy Research
    • Helicone
    • Hugging Face
    • Jina
    • Llama.cpp
    • Milvus
    • Modal
    • NLPCloud
    • OpenAI
    • OpenSearch
    • Petals
    • PGVector
    • Pinecone
    • PromptLayer
    • Qdrant
    • Replicate
    • Runhouse
    • RWKV-4
    • SearxNG Search API
    • SerpAPI
    • StochasticAI
    • Unstructured
    • Weights & Biases
    • Weaviate
    • Wolfram Alpha Wrapper
    • Writer
    • Zilliz

Additional Resources

  • LangChainHub
  • Glossary
  • LangChain Gallery
  • Deployments
  • Tracing
  • Discord
  • Production Support
  • .ipynb

Pinecone Hybrid Search

Contents

  • Setup Pinecone
  • Get embeddings and sparse encoders
  • Load Retriever
  • Add texts (if necessary)
  • Use Retriever

Pinecone Hybrid Search#

This notebook goes over how to use a retriever that under the hood uses Pinecone and Hybrid Search.

The logic of this retriever is taken from this documentaion

from langchain.retrievers import PineconeHybridSearchRetriever

Setup Pinecone#

You should only have to do this part once.

Note: it’s important to make sure that the “context” field that holds the document text in the metadata is not indexed. Currently you need to specify explicitly the fields you do want to index. For more information checkout Pinecone’s docs.

import os
import pinecone

api_key = os.getenv("PINECONE_API_KEY") or "PINECONE_API_KEY"
# find environment next to your API key in the Pinecone console
env = os.getenv("PINECONE_ENVIRONMENT") or "PINECONE_ENVIRONMENT"

index_name = "langchain-pinecone-hybrid-search"

pinecone.init(api_key=api_key, enviroment=env)
pinecone.whoami()
WhoAmIResponse(username='load', user_label='label', projectname='load-test')
 # create the index
pinecone.create_index(
   name = index_name,
   dimension = 1536,  # dimensionality of dense model
   metric = "dotproduct",  # sparse values supported only for dotproduct
   pod_type = "s1",
   metadata_config={"indexed": []}  # see explaination above
)

Now that its created, we can use it

index = pinecone.Index(index_name)

Get embeddings and sparse encoders#

Embeddings are used for the dense vectors, tokenizer is used for the sparse vector

from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()

To encode the text to sparse values you can either choose SPLADE or BM25. For out of domain tasks we recommend using BM25.

For more information about the sparse encoders you can checkout pinecone-text library docs.

from pinecone_text.sparse import BM25Encoder
# or from pinecone_text.sparse import SpladeEncoder if you wish to work with SPLADE

# use default tf-idf values
bm25_encoder = BM25Encoder().default()

The above code is using default tfids values. It’s highly recommended to fit the tf-idf values to your own corpus. You can do it as follow:

corpus = ["foo", "bar", "world", "hello"]

# fit tf-idf values on your corpus
bm25_encoder.fit(corpus)

# store the values to a json file
bm25_encoder.dump("bm25_values.json")

# load to your BM25Encoder object
bm25_encoder = BM25Encoder().load("bm25_values.json")

Load Retriever#

We can now construct the retriever!

retriever = PineconeHybridSearchRetriever(embeddings=embeddings, sparse_encoder=bm25_encoder, index=index)

Add texts (if necessary)#

We can optionally add texts to the retriever (if they aren’t already in there)

retriever.add_texts(["foo", "bar", "world", "hello"])
100%|██████████| 1/1 [00:02<00:00,  2.27s/it]

Use Retriever#

We can now use the retriever!

result = retriever.get_relevant_documents("foo")
result[0]
Document(page_content='foo', metadata={})

previous

Metal

next

TF-IDF Retriever

Contents
  • Setup Pinecone
  • Get embeddings and sparse encoders
  • Load Retriever
  • Add texts (if necessary)
  • Use Retriever

By Harrison Chase

© Copyright 2023, Harrison Chase.

Last updated on Apr 18, 2023.