Bagikan melalui


Pustaka klien Azure OpenAI untuk JavaScript - versi 1.0.0-beta.12

Pustaka klien Azure OpenAI untuk JavaScript adalah adaptasi DARI REST API OpenAI yang menyediakan antarmuka idiomatik dan integrasi yang kaya dengan ekosistem Azure SDK lainnya. Ini dapat terhubung ke sumber daya Azure OpenAI atau ke titik akhir inferensi OpenAI non-Azure, menjadikannya pilihan yang bagus untuk pengembangan OpenAI non-Azure sekalipun.

Gunakan pustaka klien untuk Azure OpenAI untuk:

Azure OpenAI adalah layanan terkelola yang memungkinkan pengembang untuk menyebarkan, menyelaraskan, dan menghasilkan konten dari model OpenAI pada sumber daya Azure.

Lihat contoh berikut:

Tautan utama:

Memulai

const { OpenAIClient, AzureKeyCredential } = require("@azure/openai");

const client = new OpenAIClient(
  "https://<resource name>.openai.azure.com/", 
  new AzureKeyCredential("<Azure API key>")
);
const { id, created, choices, usage } = await client.getCompletions("<deployment ID>", ["YOUR PROMPT HERE"]);

Lingkungan yang didukung saat ini

Prasyarat

Jika Anda ingin menggunakan sumber daya Azure OpenAI, Anda harus memiliki langganan Azure dan akses Azure OpenAI. Ini akan memungkinkan Anda membuat sumber daya Azure OpenAI dan mendapatkan URL koneksi serta kunci API. Untuk informasi selengkapnya, lihat Mulai Cepat: Mulai menghasilkan teks menggunakan Azure OpenAI Service.

Jika Anda ingin menggunakan pustaka klien Azure OpenAI JS untuk menyambungkan ke OpenAI non-Azure, Anda memerlukan kunci API dari akun pengembang di https://platform.openai.com/.

Pasang paket @azure/openai

Instal pustaka klien klien Azure OpenAI untuk JavaScript dengan npm:

npm install @azure/openai

Membuat dan mengautentikasi OpenAIClient

Untuk mengonfigurasi klien untuk digunakan dengan Azure OpenAI, berikan URI titik akhir yang valid ke sumber daya Azure OpenAI bersama dengan kredensial kunci yang sesuai, kredensial token, atau kredensial identitas Azure yang berwenang untuk menggunakan sumber daya Azure OpenAI. Untuk mengonfigurasi klien agar terhubung ke layanan OpenAI, berikan kunci API dari portal pengembang OpenAI.

Menggunakan Kunci API dari Azure

Gunakan Portal Microsoft Azure untuk menelusuri sumber daya OpenAI Anda dan mengambil kunci API, atau gunakan cuplikan Azure CLI di bawah ini:

Catatan: Terkadang kunci API disebut sebagai "kunci langganan" atau "kunci API langganan."

az cognitiveservices account keys list --resource-group <your-resource-group-name> --name <your-resource-name>

Setelah Anda memiliki kunci API dan titik akhir, Anda dapat menggunakan AzureKeyCredential kelas untuk mengautentikasi klien sebagai berikut:

const { OpenAIClient, AzureKeyCredential } = require("@azure/openai");

const client = new OpenAIClient("<endpoint>", new AzureKeyCredential("<API key>"));

Menggunakan Kredensial Azure Active Directory

Autentikasi kunci API klien digunakan di sebagian besar contoh, tetapi Anda juga dapat mengautentikasi dengan Azure Active Directory menggunakan pustaka Azure Identity. Untuk menggunakan penyedia DefaultAzureCredential yang ditunjukkan di bawah ini, atau penyedia kredensial lain yang disediakan dengan Azure SDK, instal @azure/identity paket:

npm install @azure/identity

Anda juga perlu mendaftarkan aplikasi AAD baru dan memberikan akses ke OpenAI dengan menetapkan peran ke "Cognitive Services User" perwakilan layanan Anda (catatan: peran lain seperti "Owner" tidak akan memberikan izin yang diperlukan, hanya "Cognitive Services User" cukup untuk menjalankan contoh dan kode sampel).

