검색 증강 생성(RAG) - 퀵스타트

검색 증강 생성(RAG) - 퀵스타트

Cohere의 Command 모델(v2 API)로 검색 증강 생성(RAG)을 수행하는 퀵스타트 가이드예요.

출처: 문서

본문

검색 증강 생성(RAG)이란

검색 증강 생성(RAG)은 LLM이 외부 문서에 기반해서 답변을 내놓을 수 있게 해 줘요. 그래서 답변의 정확도를 높이고 환각(hallucination)을 최소화할 수 있죠.

Chat 엔드포인트에는 문서 그라운딩(document grounding)과 인용 생성(citation generation) 같은 RAG 기능이 내장되어 있어요.

이 퀵스타트 가이드는 Chat 엔드포인트로 RAG를 수행하는 방법을 보여드려요.

설정

먼저 다음 명령으로 Cohere Python SDK를 설치해요.

pip install -U cohere

다음으로 라이브러리를 import하고 클라이언트를 만들어요.

Cohere Platform

PYTHON

import cohere

co = cohere.ClientV2(
    "COHERE_API_KEY"
)  # Get your free API key here: https://dashboard.cohere.com/api-keys

Private Deployment

PYTHON

import cohere

co = cohere.ClientV2(
    api_key="",  # Leave this blank
    base_url="<YOUR_DEPLOYMENT_URL>",
)

Bedrock

PYTHON

import cohere

co = cohere.BedrockClientV2(
    aws_region="AWS_REGION",
    aws_access_key="AWS_ACCESS_KEY_ID",
    aws_secret_key="AWS_SECRET_ACCESS_KEY",
    aws_session_token="AWS_SESSION_TOKEN",
)

# Get the model name: https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html

SageMaker

PYTHON

import cohere

co = cohere.SagemakerClientV2(
    aws_region="AWS_REGION",
    aws_access_key="AWS_ACCESS_KEY_ID",
    aws_secret_key="AWS_SECRET_ACCESS_KEY",
    aws_session_token="AWS_SESSION_TOKEN",
)

Azure AI

PYTHON

import cohere

co = cohere.ClientV2(
    api_key="AZURE_API_KEY",
    base_url="AZURE_ENDPOINT",  # example: "https://cohere-command-r-plus-08-2024-xyz.eastus.models.ai.azure.com/"
)

문서(Documents)

먼저 RAG의 컨텍스트로 전달될 문서들을 정의해요. 이런 문서들은 보통 벡터 데이터베이스에서 의미 기반 검색(semantic search)으로, 또는 사용자 쿼리가 주어졌을 때 비정형 데이터를 검색할 수 있는 어떤 시스템에서든 가져오게 돼요.

각 문서는 어떤 필드든 가질 수 있는 data 객체예요. 예를 들어 title, url, text 같은 필드들이죠.

PYTHON

documents = [
    {
        "data": {
            "text": "Reimbursing Travel Expenses: Easily manage your travel expenses by submitting them through our finance tool. Approvals are prompt and straightforward."
        }
    },
    {
        "data": {
            "text": "Working from Abroad: Working remotely from another country is possible. Simply coordinate with your manager and ensure your availability during core hours."
        }
    },
    {
        "data": {
            "text": "Health and Wellness Benefits: We care about your well-being and offer gym memberships, on-site yoga classes, and comprehensive health insurance."
        }
    },
]

응답 생성

다음으로, documents 파라미터에 문서들을 넣어 Chat API를 호출해요. 이렇게 하면 모델이 RAG 모드로 동작하고, 응답의 컨텍스트로 이 문서들을 사용하게 돼요.

Cohere Platform

PYTHON

# Add the user query
query = "Are there health benefits?"

# Generate the response
response = co.chat(
    model="command-a-plus-05-2026",
    messages=[{"role": "user", "content": query}],
    documents=documents,
)

# Display the response
print(response.message.content[0].text)

Private Deployment

PYTHON

# Add the user query
query = "Are there health benefits?"

# Generate the response
response = co.chat(
    model="command-a-plus-05-2026",
    messages=[{"role": "user", "content": query}],
    documents=documents,
)

# Display the response
print(response.message.content[0].text)

Bedrock

PYTHON

# Add the user query
query = "Are there health benefits?"

# Generate the response
response = co.chat(
    model="YOUR_MODEL_NAME",
    messages=[{"role": "user", "content": query}],
    documents=documents,
)

# Display the response
print(response.message.content[0].text)

SageMaker

PYTHON

# Add the user query
query = "Are there health benefits?"

# Generate the response
response = co.chat(
    model="YOUR_ENDPOINT_NAME",
    messages=[{"role": "user", "content": query}],
    documents=documents,
)

# Display the response
print(response.message.content[0].text)

Azure AI

PYTHON

# Add the user query
query = "Are there health benefits?"

# Generate the response
response = co.chat(
    model="model",  # Pass a dummy string
    messages=[{"role": "user", "content": query}],
    documents=documents,
)

# Display the response
print(response.message.content[0].text)
Yes, there are health benefits. We offer gym memberships, on-site yoga classes, and comprehensive health insurance.

인용 생성(Citation Generation)

응답 객체에는 citations 필드가 있는데, 여기에는 응답이 기반하고 있는 문서의 특정 텍스트 조각들이 들어 있어요.

PYTHON

if response.message.citations:
    for citation in response.message.citations:
        print(citation, "\n")
start=14 end=88 text='gym memberships, on-site yoga classes, and comprehensive health insurance.' document_ids=['doc_1'] 

더 보기(Further Resources)

더 알아보기 (Learn more)