LangChain에서 Cohere Chat 사용하기
LangChain에서 Cohere Chat 사용하기 (통합 가이드)
Cohere를 LangChain과 통합해 Cohere의 모델과 LangChain 도구를 사용하는 애플리케이션을 구축하는 방법을 알아볼 거예요.
Cohere는 Cohere의 모델을 기반으로 애플리케이션을 빠르게 만들 수 있게 해 주는 대규모 언어 모델(LLM) 프레임워크인 LangChain과 다양한 통합을 지원해요. 이 문서는 LangChain과 함께 Cohere Chat을 활용하는 방법을 안내할 거예요.
출처: 문서
사전 요구 사항 (Prerequisites)
LangChain으로 Cohere Chat을 실행하는 데는 사전 요구 사항이 많지 않아요. 자세한 내용은 최상위 문서를 참조하세요.
LangChain과 함께하는 Cohere Chat
LangChain에서 Cohere chat을 사용하려면 ChatCohere 객체를 만들어 메시지 또는 메시지 이력을 전달하기만 하면 돼요. 아래 예시에서는 Cohere API 키를 추가해야 해요.
PYTHON
from langchain_cohere import ChatCohere
from langchain_core.messages import AIMessage, HumanMessage
# Define the Cohere LLM
llm = ChatCohere(
cohere_api_key="COHERE_API_KEY", model="command-a-03-2025"
)
# Send a chat message without chat history
current_message = [HumanMessage(content="knock knock")]
print(llm.invoke(current_message))
# Send a chat message with chat history, note the last message is the current user message
current_message_and_history = [
HumanMessage(content="knock knock"),
AIMessage(content="Who's there?"),
HumanMessage(content="Tank"),
]
print(llm.invoke(current_message_and_history))
LangChain과 함께하는 Reasoning
리즈닝 모델(예: command-a-reasoning-08-2025)을 선택하면, 그 응답에는 모델의 추론(reasoning)과 최종 답변이 구조화된 콘텐츠 블록으로 모두 포함돼요. 별도의 매개변수가 필요 없어요. 리즈닝 모델이 어떻게 동작하는지에 대한 배경은 Cohere의 Reasoning 가이드를 참조하세요.
Reasoning 지원에는 langchain-cohere >= 0.5.1이 필요해요.
PYTHON
from langchain_cohere import ChatCohere
from langchain_core.messages import HumanMessage
# Define the Cohere LLM
llm = ChatCohere(
cohere_api_key="COHERE_API_KEY",
model="command-a-reasoning-08-2025",
)
response = llm.invoke(
[
HumanMessage(
content="Alice has 3 brothers and 2 sisters. How many sisters does Alice's brother have?"
)
]
)
# The reasoning model returns its content as a list of blocks: a "reasoning"
# block (the model's reasoning) followed by a "text" block (the final answer).
for block in response.content:
if block["type"] == "reasoning":
for step in block["summary"]:
print("Reasoning:", step["text"])
elif block["type"] == "text":
print("Answer:", block["text"])
LangChain과 함께하는 이미지 입력
Command A Vision (command-a-vision-07-2025)은 이미지를 해석할 수 있어요. 텍스트 프롬프트와 함께 image_url 타입(공개적으로 접근 가능한 이미지 URL 또는 base64 데이터 URI)의 이미지 콘텐츠 블록을 전달하면 돼요. Cohere의 비전 기능에 대한 자세한 내용은 Image Inputs 가이드를 참조하세요.
Vision 지원에는 langchain-cohere >= 0.6.0이 필요해요.
PYTHON
from langchain_cohere import ChatCohere
from langchain_core.messages import HumanMessage
# Define the Cohere LLM
llm = ChatCohere(
cohere_api_key="COHERE_API_KEY",
model="command-a-vision-07-2025",
)
# Use a publicly accessible image URL (a base64 data URI also works)
image_url = "https://raw.githubusercontent.com/cohere-ai/cohere-developer-experience/main/fern/assets/images/waste-management-request.png"
# Pass the image alongside a text prompt
message = HumanMessage(
content=[
{"type": "text", "text": "What is shown in this image?"},
{"type": "image_url", "image_url": {"url": image_url}},
]
)
print(llm.invoke([message]).content)
LangChain과 함께하는 Cohere 에이전트
에이전트(agent)는 언어 모델을 사용해 취할 일련의 행동을 선택해요. LangChain v1에서 이를 구축하는 관용적인 방법은 langchain.agents의 create_agent예요 (langchain에 포함되어 있으므로 추가 설치가 필요 없어요). 에이전트가 사용하길 원하는 LangChain 도구를 전달하면 돼요.
아래 예시에서는 에이전트에게 인터넷 검색 도구(Tavily)를 주고 언제 호출할지 스스로 결정하게 한 다음, 답변을 출력해요. 실행하려면 pip install langchain-tavily로 검색 도구를 설치하고 TAVILY_API_KEY 환경 변수를 설정하세요. 다른 LangChain 도구로 바꿔도 돼요. (인용이 포함된 근거 있는 답변에 대해서는 아래의 Web Search와 RAG 예시를 참조하세요.)
PYTHON
import os
from langchain.agents import create_agent
from langchain_cohere import ChatCohere
from langchain_tavily import TavilySearch
# Internet search tool. Replace the placeholder with your Tavily API key.
os.environ["TAVILY_API_KEY"] = "TAVILY_API_KEY"
internet_search = TavilySearch()
# Define the Cohere LLM
llm = ChatCohere(
cohere_api_key="COHERE_API_KEY", model="command-a-03-2025"
)
# Create an agent with the internet search tool
agent = create_agent(llm, tools=[internet_search])
# Run the agent
result = agent.invoke(
{"messages": [("user", "I want to write an essay. Any tips?")]}
)
# See Cohere's response
print(result["messages"][-1].content)
LangChain과 함께하는 Cohere Chat 및 RAG
LangChain에서 Cohere의 검색 증강 생성 (RAG) 기능을 사용하려면 문서를 ChatCohere의 documents 인자로 전달하면 돼요. Cohere는 그 문서들에 답변을 근거시키고, 문서를 가리키는 인용(citations)을 반환해요. 다음 몇 섹션에서 문서를 제공하는 몇 가지 방법을 보여줄 거예요.
LangChain의 리트리버 사용하기
이 예시에서는 wikipedia 리트리버를 사용하지만, LangChain이 지원하는 어떤 리트리버든 여기서 사용할 수 있어요. wikipedia 리트리버를 설정하려면 %pip install --upgrade --quiet wikipedia로 wikipedia 패키지를 설치해야 해요. Wikipedia는 설명적인 User-Agent도 요구하므로, 쿼리하기 전에 wikipedia.set_user_agent(...)로 설정하세요. 그렇게 하면 다음 코드를 실행해 리트리버가 어떻게 동작하는지 확인할 수 있어요.
PYTHON
import wikipedia
from langchain_cohere import ChatCohere
from langchain_community.retrievers import WikipediaRetriever
# Wikipedia requires a descriptive User-Agent; set one before querying.
wikipedia.set_user_agent("my-app/1.0 ([email protected])")
# User query we will use for the generation
user_query = "What is Cohere?"
# Define the Cohere LLM
llm = ChatCohere(
cohere_api_key="COHERE_API_KEY", model="command-a-03-2025"
)
# Retrieve documents with any LangChain retriever
wiki_retriever = WikipediaRetriever()
wiki_docs = wiki_retriever.invoke(user_query)
# Ground the answer in the retrieved documents
response = llm.invoke(user_query, documents=wiki_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"))
문서 사용하기
이 예시에서는 문서(애플리케이션의 다른 부분에서 생성된 것일 수 있어요)를 가져와 ChatCohere에 직접 전달해요.
PYTHON
from langchain_cohere import ChatCohere
from langchain_core.documents import Document
# Define the Cohere LLM
llm = ChatCohere(
cohere_api_key="COHERE_API_KEY", model="command-a-03-2025"
)
# Supply your own documents (these might come from elsewhere in your application)
documents = [
Document(
page_content="LangChain supports Cohere RAG!",
metadata={"id": "id-1"},
),
Document(
page_content="The sky is blue!", metadata={"id": "id-2"}
),
]
# Ground the answer in the documents
response = llm.invoke(
"Does LangChain support Cohere RAG?", documents=documents
)
# 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"))
웹 검색 (Web Search)
웹의 최신 정보로 쿼리에 답하려면 도구 사용으로 모델에게 검색 도구를 주면 돼요: 모델이 검색을 요청하면, 여러분이 검색을 실행해 결과를 되돌려주고, Cohere가 그 결과에 답변을 근거시키고 인용을 반환해요. 예시를 실행하려면 TAVILY_API_KEY 환경 변수를 설정하거나, 다른 검색 도구로 바꿔도 돼요.
PYTHON
import os
from langchain_cohere import ChatCohere
from langchain_core.messages import HumanMessage, ToolMessage
from langchain_tavily import TavilySearch
# Web search tool. Replace the placeholder with your Tavily API key.
os.environ["TAVILY_API_KEY"] = "TAVILY_API_KEY"
web_search = TavilySearch()
# Define the Cohere LLM and bind the search tool
llm = ChatCohere(
cohere_api_key="COHERE_API_KEY", model="command-a-03-2025"
)
llm_with_tools = llm.bind_tools([web_search])
# 1. Force a search on the first turn so the answer is grounded
messages = [HumanMessage("Who founded Cohere?")]
ai_message = llm_with_tools.invoke(messages, tool_choice="REQUIRED")
messages.append(ai_message)
# 2. Run the search and pass the results back to the model
for tool_call in ai_message.tool_calls:
results = web_search.invoke(tool_call["args"])
messages.append(
ToolMessage(
content=str(results), tool_call_id=tool_call["id"]
)
)
# 3. The model answers, grounded in the search results
final = llm_with_tools.invoke(messages)
print("Answer:", final.content)
# Cohere returns citations that ground the answer in the search results
# (`.get` avoids a KeyError if the answer came back without any citations)
print("Citations:", final.additional_kwargs.get("citations"))
create_stuff_documents_chain 체인 사용하기
이 체인은 문서 목록을 가져와 모두 프롬프트로 포맷한 다음 그 프롬프트를 LLM에 전달해요. 모든 문서를 전달하므로, 사용하는 LLM의 컨텍스트 윈도우 안에 들어가는지 확인해야 해요.
참고: 이 기능은 현재 베타 단계예요.
PYTHON
from langchain_cohere import ChatCohere
from langchain_core.documents import Document
from langchain_core.prompts import ChatPromptTemplate
from langchain_classic.chains.combine_documents import (
create_stuff_documents_chain,
)
prompt = ChatPromptTemplate.from_messages(
[("human", "What are everyone's favorite colors:\n\n{context}")]
)
# Define the Cohere LLM
llm = ChatCohere(
cohere_api_key="COHERE_API_KEY", model="command-a-03-2025"
)
chain = create_stuff_documents_chain(llm, prompt)
docs = [
Document(page_content="Jesse loves red but not yellow"),
Document(
page_content="Jamal loves green but not as much as he loves orange"
),
]
res = chain.invoke({"context": docs})
print(res)
구조화된 출력 생성 (Structured Output Generation)
Cohere는 JSON 객체 생성을 지원해서 모델의 응답을 다운스트림 애플리케이션에서 사용할 수 있는 방식으로 구조화하고 정리해 줘요.
response_format 매개변수를 지정해 응답을 JSON 객체 형식으로 받고 싶다고 나타낼 수 있어요.
PYTHON
from langchain_cohere import ChatCohere
# Define the Cohere LLM
llm = ChatCohere(
cohere_api_key="COHERE_API_KEY", model="command-a-03-2025"
)
res = llm.invoke(
"John is five years old",
response_format={
"type": "json_object",
"schema": {
"title": "Person",
"description": "Identifies the age and name of a person",
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Name of the person",
},
"age": {
"type": "number",
"description": "Age of the person",
},
},
"required": [
"name",
"age",
],
},
},
)
print(res)
텍스트 요약 (Text Summarization)
load_summarize_chain 체인을 사용해 텍스트 요약을 수행할 수 있어요.
PYTHON
from langchain_cohere import ChatCohere
from langchain_classic.chains.summarize import load_summarize_chain
from langchain_community.document_loaders import WebBaseLoader
loader = WebBaseLoader("https://docs.cohere.com/docs/cohere-toolkit")
docs = loader.load()
# Define the Cohere LLM
llm = ChatCohere(
cohere_api_key="COHERE_API_KEY",
model="command-a-03-2025",
temperature=0,
)
chain = load_summarize_chain(llm, chain_type="stuff")
result = chain.invoke({"input_documents": docs})
print(result["output_text"])
프라이빗 배포에서 LangChain 사용하기
프라이빗 배포된 Cohere 모델과 함께 LangChain을 사용할 수 있어요. 사용하려면 base_url 매개변수에 모델 배포 URL을 지정하세요.
PYTHON
llm = ChatCohere(
base_url="<YOUR_DEPLOYMENT_URL>",
cohere_api_key="COHERE_API_KEY",
model="MODEL_NAME",
)