Atur nilai ID klien, ID penyewa, dan rahasia klien aplikasi AAD sebagai variabel lingkungan: AZURE_CLIENT_ID, , AZURE_TENANT_IDAZURE_CLIENT_SECRET.

const { OpenAIClient } = require("@azure/openai");
const { DefaultAzureCredential } = require("@azure/identity");

const client = new OpenAIClient("<endpoint>", new DefaultAzureCredential());

Menggunakan Kunci API dari OpenAI

Untuk mengonfigurasi klien agar terhubung ke layanan OpenAI, berikan kunci API dari portal pengembang OpenAI. Setelah memiliki kunci API, Anda dapat menggunakan OpenAIKeyCredential kelas untuk mengautentikasi klien sebagai berikut:

const { OpenAIClient, OpenAIKeyCredential } = require("@azure/openai");

const client = new OpenAIClient(new OpenAIKeyCredential("<API key>"));

Konsep utama

Konsep utama yang perlu dipahami adalah Penyelesaian. Dijelaskan secara singkat, penyelesaian menyediakan fungsionalitasnya dalam bentuk prompt teks, yang dengan menggunakan model tertentu, kemudian akan mencoba mencocokkan konteks dan pola, menyediakan teks output. Cuplikan kode berikut memberikan gambaran umum kasar:

const { OpenAIClient, AzureKeyCredential } = require("@azure/openai");

