mirror of
https://github.com/hwchase17/langchain
synced 2024-11-06 03:20:49 +00:00
fa5d49f2c1
ran ```bash g grep -l "langchain.vectorstores" | xargs -L 1 sed -i '' "s/langchain\.vectorstores/langchain_community.vectorstores/g" g grep -l "langchain.document_loaders" | xargs -L 1 sed -i '' "s/langchain\.document_loaders/langchain_community.document_loaders/g" g grep -l "langchain.chat_loaders" | xargs -L 1 sed -i '' "s/langchain\.chat_loaders/langchain_community.chat_loaders/g" g grep -l "langchain.document_transformers" | xargs -L 1 sed -i '' "s/langchain\.document_transformers/langchain_community.document_transformers/g" g grep -l "langchain\.graphs" | xargs -L 1 sed -i '' "s/langchain\.graphs/langchain_community.graphs/g" g grep -l "langchain\.memory\.chat_message_histories" | xargs -L 1 sed -i '' "s/langchain\.memory\.chat_message_histories/langchain_community.chat_message_histories/g" gco master libs/langchain/tests/unit_tests/*/test_imports.py gco master libs/langchain/tests/unit_tests/**/test_public_api.py ```
51 lines
1.4 KiB
Python
51 lines
1.4 KiB
Python
from langchain import hub
|
|
from langchain.load import dumps, loads
|
|
from langchain_community.chat_models import ChatOpenAI
|
|
from langchain_community.embeddings import OpenAIEmbeddings
|
|
from langchain_community.vectorstores import Pinecone
|
|
from langchain_core.output_parsers import StrOutputParser
|
|
from langchain_core.pydantic_v1 import BaseModel
|
|
|
|
|
|
def reciprocal_rank_fusion(results: list[list], k=60):
|
|
fused_scores = {}
|
|
for docs in results:
|
|
# Assumes the docs are returned in sorted order of relevance
|
|
for rank, doc in enumerate(docs):
|
|
doc_str = dumps(doc)
|
|
if doc_str not in fused_scores:
|
|
fused_scores[doc_str] = 0
|
|
fused_scores[doc_str] += 1 / (rank + k)
|
|
|
|
reranked_results = [
|
|
(loads(doc), score)
|
|
for doc, score in sorted(fused_scores.items(), key=lambda x: x[1], reverse=True)
|
|
]
|
|
return reranked_results
|
|
|
|
|
|
prompt = hub.pull("langchain-ai/rag-fusion-query-generation")
|
|
|
|
generate_queries = (
|
|
prompt | ChatOpenAI(temperature=0) | StrOutputParser() | (lambda x: x.split("\n"))
|
|
)
|
|
|
|
vectorstore = Pinecone.from_existing_index("rag-fusion", OpenAIEmbeddings())
|
|
retriever = vectorstore.as_retriever()
|
|
|
|
chain = (
|
|
{"original_query": lambda x: x}
|
|
| generate_queries
|
|
| retriever.map()
|
|
| reciprocal_rank_fusion
|
|
)
|
|
|
|
# Add typed inputs to chain for playground
|
|
|
|
|
|
class Question(BaseModel):
|
|
__root__: str
|
|
|
|
|
|
chain = chain.with_types(input_type=Question)
|