Files
joke-app/apps/server/src/ai/lines.ts
EJClaw 13974181e7 컴퓨터 플레이어 + GPU 로컬 모델(gemma3:4b): 생각 중/입력 중 표시, 성격대로 채팅·도발·심리전, 바퀴벌레 포커 블러핑, 마피아 대사
- ai/llm.ts: Ollama 클라이언트(동시 2개·대기열·시간 제한·연속 실패 시 쉬기), 꺼져 있으면 예전처럼 조용히 둔다
- ai/lines.ts: 성격 5가지(도발·허세·차분·수다·소심)×말투(존댓말/반말), 한 줄 정리(외국어·AI 말·욕·링크 거르기)
- ai/brain.ts: 수 두기 전 생각 중… → 가끔 입력 중…(타자 시간) → 채팅 → 수, 사람 수에 반응, 이름 부르면 대답, 시작·끝 한마디
  바퀴벌레 포커: 진실/블러핑과 건네는 말을 모델이 정함. 마피아: 계획한 대사를 모델이 자기 말로(직업 주장은 버림)
- RoomView.botActivity + 화면 표시(상태 줄, 채팅 칸), AI_URL/AI_MODEL 설정, /healthz에 ai 통계
- 테스트: 클라이언트·정리·방 동작(가짜 모델), 실제 GPU 모델 브라우저 E2E(e2e/ai.e2e.ts)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 03:37:04 +09:00

