다음을 통해 공유


Azure AI 모델 유추를 사용하여 추론 모델을 사용하는 방법

중요

이 문서에 표시된 항목(미리 보기)은 현재 퍼블릭 미리 보기에서 확인할 수 있습니다. 이 미리 보기는 서비스 수준 계약 없이 제공되며, 프로덕션 워크로드에는 권장되지 않습니다. 특정 기능이 지원되지 않거나 기능이 제한될 수 있습니다. 자세한 내용은 Microsoft Azure Preview에 대한 추가 사용 약관을 참조하세요.

이 문서에서는 Azure AI 서비스에서 Azure AI 모델 유추에 배포된 채팅 완료 모델의 추론 기능을 사용하는 방법을 설명합니다.

추론 모델

추론 모델은 수학, 코딩, 과학, 전략 및 물류와 같은 도메인에서 더 높은 수준의 성능에 도달할 수 있습니다. 이러한 모델이 출력을 생성하는 방법은 대답을 생성하기 전에 생각 체인을 명시적으로 사용하여 가능한 모든 경로를 탐색하는 것입니다. 그들은 자신의 답변을 생성할 때마다 이를 확인하여 더 나은 정확한 결론에 도달하는 데 도움이 됩니다. 즉, 추론 모델은 효과적인 결과를 생성하기 위해 프롬프트에 더 적은 컨텍스트가 필요할 수 있습니다.

이러한 모델 성능 크기 조정 방법은 더 높은 대기 시간 및 비용에 대해 성능을 거래하기 때문에 유추 컴퓨팅 시간이라고 합니다. 학습 컴퓨팅 시간을 통해 스케일링되는 다른 접근 방식과 대조됩니다.

추론 모델은 다음 두 가지 유형의 출력을 생성합니다.

  • 추론 완료
  • 출력 완료

이러한 완료는 모두 모델에서 생성된 콘텐츠에 포함되므로 모델과 관련된 토큰 제한 및 비용을 계산합니다. 일부 모델은 다음과 같은 DeepSeek-R1추론 콘텐츠를 출력할 수 있습니다. 다른 일부는, 예를 들어 o1는, 완료의 출력 부분만을 출력합니다.

필수 조건

이 자습서를 완전히 학습하려면 다음이 필요합니다.

  • 다음 명령을 사용하여 Python용 Azure AI 추론 패키지를 설치합니다.

    pip install -U azure-ai-inference
    

채팅에서 추론 기능 사용

먼저 모델을 사용할 클라이언트를 만듭니다. 다음 코드는 환경 변수에 저장된 엔드포인트 URL과 키를 사용합니다.

import os
from azure.ai.inference import ChatCompletionsClient
from azure.core.credentials import AzureKeyCredential

client = ChatCompletionsClient(
    endpoint="https://<resource>.services.ai.azure.com/models",
    credential=AzureKeyCredential(os.environ["AZURE_INFERENCE_CREDENTIAL"]),
    model="deepseek-r1"
)

Azure AI 모델 유추 API를 사용하여 Azure AI Services 리소스에 모델을 배포했는지 확인합니다. Deepseek-R1 은 서버리스 API 엔드포인트로도 사용할 수 있습니다. 그러나 이러한 엔드포인트는 이 자습서에서 설명한 대로 매개 변수 model 를 사용하지 않습니다. Azure AI Foundry 포털>이동하여 모델이 Azure AI Services 섹션 아래에 나열되는지 확인할 수 있습니다.

Microsoft Entra ID 지원을 사용하여 리소스를 구성한 경우 다음 코드 조각을 사용하여 클라이언트를 만들 수 있습니다.

import os
from azure.ai.inference import ChatCompletionsClient
from azure.identity import DefaultAzureCredential

client = ChatCompletionsClient(
    endpoint="https://<resource>.services.ai.azure.com/models",
    credential=DefaultAzureCredential(),
    credential_scopes=["https://cognitiveservices.azure.com/.default"],
    model="deepseek-r1"
)

채팅 완료 요청 만들기

다음 예제에서는 모델에 대한 기본 채팅 요청을 만드는 방법을 보여 줍니다.

from azure.ai.inference.models import SystemMessage, UserMessage

response = client.complete(
    messages=[
        UserMessage(content="How many languages are in the world?"),
    ],
)

추론 모델에 대한 프롬프트를 작성할 때 다음 사항을 고려합니다.

  • 간단한 지침을 사용하고 생각의 사슬 기술을 사용하지 마십시오.
  • 기본 제공 추론 기능은 간단한 제로샷 프롬프트를 보다 복잡한 메서드만큼 효과적으로 만듭니다.
  • RAG 시나리오와 같은 추가 컨텍스트 또는 문서를 제공할 때 가장 관련성이 큰 정보만 포함하면 모델이 응답을 과도하게 복잡하게 만드는 것을 방지할 수 있습니다.
  • 추론 모델은 시스템 메시지의 사용을 지원할 수 있습니다. 그러나 다른 비이성적 모델만큼 엄격하게 따르지 않을 수도 있습니다.
  • 멀티 턴 애플리케이션을 만들 때 추론 콘텐츠 섹션에 설명된 대로 추론 콘텐츠 없이 모델의 최종 답변만 추가하면 됩니다.

추론 모델은 응답을 생성하는 데 시간이 더 오래 걸릴 수 있습니다. 그들은 더 깊고 구조화 된 문제 해결을 가능하게 생각의 긴 추론 체인을 사용합니다. 또한 자체 확인을 수행하여 자체 답변을 교차 확인하고 자신의 실수를 수정하여 새로운 자기 반영 동작을 보여 줍니다.

응답은 다음과 같습니다. 여기서 모델의 사용 통계를 볼 수 있습니다.

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: <think>Okay, the user is asking how many languages exist in the world. I need to provide a clear and accurate answer...</think>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: deepseek-r1
Usage: 
  Prompt tokens: 11
  Total tokens: 897
  Completion tokens: 886

추론 콘텐츠

DeepSeek-R1과 같은 일부 추론 모델은 완성을 생성하고 그 뒤에 추론을 포함합니다. 완료와 관련된 추론은 태그 <think></think> 내의 응답 콘텐츠에 포함됩니다. 모델은 추론 콘텐츠를 생성할 시나리오를 선택할 수 있습니다. 응답에서 추론 콘텐츠를 추출하여 다음과 같이 모델의 사고 프로세스를 이해할 수 있습니다.

import re

match = re.match(r"<think>(.*?)</think>(.*)", response.choices[0].message.content, re.DOTALL)

print("Response:", )
if match:
    print("\tThinking:", match.group(1))
    print("\tAnswer:", match.group(2))
else:
    print("\tAnswer:", 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)
Thinking: Okay, the user is asking how many languages exist in the world. I need to provide a clear and accurate answer. Let's start by recalling the general consensus from linguistic sources. I remember that the number often cited is around 7,000, but maybe I should check some reputable organizations.\n\nEthnologue is a well-known resource for language data, and I think they list about 7,000 languages. But wait, do they update their numbers? It might be around 7,100 or so. Also, the exact count can vary because some sources might categorize dialects differently or have more recent data. \n\nAnother thing to consider is language endangerment. Many languages are endangered, with some having only a few speakers left. Organizations like UNESCO track endangered languages, so mentioning that adds context. Also, the distribution isn't even. Some countries have hundreds of languages, like Papua New Guinea with over 800, while others have just a few. \n\nA user might also wonder why the exact number is hard to pin down. It's because the distinction between a language and a dialect can be political or cultural. For example, Mandarin and Cantonese are considered dialects of Chinese by some, but they're mutually unintelligible, so others classify them as separate languages. Also, some regions are under-researched, making it hard to document all languages. \n\nI should also touch on language families. The 7,000 languages are grouped into families like Indo-European, Sino-Tibetan, Niger-Congo, etc. Maybe mention a few of the largest families. But wait, the question is just about the count, not the families. Still, it's good to provide a bit more context. \n\nI need to make sure the information is up-to-date. Let me think – recent estimates still hover around 7,000. However, languages are dying out rapidly, so the number decreases over time. Including that note about endangerment and language extinction rates could be helpful. For instance, it's often stated that a language dies every few weeks. \n\nAnother point is sign languages. Does the count include them? Ethnologue includes some, but not all sources might. If the user is including sign languages, that adds more to the count, but I think the 7,000 figure typically refers to spoken languages. For thoroughness, maybe mention that there are also over 300 sign languages. \n\nSummarizing, the answer should state around 7,000, mention Ethnologue's figure, explain why the exact number varies, touch on endangerment, and possibly note sign languages as a separate category. Also, a brief mention of Papua New Guinea as the most linguistically diverse country. \n\nWait, let me verify Ethnologue's current number. As of their latest edition (25th, 2022), they list 7,168 living languages. But I should check if that's the case. Some sources might round to 7,000. Also, SIL International publishes Ethnologue, so citing them as reference makes sense. \n\nOther sources, like Glottolog, might have a different count because they use different criteria. Glottolog might list around 7,000 as well, but exact numbers vary. It's important to highlight that the count isn't exact because of differing definitions and ongoing research. \n\nIn conclusion, the approximate number is 7,000, with Ethnologue being a key source, considerations of endangerment, and the challenges in counting due to dialect vs. language distinctions. I should make sure the answer is clear, acknowledges the variability, and provides key points succinctly.

