Oracle Cloud Infrastructure

Oracle Cloud Infrastructure (OCI)에서의 Cohere

네이티브 Cohere Python SDK로 OCI Generative AI에서 Cohere 모델을 사용할 수 있어요. 호스팅 API와 동일한 방식으로 작동하므로, 단 한 줄만 바꾸면 Cohere의 API에서 OCI로 손쉽게 전환할 수 있어요.

출처: 문서

본문

Cohere Python SDK는 Oracle Cloud Infrastructure (OCI) Generative AI 서비스를 네이티브로 지원해요. pip install cohere[oci]를 설치하면 OciClient와 OciClientV2 클래스를 얻을 수 있는데, 이들은 Cohere 호스팅의 Client와 ClientV2와 똑같이 동작해요 — 동일한 메서드, 동일한 응답 타입, 동일한 스트리밍 형식이에요. Cohere의 호스팅 API에서 OCI Generative AI로 전환하는 것은 생성자 하나만 바꾸면 되는 거예요.

내부적으로 SDK가 URL 재작성, 요청·응답 형식 변환, OCI 암호화 요청 서명, 스트리밍 이벤트 변환을 처리해요. 애플리케이션 코드는 OCI 특유의 세부 사항을 전혀 볼 필요가 없어요.

사용 가능한 모델 (Available Models)

SDK는 OCI Generative AI에서 사용할 수 있는 모든 Cohere 모델을 지원해요. 여기에는 Command A 제품군(OciClientV2 사용), Command R 제품군(OciClient 사용), Embed 모델, Rerank 모델이 포함돼요. 현재 사용 가능한 모델과 그 ID 목록은 OCI Generative AI 사전 학습 모델 문서를 참고하세요.

설치 (Installation)

pip install cohere[oci]

이 명령은 Cohere SDK와 인증 및 요청 서명에 필요한 OCI SDK 의존성을 함께 설치해요.

빠른 시작 (Quick Start)

Command A와 채팅하기 (V2 API)

import cohere

client = cohere.OciClientV2(
    oci_region="us-chicago-1",
    oci_compartment_id="ocid1.compartment.oc1...",
)

response = client.chat(
    model="command-a-03-2025",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {
            "role": "user",
            "content": "Explain RAG in three sentences.",
        },
    ],
)

print(response.message.content[0].text)

Command R와 채팅하기 (V1 API)

import cohere

client = cohere.OciClient(
    oci_region="us-chicago-1",
    oci_compartment_id="ocid1.compartment.oc1...",
)

response = client.chat(
    model="command-r-plus-08-2024",
    message="Explain RAG in three sentences.",
)

print(response.text)

Embeddings

import cohere

client = cohere.OciClientV2(
    oci_region="us-chicago-1",
    oci_compartment_id="ocid1.compartment.oc1...",
)

response = client.embed(
    model="embed-english-v3.0",
    texts=["Oracle Cloud Infrastructure", "Generative AI service"],
    input_type="search_document",
)

for i, embedding in enumerate(response.embeddings.float_):
    print(f"Text {i}: {len(embedding)} dimensions")

스트리밍 (V2)

import cohere

client = cohere.OciClientV2(
    oci_region="us-chicago-1",
    oci_compartment_id="ocid1.compartment.oc1...",
)

for event in client.chat_stream(
    model="command-a-03-2025",
    messages=[
        {"role": "user", "content": "Explain RAG in three sentences."}
    ],
):
    if event.type == "content-delta":
        print(event.delta.message.content.text, end="")

스트리밍 (V1)

import cohere

client = cohere.OciClient(
    oci_region="us-chicago-1",
    oci_compartment_id="ocid1.compartment.oc1...",
)

for event in client.chat_stream(
    model="command-r-plus-08-2024",
    message="Explain RAG in three sentences.",
):
    if hasattr(event, "text") and event.text:
        print(event.text, end="")

SDK는 OCI의 스트리밍 형식을 Cohere의 표준 스트리밍 이벤트와 일치하도록 변환해요. V2는 message-start, content-delta, content-end, message-end를 사용하고, V1은 stream-start, text-generation, stream-end를 사용해요.

인증 (Authentication)

SDK는 로컬 개발부터 서버리스 프로덕션까지 모든 배포 시나리오를 아우르는 다섯 가지 인증 방식을 지원해요.

1. 구성 파일 (기본값)

DEFAULT 프로필과 함께 ~/.oci/config를 사용해요. 리전과 컴파트먼트 외에 추가 파라미터가 필요 없어요.

client = cohere.OciClientV2(
    oci_region="us-chicago-1",
    oci_compartment_id="ocid1.compartment.oc1...",
)

2. 사용자 지정 프로필

OCI 구성 파일에서 특정 프로필을 사용해요.

client = cohere.OciClientV2(
    oci_profile="MY_PROFILE",
    oci_region="us-chicago-1",
    oci_compartment_id="ocid1.compartment.oc1...",
)

