LangChain에서 Cohere Rerank 사용하기
LangChain에서 Cohere Rerank 사용하기 (통합 가이드)
Cohere의 ReRank 모델을 LangChain과 통합하는 방법을 알아볼 거예요.
Cohere는 Cohere의 모델을 기반으로 애플리케이션을 빠르게 만들 수 있게 해 주는 대규모 언어 모델(LLM) 프레임워크인 LangChain과 다양한 통합을 지원해요. 이 문서는 LangChain과 함께 Rerank를 활용하는 방법을 안내할 거예요.
출처: 문서
사전 요구 사항 (Prerequisites)
LangChain으로 Cohere Rerank를 실행하는 데는 사전 요구 사항이 많지 않아요. 자세한 내용은 최상위 문서를 참조하세요.
LangChain과 함께하는 Cohere ReRank
LangChain에서 Cohere의 rerank 기능을 사용하려면 다음과 같이 CohereRerank 객체를 인스턴스화하는 것부터 시작하세요: cohere_rerank = CohereRerank(cohere_api_key="{API_KEY}").
그런 다음 LangChain 리트리버, 임베딩, RAG와 함께 사용할 수 있어요. 아래 예시는 pip install chromadb가 필요한 chroma 벡터 DB를 사용해요. 이 목록의 다른 벡터 DB도 사용할 수 있어요. 재정렬 후 상위 문서를 ChatCohere의 documents 인자로 전달해 인용이 포함된 근거 있는 답변을 얻어요.
PYTHON
from langchain_classic.retrievers import (
ContextualCompressionRetriever,
)
from langchain_cohere import (
ChatCohere,
CohereEmbeddings,
CohereRerank,
)
from langchain_text_splitters import CharacterTextSplitter
from langchain_community.vectorstores import Chroma
from langchain_community.document_loaders import WebBaseLoader
user_query = "what is Cohere Toolkit?"
# Define the Cohere LLM
llm = ChatCohere(
cohere_api_key="COHERE_API_KEY", model="command-a-03-2025"
)
# Define the Cohere embedding model
embeddings = CohereEmbeddings(
cohere_api_key="COHERE_API_KEY", model="embed-english-light-v3.0"
)
# Load text and split into chunks, you can also use data gathered elsewhere in your application
raw_documents = WebBaseLoader(
"https://docs.cohere.com/docs/cohere-toolkit"
).load()
text_splitter = CharacterTextSplitter(
chunk_size=1000, chunk_overlap=0
)
documents = text_splitter.split_documents(raw_documents)
# Create a vector store from the documents
db = Chroma.from_documents(documents, embeddings)
# Create Cohere's reranker with the vector DB using Cohere's embeddings as the base retriever
reranker = CohereRerank(
cohere_api_key="COHERE_API_KEY", model="rerank-english-v3.0"
)
compression_retriever = ContextualCompressionRetriever(
base_compressor=reranker, base_retriever=db.as_retriever()
)
compressed_docs = compression_retriever.invoke(user_query)
# Print the reranked documents from using the embeddings and reranker
print(compressed_docs)
# Ground the answer in the reranked documents
response = llm.invoke(user_query, documents=compressed_docs)
# Print the answer
print("Answer:")
print(response.content)
# Print the citations that ground the answer in the documents
print("Citations:")
print(response.additional_kwargs.get("citations"))
프라이빗 배포에서 LangChain 사용하기
프라이빗 배포된 Cohere 모델과 함께 LangChain을 사용할 수 있어요. 사용하려면 base_url 매개변수에 모델 배포 URL을 지정하세요.
PYTHON
llm = CohereRerank(
base_url="<YOUR_DEPLOYMENT_URL>",
cohere_api_key="COHERE_API_KEY",
model="MODEL_NAME",
)