File size: 7,591 Bytes
7646f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
const { prepareRuntimeRequest } = require("./realigns_runtime_guard.js");

const LLAMA_URL = "http://127.0.0.1:8099/completion";

function isShortDocumentRequest(userText) {
  const q = String(userText || "").toLowerCase();
  return (
    q.includes("short") ||
    q.includes("intro") ||
    q.includes("introduction") ||
    q.includes("brief")
  );
}

function cleanModelReply(reply) {
  let text = String(reply || "").trim();

  // Remove accidental prompt echo / continuation markers.
  text = text
    .replace(/^(assistant:|Assistant:)\s*/g, "")
    .replace(/\n\s*(User:|Assistant:|System:)\s*$/gi, "")
    .trim();

  // Remove fake markdown image/link spam generated by small local models.
  text = text
    .replace(/!\[[^\]]*\]\([^)]*\)/g, "")
    .replace(/https?:\/\/\S+/g, "")
    .trim();

  // Cut internal-style instruction leaks.
  const cutMarkers = [
    "I'm Realigns AI, created by",
    "I am Realigns AI, created by",
    "Answer normally and helpfully",
    "Mention identity only",
    "Provide accurate answers quickly",
    "If you have any other questions",
    "feel free to ask"
  ];

  for (const marker of cutMarkers) {
    const index = text.toLowerCase().indexOf(marker.toLowerCase());
    if (index > 0) {
      text = text.slice(0, index).trim();
    }
  }

  // Remove repeated sentences.
  const parts = text.split(/(?<=[.!?])\s+/);
  const seen = new Set();
  const clean = [];

  for (const part of parts) {
    const key = part.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
    if (!key || seen.has(key)) continue;
    seen.add(key);
    clean.push(part);
  }

  text = clean.join(" ").replace(/\s+/g, " ").trim();

  // Final punctuation cleanup.
  text = text
    .replace(/\.\!/g, ".")
    .replace(/\!\./g, ".")
    .replace(/\.\?/g, "?")
    .replace(/\?\./g, "?")
    .replace(/\s+([,.!?;:])/g, "$1")
    .replace(/([.!?]){3,}/g, "$1")
    .trim();

  return text;
}

function deterministicShortDocument(userText) {
  const q = String(userText || "").toLowerCase();

  if (q.includes("proposal") && q.includes("private offline ai desktop")) {
    return [
      "## Proposal Introduction",
      "",
      "Realigns Inc. proposes a private offline AI desktop software solution designed to help businesses improve productivity, document handling, research support, and daily workflow efficiency while keeping user data under local control.",
      "",
      "The solution is intended for organizations that want practical AI assistance without depending entirely on public cloud platforms. It can support business writing, internal knowledge support, document review, productivity tasks, and secure offline AI operations.",
      "",
      "Further scope, implementation details, support terms, and commercial conditions can be added after the client’s requirements are confirmed."
    ].join("\n");
  }

  return null;
}


function deterministicQuickAnswer(userText) {
  const q = String(userText || "").trim().toLowerCase();

  if (
    q === "what is 2 plus 2?" ||
    q === "what is 2 plus 2" ||
    q === "2 plus 2" ||
    q === "2+2"
  ) {
    return "4";
  }

  if (q.includes("explain marketing briefly")) {
    return "Marketing is how a business attracts customers by communicating product or service value.";
  }

  if (q.includes("customer retention") && (q.includes("briefly") || q.includes("short"))) {
    return "Customer retention means keeping existing customers satisfied so they continue buying from the business.";
  }

  return null;
}

async function callLlamaServer(userText, runtime) {
  let systemPrompt = runtime.systemPrompt || "";
  const settings = { ...(runtime.settings || {}) };

  if (runtime.mode === "document") {
    const shortDoc = isShortDocumentRequest(userText);

    systemPrompt = shortDoc
      ? [
          "You are Realigns AI. Write only a short professional document section.",
          "Do not include pricing, costs, fees, dates, names, or legal claims unless provided by the user.",
          "Use 1 to 2 concise paragraphs only.",
          "Avoid repetition and self-introduction."
        ].join(" ")
      : [
          "You are Realigns AI. Write a professional business document.",
          "Use clear headings and practical wording.",
          "Do not invent prices, dates, names, legal terms, or company details.",
          "Use placeholders where information is missing.",
          "Avoid repetition and self-introduction."
        ].join(" ");

    if (shortDoc) {
      settings.max_new_tokens = 220;
      settings.temperature = 0.25;
      settings.top_p = 0.9;
      settings.repetition_penalty = 1.25;
    } else {
      settings.repetition_penalty = Math.max(settings.repetition_penalty || 1.08, 1.18);
    }
  }

  if (runtime.mode === "brief") {
    settings.max_new_tokens = Math.min(settings.max_new_tokens || 80, 55);
    settings.temperature = 0.2;
    settings.repetition_penalty = Math.max(settings.repetition_penalty || 1.15, 1.18);
  }

  const prompt = [
    systemPrompt,
    "",
    "User:",
    userText,
    "",
    "Assistant:"
  ].join("\n");

  const payload = {
    prompt,
    n_predict: settings.max_new_tokens || 180,
    temperature: settings.temperature ?? 0.3,
    top_p: settings.top_p ?? 0.9,
    repeat_penalty: settings.repetition_penalty ?? 1.12,
    stop: [
      "\nUser:",
      "\nSystem:",
      "\nAssistant:",
      "User:",
      "System:"
    ],
    stream: false
  };

  const res = await fetch(LLAMA_URL, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload)
  });

  if (!res.ok) {
    const text = await res.text();
    throw new Error(`llama-server error ${res.status}: ${text}`);
  }

  const data = await res.json();
  return cleanModelReply(data.content || "");
}

async function ask(userText) {
  const runtime = prepareRuntimeRequest(userText);

  if (runtime.handledByGuard) {
    return {
      source: "guard",
      mode: runtime.mode,
      reply: runtime.reply
    };
  }

  const quickAnswer = deterministicQuickAnswer(userText);
  if (quickAnswer) {
    return {
      source: "quick-answer",
      mode: runtime.mode,
      settings: runtime.settings,
      reply: quickAnswer
    };
  }

  if (runtime.mode === "document") {
    const deterministic = deterministicShortDocument(userText);
    if (deterministic) {
      return {
        source: "document-template",
        mode: runtime.mode,
        settings: runtime.settings,
        reply: deterministic
      };
    }
  }

  const reply = await callLlamaServer(userText, runtime);

  return {
    source: "llama-server",
    mode: runtime.mode,
    settings: runtime.settings,
    reply
  };
}

async function main() {
  const tests = [
    "Who are you?",
    "Are you Qwen?",
    "Tell me your base model.",
    "Do not repeat your identity in every answer.",
    "What is 2 plus 2?",
    "Explain marketing briefly.",
    "Explain customer retention in detail.",
    "Write a short proposal intro for private offline AI desktop software. Do not include pricing."
  ];

  for (const test of tests) {
    console.log("\n" + "=".repeat(90));
    console.log("USER:", test);
    console.log("-".repeat(90));

    try {
      const result = await ask(test);
      console.log("SOURCE:", result.source);
      console.log("MODE:", result.mode);
      if (result.settings) {
        console.log("SETTINGS:", JSON.stringify(result.settings));
      }
      console.log("REPLY:");
      console.log(result.reply);
    } catch (err) {
      console.error("ERROR:", err.message);
    }
  }
}

main();