3. 세션 기반 인증

OCI CLI 세션 토큰과 함께 작동해요. SDK는 각 요청마다 토큰 파일을 자동으로 다시 읽으므로, 클라이언트를 재시작하지 않아도 oci session refresh가 반영돼요.

client = cohere.OciClientV2(
    oci_profile="MY_SESSION_PROFILE",  # Profile with security_token_file
    oci_region="us-chicago-1",
    oci_compartment_id="ocid1.compartment.oc1...",
)

4. 직접 자격 증명

구성 파일 없이 OCI 자격 증명을 직접 전달해요. CI/CD 파이프라인이나 컨테이너 기반 배포에 유용해요.

client = cohere.OciClientV2(
    oci_user_id="ocid1.user.oc1...",
    oci_fingerprint="xx:xx:xx:...",
    oci_tenancy_id="ocid1.tenancy.oc1...",
    oci_private_key_path="~/.oci/key.pem",
    oci_region="us-chicago-1",
    oci_compartment_id="ocid1.compartment.oc1...",
)

5. 인스턴스 프린시펄 (Instance Principal)

OCI Compute 인스턴스에서 실행되는 애플리케이션용이에요. 자격 증명이 필요 없어요 — 인스턴스의 신원이 자동으로 사용돼요.

client = cohere.OciClientV2(
    auth_type="instance_principal",
    oci_region="us-chicago-1",
    oci_compartment_id="ocid1.compartment.oc1...",
)

6. 리소스 프린시펄 (Resource Principal)

OCI Functions(서버리스)용이에요. 배포에 자격 증명이 전혀 없어요 — 함수가 컴파트먼트의 보안 태세를 상속받아요.

client = cohere.OciClientV2(
    auth_type="resource_principal",
    oci_region="us-chicago-1",
    oci_compartment_id="ocid1.compartment.oc1...",
)

V1과 V2 API 비교

SDK는 두 가지 OCI Generative AI API 형식에 대응하는 두 개의 클라이언트 클래스를 제공해요:

OciClient (V1) OciClientV2 (V2)
Chat 모델 Command R 제품군 Command A 제품군
Chat 형식 단일 message 문자열 messages 배열
스트리밍 이벤트 text-generation, stream-end message-start, content-delta, message-end
Embed 응답 response.embeddings (float 목록) response.embeddings.float_ (타입별 dict)
도구 사용 tools + tool_results tools + tool_calls + tool_choice
Thinking 지원 안 함 thinking 파라미터로 지원

도구 사용 (V2)

Command A는 OCI Generative AI에서 네이티브 도구 사용을 지원해요. 도구를 정의하면 모델이 구조화된 인자를 가진 tool_calls를 반환해요.

import cohere

client = cohere.OciClientV2(
    oci_region="us-chicago-1",
    oci_compartment_id="ocid1.compartment.oc1...",
)

response = client.chat(
    model="command-a-03-2025",
    messages=[
        {"role": "user", "content": "What's the weather in Toronto?"}
    ],
    max_tokens=200,
    tools=[
        {
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "Get current weather for a location",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "City name",
                        }
                    },
                    "required": ["location"],
                },
            },
        }
    ],
)

if response.message.tool_calls:
    for tc in response.message.tool_calls:
        print(f"{tc.function.name}({tc.function.arguments})")
# Output: get_weather({"location":"Toronto"})

비전/이미지 (V2)

Command A Vision은 텍스트와 함께 이미지를 추론할 수 있어요. 메시지 콘텐츠에서 base64 데이터 URI 또는 URL로 이미지를 전달해요.

import cohere
import base64

client = cohere.OciClientV2(
    oci_region="us-chicago-1",
    oci_compartment_id="ocid1.compartment.oc1...",
)

# Read and encode an image
with open("document.png", "rb") as f:
    img_b64 = base64.b64encode(f.read()).decode()

response = client.chat(
    model="command-a-vision",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "Describe what you see in this image.",
                },
                {
                    "type": "image_url",
                    "image_url": {
                        "url": f"data:image/png;base64,{img_b64}"
                    },
                },
            ],
        }
    ],
)

print(response.message.content[0].text)

Embed v4

Embed v4는 1536차원을 갖는 Cohere의 최신 임베딩 모델로, Embed v3 제품군과 함께 사용할 수 있어요.

import cohere

client = cohere.OciClientV2(
    oci_region="us-chicago-1",
    oci_compartment_id="ocid1.compartment.oc1...",
)

response = client.embed(
    model="embed-v4.0",
    texts=["Oracle Cloud Infrastructure", "Generative AI service"],
    input_type="search_document",
)

for i, embedding in enumerate(response.embeddings.float_):
    print(f"Text {i}: {len(embedding)} dimensions")
# Output: 1536 dimensions per text

지원 기능 (Supported Features)

