Aracılığıyla paylaş


Azure OpenAI tarafından desteklenen programlama dilleri

.NET için Azure OpenAI istemci kitaplığı, .NET için resmi OpenAI istemci kitaplığının eşlikçisidir. Azure OpenAI kütüphanesi, Azure OpenAI ile kullanmak üzere bir istemci yapılandırır ve Azure OpenAI senaryolarına özgü istek ve yanıt modelleri için ekstra güçlü biçimde türlendirilmiş uzantı desteği sağlar.

Kararlı sürüm:

Kaynak kodu | Paketi (NuGet) | Paket başvurusu belgeleriAPI başvuru belgeleri Örnekler |

Önizleme sürümü:

Önizleme sürümü en son özelliklere erişebilir.

Kaynak kodu | Paketi (NuGet) | API başvuru belgeleri | Paket başvurusu belgeleri Örnekler

Azure OpenAI API sürüm desteği

Python ve JavaScript için Azure OpenAI istemci kitaplıklarından farklı olarak Azure OpenAI .NET paketi, Azure OpenAI API sürümlerinin belirli bir alt kümesini hedeflemeyle sınırlıdır. Genellikle her Azure OpenAI .NET paketi daha yeni Azure OpenAI API yayın özelliklerine erişimin kilidini açar. En son API sürümlerine erişim sahibi olmak özellik kullanılabilirliğini etkiler.

Sürüm seçimi AzureOpenAIClientOptions.ServiceVersion numaralandırması tarafından kontrol edilmektedir.

Kararlı sürüm şu anda şunları hedefliyor:

2024-06-01

Önizleme sürümü şu anda şunları hedefleyebilir:

  • 2024-08-01-preview
  • 2024-09-01-preview
  • 2024-10-01-preview
  • 2024-12-01-preview
  • 2025-01-01-preview
  • 2025-03-01-preview

Kurulum

dotnet add package Azure.AI.OpenAI --prerelease

Paket Azure.AI.OpenAI, bağımlılık olarak dahil edilen resmi OpenAI paketini temel alır.

Kimlik doğrulama

Azure OpenAI veya OpenAI ile etkileşim kurmak için aşağıdaki yaklaşımlardan biriyle bir instance AzureOpenAIClient oluşturun.

Güvenli, anahtarsız bir kimlik doğrulama yaklaşımı, Azure Identity kitaplığı aracılığıyla Microsoft Entra ID (eski adıyla Azure Active Directory) kullanmaktır. Kitaplığı kullanmak için:

dotnet add package Azure.Identity

Kütüphaneden tercih edilen kimlik bilgisi türünü kullanın. Örneğin, DefaultAzureCredential:

AzureOpenAIClient openAIClient = new(
    new Uri("https://your-azure-openai-resource.com"),
    new DefaultAzureCredential());
ChatClient chatClient = openAIClient.GetChatClient("my-gpt-4o-mini-deployment");

Azure OpenAI anahtarsız kimlik doğrulaması hakkında daha fazla bilgi için "Azure OpenAI güvenlik yapı taşını kullanmaya başlama" Hızlı Başlangıç makalesine bakın.

Ses

AzureOpenAIClient.GetAudioClient

Transkripsiyon

AzureOpenAIClient openAIClient = new(
    new Uri("https://your-azure-openai-resource.com"),
    new DefaultAzureCredential());

AudioClient client = openAIClient.GetAudioClient("whisper");

string audioFilePath = Path.Combine("Assets", "speech.mp3");

AudioTranscriptionOptions options = new()
{
    ResponseFormat = AudioTranscriptionFormat.Verbose,
    TimestampGranularities = AudioTimestampGranularities.Word | AudioTimestampGranularities.Segment,
};

AudioTranscription transcription = client.TranscribeAudio(audioFilePath, options);

Console.WriteLine("Transcription:");
Console.WriteLine($"{transcription.Text}");

Console.WriteLine();
Console.WriteLine($"Words:");
foreach (TranscribedWord word in transcription.Words)
{
    Console.WriteLine($"  {word.Word,15} : {word.StartTime.TotalMilliseconds,5:0} - {word.EndTime.TotalMilliseconds,5:0}");
}

Console.WriteLine();
Console.WriteLine($"Segments:");
foreach (TranscribedSegment segment in transcription.Segments)
{
    Console.WriteLine($"  {segment.Text,90} : {segment.StartTime.TotalMilliseconds,5:0} - {segment.EndTime.TotalMilliseconds,5:0}");
}

Metin Okuma (TTS)

using Azure.AI.OpenAI;
using Azure.Identity;
using OpenAI.Audio;

AzureOpenAIClient openAIClient = new(
    new Uri("https://your-azure-openai-resource.com"),
    new DefaultAzureCredential());

AudioClient client = openAIClient.GetAudioClient("tts-hd"); //Replace with your Azure OpenAI model deployment

string input = "Testing, testing, 1, 2, 3";

BinaryData speech = client.GenerateSpeech(input, GeneratedSpeechVoice.Alloy);

using FileStream stream = File.OpenWrite($"{Guid.NewGuid()}.mp3");
speech.ToStream().CopyTo(stream);

Sohbet

AzureOpenAIClient.GetChatClient

AzureOpenAIClient openAIClient = new(
    new Uri("https://your-azure-openai-resource.com"),
    new DefaultAzureCredential());
ChatClient chatClient = openAIClient.GetChatClient("my-gpt-4o-deployment");

ChatCompletion completion = chatClient.CompleteChat(
    [
        // System messages represent instructions or other guidance about how the assistant should behave
        new SystemChatMessage("You are a helpful assistant that talks like a pirate."),
        // User messages represent user input, whether historical or the most recent input
        new UserChatMessage("Hi, can you help me?"),
        // Assistant messages in a request represent conversation history for responses
        new AssistantChatMessage("Arrr! Of course, me hearty! What can I do for ye?"),
        new UserChatMessage("What's the best way to train a parrot?"),
    ]);

Console.WriteLine($"{completion.Role}: {completion.Content[0].Text}");

Sohbet iletilerini akışla aktar

Akış sohbeti tamamlamaları, bir CompleteChatStreaming yerine bir CompleteChatStreamingAsync veya ResultCollection<StreamingChatCompletionUpdate> döndüren AsyncCollectionResult<StreamingChatCompletionUpdate> ve ClientResult<ChatCompletion> yöntemini kullanır.

Bu sonuç koleksiyonları foreach veya await foreach kullanılarak yinelenebilir; stream yanıtından yeni veriler kullanıma sunulduğunda her güncelleme gelir.

AzureOpenAIClient openAIClient = new(
    new Uri("https://your-azure-openai-resource.com"),
    new DefaultAzureCredential());
ChatClient chatClient = openAIClient.GetChatClient("my-gpt-4o-deployment");

