LangChain에서 Cohere Embed 사용하기
LangChain에서 Cohere Embed 사용하기 (통합 가이드)
Cohere의 임베딩 모델과 LangChain을 함께 사용하는 방법을 알아볼 거예요.
Cohere는 Cohere의 모델을 기반으로 애플리케이션을 빠르게 만들 수 있게 해 주는 대규모 언어 모델(LLM) 프레임워크인 LangChain과 다양한 통합을 지원해요. 이 문서는 LangChain과 함께 다양한 Cohere 임베딩을 활용하는 방법을 안내할 거예요.
출처: 문서
사전 요구 사항 (Prerequisites)
LangChain으로 Cohere 임베딩을 실행하는 데는 사전 요구 사항이 많지 않아요. 자세한 내용은 최상위 문서를 참조하세요.
LangChain과 함께하는 Cohere Embeddings
LangChain에서 Cohere의 Embeddings를 사용하려면 다음과 같이 CohereEmbedding 객체를 만드세요 (사용 가능한 cohere 임베딩 모델은 여기에 나열되어 있어요):
PYTHON
from langchain_cohere import CohereEmbeddings
# Define the Cohere embedding model
embeddings = CohereEmbeddings(
cohere_api_key="COHERE_API_KEY", model="embed-v4.0"
)
# Embed a document
text = "This is a test document."
query_result = embeddings.embed_query(text)
print(query_result[:5], "...")
doc_result = embeddings.embed_documents([text])
print(doc_result[0][:5], "...")
이 임베딩을 Cohere의 RAG 기능과 함께 사용하려면 이 목록에 있는 벡터 DB 중 하나를 사용해야 해요. 이 예시에서는 chroma를 사용하므로, 실행하려면 pip install chromadb로 chroma를 설치해야 해요. 벡터 저장소에서 가장 관련성 높은 청크를 검색해 ChatCohere의 documents 인자로 전달해 인용이 포함된 근거 있는 답변을 얻어요.
PYTHON
from langchain_cohere import ChatCohere, CohereEmbeddings
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?"
llm = ChatCohere(
cohere_api_key="COHERE_API_KEY",
model="command-a-03-2025",
temperature=0,
)
embeddings = CohereEmbeddings(
cohere_api_key="COHERE_API_KEY", model="embed-v4.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=500, chunk_overlap=0)
documents = text_splitter.split_documents(raw_documents)
# Create a vector store from the documents and retrieve the most relevant chunks
db = Chroma.from_documents(documents, embeddings)
input_docs = db.as_retriever().invoke(user_query)
# Ground the answer in the retrieved documents
response = llm.invoke(user_query, documents=input_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 및 Bedrock과 함께하는 Cohere
사전 요구 사항 (Prerequisite)
위의 사전 요구 사항에 더해, Amazon Bedrock에서 Cohere를 LangChain과 통합하려면 추가로 다음이 필요해요.
- LangChain AWS 패키지. 설치하려면
pip install langchain-aws를 실행하세요. - AWS Python SDK. 설치하려면
pip install boto3를 실행하세요. 자세한 내용은 여기에서 확인할 수 있어요. - AWS용 인증 자격 증명이 구성되어 있어야 함. 자세한 내용은 이 문서를 참조하세요.
LangChain과 Amazon Bedrock으로 Cohere 임베딩 사용하기
이 예시에서는 Bedrock과 LangChain을 사용해 쿼리에 대한 임베딩을 만들어요.
PYTHON
from langchain_aws import BedrockEmbeddings
# Replace the profile name with the one created in the setup.
embeddings = BedrockEmbeddings(
credentials_profile_name="{PROFILE-NAME}",
region_name="us-east-1",
model_id="cohere.embed-english-v3",
)
embeddings.embed_query("This is a content of the document")
프라이빗 배포에서 LangChain 사용하기
프라이빗 배포된 Cohere 모델과 함께 LangChain을 사용할 수 있어요. 사용하려면 base_url 매개변수에 모델 배포 URL을 지정하세요.
PYTHON
llm = CohereEmbeddings(
base_url="<YOUR_DEPLOYMENT_URL>",
cohere_api_key="COHERE_API_KEY",
model="MODEL_NAME",
)