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

生成AIなぞかけメーカー制作奮闘記その2

Posted at

少し動いた

生成AIを使ってなぞかけを作らせるプロジェクトに挑戦中である。今回は少し動いたので、その様子を書いておく。

まず作る動機はこちら。

続いて、なぜ、ふつうに生成AIになぞかけをつくらると面白くない(ヒネリがきいていない)か?がこちら。

現在は、PCのEdge経由でCopilotに相談しながら、Githubでコードを書いている。正確に言うとコードもCopilotに書いてもらい、Githubの操作やVercelへのdeployの仕方も教えてもらっている。

仕様とシステム構成案

最終的な仕様はスマホでもPCでもよいので、あるURLにアクセスしてお題Aを入力すると、なんのヒネリもない素のAI生成なぞかけ作品「AとかけてB1ととく。そのこころはC1。」とヒネリを効かせた作品「AとかけてB2ととく。そのこころはC2。」の二つを表示し、二つ目の評価を◎△✖で入力し、よければコメントも入力いただいて終わり、というものである。
 しかし最初はまず、お題を入力して「AとかけてB1ととく。そのこころはC1。」だけを表示させるところからである。

最初の開発は以下の構成である。

最終構成案は以下である。

ここでGoogle Spreadsheetには、OpenAIに与えるなぜいかけ生成条件(プロンプト)の要素である。容易に変更できるよう、Google Spreadsheetにした。
また、Supabaseは、どのような条件で生成を行ったかの管理者用ログであり、なぞかけ生成ロジックの改良用である。

一番困ったこと:OpenAIの出力がみられない

 開発を初めて税所はいろんなところでトラブった。一部はこんなところである。

しかし、一番困ったのはOpenAIが何か返してきているが、その結果を受け取れないでエラーが出ることである。これについてはよくわかっていないが、とにかく動いたコード(OpenAIと皇孫する部分は以下である。備忘録として載せておく。

generate.ts
import type { NextApiRequest, NextApiResponse } from 'next';

const OPENAI_API_KEY = process.env.OPENAI_API_KEY as string;

type GenerateRequest = {
  theme: string;
  style?: string;
  difficulty?: string;
};

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method Not Allowed' });
  }

  const { theme, style = '標準', difficulty = '普通' } = req.body as GenerateRequest;

  if (!theme || typeof theme !== 'string') {
    return res.status(400).json({ error: 'テーマが必要です' });
  }

  const prompt = buildPrompt(theme, style, difficulty);

  try {
    const response: Response = await fetch('https://api.openai.com/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${OPENAI_API_KEY}`,
      },
      body: JSON.stringify({
        model: 'gpt-4', // 必要に応じて 'gpt-5' に変更
        messages: [{ role: 'user', content: prompt }],
        temperature: 0.8,
        max_tokens: 200,
      }),
    });

    const data = await response.json();
    const content = data.choices?.[0]?.message?.content?.trim();

    const result = typeof content === 'string' && content
      ? content
      : `◯◯とかけて、◯◯と解く。その心は、◯◯です。`;

    return res.status(200).json({ result });
  } catch (error) {
    console.error('💥 OpenAI APIエラー:', error);
    return res.status(500).json({ error: 'エラーが発生しました' });
  }
}

function buildPrompt(theme: string, style: string, difficulty: string): string {
  return `あなたは日本語の「なぞかけ職人」です。
以下の条件に従って、ユーモアと知性を込めたなぞかけを1つ生成してください。
【テーマ】${theme}
【スタイル】${style}
【難易度】${difficulty}
形式:「◯◯とかけて、◯◯と解く。その心は、◯◯です。」
※出力はこの形式に従ってください。説明や補足は不要です。`;
}

今後はヒネリありなしの2本生成に向けて進めてゆく。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?