LlamaIndex와 Cohere의 모델
LlamaIndex와 Cohere의 모델
Cohere와 LlamaIndex를 함께 사용해 데이터를 기반으로 응답을 생성하는 방법을 알아볼 거예요.
출처: 문서
사전 요구 사항 (Prerequisite)
LlamaIndex와 Cohere를 사용하려면 다음이 필요해요.
- LlamaIndex 패키지. 설치하려면 다음을 실행하세요:
pip install llama-indexpip install llama-index-llms-cohere(Command 모델 사용용)pip install llama-index-embeddings-cohere(Embed 모델 사용용)pip install llama-index-postprocessor-cohere-rerank(Rerank 모델 사용용)
- Cohere SDK. 설치하려면
pip install cohere를 실행하세요. 문제가 생기거나 Cohere SDK에 대한 자세한 내용이 필요하면 이 위키를 참조하세요. - Cohere API 키. 가격에 대한 자세한 내용은 이 페이지를 참조하세요. Cohere로 계정을 만들면 트라이얼 API 키가 자동으로 생성돼요. 이 키는 대시보드에서 복사할 수 있고, 대시보드의 "API Keys" 섹션에도 있어요.
LlamaIndex와 함께하는 Cohere Chat
LlamaIndex에서 Cohere의 채팅 기능을 사용하려면 Cohere 모델 객체를 만들고 chat 함수를 호출하세요.
PYTHON
from llama_index.llms.cohere import Cohere
from llama_index.core.llms import ChatMessage
cohere_model = Cohere(
api_key="COHERE_API_KEY", model="command-a-03-2025"
)
message = ChatMessage(role="user", content="What is 2 + 3?")
response = cohere_model.chat([message])
print(response)
LlamaIndex와 함께하는 Cohere Embeddings
LlamaIndex에서 Cohere의 임베딩을 사용하려면 이 목록의 임베딩 모델로 Cohere Embeddings 객체를 만들고 get_text_embedding을 호출하세요.
PYTHON
from llama_index.embeddings.cohere import CohereEmbedding
embed_model = CohereEmbedding(
api_key="COHERE_API_KEY",
model_name="embed-english-v3.0",
input_type="search_document", # Use search_query for queries, search_document for documents
max_tokens=8000,
embedding_types=["float"],
)
# Generate Embeddings
embeddings = embed_model.get_text_embedding("Welcome to Cohere!")
# Print embeddings
print(len(embeddings))
print(embeddings[:5])
LlamaIndex와 함께하는 Cohere Rerank
LlamaIndex에서 Cohere의 rerank 기능을 사용하려면 Cohere Rerank 객체를 만들고 노드 후처리기(node post processor)로 사용하세요.
PYTHON
from llama_index.postprocessor.cohere_rerank import CohereRerank
from llama_index.readers.web import (
SimpleWebPageReader,
) # first, run `pip install llama-index-readers-web`
# create index (we are using an example page from Cohere's docs)
documents = SimpleWebPageReader(html_to_text=True).load_data(
["https://docs.cohere.com/v2/docs/cohere-embed"]
) # you can replace this with any other reader or documents
index = VectorStoreIndex.from_documents(documents=documents)
# create reranker
cohere_rerank = CohereRerank(
api_key="COHERE_API_KEY", model="rerank-english-v3.0", top_n=2
)
# query the index
query_engine = index.as_query_engine(
similarity_top_k=10,
node_postprocessors=[cohere_rerank],
)
print(query_engine)
# generate a response
response = query_engine.query(
"What is Cohere's Embed Model?",
)
print(response)
# To view the source documents
from llama_index.core.response.pprint_utils import pprint_response
pprint_response(response, show_source=True)
LlamaIndex와 함께하는 Cohere RAG
다음 예시는 Cohere의 채팅 모델, 임베딩, rerank 기능을 사용해 데이터를 기반으로 응답을 생성해요.
PYTHON
from llama_index.llms.cohere import Cohere
from llama_index.embeddings.cohere import CohereEmbedding
from llama_index.postprocessor.cohere_rerank import CohereRerank
from llama_index.core import Settings
from llama_index.core import VectorStoreIndex
from llama_index.readers.web import (
SimpleWebPageReader,
) # first, run `pip install llama-index-readers-web`
# Create the embedding model
embed_model = CohereEmbedding(
api_key="COHERE_API_KEY",
model="embed-english-v3.0",
input_type="search_document",
max_tokens=8000,
embedding_types=["float"],
)
# Create the service context with the cohere model for generation and embedding model
Settings.llm = Cohere(
api_key="COHERE_API_KEY", model="command-a-03-2025"
)
Settings.embed_model = embed_model
# create index (we are using an example page from Cohere's docs)
documents = SimpleWebPageReader(html_to_text=True).load_data(
["https://docs.cohere.com/v2/docs/cohere-embed"]
) # you can replace this with any other reader or documents
index = VectorStoreIndex.from_documents(documents=documents)
# Create a cohere reranker
cohere_rerank = CohereRerank(
api_key="COHERE_API_KEY", model="rerank-english-v3.0", top_n=2
)
# Create the query engine
query_engine = index.as_query_engine(
node_postprocessors=[cohere_rerank]
)
# Generate the response
response = query_engine.query("What is Cohere's Embed model?")
print(response)
LlamaIndex와 함께하는 Cohere 도구 사용 (함수 호출)
LlamaIndex에서 Cohere의 도구 사용 기능을 활용하려면 FunctionTool 클래스를 사용해 Cohere의 API를 활용하는 도구를 만들 수 있어요.
PYTHON
from llama_index.llms.cohere import Cohere
from llama_index.core.tools import FunctionTool
from llama_index.core.agent import FunctionCallingAgent
# Define tools
def multiply(a: int, b: int) -> int:
"""Multiple two integers and returns the result integer"""
return a * b
multiply_tool = FunctionTool.from_defaults(fn=multiply)
def add(a: int, b: int) -> int:
"""Add two integers and returns the result integer"""
return a + b
add_tool = FunctionTool.from_defaults(fn=add)
# Define LLM
llm = Cohere(api_key="COHERE_API_KEY", model="command-a-03-2025")
# Create agent
agent = FunctionCallingAgent.from_tools(
[multiply_tool, add_tool],
llm=llm,
verbose=True,
allow_parallel_tool_calls=True,
)
# Run agent
response = await agent.achat("What is (121 * 3) + (5 * 8)?")