0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Azure OpenAI Serviceからのレスポンスをブラウザに表示 (no stream)

0
Posted at

変更元のプログラム

この記事は以下の簡単なGPTプログラムをCLIからWebUIにする。

変更点

  • main関数をchatWithGPT関数に変更し、GPTの結果をstringとして返す
  • Denoサーバーを追加し、リクエストハンドラーを登録
  • リクエストハンドラーでchatWithGPT関数をコールし、結果をtext/plainでレスポンス
import OpenAI from "@openai/openai";

const endpoint = Deno.env.get("AZURE_OPENAI_ENDPOINT") ?? "";
const deployment_name = Deno.env.get("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4.1-mini";
const api_key = Deno.env.get("AZURE_OPENAI_API_KEY") ?? "";

const client = new OpenAI({
    baseURL: endpoint,
    apiKey: api_key
});

// 変更点1. 関数名を目的に沿った名前に変更しstringを返す。
// * 非同期関数からの戻りはPromise型
-async function main() {
+async function chatWithGPT(): Promise<string> {
  const completion = await client.chat.completions.create({
    messages: [
      { role: "developer", content: "レシピ作成アシスタント" },
      { role: "user", content: "おでん" }
    ],
    model: deployment_name,
  });

  // 変更点2. コンソール出力はやめて、文字列としてreturn
- console.log(completion.choices[0].message.content);
+ return completion.choices[0].message.content || "";
}

// 変更点3. WebリクエストハンドラーでGPTを実行し、結果をplaintextでレスポンス。
+async function handler() {
+  const response = new Response(await chatWithGPT(), {
+    headers: { "Content-Type": "text/plain; charset=utf-8" },
+  });
+  return response;
+}
+
// 変更点4. Deno Webサーバーを実行
-main();
+Deno.serve(handler);

実行結果

少し待ってから結果が表示される。

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?