botpsy-0.8b-web / packages /tools /src /protocol.ts
null
feat: deploy BotPsy local WebGPU static Space
1cc8d34
Raw History Blame Contribute Delete
5.85 kB
import type { JsonSchema, ToolCall } from '@botpsy/protocol';
export interface ParsedToolCall {
name: string;
arguments: Record<string, unknown>;
raw: string;
complete: boolean;
}
export interface ParsedAssistantText {
reasoning: string;
answer: string;
calls: ParsedToolCall[];
/** Raw generated text retained for auditing. */
raw: string;
hasOpenToolCall: boolean;
}
/** Parse the pinned Qwen/BotPsy XML-like tool protocol without assuming XML. */
export function parseToolCallBlock(block: string): ParsedToolCall | null {
const functionMatch = /<function=([^>\s]+)>/.exec(block);
if (!functionMatch) return null;
const name = functionMatch[1]!;
const argumentsObject: Record<string, unknown> = {};
const parameterPattern = /<parameter=([^>\s]+)>\n([\s\S]*?)\n<\/parameter>/g;
for (const match of block.matchAll(parameterPattern)) {
const key = match[1]!;
const rawValue = match[2]!;
const trimmed = rawValue.trim();
let parsed: unknown = rawValue;
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
try {
parsed = JSON.parse(trimmed);
} catch {
parsed = rawValue;
}
} else if (trimmed === 'true') parsed = true;
else if (trimmed === 'false') parsed = false;
else if (trimmed === 'null') parsed = null;
else if (/^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(trimmed)) parsed = Number(trimmed);
argumentsObject[key] = parsed;
}
return {
name,
arguments: argumentsObject,
raw: block,
complete: block.includes('</function>') && block.includes('</tool_call>'),
};
}
export function parseAssistantText(raw: string, thinking: boolean): ParsedAssistantText {
let reasoning = '';
let rest = raw;
if (thinking) {
const close = raw.indexOf('</think>');
if (close >= 0) {
reasoning = raw.slice(0, close).replace(/^<think>\s*/, '').replace(/\s+$/, '');
rest = raw.slice(close + '</think>'.length).replace(/^\s+/, '');
} else {
// Still inside the thinking channel; hide nothing from the reasoning view.
const open = raw.indexOf('<think>');
reasoning = (open >= 0 ? raw.slice(open + '<think>'.length) : raw).replace(/\s+$/, '');
rest = '';
}
}
const calls: ParsedToolCall[] = [];
let visible = '';
let cursor = 0;
let hasOpenToolCall = false;
while (cursor < rest.length) {
const start = rest.indexOf('<tool_call>', cursor);
if (start < 0) {
visible += rest.slice(cursor);
break;
}
visible += rest.slice(cursor, start);
const end = rest.indexOf('</tool_call>', start);
if (end < 0) {
hasOpenToolCall = true;
const partial = rest.slice(start);
const parsed = parseToolCallBlock(partial);
if (parsed) calls.push(parsed);
break;
}
const block = rest.slice(start, end + '</tool_call>'.length);
const parsed = parseToolCallBlock(block);
if (parsed) calls.push(parsed);
cursor = end + '</tool_call>'.length;
}
return { reasoning, answer: visible.trim(), calls, raw, hasOpenToolCall };
}
export function validateToolCall(call: ToolCall, schema: JsonSchema): string[] {
const errors: string[] = [];
validateValue(call.arguments, schema, 'arguments', errors, 0);
return errors;
}
function validateValue(value: unknown, schema: JsonSchema, path: string, errors: string[], depth: number): void {
if (depth > 16) {
errors.push(`${path}: nesting depth exceeded`);
return;
}
if (schema.enum && !schema.enum.includes(value as never)) {
errors.push(`${path}: value is not in the allowed enum`);
return;
}
switch (schema.type) {
case 'object': {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
errors.push(`${path}: expected object`);
return;
}
const object = value as Record<string, unknown>;
for (const required of schema.required ?? []) {
if (!(required in object)) errors.push(`${path}.${required}: required field missing`);
}
if (schema.additionalProperties === false) {
for (const key of Object.keys(object)) {
if (!(key in (schema.properties ?? {}))) errors.push(`${path}.${key}: unknown field`);
}
}
for (const [key, child] of Object.entries(schema.properties ?? {})) {
if (key in object) validateValue(object[key], child, `${path}.${key}`, errors, depth + 1);
}
return;
}
case 'array':
if (!Array.isArray(value)) {
errors.push(`${path}: expected array`);
return;
}
if (schema.items) {
value.forEach((item, index) => validateValue(item, schema.items!, `${path}[${index}]`, errors, depth + 1));
}
return;
case 'string':
if (typeof value !== 'string') {
errors.push(`${path}: expected string`);
return;
}
if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(`${path}: too short`);
if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(`${path}: too long`);
return;
case 'number':
case 'integer':
if (typeof value !== 'number' || !Number.isFinite(value)) {
errors.push(`${path}: expected ${schema.type}`);
return;
}
if (schema.type === 'integer' && !Number.isInteger(value)) errors.push(`${path}: expected integer`);
if (schema.minimum !== undefined && value < schema.minimum) errors.push(`${path}: below minimum`);
if (schema.maximum !== undefined && value > schema.maximum) errors.push(`${path}: above maximum`);
return;
case 'boolean':
if (typeof value !== 'boolean') errors.push(`${path}: expected boolean`);
return;
case 'null':
if (value !== null) errors.push(`${path}: expected null`);
return;
default:
return;
}
}