|
| 1 | +/* eslint-disable import/prefer-default-export */ |
| 2 | +import {stripIndent} from 'common-tags'; |
| 3 | +import {z} from 'zod'; |
| 4 | +import logger from '../lib/logger'; |
| 5 | +import openai from '../lib/openai'; |
| 6 | + |
| 7 | +const log = logger.child({bot: 'tahoiya/arbitraryAibot'}); |
| 8 | + |
| 9 | +const MODEL = 'gpt-4.1-mini'; |
| 10 | +const MAX_ANSWER_LENGTH = 256; |
| 11 | + |
| 12 | +// Initial generation + up to 2 regenerations when the previous attempt is judged correct. |
| 13 | +const MAX_GENERATION_ATTEMPTS = 3; |
| 14 | + |
| 15 | +const DecoyAnswerResponse = z.object({ |
| 16 | + decoyAnswer: z.string().trim().nonempty(), |
| 17 | +}); |
| 18 | + |
| 19 | +const JudgeResponse = z.object({ |
| 20 | + isCorrect: z.boolean(), |
| 21 | +}); |
| 22 | + |
| 23 | +const extractJson = (content: string): unknown => { |
| 24 | + const match = content.match(/\{[\s\S]*\}/); |
| 25 | + if (!match) { |
| 26 | + throw new Error(`No JSON object found in response: ${content}`); |
| 27 | + } |
| 28 | + return JSON.parse(match[0]); |
| 29 | +}; |
| 30 | + |
| 31 | +const buildGenerationPrompt = ( |
| 32 | + question: string, |
| 33 | + answer: string, |
| 34 | + isMimicryAllowed: boolean, |
| 35 | + previousAttempts: string[], |
| 36 | +): string => stripIndent` |
| 37 | + あなたは「たほいや」という言葉遊びゲームの「任意お題モード」に、他のプレイヤーに混じって参加するAIです。 |
| 38 | + このモードでは、出題者があらかじめ「質問」と「正解」の組を用意しており、参加者は正解を知らないまま、他のプレイヤーを騙すための「誤答選択肢」を考えて提出します。 |
| 39 | + 最終的に、正解と全参加者の誤答選択肢がシャッフルされて提示され、他のプレイヤーはどれが正解かを当てます。 |
| 40 | +
|
| 41 | + # 質問 |
| 42 | + ${question} |
| 43 | +
|
| 44 | + # 正解(あなたはこれを知っていますが、誤答選択肢としてこれを使ったり、言い換えて使ったりしてはいけません) |
| 45 | + ${answer} |
| 46 | +
|
| 47 | + # あなたのタスク |
| 48 | + 以下の手順で思考しながら、この質問に対する「誤答選択肢」を1つ作成してください。 |
| 49 | +
|
| 50 | + 1. 質問の分野・意図と、正解の形式(固有名詞か説明文か、文体、大まかな分量など)を分析する。 |
| 51 | + 2. 分析結果を踏まえ、正解と似た形式でありながら内容が異なる、もっともらしい誤答の候補を3つ挙げる。 |
| 52 | + 3. 各候補について、他のプレイヤーが正解と誤認しそうな説得力があるかを吟味し、最も優れた候補を1つ選ぶ。 |
| 53 | + 4. 選んだ候補の内容が、正解と実質的に同じ意味になっていないかを再確認し、もし同じ意味であれば候補を修正する。 |
| 54 | +
|
| 55 | + # 重要な注意事項(必ず守ること) |
| 56 | + - どのような場合であっても、質問に対して正解となるような回答をしてはいけません。これはこのゲームの設定(正解を答えることが許可されているかどうか)に関わらず、常に守ってください。 |
| 57 | + - 誤答選択肢は日本語で、正解と同程度の分量・自然さにしてください。 |
| 58 | + - 誤答選択肢は${MAX_ANSWER_LENGTH}文字以内にしてください。 |
| 59 | + ${isMimicryAllowed ? '- このゲームでは人間の参加者が正解をそのまま登録することも許可されていますが、あなたは必ず誤答を作成してください。' : ''} |
| 60 | + ${previousAttempts.length > 0 ? stripIndent` |
| 61 | +
|
| 62 | + # 補足 |
| 63 | + 以下の誤答選択肢は、実質的に正解と同じ内容であると判定され、却下されました。これらとは異なる、正解ではないことがより明確な誤答選択肢を考えてください。 |
| 64 | + ${previousAttempts.map((attempt, i) => `${i + 1}. ${attempt}`).join('\n')} |
| 65 | + ` : ''} |
| 66 | +
|
| 67 | + 最後に、これまでの思考過程を踏まえて、以下のJSON形式のみを出力してください。それ以外の文章は一切出力しないでください。 |
| 68 | + \`\`\` |
| 69 | + {"decoyAnswer": "誤答選択肢の文字列"} |
| 70 | + \`\`\` |
| 71 | +`; |
| 72 | + |
| 73 | +const buildJudgePrompt = (question: string, answer: string, candidateAnswer: string): string => stripIndent` |
| 74 | + あなたは「たほいや」という言葉遊びゲームにおける、回答の正解判定を行う審判です。 |
| 75 | + 以下の「質問」と「正解」に対して、「判定対象の回答」が正解として扱われるべきかどうかを判定してください。 |
| 76 | +
|
| 77 | + # 質問 |
| 78 | + ${question} |
| 79 | +
|
| 80 | + # 正解 |
| 81 | + ${answer} |
| 82 | +
|
| 83 | + # 判定対象の回答 |
| 84 | + ${candidateAnswer} |
| 85 | +
|
| 86 | + 表記ゆれ・言い回しの違い・言語の違いなどは無視し、意味内容が正解と実質的に同じであれば true 、 |
| 87 | + 正解とは異なる内容であれば false としてください。 |
| 88 | +
|
| 89 | + 以下のJSON形式のみを出力してください。それ以外の文章は一切出力しないでください。 |
| 90 | + \`\`\` |
| 91 | + {"isCorrect": true または false} |
| 92 | + \`\`\` |
| 93 | +`; |
| 94 | + |
| 95 | +const generateDecoyAnswer = async ( |
| 96 | + question: string, |
| 97 | + answer: string, |
| 98 | + isMimicryAllowed: boolean, |
| 99 | + previousAttempts: string[], |
| 100 | +): Promise<string | null> => { |
| 101 | + const response = await openai.chat.completions.create({ |
| 102 | + model: MODEL, |
| 103 | + messages: [ |
| 104 | + {role: 'user', content: buildGenerationPrompt(question, answer, isMimicryAllowed, previousAttempts)}, |
| 105 | + ], |
| 106 | + max_tokens: 1024, |
| 107 | + }); |
| 108 | + |
| 109 | + const content = response?.choices?.[0]?.message?.content; |
| 110 | + if (!content) { |
| 111 | + log.warn('No content found in the decoy generation response'); |
| 112 | + return null; |
| 113 | + } |
| 114 | + |
| 115 | + const parsed = DecoyAnswerResponse.parse(extractJson(content)); |
| 116 | + return parsed.decoyAnswer.slice(0, MAX_ANSWER_LENGTH); |
| 117 | +}; |
| 118 | + |
| 119 | +const judgeIsCorrect = async (question: string, answer: string, candidateAnswer: string): Promise<boolean> => { |
| 120 | + const response = await openai.chat.completions.create({ |
| 121 | + model: MODEL, |
| 122 | + messages: [ |
| 123 | + {role: 'user', content: buildJudgePrompt(question, answer, candidateAnswer)}, |
| 124 | + ], |
| 125 | + max_tokens: 256, |
| 126 | + }); |
| 127 | + |
| 128 | + const content = response?.choices?.[0]?.message?.content; |
| 129 | + if (!content) { |
| 130 | + throw new Error('No content found in the judge response'); |
| 131 | + } |
| 132 | + |
| 133 | + const parsed = JudgeResponse.parse(extractJson(content)); |
| 134 | + return parsed.isCorrect; |
| 135 | +}; |
| 136 | + |
| 137 | +// Returns null if generation fails, the API is unavailable, or every attempt ends up |
| 138 | +// being judged as a correct answer, so the caller can just skip AI participation. |
| 139 | +export const getArbitraryAIAnswer = async ( |
| 140 | + question: string, |
| 141 | + answer: string, |
| 142 | + isMimicryAllowed: boolean, |
| 143 | +): Promise<string | null> => { |
| 144 | + const previousAttempts: string[] = []; |
| 145 | + |
| 146 | + for (let attempt = 1; attempt <= MAX_GENERATION_ATTEMPTS; attempt++) { |
| 147 | + let decoyAnswer: string | null = null; |
| 148 | + |
| 149 | + try { |
| 150 | + decoyAnswer = await generateDecoyAnswer(question, answer, isMimicryAllowed, previousAttempts); |
| 151 | + } catch (error) { |
| 152 | + log.error(`Failed to generate decoy answer (attempt ${attempt}): ${(error as Error)?.message ?? error}`); |
| 153 | + return null; |
| 154 | + } |
| 155 | + |
| 156 | + if (!decoyAnswer) { |
| 157 | + return null; |
| 158 | + } |
| 159 | + |
| 160 | + try { |
| 161 | + const isCorrect = await judgeIsCorrect(question, answer, decoyAnswer); |
| 162 | + if (!isCorrect) { |
| 163 | + return decoyAnswer; |
| 164 | + } |
| 165 | + log.warn(`Decoy answer "${decoyAnswer}" was judged as correct (attempt ${attempt}/${MAX_GENERATION_ATTEMPTS})`); |
| 166 | + } catch (error) { |
| 167 | + log.error(`Failed to judge decoy answer (attempt ${attempt}): ${(error as Error)?.message ?? error}`); |
| 168 | + return null; |
| 169 | + } |
| 170 | + |
| 171 | + previousAttempts.push(decoyAnswer); |
| 172 | + } |
| 173 | + |
| 174 | + log.warn(`Gave up generating a decoy answer for question "${question}" after ${MAX_GENERATION_ATTEMPTS} attempts`); |
| 175 | + return null; |
| 176 | +}; |
0 commit comments