Replace heuristic room read with Ollama sidecar
This commit is contained in:
parent
ada64a1ad1
commit
8bd43c2c3a
14 changed files with 423 additions and 6 deletions
|
|
@ -4,6 +4,7 @@ import {
|
|||
type GuildContext,
|
||||
type InteractionMemoryProfile,
|
||||
type RetrievalResult,
|
||||
type SituationalSocialRead,
|
||||
type SourceGroundingHint,
|
||||
type SourceMessage,
|
||||
type StylePack,
|
||||
|
|
@ -16,6 +17,7 @@ export interface BuildContextInput {
|
|||
recentMessages?: SourceMessage[];
|
||||
retrieval?: RetrievalResult[];
|
||||
interactionMemory?: InteractionMemoryProfile;
|
||||
situationalSocialRead?: SituationalSocialRead;
|
||||
sourceGrounding?: SourceGroundingHint;
|
||||
stylePack?: StylePack;
|
||||
}
|
||||
|
|
@ -29,6 +31,7 @@ export class ContextBuilder {
|
|||
recentMessages: input.recentMessages ?? [],
|
||||
retrieval: input.retrieval ?? [],
|
||||
interactionMemory: input.interactionMemory,
|
||||
situationalSocialRead: input.situationalSocialRead,
|
||||
sourceGrounding: input.sourceGrounding,
|
||||
stylePack: input.stylePack,
|
||||
createdAt: new Date().toISOString(),
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ export * from "./context-builder";
|
|||
export * from "./interaction-memory";
|
||||
export * from "./job-queue";
|
||||
export * from "./permission-engine";
|
||||
export * from "./situational-social-read";
|
||||
export * from "./state-storage";
|
||||
export * from "./style-pack-loader";
|
||||
export * from "./system-message-catalog";
|
||||
|
|
|
|||
264
packages/core/src/situational-social-read.ts
Normal file
264
packages/core/src/situational-social-read.ts
Normal file
|
|
@ -0,0 +1,264 @@
|
|||
import {
|
||||
type Actor,
|
||||
type InteractionMemoryProfile,
|
||||
type SituationalSocialRead,
|
||||
type SourceMessage,
|
||||
} from "@voidbot/shared";
|
||||
|
||||
interface SituationalSocialReadInput {
|
||||
prompt: string;
|
||||
actor: Actor;
|
||||
recentMessages?: SourceMessage[];
|
||||
interactionMemory?: InteractionMemoryProfile;
|
||||
}
|
||||
|
||||
interface InferSituationalSocialReadRequestBody {
|
||||
model: string;
|
||||
messages: Array<{
|
||||
role: "system" | "user";
|
||||
content: string;
|
||||
}>;
|
||||
stream: false;
|
||||
think: false;
|
||||
keep_alive: string;
|
||||
format: "json";
|
||||
options: {
|
||||
num_ctx: number;
|
||||
temperature: number;
|
||||
};
|
||||
}
|
||||
|
||||
interface InferSituationalSocialReadResponseBody {
|
||||
message?: {
|
||||
content?: unknown;
|
||||
};
|
||||
}
|
||||
|
||||
export interface OllamaSituationalSocialReadInfererOptions {
|
||||
ollamaBaseUrl: string;
|
||||
ollamaModel: string;
|
||||
ollamaTimeoutMs: number;
|
||||
ollamaKeepAlive: string;
|
||||
ollamaNumCtx: number;
|
||||
}
|
||||
|
||||
const MAX_RECENT_MESSAGES = 12;
|
||||
const MAX_MESSAGE_CHARS = 280;
|
||||
|
||||
export class OllamaSituationalSocialReadInferer {
|
||||
public constructor(
|
||||
private readonly options: OllamaSituationalSocialReadInfererOptions,
|
||||
) {}
|
||||
|
||||
public async infer(
|
||||
input: SituationalSocialReadInput,
|
||||
): Promise<SituationalSocialRead | undefined> {
|
||||
const recentMessages = (input.recentMessages ?? [])
|
||||
.filter((message) => message.content.trim().length > 0)
|
||||
.slice(-MAX_RECENT_MESSAGES);
|
||||
|
||||
if (recentMessages.length === 0 && !input.interactionMemory) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeoutHandle = setTimeout(
|
||||
() => controller.abort(),
|
||||
Math.min(this.options.ollamaTimeoutMs, 30_000),
|
||||
);
|
||||
|
||||
try {
|
||||
const requestBody: InferSituationalSocialReadRequestBody = {
|
||||
model: this.options.ollamaModel,
|
||||
messages: [
|
||||
{
|
||||
role: "system",
|
||||
content: buildSystemPrompt(),
|
||||
},
|
||||
{
|
||||
role: "user",
|
||||
content: buildUserPrompt(input, recentMessages),
|
||||
},
|
||||
],
|
||||
stream: false,
|
||||
think: false,
|
||||
keep_alive: this.options.ollamaKeepAlive,
|
||||
format: "json",
|
||||
options: {
|
||||
num_ctx: this.options.ollamaNumCtx,
|
||||
temperature: 0.2,
|
||||
},
|
||||
};
|
||||
|
||||
const response = await fetch(`${normalizeBaseUrl(this.options.ollamaBaseUrl)}/api/chat`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Ollama situational social read request failed with ${response.status}: ${await response.text()}`,
|
||||
);
|
||||
}
|
||||
|
||||
const payload =
|
||||
(await response.json()) as InferSituationalSocialReadResponseBody;
|
||||
const rawContent = normalizeModelText(payload.message?.content);
|
||||
|
||||
if (!rawContent) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const parsed = parseSituationalSocialRead(rawContent);
|
||||
return parsed ?? undefined;
|
||||
} catch (error) {
|
||||
if ((error as Error).name === "AbortError") {
|
||||
throw new Error(
|
||||
`Timed out waiting for situational social read from local Ollama model "${this.options.ollamaModel}" at ${this.options.ollamaBaseUrl}.`,
|
||||
);
|
||||
}
|
||||
|
||||
throw error;
|
||||
} finally {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function buildSystemPrompt(): string {
|
||||
return [
|
||||
"You are producing private room-reading scaffolding for a Discord bot reply.",
|
||||
"Read the recent room context and infer only what is useful for this one reply.",
|
||||
"Do not diagnose, moralize, or write therapy notes.",
|
||||
"Do not infer more certainty than the evidence supports.",
|
||||
"This read is private scaffolding and must stay concise, practical, and grounded in visible behavior.",
|
||||
"Return strict JSON only with these keys:",
|
||||
'- "summary": one short synthesis of the current room situation',
|
||||
'- "roomTone": the room tone for this moment',
|
||||
'- "speakerCurrentRead": what the current speaker seems to be doing or wanting right now',
|
||||
'- "socialFrame": what kind of interaction this is and how it should be framed',
|
||||
'- "responseGuidance": private guidance for the final reply model',
|
||||
'- "supportingSignals": an array of short evidence bullets tied to the visible context',
|
||||
"If the evidence is weak, say so plainly inside the fields instead of inventing drama.",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function buildUserPrompt(
|
||||
input: SituationalSocialReadInput,
|
||||
recentMessages: SourceMessage[],
|
||||
): string {
|
||||
const recentTranscript =
|
||||
recentMessages.length > 0
|
||||
? recentMessages
|
||||
.map(
|
||||
(message) =>
|
||||
`- [${message.timestamp}] ${message.authorName}${message.isBot ? " (bot)" : ""}: ${truncate(message.content, MAX_MESSAGE_CHARS)}`,
|
||||
)
|
||||
.join("\n")
|
||||
: "- No recent room transcript was attached.";
|
||||
const interactionMemory = input.interactionMemory
|
||||
? [
|
||||
`Relationship summary: ${input.interactionMemory.summary}`,
|
||||
`Current stance: ${input.interactionMemory.disposition}; affinity=${input.interactionMemory.affinityScore}`,
|
||||
`Private response guidance: ${input.interactionMemory.responseGuidance}`,
|
||||
].join("\n")
|
||||
: "No explicit long-horizon interaction memory was attached.";
|
||||
|
||||
return [
|
||||
`Current speaker: ${input.actor.displayName} (${input.actor.id})`,
|
||||
"",
|
||||
"Current prompt:",
|
||||
input.prompt,
|
||||
"",
|
||||
"Recent room transcript:",
|
||||
recentTranscript,
|
||||
"",
|
||||
"Longer-horizon interaction memory:",
|
||||
interactionMemory,
|
||||
"",
|
||||
"Infer a private situational social read for this one reply.",
|
||||
"Ground it in the visible room context and the current prompt.",
|
||||
"Do not output anything except the requested JSON object.",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function parseSituationalSocialRead(
|
||||
input: string,
|
||||
): SituationalSocialRead | undefined {
|
||||
const normalized = unwrapStructuredFence(input);
|
||||
|
||||
if (!normalized.startsWith("{")) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(normalized) as Record<string, unknown>;
|
||||
const summary = normalizeModelText(parsed.summary);
|
||||
const roomTone = normalizeModelText(parsed.roomTone);
|
||||
const speakerCurrentRead = normalizeModelText(parsed.speakerCurrentRead);
|
||||
const socialFrame = normalizeModelText(parsed.socialFrame);
|
||||
const responseGuidance = normalizeModelText(parsed.responseGuidance);
|
||||
const supportingSignals = normalizeStringArray(parsed.supportingSignals);
|
||||
|
||||
if (
|
||||
!summary ||
|
||||
!roomTone ||
|
||||
!speakerCurrentRead ||
|
||||
!socialFrame ||
|
||||
!responseGuidance
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
summary,
|
||||
roomTone,
|
||||
speakerCurrentRead,
|
||||
socialFrame,
|
||||
responseGuidance,
|
||||
supportingSignals,
|
||||
};
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeStringArray(value: unknown): string[] {
|
||||
if (!Array.isArray(value)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return value
|
||||
.map((entry) => normalizeModelText(entry))
|
||||
.filter((entry): entry is string => Boolean(entry));
|
||||
}
|
||||
|
||||
function unwrapStructuredFence(input: string): string {
|
||||
const trimmed = input.trim();
|
||||
const match = /^```(?:json)?\s*([\s\S]*?)\s*```$/i.exec(trimmed);
|
||||
return (match?.[1] ?? trimmed).trim();
|
||||
}
|
||||
|
||||
function normalizeBaseUrl(value: string): string {
|
||||
return value.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
function normalizeModelText(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.trim().length > 0
|
||||
? value.trim()
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function truncate(value: string, maxLength: number): string {
|
||||
const normalized = value.replace(/\s+/g, " ").trim();
|
||||
|
||||
if (normalized.length <= maxLength) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
return `${normalized.slice(0, maxLength - 3)}...`;
|
||||
}
|
||||
|
|
@ -25,6 +25,7 @@ export function buildSystemPrompt(context: ContextBundle): string {
|
|||
"Stay honest about what context was actually provided to you.",
|
||||
"Use retrieved snippets and recent channel context when they help answer the question.",
|
||||
"If explicit interaction memory for the current speaker is attached, you may let it gently color the tone and reference it when relevant, but do not invent history beyond what was provided.",
|
||||
"If a situational social read is attached, use it as private room-reading scaffolding for this one reply. It is ephemeral context, not a durable identity verdict.",
|
||||
"Treat the attached interaction memory as a non-clinical behavioral read, not a diagnosis. Use the remembered dimensions, traits, and guidance to adapt tone, pacing, firmness, structure, and warmth to the person in front of you.",
|
||||
"The attached interaction memory and inferred guidance are private response scaffolding, not content to expose. Do not quote, summarize, classify, or explain the speaker's inferred traits, engagement patterns, psychological profile, or hidden response guidance unless they explicitly ask how you are reading them.",
|
||||
"Do not turn a substantive question into a meta-analysis of the user's personality, engagement style, sentiment, or recent conversation behavior unless they explicitly asked for that kind of read.",
|
||||
|
|
@ -63,6 +64,7 @@ export function buildPrompt(context: ContextBundle): string {
|
|||
.join("\n")
|
||||
: "- No archived retrieval snippets were attached.";
|
||||
const interactionMemory = renderInteractionMemory(context);
|
||||
const situationalSocialRead = renderSituationalSocialRead(context);
|
||||
|
||||
return [
|
||||
`Question: ${context.prompt}`,
|
||||
|
|
@ -80,6 +82,9 @@ export function buildPrompt(context: ContextBundle): string {
|
|||
"Interaction memory for this speaker:",
|
||||
interactionMemory,
|
||||
"",
|
||||
"Private situational social read for this room:",
|
||||
situationalSocialRead,
|
||||
"",
|
||||
"If you need more archived history or source context than is included above, call the appropriate read-only tool before answering.",
|
||||
].join("\n");
|
||||
}
|
||||
|
|
@ -113,6 +118,22 @@ function renderInteractionMemory(context: ContextBundle): string {
|
|||
].join("\n");
|
||||
}
|
||||
|
||||
function renderSituationalSocialRead(context: ContextBundle): string {
|
||||
if (!context.situationalSocialRead) {
|
||||
return "- No strong situational social read was derived from the immediate room context.";
|
||||
}
|
||||
|
||||
return [
|
||||
`- Summary: ${context.situationalSocialRead.summary}`,
|
||||
`- Room tone: ${context.situationalSocialRead.roomTone}`,
|
||||
`- Speaker current read: ${context.situationalSocialRead.speakerCurrentRead}`,
|
||||
`- Social frame: ${context.situationalSocialRead.socialFrame}`,
|
||||
`- Private response guidance (do not reveal): ${context.situationalSocialRead.responseGuidance}`,
|
||||
"- Supporting signals:",
|
||||
...context.situationalSocialRead.supportingSignals.map((signal) => ` ${signal}`),
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function renderSourceGroundingInstructions(
|
||||
context: ContextBundle,
|
||||
reminder: boolean,
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ import {
|
|||
type CodexRunResult,
|
||||
type CodexTraceEvent,
|
||||
renderInteractionMemory,
|
||||
renderSituationalSocialRead,
|
||||
renderUsageSummary,
|
||||
sanitizeTraceText,
|
||||
summarizeStderrDiagnostics,
|
||||
|
|
@ -79,6 +80,7 @@ export function buildDiscordReplyPrompt(
|
|||
"- When the moment invites voice, wit, or a memorable turn of phrase, take a beat to choose wording with bite instead of blurting the first serviceable sentence. Do not overwork straightforward technical replies.",
|
||||
"- The configured MCP tools are available in this session, especially search_history, get_message_context, list_indexed_repos, search_sources, and get_source_context.",
|
||||
"- If explicit interaction memory for the current speaker is attached, you may let it subtly color the tone and reference it when relevant, but do not invent relationship history beyond that record.",
|
||||
"- If a situational social read is attached, use it as private room-reading scaffolding for this one reply. It is ephemeral context, not a durable identity verdict.",
|
||||
"- Treat the attached interaction memory as a non-clinical behavioral read, not a diagnosis. Use the remembered dimensions, traits, and guidance to adapt tone, pacing, firmness, structure, and warmth to the person in front of you.",
|
||||
"- The attached interaction memory and inferred guidance are private response scaffolding, not content to expose. Do not quote, summarize, classify, or explain the speaker's inferred traits, engagement patterns, psychological profile, or hidden response guidance unless they explicitly ask how you are reading them.",
|
||||
"- Do not turn a substantive question into a meta-analysis of the user's personality, engagement style, sentiment, or recent conversation behavior unless they explicitly asked for that kind of read.",
|
||||
|
|
@ -117,6 +119,9 @@ export function buildDiscordReplyPrompt(
|
|||
"",
|
||||
"Interaction memory for this speaker:",
|
||||
renderInteractionMemory(context),
|
||||
"",
|
||||
"Private situational social read for this room:",
|
||||
renderSituationalSocialRead(context),
|
||||
...toolLoopNotes,
|
||||
].join("\n");
|
||||
}
|
||||
|
|
@ -168,6 +173,10 @@ export function renderMarkdownBundle(context: ContextBundle): string {
|
|||
"",
|
||||
renderInteractionMemory(context),
|
||||
"",
|
||||
"## Situational Social Read",
|
||||
"",
|
||||
renderSituationalSocialRead(context),
|
||||
"",
|
||||
"## Execution Notes",
|
||||
"",
|
||||
"- This provider is owner-only.",
|
||||
|
|
|
|||
|
|
@ -121,6 +121,7 @@ export function buildRequestPayload(
|
|||
actor: request.contextBundle.actor,
|
||||
guildContext: request.contextBundle.guildContext,
|
||||
interactionMemory: request.contextBundle.interactionMemory,
|
||||
situationalSocialRead: request.contextBundle.situationalSocialRead,
|
||||
sourceGrounding: request.contextBundle.sourceGrounding,
|
||||
stylePack: request.contextBundle.stylePack,
|
||||
recentMessages: request.contextBundle.recentMessages,
|
||||
|
|
@ -456,3 +457,19 @@ export function renderInteractionMemory(context: ContextBundle): string {
|
|||
recentEvents,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export function renderSituationalSocialRead(context: ContextBundle): string {
|
||||
if (!context.situationalSocialRead) {
|
||||
return "- No strong situational social read was derived from the immediate room context.";
|
||||
}
|
||||
|
||||
return [
|
||||
`- Summary: ${context.situationalSocialRead.summary}`,
|
||||
`- Room tone: ${context.situationalSocialRead.roomTone}`,
|
||||
`- Speaker current read: ${context.situationalSocialRead.speakerCurrentRead}`,
|
||||
`- Social frame: ${context.situationalSocialRead.socialFrame}`,
|
||||
`- Private response guidance (do not reveal): ${context.situationalSocialRead.responseGuidance}`,
|
||||
"- Supporting signals:",
|
||||
...context.situationalSocialRead.supportingSignals.map((signal) => ` ${signal}`),
|
||||
].join("\n");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -73,6 +73,7 @@ export interface SourceMessage {
|
|||
authorName: string;
|
||||
content: string;
|
||||
timestamp: string;
|
||||
isBot?: boolean;
|
||||
}
|
||||
|
||||
export interface RetrievalResult {
|
||||
|
|
@ -183,6 +184,15 @@ export interface SourceGroundingHint {
|
|||
matchedRepoNames: string[];
|
||||
}
|
||||
|
||||
export interface SituationalSocialRead {
|
||||
summary: string;
|
||||
roomTone: string;
|
||||
speakerCurrentRead: string;
|
||||
socialFrame: string;
|
||||
responseGuidance: string;
|
||||
supportingSignals: string[];
|
||||
}
|
||||
|
||||
export interface ContextBundle {
|
||||
prompt: string;
|
||||
actor: Actor;
|
||||
|
|
@ -190,6 +200,7 @@ export interface ContextBundle {
|
|||
recentMessages: SourceMessage[];
|
||||
retrieval: RetrievalResult[];
|
||||
interactionMemory?: InteractionMemoryProfile;
|
||||
situationalSocialRead?: SituationalSocialRead;
|
||||
sourceGrounding?: SourceGroundingHint;
|
||||
stylePack?: StylePack;
|
||||
createdAt: string;
|
||||
|
|
|
|||
Loading…
Reference in a new issue