Microsoft Azure 플랫폼에서의 Cohere
Microsoft Azure 플랫폼에서의 Cohere
이 문서는 Microsoft Azure에서 Cohere 모델을 사용하는 방법을 설명해요. Azure AI Foundry를 통해 Cohere의 Command, Embed, Rerank, Parse 모델을 배포하고 활용하는 전체 과정을 다룰게요.
출처: 문서
본문
이 문서에서는 Azure AI Foundry를 사용해 Cohere의 Command, Embed, Rerank, Parse 모델을 Microsoft의 Azure 클라우드 컴퓨팅 플랫폼에 배포하는 방법을 배우게 돼요. Azure AI Foundry에 대한 자세한 내용은 그 문서에서 확인할 수 있어요.
Azure AI Foundry를 통해 토큰 기반 결제(pay-as-you-go)로 이용할 수 있는 모델은 다음과 같아요:
- Command A
- Embed v4
- Embed v3 - English
- Embed v3 - Multilingual
- Cohere Rerank V4.0 Pro
- Cohere Rerank V4.0 Fast
Azure AI Foundry를 통해 페이지 기반 결제(pay-as-you-go)로 이용할 수 있는 모델은 다음과 같아요:
- Parse v5
사전 준비물 (Prerequisites)
Command, Embed, Rerank 또는 Parse 중 무엇을 사용하든 초기 설정은 동일해요. 필요한 것은 다음과 같아요:
- 유효한 결제 수단이 있는 Azure 구독. 무료 또는 평가판 Azure 구독은 작동하지 않아요. Azure 구독이 없다면 유료 Azure 계정을 만들어 시작해요.
- Azure AI hub 리소스. 참고: Cohere 모델의 경우 pay-as-you-go 배포 제공은
East US,East US 2,North Central US,South Central US,Sweden Central,West US또는West US 3리전에서 생성된 AI hub에서만 사용할 수 있어요. - Azure AI Studio의 Azure AI 프로젝트.
- Azure AI Studio에서 작업에 대한 접근 권한을 부여하는 데 Azure 역할 기반 접근 제어(Azure RBAC)가 사용돼요. 필요한 단계를 수행하려면 사용자 계정에 리소스 그룹에 대한 Azure AI Developer 역할이 할당되어 있어야 해요. 권한에 대한 자세한 내용은 Azure AI Studio의 역할 기반 접근 제어를 참고하세요.
Command, Embed, Rerank 또는 Parse 기반 워크플로를 위해서는 배포를 만들고 모델을 사용하는 작업도 필요해요. Foundry 모델을 배포하는 방법에 대한 자세한 정보는 여기를 참고하세요.
텍스트 생성 (Text Generation)
Command R과 Command R+ 추론에는 두 가지 경로를 제공해요:
v1/chat/completions는 Azure AI Generative Messages API 스키마를 따르는 경로예요;v1/chat는 Cohere의 네이티브 API 스키마를 지원해요.
Azure API에 대한 자세한 내용은 Microsoft 문서에서 확인할 수 있어요.
Azure에서 Cohere 모델과 프로그래밍 방식으로 상호 작용하는 방법을 보여주는 코드 스니펫은 다음과 같아요:
PYTHON
import urllib.request
import json
# Configure payload data sending to API endpoint
data = {
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is good about Wuhan?"},
],
"max_tokens": 500,
"temperature": 0.3,
"stream": "True",
}
body = str.encode(json.dumps(data))
# Replace the url with your API endpoint
url = (
"https://your-endpoint.inference.ai.azure.com/v1/chat/completions"
)
# Replace this with the key for the endpoint
api_key = "your-auth-key"
if not api_key:
raise Exception("API Key is missing")
headers = {
"Content-Type": "application/json",
"Authorization": (api_key),
}
req = urllib.request.Request(url, body, headers)
try:
response = urllib.request.urlopen(req)
result = response.read()
print(result)
except urllib.error.HTTPError as error:
print("The request failed with status code: " + str(error.code))
# Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
print(error.info())
print(error.read().decode("utf8", "ignore"))
응답 스트리밍 예제를 포함한 더 많은 코드 스니펫은 이 노트북에서 확인할 수 있어요.
이 섹션 이름이 "Text Generation"이긴 하지만, 이 모델들이 훨씬 더 많은 일을 할 수 있다는 점을 짚어 둘 가치가 있어요. 특히 Azure에서 호스팅되는 Cohere 모델을 검색 증강 생성(retrieval augmented generation)과 멀티스텝 도구 사용 모두에 사용할 수 있어요. 자세한 내용은 링크된 페이지를 확인해 보세요.
마지막으로, 2024년 8월에 Command R과 Command R+의 새 버전을 출시했고, 두 버전 모두 이제 Azure에서 사용할 수 있어요. 자세한 내용은 이 Microsoft 문서를 참고하세요 (Cohere Command R 08-2024 또는 Cohere Command R+ 08-2024 탭을 선택하세요).
Embeddings
Embed v4와 Embed v3 추론에는 두 가지 경로를 제공해요:
v1/embeddings는 Azure AI Generative Messages API 스키마를 따르는 경로예요;v1/embed는 Cohere의 네이티브 API 스키마를 지원해요.
Azure API에 대한 자세한 내용은 Microsoft 문서에서 확인할 수 있어요.
PYTHON
import urllib.request
import json
# Configure payload data sending to API endpoint
data = {"input": ["hi"]}
body = str.encode(json.dumps(data))
# Replace the url with your API endpoint
url = "https://your-endpoint.inference.ai.azure.com/v1/embedding"
# Replace this with the key for the endpoint
api_key = "your-auth-key"
if not api_key:
raise Exception("API Key is missing")
headers = {
"Content-Type": "application/json",
"Authorization": (api_key),
}
req = urllib.request.Request(url, body, headers)
try:
response = urllib.request.urlopen(req)
result = response.read()
print(result)
except urllib.error.HTTPError as error:
print("The request failed with status code: " + str(error.code))
# Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
print(error.info())
print(error.read().decode("utf8", "ignore"))
Rerank
현재 Rerank v4.0 Pro, Rerank v4.0 Fast, Rerank v3.5, Rerank v3 English, Rerank 3 Multilingual 추론을 위해 v1/rerank 엔드포인트를 제공해요. API 사용에 대한 자세한 내용은 참조 섹션을 참고하세요.
PYTHON
import cohere
co = cohere.Client(
base_url="https://<endpoint>.<region>.inference.ai.azure.com/v1/rerank",
api_key="<key>",
)
documents = [
{
"Title": "Incorrect Password",
"Content": "Hello, I have been trying to access my account for the past hour and it keeps saying my password is incorrect. Can you please help me?",
},
{
"Title": "Confirmation Email Missed",
"Content": "Hi, I recently purchased a product from your website but I never received a confirmation email. Can you please look into this for me?",
},
{
"Title": "Questions about Return Policy",
"Content": "Hello, I have a question about the return policy for this product. I purchased it a few weeks ago and it is defective.",
},
{
"Title": "Customer Support is Busy",
"Content": "Good morning, I have been trying to reach your customer support team for the past week but I keep getting a busy signal. Can you please help me?",
},
{
"Title": "Received Wrong Item",
"Content": "Hi, I have a question about my recent order. I received the wrong item and I need to return it.",
},
{
"Title": "Customer Service is Unavailable",
"Content": "Hello, I have been trying to reach your customer support team for the past hour but I keep getting a busy signal. Can you please help me?",
},
{
"Title": "Return Policy for Defective Product",
"Content": "Hi, I have a question about the return policy for this product. I purchased it a few weeks ago and it is defective.",
},
{
"Title": "Wrong Item Received",
"Content": "Good morning, I have a question about my recent order. I received the wrong item and I need to return it.",
},
{
"Title": "Return Defective Product",
"Content": "Hello, I have a question about the return policy for this product. I purchased it a few weeks ago and it is defective.",
},
]
response = co.rerank(
documents=documents,
query="What emails have been about returning items?",
model="rerank-v4.0-pro",
rank_fields=["Title", "Content"],
top_n=5,
)
Parse
Cohere SDK를 사용해 Azure AI Foundry에서 Parse를 호출할 수 있어요. Parse는 문서 이미지를 구조화된 Markdown으로 변환해요. 데이터 URI가 페이로드 제한을 넘지 않도록 먼저 이미지 크기를 조정하고 WEBP로 변환하세요.
PYTHON
from PIL import Image
import base64
import cohere
IMG_MAX_SIZE = 2048
with Image.open("page.png") as img:
img.thumbnail(
(IMG_MAX_SIZE, IMG_MAX_SIZE), Image.Resampling.LANCZOS
)
if img.mode != "RGB":
img = img.convert("RGB")
img.save("page.webp", format="WEBP", quality=90)
with open("page.webp", "rb") as f:
b64 = base64.b64encode(f.read()).decode()
image_url = f"data:image/webp;base64,{b64}"
co = cohere.ClientV2(
api_key="<key>",
base_url="https://<endpoint>.<region>.inference.ai.azure.com/",
)
response = co.parse(
model="parse-v5.0",
document={
"type": "image_url",
"image_url": image_url,
},
output_format="markdown", # or "blocks"
)
print(response)
Cohere SDK 사용하기
Cohere SDK 클라이언트를 사용해 Azure AI Foundry를 통해 배포된 Cohere 모델을 사용할 수 있어요. 즉, RAG, 도구 사용, 구조화된 출력 등 SDK의 기능을 활용할 수 있다는 뜻이에요.
다음은 다양한 모델에 SDK를 사용하는 몇 가지 예시예요.
설정 (Setup)
PYTHON
# pip install cohere
import cohere
# For Command models
co_chat = cohere.Client(
api_key="AZURE_INFERENCE_CREDENTIAL",
base_url="AZURE_MODEL_ENDPOINT", # Example - https://Cohere-command-r-plus-08-2024-xyz.eastus.models.ai.azure.com/
)
# For Embed models
co_embed = cohere.Client(
api_key="AZURE_INFERENCE_CREDENTIAL",
base_url="AZURE_MODEL_ENDPOINT", # Example - https://cohere-embed-v4-xyz.eastus.models.ai.azure.com/
)
# For Rerank models
co_rerank = cohere.Client(
api_key="AZURE_INFERENCE_CREDENTIAL",
base_url="AZURE_MODEL_ENDPOINT", # Example - https://cohere-rerank-v4-pro-xyz.eastus.models.ai.azure.com/
)
# For Parse models
co_parse = cohere.ClientV2(
api_key="AZURE_INFERENCE_CREDENTIAL",
base_url="AZURE_MODEL_ENDPOINT", # Example - https://cohere-parse-v5-xyz.eastus.models.ai.azure.com/
)
Chat
PYTHON
message = "I'm joining a new startup called Co1t today. Could you help me write a short introduction message to my teammates."
response = co_chat.chat(message=message)
print(response)
RAG
PYTHON
faqs_short = [
{
"text": "Reimbursing Travel Expenses: Easily manage your travel expenses by submitting them through our finance tool. Approvals are prompt and straightforward."
},
{
"text": "Health and Wellness Benefits: We care about your well-being and offer gym memberships, on-site yoga classes, and comprehensive health insurance."
},
]
query = "Are there fitness-related perks?"
response = co_chat.chat(message=query, documents=faqs_short)
print(response)
Embed
PYTHON
docs = [
"Joining Slack Channels: You will receive an invite via email. Be sure to join relevant channels to stay informed and engaged.",
"Finding Coffee Spots: For your caffeine fix, head to the break room's coffee machine or cross the street to the café for artisan coffee.",
]
doc_emb = co_embed.embed(
input_type="search_document",
texts=docs,
).embeddings
Rerank
PYTHON
faqs_short = [
{
"text": "Reimbursing Travel Expenses: Easily manage your travel expenses by submitting them through our finance tool. Approvals are prompt and straightforward."
},
{
"text": "Working from Abroad: Working remotely from another country is possible. Simply coordinate with your manager and ensure your availability during core hours."
},
{
"text": "Health and Wellness Benefits: We care about your well-being and offer gym memberships, on-site yoga classes, and comprehensive health insurance."
},
]
query = "Are there fitness-related perks?"
results = co_rerank.rerank(
query=query,
documents=faqs_short,
top_n=2,
model="rerank-v4.0-pro",
)
Parse
PYTHON
response = co_parse.parse(
model="parse-v5.0",
document={
"type": "image_url",
"image_url": image_url, # data URI; see the Parse section above
},
output_format="markdown", # or "blocks"
)
print(response)
Command와 Embed에 대한 다른 예제도 여기서 확인할 수 있어요.
여기서 이해해야 할 중요한 점은 신규 및 기존 고객 모두 Cohere SDK와의 통합을 그대로 활용하면서 Azure에서 모델을 호출할 수 있다는 거예요.