컴퓨터 플레이어 + 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

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;
}
}