Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

The Digital Lyceum — Core

偉人のAIペルソナがあなたの問いをめぐって議論する、その中核エンジン。 The core engine where AI personas of great minds debate your question.


日本語 | English


アーキテクチャ / Architecture

レンダリング層がコアを駆動し、コアは Express 経由でローカル Ollama にプロキシする — リクエストの全経路。 The rendering layer drives the core, which proxies through Express to a local Ollama — the full request path at a glance.

flowchart LR
    UI["Rendering layer<br/>main.js · render.js<br/>(out of scope)"]
    subgraph core["Core"]
        ENG["engine.js<br/>DiscussionEngine"]
        PR["prompts.js"]
        ST["state.js"]
        CFG["config.js"]
        API["api.js"]
    end
    subgraph srv["Express · server.js"]
        EP["/api/models<br/>/api/chat"]
        SP["streamParser.js<br/>think strip + ndjson parse"]
    end
    OLL[("Ollama")]
    UI -->|"run / onToken"| ENG
    ENG --> PR
    ENG --> ST
    ST --> CFG
    ENG -->|streamChat| API
    API -->|"HTTP /api/*"| EP
    API -.->|"shares ndjson parse"| SP
    EP --> SP
    EP -->|"POST /api/generate"| OLL
    OLL -->|"ndjson stream"| EP
Loading

日本語

The Digital Lyceum のコア部分——複数ペルソナによる議論を回すエンジン、各ペルソナを役柄に保つプロンプト構築、そしてローカルの Ollama から応答をストリーミングする Express プロキシ。

このドキュメントが扱うのはコアのみで、描画レイヤー(DOM・CSS・イベント配線)は意図的に対象外です。コアは DOM を一切知らず、プレーンなコールバックと小さなステータス用インターフェースを通じて UI とやり取りします。

コアの役割

ユーザーの問いと選択されたペルソナ群を受け取り、コアは次を行います。

  1. 毎ターン話者を選ぶ(最初はランダム、同じ話者を2連続では選ばない)。
  2. そのターンに弁証法的な動き——開始 / 反論 / 発展 / 問い——を割り当て、平行な独白ではなく互いに噛み合う応答にする。
  3. そのペルソナ向けの役柄に沿ったシステムプロンプトを組み立て、Ollama から応答をトークン単位でストリーミングする。
  4. maxTurns に達するか、エラーが起きるか、ユーザーが停止するまで繰り返す。最終ターンには結論の統合を求める。

モデルは内部で推論しますが(Ollama の think)、転送されるのは最終回答のみです。別フィールド thinking の推論は読まれず、インラインの <think>…</think> ブロックもフォールバックとして除去されます。

モジュール構成

server.js                Ollama への Express プロキシ (/api/models, /api/chat)
server/config.js         既定ポート定数(server.js と vite.config.js で共有)
server/streamParser.js   <think> 逐次除去 + 共有 NDJSON パーサー(チャンク境界安全)
src/
  api.js                 ブラウザ側 fetch 層(モデル一覧・チャットのストリーミング)
  engine.js              DiscussionEngine: ターンループ + 話者選択
  prompts.js             システム/コンテキストのプロンプト構築(弁証法)
  config.js              既定値・シードペルソナ・定数
  state.js               アプリ状態 + localStorage 永続化

描画レイヤー(src/main.js・src/render.js・src/personaColor.js・src/styles/・index.html)はここでは対象外です。

1ターンの制御フロー

sequenceDiagram
    actor U as UI
    participant E as engine.js
    participant P as prompts.js
    participant A as api.js
    participant S as server.js
    participant O as Ollama
    U->>E: run(question)
    loop maxTurns 到達 / 停止 / エラー まで
        E->>E: pickSpeaker(history)
        E->>P: buildSystemPrompt + buildContext
        E->>A: streamChat(payload, onToken)
        A->>S: POST /api/chat
        S->>O: POST /api/generate (stream)
        O-->>S: ndjson トークン (推論を含む)
        Note over S: think ブロックを除去 (streamParser)
        S-->>A: ndjson { response, done }
        A-->>E: onToken(fullTextSoFar)
        A-->>U: 逐次レンダリング
        E->>E: history.push(reply)
    end
    E-->>U: 議論の完了
Loading