126 lines
5.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* What a computer says, written by the local model (docs/06 §12.1): a character (성격 + 말투) per computer, a prompt
* per moment, and a strict clean-up so only one short, kind, Korean chat line ever reaches people.
*/
import { botPersona, hash01 } from '@bg/games/bots';
import { chatProblem } from '@bg/games/mafia';
import type { Llm, LlmMessage } from './llm';
export interface Temper {
key: 'taunt' | 'bluff' | 'calm' | 'chatty' | 'timid';
ko: string;
desc: string;
/** How often it speaks up on its own move (before rate limits). */
talk: number;
}
export const TEMPERS: readonly Temper[] = [
{ key: 'taunt', ko: '도발형', desc: '장난스럽게 상대를 도발하고 약을 올린다. 그래도 욕이나 비하는 절대 하지 않는다.', talk: 0.32 },
{ key: 'bluff', ko: '허세형', desc: '자신감이 넘치고 허세를 부린다. 질 것 같아도 이길 거라고 큰소리친다.', talk: 0.28 },
{ key: 'calm', ko: '차분형', desc: '차분하고 담담하다. 짧게 말하고, 가끔 날카로운 한마디로 심리전을 건다.', talk: 0.14 },
{ key: 'chatty', ko: '수다형', desc: '말이 많고 리액션이 크다. 감탄사를 자주 쓴다.', talk: 0.38 },
{ key: 'timid', ko: '소심형', desc: '소심하고 엄살이 많다. 걱정하는 척하면서 은근히 상대를 떠본다.', talk: 0.18 },
];
/** Each computer's character: 성격 from its id, 말투 from 똑똑한 편(존댓말)/허술한 편(반말). */
export function temperOf(bot: string): Temper {
return TEMPERS[Math.floor(hash01(bot, 'temper') * TEMPERS.length)]!;
}
export function speechOf(bot: string): string {
return botPersona(bot).smart ? '존댓말(해요체), 또박또박' : '반말, 짧고 가볍게, ㅋㅋ를 가끔 붙임';
}
export function systemPrompt(bot: string, name: string, maxLen: number): string {
const t = temperOf(bot);
return [
`너는 온라인 보드게임 사이트 "같이 놀자"에서 사람들과 함께 게임하는 컴퓨터 플레이어 "${name}"이다.`,
`성격: ${t.ko} — ${t.desc}`,
`말투: ${speechOf(bot)}.`,
`규칙: 한국어 채팅 한 줄만 쓴다. ${maxLen}자 이내. 대사만 쓰고 따옴표·설명·괄호·영어·한자는 쓰지 않는다.`,
'욕설, 비하, 외모·성별·나이 언급, 개인정보, 링크는 절대 쓰지 않는다. 게임과 상관없는 이야기는 하지 않는다.',
'자신이 AI나 프로그램이라고 말하지 않는다. 숨겨진 정보(내 패, 내 카드, 내 직업)는 절대 밝히지 않는다.',
].join('\n');
}
export interface LineRequest {
bot: string;
name: string;
game: string;
/** What is going on, in plain Korean. */
situation: string;
/** What to say now. */
task: string;
/** Recent chat, oldest first. */
recent?: { from: string; text: string }[];
/** Example line (the built-in one), so the model keeps the meaning. */
example?: string;
maxLen?: number;
/** Extra patterns the line must not contain (e.g. a mafia computer saying it is mafia). */
forbid?: RegExp[];
}
const AI_WORDS = /인공\s*지능|\bAI\b|챗봇|언어\s*모델|어시스턴트|프로그램입니다|GPT|모델로서/i;
const FOREIGN = /[一-鿿぀-ヿ]|[A-Za-z]{4,}/;
/** One clean chat line out of whatever the model wrote, or null when nothing usable is left. */
export function cleanLine(raw: string, maxLen = 40, forbid: RegExp[] = []): string | null {
let line = raw
.split('\n')
.map((l) => l.trim())
.find((l) => l.length > 0);
if (!line) return null;
line = line
.replace(/^[^::]{1,12}[::]\s*/, (m) => (/[ㄱ-ㅎ가-힣]/.test(m) && m.length <= 12 ? '' : m)) // "컴퓨터 2: …"
.replace(/^["'“”‘’`「」『』]+|["'“”‘’`「」『』]+$/g, '')
.replace(/[*_#>]/g, '')
.replace(/\s+/g, ' ')
.trim();
if (!line || FOREIGN.test(line) || AI_WORDS.test(line)) return null;
if ([...line].length > maxLen) {
const chars = [...line];
const cut = chars.slice(0, maxLen).join('');
const end = Math.max(cut.lastIndexOf('.'), cut.lastIndexOf('!'), cut.lastIndexOf('?'), cut.lastIndexOf('~'));
if ([...line].length > maxLen * 1.6 || end < maxLen * 0.4) return null;
line = cut.slice(0, end + 1);
}
if (!/[가-힣ㅋㅎㅠ]/.test(line)) return null;
if (chatProblem(line, true)) return null;
if (forbid.some((re) => re.test(line!))) return null;
return line;
}
/** Asks the model for one line; null when the model is unavailable or wrote nothing usable. */
export async function writeLine(llm: Llm | null, req: LineRequest): Promise<string | null> {
if (!llm || !llm.available()) return null;
const maxLen = req.maxLen ?? 40;
const parts = [`게임: ${req.game}`, `상황: ${req.situation}`];
if (req.recent?.length) parts.push(`최근 채팅:\n${req.recent.slice(-8).map((m) => `${m.from}: ${m.text}`).join('\n')}`);
if (req.example) parts.push(`예시(뜻은 같게, 표현은 너답게 새로): ${req.example}`);
parts.push(`할 말: ${req.task}`);
const messages: LlmMessage[] = [
{ role: 'system', content: systemPrompt(req.bot, req.name, maxLen) },
{ role: 'user', content: parts.join('\n') },
];
const raw = await llm.chat(messages, { maxTokens: 70, temperature: 0.95 });
return raw === null ? null : cleanLine(raw, maxLen, req.forbid);
}
/** Structured choice (JSON schema) — e.g. 바퀴벌레 포커: tell the truth or bluff, and what to say. */
export async function decide<T>(llm: Llm | null, bot: string, name: string, prompt: string, schema: object): Promise<T | null> {
if (!llm || !llm.available()) return null;
const raw = await llm.chat(
[
{ role: 'system', content: systemPrompt(bot, name, 40) + '\n대답은 요청한 JSON 형식으로만 한다.' },
{ role: 'user', content: prompt },
],
{ maxTokens: 120, temperature: 0.9, format: schema },
);
if (raw === null) return null;
try {
return JSON.parse(raw) as T;
} catch {
return null;
}
}