Share via


Java 用 Azure OpenAI クライアント ライブラリ - バージョン 1.0.0-beta.5

Azure OpenAI は、開発者が Azure リソース上の OpenAI モデルからコンテンツをデプロイ、調整、生成できるようにするマネージド サービスです。

Java 用 Azure OpenAI クライアント ライブラリは、慣用インターフェイスと Azure SDK エコシステムの残りの部分との豊富な統合を提供する OpenAI の REST API を適応しています。

Azure OpenAI 用のクライアント ライブラリを使用して、次の手順を実行します。

具体的な例については、次のリンクを参照してください。 より一般的なシナリオの一部について説明します。

これらのスニペットの完全なコードを表示する場合は、サンプル フォルダーチェック。

ソース コード | API リファレンス ドキュメント | 製品ドキュメント | サンプル

作業の開始

前提条件

製品へのパッケージの追加

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

認証

Azure OpenAI サービスと対話するには、OpenAIClientBuilder を使用して、クライアント クラス OpenAIAsyncClient または OpenAIClient のインスタンスを作成する必要があります。 Azure OpenAI で使用するようにクライアントを構成するには、Azure OpenAI リソースに対する有効なエンドポイント URI と、Azure OpenAI リソースの使用が許可されている対応するキー資格情報、トークン資格情報、または Azure ID 資格情報を指定します。

キー資格情報を使用して Azure OpenAI クライアントを作成する

Azure Portal から Azure OpenAI key 資格情報を取得します。

OpenAIClient client = new OpenAIClientBuilder()
    .credential(new AzureKeyCredential("{key}"))
    .endpoint("{endpoint}")
    .buildClient();

または

OpenAIAsyncClient client = new OpenAIClientBuilder()
    .credential(new AzureKeyCredential("{key}"))
    .endpoint("{endpoint}")
    .buildAsyncClient();

Azure 以外の OpenAI のサポート

SDK では、Azure 以外のパブリック OpenAI に対する運用もサポートされています。 応答モデルは変わりませんが、 の OpenAIClient 設定のみが若干異なります。 まず、Open AI 認証 API キーから Azure 以外の OpenAI API キーを取得します。 次に、次のように を設定します。OpenAIClient

OpenAIClient client = new OpenAIClientBuilder()
    .credential(new KeyCredential("{openai-secret-key}"))
    .buildClient();

または

OpenAIAsyncClient client = new OpenAIClientBuilder()
    .credential(new KeyCredential("{openai-secret-key}"))
    .buildAsyncClient();

Azure Active Directory 資格情報を使用して Azure OpenAI クライアントを作成する

Azure SDK for Java では Azure Identity パッケージがサポートされているため、Microsoft ID プラットフォームから資格情報を簡単に取得できます。

AAD を使用した認証には、いくつかの初期セットアップが必要です。

  • Azure Identity パッケージを追加する
<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-identity</artifactId>
    <version>1.10.1</version>
</dependency>

セットアップ後、使用する azure.identity から 資格情報 の種類を選択できます。 たとえば、DefaultAzureCredential を使用してクライアントを認証できます。AAD アプリケーションのクライアント ID、テナント ID、およびクライアント シークレットの値を環境変数として設定します。 AZURE_CLIENT_IDAZURE_TENANT_IDAZURE_CLIENT_SECRET

承認は、 DefaultAzureCredential を使用するのが最も簡単です。 実行中の環境で使用するのに最適な資格情報が見つかります。 OpenAI サービスで Azure Active Directory 承認を使用する方法の詳細については、 関連するドキュメントを参照してください。

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

プロキシ オプションを使用してクライアントを作成する

プロキシ オプションを使用して OpenAI クライアントを作成します。

// Proxy options
final String hostname = "{your-host-name}";
final int port = 447; // your port number

ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(hostname, port))
    .setCredentials("{username}", "{password}");

OpenAIClient client = new OpenAIClientBuilder()
    .credential(new AzureKeyCredential("{key}"))
    .endpoint("{endpoint}")
    .clientOptions(new HttpClientOptions().setProxyOptions(proxyOptions))
    .buildClient();

主要な概念

次のセクションでは、次のような最も一般的な OpenAI サービス タスクをカバーするいくつかのコード スニペットを示します。

テキスト入力候補

List<String> prompt = new ArrayList<>();
prompt.add("Say this is a test");

Completions completions = client.getCompletions("{deploymentOrModelId}", new CompletionsOptions(prompt));

System.out.printf("Model ID=%s is created at %s.%n", completions.getId(), completions.getCreatedAt());
for (Choice choice : completions.getChoices()) {
    System.out.printf("Index: %d, Text: %s.%n", choice.getIndex(), choice.getText());
}

完全なサンプル例については、「 テキスト補完のサンプル」を参照してください。

ストリーミング テキスト入力候補

List<String> prompt = new ArrayList<>();
prompt.add("How to bake a cake?");

IterableStream<Completions> completionsStream = client
    .getCompletionsStream("{deploymentOrModelId}", new CompletionsOptions(prompt));

completionsStream
    .stream()
    // Remove .skip(1) when using Non-Azure OpenAI API
    // Note: the first chat completions can be ignored when using Azure OpenAI service which is a known service bug.
    // TODO: remove .skip(1) when service fix the issue.
    .skip(1)
    .forEach(completions -> System.out.print(completions.getChoices().get(0).getText()));