CollectionResult<StreamingChatCompletionUpdate> completionUpdates = chatClient.CompleteChatStreaming(
    [
        new SystemChatMessage("You are a helpful assistant that talks like a pirate."),
        new UserChatMessage("Hi, can you help me?"),
        new AssistantChatMessage("Arrr! Of course, me hearty! What can I do for ye?"),
        new UserChatMessage("What's the best way to train a parrot?"),
    ]);

foreach (StreamingChatCompletionUpdate completionUpdate in completionUpdates)
{
    foreach (ChatMessageContentPart contentPart in completionUpdate.ContentUpdate)
    {
        Console.Write(contentPart.Text);
    }
}

Eklemeler

AzureOpenAIClient.GetEmbeddingClient

using Azure.AI.OpenAI;
using Azure.Identity;
using OpenAI.Embeddings;

AzureOpenAIClient openAIClient = new(
    new Uri("https://your-azure-openai-resource.com"),
    new DefaultAzureCredential());

EmbeddingClient client = openAIClient.GetEmbeddingClient("text-embedding-3-large"); //Replace with your model deployment name

string description = "This is a test embedding";

OpenAIEmbedding embedding = client.GenerateEmbedding(description);
ReadOnlyMemory<float> vector = embedding.ToFloats();

Console.WriteLine(string.Join(", ", vector.ToArray()));

Hassas ayarlama

Şu anda Azure OpenAI .NET paketleriyle desteklenmiyor.

Toplu işlem

Şu anda Azure OpenAI .NET paketleriyle desteklenmiyor.

Resimler

AzureOpenAIClient.GetImageClient

using Azure.AI.OpenAI;
using Azure.Identity;
using OpenAI.Images;

AzureOpenAIClient openAIClient = new(
    new Uri("https://your-azure-openai-resource.com"),
    new DefaultAzureCredential());

ImageClient client = openAIClient.GetImageClient("dall-e-3"); // replace with your model deployment name.

string prompt = "A rabbit eating pancakes.";

ImageGenerationOptions options = new()
{
     Quality = GeneratedImageQuality.High,
     Size = GeneratedImageSize.W1792xH1024,
     Style = GeneratedImageStyle.Vivid,
     ResponseFormat = GeneratedImageFormat.Bytes
};

GeneratedImage image = client.GenerateImage(prompt, options);
BinaryData bytes = image.ImageBytes;

using FileStream stream = File.OpenWrite($"{Guid.NewGuid()}.png");
bytes.ToStream().CopyTo(stream);

Akıl yürütme modelleri

using Azure.AI.OpenAI;
using Azure.AI.OpenAI.Chat;
using Azure.Identity;
using OpenAI.Chat;


AzureOpenAIClient openAIClient = new(
    new Uri("https://YOUR-RESOURCE-NAME.openai.azure.com/"),
    new DefaultAzureCredential());
ChatClient chatClient = openAIClient.GetChatClient("o3-mini");

// Create ChatCompletionOptions and set the reasoning effort level
ChatCompletionOptions options = new ChatCompletionOptions
{
    ReasoningEffortLevel = ChatReasoningEffortLevel.Low,
    MaxOutputTokenCount = 100000
};

#pragma warning disable AOAI001 //currently required to use MaxOutputTokenCount

options.SetNewMaxCompletionTokensPropertyEnabled(true);

ChatCompletion completion = chatClient.CompleteChat(
    [

        new UserChatMessage("Testing 1,2,3")
    ],
    options); // Pass the options to the CompleteChat method

Console.WriteLine($"{completion.Role}: {completion.Content[0].Text}");

Tamamlamalar (eski)

Azure OpenAI .NET paketleriyle desteklenmez.

Hata yönetimi

Hata kodları

Durum Kodu Hata Türü
400 Bad Request Error
401 Authentication Error
403 Permission Denied Error
404 Not Found Error
422 Unprocessable Entity Error
429 Rate Limit Error
beş yüz Internal Server Error
503 Service Unavailable
504 Gateway Timeout

Yeniden denemeler

İstemci sınıfları, üstel geri alma kullanarak aşağıdaki hataları en fazla üç kez daha otomatik olarak yeniden dener:

  • 408 İstek Zaman Aşımı
  • 429 Çok Fazla İstek Var
  • 500 İç Sunucu Hatası
  • 502 Hatalı Ağ Geçidi
  • 503 Hizmet Kullanılamıyor
  • 504 Ağ Geçidi Zaman Aşımı

Kaynak kodu | Paket (pkg.go.dev) | API referans belgeleri | Paket referans belgeleriÖrnekler

Azure OpenAI API sürüm desteği

Python ve JavaScript için Azure OpenAI istemci kitaplıklarının aksine, Azure OpenAI Go kitaplığı belirli bir Azure OpenAI API sürümüne hedeflenir. En son API sürümlerine erişim sahibi olmak özellik kullanılabilirliğini etkiler.

Geçerli Azure OpenAI API sürüm hedefi: 2025-01-01-preview

Bu, custom_client.go dosyasında tanımlanır.

Kurulum

azopenai ve azidentity modüllerini go get ile yükleyin.

go get github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai

# optional
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity

Kimlik doğrulama

azidentity modülü, Azure OpenAI ile Azure Active Directory kimlik doğrulaması için kullanılır.

package main

import (
	"log"

	"github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai"
	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)

func main() {
	dac, err := azidentity.NewDefaultAzureCredential(nil)

	if err != nil {
		// TODO: Update the following line with your application specific error handling logic
		log.Printf("ERROR: %s", err)
		return
	}

	// NOTE: this constructor creates a client that connects to an Azure OpenAI endpoint.
	// To connect to the public OpenAI endpoint, use azopenai.NewClientForOpenAI
	client, err := azopenai.NewClient("https://<your-azure-openai-host>.openai.azure.com", dac, nil)

	if err != nil {
		// TODO: Update the following line with your application specific error handling logic
		log.Printf("ERROR: %s", err)
		return
	}

	_ = client
}

Azure OpenAI anahtarsız kimlik doğrulaması hakkında daha fazla bilgi için bkz. Anahtar Kullanılmadan Azure OpenAI Kullanma.

Ses

İstemci.MetindenKonuşmaOluştur

ackage main

import (
	"context"
	"fmt"
	"io"
	"log"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
)

func main() {
	openAIKey := os.Getenv("OPENAI_API_KEY")

	// Ex: "https://api.openai.com/v1"
	openAIEndpoint := os.Getenv("OPENAI_ENDPOINT")

	modelDeploymentID := "tts-1"

	if openAIKey == "" || openAIEndpoint == "" || modelDeploymentID == "" {
		fmt.Fprintf(os.Stderr, "Skipping example, environment variables missing\n")
		return
	}

	keyCredential := azcore.NewKeyCredential(openAIKey)

	client, err := azopenai.NewClientForOpenAI(openAIEndpoint, keyCredential, nil)

	if err != nil {
		// TODO: Update the following line with your application specific error handling logic
		log.Printf("ERROR: %s", err)
		return
	}

	audioResp, err := client.GenerateSpeechFromText(context.Background(), azopenai.SpeechGenerationOptions{
		Input:          to.Ptr("i am a computer"),
		Voice:          to.Ptr(azopenai.SpeechVoiceAlloy),
		ResponseFormat: to.Ptr(azopenai.SpeechGenerationResponseFormatFlac),
		DeploymentName: to.Ptr("tts-1"),
	}, nil)

	if err != nil {
		// TODO: Update the following line with your application specific error handling logic
		log.Printf("ERROR: %s", err)
		return
	}

	defer audioResp.Body.Close()

	audioBytes, err := io.ReadAll(audioResp.Body)

	if err != nil {
		// TODO: Update the following line with your application specific error handling logic
		log.Printf("ERROR: %s", err)
		return
	}

	fmt.Fprintf(os.Stderr, "Got %d bytes of FLAC audio\n", len(audioBytes))

}