Answer: The exact number of languages in the world is challenging to determine due to differences in definitions (e.g., distinguishing languages from dialects) and ongoing documentation efforts. However, widely cited estimates suggest there are approximately **7,000 languages** globally.
Model: DeepSeek-R1
Usage: 
  Prompt tokens: 11
  Total tokens: 897
  Completion tokens: 886

멀티 턴 대화를 만들 때 추론이 긴 설명을 생성하는 경향이 있으므로 채팅 기록에서 추론 콘텐츠를 보내지 않는 것이 유용합니다.

콘텐츠 스트리밍

기본적으로 완료 API는 생성된 전체 콘텐츠를 단일 응답으로 반환합니다. 긴 완료를 생성하는 경우 응답을 기다리는 데 몇 초 정도 걸릴 수 있습니다.

생성될 때 가져오기 위해 콘텐츠를 스트리밍할 수 있습니다. 콘텐츠를 스트리밍하면 콘텐츠를 사용할 수 있게 되면 완료 처리를 시작할 수 있습니다. 이 모드는 데이터 전용 서버 전송 이벤트 응답을 다시 스트리밍하는 개체를 반환합니다. 메시지 필드가 아닌 델타 필드에서 청크를 추출합니다.

완성을 스트리밍하려면 모델을 호출할 때 stream=True를 설정합니다.

result = client.complete(
    model="deepseek-r1",
    messages=[
        UserMessage(content="How many languages are in the world?"),
    ],
    max_tokens=2048,
    stream=True,
)

출력을 시각화하려면 스트림을 인쇄하는 도우미 함수를 정의합니다. 다음 예제에서는 추론 콘텐츠 없이 답변만 스트리밍하는 라우팅을 구현합니다.

def print_stream(result):
    """
    Prints the chat completion with streaming.
    """
    is_thinking = False
    for event in completion:
        if event.choices:
            content = event.choices[0].delta.content
            if content == "<think>":
                is_thinking = True
                print("🧠 Thinking...", end="", flush=True)
            elif content == "</think>":
                is_thinking = False
                print("🛑\n\n")
            elif content:
                print(content, end="", flush=True)

스트리밍에서 콘텐츠를 생성하는 방법을 시각화할 수 있습니다.

print_stream(result)

매개 변수

일반적으로 추론 모델은 채팅 완성 모델에서 찾을 수 있는 다음 매개 변수를 지원하지 않습니다.

  • 온도
  • 현재 상태 패널티
  • 반복 페널티
  • 매개 변수 top_p

일부 모델은 도구 또는 구조화된 출력(JSON 스키마 포함)의 사용을 지원합니다. 각 모델의 지원을 이해하려면 모델 세부 정보 페이지를 참조하세요.

콘텐츠 안전 적용

Azure AI 모델 유추 API는 Azure AI 콘텐츠 안전을 지원합니다. Azure AI 콘텐츠 안전이 켜져 있는 배포를 사용하는 경우 입력 및 출력은 유해한 콘텐츠의 출력을 감지하고 방지하기 위한 분류 모델의 앙상블을 통과합니다. 콘텐츠 필터링 시스템은 입력 프롬프트와 출력 완료 모두에서 잠재적으로 유해한 콘텐츠의 특정 범주를 탐지하고 조치를 취합니다.

다음 예제에서는 모델이 입력 프롬프트에서 유해한 콘텐츠를 감지하고 콘텐츠 안전이 사용하도록 설정된 경우 이벤트를 처리하는 방법을 보여 줍니다.

from azure.ai.inference.models import AssistantMessage, UserMessage