完全なサンプル例については、「 ストリーミング テキスト補完のサンプル」を参照してください。

チャット入力候補

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

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

System.out.printf("Model ID=%s is created at %s.%n", chatCompletions.getId(), chatCompletions.getCreatedAt());
for (ChatChoice choice : chatCompletions.getChoices()) {
    ChatMessage 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());
}

完全なサンプル例については、「 チャットの完了のサンプル」を参照してください。

サンプルについては、「function call関数呼び出し」を参照してください。

サンプルについては、「Bring Your Own DataBring Your Own Data」を参照してください。

テキスト補完の概念的な説明については、サービス ドキュメントを参照してください。

ストリーミング チャットの完了

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

IterableStream<ChatCompletions> chatCompletionsStream = client.getChatCompletionsStream("{deploymentOrModelId}",
    new ChatCompletionsOptions(chatMessages));

chatCompletionsStream
    .stream()
    // Remove .skip(1) when using Non-Azure OpenAI API
    // Note: the first chat completions can be ignored when using Azure OpenAI service which is a known service bug.
    // TODO: remove .skip(1) when service fix the issue.
    .skip(1)
    .forEach(chatCompletions -> {
        ChatMessage delta = chatCompletions.getChoices().get(0).getDelta();
        if (delta.getRole() != null) {
            System.out.println("Role = " + delta.getRole());
        }
        if (delta.getContent() != null) {
            System.out.print(delta.getContent());
        }
    });

完全なサンプル例については、「 ストリーミング チャットの完了のサンプル」を参照してください。

テキスト埋め込み

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

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

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

完全なサンプル例については、「 埋め込みのサンプル」を参照してください。

openAI 埋め込みの概念については、サービス ドキュメントを参照してください。

イメージの生成

ImageGenerationOptions imageGenerationOptions = new ImageGenerationOptions(
    "A drawing of the Seattle skyline in the style of Van Gogh");
ImageResponse images = client.getImages(imageGenerationOptions);

for (ImageLocation imageLocation : images.getData()) {
    ResponseError error = imageLocation.getError();
    if (error != null) {
        System.out.printf("Image generation operation failed. Error code: %s, error message: %s.%n",
            error.getCode(), error.getMessage());
    } else {
        System.out.printf(
            "Image location URL that provides temporary access to download the generated image is %s.%n",
            imageLocation.getUrl());
    }
}

完全なサンプル例については、「 イメージ生成のサンプル」を参照してください。

オーディオ文字起こし

OpenAI サービスは、モデルの導入に伴うサポート audio transcriptionWhisper 開始します。 次のコード スニペットは、サービスを使用してオーディオを文字起こしする方法を示しています。

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("{deploymentOrModelId}", fileName, transcriptionOptions);

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

完全なサンプル例については、「 オーディオ文字起こしのサンプル」を参照してください。 ささやきの概念的な説明については、サービスのドキュメントを参照してください。

オーディオ翻訳

OpenAI サービスは、モデルの導入に伴うサポート audio translationWhisper 開始します。 次のコード スニペットは、サービスを使用してオーディオを翻訳する方法を示しています。

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

byte[] file = BinaryData.fromFile(filePath).toBytes();
AudioTranslationOptions translationOptions = new AudioTranslationOptions(file)
    .setResponseFormat(AudioTranslationFormat.JSON);

AudioTranslation translation = client.getAudioTranslation("{deploymentOrModelId}", fileName, translationOptions);

System.out.println("Translation: " + translation.getText());

完全なサンプル例については、「 オーディオ翻訳のサンプル」を参照してください。 ささやきの概念的な説明については、サービスのドキュメントを参照してください。

トラブルシューティング

クライアントのログ記録を有効にする

クライアント ライブラリで実行されたログ記録ステートメントは、AZURE_LOG_LEVEL 環境変数を設定することで表示できます。 たとえば、AZURE_LOG_LEVEL=2 と設定すると、情報、警告、エラーのすべてのログ メッセージが表示されます。 ログ レベルについては、こちらのログ レベルに関するページを参照してください。

既定の HTTP クライアント

すべてのクライアント ライブラリでは、Netty HTTP クライアントが既定で使用されます。 前述の依存関係を追加すると、Netty HTTP クライアントを使用するようにクライアント ライブラリが自動的に構成されます。 HTTP クライアントの構成と変更については、HTTP クライアントの Wiki で詳しく説明されています。

既定の SSL ライブラリ

すべてのクライアント ライブラリは、Tomcat ネイティブの Boring SSL ライブラリを既定で使用して、SSL 操作にネイティブレベルのパフォーマンスを実現しています。 Boring SSL ライブラリは、Linux、macOS、Windows のネイティブ ライブラリを含んだ uber jar であり、JDK 内の既定の SSL 実装よりも優れたパフォーマンスを備えています。 依存関係のサイズを縮小する方法など、詳細については、Wiki の「パフォーマンス チューニング」セクションを参照してください。

次のステップ

共同作成

このリポジトリへの投稿の詳細については、 投稿ガイドを参照してください。

  1. フォークする
  2. 機能ブランチを作成する (git checkout -b my-new-feature)
  3. 変更をコミットする (git commit -am 'Add some feature')
  4. ブランチにプッシュする (git push origin my-new-feature)
  5. 新しい Pull Request を作成する