.NET용 Azure OpenAI 클라이언트 라이브러리 - 버전 1.0.0-beta.5

.NET용 Azure OpenAI 클라이언트 라이브러리는 다른 Azure SDK 에코시스템과 Idiomatic 인터페이스 및 풍부한 통합을 제공하는 OpenAI의 REST API를 적용한 것입니다. Azure OpenAI 리소스 또는 비 Azure OpenAI 유추 엔드포인트에 연결할 수 있으므로 비 Azure OpenAI 개발에도 적합합니다.

Azure OpenAI용 클라이언트 라이브러리를 사용하여 다음을 수행합니다.

Azure OpenAI는 개발자가 Azure 리소스의 OpenAI 모델에서 콘텐츠를 배포, 조정 및 생성할 수 있는 관리형 서비스입니다.

소스 코드 | 패키지(NuGet) | API 참조 설명서 | 제품 설명서 | 샘플

시작

필수 조건

Azure OpenAI 리소스를 사용하려면 Azure 구독Azure OpenAI 액세스 권한이 있어야 합니다. 이렇게 하면 Azure OpenAI 리소스를 만들고 연결 URL과 API 키를 모두 가져올 수 있습니다. 자세한 내용은 빠른 시작: Azure OpenAI Service를 사용하여 텍스트 생성 시작을 참조하세요.

Azure OpenAI .NET 클라이언트 라이브러리를 사용하여 비 Azure OpenAI에 연결하려면 의 개발자 계정 https://platform.openai.com/에서 API 키가 필요합니다.

패키지 설치

NuGet을 사용하여 .NET용 클라이언트 라이브러리를 설치합니다.

dotnet add package Azure.AI.OpenAI --prerelease

클라이언트 인증

Azure OpenAI 또는 OpenAI와 상호 작용하려면 OpenAIClient 클래스의 instance 만들어야 합니다. Azure OpenAI에서 사용할 클라이언트를 구성하려면 Azure OpenAI 리소스를 사용할 수 있는 권한이 부여된 해당 키 자격 증명, 토큰 자격 증명 또는 Azure ID 자격 증명과 함께 Azure OpenAI 리소스에 유효한 엔드포인트 URI를 제공합니다. 대신 OpenAI의 서비스에 연결하도록 클라이언트를 구성하려면 OpenAI 개발자 포털에서 API 키를 제공합니다.

OpenAIClient client = useAzureOpenAI
    ? new OpenAIClient(
        new Uri("https://your-azure-openai-resource.com/"),
        new AzureKeyCredential("your-azure-openai-resource-api-key"))
    : new OpenAIClient("your-api-key-from-platform.openai.com");

Azure Active Directory 자격 증명을 사용하여 OpenAIClient 만들기

클라이언트 구독 키 인증은 이 시작 가이드의 대부분의 예제에서 사용되지만 Azure ID 라이브러리를 사용하여 Azure Active Directory로 인증할 수도 있습니다. 아래 표시된 DefaultAzureCredential 공급자 또는 Azure SDK와 함께 제공되는 다른 자격 증명 공급자를 사용하려면 Azure.Identity 패키지를 설치하세요.

dotnet add package Azure.Identity
string endpoint = "https://myaccount.openai.azure.com/";
var client = new OpenAIClient(new Uri(endpoint), new DefaultAzureCredential());

주요 개념

이해해야 할 기본 개념은 완료입니다. 간략하게 설명하면 완성은 특정 모델을 사용하여 컨텍스트 및 패턴과 일치하도록 시도하여 출력 텍스트를 제공하는 텍스트 프롬프트 형식의 기능을 제공합니다. 다음 코드 조각은 대략적인 개요를 제공합니다(자세한 내용은 샘플 코드에서 GenerateChatbotResponsesWithToken 찾을 수 있음).

OpenAIClient client = useAzureOpenAI
    ? new OpenAIClient(
        new Uri("https://your-azure-openai-resource.com/"),
        new AzureKeyCredential("your-azure-openai-resource-api-key"))
    : new OpenAIClient("your-api-key-from-platform.openai.com");

Response<Completions> response = await client.GetCompletionsAsync(
    "text-davinci-003", // assumes a matching model deployment or model name
    "Hello, world!");

foreach (Choice choice in response.Value.Choices)
{
    Console.WriteLine(choice.Text);
}

스레드로부터의 안전성

모든 클라이언트 instance 메서드가 스레드로부터 안전하고 서로 독립적임을 보장합니다(지침). 이렇게 하면 스레드 간에도 클라이언트 인스턴스를 다시 사용하는 것이 항상 안전합니다.

추가 개념

클라이언트 옵션 | 응답 | 에 액세스 장기 실행 작업 | 오류 | 처리 진단 | 조롱 | 클라이언트 수명

예제

샘플을 사용하여 다양한 API를 숙지할 수 있습니다.

챗봇 응답 생성

메서드는 GenerateChatbotResponse DefaultAzureCredential을 사용하여 인증한 다음 입력 프롬프트에 대한 텍스트 응답을 생성합니다.

string endpoint = "https://myaccount.openai.azure.com/";
var client = new OpenAIClient(new Uri(endpoint), new DefaultAzureCredential());

string deploymentName = "text-davinci-003";
string prompt = "What is Azure OpenAI?";
Console.Write($"Input: {prompt}");

Response<Completions> completionsResponse = client.GetCompletions(deploymentName, prompt);
string completion = completionsResponse.Value.Choices[0].Text;
Console.WriteLine($"Chatbot: {completion}");

구독 키를 사용하여 여러 챗봇 응답 생성

메서드는 GenerateMultipleChatbotResponsesWithSubscriptionKey Azure 구독 키를 사용하여 입력 프롬프트에 대한 텍스트 응답을 생성하는 예제를 제공합니다.