streamChat は完成した応答テキストを返します。UI が必要とするフックは onToken(fullTextSoFar) だけで、これで逐次描画できます。AbortSignal により ターンを途中でキャンセルできます(stop() が使用)。

バックエンドプロキシ (server.js)

ブラウザから直接モデルへ話しかけず、ローカルの Ollama へプロキシする薄い Express サーバー(既定ポート 3005、PORT で上書き可)。

  • GET /api/models?port=<n> — Ollama の /api/tags からモデル一覧を取得。
  • POST /api/chat — ボディ { port, model, prompt, system, think }。Ollama の /api/generate に stream: true で転送し、{ response, done } の改行区切り JSON(application/x-ndjson)として再送する。

ここには2つの堅牢化が入っています。

  • thinking フォールバック — モデルが think を拒否した場合、think 無しで 一度だけ再試行する。これによりサポートしないモデルでも壊れない。
  • <think> 除去 — server/streamParser.js が <think>…</think> を逐次除去。 チャンク境界をまたぐ部分タグを保留し、TCP パケットで分割されたタグも取りこぼさない。
  • 共有 NDJSON パーサー — チャンク境界をまたぐ改行区切り JSON の再構成は server/streamParser.js の createNdjsonParser() に一元化され、サーバー(server.js) とブラウザ(src/api.js)の両方が同じ実装を使うため二重実装が分岐しない。

プロンプト構築 (prompts.js)

DOM・ネットワークコードを含めず、言い回しを一箇所に集約しています。

  • TURN_INTENTS = ['REBUT', 'BUILD', 'ASK'] — ターンごとに回して実際の噛み合いを 強制する。最初の話者は OPEN、最終ターンは結論用ディレクティブ。
  • buildSystemPrompt(persona, {isFinalTurn, otherNames, lastName, intent}) — ペルソナのプロフィール(任意の口調 exemplar)、共有の議論ルール(自分としてのみ 話す・相手を名前で呼ぶ・人名は英語表記を保つ)、そのターンのディレクティブを結合。
  • buildContext(question, history) — 元の問いに加え、進行中の会話履歴。

各シードペルソナ(config.js)は、6セクション構成(identity / worldview / method / voice / debate / constraints)のプロフィールを持ち、モデルに一つの明確な 重心と明示的なアンチパターン一覧を与えることで、無難で平板な出力を避けます。

状態と設定

  • state.js — State がペルソナ・設定・現在の選択・実行フラグを保持し、 localStorage 永続化を自前で持つ。
  • config.js — ストレージキー、DEFAULT_SETTINGS(Ollama ポート 11435、モデル、 maxTurns、thinkingMode)、TURN_DELAY_MS、MIN_PERSONAS、シードペルソナ (Socrates・Elon Musk・Alan Turing)。
  • server/config.js — DEFAULT_PORT(既定 3005)。server.js と vite.config.js が共有し、dev プロキシ先がサーバーの待受ポートとずれないようにする。

前提

  • Node 18+ と起動中の Ollama インスタンス(既定ポート 11435)。

バックエンドの起動

npm install
npm start        # Express + /api プロキシを :3005 で(あれば dist/ を配信)

npm run dev は加えて Vite フロントエンドを HMR 付きで :5173 に立て、/api を Express へプロキシします。詳細は描画レイヤーを参照。


English

The discussion core of The Digital Lyceum: the engine that runs a multi-persona debate, the prompt construction that keeps each persona in character, and the Express proxy that streams replies from a local Ollama instance.

This document covers only the core — the rendering layer (DOM, CSS, event wiring) is intentionally out of scope. The core knows nothing about the DOM and talks to the UI through plain callbacks and a small status interface.

What the core does

Given a user question and a set of selected personas, the core:

  1. Picks a speaker each turn (random first, never the same speaker twice in a row).
  2. Assigns the turn a dialectical move — open, rebut, build, or ask — so replies engage each other instead of running as parallel monologues.
  3. Builds an in-character system prompt for that persona and streams its reply from Ollama, token by token.
  4. Repeats until maxTurns is reached, an error occurs, or the user stops it. The final turn is asked to synthesize a conclusion.

The model reasons internally (Ollama think) but only its final answer is forwarded; reasoning in a separate thinking field is never read, and any inline <think>…</think> blocks are stripped as a fallback.