Client.GetAudioTranscription

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
)

func main() {
	azureOpenAIKey := os.Getenv("AOAI_AUDIO_API_KEY")

	// Ex: "https://<your-azure-openai-host>.openai.azure.com"
	azureOpenAIEndpoint := os.Getenv("AOAI_AUDIO_ENDPOINT")

	modelDeploymentID := os.Getenv("AOAI_AUDIO_MODEL")

	if azureOpenAIKey == "" || azureOpenAIEndpoint == "" || modelDeploymentID == "" {
		fmt.Fprintf(os.Stderr, "Skipping example, environment variables missing\n")
		return
	}

	keyCredential := azcore.NewKeyCredential(azureOpenAIKey)

	client, err := azopenai.NewClientWithKeyCredential(azureOpenAIEndpoint, keyCredential, nil)

	if err != nil {
		// TODO: Update the following line with your application specific error handling logic
		log.Printf("ERROR: %s", err)
		return
	}

	mp3Bytes, err := os.ReadFile("testdata/sampledata_audiofiles_myVoiceIsMyPassportVerifyMe01.mp3")

	if err != nil {
		// TODO: Update the following line with your application specific error handling logic
		log.Printf("ERROR: %s", err)
		return
	}

	resp, err := client.GetAudioTranscription(context.TODO(), azopenai.AudioTranscriptionOptions{
		File: mp3Bytes,

		// this will return _just_ the translated text. Other formats are available, which return
		// different or additional metadata. See [azopenai.AudioTranscriptionFormat] for more examples.
		ResponseFormat: to.Ptr(azopenai.AudioTranscriptionFormatText),

		DeploymentName: &modelDeploymentID,
	}, nil)

	if err != nil {
		// TODO: Update the following line with your application specific error handling logic
		log.Printf("ERROR: %s", err)
		return
	}

	fmt.Fprintf(os.Stderr, "Transcribed text: %s\n", *resp.Text)

}

Sohbet

Client.GetChatTamamlamaları

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
)

func main() {
	azureOpenAIKey := os.Getenv("AOAI_CHAT_COMPLETIONS_API_KEY")
	modelDeploymentID := os.Getenv("AOAI_CHAT_COMPLETIONS_MODEL")

	// Ex: "https://<your-azure-openai-host>.openai.azure.com"
	azureOpenAIEndpoint := os.Getenv("AOAI_CHAT_COMPLETIONS_ENDPOINT")

	if azureOpenAIKey == "" || modelDeploymentID == "" || azureOpenAIEndpoint == "" {
		fmt.Fprintf(os.Stderr, "Skipping example, environment variables missing\n")
		return
	}

	keyCredential := azcore.NewKeyCredential(azureOpenAIKey)

	// In Azure OpenAI you must deploy a model before you can use it in your client. For more information
	// see here: https://learn.microsoft.com/azure/cognitive-services/openai/how-to/create-resource
	client, err := azopenai.NewClientWithKeyCredential(azureOpenAIEndpoint, keyCredential, nil)

	if err != nil {
		// TODO: Update the following line with your application specific error handling logic
		log.Printf("ERROR: %s", err)
		return
	}

	// This is a conversation in progress.
	// NOTE: all messages, regardless of role, count against token usage for this API.
	messages := []azopenai.ChatRequestMessageClassification{
		// You set the tone and rules of the conversation with a prompt as the system role.
		&azopenai.ChatRequestSystemMessage{Content: azopenai.NewChatRequestSystemMessageContent("You are a helpful assistant. You will talk like a pirate.")},

		// The user asks a question
		&azopenai.ChatRequestUserMessage{Content: azopenai.NewChatRequestUserMessageContent("Can you help me?")},

		// The reply would come back from the ChatGPT. You'd add it to the conversation so we can maintain context.
		&azopenai.ChatRequestAssistantMessage{Content: azopenai.NewChatRequestAssistantMessageContent("Arrrr! Of course, me hearty! What can I do for ye?")},

		// The user answers the question based on the latest reply.
		&azopenai.ChatRequestUserMessage{Content: azopenai.NewChatRequestUserMessageContent("What's the best way to train a parrot?")},

		// from here you'd keep iterating, sending responses back from ChatGPT
	}

	gotReply := false

	resp, err := client.GetChatCompletions(context.TODO(), azopenai.ChatCompletionsOptions{
		// This is a conversation in progress.
		// NOTE: all messages count against token usage for this API.
		Messages:       messages,
		DeploymentName: &modelDeploymentID,
	}, nil)

	if err != nil {
		// TODO: Update the following line with your application specific error handling logic
		log.Printf("ERROR: %s", err)
		return
	}

	for _, choice := range resp.Choices {
		gotReply = true

		if choice.ContentFilterResults != nil {
			fmt.Fprintf(os.Stderr, "Content filter results\n")

			if choice.ContentFilterResults.Error != nil {
				fmt.Fprintf(os.Stderr, "  Error:%v\n", choice.ContentFilterResults.Error)
			}

			fmt.Fprintf(os.Stderr, "  Hate: sev: %v, filtered: %v\n", *choice.ContentFilterResults.Hate.Severity, *choice.ContentFilterResults.Hate.Filtered)
			fmt.Fprintf(os.Stderr, "  SelfHarm: sev: %v, filtered: %v\n", *choice.ContentFilterResults.SelfHarm.Severity, *choice.ContentFilterResults.SelfHarm.Filtered)
			fmt.Fprintf(os.Stderr, "  Sexual: sev: %v, filtered: %v\n", *choice.ContentFilterResults.Sexual.Severity, *choice.ContentFilterResults.Sexual.Filtered)
			fmt.Fprintf(os.Stderr, "  Violence: sev: %v, filtered: %v\n", *choice.ContentFilterResults.Violence.Severity, *choice.ContentFilterResults.Violence.Filtered)
		}

		if choice.Message != nil && choice.Message.Content != nil {
			fmt.Fprintf(os.Stderr, "Content[%d]: %s\n", *choice.Index, *choice.Message.Content)
		}

		if choice.FinishReason != nil {
			// this choice's conversation is complete.
			fmt.Fprintf(os.Stderr, "Finish reason[%d]: %s\n", *choice.Index, *choice.FinishReason)
		}
	}

	if gotReply {
		fmt.Fprintf(os.Stderr, "Got chat completions reply\n")
	}

}