// Replace with your Azure OpenAI key
string key = "YOUR_AZURE_OPENAI_KEY";
string endpoint = "https://myaccount.openai.azure.com/";
var client = new OpenAIClient(new Uri(endpoint), new AzureKeyCredential(key));

List<string> examplePrompts = new(){
    "How are you today?",
    "What is Azure OpenAI?",
    "Why do children love dinosaurs?",
    "Generate a proof of Euler's identity",
    "Describe in single words only the good things that come into your mind about your mother.",
};

string deploymentName = "text-davinci-003";

foreach (string prompt in examplePrompts)
{
    Console.Write($"Input: {prompt}");
    CompletionsOptions completionsOptions = new CompletionsOptions();
    completionsOptions.Prompts.Add(prompt);

    Response<Completions> completionsResponse = client.GetCompletions(deploymentName, completionsOptions);
    string completion = completionsResponse.Value.Choices[0].Text;
    Console.WriteLine($"Chatbot: {completion}");
}

완성을 사용하여 텍스트 요약

메서드는 SummarizeText 지정된 입력 프롬프트의 요약을 생성합니다.

string endpoint = "https://myaccount.openai.azure.com/";
var client = new OpenAIClient(new Uri(endpoint), new DefaultAzureCredential());

string textToSummarize = @"
    Two independent experiments reported their results this morning at CERN, Europe's high-energy physics laboratory near Geneva in Switzerland. Both show convincing evidence of a new boson particle weighing around 125 gigaelectronvolts, which so far fits predictions of the Higgs previously made by theoretical physicists.

    ""As a layman I would say: 'I think we have it'. Would you agree?"" Rolf-Dieter Heuer, CERN's director-general, asked the packed auditorium. The physicists assembled there burst into applause.
:";

string summarizationPrompt = @$"
    Summarize the following text.

    Text:
    """"""
    {textToSummarize}
    """"""

    Summary:
";

Console.Write($"Input: {summarizationPrompt}");
var completionsOptions = new CompletionsOptions()
{
    Prompts = { summarizationPrompt },
};

string deploymentName = "text-davinci-003";

Response<Completions> completionsResponse = client.GetCompletions(deploymentName, completionsOptions);
string completion = completionsResponse.Value.Choices[0].Text;
Console.WriteLine($"Summarization: {completion}");

비 Azure OpenAI를 사용하여 채팅 메시지 스트리밍

string nonAzureOpenAIApiKey = "your-api-key-from-platform.openai.com";
var client = new OpenAIClient(nonAzureOpenAIApiKey, new OpenAIClientOptions());
var chatCompletionsOptions = new ChatCompletionsOptions()
{
    Messages =
    {
        new ChatMessage(ChatRole.System, "You are a helpful assistant. You will talk like a pirate."),
        new ChatMessage(ChatRole.User, "Can you help me?"),
        new ChatMessage(ChatRole.Assistant, "Arrrr! Of course, me hearty! What can I do for ye?"),
        new ChatMessage(ChatRole.User, "What's the best way to train a parrot?"),
    }
};

Response<StreamingChatCompletions> response = await client.GetChatCompletionsStreamingAsync(
    deploymentOrModelName: "gpt-3.5-turbo",
    chatCompletionsOptions);
using StreamingChatCompletions streamingChatCompletions = response.Value;

await foreach (StreamingChatChoice choice in streamingChatCompletions.GetChoicesStreaming())
{
    await foreach (ChatMessage message in choice.GetMessageStreaming())
    {
        Console.Write(message.Content);
    }
    Console.WriteLine();
}

문제 해결

.NET SDK를 사용하여 Azure OpenAI와 상호 작용하는 경우 서비스에서 반환된 오류는 REST API 요청에 대해 반환된 동일한 HTTP 상태 코드에 해당합니다.

예를 들어 Azure OpenAI 리소스 엔드포인트와 일치하지 않는 엔드포인트를 사용하여 클라이언트를 만들려고 하면 을 404 나타내는 Resource Not Found오류가 반환됩니다.

다음 단계

  • 패키지 /samples 디렉터리의 추가 정보 옆에 있는 사용자에게 이상적으로 추가 코드 예제에 대한 링크를 제공합니다.
  • 적절한 경우 사용자에게 유용할 수 있는 다른 패키지를 가리킵니다.
  • 개발자가 특정 기능을 검색하고 패키지가 해당 기능을 제공한다고 잘못 생각하기 때문에 오류가 발생할 가능성이 높다고 생각되면 원하는 패키지를 가리킵니다.

참여

이 라이브러리의 빌드, 테스트 및 기여에 대한 자세한 내용은 OpenAI CONTRIBUTING.md 참조하세요.

이 프로젝트에 대한 기여와 제안을 환영합니다. 대부분의 경우 기여하려면 권한을 부여하며 실제로 기여를 사용할 권한을 당사에 부여한다고 선언하는 CLA(기여자 라이선스 계약)에 동의해야 합니다. 자세한 내용은 cla.microsoft.com.

끌어오기 요청을 제출하면 CLA-bot은 CLA를 제공하고 PR을 적절하게 데코레이팅해야 하는지 여부를 자동으로 결정합니다(예: 레이블, 설명). 봇에서 제공하는 지침을 따르기만 하면 됩니다. 이 작업은 CLA를 사용하여 모든 리포지토리에서 한 번만 수행하면 됩니다.

이 프로젝트에는 Microsoft Open Source Code of Conduct(Microsoft 오픈 소스 준수 사항)가 적용됩니다. 자세한 내용은 Code of Conduct FAQ(규정 FAQ)를 참조하세요. 또는 추가 질문이나 의견은 opencode@microsoft.com으로 문의하세요.

Impressions