chatbotlite 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,57 @@
1
+ // src/core/tools.ts
2
+ var MARKER_RE = /\[SKILL:(\w+)((?:\s+\w+=(?:"[^"]*"|[\w./@*+,:-]+))*)\s*\]/g;
3
+ var ARG_RE = /(\w+)=("([^"]*)"|([\w./@*+,:-]+))/g;
4
+ function coerce(value) {
5
+ if (value === "true") return true;
6
+ if (value === "false") return false;
7
+ if (/^-?\d+(?:\.\d+)?$/.test(value)) return Number(value);
8
+ return value;
9
+ }
10
+ function parseToolMarkers(text) {
11
+ const markers = [];
12
+ let m;
13
+ MARKER_RE.lastIndex = 0;
14
+ while ((m = MARKER_RE.exec(text)) !== null) {
15
+ const name = m[1];
16
+ const argsRaw = m[2] ?? "";
17
+ const args = {};
18
+ let a;
19
+ ARG_RE.lastIndex = 0;
20
+ while ((a = ARG_RE.exec(argsRaw)) !== null) {
21
+ const key = a[1];
22
+ const value = a[3] ?? a[4] ?? "";
23
+ args[key] = coerce(value);
24
+ }
25
+ markers.push({ name, args, raw: m[0] });
26
+ }
27
+ return markers;
28
+ }
29
+ function stripToolMarkers(text) {
30
+ return text.replace(MARKER_RE, "").replace(/\s+\n/g, "\n").trim();
31
+ }
32
+ function buildToolsPromptAddendum(enabledTools) {
33
+ if (enabledTools.length === 0) return "";
34
+ const examples = {
35
+ uploadForReview: '[SKILL:uploadForReview purpose="T4 slip" accept="image/*,application/pdf" maxMb=10] \u2014 collect a document for human review (bytes go to webhook, you never see content)',
36
+ scheduleCallback: '[SKILL:scheduleCallback durationMin=15 timezone="America/Vancouver"] \u2014 let the user pick a callback time slot',
37
+ requestPayment: '[SKILL:requestPayment amount=4250 currency="cad" reason="initial deposit"] \u2014 collect payment via inline card'
38
+ };
39
+ const lines = enabledTools.filter((t) => examples[t]).map((t) => `- ${examples[t]}`);
40
+ if (lines.length === 0) return "";
41
+ return [
42
+ "",
43
+ "## Available tools",
44
+ "When you need one of these workflows, emit the marker INLINE in your reply.",
45
+ "Write a short message first, THEN the marker. The marker will be replaced by an interactive card.",
46
+ "Pause the conversation after emitting \u2014 wait for the tool result before continuing.",
47
+ "",
48
+ ...lines
49
+ ].join("\n");
50
+ }
51
+
1
52
  // src/core/prompts.ts
2
- function buildSystemPrompt(knowledge) {
53
+ function buildSystemPrompt(knowledge, enabledTools = []) {
54
+ const toolsAddendum = buildToolsPromptAddendum(enabledTools);
3
55
  return [
4
56
  "You are an AI assistant on a business website. Use ONLY the knowledge below to answer.",
5
57
  "",
@@ -12,33 +64,23 @@ function buildSystemPrompt(knowledge) {
12
64
  "- For anything not covered in the knowledge above, say the owner will follow up \u2014 do NOT guess.",
13
65
  '- If the caller is clearly a vendor/sales pitch, say: "This does not look like a customer service request, so we will not continue this thread."',
14
66
  `- If wrong number or asked to stop, say: "Sorry about that. We won't text again."`,
15
- "- Match the caller's language automatically."
16
- ].join("\n");
67
+ "- Match the caller's language automatically.",
68
+ toolsAddendum
69
+ ].filter(Boolean).join("\n");
17
70
  }
18
71
 
19
72
  // src/core/guards.ts
20
73
  var FORBIDDEN_PHRASES = [
21
- "help is coming",
22
- "someone is on the way",
23
- "technician is on the way",
24
- "provider is on the way",
25
- "dispatching someone",
26
74
  "i've booked",
75
+ // fake booking
27
76
  "i have booked",
28
- "reservation confirmed",
29
77
  "your appointment is confirmed",
30
- "i've scheduled",
31
- "i have scheduled",
32
- "we've dispatched",
33
- "we have dispatched",
34
- "i can confirm",
35
- "i guarantee",
36
- "guaranteed delivery",
37
- "guaranteed arrival",
38
- "will arrive at",
39
- "arriving at",
40
- "i'll send",
41
- "i will send"
78
+ // fake confirmation
79
+ "reservation confirmed",
80
+ "someone is on the way",
81
+ // false dispatch
82
+ "i guarantee"
83
+ // legal liability
42
84
  ];
43
85
  function checkForbiddenPhrases(reply) {
44
86
  const lower = reply.toLowerCase();
@@ -63,6 +105,33 @@ function stripForbidden(reply) {
63
105
  return trimmed;
64
106
  }
65
107
 
108
+ // src/core/judges.ts
109
+ async function runJudge(config, apiKey, endpointUrl, content, fetcher) {
110
+ const res = await fetcher(`${endpointUrl}/chat/completions`, {
111
+ method: "POST",
112
+ headers: {
113
+ Authorization: `Bearer ${apiKey}`,
114
+ "Content-Type": "application/json"
115
+ },
116
+ body: JSON.stringify({
117
+ model: config.model,
118
+ messages: [
119
+ { role: "system", content: config.prompt },
120
+ { role: "user", content }
121
+ ],
122
+ temperature: 0,
123
+ max_tokens: 10
124
+ })
125
+ });
126
+ if (!res.ok) {
127
+ return { decision: "PASS", raw: `judge HTTP ${res.status} \u2014 fail-open` };
128
+ }
129
+ const data = await res.json();
130
+ const raw = (data.choices?.[0]?.message?.content ?? "").trim().toUpperCase();
131
+ const decision = raw.startsWith("BLOCK") ? "BLOCK" : "PASS";
132
+ return { decision, raw };
133
+ }
134
+
66
135
  // src/client/types.ts
67
136
  var PROVIDER_NAMES = /* @__PURE__ */ new Set([
68
137
  "openai",
@@ -83,22 +152,34 @@ function isKnownProvider(name) {
83
152
 
84
153
  // src/client/providers.ts
85
154
  var PROVIDER_ENDPOINTS = {
86
- openai: { baseUrl: "https://api.openai.com/v1", defaultModel: "gpt-4o-mini" },
155
+ openai: { baseUrl: "https://api.openai.com/v1", defaultModel: "gpt-4o-mini", visionModel: "gpt-4o" },
87
156
  deepseek: { baseUrl: "https://api.deepseek.com/v1", defaultModel: "deepseek-chat" },
88
- groq: { baseUrl: "https://api.groq.com/openai/v1", defaultModel: "llama-3.3-70b-versatile" },
89
- gemini: { baseUrl: "https://generativelanguage.googleapis.com/v1beta/openai", defaultModel: "gemini-2.5-flash" },
90
- anthropic: { baseUrl: "https://api.anthropic.com/v1", defaultModel: "claude-haiku-4-5" },
157
+ groq: { baseUrl: "https://api.groq.com/openai/v1", defaultModel: "llama-3.3-70b-versatile", visionModel: "llama-3.2-90b-vision-preview" },
158
+ gemini: { baseUrl: "https://generativelanguage.googleapis.com/v1beta/openai", defaultModel: "gemini-2.5-flash", visionModel: "gemini-2.5-flash" },
159
+ anthropic: { baseUrl: "https://api.anthropic.com/v1", defaultModel: "claude-haiku-4-5", visionModel: "claude-haiku-4-5" },
91
160
  cerebras: { baseUrl: "https://api.cerebras.ai/v1", defaultModel: "qwen-3-235b-a22b-instruct-2507" },
92
161
  sambanova: { baseUrl: "https://api.sambanova.ai/v1", defaultModel: "Meta-Llama-3.3-70B-Instruct" },
93
162
  fireworks: { baseUrl: "https://api.fireworks.ai/inference/v1", defaultModel: "accounts/fireworks/models/llama-v3p3-70b-instruct" },
94
163
  mistral: { baseUrl: "https://api.mistral.ai/v1", defaultModel: "mistral-small-latest" },
95
- openrouter: { baseUrl: "https://openrouter.ai/api/v1", defaultModel: "deepseek/deepseek-chat" },
96
- moonshot: { baseUrl: "https://api.moonshot.ai/v1", defaultModel: "moonshot-v1-32k" }
164
+ openrouter: { baseUrl: "https://openrouter.ai/api/v1", defaultModel: "deepseek/deepseek-chat", visionModel: "openai/gpt-4o" },
165
+ moonshot: { baseUrl: "https://api.moonshot.ai/v1", defaultModel: "moonshot-v1-32k", visionModel: "moonshot-v1-32k-vision-preview" }
97
166
  };
98
167
  function isRetryableError(err) {
99
168
  const msg = err instanceof Error ? err.message : String(err);
100
169
  return /\b(429|rate.?limit|quota|exceed|5\d\d|timeout|ECONNRESET|fetch failed)\b/i.test(msg);
101
170
  }
171
+ async function fileToDataUrl(file) {
172
+ const buf = new Uint8Array(await file.arrayBuffer());
173
+ const base64 = bufferToBase64(buf);
174
+ const mime = file.type || "application/octet-stream";
175
+ return `data:${mime};base64,${base64}`;
176
+ }
177
+ function bufferToBase64(buf) {
178
+ let bin = "";
179
+ for (let i = 0; i < buf.length; i++) bin += String.fromCharCode(buf[i]);
180
+ if (typeof btoa === "function") return btoa(bin);
181
+ return globalThis.Buffer.from(bin, "binary").toString("base64");
182
+ }
102
183
 
103
184
  // src/client/chatbot.ts
104
185
  var ChatBot = class {
@@ -107,18 +188,258 @@ var ChatBot = class {
107
188
  fetcher;
108
189
  timeoutMs;
109
190
  cachedSystemPrompt;
191
+ guards;
192
+ knowledge;
110
193
  constructor(init) {
111
194
  if (!init.knowledge || typeof init.knowledge !== "string" || init.knowledge.trim().length === 0) {
112
195
  throw new Error("chatbotlite: knowledge is required (a non-empty markdown string).");
113
196
  }
197
+ this.knowledge = init.knowledge;
114
198
  this.keys = init.providers.keys ?? {};
115
199
  this.steps = resolveChain(init.providers);
116
200
  this.fetcher = init.options?.fetch ?? globalThis.fetch.bind(globalThis);
117
201
  this.timeoutMs = init.options?.timeoutMs ?? 3e4;
118
202
  this.cachedSystemPrompt = buildSystemPrompt(init.knowledge);
203
+ this.guards = init.guards ?? {};
204
+ }
205
+ /** Build system prompt for given opts — uses cached if no enabledTools, else rebuilds. */
206
+ resolveSystemPrompt(opts) {
207
+ if (opts.systemPrompt) return opts.systemPrompt;
208
+ if (opts.enabledTools && opts.enabledTools.length > 0) {
209
+ return buildSystemPrompt(this.knowledge, opts.enabledTools);
210
+ }
211
+ return this.cachedSystemPrompt;
212
+ }
213
+ /** Run an LLM judge against content. Fail-open on errors. */
214
+ async judge(config, content) {
215
+ const endpoint = PROVIDER_ENDPOINTS[config.provider];
216
+ const key = this.keys[config.provider];
217
+ if (!key) {
218
+ return { decision: "PASS", raw: `judge provider ${config.provider} has no key \u2014 fail-open` };
219
+ }
220
+ const model = config.model ?? endpoint.defaultModel;
221
+ return runJudge(
222
+ { provider: config.provider, model, prompt: config.prompt },
223
+ key,
224
+ endpoint.baseUrl,
225
+ content,
226
+ this.fetcher
227
+ );
228
+ }
229
+ /**
230
+ * Stream a reply as SSE events. Returns a ReadableStream that yields tokens
231
+ * progressively. Designed to plug into Next.js/Hono/Express route handlers:
232
+ *
233
+ * ```ts
234
+ * export async function POST(req: Request) {
235
+ * const { message, transcript } = await req.json();
236
+ * const stream = await bot.replyStream(message, { history: transcript });
237
+ * return new Response(stream, {
238
+ * headers: { "Content-Type": "text/event-stream" }
239
+ * });
240
+ * }
241
+ * ```
242
+ *
243
+ * Events emitted (one per `data:` line, SSE format):
244
+ * event: token data: "<text fragment>"
245
+ * event: done data: {"reply":"...","usedProvider":"...","usedModel":"...","attempts":[...]}
246
+ * event: error data: {"message":"...","attempts":[...]}
247
+ */
248
+ async replyStream(message, opts = {}) {
249
+ const systemPrompt = this.resolveSystemPrompt(opts);
250
+ const messages = [
251
+ { role: "system", content: systemPrompt },
252
+ ...opts.history ?? [],
253
+ { role: "user", content: message }
254
+ ];
255
+ const steps = this.steps;
256
+ const fetcher = this.fetcher;
257
+ const keys = this.keys;
258
+ const timeoutMs = this.timeoutMs;
259
+ const encoder = new TextEncoder();
260
+ const sse = (event, data) => encoder.encode(`event: ${event}
261
+ data: ${data}
262
+
263
+ `);
264
+ return new ReadableStream({
265
+ async start(controller) {
266
+ const attempts = [];
267
+ let lastError;
268
+ let assembled = "";
269
+ for (const step of steps) {
270
+ const t0 = Date.now();
271
+ const endpoint = PROVIDER_ENDPOINTS[step.provider];
272
+ const key = keys[step.provider];
273
+ if (!key) {
274
+ attempts.push({ provider: step.provider, model: step.model, status: "error", error: "missing key", latencyMs: 0 });
275
+ continue;
276
+ }
277
+ const abortCtrl = new AbortController();
278
+ const timer = setTimeout(() => abortCtrl.abort(), timeoutMs);
279
+ try {
280
+ const res = await fetcher(`${endpoint.baseUrl}/chat/completions`, {
281
+ method: "POST",
282
+ headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
283
+ body: JSON.stringify({ model: step.model, messages, temperature: 0.3, max_tokens: 300, stream: true }),
284
+ signal: abortCtrl.signal
285
+ });
286
+ if (!res.ok) {
287
+ const body = await res.text();
288
+ throw new Error(`${res.status}: ${body.slice(0, 200)}`);
289
+ }
290
+ const reader = res.body.getReader();
291
+ const decoder = new TextDecoder();
292
+ let sseBuffer = "";
293
+ while (true) {
294
+ const { done, value } = await reader.read();
295
+ if (done) break;
296
+ sseBuffer += decoder.decode(value, { stream: true });
297
+ const lines = sseBuffer.split("\n");
298
+ sseBuffer = lines.pop() ?? "";
299
+ for (const line of lines) {
300
+ const trimmed = line.trim();
301
+ if (!trimmed.startsWith("data:")) continue;
302
+ const payload = trimmed.slice(5).trim();
303
+ if (payload === "[DONE]") continue;
304
+ try {
305
+ const obj = JSON.parse(payload);
306
+ const delta = obj.choices?.[0]?.delta?.content ?? obj.choices?.[0]?.delta?.reasoning_content ?? "";
307
+ if (delta) {
308
+ assembled += delta;
309
+ controller.enqueue(sse("token", JSON.stringify(delta)));
310
+ }
311
+ } catch {
312
+ }
313
+ }
314
+ }
315
+ attempts.push({ provider: step.provider, model: step.model, status: "ok", latencyMs: Date.now() - t0 });
316
+ const guard = checkForbiddenPhrases(assembled);
317
+ const finalReply = guard.ok ? assembled : stripForbidden(assembled);
318
+ controller.enqueue(sse("done", JSON.stringify({
319
+ reply: finalReply,
320
+ usedProvider: step.provider,
321
+ usedModel: step.model,
322
+ guardWarnings: guard.violations,
323
+ attempts
324
+ })));
325
+ controller.close();
326
+ return;
327
+ } catch (err) {
328
+ lastError = err;
329
+ const errMsg = err instanceof Error ? err.message : String(err);
330
+ attempts.push({ provider: step.provider, model: step.model, status: "error", error: errMsg, latencyMs: Date.now() - t0 });
331
+ assembled = "";
332
+ if (!isRetryableError(err)) {
333
+ controller.enqueue(sse("error", JSON.stringify({ message: `${step.label} failed (non-retryable): ${errMsg}`, attempts })));
334
+ controller.close();
335
+ return;
336
+ }
337
+ } finally {
338
+ clearTimeout(timer);
339
+ }
340
+ }
341
+ const summary = attempts.map((a) => `${a.provider}/${a.model}:${a.error ?? "ok"}`).join(" \u2192 ");
342
+ controller.enqueue(sse("error", JSON.stringify({
343
+ message: `all chain steps failed. Trace: ${summary}. Last error: ${lastError instanceof Error ? lastError.message : String(lastError)}`,
344
+ attempts
345
+ })));
346
+ controller.close();
347
+ }
348
+ });
349
+ }
350
+ /**
351
+ * Reply to a message with optional image attachments. Routes through vision-capable
352
+ * providers only — chain steps without `visionModel` are skipped (logged in attempts).
353
+ *
354
+ * Images are inlined as data: URLs. Keep total payload modest (<10MB).
355
+ */
356
+ async replyWithMedia(message, opts = {}) {
357
+ const images = opts.images ?? [];
358
+ if (images.length === 0) {
359
+ return this.reply(message, opts);
360
+ }
361
+ const dataUrls = await Promise.all(images.map(fileToDataUrl));
362
+ const systemPrompt = this.resolveSystemPrompt(opts);
363
+ const userContent = [];
364
+ if (message) userContent.push({ type: "text", text: message });
365
+ for (const url of dataUrls) userContent.push({ type: "image_url", image_url: { url } });
366
+ const messages = [
367
+ { role: "system", content: systemPrompt },
368
+ ...opts.history ?? [],
369
+ { role: "user", content: userContent }
370
+ ];
371
+ const attempts = [];
372
+ let lastError;
373
+ for (const step of this.steps) {
374
+ const endpoint = PROVIDER_ENDPOINTS[step.provider];
375
+ if (!endpoint.visionModel) {
376
+ attempts.push({ provider: step.provider, model: step.model, status: "error", error: "no vision support", latencyMs: 0 });
377
+ continue;
378
+ }
379
+ const t0 = Date.now();
380
+ const visionStep = { provider: step.provider, model: endpoint.visionModel, label: `${step.provider}/${endpoint.visionModel}` };
381
+ try {
382
+ const key = this.keys[step.provider];
383
+ if (!key) throw new Error(`Missing API key for provider: ${step.provider}`);
384
+ const controller = new AbortController();
385
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
386
+ try {
387
+ const res = await this.fetcher(`${endpoint.baseUrl}/chat/completions`, {
388
+ method: "POST",
389
+ headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
390
+ body: JSON.stringify({ model: visionStep.model, messages, temperature: 0.3, max_tokens: 400 }),
391
+ signal: controller.signal
392
+ });
393
+ if (!res.ok) {
394
+ const body = await res.text();
395
+ throw new Error(`${res.status}: ${body.slice(0, 200)}`);
396
+ }
397
+ const data = await res.json();
398
+ const reply = (data.choices?.[0]?.message?.content ?? "").trim();
399
+ if (!reply) throw new Error("empty vision reply");
400
+ attempts.push({ provider: visionStep.provider, model: visionStep.model, status: "ok", latencyMs: Date.now() - t0 });
401
+ const guard = checkForbiddenPhrases(reply);
402
+ const finalReply = guard.ok ? reply : stripForbidden(reply);
403
+ return {
404
+ reply: finalReply,
405
+ usedProvider: visionStep.provider,
406
+ usedModel: visionStep.model,
407
+ ...data.usage ? { usage: data.usage } : {},
408
+ guardWarnings: guard.violations,
409
+ attempts
410
+ };
411
+ } finally {
412
+ clearTimeout(timer);
413
+ }
414
+ } catch (err) {
415
+ lastError = err;
416
+ const errMsg = err instanceof Error ? err.message : String(err);
417
+ attempts.push({ provider: visionStep.provider, model: visionStep.model, status: "error", error: errMsg, latencyMs: Date.now() - t0 });
418
+ if (!isRetryableError(err)) {
419
+ throw new Error(`chatbotlite: ${visionStep.label} vision failed (non-retryable). ${errMsg}`);
420
+ }
421
+ }
422
+ }
423
+ const summary = attempts.map((a) => `${a.provider}/${a.model}:${a.error ?? "ok"}`).join(" \u2192 ");
424
+ throw new Error(`chatbotlite: no vision-capable provider succeeded. Trace: ${summary}. Last error: ${lastError instanceof Error ? lastError.message : String(lastError)}`);
119
425
  }
120
426
  async reply(message, opts = {}) {
121
- const systemPrompt = opts.systemPrompt ?? this.cachedSystemPrompt;
427
+ let inputVerdict;
428
+ if (this.guards.inputJudge) {
429
+ inputVerdict = await this.judge(this.guards.inputJudge, message);
430
+ if (inputVerdict.decision === "BLOCK") {
431
+ return {
432
+ reply: "I can't process that request. Please ask in a different way.",
433
+ usedProvider: this.steps[0].provider,
434
+ usedModel: this.steps[0].model,
435
+ guardWarnings: [],
436
+ judges: { input: inputVerdict },
437
+ attempts: [],
438
+ blockedByInputJudge: true
439
+ };
440
+ }
441
+ }
442
+ const systemPrompt = this.resolveSystemPrompt(opts);
122
443
  const messages = [
123
444
  { role: "system", content: systemPrompt },
124
445
  ...opts.history ?? [],
@@ -132,13 +453,21 @@ var ChatBot = class {
132
453
  const result = await this.callProvider(step, messages);
133
454
  attempts.push({ provider: step.provider, model: step.model, status: "ok", latencyMs: Date.now() - t0 });
134
455
  const guard = checkForbiddenPhrases(result.reply);
135
- const finalReply = guard.ok ? result.reply : stripForbidden(result.reply);
456
+ let finalReply = guard.ok ? result.reply : stripForbidden(result.reply);
457
+ let outputVerdict;
458
+ if (this.guards.outputJudge) {
459
+ outputVerdict = await this.judge(this.guards.outputJudge, finalReply);
460
+ if (outputVerdict.decision === "BLOCK") {
461
+ finalReply = "Let me check with the owner and get back to you on that.";
462
+ }
463
+ }
136
464
  return {
137
465
  reply: finalReply,
138
466
  usedProvider: step.provider,
139
467
  usedModel: step.model,
140
468
  ...result.usage ? { usage: result.usage } : {},
141
469
  guardWarnings: guard.violations,
470
+ ...inputVerdict || outputVerdict ? { judges: { ...inputVerdict ? { input: inputVerdict } : {}, ...outputVerdict ? { output: outputVerdict } : {} } } : {},
142
471
  attempts
143
472
  };
144
473
  } catch (err) {
@@ -224,6 +553,6 @@ function normalizeChainEntry(entry, keys) {
224
553
  return { provider, model, label: `${provider}/${model}` };
225
554
  }
226
555
 
227
- export { ChatBot, FORBIDDEN_PHRASES, PROVIDER_ENDPOINTS, buildSystemPrompt, checkForbiddenPhrases, isKnownProvider, isRetryableError, stripForbidden };
556
+ export { ChatBot, FORBIDDEN_PHRASES, PROVIDER_ENDPOINTS, buildSystemPrompt, buildToolsPromptAddendum, checkForbiddenPhrases, fileToDataUrl, isKnownProvider, isRetryableError, parseToolMarkers, runJudge, stripForbidden, stripToolMarkers };
228
557
  //# sourceMappingURL=index.js.map
229
558
  //# sourceMappingURL=index.js.map