LoginSignup
1
0

[Deno] Fresh + OpenAI SDK for DenoでAI LINE Botを作ってみる

Posted at

はじめに

最近DenoでのLINE Bot開発が手軽でいいなと思いはじめていろいろやってみています。今回は最近登場した OpenAI SDK for Denoを組み込んだAI Botをカンタンに作ってみようと思います。

やってみた

前回作ったFreshのBotをベースにします。Text Generationのサンプルを参考に routes/api/messaging.ts を以下のように更新します。

routes/api/messaging.ts
import type { Handlers, FreshContext } from "$fresh/server.ts";
import { messagingApi, MessageEvent } from "npm:@line/bot-sdk@8.4.0";
import type { ClientConfig, TextEventMessage } from "npm:@line/bot-sdk@8.4.0";
import OpenAI from "https://deno.land/x/openai@v4.33.1/mod.ts";

const config: ClientConfig = {
    channelAccessToken: "YOUR_CHANNEL_ACCESS_TOKEN",
    channelSecret: "YOUR_CHANNEL_SECRET",
};
const client = new messagingApi.MessagingApiClient(config);

const ai = new OpenAI();

export const handler: Handlers =  {
  async POST(_req: Request, _ctx: FreshContext): Promise<Response> {
    const body = await _req.json(); 
    const event: MessageEvent = body.events[0];
    const textMessage = event.message as TextEventMessage;
    const chatCompletion = await ai.chat.completions.create({
      messages: [{ role: "user", content: `あなたは何でも知ってる物知り博士です。次の"#動物の名称"欄に記載される動物の生態を詳しく教えてください。ただし、"#動物の名称"欄に動物の名称ではないものが記載された場合は、"それは動物の名称ではありません"と回答してください。\n\n#動物の名称: ${textMessage.text}` }],
      model: "gpt-4-1106-preview",
    });
    const completion = chatCompletion.choices[0].message.content;
    await client.replyMessage({
      replyToken: event.replyToken,
      messages: [
        {
          type: "text",
          text: completion,
        },
      ],
    });
    return new Response(null, { status: 204 });
  }
};

Open AIのAPIを環境変数に設定して実行します

OPENAI_API_KEY=[YOUR OPENAI API KEY] deno task start

Task start deno run -A --watch=static/,routes/ dev.ts
Watcher Process started.
The manifest has been generated for 6 routes and 1 islands.

 🍋 Fresh ready 
    Local: http://localhost:8000/

LINE Chatで動物の名前を送信すると詳しい生態の説明が返ってきました。

SC_20240415.png

おわりに

Open AI SDK for Denoが公式にリリースされたことでDenoでもChatGPT等を利用したAI開発が加速しそうです。FreshなどのWeb Frameworkと組み合わせれば非常にカンタンにLINE Botも開発できることがわかりました。

やはりTypeScriptでの開発はnode.jsよりDenoのほうがカジュアルにやれる感覚があります。モジュールも充実してきているので積極的にやっていきたいと思います。

1
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
1
0