Obsługiwane języki programowania w usłudze Azure OpenAI
Artykuł
Biblioteka klienta platformy Azure OpenAI dla platformy .NET jest towarzyszem oficjalnej biblioteki klienta openAI dla platformy .NET. Biblioteka Azure OpenAI konfiguruje klienta do użycia z usługą Azure OpenAI i zapewnia bardzo silnie typizowaną obsługę rozszerzeń dla modeli żądań i odpowiedzi specyficznych dla scenariuszy usługi Azure OpenAI.
W przeciwieństwie do bibliotek klienckich platformy Azure OpenAI dla języków Python i JavaScript pakiet platformy .NET usługi Azure OpenAI jest ograniczony do określania określonego podzestawu wersji interfejsu API usługi Azure OpenAI. Ogólnie każdy pakiet platformy .NET platformy Azure OpenAI odblokowuje dostęp do nowszych funkcji interfejsu API openAI platformy Azure. Dostęp do najnowszych wersji interfejsu API ma wpływ na dostępność funkcji.
Bezpieczne, bezkluczane podejście do uwierzytelniania polega na użyciu identyfikatora Entra firmy Microsoft (dawniej Azure Active Directory) za pośrednictwem biblioteki tożsamości platformy Azure. Aby użyć biblioteki:
AzureOpenAIClient azureClient = new(
new Uri("https://your-azure-openai-resource.com"),
new DefaultAzureCredential());
ChatClient chatClient = azureClient.GetChatClient("my-gpt-4o-mini-deployment");
Aby uzyskać więcej informacji na temat uwierzytelniania bez klucza usługi Azure OpenAI, zobacz artykuł Szybki start "Rozpoczynanie pracy z blokiem konstrukcyjnym zabezpieczeń usługi Azure OpenAI".
C#
string keyFromEnvironment = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY");
AzureOpenAIClient azureClient = new(
new Uri("https://your-azure-openai-resource.com"),
new ApiKeyCredential(keyFromEnvironment));
ChatClient chatClient = azureClient.GetChatClient("my-gpt-35-turbo-deployment");
using Azure.AI.OpenAI;
using Azure.Identity;
using OpenAI.Audio;
AzureOpenAIClient azureClient = new(
new Uri("https://your-azure-openai-resource.com"),
new DefaultAzureCredential());
AudioClient client = azureClient.GetAudioClient("tts-hd"); //Replace with your Azure OpenAI model deploymentstring 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);
AzureOpenAIClient azureClient = new(
new Uri("https://your-azure-openai-resource.com"),
new DefaultAzureCredential());
ChatClient chatClient = azureClient.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}");
Przesyłanie strumieniowe wiadomości czatu
Ukończenie czatu przesyłania strumieniowego CompleteChatStreaming używa metody i CompleteChatStreamingAsync , która zwraca ResultCollection<StreamingChatCompletionUpdate> wartość lub AsyncCollectionResult<StreamingChatCompletionUpdate> zamiast ClientResult<ChatCompletion>.
Te kolekcje wyników mogą być iterowane za pomocą foreach lub await foreach, a każda aktualizacja przybywa, ponieważ nowe dane są dostępne z odpowiedzi przesyłanej strumieniowo.
C#
AzureOpenAIClient azureClient = new(
new Uri("https://your-azure-openai-resource.com"),
new DefaultAzureCredential());
ChatClient chatClient = azureClient.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);
}
}
using Azure.AI.OpenAI;
using Azure.Identity;
using OpenAI.Embeddings;
AzureOpenAIClient azureClient = new(
new Uri("https://your-azure-openai-resource.com"),
new DefaultAzureCredential());
EmbeddingClient client = azureClient.GetEmbeddingClient("text-embedding-3-large"); //Replace with your model deployment namestring description = "This is a test embedding";
OpenAIEmbedding embedding = client.GenerateEmbedding(description);
ReadOnlyMemory<float> vector = embedding.ToFloats();
Console.WriteLine(string.Join(", ", vector.ToArray()));
Dostrajanie
Obecnie nieobsługiwane w pakietach platformy .NET usługi Azure OpenAI.
Batch
Obecnie nieobsługiwane w pakietach platformy .NET usługi Azure OpenAI.
W przeciwieństwie do bibliotek klienckich platformy Azure OpenAI dla języków Python i JavaScript biblioteka Azure OpenAI Go jest przeznaczona dla określonej wersji interfejsu API usługi Azure OpenAI. Dostęp do najnowszych wersji interfejsu API ma wpływ na dostępność funkcji.
Bieżąca wersja interfejsu API usługi Azure OpenAI: 2024-10-01-preview
Moduł azidentity jest używany do uwierzytelniania usługi Azure Active Directory za pomocą usługi Azure OpenAI.
Go
package main
import (
"log""github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai""github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)
funcmain() {
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
}
package main
import (
"log""github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai""github.com/Azure/azure-sdk-for-go/sdk/azcore"
)
funcmain() {
keyCredential := azcore.NewKeyCredential("<Azure-OpenAI-APIKey>")
// 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.NewClientWithKeyCredential("https://<your-azure-openai-host>.openai.azure.com", keyCredential, nil)
if err != nil {
// TODO: Update the following line with your application specific error handling logic
log.Printf("ERROR: %s", err)
return
}
_ = client
}
Audio
Client.GenerateSpeechFromText
Go
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"
)
funcmain() {
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
Go
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"
)
funcmain() {
azureOpenAIKey := os.Getenv("AOAI_WHISPER_API_KEY")
// Ex: "https://<your-azure-openai-host>.openai.azure.com"
azureOpenAIEndpoint := os.Getenv("AOAI_WHISPER_ENDPOINT")
modelDeploymentID := os.Getenv("AOAI_WHISPER_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)
}
Czat
Client.GetChatCompletions
Go
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"
)
funcmain() {
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 = trueif 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
Go
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"
)
funcmain() {
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 := falsefor {
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")
}
}
Osadzanie
Client.GetEmbeddings
Go
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"
)
funcmain() {
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)
}
}
Generowanie obrazu
Client.GetImageGenerations
Go
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"
)
funcmain() {
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)
}
}
Ukończenia (starsza wersja)
Client.GetChatCompletions
Go
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"
)
funcmain() {
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)
}
}
Obsługa błędów
Wszystkie metody wysyłające żądania HTTP zwracają *azcore.ResponseError się, gdy te żądania kończą się niepowodzeniem.
ResponseError zawiera szczegóły błędu i nieprzetworzone odpowiedzi z usługi.
Rejestrowanie
W tym module użyto implementacji rejestrowania w narzędziu azcore. Aby włączyć rejestrowanie dla wszystkich modułów zestawu Azure SDK, ustaw AZURE_SDK_GO_LOGGING na wszystkie. Domyślnie rejestrator zapisuje dane w stderr. Użyj pakietu azcore/log, aby kontrolować dane wyjściowe dziennika. Na przykład rejestrowanie tylko zdarzeń żądania HTTP i odpowiedzi oraz drukowanie ich w stdout:
Go
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)
W przeciwieństwie do bibliotek klienckich platformy Azure OpenAI dla języków Python i JavaScript, aby zapewnić zgodność pakietu Java usługi Azure OpenAI jest ograniczona do określania określonego podzestawu wersji interfejsu API usługi Azure OpenAI. Ogólnie każdy pakiet Java openAI platformy Azure odblokowuje dostęp do nowszych funkcji interfejsu API openAI platformy Azure. Dostęp do najnowszych wersji interfejsu API ma wpływ na dostępność funkcji.
Aby móc korzystać z usługi Azure OpenAI Service, musisz utworzyć wystąpienie klasy OpenAIAsyncClient klienta lub OpenAIClient za pomocą polecenia OpenAIClientBuilder. Aby skonfigurować klienta do użycia z usługą Azure OpenAI, podaj prawidłowy identyfikator URI punktu końcowego dla zasobu usługi Azure OpenAI wraz z odpowiednimi poświadczeniami klucza, poświadczeniami tokenu lub poświadczeniami tożsamości platformy Azure, które są autoryzowane do korzystania z zasobu usługi Azure OpenAI.
Po skonfigurowaniu można wybrać typ poświadczeń azure.identity do użycia. Na przykład DefaultAzureCredential można użyć do uwierzytelniania klienta: ustaw wartości identyfikatora klienta, identyfikatora dzierżawy i wpisu tajnego klienta aplikacji Microsoft Entra ID jako zmienne środowiskowe: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET.
Autoryzacja jest najłatwiejsza przy użyciu wartości DefaultAzureCredential. Znajduje najlepsze poświadczenia do użycia w swoim uruchomionym środowisku.
Java
TokenCredential defaultCredential = new DefaultAzureCredentialBuilder().build();
OpenAIClient client = new OpenAIClientBuilder()
.credential(defaultCredential)
.endpoint("{endpoint}")
.buildClient();
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());
Czat
client.getChatCompletions
Java
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());
}
Przesyłanie strumieniowe
Java
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());
}
Kończenia czatu z obrazami
Java
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());
Osadzanie
client.getEmbeddings
Java
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);
}
}
Generowanie obrazu
Java
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());
}
Obsługa błędów
Włączanie rejestrowania klientów
Aby rozwiązać problemy z biblioteką Azure OpenAI, należy najpierw włączyć rejestrowanie w celu monitorowania zachowania aplikacji. Błędy i ostrzeżenia w dziennikach zwykle zapewniają przydatne informacje o tym, co poszło nie tak, a czasami obejmują akcje naprawcze w celu rozwiązania problemów. Biblioteki klienta platformy Azure dla języka Java mają dwie opcje rejestrowania:
Wbudowana struktura rejestrowania.
Obsługa rejestrowania przy użyciu interfejsu SLF4J .
Zapoznaj się z instrukcjami w tym dokumencie referencyjnym, aby dowiedzieć się, jak [skonfigurować rejestrowanie w zestawie Azure SDK dla języka Java][logging_overview].
Włączanie rejestrowania żądań HTTP/odpowiedzi
Przeglądanie żądania HTTP wysłanego lub odpowiedzi odebranego za pośrednictwem przewodu do/z usługi Azure OpenAI może być przydatne w rozwiązywaniu problemów. Aby włączyć rejestrowanie ładunku żądania HTTP i odpowiedzi, można skonfigurować element [OpenAIClient][openai_client], jak pokazano poniżej. Jeśli na ścieżce klasy nie ma żadnego SLF4J Logger , ustaw zmienną środowiskową [AZURE_LOG_LEVEL][azure_log_level] na maszynie, aby włączyć rejestrowanie.
Java
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();
Alternatywnie można skonfigurować rejestrowanie żądań HTTP i odpowiedzi dla całej aplikacji, ustawiając następującą zmienną środowiskową. Pamiętaj, że ta zmiana spowoduje włączenie rejestrowania dla każdego klienta platformy Azure, który obsługuje rejestrowanie żądań/odpowiedzi HTTP.
Nazwa zmiennej środowiskowej: AZURE_HTTP_LOG_DETAIL_LEVEL
Wartość
Poziom rejestrowania
Brak
Rejestrowanie żądań HTTP/odpowiedzi jest wyłączone
podstawowy
Rejestruje tylko adresy URL, metody HTTP i czas zakończenia żądania.
nagłówki
Rejestruje wszystkie elementy w warstwie PODSTAWOWA oraz wszystkie nagłówki żądań i odpowiedzi.
treść
Rejestruje wszystko w warstwie PODSTAWOWA oraz całą treść żądania i odpowiedzi.
body_and_headers
Rejestruje wszystko w nagłówkach i treści.
Uwaga
Podczas rejestrowania treści żądania i odpowiedzi upewnij się, że nie zawierają informacji poufnych. Podczas rejestrowania nagłówków biblioteka klienta ma domyślny zestaw nagłówków, które są uważane za bezpieczne do rejestrowania, ale ten zestaw można zaktualizować, aktualizując opcje dziennika w konstruktorze, jak pokazano poniżej.
Metody usługi Azure OpenAI zgłaszają błąd[HttpResponseException lub jej podklasę.
Biblioteka HttpResponseException klienta OpenAI zgłaszana przez bibliotekę klienta programu OpenAI zawiera szczegółowy obiekt błędu odpowiedzi, który zapewnia szczegółowe informacje o tym, co poszło nie tak, i zawiera akcje naprawcze w celu rozwiązania typowych problemów.
Te informacje o błędzie można znaleźć wewnątrz właściwości komunikatu HttpResponseException obiektu.
Oto przykład sposobu przechwytywania go za pomocą klienta synchronicznego
Java
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
}
Za pomocą klientów asynchronicznych można przechwytywać wyjątki i obsługiwać je w wywołaniach zwrotnych błędów:
Java
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."));
Błędy uwierzytelniania
Usługa Azure OpenAI obsługuje uwierzytelnianie identyfikatora Entra firmy Microsoft.
OpenAIClientBuilder has method to set the credential. Aby podać prawidłowe poświadczenia, możesz użyć azure-identity zależności.
Dostępność funkcji w usłudze Azure OpenAI zależy od wersji docelowego interfejsu API REST. Najnowsze funkcje są przeznaczone dla najnowszego interfejsu API w wersji zapoznawczej.
Istnieje kilka sposobów uwierzytelniania za pomocą usługi Azure OpenAI przy użyciu tokenów identyfikatora Entra firmy Microsoft. Domyślnym sposobem jest użycie DefaultAzureCredential klasy z @azure/identity pakietu.
TypeScript
import { DefaultAzureCredential } from"@azure/identity";
const credential = new DefaultAzureCredential();
Ten obiekt jest następnie przekazywany jako część AzureClientOptions obiektu do AzureOpenAI konstruktorów klienta i AssistantsClient .
Aby uwierzytelnić AzureOpenAI klienta, musimy jednak użyć getBearerTokenProvider funkcji z @azure/identity pakietu. Ta funkcja tworzy dostawcę tokenów, który AzureOpenAI używa wewnętrznie do uzyskiwania tokenów dla każdego żądania. Dostawca tokenu jest tworzony w następujący sposób:
Aby uzyskać więcej informacji na temat uwierzytelniania bez klucza usługi Azure OpenAI, zobacz artykuł Szybki start "Rozpoczynanie pracy z blokiem konstrukcyjnym zabezpieczeń usługi Azure OpenAI".
Konfigurowanie
Obiekt AzureClientOptions rozszerza obiekt OpenAI ClientOptions . Ten obiekt klienta specyficzny dla platformy Azure służy do konfigurowania połączenia i zachowania klienta usługi Azure OpenAI. Zawiera właściwości służące do określania właściwości unikatowych dla platformy Azure.
Właściwości
Szczegóły
apiVersion: string
Określa wersję interfejsu API do użycia.
azureADTokenProvider: (() => Promise<string>)
Funkcja, która zwraca token dostępu dla firmy Microsoft Entra (wcześniej znanej jako Azure Active Directory), wywoływana na każdym żądaniu.
Wdrażania: string
Wdrożenie modelu. Jeśli zostanie podana, ustawia podstawowy adres URL klienta tak, aby zawierał /deployments/{deployment}wartość . Nie można używać punktów końcowych innych niż wdrożenie (nieobsługiwane w przypadku interfejsów API Asystentów).
punkt końcowy: string
Punkt końcowy usługi Azure OpenAI ma następujący format: https://RESOURCE-NAME.azure.openai.com/.
Klucze interfejsu API nie są zalecane do użytku produkcyjnego, ponieważ są one mniej bezpieczne niż inne metody uwierzytelniania.
Obiekt AzureClientOptions rozszerza obiekt OpenAI ClientOptions . Ten obiekt klienta specyficzny dla platformy Azure służy do konfigurowania połączenia i zachowania klienta usługi Azure OpenAI. Zawiera właściwości służące do określania właściwości unikatowych dla platformy Azure.
Właściwości
Szczegóły
apiKey: string
Klucz interfejsu API do uwierzytelniania żądań.
apiVersion: string
Określa wersję interfejsu API do użycia.
Wdrażania: string
Wdrożenie modelu. Jeśli zostanie podana, ustawia podstawowy adres URL klienta tak, aby zawierał /deployments/{deployment}wartość . Nie można używać punktów końcowych innych niż wdrożenie (nieobsługiwane w przypadku interfejsów API Asystentów).
punkt końcowy: string
Punkt końcowy usługi Azure OpenAI ma następujący format: https://RESOURCE-NAME.azure.openai.com/.
Ważne
Używaj kluczy interfejsu API z ostrożnością. Nie dołączaj klucza interfejsu API bezpośrednio do kodu i nigdy nie publikuj go publicznie. Jeśli używasz klucza interfejsu API, zapisz go bezpiecznie w usłudze Azure Key Vault. Aby uzyskać więcej informacji na temat bezpiecznego używania kluczy interfejsu API w aplikacjach, zobacz Klucze interfejsu API w usłudze Azure Key Vault.
Aby uzyskać więcej informacji na temat zabezpieczeń usług sztucznej inteligencji, zobacz Uwierzytelnianie żądań w usługach Azure AI.
Następujące błędy są domyślnie automatycznie wycofywały się dwukrotnie z krótkim wycofywaniem wykładniczym:
Błędy połączenia
408 — limit czasu żądania
Limit szybkości 429
>=Błędy wewnętrzne 500
Użyj maxRetries polecenia , aby ustawić/wyłączyć zachowanie ponawiania prób:
TypeScript
// 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,
});
Ta biblioteka jest utrzymywana przez interfejs OpenAI. Zapoznaj się z historią wydania, aby śledzić najnowsze aktualizacje biblioteki.
Obsługa wersji interfejsu API usługi Azure OpenAI
Dostępność funkcji w usłudze Azure OpenAI zależy od wersji docelowego interfejsu API REST. Najnowsze funkcje są przeznaczone dla najnowszego interfejsu API w wersji zapoznawczej.
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"
)
Aby uzyskać więcej informacji na temat uwierzytelniania bez klucza usługi Azure OpenAI, zobacz artykuł Szybki start "Rozpoczynanie pracy z blokiem konstrukcyjnym zabezpieczeń usługi Azure OpenAI".
Ważne
Używaj kluczy interfejsu API z ostrożnością. Nie dołączaj klucza interfejsu API bezpośrednio do kodu i nigdy nie publikuj go publicznie. Jeśli używasz klucza interfejsu API, zapisz go bezpiecznie w usłudze Azure Key Vault. Aby uzyskać więcej informacji na temat bezpiecznego używania kluczy interfejsu API w aplikacjach, zobacz Klucze interfejsu API w usłudze Azure Key Vault.
Aby uzyskać więcej informacji na temat zabezpieczeń usług sztucznej inteligencji, zobacz Uwierzytelnianie żądań w usługach Azure AI.
Python
import os
from openai import AzureOpenAI
client = AzureOpenAI(
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
api_version="2024-10-21",
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT")
)
Audio
audio.speech.create()
Ta funkcja obecnie wymaga wersji zapoznawczej interfejsu API.
Ustaw api_version="2024-10-01-preview" wartość , aby użyć tej funkcji.
Python
# 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)
# 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)
# 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 isnotNone:
print(chunk.choices[0].delta.content, end='',)
text
Microsoft was founded on April 4, 1975, by Bill Gates and Paul Allen.
# 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)
# 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)
Kody błędów
Kod stanu
Typ błędu
400
BadRequestError
401
AuthenticationError
403
PermissionDeniedError
404
NotFoundError
422
UnprocessableEntityError
429
RateLimitError
>=500
InternalServerError
Nie dotyczy
APIConnectionError
Identyfikatory żądań
Aby pobrać identyfikator żądania, możesz użyć _request_id właściwości odpowiadającej nagłówkowi x-request-id odpowiedzi.
Następujące błędy są domyślnie automatycznie wycofywały się dwukrotnie z krótkim wycofywaniem wykładniczym:
Błędy połączenia
408 — limit czasu żądania
Limit szybkości 429
>=Błędy wewnętrzne 500
Użyj max_retries polecenia , aby ustawić/wyłączyć zachowanie ponawiania prób:
Python
# For all requestsfrom openai import AzureOpenAI
client = AzureOpenAI(
max_retries=0
)
Python
# 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",
)
Dołącz do serii meetup, aby tworzyć skalowalne rozwiązania sztucznej inteligencji oparte na rzeczywistych przypadkach użycia z innymi deweloperami i ekspertami.