Client.GetChatCompletionsStream

package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
)

func main() {
	azureOpenAIKey := os.Getenv("AOAI_CHAT_COMPLETIONS_API_KEY")
	modelDeploymentID := os.Getenv("AOAI_CHAT_COMPLETIONS_MODEL")

	// Ex: "https://<your-azure-openai-host>.openai.azure.com"
	azureOpenAIEndpoint := os.Getenv("AOAI_CHAT_COMPLETIONS_ENDPOINT")

	if azureOpenAIKey == "" || modelDeploymentID == "" || azureOpenAIEndpoint == "" {
		fmt.Fprintf(os.Stderr, "Skipping example, environment variables missing\n")
		return
	}

	keyCredential := azcore.NewKeyCredential(azureOpenAIKey)

	// In Azure OpenAI you must deploy a model before you can use it in your client. For more information
	// see here: https://learn.microsoft.com/azure/cognitive-services/openai/how-to/create-resource
	client, err := azopenai.NewClientWithKeyCredential(azureOpenAIEndpoint, keyCredential, nil)

	if err != nil {
		// TODO: Update the following line with your application specific error handling logic
		log.Printf("ERROR: %s", err)
		return
	}

	// This is a conversation in progress.
	// NOTE: all messages, regardless of role, count against token usage for this API.
	messages := []azopenai.ChatRequestMessageClassification{
		// You set the tone and rules of the conversation with a prompt as the system role.
		&azopenai.ChatRequestSystemMessage{Content: azopenai.NewChatRequestSystemMessageContent("You are a helpful assistant. You will talk like a pirate and limit your responses to 20 words or less.")},

		// The user asks a question
		&azopenai.ChatRequestUserMessage{Content: azopenai.NewChatRequestUserMessageContent("Can you help me?")},

		// The reply would come back from the ChatGPT. You'd add it to the conversation so we can maintain context.
		&azopenai.ChatRequestAssistantMessage{Content: azopenai.NewChatRequestAssistantMessageContent("Arrrr! Of course, me hearty! What can I do for ye?")},

		// The user answers the question based on the latest reply.
		&azopenai.ChatRequestUserMessage{Content: azopenai.NewChatRequestUserMessageContent("What's the best way to train a parrot?")},

		// from here you'd keep iterating, sending responses back from ChatGPT
	}

	resp, err := client.GetChatCompletionsStream(context.TODO(), azopenai.ChatCompletionsStreamOptions{
		// This is a conversation in progress.
		// NOTE: all messages count against token usage for this API.
		Messages:       messages,
		N:              to.Ptr[int32](1),
		DeploymentName: &modelDeploymentID,
	}, nil)

	if err != nil {
		// TODO: Update the following line with your application specific error handling logic
		log.Printf("ERROR: %s", err)
		return
	}

	defer resp.ChatCompletionsStream.Close()

	gotReply := false

	for {
		chatCompletions, err := resp.ChatCompletionsStream.Read()

		if errors.Is(err, io.EOF) {
			break
		}

		if err != nil {
			//  TODO: Update the following line with your application specific error handling logic
			log.Printf("ERROR: %s", err)
			return
		}

		for _, choice := range chatCompletions.Choices {
			gotReply = true

			text := ""

			if choice.Delta.Content != nil {
				text = *choice.Delta.Content
			}

			role := ""

			if choice.Delta.Role != nil {
				role = string(*choice.Delta.Role)
			}

			fmt.Fprintf(os.Stderr, "Content[%d], role %q: %q\n", *choice.Index, role, text)
		}
	}

	if gotReply {
		fmt.Fprintf(os.Stderr, "Got chat completions streaming reply\n")
	}

}

Eklemeler

Müşteri.GömüleriAl

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
)

func main() {
	azureOpenAIKey := os.Getenv("AOAI_EMBEDDINGS_API_KEY")
	modelDeploymentID := os.Getenv("AOAI_EMBEDDINGS_MODEL")

	// Ex: "https://<your-azure-openai-host>.openai.azure.com"
	azureOpenAIEndpoint := os.Getenv("AOAI_EMBEDDINGS_ENDPOINT")

	if azureOpenAIKey == "" || modelDeploymentID == "" || azureOpenAIEndpoint == "" {
		fmt.Fprintf(os.Stderr, "Skipping example, environment variables missing\n")
		return
	}

	keyCredential := azcore.NewKeyCredential(azureOpenAIKey)

	// In Azure OpenAI you must deploy a model before you can use it in your client. For more information
	// see here: https://learn.microsoft.com/azure/cognitive-services/openai/how-to/create-resource
	client, err := azopenai.NewClientWithKeyCredential(azureOpenAIEndpoint, keyCredential, nil)

	if err != nil {
		// TODO: Update the following line with your application specific error handling logic
		log.Printf("ERROR: %s", err)
		return
	}

	resp, err := client.GetEmbeddings(context.TODO(), azopenai.EmbeddingsOptions{
		Input:          []string{"Testing, testing, 1,2,3."},
		DeploymentName: &modelDeploymentID,
	}, nil)

	if err != nil {
		// TODO: Update the following line with your application specific error handling logic
		log.Printf("ERROR: %s", err)
		return
	}

	for _, embed := range resp.Data {
		// embed.Embedding contains the embeddings for this input index.
		fmt.Fprintf(os.Stderr, "Got embeddings for input %d\n", *embed.Index)
	}

}

Görüntü Oluşturma

Client.GetImageGenerations

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
)

func main() {
	azureOpenAIKey := os.Getenv("AOAI_DALLE_API_KEY")

	// Ex: "https://<your-azure-openai-host>.openai.azure.com"
	azureOpenAIEndpoint := os.Getenv("AOAI_DALLE_ENDPOINT")

	azureDeployment := os.Getenv("AOAI_DALLE_MODEL")

	if azureOpenAIKey == "" || azureOpenAIEndpoint == "" || azureDeployment == "" {
		fmt.Fprintf(os.Stderr, "Skipping example, environment variables missing\n")
		return
	}

	keyCredential := azcore.NewKeyCredential(azureOpenAIKey)

	client, err := azopenai.NewClientWithKeyCredential(azureOpenAIEndpoint, keyCredential, nil)

	if err != nil {
		// TODO: Update the following line with your application specific error handling logic
		log.Printf("ERROR: %s", err)
		return
	}

	resp, err := client.GetImageGenerations(context.TODO(), azopenai.ImageGenerationOptions{
		Prompt:         to.Ptr("a cat"),
		ResponseFormat: to.Ptr(azopenai.ImageGenerationResponseFormatURL),
		DeploymentName: &azureDeployment,
	}, nil)

	if err != nil {
		// TODO: Update the following line with your application specific error handling logic
		log.Printf("ERROR: %s", err)
		return
	}

	for _, generatedImage := range resp.Data {
		// the underlying type for the generatedImage is dictated by the value of
		// ImageGenerationOptions.ResponseFormat. In this example we used `azopenai.ImageGenerationResponseFormatURL`,
		// so the underlying type will be ImageLocation.

		resp, err := http.Head(*generatedImage.URL)

		if err != nil {
			// TODO: Update the following line with your application specific error handling logic
			log.Printf("ERROR: %s", err)
			return
		}

		_ = resp.Body.Close()
		fmt.Fprintf(os.Stderr, "Image generated, HEAD request on URL returned %d\n", resp.StatusCode)
	}

}

