mirror of https://github.com/hwchase17/langchain
Template for Ollama + Multi-query retriever (#14092)
parent
75312c3694
commit
b07a5a9509
@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 LangChain, Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
@ -0,0 +1,83 @@
|
||||
|
||||
# rag-ollama-multi-query
|
||||
|
||||
This template performs RAG using Ollama and OpenAI with a multi-query retriever.
|
||||
|
||||
The multi-query retriever is an example of query transformation, generating multiple queries from different perspectives based on the user's input query.
|
||||
|
||||
For each query, it retrieves a set of relevant documents and takes the unique union across all queries for answer synthesis.
|
||||
|
||||
We use a private, local LLM for the narrow task of query generation to avoid excessive calls to a larger LLM API.
|
||||
|
||||
See an example trace for Ollama LLM performing the query expansion [here](https://smith.langchain.com/public/8017d04d-2045-4089-b47f-f2d66393a999/r).
|
||||
|
||||
But we use OpenAI for the more challenging task of answer syntesis (full trace example [here](https://smith.langchain.com/public/ec75793b-645b-498d-b855-e8d85e1f6738/r)).
|
||||
|
||||
## Environment Setup
|
||||
|
||||
To set up the environment, you need to download Ollama.
|
||||
|
||||
Follow the instructions [here](https://python.langchain.com/docs/integrations/chat/ollama).
|
||||
|
||||
You can choose the desired LLM with Ollama.
|
||||
|
||||
This template uses `zephyr`, which can be accessed using `ollama pull zephyr`.
|
||||
|
||||
There are many other options available [here](https://ollama.ai/library).
|
||||
|
||||
Set the `OPENAI_API_KEY` environment variable to access the OpenAI models.
|
||||
|
||||
## Usage
|
||||
|
||||
To use this package, you should first install the LangChain CLI:
|
||||
|
||||
```shell
|
||||
pip install -U langchain-cli
|
||||
```
|
||||
|
||||
To create a new LangChain project and install this package, do:
|
||||
|
||||
```shell
|
||||
langchain app new my-app --package rag-ollama-multi-query
|
||||
```
|
||||
|
||||
To add this package to an existing project, run:
|
||||
|
||||
```shell
|
||||
langchain app add rag-ollama-multi-query
|
||||
```
|
||||
|
||||
And add the following code to your `server.py` file:
|
||||
|
||||
```python
|
||||
from rag_ollama_multi_query import chain as rag_ollama_multi_query_chain
|
||||
|
||||
add_routes(app, rag_ollama_multi_query_chain, path="/rag-ollama-multi-query")
|
||||
```
|
||||
|
||||
(Optional) Now, let's configure LangSmith. LangSmith will help us trace, monitor, and debug LangChain applications. LangSmith is currently in private beta, you can sign up [here](https://smith.langchain.com/). If you don't have access, you can skip this section
|
||||
|
||||
```shell
|
||||
export LANGCHAIN_TRACING_V2=true
|
||||
export LANGCHAIN_API_KEY=<your-api-key>
|
||||
export LANGCHAIN_PROJECT=<your-project> # if not specified, defaults to "default"
|
||||
```
|
||||
|
||||
If you are inside this directory, then you can spin up a LangServe instance directly by:
|
||||
|
||||
```shell
|
||||
langchain serve
|
||||
```
|
||||
|
||||
This will start the FastAPI app with a server running locally at [http://localhost:8000](http://localhost:8000)
|
||||
|
||||
You can see all templates at [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)
|
||||
You can access the playground at [http://127.0.0.1:8000/rag-ollama-multi-query/playground](http://127.0.0.1:8000/rag-ollama-multi-query/playground)
|
||||
|
||||
To access the template from code, use:
|
||||
|
||||
```python
|
||||
from langserve.client import RemoteRunnable
|
||||
|
||||
runnable = RemoteRunnable("http://localhost:8000/rag-ollama-multi-query")
|
||||
```
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,34 @@
|
||||
[tool.poetry]
|
||||
name = "rag-ollama-multi-query"
|
||||
version = "0.1.0"
|
||||
description = "RAG with multi-query retriever using Ollama"
|
||||
authors = [
|
||||
"Lance Martin <lance@langchain.dev>",
|
||||
]
|
||||
readme = "README.md"
|
||||
|
||||
[tool.poetry.dependencies]
|
||||
python = ">=3.8.1,<4.0"
|
||||
langchain = ">=0.0.325"
|
||||
openai = "<2"
|
||||
tiktoken = ">=0.5.1"
|
||||
chromadb = ">=0.4.14"
|
||||
|
||||
[tool.poetry.group.dev.dependencies]
|
||||
langchain-cli = ">=0.0.15"
|
||||
|
||||
[tool.langserve]
|
||||
export_module = "rag_ollama_multi_query"
|
||||
export_attr = "chain"
|
||||
|
||||
[tool.templates-hub]
|
||||
use-case = "rag"
|
||||
author = "LangChain"
|
||||
integrations = ["OpenAI", "Ollama"]
|
||||
tags = ["vectordbs"]
|
||||
|
||||
[build-system]
|
||||
requires = [
|
||||
"poetry-core",
|
||||
]
|
||||
build-backend = "poetry.core.masonry.api"
|
@ -0,0 +1,63 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"id": "681a5d1e",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Connect to template\n",
|
||||
"\n",
|
||||
"In `server.py`, set -\n",
|
||||
"```\n",
|
||||
"add_routes(app, chain_ext, path=\"/rag_ollama_multi_query\")\n",
|
||||
"```"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"id": "8d61a866-f91f-41ec-a840-270b0c9c895c",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"'The various types of agent memory mentioned in the context are:\\n\\n1. Explicit / declarative memory: This refers to memory of facts and events, including episodic memory (events and experiences) and semantic memory (facts and concepts).\\n\\n2. Implicit / procedural memory: This type of memory is unconscious and involves skills and routines that are performed automatically, like riding a bike or typing on a keyboard.\\n\\n3. Short-term memory: This is the in-context learning utilized by the model to learn.\\n\\n4. Long-term memory: This provides the agent with the capability to retain and recall information over extended periods, often by leveraging an external vector store and fast retrieval.\\n\\n5. Sensory memory: This is the earliest stage of memory that retains impressions of sensory information (visual, auditory, etc) after the original stimuli have ended. It includes subcategories like iconic memory (visual), echoic memory (auditory), and haptic memory (touch).'"
|
||||
]
|
||||
},
|
||||
"execution_count": 4,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"from langserve.client import RemoteRunnable\n",
|
||||
"\n",
|
||||
"rag_app_ollama = RemoteRunnable(\"http://0.0.0.0:8001/rag_ollama_multi_query\")\n",
|
||||
"rag_app_ollama.invoke(\"What are the different types of agent memory?\")"
|
||||
]
|
||||
}
|
||||
],
|
||||
"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"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
from rag_ollama_multi_query.chain import chain
|
||||
|
||||
__all__ = ["chain"]
|
@ -0,0 +1,93 @@
|
||||
from typing import List
|
||||
|
||||
from langchain.chains import LLMChain
|
||||
from langchain.chat_models import ChatOllama, ChatOpenAI
|
||||
from langchain.document_loaders import WebBaseLoader
|
||||
from langchain.embeddings import OpenAIEmbeddings
|
||||
from langchain.output_parsers import PydanticOutputParser
|
||||
from langchain.prompts import ChatPromptTemplate, PromptTemplate
|
||||
from langchain.pydantic_v1 import BaseModel, Field
|
||||
from langchain.retrievers.multi_query import MultiQueryRetriever
|
||||
from langchain.schema.output_parser import StrOutputParser
|
||||
from langchain.schema.runnable import RunnableParallel, RunnablePassthrough
|
||||
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
||||
from langchain.vectorstores import Chroma
|
||||
|
||||
# Load
|
||||
loader = WebBaseLoader("https://lilianweng.github.io/posts/2023-06-23-agent/")
|
||||
data = loader.load()
|
||||
|
||||
# Split
|
||||
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=0)
|
||||
all_splits = text_splitter.split_documents(data)
|
||||
|
||||
# Add to vectorDB
|
||||
vectorstore = Chroma.from_documents(
|
||||
documents=all_splits,
|
||||
collection_name="rag-private",
|
||||
embedding=OpenAIEmbeddings(),
|
||||
)
|
||||
|
||||
|
||||
# Output parser will split the LLM result into a list of queries
|
||||
class LineList(BaseModel):
|
||||
# "lines" is the key (attribute name) of the parsed output
|
||||
lines: List[str] = Field(description="Lines of text")
|
||||
|
||||
|
||||
class LineListOutputParser(PydanticOutputParser):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(pydantic_object=LineList)
|
||||
|
||||
def parse(self, text: str) -> LineList:
|
||||
lines = text.strip().split("\n")
|
||||
return LineList(lines=lines)
|
||||
|
||||
|
||||
output_parser = LineListOutputParser()
|
||||
|
||||
QUERY_PROMPT = PromptTemplate(
|
||||
input_variables=["question"],
|
||||
template="""You are an AI language model assistant. Your task is to generate five
|
||||
different versions of the given user question to retrieve relevant documents from
|
||||
a vector database. By generating multiple perspectives on the user question, your
|
||||
goal is to help the user overcome some of the limitations of the distance-based
|
||||
similarity search. Provide these alternative questions separated by newlines.
|
||||
Original question: {question}""",
|
||||
)
|
||||
|
||||
# Add the LLM downloaded from Ollama
|
||||
ollama_llm = "zephyr"
|
||||
llm = ChatOllama(model=ollama_llm)
|
||||
|
||||
# Chain
|
||||
llm_chain = LLMChain(llm=llm, prompt=QUERY_PROMPT, output_parser=output_parser)
|
||||
|
||||
# Run
|
||||
retriever = MultiQueryRetriever(
|
||||
retriever=vectorstore.as_retriever(), llm_chain=llm_chain, parser_key="lines"
|
||||
) # "lines" is the key (attribute name) of the parsed output
|
||||
|
||||
# RAG prompt
|
||||
template = """Answer the question based only on the following context:
|
||||
{context}
|
||||
Question: {question}
|
||||
"""
|
||||
prompt = ChatPromptTemplate.from_template(template)
|
||||
|
||||
# RAG
|
||||
model = ChatOpenAI()
|
||||
chain = (
|
||||
RunnableParallel({"context": retriever, "question": RunnablePassthrough()})
|
||||
| prompt
|
||||
| model
|
||||
| StrOutputParser()
|
||||
)
|
||||
|
||||
|
||||
# Add typing for input
|
||||
class Question(BaseModel):
|
||||
__root__: str
|
||||
|
||||
|
||||
chain = chain.with_types(input_type=Question)
|
Loading…
Reference in New Issue