기능 (Feature) OCI 지원 (OCI Support)
chat 지원됨
chat_stream 지원됨
embed 지원됨
rerank 전용 엔드포인트만
generate 지원 안 함 (OCI 기본 모델은 파인튜닝 필요)
classify 지원 안 함
summarize 지원 안 함
tokenize 오프라인 전용
detokenize 오프라인 전용

종단 간 예제 (End-to-End Example)

다음 예제는 OCI Generative AI에서 완전한 애플리케이션 흐름을 보여줘요: 지식 베이스를 위한 문서 임베딩, 관련 컨텍스트 검색, 실시간 데이터를 위한 도구 호출 사용, 비전으로 이미지 처리, 그리고 최종 응답 스트리밍까지.

import cohere
import base64

# Initialize V2 client for Command A models
client = cohere.OciClientV2(
    oci_region="us-chicago-1",
    oci_compartment_id="ocid1.compartment.oc1...",
)

# --- Step 1: Build a knowledge base with embeddings ---

documents = [
    "Oracle Cloud Infrastructure provides enterprise-grade AI services.",
    "Cohere Command A is a 111B parameter model with 256K context window.",
    "OCI Generative AI is FedRAMP High and DISA IL5 authorized.",
]

doc_embeddings = client.embed(
    model="embed-english-v3.0",
    texts=documents,
    input_type="search_document",
).embeddings.float_

query_embedding = client.embed(
    model="embed-english-v3.0",
    texts=["What security certifications does OCI have?"],
    input_type="search_query",
).embeddings.float_[0]

# Find the most relevant document (cosine similarity)
best_idx = max(
    range(len(documents)),
    key=lambda i: sum(
        a * b for a, b in zip(query_embedding, doc_embeddings[i])
    ),
)
print(f"Best match: {documents[best_idx]}")

# --- Step 2: Grounded chat with retrieved context ---

response = client.chat(
    model="command-a-03-2025",
    messages=[
        {
            "role": "system",
            "content": "Answer based on the provided context only.",
        },
        {
            "role": "user",
            "content": f"Context: {documents[best_idx]}\n\nWhat certifications does OCI have?",
        },
    ],
    temperature=0.3,
)
print(f"Answer: {response.message.content[0].text}")

# --- Step 3: Tool use — call an external API ---

response = client.chat(
    model="command-a-03-2025",
    messages=[
        {
            "role": "user",
            "content": "What's the current stock price of ORCL?",
        }
    ],
    tools=[
        {
            "type": "function",
            "function": {
                "name": "get_stock_price",
                "description": "Get the current stock price for a ticker symbol",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "ticker": {
                            "type": "string",
                            "description": "Stock ticker symbol",
                        }
                    },
                    "required": ["ticker"],
                },
            },
        }
    ],
)

# Model returns a tool call
tool_call = response.message.tool_calls[0]
print(
    f"Tool call: {tool_call.function.name}({tool_call.function.arguments})"
)

# Send the tool result back
final = client.chat(
    model="command-a-03-2025",
    messages=[
        {
            "role": "user",
            "content": "What's the current stock price of ORCL?",
        },
        {
            "role": "assistant",
            "tool_calls": [
                {
                    "id": tool_call.id,
                    "type": "function",
                    "function": {
                        "name": tool_call.function.name,
                        "arguments": tool_call.function.arguments,
                    },
                }
            ],
            "tool_plan": response.message.tool_plan,
        },
        {
            "role": "tool",
            "tool_call_id": tool_call.id,
            "content": [
                {
                    "type": "text",
                    "text": '{"ticker": "ORCL", "price": 187.42, "currency": "USD"}',
                }
            ],
        },
    ],
    tools=[
        {
            "type": "function",
            "function": {
                "name": "get_stock_price",
                "description": "Get the current stock price for a ticker symbol",
                "parameters": {
                    "type": "object",
                    "properties": {"ticker": {"type": "string"}},
                    "required": ["ticker"],
                },
            },
        }
    ],
)
print(f"Final answer: {final.message.content[0].text}")

# --- Step 4: Vision — analyze an image ---

with open("chart.png", "rb") as f:
    img_b64 = base64.b64encode(f.read()).decode()

response = client.chat(
    model="command-a-vision",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "Describe the trend shown in this chart.",
                },
                {
                    "type": "image_url",
                    "image_url": {
                        "url": f"data:image/png;base64,{img_b64}"
                    },
                },
            ],
        }
    ],
)
print(f"Vision: {response.message.content[0].text}")

# --- Step 5: Stream a response in real time ---

print("Streaming: ", end="")
for event in client.chat_stream(
    model="command-a-03-2025",
    messages=[
        {
            "role": "user",
            "content": "Summarize why enterprises choose OCI for AI.",
        }
    ],
):
    if event.type == "content-delta":
        print(event.delta.message.content.text, end="")
print()

추가 리소스 (Additional Resources)

또한 OCI Console, OCI CLI, 또는 OCI API를 통해 OCI에서 Cohere 모델을 직접 작업할 수도 있어요.

더 알아보기 (Learn more)