Tamamlamalar (eski)

Client.GetChatTamamlamaları

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
)

func main() {
	azureOpenAIKey := os.Getenv("AOAI_COMPLETIONS_API_KEY")
	modelDeployment := os.Getenv("AOAI_COMPLETIONS_MODEL")

	// Ex: "https://<your-azure-openai-host>.openai.azure.com"
	azureOpenAIEndpoint := os.Getenv("AOAI_COMPLETIONS_ENDPOINT")

	if azureOpenAIKey == "" || modelDeployment == "" || azureOpenAIEndpoint == "" {
		fmt.Fprintf(os.Stderr, "Skipping example, environment variables missing\n")
		return
	}

	keyCredential := azcore.NewKeyCredential(azureOpenAIKey)

	// In Azure OpenAI you must deploy a model before you can use it in your client. For more information
	// see here: https://learn.microsoft.com/azure/cognitive-services/openai/how-to/create-resource
	client, err := azopenai.NewClientWithKeyCredential(azureOpenAIEndpoint, keyCredential, nil)

	if err != nil {
		// TODO: Update the following line with your application specific error handling logic
		log.Printf("ERROR: %s", err)
		return
	}

	resp, err := client.GetCompletions(context.TODO(), azopenai.CompletionsOptions{
		Prompt:         []string{"What is Azure OpenAI, in 20 words or less"},
		MaxTokens:      to.Ptr(int32(2048)),
		Temperature:    to.Ptr(float32(0.0)),
		DeploymentName: &modelDeployment,
	}, nil)

	if err != nil {
		// TODO: Update the following line with your application specific error handling logic
		log.Printf("ERROR: %s", err)
		return
	}

	for _, choice := range resp.Choices {
		fmt.Fprintf(os.Stderr, "Result: %s\n", *choice.Text)
	}

}

Hata yönetimi

HTTP istekleri gönderen tüm yöntemler, bu istekler başarısız olduğunda geri döner *azcore.ResponseError . ResponseError hata ayrıntılarına ve hizmetten gelen ham yanıta sahiptir.

Ağaç kesimi

Bu modülde azcore'un kullandığı günlüğe kaydetme uygulaması kullanılır. Tüm Azure SDK modülleri için loglamayı etkinleştirmek için AZURE_SDK_GO_LOGGING'u all olarak ayarlayın. Günlükçü varsayılan olarak stderr'a yazar. Günlük çıkışını denetlemek için azcore/log paketini kullanın. Örneğin, yalnızca HTTP isteği ve yanıt olaylarını günlüğe kaydetme ve bunları stdout'a yazdırma:

import azlog "github.com/Azure/azure-sdk-for-go/sdk/azcore/log"

// Print log events to stdout
azlog.SetListener(func(cls azlog.Event, msg string) {
	fmt.Println(msg)
})

// Includes only requests and responses in credential logs
azlog.SetEvents(azlog.EventRequest, azlog.EventResponse)

Kaynak kodu | Yapı (Maven) | API başvuru belgeleri | Paket başvuru belgeleriÖrnekler

Azure OpenAI API sürüm desteği

Python ve JavaScript için Azure OpenAI istemci kitaplıklarından farklı olarak, uyumluluğu sağlamak için Azure OpenAI Java paketinin Azure OpenAI API sürümlerinin belirli bir alt kümesini hedeflemeyle sınırlı olduğundan emin olun. Genel olarak her Azure OpenAI Java paketi, daha yeni Azure OpenAI API yayın özelliklerine erişimin kilidini açar. En son API sürümlerine erişim sahibi olmak özellik kullanılabilirliğini etkiler.

Sürüm seçimi OpenAIServiceVersion numaralandırması tarafından kontrol edilmektedir.

Desteklenen en son Azure OpenAI önizleme API'si:

-2025-01-01-preview

Desteklenen en son kararlı (GA) sürüm:

-2024-06-01

Kurulum

Paket ayrıntıları

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-ai-openai</artifactId>
    <version>1.0.0-beta.16</version>
</dependency>

Kimlik doğrulama

Azure AI Foundry Modellerinde Azure OpenAI ile etkileşim kurmak için istemci sınıfının OpenAIAsyncClient bir örneğini veya OpenAIClient kullanarak OpenAIClientBuilderoluşturmanız gerekir. Bir istemciyi Azure OpenAI ile kullanmak üzere yapılandırmak için Azure OpenAI kaynağına geçerli bir uç nokta URI'si ve azure OpenAI kaynağını kullanma yetkisi olan ilgili anahtar kimlik bilgileri, belirteç kimlik bilgileri veya Azure Kimlik bilgileri sağlayın.

Microsoft Entra Id ile kimlik doğrulaması için bazı ilk kurulumlar gerekir:

Azure Kimlik paketini ekleyin:

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-identity</artifactId>
    <version>1.13.3</version>
</dependency>

Kurulumdan sonra, hangi kimlik bilgisi azure.identity türünü kullanacağınızı seçebilirsiniz. Örneğin, DefaultAzureCredential istemcinin kimliğini doğrulamak için kullanılabilir: Microsoft Entra ID uygulamasının istemci kimliği, kiracı kimliği ve istemci gizli dizisi değerlerini ortam değişkenleri olarak ayarlayın: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET.

Yetkilendirme en kolayı DefaultAzureCredential kullanmaktır. Çalışma ortamında kullanılacak en iyi kimlik bilgilerini bulur.

TokenCredential defaultCredential = new DefaultAzureCredentialBuilder().build();
OpenAIClient client = new OpenAIClientBuilder()
    .credential(defaultCredential)
    .endpoint("{endpoint}")
    .buildClient();

Azure OpenAI anahtarsız kimlik doğrulaması hakkında daha fazla bilgi için bkz. Anahtar Kullanılmadan Azure OpenAI Kullanma.

Ses

client.getAudioTranscription

String fileName = "{your-file-name}";
Path filePath = Paths.get("{your-file-path}" + fileName);

byte[] file = BinaryData.fromFile(filePath).toBytes();
AudioTranscriptionOptions transcriptionOptions = new AudioTranscriptionOptions(file)
    .setResponseFormat(AudioTranscriptionFormat.JSON);

AudioTranscription transcription = client.getAudioTranscription("{deploymentOrModelName}", fileName, transcriptionOptions);

System.out.println("Transcription: " + transcription.getText());

client.metinKutlemesindenKonusmaÜret

Metin okuma (TTS)

String deploymentOrModelId = "{azure-open-ai-deployment-model-id}";
SpeechGenerationOptions options = new SpeechGenerationOptions(
        "Today is a wonderful day to build something people love!",
        SpeechVoice.ALLOY);
BinaryData speech = client.generateSpeechFromText(deploymentOrModelId, options);
// Checkout your generated speech in the file system.
Path path = Paths.get("{your-local-file-path}/speech.wav");
Files.write(path, speech.toBytes());

Sohbet

client.getChatCompletions

List<ChatRequestMessage> chatMessages = new ArrayList<>();
chatMessages.add(new ChatRequestSystemMessage("You are a helpful assistant. You will talk like a pirate."));
chatMessages.add(new ChatRequestUserMessage("Can you help me?"));
chatMessages.add(new ChatRequestAssistantMessage("Of course, me hearty! What can I do for ye?"));
chatMessages.add(new ChatRequestUserMessage("What's the best way to train a parrot?"));

ChatCompletions chatCompletions = client.getChatCompletions("{deploymentOrModelName}",
    new ChatCompletionsOptions(chatMessages));

System.out.printf("Model ID=%s is created at %s.%n", chatCompletions.getId(), chatCompletions.getCreatedAt());
for (ChatChoice choice : chatCompletions.getChoices()) {
    ChatResponseMessage message = choice.getMessage();
    System.out.printf("Index: %d, Chat Role: %s.%n", choice.getIndex(), message.getRole());
    System.out.println("Message:");
    System.out.println(message.getContent());
}

Yayın

List<ChatRequestMessage> chatMessages = new ArrayList<>();
chatMessages.add(new ChatRequestSystemMessage("You are a helpful assistant. You will talk like a pirate."));
chatMessages.add(new ChatRequestUserMessage("Can you help me?"));
chatMessages.add(new ChatRequestAssistantMessage("Of course, me hearty! What can I do for ye?"));
chatMessages.add(new ChatRequestUserMessage("What's the best way to train a parrot?"));

ChatCompletions chatCompletions = client.getChatCompletions("{deploymentOrModelName}",
    new ChatCompletionsOptions(chatMessages));

System.out.printf("Model ID=%s is created at %s.%n", chatCompletions.getId(), chatCompletions.getCreatedAt());
for (ChatChoice choice : chatCompletions.getChoices()) {
    ChatResponseMessage message = choice.getMessage();
    System.out.printf("Index: %d, Chat Role: %s.%n", choice.getIndex(), message.getRole());
    System.out.println("Message:");
    System.out.println(message.getContent());
}

Resimlerle sohbet tamamlamaları

List<ChatRequestMessage> chatMessages = new ArrayList<>();
chatMessages.add(new ChatRequestSystemMessage("You are a helpful assistant that describes images"));
chatMessages.add(new ChatRequestUserMessage(Arrays.asList(
        new ChatMessageTextContentItem("Please describe this image"),
        new ChatMessageImageContentItem(
                new ChatMessageImageUrl("https://raw.githubusercontent.com/MicrosoftDocs/azure-ai-docs/main/articles/ai-services/openai/media/how-to/generated-seattle.png"))
)));

ChatCompletionsOptions chatCompletionsOptions = new ChatCompletionsOptions(chatMessages);
ChatCompletions chatCompletions = client.getChatCompletions("{deploymentOrModelName}", chatCompletionsOptions);

System.out.println("Chat completion: " + chatCompletions.getChoices().get(0).getMessage().getContent());

Eklemeler

client.getEmbeddings

EmbeddingsOptions embeddingsOptions = new EmbeddingsOptions(
    Arrays.asList("Your text string goes here"));

Embeddings embeddings = client.getEmbeddings("{deploymentOrModelName}", embeddingsOptions);

for (EmbeddingItem item : embeddings.getData()) {
    System.out.printf("Index: %d.%n", item.getPromptIndex());
    for (Float embedding : item.getEmbedding()) {
        System.out.printf("%f;", embedding);
    }
}

Görüntü oluşturma

ImageGenerationOptions imageGenerationOptions = new ImageGenerationOptions(
    "A drawing of the Seattle skyline in the style of Van Gogh");
ImageGenerations images = client.getImageGenerations("{deploymentOrModelName}", imageGenerationOptions);

for (ImageGenerationData imageGenerationData : images.getData()) {
    System.out.printf(
        "Image location URL that provides temporary access to download the generated image is %s.%n",
        imageGenerationData.getUrl());
}

Hataları işleme

İstemci günlüğünü etkinleştirme

Azure OpenAI kitaplığıyla ilgili sorunları giderirken, öncelikle uygulamanın davranışını izlemek amacıyla günlüğe kaydetmeyi etkinleştirmek önemlidir. Günlüklerdeki hatalar ve uyarılar genellikle neyin yanlış gittiğine ilişkin yararlı içgörüler sağlar ve bazen sorunları düzeltmek için düzeltici eylemler içerir. Java için Azure istemci kitaplıklarının iki kayıt tutma seçeneği vardır.

  • Yerleşik günlük çerçevesi.
  • SLF4J arabirimi kullanılarak günlüğe kaydetme desteği.