Modules

server.js                Express proxy to Ollama (/api/models, /api/chat)
server/config.js         default-port constant shared with vite.config.js
server/streamParser.js   incremental <think> stripper + shared NDJSON parser (chunk-safe)
src/
  api.js                 browser-side fetch layer (models, streaming chat)
  engine.js              DiscussionEngine: turn loop + speaker selection
  prompts.js             system + context prompt construction (dialectics)
  config.js              defaults, seed personas, constants
  state.js               app state + localStorage persistence

The rendering layer (src/main.js, src/render.js, src/personaColor.js, src/styles/, index.html) is excluded here.

Control flow of one turn

sequenceDiagram
    actor U as UI
    participant E as engine.js
    participant P as prompts.js
    participant A as api.js
    participant S as server.js
    participant O as Ollama
    U->>E: run(question)
    loop until maxTurns, stop, or error
        E->>E: pickSpeaker(history)
        E->>P: buildSystemPrompt + buildContext
        E->>A: streamChat(payload, onToken)
        A->>S: POST /api/chat
        S->>O: POST /api/generate (stream)
        O-->>S: ndjson tokens (incl. reasoning)
        Note over S: strip think blocks (streamParser)
        S-->>A: ndjson { response, done }
        A-->>E: onToken(fullTextSoFar)
        A-->>U: incremental render
        E->>E: history.push(reply)
    end
    E-->>U: discussion complete
Loading

streamChat resolves with the complete reply text; onToken(fullTextSoFar) is the only hook the UI needs to render incrementally. An AbortSignal cancels a turn mid-stream (used by stop()).

Backend proxy (server.js)

A thin Express server (default port 3005, override with PORT) that never talks to the model directly from the browser — it proxies to a local Ollama.

  • GET /api/models?port=<n> — lists models from Ollama's /api/tags.
  • POST /api/chat — body { port, model, prompt, system, think }. Forwards to Ollama's /api/generate with stream: true and re-emits a newline-delimited JSON (application/x-ndjson) stream of { response, done } objects.

Two robustness behaviors live here:

  • Thinking fallback — if a model rejects think, the request is retried once without it, so enabling thinking-mode never breaks a model that lacks it.
  • Think stripping — server/streamParser.js removes <think>…</think> blocks incrementally, holding back a possible partial tag across chunk boundaries so a tag split across TCP packets is still caught.
  • Shared NDJSON parser — the chunk-boundary reassembly of newline-delimited JSON lives once in createNdjsonParser() (server/streamParser.js); both the server (server.js) and the browser client (src/api.js) use it, so the two copies can't silently diverge.

Prompt construction (prompts.js)

Kept free of DOM and network code so all wording lives in one place.

  • TURN_INTENTS = ['REBUT', 'BUILD', 'ASK'] — rotated per turn to force real engagement; the first speaker gets OPEN, the last turn gets a conclusion directive.
  • buildSystemPrompt(persona, {isFinalTurn, otherNames, lastName, intent}) — combines the persona profile (and optional voice exemplar), shared discussion rules (speak only as yourself, address others by name, keep names in English), and the per-turn directive.
  • buildContext(question, history) — the original problem plus the running conversation history.

Each seeded persona (config.js) uses a labeled 6-section profile (identity / worldview / method / voice / debate / constraints) giving the model one distinct center of gravity plus an explicit anti-pattern list, to resist generic balanced output.

State & configuration

  • state.js — State holds personas, settings, the current selection, and run flags, and owns its own localStorage persistence.
  • config.js — storage keys, DEFAULT_SETTINGS (Ollama port 11435, model, maxTurns, thinkingMode), TURN_DELAY_MS, MIN_PERSONAS, and the seed personas (Socrates, Elon Musk, Alan Turing).
  • server/config.js — DEFAULT_PORT (default 3005), shared by server.js and vite.config.js so the dev proxy target can't drift from the server's listen port.

Prerequisites

  • Node 18+ and a running Ollama instance (default port 11435).

Run the backend

npm install
npm start        # Express + /api proxy on :3005 (serves prebuilt dist/ if present)

npm run dev additionally starts the Vite frontend with HMR on :5173 and proxies /api to Express — see the rendering layer for that path.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages