컴퓨터 플레이어 + 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>
This commit is contained in:
EJClaw
2026-10-11 03:37:04 +09:00
parent 65a0f34d93
commit 13974181e7
17 changed files with 1030 additions and 5 deletions

View File

@@ -0,0 +1,221 @@
/** Computers with the local model (docs/06 §12.1): client limits, clean lines, and how rooms use it. */
import { afterEach, describe, expect, test } from 'bun:test';
import { GAMES } from '@bg/games';
import { botProfile, isBotId } from '@bg/shared';
import { openDb } from '../db';
import { RoomManager } from '../rooms/manager';
import type { Room } from '../rooms/room';
import { RoomStore } from '../rooms/store';
import { BotBrain } from './brain';
import { cleanLine, temperOf, TEMPERS } from './lines';
import { Llm } from './llm';
/** A fake Ollama: answers with `reply(prompt)`; records the prompts. */
function fakeOllama(reply: (user: string, body: { format?: unknown }) => string | Error) {
const prompts: string[] = [];
const fetchFn = (async (_url: string, init: RequestInit) => {
const body = JSON.parse(String(init.body)) as { messages: { role: string; content: string }[]; format?: unknown };
const user = body.messages.find((m) => m.role === 'user')!.content;
prompts.push(user);
const r = reply(user, body);
if (r instanceof Error) throw r;
return new Response(JSON.stringify({ message: { content: r } }), { headers: { 'content-type': 'application/json' } });
}) as unknown as typeof fetch;
return { fetchFn, prompts };
}
describe('Llm client', () => {
test('returns the text; a few failures in a row back off; a full queue is refused at once', async () => {
let fail = false;
const { fetchFn } = fakeOllama(() => (fail ? new Error('down') : '안녕'));
let now = 0;
const llm = new Llm({ url: 'http://x', model: 'm', fetch: fetchFn, now: () => now, maxQueue: 0, maxConcurrent: 1 });
expect(await llm.chat([{ role: 'user', content: 'hi' }])).toBe('안녕');
fail = true;
for (let i = 0; i < 3; i++) expect(await llm.chat([{ role: 'user', content: 'hi' }])).toBeNull();
expect(llm.available()).toBe(false);
expect(await llm.chat([{ role: 'user', content: 'hi' }])).toBeNull(); // skipped, not even sent
expect(llm.stats.skipped).toBe(1);
now += 31_000;
fail = false;
expect(llm.available()).toBe(true);
// One running, no waiting room: the second is refused immediately.
const a = llm.chat([{ role: 'user', content: 'a' }]);
const b = await llm.chat([{ role: 'user', content: 'b' }]);
expect(b).toBeNull();
expect(await a).toBe('안녕');
});
test('a hung model times out', async () => {
const hang = (async (_u: string, init: RequestInit) =>
new Promise((_, rej) => init.signal!.addEventListener('abort', () => rej(new Error('aborted'))))) as unknown as typeof fetch;
const llm = new Llm({ url: 'http://x', model: 'm', fetch: hang, timeoutMs: 30 });
expect(await llm.chat([{ role: 'user', content: 'hi' }])).toBeNull();
expect(llm.stats.failed).toBe(1);
});
});
describe('clean lines', () => {
test('one short Korean line; quotes, names and markdown stripped; foreign, AI talk and bad words refused', () => {
expect(cleanLine('"흐음, 또 막았네? 😎 잘 봤다!"')).toBe('흐음, 또 막았네? 😎 잘 봤다!');
expect(cleanLine('컴퓨터 2: 이번엔 내가 이긴다!\n두 번째 줄')).toBe('이번엔 내가 이긴다!');
expect(cleanLine('**좋아요**')).toBe('좋아요');
expect(cleanLine('철수님真爱吗')).toBeNull();
expect(cleanLine('Nice move, buddy!')).toBeNull();
expect(cleanLine('저는 AI라서 잘 몰라요')).toBeNull();
expect(cleanLine('시발 뭐야')).toBeNull();
expect(cleanLine('www.example.com 와봐')).toBeNull();
expect(cleanLine('나 마피아임 ㅋㅋ', 40, [/(나|저)\s*마피아/])).toBeNull();
// Too long: cut at a sentence end, or refused when there is none early enough.
expect(cleanLine('이번 판은 정말 재밌겠네요. 다들 준비됐나요', 20)).toBe('이번 판은 정말 재밌겠네요.');
expect(cleanLine('가'.repeat(80), 20)).toBeNull();
});
test('every computer has one of five characters, fixed by its id', () => {
const seen = new Set(Array.from({ length: 200 }, (_, i) => temperOf(`bot:${i}:x`).key));
expect(seen.size).toBe(TEMPERS.length);
expect(temperOf('bot:1:abc')).toBe(temperOf('bot:1:abc'));
});
});
// ---------------------------------------------------------------- rooms
const rooms: Room[] = [];
afterEach(() => {
for (const r of rooms.splice(0)) r.clearTimer();
});
function harness(reply: (user: string, body: { format?: unknown }) => string | Error, random = () => 0) {
const db = openDb(':memory:');
const store = new RoomStore(db);
let now = 1_000_000;
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id === 'A' ? '철수' : id, avatar: null, kind: 'guest' as const } };
const { fetchFn, prompts } = fakeOllama(reply);
const ai = new Llm({ url: 'http://gpu', model: 'gemma3:4b', fetch: fetchFn });
const slept: number[] = [];
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0, ai, aiRandom: random, aiSleep: async (ms) => {
// Typing takes time on the room clock too.
slept.push(ms);
clock.advance(ms);
} });
const conn = (userId: string) => {
const msgs: import('@bg/shared').ServerMessage[] = [];
return { userId, msgs, send: (m: (typeof msgs)[number]) => msgs.push(m), close: () => {} };
};
return { manager, clock, conn, prompts, slept, store };
}
const settle = () => new Promise((r) => setTimeout(r, 5));
describe('rooms with the model', () => {
test('omok: the computer thinks (visible), types a taunt in the chat, then moves', async () => {
const h = harness((u) => (u.includes('할 말') ? '흐음, 여기 두면 아프겠는데?' : '좋아'));
const room = h.manager.createPractice('A', 'omok') as Room;
rooms.push(room);
const a = h.conn('A');
room.join(a, 'player');
room.configure('A', { options: { ...(room.config.options as object), colorAssignment: 'hostBlack' } });
expect(room.start('A')).toBeNull();
await settle();
room.act('A', 1, { type: 'place', x: 7, y: 7 });
const activity = a.msgs.filter((m) => m.t === 'room').map((m) => (m as { room: { botActivity?: Record<string, string> } }).room.botActivity ?? {});
expect(activity.some((x) => Object.values(x).includes('thinking'))).toBe(true);
room.bots.fire();
for (let i = 0; i < 20 && (room.game!.state as { moves: unknown[] }).moves.length < 2; i++) await settle();
expect((room.game!.state as { moves: unknown[] }).moves).toHaveLength(2);
const chats = a.msgs.filter((m) => m.t === 'chat') as { from: { id: string } | null; text: string }[];
expect(chats.some((c) => c.from && isBotId(c.from.id) && c.text === '흐음, 여기 두면 아프겠는데?')).toBe(true);
// It typed for a while before sending, and "입력 중" was shown then cleared.
expect(h.slept.some((ms) => ms >= 900)).toBe(true);
const last = a.msgs.filter((m) => m.t === 'room').at(-1) as { room: { botActivity?: object } };
expect(last.room.botActivity).toBeUndefined();
expect(h.prompts.some((p) => p.includes('오목'))).toBe(true);
});
test('a person asks a computer by name: it answers in the room chat', async () => {
const h = harness(() => '저요? 저 오목 잘 둬요 ㅎㅎ', () => 0.99);
const room = h.manager.createPractice('A', 'omok') as Room;
rooms.push(room);
const a = h.conn('A');
room.join(a, 'player');
expect(room.start('A')).toBeNull();
room.chat('A', '컴퓨터 1 오목 잘해?');
for (let i = 0; i < 20 && !a.msgs.some((m) => m.t === 'chat' && (m as { text: string }).text.startsWith('저요?')); i++) await settle();
expect(a.msgs.some((m) => m.t === 'chat' && (m as { text: string }).text === '저요? 저 오목 잘 둬요 ㅎㅎ')).toBe(true);
expect(h.prompts.at(-1)).toContain('컴퓨터 1 오목 잘해?');
});
test('without a model, or with a model that is down, computers play silently as before', async () => {
const h = harness(() => new Error('down'));
const room = h.manager.createPractice('A', 'omok') as Room;
rooms.push(room);
const a = h.conn('A');
room.join(a, 'player');
room.configure('A', { options: { ...(room.config.options as object), colorAssignment: 'hostBlack' } });
expect(room.start('A')).toBeNull();
for (let i = 0; i < 3; i++) {
room.act('A', i + 1, { type: 'place', x: [0, 14, 0][i]!, y: [0, 14, 14][i]! }); // corners: the computer never needs them
room.bots.fire();
for (let k = 0; k < 20 && (room.game!.state as { moves: unknown[] }).moves.length < 2 * (i + 1); k++) await settle();
}
expect((room.game!.state as { moves: unknown[] }).moves.length).toBe(6);
expect(a.msgs.some((m) => m.t === 'chat')).toBe(false);
});
test('바퀴벌레 포커: the model decides truth or bluff; telling the truth sets the real kind', async () => {
let checked = false;
// The starter is random: try new rooms until the computer offers first.
for (let attempt = 0; attempt < 12 && !checked; attempt++) {
const h = harness((_u, body) => (body.format ? JSON.stringify({ bluff: false, say: '이건 진짜야, 믿어봐~' }) : '흠'));
const room = h.manager.createPractice(`A${attempt}`, 'cockroach-poker') as Room;
rooms.push(room);
const a = h.conn(`A${attempt}`);
room.join(a, 'player');
expect(room.start(`A${attempt}`)).toBeNull();
const st = () => room.game!.state as { round: { claim: string | null; card: string | null; starter: string } };
if (!isBotId(st().round.starter)) continue;
await settle(); // the start greeting goes out first
h.clock.advance(20_000);
for (let i = 0; i < 30 && !st().round.claim; i++) {
room.bots.fire();
await settle();
}
const kind = st().round.card!.replace(/-\d+$/, '');
expect(st().round.claim).toBe(kind);
expect(a.msgs.some((m) => m.t === 'chat' && (m as { text: string }).text === '이건 진짜야, 믿어봐~')).toBe(true);
checked = true;
}
expect(checked).toBe(true);
});
test('마피아: a computer says its planned line in its own words; a line claiming a role is thrown away', async () => {
let n = 0;
const h = harness(() => (n++ % 2 === 0 ? '안녕하세요~ 오늘 마피아 꼭 잡아봐요!' : '저 경찰이에요 믿어주세요'));
const room = h.manager.createPractice('A', 'mafia') as Room;
rooms.push(room);
room.join(h.conn('A'), 'player');
expect(room.start('A')).toBeNull();
for (let i = 0; i < 4 * 40; i++) {
h.clock.advance(250);
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
const d = room.effectiveDeadline();
if (d !== null && d <= h.clock.now()) room.onTimer();
await settle();
}
const chat = (room.game!.state as { chat: { from: string; channel: string; text: string }[] }).chat.filter((m) => isBotId(m.from) && m.channel === 'day');
expect(chat.length).toBeGreaterThan(0);
expect(chat.some((m) => m.text === '안녕하세요~ 오늘 마피아 꼭 잡아봐요!')).toBe(true);
expect(chat.some((m) => m.text === '저 경찰이에요 믿어주세요')).toBe(false);
});
});
test('BotBrain typing time grows with the line and stays human (0.9~6.5 s)', () => {
const brain = new BotBrain({} as never, null);
const short = brain.typingMs('bot:1:x', 'ㅋㅋ');
const long = brain.typingMs('bot:1:x', '이번 판은 내가 무조건 이긴다 각오해라 진짜로');
expect(short).toBeGreaterThanOrEqual(900);
expect(long).toBeGreaterThan(short);
expect(long).toBeLessThanOrEqual(6500);
});

254
apps/server/src/ai/brain.ts Normal file
View File

@@ -0,0 +1,254 @@
/**
* A room's computers, played like people with the local model (docs/06 §12.1).
*
* - They show what they are doing: "생각 중…" while choosing a move and "입력 중…" while typing, for as long as a
* person would take to type that line — then they send it and make the move ("채팅 치고 클릭").
* - They talk in character (도발형·허세형·차분형·수다형·소심형, 존댓말/반말): a word with their own move, a reaction
* to a person's move, answers when people chat, a greeting at the start and a word at the end.
* - Psychological choices go to the model: in 바퀴벌레 포커 it decides whether to tell the truth or bluff, and says
* something to sell it. In 마피아 it says each line of the computer's plan in its own words.
* Moves themselves still come from each game's computer strategy (it sees only its own screen). Without a model
* (not configured, busy, down) the computers simply play as before, silently, and 마피아 uses its built-in lines.
*/
import { botPace, hash01 } from '@bg/games/bots';
import type { Llm } from './llm';
import { cleanLine, decide, temperOf, writeLine, type LineRequest } from './lines';
export type BotActivity = 'thinking' | 'typing';
export interface BrainRoom {
gameId(): string;
gameName(): string;
nameOf(id: string): string;
/** People and computers seated in the running game. */
humans(): string[];
bots(): string[];
playing(): boolean;
/** Posts in the room chat as `bot` (games without their own chat channels). */
roomChat(bot: string, text: string): void;
setActivity(bot: string, a: BotActivity | null): void;
recentChat(): { from: string; text: string }[];
now(): number;
}
/** A few words for what someone just did (any game). */
const ACTION_KO: Record<string, string> = {
place: '돌을 놓음', move: '말을 움직임', MOVE: '말을 움직임', placeWall: '벽을 세움', castle: '캐슬링',
play: '카드를 냄', discard: '패를 버림', DISCARD: '패를 버림', draw: '패를 가져옴', pass: '넘김', PASS: '넘김',
call: '콜', check: '체크', die: '다이(포기)', half: '하프 베팅', quarter: '쿼터 베팅', ddadang: '따당', full: '풀 베팅',
roll: '주사위를 굴림', hold: '주사위를 고정함', score: '점수를 적음', guess: '추리함', stop: '멈춤', continue: '계속 추리',
offer: '카드를 건넴', peek: '카드를 몰래 봄', claim: '선언함', declare: '선언함', tsumo: '쯔모', ring: '종을 침',
flip: '카드를 뒤집음', BUY: '땅을 삼', sell: '땅을 팖', THROW: '윷을 던짐', commit: '타일을 내려놓음', goStop: '고/스톱',
respond: '대답함', resign: '기권', concede: '기권', CONCEDE: '기권', giveUp: '포기', choose: '골랐음', vote: '투표',
};
const sleepReal = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
export class BotBrain {
private lastRoomLine = -Infinity;
private lastBotLine = new Map<string, number>();
private happened: string[] = [];
private typing = new Set<string>();
constructor(
private room: BrainRoom,
readonly llm: Llm | null,
private random: () => number = Math.random,
private sleep: (ms: number) => Promise<void> = sleepReal,
) {}
/** The model is set up and answering, and there is someone to play for. */
enabled(): boolean {
return !!this.llm && this.llm.available() && this.room.playing() && this.room.humans().length > 0;
}
/** How long `bot` takes to type `text` (each computer types at its own speed). */
typingMs(bot: string, text: string): number {
const perChar = (120 + 90 * hash01(bot, 'typing')) * botPace(bot);
return Math.round(Math.min(6500, Math.max(900, [...text].length * perChar)));
}
thinking(bot: string, on: boolean): void {
if (!this.typing.has(bot)) this.room.setActivity(bot, on ? 'thinking' : null);
}
/** "입력 중…" for as long as typing takes, then `send` (skipped if the game ended meanwhile). */
async type(bot: string, text: string, send: () => void, needPlaying = true): Promise<void> {
this.typing.add(bot);
this.room.setActivity(bot, 'typing');
try {
await this.sleep(this.typingMs(bot, text));
} finally {
this.typing.delete(bot);
this.room.setActivity(bot, null);
}
if (!needPlaying || this.room.playing()) send();
}
private request(bot: string, situation: string, task: string, extra: Partial<LineRequest> = {}): LineRequest {
return {
bot,
name: this.room.nameOf(bot),
game: this.room.gameName(),
situation,
task,
recent: this.room.recentChat(),
...extra,
};
}
private canTalk(bot: string, roomGap = 8000, botGap = 20_000): boolean {
const now = this.room.now();
return now - this.lastRoomLine >= roomGap && now - (this.lastBotLine.get(bot) ?? -Infinity) >= botGap && !this.typing.has(bot);
}
private spoke(bot: string): void {
const now = this.room.now();
this.lastRoomLine = now;
this.lastBotLine.set(bot, now);
}
private say(bot: string, line: string): Promise<void> {
this.spoke(bot);
return this.type(bot, line, () => this.room.roomChat(bot, line));
}
private situation(): string {
const last = this.happened.slice(-4);
return last.length ? `최근: ${last.join(', ')}` : '게임이 막 시작됐다';
}
/** Someone played: remembered for the computers' sense of the game; now and then a computer reacts to a person. */
onAction(actor: string, action: unknown): void {
const type = String((action as { type?: string } | null)?.type ?? '');
if (!type || type === 'chat' || type === 'say' || type === 'reaction' || type === 'ping' || type === 'timeout') return;
this.happened.push(`${this.room.nameOf(actor)} ${ACTION_KO[type] ?? '행동함'}`);
if (this.happened.length > 12) this.happened.shift();
if (!this.enabled() || this.room.bots().includes(actor) || this.room.gameId() === 'mafia') return;
const bots = this.room.bots().filter((b) => this.canTalk(b, 10_000, 30_000));
if (!bots.length || this.random() > 0.12) return;
const bot = bots[Math.floor(this.random() * bots.length)]!;
this.spoke(bot);
const who = this.room.nameOf(actor);
void writeLine(this.llm, this.request(bot, this.situation(), `${who}이(가) 방금 ${ACTION_KO[type] ?? '수를 뒀다'}. ${who}에게 반응하는 한마디(놀리거나 떠보기).`)).then((line) => {
if (line) return this.type(bot, line, () => this.room.roomChat(bot, line));
});
}
/**
* Before a computer's own move: maybe a word with it (typed first, then the move), and in 바퀴벌레 포커 the
* truth-or-bluff choice. Returns the action to play (possibly with a different claim).
*/
async beforeMove(bot: string, action: unknown, view: unknown): Promise<unknown> {
if (!this.enabled()) return action;
let act = action;
let line: string | null = null;
const a = action as { type?: string; claim?: string; cardId?: string; to?: string };
if (this.room.gameId() === 'cockroach-poker' && (a.type === 'offer' || a.type === 'pass') && a.claim) {
const r = await this.cockroachBluff(bot, a, view);
if (r) {
act = r.action;
line = r.say;
}
} else if (this.canTalk(bot) && this.random() < temperOf(bot).talk) {
const type = String(a.type ?? '');
line = await writeLine(this.llm, this.request(bot, this.situation(), `나는 지금 "${ACTION_KO[type] ?? '내 수'}"를 하려 한다. 이 수를 두며 상대에게 던지는 도발이나 심리전 한마디.`));
}
if (line && this.room.playing()) {
await this.say(bot, line);
await this.sleep(Math.round((300 + 500 * this.random()) * botPace(bot)));
}
return act;
}
/** 바퀴벌레 포커: the model decides to tell the truth or bluff (and what to say); the strategy picked card and person. */
private async cockroachBluff(bot: string, a: { type?: string; claim?: string; cardId?: string; to?: string }, view: unknown): Promise<{ action: unknown; say: string | null } | null> {
const v = view as { myHand?: { kind: string; ids: string[] }[]; card?: { known: boolean; kind?: string } | null; fronts?: Record<string, { counts: Record<string, number> }> };
const kind = a.type === 'offer' ? v.myHand?.find((g) => g.ids.includes(a.cardId!))?.kind : v.card?.known ? v.card.kind : undefined;
if (!kind || !a.to) return null;
const KO: Record<string, string> = { cockroach: '바퀴벌레', bat: '박쥐', fly: '파리', toad: '두꺼비', rat: '쥐', scorpion: '전갈', spider: '거미', stinkbug: '노린재' };
const target = this.room.nameOf(a.to);
const front = v.fronts?.[a.to]?.counts ?? {};
const pile = Object.entries(front).filter(([, n]) => n > 0).map(([k, n]) => `${KO[k] ?? k} ${n}장`).join(', ') || '없음';
const r = await decide<{ bluff: boolean; say: string }>(
this.llm,
bot,
this.room.nameOf(bot),
`바퀴벌레 포커. 나는 ${target}에게 카드를 건넨다. 실제 카드는 ${KO[kind] ?? kind}다. ${target}의 앞마당: ${pile}.\n` +
`진짜 이름을 말할지(bluff=false) 다른 벌레라고 거짓말할지(bluff=true) 정하고, 건네며 할 한마디(say, 30자 이내, 실제 카드를 밝히지 말 것)를 정해.`,
{ type: 'object', properties: { bluff: { type: 'boolean' }, say: { type: 'string' } }, required: ['bluff', 'say'] },
);
if (!r) return null;
let claim = a.claim!;
if (r.bluff && claim === kind) claim = Object.keys(KO).filter((k) => k !== kind)[Math.floor(this.random() * 7)]!;
if (!r.bluff) claim = kind;
// The line must not give the real card away.
const say = cleanLine(String(r.say ?? ''), 36, [new RegExp(KO[kind] ?? kind)]);
// Selling the claim is part of the move, so it is said even right after another line.
return { action: { ...a, claim }, say };
}
/** People chatting: a named computer answers; otherwise sometimes one of them joins in. */
onHumanChat(from: string, text: string): void {
if (!this.enabled() || this.room.gameId() === 'mafia') return;
const bots = this.room.bots();
const named = bots.find((b) => {
const n = /^컴퓨터 (\d+)$/.exec(this.room.nameOf(b))?.[1];
return n ? new RegExp(`(컴퓨터\\s?${n}|컴${n}|(?<![0-9])${n}번)(?![0-9])`).test(text) : false;
});
const bot = named ?? (this.random() < 0.4 ? bots[Math.floor(this.random() * bots.length)] : undefined);
if (!bot || this.typing.has(bot)) return;
this.spoke(bot);
const who = this.room.nameOf(from);
void writeLine(this.llm, this.request(bot, this.situation(), `${who}이(가) 채팅으로 "${text.slice(0, 100)}"라고 했다. 같이 게임하는 사람으로서 대답한다. 질문이면 그 질문에 직접 답하고(성격대로, 허세·도발·엄살 가능), 질문이 아니면 맞장구치거나 받아친다.`)).then((line) => {
if (line) return this.type(bot, line, () => this.room.roomChat(bot, line));
});
}
onGameStart(): void {
this.happened = [];
if (!this.enabled() || this.room.gameId() === 'mafia' || this.random() > 0.7) return;
const bots = this.room.bots();
const bot = bots[Math.floor(this.random() * bots.length)];
if (!bot) return;
this.spoke(bot);
void writeLine(this.llm, this.request(bot, '게임이 막 시작됐다', '시작 인사 겸 가벼운 선전포고 한마디.')).then((line) => {
if (line) return this.type(bot, line, () => this.room.roomChat(bot, line));
});
}
/** The game ended: a computer that won gloats a little, or one that lost takes it with a word. */
onGameEnd(ranking: string[][]): void {
if (!this.llm?.available() || !this.room.humans().length || this.room.gameId() === 'mafia' || this.random() > 0.85) return;
const bots = this.room.bots();
const winner = (ranking[0] ?? []).find((p) => bots.includes(p));
const bot = winner ?? bots[Math.floor(this.random() * bots.length)];
if (!bot) return;
const task = winner ? '내가 이겼다. 상대를 살짝 놀리며 이긴 소감 한마디(한 판 더 하자고 해도 좋다).' : '내가 졌다. 아쉬워하며 다음엔 이기겠다는 한마디.';
void writeLine(this.llm, this.request(bot, '게임이 끝났다', task)).then((line) => {
if (line) return this.type(bot, line, () => this.room.roomChat(bot, line), false);
});
}
/**
* 마피아: a computer's planned line (`hint` = what it means, `text` = built-in wording) in its own words. The model is
* told only what the line means and the public chat — never the computer's role — and a line that claims a role
* or "I'm mafia" is thrown away. Returns the built-in text when there is no usable answer.
*/
async mafiaLine(bot: string, hint: string, text: string, recent: { from: string; text: string }[]): Promise<string> {
if (!this.llm?.available()) return text;
const line = await writeLine(this.llm, {
bot,
name: this.room.nameOf(bot),
game: '마피아(낮 토론, 모두가 보는 채팅)',
situation: '누가 마피아인지 추리하며 이야기하는 중이다. 너는 자신이 시민 팀이라고 말한다.',
task: hint,
recent,
example: text,
maxLen: 45,
// Never a role claim of its own ("저 경찰이에요", "나 마피아임"): the plan decides those, word for word.
forbid: [/(저|제가|나|내가|난|전)\s*(는|가|도)?\s*(진짜\s*)?(마피아|경찰|의사|군인|정치인|영매|연인)/],
});
return line ?? text;
}
}

