Jais 채팅 모델을 사용하는 방법
Important
이 문서에 표시된 항목(미리 보기)은 현재 퍼블릭 미리 보기에서 확인할 수 있습니다. 이 미리 보기는 서비스 수준 계약 없이 제공되며, 프로덕션 워크로드에는 권장되지 않습니다. 특정 기능이 지원되지 않거나 기능이 제한될 수 있습니다. 자세한 내용은 Microsoft Azure Preview에 대한 추가 사용 약관을 참조하세요.
이 문서에서는 Jais 채팅 모델 및 사용 방법에 대해 알아봅니다. JAIS 30b 채팅은 아랍어 및 영어 자동 회귀 이중 언어 LLM입니다. 조정된 버전은 감독된 SFT(미세 조정)를 사용합니다. 모델은 아랍어 및 영어 프롬프트 응답 쌍으로 미세 조정됩니다. 미세 조정 데이터 세트에는 다양한 도메인에 걸쳐 광범위한 교육 데이터가 포함되었습니다. 이 모델은 질문 답변, 코드 생성 및 텍스트 콘텐츠에 대한 추론을 비롯한 다양한 일반적인 작업을 다룹니다. 아랍어로 성능을 향상시키기 위해 Core42 팀은 사내 아랍어 데이터 세트를 개발하고 일부 오픈 소스 영어 지침을 아랍어로 번역했습니다.
- 컨텍스트 길이: JAIS는 8K의 컨텍스트 길이를 지원합니다.
- 입력: 모델 입력은 텍스트에만 해당합니다.
- 출력: 모델은 텍스트만 생성합니다.
Important
미리 보기에 있는 모델은 모델 카탈로그의 모델 카드에서 미리 보기로 표시됩니다.
Jais 채팅 모델
해당 모델 카드의 모델에 대해 자세히 알아볼 수 있습니다.
필수 조건
Azure AI Foundry에서 Jais 채팅 모델을 사용하려면 다음 필수 구성 요소가 필요합니다.
모델 배포
서버리스 API에 배포
Jais 채팅 모델은 종량제 청구를 사용하여 서버리스 API 엔드포인트에 배포할 수 있습니다. 이 종류의 배포를 활용하면 조직에 필요한 엔터프라이즈 보안 및 규정 준수를 유지하면서 구독에서 모델을 호스트하지 않고 API로 모델을 사용할 수 있습니다.
서버리스 API 엔드포인트에 배포해도 구독의 할당량이 필요하지 않습니다. 모델이 아직 배포되지 않은 경우 Azure AI Foundry 포털, Python용 Azure Machine Learning SDK, Azure CLI 또는 ARM 템플릿을 사용하여 모델을 서버리스 API로 배포합니다.
설치된 유추 패키지
Python과 함께 azure-ai-inference
패키지를 사용하여 이 모델의 예측을 사용할 수 있습니다. 이 패키지를 설치하려면 다음 필수 구성 요소가 필요합니다.
- pip를 포함하여 Python 3.8 이상이 설치됨.
- 엔드포인트 URL. 클라이언트 라이브러리를 생성하려면 엔드포인트 URL을 전달해야 합니다. 엔드포인트 URL에는
https://your-host-name.your-azure-region.inference.ai.azure.com
형식이 있습니다. 여기서your-host-name
은(는) 고유한 모델 배포 호스트 이름이고your-azure-region
은(는) 모델이 배포되는 Azure 지역입니다(예: eastus2). - 모델 배포 및 인증 기본 설정에 따라 서비스에 대해 인증할 키 또는 Microsoft Entra ID 자격 증명이 필요합니다. 키는 32자 문자열입니다.
이러한 필수 구성 요소가 있으면 다음 명령을 사용하여 Azure AI 유추 패키지를 설치합니다.
pip install azure-ai-inference
Azure AI 유추 패키지 및 참조에 대해 자세히 알아보세요.
채팅 완료 작업
이 섹션에서는 채팅을 위한 채팅 완성 모델과 함께 Azure AI 모델 유추 API를 사용합니다.
팁
Azure AI 모델 유추 API를 사용하면 Jais 채팅 모델을 포함하여 동일한 코드와 구조로 Azure AI Foundry 포털에 배포된 대부분의 모델과 통신할 수 있습니다.
모델을 사용할 클라이언트 만들기
먼저 모델을 사용할 클라이언트를 만듭니다. 다음 코드는 환경 변수에 저장된 엔드포인트 URL 및 키를 사용합니다.
import os
from azure.ai.inference import ChatCompletionsClient
from azure.core.credentials import AzureKeyCredential
client = ChatCompletionsClient(
endpoint=os.environ["AZURE_INFERENCE_ENDPOINT"],
credential=AzureKeyCredential(os.environ["AZURE_INFERENCE_CREDENTIAL"]),
)
모델의 기능 가져오기
/info
경로는 엔드포인트에 배포된 모델에 대한 정보를 반환합니다. 다음 메서드를 호출하여 모델의 정보를 반환합니다.
model_info = client.get_model_info()
응답은 다음과 같습니다.
print("Model name:", model_info.model_name)
print("Model type:", model_info.model_type)
print("Model provider name:", model_info.model_provider_name)
Model name: jais-30b-chat
Model type: chat-completions
Model provider name: G42
채팅 완료 요청 만들기
다음 예제에서는 모델에 대한 기본 채팅 완료 요청을 만드는 방법을 보여 줍니다.
from azure.ai.inference.models import SystemMessage, UserMessage
response = client.complete(
messages=[
SystemMessage(content="You are a helpful assistant."),
UserMessage(content="How many languages are in the world?"),
],
)
응답은 다음과 같습니다. 여기서 모델의 사용 통계를 볼 수 있습니다.
print("Response:", response.choices[0].message.content)
print("Model:", response.model)
print("Usage:")
print("\tPrompt tokens:", response.usage.prompt_tokens)
print("\tTotal tokens:", response.usage.total_tokens)
print("\tCompletion tokens:", response.usage.completion_tokens)
Response: As of now, it's estimated that there are about 7,000 languages spoken around the world. However, this number can vary as some languages become extinct and new ones develop. It's also important to note that the number of speakers can greatly vary between languages, with some having millions of speakers and others only a few hundred.
Model: jais-30b-chat
Usage:
Prompt tokens: 19
Total tokens: 91
Completion tokens: 72
응답의 usage
섹션을 검사하여 프롬프트에 사용된 토큰 수, 생성된 총 토큰 수 및 완료에 사용된 토큰 수를 확인합니다.
콘텐츠 스트리밍
기본적으로 완료 API는 생성된 전체 콘텐츠를 단일 응답으로 반환합니다. 긴 완료를 생성하는 경우 응답을 기다리는 데 몇 초 정도 걸릴 수 있습니다.
생성될 때 가져오기 위해 콘텐츠를 스트리밍할 수 있습니다. 콘텐츠를 스트리밍하면 콘텐츠를 사용할 수 있게 되면 완료 처리를 시작할 수 있습니다. 이 모드는 데이터 전용 서버 전송 이벤트 응답을 다시 스트리밍하는 개체를 반환합니다. 메시지 필드가 아닌 델타 필드에서 청크를 추출합니다.
result = client.complete(
messages=[
SystemMessage(content="You are a helpful assistant."),
UserMessage(content="How many languages are in the world?"),
],
temperature=0,
top_p=1,
max_tokens=2048,
stream=True,
)
완성을 스트리밍하려면 모델을 호출할 때 stream=True
를 설정합니다.
출력을 시각화하려면 스트림을 인쇄하는 도우미 함수를 정의합니다.
def print_stream(result):
"""
Prints the chat completion with streaming.
"""
import time
for update in result:
if update.choices:
print(update.choices[0].delta.content, end="")
스트리밍에서 콘텐츠를 생성하는 방법을 시각화할 수 있습니다.
print_stream(result)
유추 클라이언트에서 지원하는 더 많은 매개 변수 살펴보기
유추 클라이언트에서 지정할 수 있는 다른 매개 변수를 탐색합니다. 지원되는 모든 매개 변수 및 해당 설명서의 전체 목록은 Azure AI 모델 유추 API 참조를 확인하세요.
from azure.ai.inference.models import ChatCompletionsResponseFormatText
response = client.complete(
messages=[
SystemMessage(content="You are a helpful assistant."),
UserMessage(content="How many languages are in the world?"),
],
presence_penalty=0.1,
frequency_penalty=0.8,
max_tokens=2048,
stop=["<|endoftext|>"],
temperature=0,
top_p=1,
response_format={ "type": ChatCompletionsResponseFormatText() },
)
Warning
Jais 모델은 JSON 출력 서식(response_format = { "type": "json_object" }
)을 지원하지 않습니다. 언제든지 모델에 JSON 출력을 생성하라는 메시지를 표시할 수 있습니다. 그러나 이러한 출력이 유효한 JSON으로 보장되지는 않습니다.
지원되는 매개 변수 목록에 없는 매개 변수를 전달하려면 추가 매개 변수를 사용하여 기본 모델에 전달할 수 있습니다. 모델 추가 매개 변수 전달을 참조하세요.
모델에 추가 매개 변수 전달
Azure AI 모델 유추 API를 사용하면 모델에 추가 매개 변수를 전달할 수 있습니다. 다음 코드 예에서는 추가 매개 변수 logprobs
를 모델에 전달하는 방법을 보여줍니다.
Azure AI 모델 유추 API에 추가 매개 변수를 전달하기 전에 모델이 이러한 추가 매개 변수를 지원하는지 확인합니다. 기본 모델에 대한 요청이 이루어지면 헤더 extra-parameters
의 pass-through
값이 모델에 전달됩니다. 이 값은 모델에 추가 매개 변수를 전달하도록 엔드포인트에 지시합니다. 모델에서 추가 매개 변수를 사용하면 모델이 실제로 매개 변수를 처리할 수 있다고 보장할 수 없습니다. 지원되는 추가 매개 변수를 이해하려면 모델의 설명서를 읽어보세요.
response = client.complete(
messages=[
SystemMessage(content="You are a helpful assistant."),
UserMessage(content="How many languages are in the world?"),
],
model_extras={
"logprobs": True
}
)
콘텐츠 안전 적용
Azure AI 모델 유추 API는 Azure AI 콘텐츠 안전을 지원합니다. Azure AI 콘텐츠 안전이 켜져 있는 배포를 사용하는 경우 입력 및 출력은 유해한 콘텐츠의 출력을 감지하고 방지하기 위한 분류 모델의 앙상블을 통과합니다. 콘텐츠 필터링(미리 보기) 시스템은 입력 프롬프트와 출력 완성 모두에서 잠재적으로 유해한 콘텐츠의 특정 범주를 검색하고 조치를 취합니다.
다음 예제에서는 모델이 입력 프롬프트에서 유해한 콘텐츠를 감지하고 콘텐츠 안전이 사용하도록 설정된 경우 이벤트를 처리하는 방법을 보여 줍니다.
from azure.ai.inference.models import AssistantMessage, UserMessage, SystemMessage
try:
response = client.complete(
messages=[
SystemMessage(content="You are an AI assistant that helps people find information."),
UserMessage(content="Chopping tomatoes and cutting them into cubes or wedges are great ways to practice your knife skills."),
]
)
print(response.choices[0].message.content)
except HttpResponseError as ex:
if ex.status_code == 400:
response = ex.response.json()
if isinstance(response, dict) and "error" in response:
print(f"Your request triggered an {response['error']['code']} error:\n\t {response['error']['message']}")
else:
raise
raise
팁
Azure AI 콘텐츠 안전 설정을 구성하고 제어하는 방법에 대한 자세한 내용은 Azure AI 콘텐츠 안전 설명서를 확인하세요.
Jais 채팅 모델
해당 모델 카드의 모델에 대해 자세히 알아볼 수 있습니다.
필수 조건
Azure AI Foundry에서 Jais 채팅 모델을 사용하려면 다음 필수 구성 요소가 필요합니다.
모델 배포
서버리스 API에 배포
Jais 채팅 모델은 종량제 청구를 사용하여 서버리스 API 엔드포인트에 배포할 수 있습니다. 이 종류의 배포를 활용하면 조직에 필요한 엔터프라이즈 보안 및 규정 준수를 유지하면서 구독에서 모델을 호스트하지 않고 API로 모델을 사용할 수 있습니다.
서버리스 API 엔드포인트에 배포해도 구독의 할당량이 필요하지 않습니다. 모델이 아직 배포되지 않은 경우 Azure AI Foundry 포털, Python용 Azure Machine Learning SDK, Azure CLI 또는 ARM 템플릿을 사용하여 모델을 서버리스 API로 배포합니다.
설치된 유추 패키지
@azure-rest/ai-inference
패키지를 npm
으로부터 사용하여 이 모델의 예측을 사용할 수 있습니다. 이 패키지를 설치하려면 다음 필수 구성 요소가 필요합니다.
-
npm
이(가) 있는Node.js
의 LTS 버전입니다. - 엔드포인트 URL. 클라이언트 라이브러리를 생성하려면 엔드포인트 URL을 전달해야 합니다. 엔드포인트 URL에는
https://your-host-name.your-azure-region.inference.ai.azure.com
형식이 있습니다. 여기서your-host-name
은(는) 고유한 모델 배포 호스트 이름이고your-azure-region
은(는) 모델이 배포되는 Azure 지역입니다(예: eastus2). - 모델 배포 및 인증 기본 설정에 따라 서비스에 대해 인증할 키 또는 Microsoft Entra ID 자격 증명이 필요합니다. 키는 32자 문자열입니다.
이러한 필수 구성 요소가 있으면 다음 명령을 사용하여 JavaScript용 Azure 유추 라이브러리를 설치합니다.
npm install @azure-rest/ai-inference
채팅 완료 작업
이 섹션에서는 채팅을 위한 채팅 완성 모델과 함께 Azure AI 모델 유추 API를 사용합니다.
팁
Azure AI 모델 유추 API를 사용하면 Jais 채팅 모델을 포함하여 동일한 코드와 구조로 Azure AI Foundry 포털에 배포된 대부분의 모델과 통신할 수 있습니다.
모델을 사용할 클라이언트 만들기
먼저 모델을 사용할 클라이언트를 만듭니다. 다음 코드는 환경 변수에 저장된 엔드포인트 URL 및 키를 사용합니다.
import ModelClient from "@azure-rest/ai-inference";
import { isUnexpected } from "@azure-rest/ai-inference";
import { AzureKeyCredential } from "@azure/core-auth";
const client = new ModelClient(
process.env.AZURE_INFERENCE_ENDPOINT,
new AzureKeyCredential(process.env.AZURE_INFERENCE_CREDENTIAL)
);
모델의 기능 가져오기
/info
경로는 엔드포인트에 배포된 모델에 대한 정보를 반환합니다. 다음 메서드를 호출하여 모델의 정보를 반환합니다.
var model_info = await client.path("/info").get()
응답은 다음과 같습니다.
console.log("Model name: ", model_info.body.model_name)
console.log("Model type: ", model_info.body.model_type)
console.log("Model provider name: ", model_info.body.model_provider_name)
Model name: jais-30b-chat
Model type: chat-completions
Model provider name: G42
채팅 완료 요청 만들기
다음 예제에서는 모델에 대한 기본 채팅 완료 요청을 만드는 방법을 보여 줍니다.
var messages = [
{ role: "system", content: "You are a helpful assistant" },
{ role: "user", content: "How many languages are in the world?" },
];
var response = await client.path("/chat/completions").post({
body: {
messages: messages,
}
});
응답은 다음과 같습니다. 여기서 모델의 사용 통계를 볼 수 있습니다.
if (isUnexpected(response)) {
throw response.body.error;
}
console.log("Response: ", response.body.choices[0].message.content);
console.log("Model: ", response.body.model);
console.log("Usage:");
console.log("\tPrompt tokens:", response.body.usage.prompt_tokens);
console.log("\tTotal tokens:", response.body.usage.total_tokens);
console.log("\tCompletion tokens:", response.body.usage.completion_tokens);
Response: As of now, it's estimated that there are about 7,000 languages spoken around the world. However, this number can vary as some languages become extinct and new ones develop. It's also important to note that the number of speakers can greatly vary between languages, with some having millions of speakers and others only a few hundred.
Model: jais-30b-chat
Usage:
Prompt tokens: 19
Total tokens: 91
Completion tokens: 72
응답의 usage
섹션을 검사하여 프롬프트에 사용된 토큰 수, 생성된 총 토큰 수 및 완료에 사용된 토큰 수를 확인합니다.
콘텐츠 스트리밍
기본적으로 완료 API는 생성된 전체 콘텐츠를 단일 응답으로 반환합니다. 긴 완료를 생성하는 경우 응답을 기다리는 데 몇 초 정도 걸릴 수 있습니다.
생성될 때 가져오기 위해 콘텐츠를 스트리밍할 수 있습니다. 콘텐츠를 스트리밍하면 콘텐츠를 사용할 수 있게 되면 완료 처리를 시작할 수 있습니다. 이 모드는 데이터 전용 서버 전송 이벤트 응답을 다시 스트리밍하는 개체를 반환합니다. 메시지 필드가 아닌 델타 필드에서 청크를 추출합니다.
var messages = [
{ role: "system", content: "You are a helpful assistant" },
{ role: "user", content: "How many languages are in the world?" },
];
var response = await client.path("/chat/completions").post({
body: {
messages: messages,
}
}).asNodeStream();
완성을 스트리밍하려면 모델을 호출할 때 .asNodeStream()
을 사용합니다.
스트리밍에서 콘텐츠를 생성하는 방법을 시각화할 수 있습니다.
var stream = response.body;
if (!stream) {
stream.destroy();
throw new Error(`Failed to get chat completions with status: ${response.status}`);
}
if (response.status !== "200") {
throw new Error(`Failed to get chat completions: ${response.body.error}`);
}
var sses = createSseStream(stream);
for await (const event of sses) {
if (event.data === "[DONE]") {
return;
}
for (const choice of (JSON.parse(event.data)).choices) {
console.log(choice.delta?.content ?? "");
}
}
유추 클라이언트에서 지원하는 더 많은 매개 변수 살펴보기
유추 클라이언트에서 지정할 수 있는 다른 매개 변수를 탐색합니다. 지원되는 모든 매개 변수 및 해당 설명서의 전체 목록은 Azure AI 모델 유추 API 참조를 확인하세요.
var messages = [
{ role: "system", content: "You are a helpful assistant" },
{ role: "user", content: "How many languages are in the world?" },
];
var response = await client.path("/chat/completions").post({
body: {
messages: messages,
presence_penalty: "0.1",
frequency_penalty: "0.8",
max_tokens: 2048,
stop: ["<|endoftext|>"],
temperature: 0,
top_p: 1,
response_format: { type: "text" },
}
});
Warning
Jais 모델은 JSON 출력 서식(response_format = { "type": "json_object" }
)을 지원하지 않습니다. 언제든지 모델에 JSON 출력을 생성하라는 메시지를 표시할 수 있습니다. 그러나 이러한 출력이 유효한 JSON으로 보장되지는 않습니다.
지원되는 매개 변수 목록에 없는 매개 변수를 전달하려면 추가 매개 변수를 사용하여 기본 모델에 전달할 수 있습니다. 모델 추가 매개 변수 전달을 참조하세요.
모델에 추가 매개 변수 전달
Azure AI 모델 유추 API를 사용하면 모델에 추가 매개 변수를 전달할 수 있습니다. 다음 코드 예에서는 추가 매개 변수 logprobs
를 모델에 전달하는 방법을 보여줍니다.
Azure AI 모델 유추 API에 추가 매개 변수를 전달하기 전에 모델이 이러한 추가 매개 변수를 지원하는지 확인합니다. 기본 모델에 대한 요청이 이루어지면 헤더 extra-parameters
의 pass-through
값이 모델에 전달됩니다. 이 값은 모델에 추가 매개 변수를 전달하도록 엔드포인트에 지시합니다. 모델에서 추가 매개 변수를 사용하면 모델이 실제로 매개 변수를 처리할 수 있다고 보장할 수 없습니다. 지원되는 추가 매개 변수를 이해하려면 모델의 설명서를 읽어보세요.
var messages = [
{ role: "system", content: "You are a helpful assistant" },
{ role: "user", content: "How many languages are in the world?" },
];
var response = await client.path("/chat/completions").post({
headers: {
"extra-params": "pass-through"
},
body: {
messages: messages,
logprobs: true
}
});
콘텐츠 안전 적용
Azure AI 모델 유추 API는 Azure AI 콘텐츠 안전을 지원합니다. Azure AI 콘텐츠 안전이 켜져 있는 배포를 사용하는 경우 입력 및 출력은 유해한 콘텐츠의 출력을 감지하고 방지하기 위한 분류 모델의 앙상블을 통과합니다. 콘텐츠 필터링(미리 보기) 시스템은 입력 프롬프트와 출력 완성 모두에서 잠재적으로 유해한 콘텐츠의 특정 범주를 검색하고 조치를 취합니다.
다음 예제에서는 모델이 입력 프롬프트에서 유해한 콘텐츠를 감지하고 콘텐츠 안전이 사용하도록 설정된 경우 이벤트를 처리하는 방법을 보여 줍니다.
try {
var messages = [
{ role: "system", content: "You are an AI assistant that helps people find information." },
{ role: "user", content: "Chopping tomatoes and cutting them into cubes or wedges are great ways to practice your knife skills." },
];
var response = await client.path("/chat/completions").post({
body: {
messages: messages,
}
});
console.log(response.body.choices[0].message.content);
}
catch (error) {
if (error.status_code == 400) {
var response = JSON.parse(error.response._content);
if (response.error) {
console.log(`Your request triggered an ${response.error.code} error:\n\t ${response.error.message}`);
}
else
{
throw error;
}
}
}
팁
Azure AI 콘텐츠 안전 설정을 구성하고 제어하는 방법에 대한 자세한 내용은 Azure AI 콘텐츠 안전 설명서를 확인하세요.
Jais 채팅 모델
해당 모델 카드의 모델에 대해 자세히 알아볼 수 있습니다.
필수 조건
Azure AI Foundry에서 Jais 채팅 모델을 사용하려면 다음 필수 구성 요소가 필요합니다.
모델 배포
서버리스 API에 배포
Jais 채팅 모델은 종량제 청구를 사용하여 서버리스 API 엔드포인트에 배포할 수 있습니다. 이 종류의 배포를 활용하면 조직에 필요한 엔터프라이즈 보안 및 규정 준수를 유지하면서 구독에서 모델을 호스트하지 않고 API로 모델을 사용할 수 있습니다.
서버리스 API 엔드포인트에 배포해도 구독의 할당량이 필요하지 않습니다. 모델이 아직 배포되지 않은 경우 Azure AI Foundry 포털, Python용 Azure Machine Learning SDK, Azure CLI 또는 ARM 템플릿을 사용하여 모델을 서버리스 API로 배포합니다.
설치된 유추 패키지
NuGet으로부터 Azure.AI.Inference
패키지를 사용하여 이 모델의 예측을 사용할 수 있습니다. 이 패키지를 설치하려면 다음 필수 구성 요소가 필요합니다.
- 엔드포인트 URL입니다. 클라이언트 라이브러리를 생성하려면 엔드포인트 URL을 전달해야 합니다. 엔드포인트 URL에는
https://your-host-name.your-azure-region.inference.ai.azure.com
형식이 있습니다. 여기서your-host-name
은(는) 고유한 모델 배포 호스트 이름이고your-azure-region
은(는) 모델이 배포되는 Azure 지역입니다(예: eastus2). - 모델 배포 및 인증 기본 설정에 따라 서비스에 대해 인증할 키 또는 Microsoft Entra ID 자격 증명이 필요합니다. 키는 32자 문자열입니다.
이러한 필수 구성 요소가 있으면 다음 명령을 사용하여 Azure AI 유추 라이브러리를 설치합니다.
dotnet add package Azure.AI.Inference --prerelease
Microsoft Entra ID(이전의 Azure Active Directory)로 인증할 수도 있습니다. Azure SDK와 함께 제공되는 자격 증명 공급자를 사용하려면 다음의 Azure.Identity
패키지를 설치합니다.
dotnet add package Azure.Identity
다음 네임스페이스를 가져옵니다.
using Azure;
using Azure.Identity;
using Azure.AI.Inference;
이 예제에서는 다음 네임스페이스도 사용하지만, 항상 필요하지는 않을 수도 있습니다.
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Reflection;
채팅 완료 작업
이 섹션에서는 채팅을 위한 채팅 완성 모델과 함께 Azure AI 모델 유추 API를 사용합니다.
팁
Azure AI 모델 유추 API를 사용하면 Jais 채팅 모델을 포함하여 동일한 코드와 구조로 Azure AI Foundry 포털에 배포된 대부분의 모델과 통신할 수 있습니다.
모델을 사용할 클라이언트 만들기
먼저 모델을 사용할 클라이언트를 만듭니다. 다음 코드는 환경 변수에 저장된 엔드포인트 URL 및 키를 사용합니다.
ChatCompletionsClient client = new ChatCompletionsClient(
new Uri(Environment.GetEnvironmentVariable("AZURE_INFERENCE_ENDPOINT")),
new AzureKeyCredential(Environment.GetEnvironmentVariable("AZURE_INFERENCE_CREDENTIAL"))
);
모델의 기능 가져오기
/info
경로는 엔드포인트에 배포된 모델에 대한 정보를 반환합니다. 다음 메서드를 호출하여 모델의 정보를 반환합니다.
Response<ModelInfo> modelInfo = client.GetModelInfo();
응답은 다음과 같습니다.
Console.WriteLine($"Model name: {modelInfo.Value.ModelName}");
Console.WriteLine($"Model type: {modelInfo.Value.ModelType}");
Console.WriteLine($"Model provider name: {modelInfo.Value.ModelProviderName}");
Model name: jais-30b-chat
Model type: chat-completions
Model provider name: G42
채팅 완료 요청 만들기
다음 예제에서는 모델에 대한 기본 채팅 완료 요청을 만드는 방법을 보여 줍니다.
ChatCompletionsOptions requestOptions = new ChatCompletionsOptions()
{
Messages = {
new ChatRequestSystemMessage("You are a helpful assistant."),
new ChatRequestUserMessage("How many languages are in the world?")
},
};
Response<ChatCompletions> response = client.Complete(requestOptions);
응답은 다음과 같습니다. 여기서 모델의 사용 통계를 볼 수 있습니다.
Console.WriteLine($"Response: {response.Value.Choices[0].Message.Content}");
Console.WriteLine($"Model: {response.Value.Model}");
Console.WriteLine("Usage:");
Console.WriteLine($"\tPrompt tokens: {response.Value.Usage.PromptTokens}");
Console.WriteLine($"\tTotal tokens: {response.Value.Usage.TotalTokens}");
Console.WriteLine($"\tCompletion tokens: {response.Value.Usage.CompletionTokens}");
Response: As of now, it's estimated that there are about 7,000 languages spoken around the world. However, this number can vary as some languages become extinct and new ones develop. It's also important to note that the number of speakers can greatly vary between languages, with some having millions of speakers and others only a few hundred.
Model: jais-30b-chat
Usage:
Prompt tokens: 19
Total tokens: 91
Completion tokens: 72
응답의 usage
섹션을 검사하여 프롬프트에 사용된 토큰 수, 생성된 총 토큰 수 및 완료에 사용된 토큰 수를 확인합니다.
콘텐츠 스트리밍
기본적으로 완료 API는 생성된 전체 콘텐츠를 단일 응답으로 반환합니다. 긴 완료를 생성하는 경우 응답을 기다리는 데 몇 초 정도 걸릴 수 있습니다.
생성될 때 가져오기 위해 콘텐츠를 스트리밍할 수 있습니다. 콘텐츠를 스트리밍하면 콘텐츠를 사용할 수 있게 되면 완료 처리를 시작할 수 있습니다. 이 모드는 데이터 전용 서버 전송 이벤트 응답을 다시 스트리밍하는 개체를 반환합니다. 메시지 필드가 아닌 델타 필드에서 청크를 추출합니다.
static async Task StreamMessageAsync(ChatCompletionsClient client)
{
ChatCompletionsOptions requestOptions = new ChatCompletionsOptions()
{
Messages = {
new ChatRequestSystemMessage("You are a helpful assistant."),
new ChatRequestUserMessage("How many languages are in the world? Write an essay about it.")
},
MaxTokens=4096
};
StreamingResponse<StreamingChatCompletionsUpdate> streamResponse = await client.CompleteStreamingAsync(requestOptions);
await PrintStream(streamResponse);
}
완성을 스트리밍하려면 모델을 호출할 때 CompleteStreamingAsync
메서드를 사용합니다. 이 예제에서는 호출이 비동기 메서드로 래핑됩니다.
출력을 시각화하려면 콘솔에서 스트림을 인쇄하는 비동기 메서드를 정의합니다.
static async Task PrintStream(StreamingResponse<StreamingChatCompletionsUpdate> response)
{
await foreach (StreamingChatCompletionsUpdate chatUpdate in response)
{
if (chatUpdate.Role.HasValue)
{
Console.Write($"{chatUpdate.Role.Value.ToString().ToUpperInvariant()}: ");
}
if (!string.IsNullOrEmpty(chatUpdate.ContentUpdate))
{
Console.Write(chatUpdate.ContentUpdate);
}
}
}
스트리밍에서 콘텐츠를 생성하는 방법을 시각화할 수 있습니다.
StreamMessageAsync(client).GetAwaiter().GetResult();
유추 클라이언트에서 지원하는 더 많은 매개 변수 살펴보기
유추 클라이언트에서 지정할 수 있는 다른 매개 변수를 탐색합니다. 지원되는 모든 매개 변수 및 해당 설명서의 전체 목록은 Azure AI 모델 유추 API 참조를 확인하세요.
requestOptions = new ChatCompletionsOptions()
{
Messages = {
new ChatRequestSystemMessage("You are a helpful assistant."),
new ChatRequestUserMessage("How many languages are in the world?")
},
PresencePenalty = 0.1f,
FrequencyPenalty = 0.8f,
MaxTokens = 2048,
StopSequences = { "<|endoftext|>" },
Temperature = 0,
NucleusSamplingFactor = 1,
ResponseFormat = new ChatCompletionsResponseFormatText()
};
response = client.Complete(requestOptions);
Console.WriteLine($"Response: {response.Value.Choices[0].Message.Content}");
Warning
Jais 모델은 JSON 출력 서식(response_format = { "type": "json_object" }
)을 지원하지 않습니다. 언제든지 모델에 JSON 출력을 생성하라는 메시지를 표시할 수 있습니다. 그러나 이러한 출력이 유효한 JSON으로 보장되지는 않습니다.
지원되는 매개 변수 목록에 없는 매개 변수를 전달하려면 추가 매개 변수를 사용하여 기본 모델에 전달할 수 있습니다. 모델 추가 매개 변수 전달을 참조하세요.
모델에 추가 매개 변수 전달
Azure AI 모델 유추 API를 사용하면 모델에 추가 매개 변수를 전달할 수 있습니다. 다음 코드 예에서는 추가 매개 변수 logprobs
를 모델에 전달하는 방법을 보여줍니다.
Azure AI 모델 유추 API에 추가 매개 변수를 전달하기 전에 모델이 이러한 추가 매개 변수를 지원하는지 확인합니다. 기본 모델에 대한 요청이 이루어지면 헤더 extra-parameters
의 pass-through
값이 모델에 전달됩니다. 이 값은 모델에 추가 매개 변수를 전달하도록 엔드포인트에 지시합니다. 모델에서 추가 매개 변수를 사용하면 모델이 실제로 매개 변수를 처리할 수 있다고 보장할 수 없습니다. 지원되는 추가 매개 변수를 이해하려면 모델의 설명서를 읽어보세요.
requestOptions = new ChatCompletionsOptions()
{
Messages = {
new ChatRequestSystemMessage("You are a helpful assistant."),
new ChatRequestUserMessage("How many languages are in the world?")
},
AdditionalProperties = { { "logprobs", BinaryData.FromString("true") } },
};
response = client.Complete(requestOptions, extraParams: ExtraParameters.PassThrough);
Console.WriteLine($"Response: {response.Value.Choices[0].Message.Content}");
콘텐츠 안전 적용
Azure AI 모델 유추 API는 Azure AI 콘텐츠 안전을 지원합니다. Azure AI 콘텐츠 안전이 켜져 있는 배포를 사용하는 경우 입력 및 출력은 유해한 콘텐츠의 출력을 감지하고 방지하기 위한 분류 모델의 앙상블을 통과합니다. 콘텐츠 필터링(미리 보기) 시스템은 입력 프롬프트와 출력 완성 모두에서 잠재적으로 유해한 콘텐츠의 특정 범주를 검색하고 조치를 취합니다.
다음 예제에서는 모델이 입력 프롬프트에서 유해한 콘텐츠를 감지하고 콘텐츠 안전이 사용하도록 설정된 경우 이벤트를 처리하는 방법을 보여 줍니다.
try
{
requestOptions = new ChatCompletionsOptions()
{
Messages = {
new ChatRequestSystemMessage("You are an AI assistant that helps people find information."),
new ChatRequestUserMessage(
"Chopping tomatoes and cutting them into cubes or wedges are great ways to practice your knife skills."
),
},
};
response = client.Complete(requestOptions);
Console.WriteLine(response.Value.Choices[0].Message.Content);
}
catch (RequestFailedException ex)
{
if (ex.ErrorCode == "content_filter")
{
Console.WriteLine($"Your query has trigger Azure Content Safety: {ex.Message}");
}
else
{
throw;
}
}
팁
Azure AI 콘텐츠 안전 설정을 구성하고 제어하는 방법에 대한 자세한 내용은 Azure AI 콘텐츠 안전 설명서를 확인하세요.
Jais 채팅 모델
해당 모델 카드의 모델에 대해 자세히 알아볼 수 있습니다.
필수 조건
Azure AI Foundry에서 Jais 채팅 모델을 사용하려면 다음 필수 구성 요소가 필요합니다.
모델 배포
서버리스 API에 배포
Jais 채팅 모델은 종량제 청구를 사용하여 서버리스 API 엔드포인트에 배포할 수 있습니다. 이 종류의 배포를 활용하면 조직에 필요한 엔터프라이즈 보안 및 규정 준수를 유지하면서 구독에서 모델을 호스트하지 않고 API로 모델을 사용할 수 있습니다.
서버리스 API 엔드포인트에 배포해도 구독의 할당량이 필요하지 않습니다. 모델이 아직 배포되지 않은 경우 Azure AI Foundry 포털, Python용 Azure Machine Learning SDK, Azure CLI 또는 ARM 템플릿을 사용하여 모델을 서버리스 API로 배포합니다.
REST 클라이언트
Azure AI 모델 유추 API를 사용하여 배포된 모델은 REST 클라이언트를 사용하여 사용할 수 있습니다. REST 클라이언트를 사용하려면 다음 필수 구성 요소가 필요합니다.
- 요청을 생성하려면 엔드포인트 URL을 전달해야 합니다. 엔드포인트 URL에는
https://your-host-name.your-azure-region.inference.ai.azure.com
형식이 있습니다. 여기서your-host-name`` is your unique model deployment host name and
azure-region``은 모델이 배포되는 Azure 지역입니다(예: eastus2). - 모델 배포 및 인증 기본 설정에 따라 서비스에 대해 인증할 키 또는 Microsoft Entra ID 자격 증명이 필요합니다. 키는 32자 문자열입니다.
채팅 완료 작업
이 섹션에서는 채팅을 위한 채팅 완성 모델과 함께 Azure AI 모델 유추 API를 사용합니다.
팁
Azure AI 모델 유추 API를 사용하면 Jais 채팅 모델을 포함하여 동일한 코드와 구조로 Azure AI Foundry 포털에 배포된 대부분의 모델과 통신할 수 있습니다.
모델을 사용할 클라이언트 만들기
먼저 모델을 사용할 클라이언트를 만듭니다. 다음 코드는 환경 변수에 저장된 엔드포인트 URL 및 키를 사용합니다.
모델의 기능 가져오기
/info
경로는 엔드포인트에 배포된 모델에 대한 정보를 반환합니다. 다음 메서드를 호출하여 모델의 정보를 반환합니다.
GET /info HTTP/1.1
Host: <ENDPOINT_URI>
Authorization: Bearer <TOKEN>
Content-Type: application/json
응답은 다음과 같습니다.
{
"model_name": "jais-30b-chat",
"model_type": "chat-completions",
"model_provider_name": "G42"
}
채팅 완료 요청 만들기
다음 예제에서는 모델에 대한 기본 채팅 완료 요청을 만드는 방법을 보여 줍니다.
{
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "How many languages are in the world?"
}
]
}
응답은 다음과 같습니다. 여기서 모델의 사용 통계를 볼 수 있습니다.
{
"id": "0a1234b5de6789f01gh2i345j6789klm",
"object": "chat.completion",
"created": 1718726686,
"model": "jais-30b-chat",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "As of now, it's estimated that there are about 7,000 languages spoken around the world. However, this number can vary as some languages become extinct and new ones develop. It's also important to note that the number of speakers can greatly vary between languages, with some having millions of speakers and others only a few hundred.",
"tool_calls": null
},
"finish_reason": "stop",
"logprobs": null
}
],
"usage": {
"prompt_tokens": 19,
"total_tokens": 91,
"completion_tokens": 72
}
}
응답의 usage
섹션을 검사하여 프롬프트에 사용된 토큰 수, 생성된 총 토큰 수 및 완료에 사용된 토큰 수를 확인합니다.
콘텐츠 스트리밍
기본적으로 완료 API는 생성된 전체 콘텐츠를 단일 응답으로 반환합니다. 긴 완료를 생성하는 경우 응답을 기다리는 데 몇 초 정도 걸릴 수 있습니다.
생성될 때 가져오기 위해 콘텐츠를 스트리밍할 수 있습니다. 콘텐츠를 스트리밍하면 콘텐츠를 사용할 수 있게 되면 완료 처리를 시작할 수 있습니다. 이 모드는 데이터 전용 서버 전송 이벤트 응답을 다시 스트리밍하는 개체를 반환합니다. 메시지 필드가 아닌 델타 필드에서 청크를 추출합니다.
{
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "How many languages are in the world?"
}
],
"stream": true,
"temperature": 0,
"top_p": 1,
"max_tokens": 2048
}
스트리밍에서 콘텐츠를 생성하는 방법을 시각화할 수 있습니다.
{
"id": "23b54589eba14564ad8a2e6978775a39",
"object": "chat.completion.chunk",
"created": 1718726371,
"model": "jais-30b-chat",
"choices": [
{
"index": 0,
"delta": {
"role": "assistant",
"content": ""
},
"finish_reason": null,
"logprobs": null
}
]
}
스트림의 마지막 메시지는 생성 프로세스가 중지되는 이유를 나타내는 finish_reason
이 설정되었습니다.
{
"id": "23b54589eba14564ad8a2e6978775a39",
"object": "chat.completion.chunk",
"created": 1718726371,
"model": "jais-30b-chat",
"choices": [
{
"index": 0,
"delta": {
"content": ""
},
"finish_reason": "stop",
"logprobs": null
}
],
"usage": {
"prompt_tokens": 19,
"total_tokens": 91,
"completion_tokens": 72
}
}
유추 클라이언트에서 지원하는 더 많은 매개 변수 살펴보기
유추 클라이언트에서 지정할 수 있는 다른 매개 변수를 탐색합니다. 지원되는 모든 매개 변수 및 해당 설명서의 전체 목록은 Azure AI 모델 유추 API 참조를 확인하세요.
{
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "How many languages are in the world?"
}
],
"presence_penalty": 0.1,
"frequency_penalty": 0.8,
"max_tokens": 2048,
"stop": ["<|endoftext|>"],
"temperature" :0,
"top_p": 1,
"response_format": { "type": "text" }
}
{
"id": "0a1234b5de6789f01gh2i345j6789klm",
"object": "chat.completion",
"created": 1718726686,
"model": "jais-30b-chat",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "As of now, it's estimated that there are about 7,000 languages spoken around the world. However, this number can vary as some languages become extinct and new ones develop. It's also important to note that the number of speakers can greatly vary between languages, with some having millions of speakers and others only a few hundred.",
"tool_calls": null
},
"finish_reason": "stop",
"logprobs": null
}
],
"usage": {
"prompt_tokens": 19,
"total_tokens": 91,
"completion_tokens": 72
}
}
Warning
Jais 모델은 JSON 출력 서식(response_format = { "type": "json_object" }
)을 지원하지 않습니다. 언제든지 모델에 JSON 출력을 생성하라는 메시지를 표시할 수 있습니다. 그러나 이러한 출력이 유효한 JSON으로 보장되지는 않습니다.
지원되는 매개 변수 목록에 없는 매개 변수를 전달하려면 추가 매개 변수를 사용하여 기본 모델에 전달할 수 있습니다. 모델 추가 매개 변수 전달을 참조하세요.
모델에 추가 매개 변수 전달
Azure AI 모델 유추 API를 사용하면 모델에 추가 매개 변수를 전달할 수 있습니다. 다음 코드 예에서는 추가 매개 변수 logprobs
를 모델에 전달하는 방법을 보여줍니다.
Azure AI 모델 유추 API에 추가 매개 변수를 전달하기 전에 모델이 이러한 추가 매개 변수를 지원하는지 확인합니다. 기본 모델에 대한 요청이 이루어지면 헤더 extra-parameters
의 pass-through
값이 모델에 전달됩니다. 이 값은 모델에 추가 매개 변수를 전달하도록 엔드포인트에 지시합니다. 모델에서 추가 매개 변수를 사용하면 모델이 실제로 매개 변수를 처리할 수 있다고 보장할 수 없습니다. 지원되는 추가 매개 변수를 이해하려면 모델의 설명서를 읽어보세요.
POST /chat/completions HTTP/1.1
Host: <ENDPOINT_URI>
Authorization: Bearer <TOKEN>
Content-Type: application/json
extra-parameters: pass-through
{
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "How many languages are in the world?"
}
],
"logprobs": true
}
콘텐츠 안전 적용
Azure AI 모델 유추 API는 Azure AI 콘텐츠 안전을 지원합니다. Azure AI 콘텐츠 안전이 켜져 있는 배포를 사용하는 경우 입력 및 출력은 유해한 콘텐츠의 출력을 감지하고 방지하기 위한 분류 모델의 앙상블을 통과합니다. 콘텐츠 필터링(미리 보기) 시스템은 입력 프롬프트와 출력 완성 모두에서 잠재적으로 유해한 콘텐츠의 특정 범주를 검색하고 조치를 취합니다.
다음 예제에서는 모델이 입력 프롬프트에서 유해한 콘텐츠를 감지하고 콘텐츠 안전이 사용하도록 설정된 경우 이벤트를 처리하는 방법을 보여 줍니다.
{
"messages": [
{
"role": "system",
"content": "You are an AI assistant that helps people find information."
},
{
"role": "user",
"content": "Chopping tomatoes and cutting them into cubes or wedges are great ways to practice your knife skills."
}
]
}
{
"error": {
"message": "The response was filtered due to the prompt triggering Microsoft's content management policy. Please modify your prompt and retry.",
"type": null,
"param": "prompt",
"code": "content_filter",
"status": 400
}
}
팁
Azure AI 콘텐츠 안전 설정을 구성하고 제어하는 방법에 대한 자세한 내용은 Azure AI 콘텐츠 안전 설명서를 확인하세요.
더 많은 유추 예
Jais 모델을 사용하는 방법에 대한 더 많은 예를 보려면 다음 예와 자습서를 참조하세요.
설명 | 언어 | Sample |
---|---|---|
C용 Azure AI 유추 패키지# | C# | 링크 |
JavaScript용 Azure AI 유추 패키지 | JavaScript | 링크 |
Python용 Azure AI 유추 패키지 | Python | 링크 |
서버리스 API 엔드포인트로 배포된 Jais 모델에 대한 비용 및 할당량 고려 사항
할당량은 배포당 관리됩니다. 각 배포에는 분당 200,000개의 토큰과 분당 1,000개의 API 요청의 속도 제한이 있습니다. 그러나 현재는 프로젝트별 모델당 하나의 배포로 제한됩니다. 현재 속도 제한이 시나리오에 충분하지 않은 경우 Microsoft Azure 지원에 문의하세요.
서버리스 API로 배포된 Jais 모델은 G42에서 Azure Marketplace를 통해 제공되며 사용할 Azure AI Foundry와 통합됩니다. 모델을 배포할 때 Azure Marketplace 가격 책정을 확인할 수 있습니다.
프로젝트가 Azure Marketplace에서 지정된 제품을 구독할 때마다 사용에 연결된 비용을 추적하기 위해 새 리소스가 만들어집니다. 유추와 관련된 비용을 추적하는 데 동일한 리소스가 사용됩니다. 그러나 여러 미터를 사용하여 각 시나리오를 독립적으로 추적할 수 있습니다.
비용을 추적하는 방법에 대한 자세한 내용은 Azure Marketplace를 통해 제공되는 모델에 대한 비용 모니터링을 참조하세요.