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?

TypeScript & DenoでAzure OpenAI Serviceへの接続とChat

0
Posted at

準備

OpenAIモデルデプロイ

Azure Foundryの GPT-4o-mini をデプロイする。

Foundryの使い方は別でまとめる。

参考にしたソースコード

以下のAzure FoundryのTypeScriptサンプルを参考にする。
後で少し変更する。

// Azure Foundry の TypeScriptサンプル

import OpenAI from "openai";

const endpoint = "https://<Foundryリソース名>.cognitiveservices.azure.com/openai/v1/";
const modelName = "gpt-4.1-mini";
const deployment_name = "<デプロイ名>";
const api_key = "<your-api-key>";

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

async function main() {
  const completion = await client.chat.completions.create({
    messages: [
      { role: "developer", content: "You talk like a pirate." },
      { role: "user", content: "Can you help me?" }
    ],
    model: deployment_name,
  });

  console.log(completion.choices[0]);
}

main();

実装

DenoでOpenAI関連のライブラリを追加

Denoでライブラリを利用する場合、Deno addコマンドを使う。
ここに情報あり。

Denoプロジェクトに追加する場合は以下のコマンドで追加。
依存関係も含めてdeno.jsonに追加される。

// denoにOpenAIライブラリを追加

sato@[22:20:54]:~/proj/try/typescript/chatgpt% deno add jsr:@openai/openai
Add jsr:@openai/openai@6.35.0
Installed 3 packages in 4s
Reused 0 packages from cache
Downloaded 3 packages from JSR
+++
Downloaded 1 package from npm
+

Dependencies:
+ jsr:@openai/openai 6.35.0
+ jsr:@std/assert 1.0.19
+ jsr:@std/internal 1.0.13
+ npm:zod 3.25.76

sato@[22:22:28]:~/proj/try/typescript/chatgpt% 
// deno.json

{
  "tasks": {
    "dev": "deno run --watch main.ts"
  },
  "imports": {
    "@openai/openai": "jsr:@openai/openai",
    "@std/assert": "jsr:@std/assert@1"
  }
}

サンプルプログラムの変更箇所

  • deno.jsonからライブラリを参照する
  • modelNameは不要
  • プロンプト指示文で少し長めの回答を得られるように修正(後でWebアプリにしてストリーム出力を試すため)
// Deno + TypeScriptでのサンプル

// deno.jsonに追加されたライブラリを参照
import OpenAI from "@openai/openai";

const endpoint = "https://<Azure Foundryリソース名>.cognitiveservices.azure.com/openai/v1/";
const deployment_name = "<デプロイ名>";
const api_key = "<API Key>";

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

async function main() {
  const completion = await client.chat.completions.create({
    // プロンプト指示文
    messages: [
      { role: "developer", content: "レシピ作成アシスタント" },
      { role: "user", content: "おでん" }
    ],
    model: deployment_name,
  });

  console.log(completion.choices[0].message.content);
}

main();

実行&回答サンプル

実行時のオプション

--allow-env : openaiライブラリが環境変数を参照するために必要

このオプションがないと以下の警告が表示され、回答入力を求められる。

sato@[8:57:02]:~/proj/try/typescript/chatgpt% deno run main.ts                         
┏ ⚠️  Deno requests env access to "OPENAI_ORG_ID".
┠─ To see a stack trace for this prompt, set the DENO_TRACE_PERMISSIONS environmental variable.
┠─ Learn more at: https://docs.deno.com/go/--allow-env
┠─ Run again with --allow-env to bypass this prompt.
┗ Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all env permissions) > 

参照しようとしている環境変数は以下の通り。

sato@[8:57:02]:~/proj/try/typescript/chatgpt% deno run main.ts  
✅ Granted env access to "OPENAI_ORG_ID".
✅ Granted env access to "OPENAI_PROJECT_ID".
✅ Granted env access to "OPENAI_WEBHOOK_SECRET".
✅ Granted env access to "OPENAI_LOG".

--allow-net ネットワークアクセスするために必要

このオプションがないと、ネットワークアクセス時に以下の警告が表示され、回答入力を求められる。

┏ ⚠️  Deno requests net access to "ai-masatoshisato19180ai905530356745.cognitiveservices.azure.com:443".
┠─ Requested by `fetch()` API.
┠─ To see a stack trace for this prompt, set the DENO_TRACE_PERMISSIONS environmental variable.
┠─ Learn more at: https://docs.deno.com/go/--allow-net
┠─ Run again with --allow-net to bypass this prompt.
┗ Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all net permissions) > 

実行結果

2つのオプションを指定して実行した結果。

sato@[7:37:22]:~/proj/try/typescript/chatgpt% deno run --allow-env --allow-net  main.ts
おでんの基本的なレシピをご紹介します。

【材料】(4人分)
- 大根:1/2本
- こんにゃく:1枚
- ちくわ:4本
- さつま揚げ:4枚
- たまご:4個
- じゃがいも:2個(お好みで)
- 昆布:10cm角1枚
- 水:1.5リットル

【だしの調味料】
- しょうゆ:大さじ4
- みりん:大さじ2
- 酒:大さじ2
- 塩:小さじ1/2

【作り方】
1. 大根は1.5cm厚の輪切りにし、面取りをして下茹でします(約10分)。
2. こんにゃくは一口大に切り、塩で揉んで臭みを取った後、下茹でします(約5分)。
3. たまごはゆで卵にして殻をむきます。
4. 鍋に水と昆布を入れ、中火でじっくりだしをとります。沸騰直前に昆布を取り出します。
5. 調味料を加え、大根、こんにゃく、じゃがいもを入れ、中火で煮ます。
6. ある程度火が通ったら、ちくわ、さつま揚げ、ゆで卵を加え、さらに30分ほど弱火で煮込みます。
7. 味を見て、必要なら塩で調整します。
8. 食べる前に一度冷ますと味がよく染み込みます。温めなおしてからお召し上がりください。

お好みで、練りがらしを添えてどうぞ。何か他に知りたいことがあれば教えてください。
sato@[8:54:56]:~/proj/try/typescript/chatgpt% 
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?