Bu başvuru belgesindeki [Java için Azure SDK'da günlüğe kaydetmeyi yapılandırma][logging_overview] yönergelerine bakın.

HTTP isteği/yanıt günlüğünü etkinleştirme

Azure OpenAI ile, kablo üzerinden gönderilen HTTP isteğinin veya alınan yanıtın gözden geçirilmesi sorunları gidermede yararlı olabilir. HTTP isteğinin ve yanıt yükünün günlüğe kaydedilmesini etkinleştirmek için [OpenAIClient][openai_client] aşağıda gösterildiği gibi yapılandırılabilir. Sınıf yolunda SLF4J Logger yoksa, günlüğe kaydetmeyi etkinleştirmek için bilgisayarınızda [AZURE_LOG_LEVEL][azure_log_level] ortam değişkenini tanımlayın.

OpenAIClient openAIClient = new OpenAIClientBuilder()
        .endpoint("{endpoint}")
        .credential(new AzureKeyCredential("{key}"))
        .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
        .buildClient();
// or
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
OpenAIClient configurationClientAad = new OpenAIClientBuilder()
        .credential(credential)
        .endpoint("{endpoint}")
        .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
        .buildClient();

Alternatif olarak, aşağıdaki ortam değişkenini ayarlayarak uygulamanızın tamamı için http isteklerinin ve yanıtlarının günlüğe kaydedilmesini yapılandırabilirsiniz. Bu değişikliğin, HTTP isteğinin/yanıtının günlüğe kaydedilmesini destekleyen her Azure istemcisi için günlüğe kaydetmeyi etkinleştireceğini unutmayın.

Ortam değişkeni adı: AZURE_HTTP_LOG_DETAIL_LEVEL

Değer Kayıt seviyesi
yok HTTP isteği/yanıt günlüğü devre dışı bırakıldı
temel Yalnızca URL'leri, HTTP yöntemlerini ve isteği tamamlama süresini günlüğe kaydeder.
Başlıklar BASIC'te kaydedilen her şeye ek olarak, tüm istek ve yanıt başlıklarını da günlüğe kaydeder.
vücut BASIC'teki her şeyin yanı sıra tüm istek ve yanıt gövdesini günlüğe kaydeder.
Gövde ve Başlıklar Başlıklar ve içerik içindeki her şeyi günlüğe kaydeder.

Uyarı

İstek ve yanıt gövdesini günlüğe kaydederek gizli bilgiler içermediklerinden emin olun. Üst bilgileri günlüğe kaydederken, istemci kitaplığı, günlüğe kaydedilmesinin güvenli olduğu kabul edilen varsayılan bir üst bilgi kümesine sahiptir; ancak bu küme, oluşturucudaki günlük seçenekleri aşağıda gösterildiği gibi güncellenerek değiştirilebilir.

clientBuilder.httpLogOptions(new HttpLogOptions().addAllowedHeaderName("safe-to-log-header-name"))

Özel durumlarla ilgili sorunları giderme

Azure OpenAI yöntemleri başarısızlık durumunda bir[HttpResponseException veya alt sınıfını fırlatır. OpenAI istemci kitaplığı tarafından atılan HttpResponseException ayrıntılı yanıt hata nesnesi, neyin yanlış gittiğine dair kesin ve yararlı içgörüler sunar ve yaygın sorunları düzeltmek için düzeltici eylemler içerir. Bu hata bilgileri, nesnenin ileti özelliğinin HttpResponseException içinde bulunabilir.

Zaman uyumlu istemciyle yakalama örneği aşağıda verilmiştir

List<ChatRequestMessage> chatMessages = new ArrayList<>();
chatMessages.add(new ChatRequestSystemMessage("You are a helpful assistant. You will talk like a pirate."));
chatMessages.add(new ChatRequestUserMessage("Can you help me?"));
chatMessages.add(new ChatRequestAssistantMessage("Of course, me hearty! What can I do for ye?"));
chatMessages.add(new ChatRequestUserMessage("What's the best way to train a parrot?"));

try {
    ChatCompletions chatCompletions = client.getChatCompletions("{deploymentOrModelName}",
            new ChatCompletionsOptions(chatMessages));
} catch (HttpResponseException e) {
    System.out.println(e.getMessage());
    // Do something with the exception
}

Zaman uyumsuz istemcilerle, hata geri çağırmalarında özel durumları yakalayabilir ve işleyebilirsiniz:

asyncClient.getChatCompletions("{deploymentOrModelName}", new ChatCompletionsOptions(chatMessages))
        .doOnSuccess(ignored -> System.out.println("Success!"))
        .doOnError(
                error -> error instanceof ResourceNotFoundException,
                error -> System.out.println("Exception: 'getChatCompletions' could not be performed."));

Kimlik doğrulama hataları

Azure OpenAI, Microsoft Entra Id kimlik doğrulamayı destekler. OpenAIClientBuilder'ün, credential ayarlamak için bir yöntemi vardır. Geçerli bir kimlik bilgisi sağlamak için bağımlılığı kullanabilirsiniz azure-identity .

Kaynak kodu | Paket (npm) | Referans |

Azure OpenAI API sürüm desteği

Azure OpenAI'de özellik kullanılabilirliği, hedeflediğiniz REST API sürümüne bağlıdır. En yeni özellikler için en son önizleme API'sini hedefleyin.

En son GA API'si En Son Önizleme API'si
2024-10-21 2025-03-01-preview

Kurulum

npm install openai

Kimlik doğrulama

Microsoft Entra ID belirteçlerini kullanarak Azure OpenAI ile kimlik doğrulaması yapmanın çeşitli yolları vardır. Varsayılan yöntem, DefaultAzureCredential paketinden @azure/identity sınıfını kullanmaktır.

import { DefaultAzureCredential } from "@azure/identity";
const credential = new DefaultAzureCredential();

Bu nesne, AzureClientOptions nesnesinin bir parçası olarak AzureOpenAI ve AssistantsClient istemci oluşturucularına geçirilir.

Ancak istemcinin AzureOpenAI kimliğini doğrulamak için getBearerTokenProvider paketinden @azure/identity işlevini kullanmamız gerekir. Bu işlev, her istek için belirteçleri dahili olarak almak üzere AzureOpenAI kullanan bir belirteç sağlayıcısı oluşturur. Belirteç sağlayıcısı aşağıdaki gibi oluşturulur:

import { AzureOpenAI } from 'openai';
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
const credential = new DefaultAzureCredential();
const endpoint = "https://your-azure-openai-resource.com";
const apiVersion = "2024-10-21"
const scope = "https://cognitiveservices.azure.com/.default";
const azureADTokenProvider = getBearerTokenProvider(credential, scope);
const deployment = "gpt-35-turbo";

const client = new AzureOpenAI({ 
    endpoint, 
    apiVersion,
    deployment,
    azureADTokenProvider
});

Azure OpenAI anahtarsız kimlik doğrulaması hakkında daha fazla bilgi için "Azure OpenAI güvenlik yapı taşını kullanmaya başlama" Hızlı Başlangıç makalesine bakın.

Konfigürasyon

AzureClientOptions nesnesi OpenAI ClientOptions nesnesini genişletir. Bu Azure'a özgü istemci nesnesi, Azure OpenAI istemcisinin bağlantısını ve davranışını yapılandırmak için kullanılır. Azure'a özgü özellikleri belirtmek için özellikler içerir.

Mülkiyet Ayrıntılar
apiVersion: string Kullanılacak API sürümünü belirtir.
azureADTokenProvider: (() => Promise<string>) Her istekte çağrılan Microsoft Entra (eski adıyla Azure Active Directory) için erişim belirteci döndüren bir işlev.
Dağıtım: string Model konuşlandırma. Sağlandığında, /deployments/{deployment}'ü içerecek şekilde temel istemci URL'sini ayarlar. Dağıtım dışı uç noktalar kullanılamaz (Yardımcılar API'leri ile desteklenmez).
bitiş noktası: string Azure OpenAI uç noktanız şu biçimdedir: https://RESOURCE-NAME.azure.openai.com/.

Ses

Transkripsiyon

import { createReadStream } from "fs";

const result = await client.audio.transcriptions.create({
  model: '',
  file: createReadStream(audioFilePath),
});

Sohbet

chat.completions.create

const result = await client.chat.completions.create({ messages, model: '', max_tokens: 100 });

Yayın

const stream = await client.chat.completions.create({ model: '', messages, max_tokens: 100, stream: true });

Eklemeler

const embeddings = await client.embeddings.create({ input, model: '' });

Görüntü oluşturma

  const results = await client.images.generate({ prompt, model: '', n, size });

Hata yönetimi

Hata kodları

Durum Kodu Hata Türü
400 Bad Request Error
401 Authentication Error
403 Permission Denied Error
404 Not Found Error
422 Unprocessable Entity Error
429 Rate Limit Error
beş yüz Internal Server Error
503 Service Unavailable
504 Gateway Timeout

Yeniden denemeler

Aşağıdaki hatalar, kısa bir üstel geri çekilme ile varsayılan olarak iki kez otomatik olarak devreden çıkarılır.

  • Bağlantı Hataları
  • 408 İstek Zaman Aşımı
  • 429 Hız Sınırı
  • >=500 İç Hata

Yeniden deneme davranışını ayarlamak/devre dışı bırakmak için kullanın maxRetries :

// Configure the default for all requests:
const client = new AzureOpenAI({
  maxRetries: 0, // default is 2
});

// Or, configure per-request:
await client.chat.completions.create({ messages: [{ role: 'user', content: 'How can I get the name of the current day in Node.js?' }], model: '' }, {
  maxRetries: 5,
});

Kitaplık kaynak kodu | PyPi Paketi | Referans |

Uyarı

Bu kitaplık OpenAI tarafından korunur. Kitaplığın en son güncelleştirmelerini izlemek için sürüm geçmişine bakın.

Azure OpenAI API sürüm desteği

Azure OpenAI'de özellik kullanılabilirliği, hedeflediğiniz REST API sürümüne bağlıdır. En yeni özellikler için en son önizleme API'sini hedefleyin.

En son GA API'si En Son Önizleme API'si
2024-10-21 2025-03-01-preview

Kurulum

pip install openai

En son sürüm için:

pip install openai --upgrade

Kimlik doğrulama

import os
from openai import AzureOpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider

token_provider = get_bearer_token_provider(
    DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
)

client = AzureOpenAI(
  azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"), 
  azure_ad_token_provider=token_provider,
  api_version="2024-10-21"
)

Azure OpenAI anahtarsız kimlik doğrulaması hakkında daha fazla bilgi için "Azure OpenAI güvenlik yapı taşını kullanmaya başlama" Hızlı Başlangıç makalesine bakın.

Ses

ses.konuşma.oluştur()

Bu işlev şu anda bir önizleme API sürümü gerektirir.

api_version="2024-10-01-preview" işlevini kullanmak için ayarlayın.

# from openai import AzureOpenAI
# client = AzureOpenAI()

from pathlib import Path
import os

speech_file_path = Path("speech.mp3")

response = client.audio.speech.create(
  model="tts-hd", #Replace with model deployment name
  voice="alloy",
  input="Testing, testing, 1,2,3."
)
response.write_to_file(speech_file_path)

ses.transkripsiyonları.oluştur()

# from openai import AzureOpenAI
# client = AzureOpenAI()

audio_file = open("speech1.mp3", "rb")
transcript = client.audio.transcriptions.create(
  model="whisper", # Replace with model deployment name
  file=audio_file
)

print(transcript)

Sohbet

chat.tamamlamalar.oluştur()

# from openai import AzureOpenAI
# client = AzureOpenAI()

completion = client.chat.completions.create(
  model="gpt-4o", # Replace with your model dpeloyment name.
  messages=[
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "When was Microsoft founded?"}
  ]
)

#print(completion.choices[0].message)
print(completion.model_dump_json(indent=2)

chat.completions.create() - akış

# from openai import AzureOpenAI
# client = AzureOpenAI()

completion = client.chat.completions.create(
  model="gpt-4o", # Replace with your model dpeloyment name.
  messages=[
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "When was Microsoft founded?"}
  ],
  stream=True
)

for chunk in completion:
    if chunk.choices and chunk.choices[0].delta.content is not None:
        print(chunk.choices[0].delta.content, end='',)

chat.completions.create() - resim girişi

completion = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "What's in this image?"},
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://raw.githubusercontent.com/MicrosoftDocs/azure-ai-docs/main/articles/ai-services/openai/media/how-to/generated-seattle.png",
                    }
                },
            ],
        }
    ],
    max_tokens=300,
)