async function main(){
  const client = new OpenAIClient(
  "https://your-azure-openai-resource.com/",
  new AzureKeyCredential("your-azure-openai-resource-api-key"));

  const { choices } = await client.getCompletions(
    "text-davinci-003", // assumes a matching model deployment or model name
    ["Hello, world!"]);

  for (const choice of choices) {
    console.log(choice.text);
  }
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

Contoh

Anda dapat membiasakan diri dengan API yang berbeda menggunakan Sampel.

Hasilkan Respons Chatbot

Contoh ini mengautentikasi menggunakan DefaultAzureCredential, lalu menghasilkan respons obrolan untuk memasukkan pertanyaan dan pesan obrolan.

const { OpenAIClient } = require("@azure/openai");
const { DefaultAzureCredential } = require("@azure/identity");

async function main(){
  const endpoint = "https://myaccount.openai.azure.com/";
  const client = new OpenAIClient(endpoint, new DefaultAzureCredential());

  const deploymentId = "gpt-35-turbo";

  const messages = [
    { role: "system", content: "You are a helpful assistant. You will talk like a pirate." },
    { role: "user", content: "Can you help me?" },
    { role: "assistant", content: "Arrrr! Of course, me hearty! What can I do for ye?" },
    { role: "user", content: "What's the best way to train a parrot?" },
  ];

  console.log(`Messages: ${messages.map((m) => m.content).join("\n")}`);

  const events = await client.streamChatCompletions(deploymentId, messages, { maxTokens: 128 });
  for await (const event of events) {
    for (const choice of event.choices) {
      const delta = choice.delta?.content;
      if (delta !== undefined) {
        console.log(`Chatbot: ${delta}`);
      }
    }
  }
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

Hasilkan Beberapa Penyelesaian Dengan Kunci Langganan

Contoh ini menghasilkan respons teks terhadap perintah input menggunakan kunci langganan Azure

const { OpenAIClient, AzureKeyCredential } = require("@azure/openai");

async function main(){
  // Replace with your Azure OpenAI key
  const key = "YOUR_AZURE_OPENAI_KEY";
  const endpoint = "https://myaccount.openai.azure.com/";
  const client = new OpenAIClient(endpoint, new AzureKeyCredential(key));

  const examplePrompts = [
    "How are you today?",
    "What is Azure OpenAI?",
    "Why do children love dinosaurs?",
    "Generate a proof of Euler's identity",
    "Describe in single words only the good things that come into your mind about your mother.",
  ];

  const deploymentName = "text-davinci-003";

  let promptIndex = 0;
  const { choices } = await client.getCompletions(deploymentName, examplePrompts);
  for (const choice of choices) {
    const completion = choice.text;
    console.log(`Input: ${examplePrompts[promptIndex++]}`);
    console.log(`Chatbot: ${completion}`);
  }
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

Meringkas Teks dengan Penyelesaian

Contoh ini menghasilkan ringkasan perintah input yang diberikan.

const { OpenAIClient } = require("@azure/openai");
const { DefaultAzureCredential } = require("@azure/identity")

async function main(){
  const endpoint = "https://myaccount.openai.azure.com/";
  const client = new OpenAIClient(endpoint, new DefaultAzureCredential());

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

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

  const summarizationPrompt = [`
    Summarize the following text.

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

    Summary:
  `];

  console.log(`Input: ${summarizationPrompt}`);

  const deploymentName = "text-davinci-003";

  const { choices } = await client.getCompletions(deploymentName, summarizationPrompt, {
    maxTokens: 64
  });
  const completion = choices[0].text;
  console.log(`Summarization: ${completion}`);
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

Menggunakan alat obrolan

Alat memperluas penyelesaian obrolan dengan memungkinkan asisten memanggil fungsi yang ditentukan dan kemampuan lain dalam proses pemenuhan permintaan penyelesaian obrolan. Untuk menggunakan alat obrolan, mulailah dengan menentukan alat fungsi:

const getCurrentWeather = {
    name: "get_current_weather",
    description: "Get the current weather in a given location",
    parameters: {
      type: "object",
      properties: {
        location: {
          type: "string",
          description: "The city and state, e.g. San Francisco, CA",
        },
        unit: {
          type: "string",
          enum: ["celsius", "fahrenheit"],
        },
      },
      required: ["location"],
    },
  };

Dengan alat yang ditentukan, sertakan definisi baru tersebut dalam opsi untuk permintaan penyelesaian obrolan:

const deploymentName = "gpt-35-turbo-1106";
const messages = [{ role: "user", content: "What is the weather like in Boston?" }];
const options = {
    tools: [
      {
        type: "function",
        function: getCurrentWeather,
      },
    ],
  };
const events = client.getChatCompletions(deploymentId, messages, options);

Ketika asisten memutuskan bahwa satu atau beberapa alat harus digunakan, pesan respons menyertakan satu atau beberapa "panggilan alat" yang semuanya harus diselesaikan melalui "pesan alat" pada permintaan berikutnya. Resolusi panggilan alat ini ke pesan permintaan baru ini dapat dianggap sebagai semacam "panggilan balik" untuk penyelesaian obrolan.

// Purely for convenience and clarity, this function handles tool call responses.
function applyToolCall({ function: call, id }) {
    if (call.name === "get_current_weather") {
      const { location, unit } = JSON.parse(call.arguments);
      // In a real application, this would be a call to a weather API with location and unit parameters
      return {
        role: "tool",
        content: `The weather in ${location} is 72 degrees ${unit} and sunny.`,
        toolCallId: id,
      }
    }
    throw new Error(`Unknown tool call: ${call.name}`);
}

Untuk memberikan resolusi panggilan alat ke asisten agar permintaan dapat dilanjutkan, berikan semua konteks historis sebelumnya -- termasuk sistem asli dan pesan pengguna, respons dari asisten yang menyertakan panggilan alat, dan pesan alat yang menyelesaikan masing-masing alat tersebut -- saat membuat permintaan berikutnya.

const choice = result.choices[0];
const responseMessage = choice.message;
if (responseMessage?.role === "assistant") {
  const requestedToolCalls = responseMessage?.toolCalls;
  if (requestedToolCalls?.length) {
    const toolCallResolutionMessages = [
      ...messages,
      responseMessage,
      ...requestedToolCalls.map(applyToolCall),
    ];
    const result = await client.getChatCompletions(deploymentName, toolCallResolutionMessages);
    // continue handling the response as normal
  }
}

Menghasilkan gambar dengan model pembuatan gambar DALL-E

Contoh ini menghasilkan gambar batch dari perintah input tertentu.

const { OpenAIClient, AzureKeyCredential } = require("@azure/openai");

async function main() {
  const endpoint = "https://myaccount.openai.azure.com/";
  const client = new OpenAIClient(endpoint, new AzureKeyCredential(azureApiKey));

  const deploymentName = "dalle-3";
  const prompt = "a monkey eating a banana";
  const size = "1024x1024";
  const n = 1;
  
  const results = await client.getImages(deploymentName, prompt, { n, size });

  for (const image of results.data) {
    console.log(`Image generation result URL: ${image.url}`);
  }
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

Menganalisis Data Bisnis

Contoh ini menghasilkan respons obrolan untuk memasukkan pertanyaan obrolan tentang data bisnis Anda. Data bisnis disediakan melalui indeks Azure Cognitive Search. Untuk mempelajari selengkapnya tentang cara menyiapkan indeks Azure Cognitive Search sebagai sumber data, lihat Mulai Cepat: Mengobrol dengan model Azure OpenAI menggunakan data Anda sendiri.

const { OpenAIClient } = require("@azure/openai");
const { DefaultAzureCredential } = require("@azure/identity");

async function main(){
  const endpoint = "https://myaccount.openai.azure.com/";
  const client = new OpenAIClient(endpoint, new DefaultAzureCredential());

  const deploymentId = "gpt-35-turbo";

  const messages = [
    { role: "user", content: "What's the most common customer feedback about our product?" },
  ];

  console.log(`Messages: ${messages.map((m) => m.content).join("\n")}`);

  const events = await client.streamChatCompletions(deploymentId, messages, { 
    maxTokens: 128,
    azureExtensionOptions: {
      extensions: [
        {
          type: "AzureCognitiveSearch",
          endpoint: "<Azure Cognitive Search endpoint>",
          key: "<Azure Cognitive Search admin key>",
          indexName: "<Azure Cognitive Search index name>",
        },
      ],
    },
  });
  for await (const event of events) {
    for (const choice of event.choices) {
      const delta = choice.delta?.content;
      if (delta !== undefined) {
        console.log(`Chatbot: ${delta}`);
      }
    }
  }
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

Mentranskripsikan dan terjemahkan file audio

Kemampuan ucapan ke teks dan terjemahan Azure OpenAI dapat digunakan untuk mentranskripsikan dan menerjemahkan berbagai format file audio. Contoh berikut menunjukkan cara menggunakan getAudioTranscription metode untuk mentranskripsikan audio ke dalam bahasa tempat audio berada. Anda juga dapat menerjemahkan dan mentranskripsikan audio ke dalam bahasa Inggris menggunakan metode .getAudioTranslation

File audio dapat dimuat ke dalam memori menggunakan API sistem file NodeJS. Di browser, file dapat dimuat menggunakan FileReader API dan output arrayBuffer metode instans dapat diteruskan ke getAudioTranscription metode .

const { OpenAIClient, AzureKeyCredential } = require("@azure/openai");
const fs = require("fs/promises");

async function main() {
  console.log("== Transcribe Audio Sample ==");

  const client = new OpenAIClient(endpoint, new AzureKeyCredential(azureApiKey));
  const deploymentName = "whisper";
  const audio = await fs.readFile("< path to an audio file >");
  const result = await client.getAudioTranscription(deploymentName, audio);

  console.log(`Transcription: ${result.text}`);
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

Mengobrol dengan gambar menggunakan gpt-4-vision-preview

Model ini gpt-4-vision-preview memungkinkan Anda menggunakan gambar sebagai komponen input ke dalam penyelesaian obrolan.

Untuk melakukan ini, berikan item konten yang berbeda pada pesan pengguna untuk permintaan penyelesaian obrolan:

const url = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
const deploymentName = "gpt-4-1106-preview";
const messages: ChatRequestMessage[] = [{role: "user", content: [{
  type: "image_url",
  imageUrl: {
    url,
    detail: "auto"
  }
}]}];

Penyelesaian Obrolan kemudian akan dilanjutkan seperti biasa, meskipun model dapat melaporkan lebih informatif finish_details sebagai pengganti finish_reason:

const result = await client.getChatCompletions(deploymentName, messages);
console.log(`Chatbot: ${result.choices[0].message?.content}`);

Pemecahan Masalah

Pencatatan

Mengaktifkan pengelogan dapat membantu menemukan informasi yang berguna tentang kegagalan. Untuk melihat log permintaan dan respons HTTP, atur variabel lingkungan AZURE_LOG_LEVEL ke info. Atau, pengelogan dapat diaktifkan saat runtime dengan memanggil setLogLevel di @azure/logger:

const { setLogLevel } = require("@azure/logger");

setLogLevel("info");

Untuk instruksi lebih rinci tentang cara mengaktifkan log, Anda dapat melihat dokumen paket @azure/pencatat.