try:
    response = client.complete(
        model="deepseek-r1",
        messages=[
            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 콘텐츠 안전 설명서를 확인하세요.

중요

이 문서에 표시된 항목(미리 보기)은 현재 퍼블릭 미리 보기에서 확인할 수 있습니다. 이 미리 보기는 서비스 수준 계약 없이 제공되며, 프로덕션 워크로드에는 권장되지 않습니다. 특정 기능이 지원되지 않거나 기능이 제한될 수 있습니다. 자세한 내용은 Microsoft Azure Preview에 대한 추가 사용 약관을 참조하세요.

이 문서에서는 Azure AI 서비스에서 Azure AI 모델 유추에 배포된 채팅 완료 모델의 추론 기능을 사용하는 방법을 설명합니다.

추론 모델

추론 모델은 수학, 코딩, 과학, 전략 및 물류와 같은 도메인에서 더 높은 수준의 성능에 도달할 수 있습니다. 이러한 모델이 출력을 생성하는 방법은 대답을 생성하기 전에 생각 체인을 명시적으로 사용하여 가능한 모든 경로를 탐색하는 것입니다. 그들은 자신의 답변을 생성할 때마다 이를 확인하여 더 나은 정확한 결론에 도달하는 데 도움이 됩니다. 즉, 추론 모델은 효과적인 결과를 생성하기 위해 프롬프트에 더 적은 컨텍스트가 필요할 수 있습니다.

이러한 모델 성능 크기 조정 방법은 더 높은 대기 시간 및 비용에 대해 성능을 거래하기 때문에 유추 컴퓨팅 시간이라고 합니다. 학습 컴퓨팅 시간을 통해 스케일링되는 다른 접근 방식과 대조됩니다.

추론 모델은 다음 두 가지 유형의 출력을 생성합니다.

  • 추론 완료
  • 출력 완료

이러한 완료는 모두 모델에서 생성된 콘텐츠에 포함되므로 모델과 관련된 토큰 제한 및 비용을 계산합니다. 일부 모델은 다음과 같은 DeepSeek-R1추론 콘텐츠를 출력할 수 있습니다. 다른 일부는, 예를 들어 o1는, 완료의 출력 부분만을 출력합니다.

필수 조건

이 자습서를 완전히 학습하려면 다음이 필요합니다.

  • 다음 명령을 사용하여 JavaScript 용 Azure 유추 라이브러리를 설치합니다.

    npm install @azure-rest/ai-inference
    npm install @azure/core-auth
    npm install @azure/identity
    

    Node.js을 사용할 경우, package.json에서 종속성을 구성할 수 있습니다.

    package.json

    {
      "name": "main_app",
      "version": "1.0.0",
      "description": "",
      "main": "app.js",
      "type": "module",
      "dependencies": {
        "@azure-rest/ai-inference": "1.0.0-beta.6",
        "@azure/core-auth": "1.9.0",
        "@azure/core-sse": "2.2.0",
        "@azure/identity": "4.8.0"
      }
    }
    
  • 다음을 가져옵니다.

    import ModelClient from "@azure-rest/ai-inference";
    import { isUnexpected } from "@azure-rest/ai-inference";
    import { createSseStream } from "@azure/core-sse";
    import { AzureKeyCredential } from "@azure/core-auth";
    import { DefaultAzureCredential } from "@azure/identity";
    

채팅에서 추론 기능 사용

먼저 모델을 사용할 클라이언트를 만듭니다. 다음 코드는 환경 변수에 저장된 엔드포인트 URL과 키를 사용합니다.

const client = ModelClient(
    "https://<resource>.services.ai.azure.com/models", 
    new AzureKeyCredential(process.env.AZURE_INFERENCE_CREDENTIAL)
);

Microsoft Entra ID 지원을 사용하여 리소스를 구성한 경우 다음 코드 조각을 사용하여 클라이언트를 만들 수 있습니다.

const clientOptions = { credentials: { "https://cognitiveservices.azure.com" } };

const client = ModelClient(
    "https://<resource>.services.ai.azure.com/models", 
    new DefaultAzureCredential()
    clientOptions,
);

채팅 완료 요청 만들기

다음 예제에서는 모델에 대한 기본 채팅 요청을 만드는 방법을 보여 줍니다.

var messages = [
    { role: "user", content: "How many languages are in the world?" },
];

var response = await client.path("/chat/completions").post({
    body: {
        model: "DeepSeek-R1",
        messages: messages,
    }
});

추론 모델에 대한 프롬프트를 작성할 때 다음 사항을 고려합니다.

  • 간단한 지침을 사용하고 생각의 사슬 기술을 사용하지 마십시오.
  • 기본 제공 추론 기능은 간단한 제로샷 프롬프트를 보다 복잡한 메서드만큼 효과적으로 만듭니다.
  • RAG 시나리오와 같은 추가 컨텍스트 또는 문서를 제공할 때 가장 관련성이 큰 정보만 포함하면 모델이 응답을 과도하게 복잡하게 만드는 것을 방지할 수 있습니다.
  • 추론 모델은 시스템 메시지의 사용을 지원할 수 있습니다. 그러나 다른 비이성적 모델만큼 엄격하게 따르지 않을 수도 있습니다.
  • 멀티 턴 애플리케이션을 만들 때 추론 콘텐츠 섹션에 설명된 대로 추론 콘텐츠 없이 모델의 최종 답변만 추가하면 됩니다.

추론 모델은 응답을 생성하는 데 시간이 더 오래 걸릴 수 있습니다. 그들은 더 깊고 구조화 된 문제 해결을 가능하게 생각의 긴 추론 체인을 사용합니다. 또한 자체 확인을 수행하여 자체 답변을 교차 확인하고 자신의 실수를 수정하여 새로운 자기 반영 동작을 보여 줍니다.

응답은 다음과 같습니다. 여기서 모델의 사용 통계를 볼 수 있습니다.

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: <think>Okay, the user is asking how many languages exist in the world. I need to provide a clear and accurate answer...</think>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: deepseek-r1
Usage: 
  Prompt tokens: 11
  Total tokens: 897
  Completion tokens: 886

추론 콘텐츠

DeepSeek-R1과 같은 일부 추론 모델은 완성을 생성하고 그 뒤에 추론을 포함합니다. 완료와 관련된 추론은 태그 <think></think> 내의 응답 콘텐츠에 포함됩니다. 모델은 추론 콘텐츠를 생성할 시나리오를 선택할 수 있습니다. 응답에서 추론 콘텐츠를 추출하여 다음과 같이 모델의 사고 프로세스를 이해할 수 있습니다.

var content = response.body.choices[0].message.content
var match = content.match(/<think>(.*?)<\/think>(.*)/s);

console.log("Response:");
if (match) {
    console.log("\tThinking:", match[1]);
    console.log("\Answer:", match[2]);
}
else {
    console.log("Response:", 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);
Thinking: Okay, the user is asking how many languages exist in the world. I need to provide a clear and accurate answer. Let's start by recalling the general consensus from linguistic sources. I remember that the number often cited is around 7,000, but maybe I should check some reputable organizations.\n\nEthnologue is a well-known resource for language data, and I think they list about 7,000 languages. But wait, do they update their numbers? It might be around 7,100 or so. Also, the exact count can vary because some sources might categorize dialects differently or have more recent data. \n\nAnother thing to consider is language endangerment. Many languages are endangered, with some having only a few speakers left. Organizations like UNESCO track endangered languages, so mentioning that adds context. Also, the distribution isn't even. Some countries have hundreds of languages, like Papua New Guinea with over 800, while others have just a few. \n\nA user might also wonder why the exact number is hard to pin down. It's because the distinction between a language and a dialect can be political or cultural. For example, Mandarin and Cantonese are considered dialects of Chinese by some, but they're mutually unintelligible, so others classify them as separate languages. Also, some regions are under-researched, making it hard to document all languages. \n\nI should also touch on language families. The 7,000 languages are grouped into families like Indo-European, Sino-Tibetan, Niger-Congo, etc. Maybe mention a few of the largest families. But wait, the question is just about the count, not the families. Still, it's good to provide a bit more context. \n\nI need to make sure the information is up-to-date. Let me think – recent estimates still hover around 7,000. However, languages are dying out rapidly, so the number decreases over time. Including that note about endangerment and language extinction rates could be helpful. For instance, it's often stated that a language dies every few weeks. \n\nAnother point is sign languages. Does the count include them? Ethnologue includes some, but not all sources might. If the user is including sign languages, that adds more to the count, but I think the 7,000 figure typically refers to spoken languages. For thoroughness, maybe mention that there are also over 300 sign languages. \n\nSummarizing, the answer should state around 7,000, mention Ethnologue's figure, explain why the exact number varies, touch on endangerment, and possibly note sign languages as a separate category. Also, a brief mention of Papua New Guinea as the most linguistically diverse country. \n\nWait, let me verify Ethnologue's current number. As of their latest edition (25th, 2022), they list 7,168 living languages. But I should check if that's the case. Some sources might round to 7,000. Also, SIL International publishes Ethnologue, so citing them as reference makes sense. \n\nOther sources, like Glottolog, might have a different count because they use different criteria. Glottolog might list around 7,000 as well, but exact numbers vary. It's important to highlight that the count isn't exact because of differing definitions and ongoing research. \n\nIn conclusion, the approximate number is 7,000, with Ethnologue being a key source, considerations of endangerment, and the challenges in counting due to dialect vs. language distinctions. I should make sure the answer is clear, acknowledges the variability, and provides key points succinctly.

Answer: The exact number of languages in the world is challenging to determine due to differences in definitions (e.g., distinguishing languages from dialects) and ongoing documentation efforts. However, widely cited estimates suggest there are approximately **7,000 languages** globally.
Model: DeepSeek-R1
Usage: 
  Prompt tokens: 11
  Total tokens: 897
  Completion tokens: 886

멀티 턴 대화를 만들 때 추론이 긴 설명을 생성하는 경향이 있으므로 채팅 기록에서 추론 콘텐츠를 보내지 않는 것이 유용합니다.

콘텐츠 스트리밍

기본적으로 완료 API는 생성된 전체 콘텐츠를 단일 응답으로 반환합니다. 긴 완료를 생성하는 경우 응답을 기다리는 데 몇 초 정도 걸릴 수 있습니다.

생성될 때 가져오기 위해 콘텐츠를 스트리밍할 수 있습니다. 콘텐츠를 스트리밍하면 콘텐츠를 사용할 수 있게 되면 완료 처리를 시작할 수 있습니다. 이 모드는 데이터 전용 서버 전송 이벤트 응답을 다시 스트리밍하는 개체를 반환합니다. 메시지 필드가 아닌 델타 필드에서 청크를 추출합니다.

완성을 스트리밍하려면 모델을 호출할 때 stream=True를 설정합니다.

var messages = [
    { role: "user", content: "How many languages are in the world?" },
];

var response = await client.path("/chat/completions").post({
    body: {
        model: "DeepSeek-R1",
        messages: messages,
    }
}).asNodeStream();

출력을 시각화하려면 스트림을 인쇄하는 도우미 함수를 정의합니다. 다음 예제에서는 추론 콘텐츠 없이 답변만 스트리밍하는 라우팅을 구현합니다.

function printStream(sses) {
    let isThinking = false;
    
    for await (const event of sses) {
        if (event.data === "[DONE]") {
            return;
        }
        for (const choice of (JSON.parse(event.data)).choices) {
            const content = choice.delta?.content ?? "";
            
            if (content === "<think>") {
                isThinking = true;
                process.stdout.write("🧠 Thinking...");
            } else if (content === "</think>") {
                isThinking = false;
                console.log("🛑\n\n");
            } else if (content) {
                process.stdout.write(content);
            }
        }
    }
}

스트리밍에서 콘텐츠를 생성하는 방법을 시각화할 수 있습니다.

var sses = createSseStream(response.body);
printStream(result)

매개 변수

일반적으로 추론 모델은 채팅 완성 모델에서 찾을 수 있는 다음 매개 변수를 지원하지 않습니다.

  • 온도
  • 현재 상태 패널티
  • 반복 페널티
  • 매개 변수 top_p

일부 모델은 도구 또는 구조화된 출력(JSON 스키마 포함)의 사용을 지원합니다. 각 모델의 지원을 이해하려면 모델 세부 정보 페이지를 참조하세요.

콘텐츠 안전 적용

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({
        model: "DeepSeek-R1",
        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 콘텐츠 안전 설명서를 확인하세요.

중요

이 문서에 표시된 항목(미리 보기)은 현재 퍼블릭 미리 보기에서 확인할 수 있습니다. 이 미리 보기는 서비스 수준 계약 없이 제공되며, 프로덕션 워크로드에는 권장되지 않습니다. 특정 기능이 지원되지 않거나 기능이 제한될 수 있습니다. 자세한 내용은 Microsoft Azure Preview에 대한 추가 사용 약관을 참조하세요.

이 문서에서는 Azure AI 서비스에서 Azure AI 모델 유추에 배포된 채팅 완료 모델의 추론 기능을 사용하는 방법을 설명합니다.

추론 모델

추론 모델은 수학, 코딩, 과학, 전략 및 물류와 같은 도메인에서 더 높은 수준의 성능에 도달할 수 있습니다. 이러한 모델이 출력을 생성하는 방법은 대답을 생성하기 전에 생각 체인을 명시적으로 사용하여 가능한 모든 경로를 탐색하는 것입니다. 그들은 자신의 답변을 생성할 때마다 이를 확인하여 더 나은 정확한 결론에 도달하는 데 도움이 됩니다. 즉, 추론 모델은 효과적인 결과를 생성하기 위해 프롬프트에 더 적은 컨텍스트가 필요할 수 있습니다.

이러한 모델 성능 크기 조정 방법은 더 높은 대기 시간 및 비용에 대해 성능을 거래하기 때문에 유추 컴퓨팅 시간이라고 합니다. 학습 컴퓨팅 시간을 통해 스케일링되는 다른 접근 방식과 대조됩니다.

추론 모델은 다음 두 가지 유형의 출력을 생성합니다.

  • 추론 완료
  • 출력 완료

이러한 완료는 모두 모델에서 생성된 콘텐츠에 포함되므로 모델과 관련된 토큰 제한 및 비용을 계산합니다. 일부 모델은 다음과 같은 DeepSeek-R1추론 콘텐츠를 출력할 수 있습니다. 다른 일부는, 예를 들어 o1는, 완료의 출력 부분만을 출력합니다.

필수 조건

이 자습서를 완전히 학습하려면 다음이 필요합니다.

  • 프로젝트에 Azure AI 유추 패키지를 추가합니다.

    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-ai-inference</artifactId>
        <version>1.0.0-beta.4</version>
    </dependency>
    
  • Entra ID를 사용하는 경우 다음 패키지도 필요합니다.

    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-identity</artifactId>
        <version>1.15.3</version>
    </dependency>
    
  • 다음 네임스페이스를 가져옵니다.

    package com.azure.ai.inference.usage;
    
    import com.azure.ai.inference.EmbeddingsClient;
    import com.azure.ai.inference.EmbeddingsClientBuilder;
    import com.azure.ai.inference.ChatCompletionsClient;
    import com.azure.ai.inference.ChatCompletionsClientBuilder;
    import com.azure.ai.inference.models.EmbeddingsResult;
    import com.azure.ai.inference.models.EmbeddingItem;
    import com.azure.ai.inference.models.ChatCompletions;
    import com.azure.core.credential.AzureKeyCredential;
    import com.azure.core.util.Configuration;
    
    import java.util.ArrayList;
    import java.util.List;
    

채팅에서 추론 기능 사용

먼저 모델을 사용할 클라이언트를 만듭니다. 다음 코드는 환경 변수에 저장된 엔드포인트 URL과 키를 사용합니다.

ChatCompletionsClient client = new ChatCompletionsClient(
        new URI("https://<resource>.services.ai.azure.com/models"),
        new AzureKeyCredential(System.getProperty("AZURE_INFERENCE_CREDENTIAL")),

Azure AI 모델 유추 API를 사용하여 Azure AI Services 리소스에 모델을 배포했는지 확인합니다. Deepseek-R1 은 서버리스 API 엔드포인트로도 사용할 수 있습니다. 그러나 이러한 엔드포인트는 이 자습서에서 설명한 대로 매개 변수 model 를 사용하지 않습니다. Azure AI Foundry 포털>이동하여 모델이 Azure AI Services 섹션 아래에 나열되는지 확인할 수 있습니다.

Microsoft Entra ID 지원을 사용하여 리소스를 구성한 경우 다음 코드 조각을 사용하여 클라이언트를 만들 수 있습니다.

client = new ChatCompletionsClient(
        new URI("https://<resource>.services.ai.azure.com/models"),
        new DefaultAzureCredentialBuilder().build()
);

채팅 완료 요청 만들기

다음 예제에서는 모델에 대한 기본 채팅 요청을 만드는 방법을 보여 줍니다.

ChatCompletionsOptions requestOptions = new ChatCompletionsOptions()
        .setModel("DeepSeek-R1")
        .setMessages(Arrays.asList(
                new ChatRequestUserMessage("How many languages are in the world?")
        ));

Response<ChatCompletions> response = client.complete(requestOptions);

추론 모델에 대한 프롬프트를 작성할 때 다음 사항을 고려합니다.

  • 간단한 지침을 사용하고 생각의 사슬 기술을 사용하지 마십시오.
  • 기본 제공 추론 기능은 간단한 제로샷 프롬프트를 보다 복잡한 메서드만큼 효과적으로 만듭니다.
  • RAG 시나리오와 같은 추가 컨텍스트 또는 문서를 제공할 때 가장 관련성이 큰 정보만 포함하면 모델이 응답을 과도하게 복잡하게 만드는 것을 방지할 수 있습니다.
  • 추론 모델은 시스템 메시지의 사용을 지원할 수 있습니다. 그러나 다른 비이성적 모델만큼 엄격하게 따르지 않을 수도 있습니다.
  • 멀티 턴 애플리케이션을 만들 때 추론 콘텐츠 섹션에 설명된 대로 추론 콘텐츠 없이 모델의 최종 답변만 추가하면 됩니다.

추론 모델은 응답을 생성하는 데 시간이 더 오래 걸릴 수 있습니다. 그들은 더 깊고 구조화 된 문제 해결을 가능하게 생각의 긴 추론 체인을 사용합니다. 또한 자체 확인을 수행하여 자체 답변을 교차 확인하고 자신의 실수를 수정하여 새로운 자기 반영 동작을 보여 줍니다.

응답은 다음과 같습니다. 여기서 모델의 사용 통계를 볼 수 있습니다.

System.out.println("Response: " + response.getValue().getChoices().get(0).getMessage().getContent());
System.out.println("Model: " + response.getValue().getModel());
System.out.println("Usage:");
System.out.println("\tPrompt tokens: " + response.getValue().getUsage().getPromptTokens());
System.out.println("\tTotal tokens: " + response.getValue().getUsage().getTotalTokens());
System.out.println("\tCompletion tokens: " + response.getValue().getUsage().getCompletionTokens());
Response: <think>Okay, the user is asking how many languages exist in the world. I need to provide a clear and accurate...</think>The exact number of languages in the world is challenging to determine due to differences in definitions (e.g., distinguishing languages from dialects) and ongoing documentation efforts. However, widely cited estimates suggest there are approximately **7,000 languages** globally.
Model: deepseek-r1
Usage: 
  Prompt tokens: 11
  Total tokens: 897
  Completion tokens: 886

추론 콘텐츠

DeepSeek-R1과 같은 일부 추론 모델은 완성을 생성하고 그 뒤에 추론을 포함합니다. 완료와 관련된 추론은 태그 <think></think> 내의 응답 콘텐츠에 포함됩니다. 모델은 추론 콘텐츠를 생성할 시나리오를 선택할 수 있습니다. 응답에서 추론 콘텐츠를 추출하여 다음과 같이 모델의 사고 프로세스를 이해할 수 있습니다.

String content = response.getValue().getChoices().get(0).getMessage().getContent()
Pattern pattern = Pattern.compile("<think>(.*?)</think>(.*)", Pattern.DOTALL);
Matcher matcher = pattern.matcher(content);

System.out.println("Response:");
if (matcher.find()) {
    System.out.println("\tThinking: " + matcher.group(1));
    System.out.println("\tAnswer: " + matcher.group(2));
}
else {
    System.out.println("Response: " + content);
}
System.out.println("Model: " + response.getValue().getModel());
System.out.println("Usage:");
System.out.println("\tPrompt tokens: " + response.getValue().getUsage().getPromptTokens());
System.out.println("\tTotal tokens: " + response.getValue().getUsage().getTotalTokens());
System.out.println("\tCompletion tokens: " + response.getValue().getUsage().getCompletionTokens());
Thinking: Okay, the user is asking how many languages exist in the world. I need to provide a clear and accurate answer. Let's start by recalling the general consensus from linguistic sources. I remember that the number often cited is around 7,000, but maybe I should check some reputable organizations.\n\nEthnologue is a well-known resource for language data, and I think they list about 7,000 languages. But wait, do they update their numbers? It might be around 7,100 or so. Also, the exact count can vary because some sources might categorize dialects differently or have more recent data. \n\nAnother thing to consider is language endangerment. Many languages are endangered, with some having only a few speakers left. Organizations like UNESCO track endangered languages, so mentioning that adds context. Also, the distribution isn't even. Some countries have hundreds of languages, like Papua New Guinea with over 800, while others have just a few. \n\nA user might also wonder why the exact number is hard to pin down. It's because the distinction between a language and a dialect can be political or cultural. For example, Mandarin and Cantonese are considered dialects of Chinese by some, but they're mutually unintelligible, so others classify them as separate languages. Also, some regions are under-researched, making it hard to document all languages. \n\nI should also touch on language families. The 7,000 languages are grouped into families like Indo-European, Sino-Tibetan, Niger-Congo, etc. Maybe mention a few of the largest families. But wait, the question is just about the count, not the families. Still, it's good to provide a bit more context. \n\nI need to make sure the information is up-to-date. Let me think – recent estimates still hover around 7,000. However, languages are dying out rapidly, so the number decreases over time. Including that note about endangerment and language extinction rates could be helpful. For instance, it's often stated that a language dies every few weeks. \n\nAnother point is sign languages. Does the count include them? Ethnologue includes some, but not all sources might. If the user is including sign languages, that adds more to the count, but I think the 7,000 figure typically refers to spoken languages. For thoroughness, maybe mention that there are also over 300 sign languages. \n\nSummarizing, the answer should state around 7,000, mention Ethnologue's figure, explain why the exact number varies, touch on endangerment, and possibly note sign languages as a separate category. Also, a brief mention of Papua New Guinea as the most linguistically diverse country. \n\nWait, let me verify Ethnologue's current number. As of their latest edition (25th, 2022), they list 7,168 living languages. But I should check if that's the case. Some sources might round to 7,000. Also, SIL International publishes Ethnologue, so citing them as reference makes sense. \n\nOther sources, like Glottolog, might have a different count because they use different criteria. Glottolog might list around 7,000 as well, but exact numbers vary. It's important to highlight that the count isn't exact because of differing definitions and ongoing research. \n\nIn conclusion, the approximate number is 7,000, with Ethnologue being a key source, considerations of endangerment, and the challenges in counting due to dialect vs. language distinctions. I should make sure the answer is clear, acknowledges the variability, and provides key points succinctly.

Answer: The exact number of languages in the world is challenging to determine due to differences in definitions (e.g., distinguishing languages from dialects) and ongoing documentation efforts. However, widely cited estimates suggest there are approximately **7,000 languages** globally.
Model: DeepSeek-R1
Usage: 
  Prompt tokens: 11
  Total tokens: 897
  Completion tokens: 886

멀티 턴 대화를 만들 때 추론이 긴 설명을 생성하는 경향이 있으므로 채팅 기록에서 추론 콘텐츠를 보내지 않는 것이 유용합니다.

콘텐츠 스트리밍

기본적으로 완료 API는 생성된 전체 콘텐츠를 단일 응답으로 반환합니다. 긴 완료를 생성하는 경우 응답을 기다리는 데 몇 초 정도 걸릴 수 있습니다.

생성될 때 가져오기 위해 콘텐츠를 스트리밍할 수 있습니다. 콘텐츠를 스트리밍하면 콘텐츠를 사용할 수 있게 되면 완료 처리를 시작할 수 있습니다. 이 모드는 데이터 전용 서버 전송 이벤트 응답을 다시 스트리밍하는 개체를 반환합니다. 메시지 필드가 아닌 델타 필드에서 청크를 추출합니다.

ChatCompletionsOptions requestOptions = new ChatCompletionsOptions()
        .setModel("DeepSeek-R1")
        .setMessages(Arrays.asList(
                new ChatRequestUserMessage("How many languages are in the world? Write an essay about it.")
        ))
        .setMaxTokens(4096);

return client.completeStreamingAsync(requestOptions).thenAcceptAsync(response -> {
    try {
        printStream(response);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
});

출력을 시각화하려면 스트림을 인쇄하는 도우미 함수를 정의합니다. 다음 예제에서는 추론 콘텐츠 없이 답변만 스트리밍하는 라우팅을 구현합니다.

public void printStream(StreamingResponse<StreamingChatCompletionsUpdate> response) throws Exception {
    boolean isThinking = false;

    for (StreamingChatCompletionsUpdate chatUpdate : response) {
       if (chatUpdate.getContentUpdate() != null && !chatUpdate.getContentUpdate().isEmpty()) {
            String content = chatUpdate.getContentUpdate();

            if ("<think>".equals(content)) {
                isThinking = true;
                System.out.print("🧠 Thinking...");
                System.out.flush();
            } else if ("</think>".equals(content)) {
                isThinking = false;
                System.out.println("🛑\n\n");
            } else if (content != null && !content.isEmpty()) {
                System.out.print(content);
                System.out.flush();
            }
        }
    }
}

스트리밍에서 콘텐츠를 생성하는 방법을 시각화할 수 있습니다.

try {
    streamMessageAsync(client).get();
} catch (Exception e) {
    throw new RuntimeException(e);
}

매개 변수

일반적으로 추론 모델은 채팅 완성 모델에서 찾을 수 있는 다음 매개 변수를 지원하지 않습니다.

  • 온도
  • 현재 상태 패널티
  • 반복 페널티
  • 매개 변수 top_p

일부 모델은 도구 또는 구조화된 출력(JSON 스키마 포함)의 사용을 지원합니다. 각 모델의 지원을 이해하려면 모델 세부 정보 페이지를 참조하세요.

중요

이 문서에 표시된 항목(미리 보기)은 현재 퍼블릭 미리 보기에서 확인할 수 있습니다. 이 미리 보기는 서비스 수준 계약 없이 제공되며, 프로덕션 워크로드에는 권장되지 않습니다. 특정 기능이 지원되지 않거나 기능이 제한될 수 있습니다. 자세한 내용은 Microsoft Azure Preview에 대한 추가 사용 약관을 참조하세요.

이 문서에서는 Azure AI 서비스에서 Azure AI 모델 유추에 배포된 채팅 완료 모델의 추론 기능을 사용하는 방법을 설명합니다.

추론 모델

추론 모델은 수학, 코딩, 과학, 전략 및 물류와 같은 도메인에서 더 높은 수준의 성능에 도달할 수 있습니다. 이러한 모델이 출력을 생성하는 방법은 대답을 생성하기 전에 생각 체인을 명시적으로 사용하여 가능한 모든 경로를 탐색하는 것입니다. 그들은 자신의 답변을 생성할 때마다 이를 확인하여 더 나은 정확한 결론에 도달하는 데 도움이 됩니다. 즉, 추론 모델은 효과적인 결과를 생성하기 위해 프롬프트에 더 적은 컨텍스트가 필요할 수 있습니다.

이러한 모델 성능 크기 조정 방법은 더 높은 대기 시간 및 비용에 대해 성능을 거래하기 때문에 유추 컴퓨팅 시간이라고 합니다. 학습 컴퓨팅 시간을 통해 스케일링되는 다른 접근 방식과 대조됩니다.

추론 모델은 다음 두 가지 유형의 출력을 생성합니다.

  • 추론 완료
  • 출력 완료

이러한 완료는 모두 모델에서 생성된 콘텐츠에 포함되므로 모델과 관련된 토큰 제한 및 비용을 계산합니다. 일부 모델은 다음과 같은 DeepSeek-R1추론 콘텐츠를 출력할 수 있습니다. 다른 일부는, 예를 들어 o1는, 완료의 출력 부분만을 출력합니다.

필수 조건

이 자습서를 완전히 학습하려면 다음이 필요합니다.

  • 다음 명령을 사용하여 Azure AI 유추 패키지를 설치합니다.

    dotnet add package Azure.AI.Inference --prerelease
    
  • Entra ID를 사용하는 경우 다음 패키지도 필요합니다.

    dotnet add package Azure.Identity
    

채팅에서 추론 기능 사용

먼저 모델을 사용할 클라이언트를 만듭니다. 다음 코드는 환경 변수에 저장된 엔드포인트 URL과 키를 사용합니다.

ChatCompletionsClient client = new ChatCompletionsClient(
    new Uri("https://<resource>.services.ai.azure.com/models"),
    new AzureKeyCredential(Environment.GetEnvironmentVariable("AZURE_INFERENCE_CREDENTIAL"))
);

Azure AI 모델 유추 API를 사용하여 Azure AI Services 리소스에 모델을 배포했는지 확인합니다. Deepseek-R1 은 서버리스 API 엔드포인트로도 사용할 수 있습니다. 그러나 이러한 엔드포인트는 이 자습서에서 설명한 대로 매개 변수 model 를 사용하지 않습니다. Azure AI Foundry 포털>이동하여 모델이 Azure AI Services 섹션 아래에 나열되는지 확인할 수 있습니다.

Microsoft Entra ID 지원을 사용하여 리소스를 구성한 경우 다음 코드 조각을 사용하여 클라이언트를 만들 수 있습니다.

TokenCredential credential = new DefaultAzureCredential(includeInteractiveCredentials: true);
AzureAIInferenceClientOptions clientOptions = new AzureAIInferenceClientOptions();
BearerTokenAuthenticationPolicy tokenPolicy = new BearerTokenAuthenticationPolicy(credential, new string[] { "https://cognitiveservices.azure.com/.default" });

clientOptions.AddPolicy(tokenPolicy, HttpPipelinePosition.PerRetry);

client = new ChatCompletionsClient(
    new Uri("https://<resource>.services.ai.azure.com/models"),
    credential,
    clientOptions,
);

채팅 완료 요청 만들기

다음 예제에서는 모델에 대한 기본 채팅 요청을 만드는 방법을 보여 줍니다.

ChatCompletionsOptions requestOptions = new ChatCompletionsOptions()
{
    Messages = {
        new ChatRequestUserMessage("How many languages are in the world?")
    },
    Model = "deepseek-r1",
};

Response<ChatCompletions> response = client.Complete(requestOptions);

추론 모델에 대한 프롬프트를 작성할 때 다음 사항을 고려합니다.

  • 간단한 지침을 사용하고 생각의 사슬 기술을 사용하지 마십시오.
  • 기본 제공 추론 기능은 간단한 제로샷 프롬프트를 보다 복잡한 메서드만큼 효과적으로 만듭니다.
  • RAG 시나리오와 같은 추가 컨텍스트 또는 문서를 제공할 때 가장 관련성이 큰 정보만 포함하면 모델이 응답을 과도하게 복잡하게 만드는 것을 방지할 수 있습니다.
  • 추론 모델은 시스템 메시지의 사용을 지원할 수 있습니다. 그러나 다른 비이성적 모델만큼 엄격하게 따르지 않을 수도 있습니다.
  • 멀티 턴 애플리케이션을 만들 때 추론 콘텐츠 섹션에 설명된 대로 추론 콘텐츠 없이 모델의 최종 답변만 추가하면 됩니다.

추론 모델은 응답을 생성하는 데 시간이 더 오래 걸릴 수 있습니다. 그들은 더 깊고 구조화 된 문제 해결을 가능하게 생각의 긴 추론 체인을 사용합니다. 또한 자체 확인을 수행하여 자체 답변을 교차 확인하고 자신의 실수를 수정하여 새로운 자기 반영 동작을 보여 줍니다.

응답은 다음과 같습니다. 여기서 모델의 사용 통계를 볼 수 있습니다.

Console.WriteLine($"Response: {response.Value.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: <think>Okay, the user is asking how many languages exist in the world. I need to provide a clear and accurate...</think>The exact number of languages in the world is challenging to determine due to differences in definitions (e.g., distinguishing languages from dialects) and ongoing documentation efforts. However, widely cited estimates suggest there are approximately **7,000 languages** globally.
Model: deepseek-r1
Usage: 
  Prompt tokens: 11
  Total tokens: 897
  Completion tokens: 886

추론 콘텐츠

DeepSeek-R1과 같은 일부 추론 모델은 완성을 생성하고 그 뒤에 추론을 포함합니다. 완료와 관련된 추론은 태그 <think></think> 내의 응답 콘텐츠에 포함됩니다. 모델은 추론 콘텐츠를 생성할 시나리오를 선택할 수 있습니다. 응답에서 추론 콘텐츠를 추출하여 다음과 같이 모델의 사고 프로세스를 이해할 수 있습니다.

Regex regex = new Regex(pattern, RegexOptions.Singleline);
Match match = regex.Match(response.Value.Content);

Console.WriteLine("Response:");
if (match.Success)
{
    Console.WriteLine($"\tThinking: {match.Groups[1].Value}");
    Console.WriteLine($"\tAnswer: {match.Groups[2].Value}");
else
{
    Console.WriteLine($"Response: {response.Value.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}");
Thinking: Okay, the user is asking how many languages exist in the world. I need to provide a clear and accurate answer. Let's start by recalling the general consensus from linguistic sources. I remember that the number often cited is around 7,000, but maybe I should check some reputable organizations.\n\nEthnologue is a well-known resource for language data, and I think they list about 7,000 languages. But wait, do they update their numbers? It might be around 7,100 or so. Also, the exact count can vary because some sources might categorize dialects differently or have more recent data. \n\nAnother thing to consider is language endangerment. Many languages are endangered, with some having only a few speakers left. Organizations like UNESCO track endangered languages, so mentioning that adds context. Also, the distribution isn't even. Some countries have hundreds of languages, like Papua New Guinea with over 800, while others have just a few. \n\nA user might also wonder why the exact number is hard to pin down. It's because the distinction between a language and a dialect can be political or cultural. For example, Mandarin and Cantonese are considered dialects of Chinese by some, but they're mutually unintelligible, so others classify them as separate languages. Also, some regions are under-researched, making it hard to document all languages. \n\nI should also touch on language families. The 7,000 languages are grouped into families like Indo-European, Sino-Tibetan, Niger-Congo, etc. Maybe mention a few of the largest families. But wait, the question is just about the count, not the families. Still, it's good to provide a bit more context. \n\nI need to make sure the information is up-to-date. Let me think – recent estimates still hover around 7,000. However, languages are dying out rapidly, so the number decreases over time. Including that note about endangerment and language extinction rates could be helpful. For instance, it's often stated that a language dies every few weeks. \n\nAnother point is sign languages. Does the count include them? Ethnologue includes some, but not all sources might. If the user is including sign languages, that adds more to the count, but I think the 7,000 figure typically refers to spoken languages. For thoroughness, maybe mention that there are also over 300 sign languages. \n\nSummarizing, the answer should state around 7,000, mention Ethnologue's figure, explain why the exact number varies, touch on endangerment, and possibly note sign languages as a separate category. Also, a brief mention of Papua New Guinea as the most linguistically diverse country. \n\nWait, let me verify Ethnologue's current number. As of their latest edition (25th, 2022), they list 7,168 living languages. But I should check if that's the case. Some sources might round to 7,000. Also, SIL International publishes Ethnologue, so citing them as reference makes sense. \n\nOther sources, like Glottolog, might have a different count because they use different criteria. Glottolog might list around 7,000 as well, but exact numbers vary. It's important to highlight that the count isn't exact because of differing definitions and ongoing research. \n\nIn conclusion, the approximate number is 7,000, with Ethnologue being a key source, considerations of endangerment, and the challenges in counting due to dialect vs. language distinctions. I should make sure the answer is clear, acknowledges the variability, and provides key points succinctly.

Answer: The exact number of languages in the world is challenging to determine due to differences in definitions (e.g., distinguishing languages from dialects) and ongoing documentation efforts. However, widely cited estimates suggest there are approximately **7,000 languages** globally.
Model: DeepSeek-R1
Usage: 
  Prompt tokens: 11
  Total tokens: 897
  Completion tokens: 886

멀티 턴 대화를 만들 때 추론이 긴 설명을 생성하는 경향이 있으므로 채팅 기록에서 추론 콘텐츠를 보내지 않는 것이 유용합니다.

콘텐츠 스트리밍

기본적으로 완료 API는 생성된 전체 콘텐츠를 단일 응답으로 반환합니다. 긴 완료를 생성하는 경우 응답을 기다리는 데 몇 초 정도 걸릴 수 있습니다.

생성될 때 가져오기 위해 콘텐츠를 스트리밍할 수 있습니다. 콘텐츠를 스트리밍하면 콘텐츠를 사용할 수 있게 되면 완료 처리를 시작할 수 있습니다. 이 모드는 데이터 전용 서버 전송 이벤트 응답을 다시 스트리밍하는 개체를 반환합니다. 메시지 필드가 아닌 델타 필드에서 청크를 추출합니다.

static async Task StreamMessageAsync(ChatCompletionsClient client)
{
    ChatCompletionsOptions requestOptions = new ChatCompletionsOptions()
    {
        Messages = {
            new ChatRequestUserMessage("How many languages are in the world?")
        },
        MaxTokens=4096,
        Model = "deepseek-r1",
    };

    StreamingResponse<StreamingChatCompletionsUpdate> streamResponse = await client.CompleteStreamingAsync(requestOptions);

    await PrintStream(streamResponse);
}

출력을 시각화하려면 스트림을 인쇄하는 도우미 함수를 정의합니다. 다음 예제에서는 추론 콘텐츠 없이 답변만 스트리밍하는 라우팅을 구현합니다.

static void PrintStream(StreamingResponse<StreamingChatCompletionsUpdate> response)
{
    bool isThinking = false;
    await foreach (StreamingChatCompletionsUpdate chatUpdate in response)
    {
        if (!string.IsNullOrEmpty(chatUpdate.ContentUpdate))
        {
            string content = chatUpdate.ContentUpdate;
            if (content == "<think>")
            {
                isThinking = true;
                Console.Write("🧠 Thinking...");
                Console.Out.Flush();
            }
            else if (content == "</think>")
            {
                isThinking = false;
                Console.WriteLine("🛑\n\n");
            }
            else if (!string.IsNullOrEmpty(content))
            {
                Console.Write(content);
                Console.Out.Flush();
            }
        }
    }
}

스트리밍에서 콘텐츠를 생성하는 방법을 시각화할 수 있습니다.

StreamMessageAsync(client).GetAwaiter().GetResult();

매개 변수

일반적으로 추론 모델은 채팅 완성 모델에서 찾을 수 있는 다음 매개 변수를 지원하지 않습니다.

  • 온도
  • 현재 상태 패널티
  • 반복 페널티
  • 매개 변수 top_p

일부 모델은 도구 또는 구조화된 출력(JSON 스키마 포함)의 사용을 지원합니다. 각 모델의 지원을 이해하려면 모델 세부 정보 페이지를 참조하세요.

콘텐츠 안전 적용

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."
            ),
        },
        Model = "deepseek-r1",
    };

    response = client.Complete(requestOptions);
    Console.WriteLine(response.Value.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 콘텐츠 안전 설명서를 확인하세요.

중요

이 문서에 표시된 항목(미리 보기)은 현재 퍼블릭 미리 보기에서 확인할 수 있습니다. 이 미리 보기는 서비스 수준 계약 없이 제공되며, 프로덕션 워크로드에는 권장되지 않습니다. 특정 기능이 지원되지 않거나 기능이 제한될 수 있습니다. 자세한 내용은 Microsoft Azure Preview에 대한 추가 사용 약관을 참조하세요.

이 문서에서는 Azure AI 서비스에서 Azure AI 모델 유추에 배포된 채팅 완료 모델의 추론 기능을 사용하는 방법을 설명합니다.

추론 모델

추론 모델은 수학, 코딩, 과학, 전략 및 물류와 같은 도메인에서 더 높은 수준의 성능에 도달할 수 있습니다. 이러한 모델이 출력을 생성하는 방법은 대답을 생성하기 전에 생각 체인을 명시적으로 사용하여 가능한 모든 경로를 탐색하는 것입니다. 그들은 자신의 답변을 생성할 때마다 이를 확인하여 더 나은 정확한 결론에 도달하는 데 도움이 됩니다. 즉, 추론 모델은 효과적인 결과를 생성하기 위해 프롬프트에 더 적은 컨텍스트가 필요할 수 있습니다.

이러한 모델 성능 크기 조정 방법은 더 높은 대기 시간 및 비용에 대해 성능을 거래하기 때문에 유추 컴퓨팅 시간이라고 합니다. 학습 컴퓨팅 시간을 통해 스케일링되는 다른 접근 방식과 대조됩니다.

추론 모델은 다음 두 가지 유형의 출력을 생성합니다.

  • 추론 완료
  • 출력 완료

이러한 완료는 모두 모델에서 생성된 콘텐츠에 포함되므로 모델과 관련된 토큰 제한 및 비용을 계산합니다. 일부 모델은 다음과 같은 DeepSeek-R1추론 콘텐츠를 출력할 수 있습니다. 다른 일부는, 예를 들어 o1는, 완료의 출력 부분만을 출력합니다.

필수 조건

이 자습서를 완전히 학습하려면 다음이 필요합니다.

채팅에서 추론 기능 사용

먼저 모델을 사용할 클라이언트를 만듭니다. 다음 코드는 환경 변수에 저장된 엔드포인트 URL과 키를 사용합니다.

POST https://<resource>.services.ai.azure.com/models/chat/completions?api-version=2024-05-01-preview
Content-Type: application/json
api-key: <key>

Azure AI 모델 유추 API를 사용하여 Azure AI Services 리소스에 모델을 배포했는지 확인합니다. Deepseek-R1 은 서버리스 API 엔드포인트로도 사용할 수 있습니다. 그러나 이러한 엔드포인트는 이 자습서에서 설명한 대로 매개 변수 model 를 사용하지 않습니다. Azure AI Foundry 포털>이동하여 모델이 Azure AI Services 섹션 아래에 나열되는지 확인할 수 있습니다.

Microsoft Entra ID 지원을 사용하도록 리소스를 구성한 경우, Authorization 헤더에 Bearer <token>에 형식으로 토큰을 전달하세요. https://cognitiveservices.azure.com/.default 범위를 사용합니다.

POST https://<resource>.services.ai.azure.com/models/chat/completions?api-version=2024-05-01-preview
Content-Type: application/json
Authorization: Bearer <token>

Microsoft Entra ID를 사용하려면 액세스 권한을 부여하기 위해 리소스에 추가 구성이 필요할 수 있습니다. Microsoft Entra ID를 사용하여 키 없는 권한 부여를 구성하는 방법을 알아보세요.

채팅 완료 요청 만들기

다음 예제에서는 모델에 대한 기본 채팅 요청을 만드는 방법을 보여 줍니다.

{
    "model": "deepseek-r1",
    "messages": [
        {
            "role": "user",
            "content": "How many languages are in the world?"
        }
    ]
}

추론 모델에 대한 프롬프트를 작성할 때 다음 사항을 고려합니다.

  • 간단한 지침을 사용하고 생각의 사슬 기술을 사용하지 마십시오.
  • 기본 제공 추론 기능은 간단한 제로샷 프롬프트를 보다 복잡한 메서드만큼 효과적으로 만듭니다.
  • RAG 시나리오와 같은 추가 컨텍스트 또는 문서를 제공할 때 가장 관련성이 큰 정보만 포함하면 모델이 응답을 과도하게 복잡하게 만드는 것을 방지할 수 있습니다.
  • 추론 모델은 시스템 메시지의 사용을 지원할 수 있습니다. 그러나 다른 비이성적 모델만큼 엄격하게 따르지 않을 수도 있습니다.
  • 멀티 턴 애플리케이션을 만들 때 추론 콘텐츠 섹션에 설명된 대로 추론 콘텐츠 없이 모델의 최종 답변만 추가하면 됩니다.

추론 모델은 응답을 생성하는 데 시간이 더 오래 걸릴 수 있습니다. 그들은 더 깊고 구조화 된 문제 해결을 가능하게 생각의 긴 추론 체인을 사용합니다. 또한 자체 확인을 수행하여 자체 답변을 교차 확인하고 자신의 실수를 수정하여 새로운 자기 반영 동작을 보여 줍니다.

응답은 다음과 같습니다. 여기서 모델의 사용 통계를 볼 수 있습니다.

{
    "id": "0a1234b5de6789f01gh2i345j6789klm",
    "object": "chat.completion",
    "created": 1718726686,
    "model": "DeepSeek-R1",
    "choices": [
        {
            "index": 0,
            "message": {
                "role": "assistant",
                "content": "<think>\nOkay, the user is asking how many languages exist in the world. I need to provide a clear and accurate answer. Let's start by recalling the general consensus from linguistic sources. I remember that the number often cited is around 7,000, but maybe I should check some reputable organizations.\n\nEthnologue is a well-known resource for language data, and I think they list about 7,000 languages. But wait, do they update their numbers? It might be around 7,100 or so. Also, the exact count can vary because some sources might categorize dialects differently or have more recent data. \n\nAnother thing to consider is language endangerment. Many languages are endangered, with some having only a few speakers left. Organizations like UNESCO track endangered languages, so mentioning that adds context. Also, the distribution isn't even. Some countries have hundreds of languages, like Papua New Guinea with over 800, while others have just a few. \n\nA user might also wonder why the exact number is hard to pin down. It's because the distinction between a language and a dialect can be political or cultural. For example, Mandarin and Cantonese are considered dialects of Chinese by some, but they're mutually unintelligible, so others classify them as separate languages. Also, some regions are under-researched, making it hard to document all languages. \n\nI should also touch on language families. The 7,000 languages are grouped into families like Indo-European, Sino-Tibetan, Niger-Congo, etc. Maybe mention a few of the largest families. But wait, the question is just about the count, not the families. Still, it's good to provide a bit more context. \n\nI need to make sure the information is up-to-date. Let me think – recent estimates still hover around 7,000. However, languages are dying out rapidly, so the number decreases over time. Including that note about endangerment and language extinction rates could be helpful. For instance, it's often stated that a language dies every few weeks. \n\nAnother point is sign languages. Does the count include them? Ethnologue includes some, but not all sources might. If the user is including sign languages, that adds more to the count, but I think the 7,000 figure typically refers to spoken languages. For thoroughness, maybe mention that there are also over 300 sign languages. \n\nSummarizing, the answer should state around 7,000, mention Ethnologue's figure, explain why the exact number varies, touch on endangerment, and possibly note sign languages as a separate category. Also, a brief mention of Papua New Guinea as the most linguistically diverse country. \n\nWait, let me verify Ethnologue's current number. As of their latest edition (25th, 2022), they list 7,168 living languages. But I should check if that's the case. Some sources might round to 7,000. Also, SIL International publishes Ethnologue, so citing them as reference makes sense. \n\nOther sources, like Glottolog, might have a different count because they use different criteria. Glottolog might list around 7,000 as well, but exact numbers vary. It's important to highlight that the count isn't exact because of differing definitions and ongoing research. \n\nIn conclusion, the approximate number is 7,000, with Ethnologue being a key source, considerations of endangerment, and the challenges in counting due to dialect vs. language distinctions. I should make sure the answer is clear, acknowledges the variability, and provides key points succinctly.\n</think>\n\nThe exact number of languages in the world is challenging to determine due to differences in definitions (e.g., distinguishing languages from dialects) and ongoing documentation efforts. However, widely cited estimates suggest there are approximately **7,000 languages** globally.",
                "tool_calls": null
            },
            "finish_reason": "stop"
        }
    ],
    "usage": {
        "prompt_tokens": 11,
        "total_tokens": 897,
        "completion_tokens": 886
    }
}

추론 콘텐츠

DeepSeek-R1과 같은 일부 추론 모델은 완성을 생성하고 그 뒤에 추론을 포함합니다. 완료와 관련된 추론은 태그 <think></think> 내의 응답 콘텐츠에 포함됩니다. 모델은 추론 콘텐츠를 생성할 시나리오를 선택할 수 있습니다.

멀티 턴 대화를 만들 때 추론이 긴 설명을 생성하는 경향이 있으므로 채팅 기록에서 추론 콘텐츠를 보내지 않는 것이 유용합니다.

콘텐츠 스트리밍

기본적으로 완료 API는 생성된 전체 콘텐츠를 단일 응답으로 반환합니다. 긴 완료를 생성하는 경우 응답을 기다리는 데 몇 초 정도 걸릴 수 있습니다.

생성될 때 가져오기 위해 콘텐츠를 스트리밍할 수 있습니다. 콘텐츠를 스트리밍하면 콘텐츠를 사용할 수 있게 되면 완료 처리를 시작할 수 있습니다. 이 모드는 데이터 전용 서버 전송 이벤트 응답을 다시 스트리밍하는 개체를 반환합니다. 메시지 필드가 아닌 델타 필드에서 청크를 추출합니다.

완성을 스트리밍하려면 모델을 호출할 때 "stream": true를 설정합니다.

{
    "model": "DeepSeek-R1",
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": "How many languages are in the world?"
        }
    ],
    "stream": true,
    "max_tokens": 2048
}

출력을 시각화하려면 스트림을 인쇄하는 도우미 함수를 정의합니다. 다음 예제에서는 추론 콘텐츠 없이 답변만 스트리밍하는 라우팅을 구현합니다.

{
    "id": "23b54589eba14564ad8a2e6978775a39",
    "object": "chat.completion.chunk",
    "created": 1718726371,
    "model": "DeepSeek-R1",
    "choices": [
        {
            "index": 0,
            "delta": {
                "role": "assistant",
                "content": ""
            },
            "finish_reason": null,
            "logprobs": null
        }
    ]
}

스트림의 마지막 메시지는 생성 프로세스가 중지되는 이유를 나타내는 finish_reason이 설정되었습니다.

{
    "id": "23b54589eba14564ad8a2e6978775a39",
    "object": "chat.completion.chunk",
    "created": 1718726371,
    "model": "DeepSeek-R1",
    "choices": [
        {
            "index": 0,
            "delta": {
                "content": ""
            },
            "finish_reason": "stop",
            "logprobs": null
        }
    ],
    "usage": {
        "prompt_tokens": 11,
        "total_tokens": 897,
        "completion_tokens": 886
    }
}

매개 변수

일반적으로 추론 모델은 채팅 완성 모델에서 찾을 수 있는 다음 매개 변수를 지원하지 않습니다.

  • 온도
  • 현재 상태 패널티
  • 반복 페널티
  • 매개 변수 top_p

일부 모델은 도구 또는 구조화된 출력(JSON 스키마 포함)의 사용을 지원합니다. 각 모델의 지원을 이해하려면 모델 세부 정보 페이지를 참조하세요.

콘텐츠 안전 적용

Azure AI 모델 유추 API는 Azure AI 콘텐츠 안전을 지원합니다. Azure AI 콘텐츠 안전이 켜져 있는 배포를 사용하는 경우 입력 및 출력은 유해한 콘텐츠의 출력을 감지하고 방지하기 위한 분류 모델의 앙상블을 통과합니다. 콘텐츠 필터링 시스템은 입력 프롬프트와 출력 완료 모두에서 잠재적으로 유해한 콘텐츠의 특정 범주를 탐지하고 조치를 취합니다.

다음 예제에서는 모델이 입력 프롬프트에서 유해한 콘텐츠를 감지하고 콘텐츠 안전이 사용하도록 설정된 경우 이벤트를 처리하는 방법을 보여 줍니다.

{
    "model": "DeepSeek-R1",
    "messages": [
        {
            "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 콘텐츠 안전 설명서를 확인하세요.