125
apps/server/src/ai/lines.ts Normal file
View File

@@ -0,0 +1,125 @@
/**
* 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;
}
}

123
apps/server/src/ai/llm.ts Normal file
View File

@@ -0,0 +1,123 @@
/**
* Local language model on the GPU (Ollama, docs/11 §8). Used by computer players to talk and think out loud
* (docs/06 §12.1). Everything here is best effort: when the model is slow, busy or down the caller gets `null`
* and the computers fall back to their built-in lines — a game never waits on the model.
*/
export interface LlmMessage {
role: 'system' | 'user' | 'assistant';
content: string;
}
export interface LlmConfig {
/** Ollama base URL, e.g. http://192.168.10.9:11434. */
url: string;
model: string;
/** Requests running at once (one GPU). */
maxConcurrent?: number;
/** Requests allowed to wait; more are refused at once (the caller uses a built-in line). */
maxQueue?: number;
timeoutMs?: number;
/** How long Ollama keeps the model in GPU memory after the last request. */
keepAlive?: string;
fetch?: typeof fetch;
log?: (level: 'info' | 'warn' | 'error', msg: string, extra?: Record<string, unknown>) => void;
now?: () => number;
}
export interface LlmStats {
model: string;
requests: number;
ok: number;
failed: number;
/** Refused because the queue was full or the model was backing off. */
skipped: number;
avgMs: number;
lastError: string | null;
backingOffUntil: number | null;
}
export class Llm {
private running = 0;
private waiting: (() => void)[] = [];
private totalMs = 0;
private backoffUntil = 0;
private failures = 0;
readonly stats: LlmStats;
constructor(private cfg: LlmConfig) {
this.stats = { model: cfg.model, requests: 0, ok: 0, failed: 0, skipped: 0, avgMs: 0, lastError: null, backingOffUntil: null };
}
private now(): number {
return this.cfg.now ? this.cfg.now() : Date.now();
}
/** False while backing off after errors (then callers don't even try). */
available(): boolean {
return this.now() >= this.backoffUntil;
}
/**
* One chat completion. `format` is a JSON schema for structured answers. Returns the text, or null when it could
* not be had in time (busy, down, timeout).
*/
async chat(messages: LlmMessage[], opts: { maxTokens?: number; temperature?: number; format?: object; timeoutMs?: number } = {}): Promise<string | null> {
this.stats.requests++;
const full = this.running >= (this.cfg.maxConcurrent ?? 2) && this.waiting.length >= (this.cfg.maxQueue ?? 6);
if (!this.available() || full) {
this.stats.skipped++;
return null;
}
if (this.running >= (this.cfg.maxConcurrent ?? 2)) await new Promise<void>((r) => this.waiting.push(r));
this.running++;
const t0 = this.now();
const ctl = new AbortController();
const timer = setTimeout(() => ctl.abort(), opts.timeoutMs ?? this.cfg.timeoutMs ?? 6000);
try {
const res = await (this.cfg.fetch ?? fetch)(`${this.cfg.url.replace(/\/$/, '')}/api/chat`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
signal: ctl.signal,
body: JSON.stringify({
model: this.cfg.model,
messages,
stream: false,
keep_alive: this.cfg.keepAlive ?? '30m',
...(opts.format ? { format: opts.format } : {}),
options: { temperature: opts.temperature ?? 0.9, num_predict: opts.maxTokens ?? 80 },
}),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const body = (await res.json()) as { message?: { content?: string } };
const text = body.message?.content ?? '';
const ms = this.now() - t0;
this.stats.ok++;
this.totalMs += ms;
this.stats.avgMs = Math.round(this.totalMs / this.stats.ok);
this.failures = 0;
return text;
} catch (err) {
this.stats.failed++;
this.stats.lastError = String(err).slice(0, 200);
this.failures++;
// A few failures in a row: stop asking for a while (30 s, up to 5 min) instead of slowing every move.
if (this.failures >= 3) {
this.backoffUntil = this.now() + Math.min(300_000, 30_000 * 2 ** (this.failures - 3));
this.stats.backingOffUntil = this.backoffUntil;
this.cfg.log?.('warn', 'ai backing off', { failures: this.failures, err: this.stats.lastError });
}
return null;
} finally {
clearTimeout(timer);
this.running--;
this.waiting.shift()?.();
}
}
/** Loads the model into GPU memory ahead of the first real request (the first load takes ~20 s). */
async warm(): Promise<boolean> {
const r = await this.chat([{ role: 'user', content: '안녕' }], { maxTokens: 1, timeoutMs: 60_000 });
return r !== null;
}
}