print(completion.model_dump_json(indent=2))

Eklemeler

embeddings.create()

# from openai import AzureOpenAI
# client = AzureOpenAI()

embedding = client.embeddings.create(
  model="text-embedding-3-large", # Replace with your model deployment name
  input="Attenion is all you need",
  encoding_format="float" 
)

print(embedding)

Hassas ayarlama

Python ile ince ayarlama nasıl yapılır makalesi

Toplu işlem

Python ile Batch nasıl yapılır makalesi

Resimler

görselleri.oluştur()

# from openai import AzureOpenAI
# client = AzureOpenAI()

generate_image = client.images.generate(
  model="dall-e-3", #replace with your model deployment name
  prompt="A rabbit eating pancakes",
  n=1,
  size="1024x1024",
  quality = "hd",
  response_format = "url",
  style = "vivid"
)

print(generate_image.model_dump_json(indent=2))

Yanıtlar API'si

Yanıtlar API'sinin belgelerine bakın.

Tamamlamalar (eski)

Tamamlama.oluştur()

# from openai import AzureOpenAI
# client = AzureOpenAI()

legacy_completion = client.completions.create(
  model="gpt-35-turbo-instruct", # Replace with model deployment name
  prompt="Hello World!",
  max_tokens=100,
  temperature=0
)

print(legacy_completion.model_dump_json(indent=2))

Hata yönetimi

# from openai import AzureOpenAI
# client = AzureOpenAI()

import openai

try:
    client.fine_tuning.jobs.create(
        model="gpt-4o",
        training_file="file-test",
    )
except openai.APIConnectionError as e:
    print("The server could not be reached")
    print(e.__cause__)  # an underlying Exception, likely raised within httpx.
except openai.RateLimitError as e:
    print("A 429 status code was received; we should back off a bit.")
except openai.APIStatusError as e:
    print("Another non-200-range status code was received")
    print(e.status_code)
    print(e.response)

Hata kodları

Durum Kodu Hata Türü
400 BadRequestError
401 AuthenticationError
403 PermissionDeniedError
404 NotFoundError
422 UnprocessableEntityError
429 RateLimitError
> = 500 InternalServerError
Geçerli Değil APIConnectionError

kimlik isteme

İsteğinizin kimliğini almak için yanıt üst bilgisine _request_idx-request-id karşılık gelen özelliğini kullanabilirsiniz.

print(completion._request_id) 
print(legacy_completion._request_id)

Yeniden denemeler

Aşağıdaki hatalar, kısa bir üstel geri çekilme ile varsayılan olarak iki kez otomatik olarak devreden çıkarılır.

  • Bağlantı Hataları
  • 408 İstek Zaman Aşımı
  • 429 Hız Sınırı
  • >=500 İç Hata

Yeniden deneme davranışını ayarlamak/devre dışı bırakmak için kullanın max_retries :

# For all requests

from openai import AzureOpenAI
client = AzureOpenAI(
      max_retries=0
)
# max retires for specific requests

client.with_options(max_retries=5).chat.completions.create(
    messages=[
        {
            "role": "user",
            "content": "When was Microsoft founded?",
        }
    ],
    model="gpt-4o",
)

Sonraki Adımlar

  • Şu anda hangi modellerin desteklendiğine bakmak için Azure OpenAI modelleri sayfasına göz atın