The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Text helper: tool calling for chat
Adarsh1b91197b754a
diff --git a/bin/lib/worker/text.mjs b/bin/lib/worker/text.mjsindex 6e69ad11..cb8e3c98 100644--- a/bin/lib/worker/text.mjs+++ b/bin/lib/worker/text.mjs@@ -176,64 +176,137 @@ export function jobOf(body) {}images = j.images;}- // A chat's turns: the person's and the model's, the newest the person's.+ // A chat's turns: the person's, the model's (words, tool calls or both) and tools' results; the newest the person's+ // or a tool's.let messages = null;if (j.messages !== undefined) {if (!Array.isArray(j.messages) || !j.messages.length || j.messages.length > CHAT_LIMITS.turns) return null;let chars = 0;+ messages = [];for (const m of j.messages) {- if (!m || (m.role !== "user" && m.role !== "assistant") || typeof m.content !== "string") return null;- chars += m.content.length;+ const turn = turnOf(m);+ if (!turn) return null;+ chars += (turn.content ?? "").length + (turn.tool_calls ?? []).reduce((a, c) => a + c.function.name.length + c.function.arguments.length, 0);+ messages.push(turn);}- if (chars > CHAT_LIMITS.chars || j.messages.at(-1).role !== "user") return null;- messages = j.messages.map((m) => ({ role: m.role, content: m.content }));+ if (chars > CHAT_LIMITS.chars || !["user", "tool"].includes(messages.at(-1).role)) return null;+ }+ // Tools the model may call (OpenAI function definitions), and how it may choose among them.+ let tools = null;+ let toolChoice = null;+ if (j.tools !== undefined) {+ if (!messages || !Array.isArray(j.tools) || !j.tools.length || j.tools.length > CHAT_LIMITS.tools || JSON.stringify(j.tools).length > CHAT_LIMITS.toolsChars) return null;+ tools = [];+ for (const t of j.tools) {+ const fn = t?.function;+ if (t?.type !== "function" || !fn || typeof fn.name !== "string" || !TOOL_NAME.test(fn.name) || (fn.description !== undefined && typeof fn.description !== "string") || !fn.parameters || typeof fn.parameters !== "object" || Array.isArray(fn.parameters)) return null;+ tools.push({ type: "function", function: { name: fn.name, ...(fn.description !== undefined && { description: fn.description }), parameters: fn.parameters } });+ }+ const c = j.toolChoice;+ if (c === "auto" || c === "none") toolChoice = c;+ else if (c?.type === "function" && tools.some((t) => t.function.name === c.function?.name)) toolChoice = { type: "function", function: { name: c.function.name } };+ else if (c !== undefined) return null;}const sampling = {};for (const [k, [lo, hi]] of Object.entries(SAMPLING_BOUNDS)) {const v = j.sampling?.[k];if (typeof v === "number" && Number.isFinite(v)) sampling[k] = Math.min(hi, Math.max(lo, v));}- return { id: j.id, lease: j.lease, system: j.system, user: j.user, maxTokens, json: j.json === true, images, messages, sampling, stream: j.stream === true };+ return { id: j.id, lease: j.lease, system: j.system, user: j.user, maxTokens, json: j.json === true, images, messages, sampling, stream: j.stream === true, tools, toolChoice };}-/** What a chat may carry (the studio sends at most 24,000 characters of turns). */-const CHAT_LIMITS = { turns: 200, chars: 32_000 };+/** What a chat may carry (the studio sends at most 24,000 characters of turns and 32,000 of tools). */+const CHAT_LIMITS = { turns: 200, chars: 32_000, tools: 64, toolsChars: 40_000, calls: 16, argsChars: 8000 };+const TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/;+const CALL_ID = /^[A-Za-z0-9_.:-]{1,100}$/;++/** One chat turn, checked, with only its own fields; null when it isn't one. */+function turnOf(m) {+ if (!m || typeof m !== "object") return null;+ if (m.role === "user") return typeof m.content === "string" ? { role: "user", content: m.content } : null;+ if (m.role === "tool") return typeof m.content === "string" && typeof m.tool_call_id === "string" && CALL_ID.test(m.tool_call_id) ? { role: "tool", tool_call_id: m.tool_call_id, content: m.content } : null;+ if (m.role !== "assistant" || (m.content !== undefined && typeof m.content !== "string")) return null;+ let calls = null;+ if (m.tool_calls !== undefined) {+ if (!Array.isArray(m.tool_calls) || !m.tool_calls.length || m.tool_calls.length > CHAT_LIMITS.calls) return null;+ calls = [];+ for (const c of m.tool_calls) {+ if (c?.type !== "function" || typeof c.id !== "string" || !CALL_ID.test(c.id) || typeof c.function?.name !== "string" || !TOOL_NAME.test(c.function.name) || typeof c.function.arguments !== "string" || c.function.arguments.length > CHAT_LIMITS.argsChars) return null;+ calls.push({ id: c.id, type: "function", function: { name: c.function.name, arguments: c.function.arguments } });+ }+ } else if (typeof m.content !== "string") return null;+ return { role: "assistant", content: m.content ?? "", ...(calls && { tool_calls: calls }) };+}/** The sampling a job may ask for, each inside these bounds. */const SAMPLING_BOUNDS = { temperature: [0, 2], top_p: [0.05, 1] };/*** The request body for one job: the family's template switches and sampling (the job's own over them), a chat's turns- * as real turns, the pictures before the words of the newest turn.+ * as real turns (tool calls and tools' results too), the pictures before the words of the person's newest turn, and the+ * tools the model may call.*/export function chatBody(job, slot = {}) {const fam = familyOf(slot);const pictures = job.images ?? [];const turns = job.messages?.length ? job.messages : [{ role: "user", content: job.user }];- const last = turns.length - 1;+ const last = turns.findLastIndex((m) => m.role === "user");const withPictures = (text) => (pictures.length ? [...pictures.map((b) => ({ type: "image_url", image_url: { url: `data:image/jpeg;base64,${b}` } })), { type: "text", text }] : text);return {model: modelName(slot),- messages: [...(job.system ? [{ role: "system", content: job.system }] : []), ...turns.map((m, n) => ({ role: m.role, content: n === last ? withPictures(m.content) : m.content }))],+ messages: [...(job.system ? [{ role: "system", content: job.system }] : []), ...turns.map((m, n) => ({ ...m, content: n === last ? withPictures(m.content) : m.content }))],max_tokens: job.maxTokens,...fam.sampling,...job.sampling,stream: !!job.stream,...(fam.kwargs && { chat_template_kwargs: fam.kwargs }),...(job.json && { response_format: { type: "json_object" } }),+ ...(job.tools?.length && { tools: job.tools, ...(job.toolChoice && { tool_choice: job.toolChoice }) }),};}+/** The tool calls in an answer, as the studio takes them: { id, name, arguments } (arguments as JSON text). */+export function callsOf(raw) {+ if (!Array.isArray(raw)) return [];+ return raw+ .filter((c) => typeof c?.function?.name === "string" && c.function.name)+ .slice(0, CHAT_LIMITS.calls)+ .map((c, n) => ({ id: typeof c.id === "string" && CALL_ID.test(c.id) ? c.id : `call_${n + 1}`, name: c.function.name, arguments: typeof c.function.arguments === "string" ? c.function.arguments : JSON.stringify(c.function.arguments ?? {}) }));+}++/** Why an answer stopped, as the studio takes it. */+const finishOf = (reason, calls) => (calls.length ? "tool_calls" : reason === "length" ? "length" : "stop");+/** The words in one server-sent event line of a streamed answer ("" for anything else). */export function streamedWords(line) {- if (!line.startsWith("data:")) return "";+ return streamedPart(line).words;+}++/** One server-sent event line of a streamed answer: its words, its pieces of tool calls, and why it stopped. */+export function streamedPart(line) {+ const none = { words: "", calls: [], finish: null };+ if (!line.startsWith("data:")) return none;const data = line.slice(5).trim();- if (!data || data === "[DONE]") return "";+ if (!data || data === "[DONE]") return none;try {- const c = JSON.parse(data)?.choices?.[0]?.delta?.content;- return typeof c === "string" ? c : "";+ const choice = JSON.parse(data)?.choices?.[0];+ const c = choice?.delta?.content;+ return { words: typeof c === "string" ? c : "", calls: Array.isArray(choice?.delta?.tool_calls) ? choice.delta.tool_calls : [], finish: typeof choice?.finish_reason === "string" ? choice.finish_reason : null };} catch {- return "";+ return none;+ }+}++/** Tool calls put together from their streamed pieces (by index: the id and name come first, the arguments in pieces). */+export function joinCalls(pieces) {+ const calls = [];+ for (const p of pieces) {+ const n = Number.isInteger(p?.index) ? p.index : calls.length ? calls.length - 1 : 0;+ const c = (calls[n] ??= { id: null, type: "function", function: { name: "", arguments: "" } });+ if (typeof p.id === "string" && p.id) c.id = p.id;+ if (typeof p.function?.name === "string") c.function.name += p.function.name;+ if (typeof p.function?.arguments === "string") c.function.arguments += p.function.arguments;}+ return calls.filter(Boolean);}/** The worker's stop for a job whose caller went: its answer isn't sent. */@@ -353,7 +426,7 @@ export class TextSlot {const res = await this.d.call("/api/gpu/computer/text/claim", {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ model: modelName(this.slot), device, vision: !!this.slot.mmproj, chat: true, wait: this.slot.claimWaitMs }),+ body: JSON.stringify({ model: modelName(this.slot), device, vision: !!this.slot.mmproj, chat: true, tools: true, wait: this.slot.claimWaitMs }),signal: AbortSignal.any([this.ending.signal, claiming.signal]),});if (res.status === 204 || !res.ok) {@@ -382,7 +455,8 @@ export class TextSlot {try {if (job.images.length && !this.slot.mmproj) throw new Error("this slot's model doesn't take pictures");await this.ensure(device);- answer = { text: await this.complete(job) };+ const a = await this.complete(job);+ answer = typeof a === "string" ? { text: a } : a;} catch (e) {this.lastJobAt = this.now();// The person went: the studio ended the job, so there is nothing to send.@@ -412,9 +486,12 @@ export class TextSlot {});if (!r.ok) throw new Error(`llama-server answered ${r.status}`);const body = await r.json();- const text = body?.choices?.[0]?.message?.content;+ const choice = body?.choices?.[0];+ const text = choice?.message?.content;+ const calls = job.tools?.length ? callsOf(choice?.message?.tool_calls) : [];+ if (calls.length) return { text: typeof text === "string" ? text : "", toolCalls: calls, finish: "tool_calls" };if (typeof text !== "string" || !text.trim()) throw new Error("llama-server gave no text");- return text;+ return job.tools?.length || job.messages ? { text, finish: finishOf(choice?.finish_reason, calls) } : text;}/**@@ -435,6 +512,14 @@ export class TextSlot {// No words for answerMs (the prompt's own reading included): it ends.let idle = setTimeout(() => end("llama-server went quiet"), this.slot.answerMs);let text = "";+ const pieces = [];+ let reason = null;+ const take = (line) => {+ const p = streamedPart(line);+ text += p.words;+ pieces.push(...p.calls);+ reason = p.finish ?? reason;+ };let sent = "";let sentAt = 0;let posting = null;@@ -480,9 +565,9 @@ export class TextSlot {buf += decoder.decode(value, { stream: true });const lines = buf.split("\n");buf = lines.pop();- for (const line of lines) text += streamedWords(line.trim());+ for (const line of lines) take(line.trim());}- text += streamedWords((buf + decoder.decode()).trim());+ take((buf + decoder.decode()).trim());} catch (e) {if (stopped) throw new Stopped("stopped");if (why) throw new Error(why);@@ -495,8 +580,9 @@ export class TextSlot {await posting;}if (stopped) throw new Stopped("stopped");- if (!text.trim()) throw new Error("llama-server gave no text");- return text;+ const calls = job.tools?.length ? callsOf(joinCalls(pieces)) : [];+ if (!text.trim() && !calls.length) throw new Error("llama-server gave no text");+ return { text, ...(calls.length && { toolCalls: calls }), finish: finishOf(reason, calls) };}/** Its server on this device, started now when it isn't (another device's is stopped first). */diff --git a/src/app/api/gpu/computer/text/claim/route.ts b/src/app/api/gpu/computer/text/claim/route.tsindex 5fc14bde..11522c01 100644--- a/src/app/api/gpu/computer/text/claim/route.ts+++ b/src/app/api/gpu/computer/text/claim/route.ts@@ -7,7 +7,7 @@ const no = (status: number, error: string) => Response.json({ error }, { status,/*** A worker's text slot asks for the free helper's next text job (src/server/text-helper.ts). It waits up to 20 s for one* (or `wait` ms, less): the job, or 204. A slot that says `chat: true` also takes chats (their turns, and it sends- * the words so far to text/:id/partial).+ * the words so far to text/:id/partial); with `tools: true` too, chats that offer tools.*/export async function POST(request: Request) {await connection();@@ -17,13 +17,13 @@ export async function POST(request: Request) {if (worker?.kind !== "pool") return no(403, "Only a shared worker takes text jobs.");const limited = rateOf(callerKey(request, principal), "claim-text", 60);if (limited) return limited;- const body = ((await request.json().catch(() => null)) ?? {}) as { model?: unknown; device?: unknown; vision?: unknown; chat?: unknown; wait?: unknown };+ const body = ((await request.json().catch(() => null)) ?? {}) as { model?: unknown; device?: unknown; vision?: unknown; chat?: unknown; tools?: unknown; wait?: unknown };const asked = Number(body.wait);const wait = Number.isFinite(asked) ? Math.max(0, Math.min(HELPER_TIMES.claimWaitMs, asked)) : HELPER_TIMES.claimWaitMs;const end = Date.now() + wait;// The slot is noted live on the first look; later looks read the line first and claim only when a job waits.for (let first = true; ; first = false) {- const job = first || helperWaiting(body.vision === true, body.chat === true) ? claimHelperJob(worker, body, Date.now(), first) : null;+ const job = first || helperWaiting(body.vision === true, body.chat === true, body.chat === true && body.tools === true) ? claimHelperJob(worker, body, Date.now(), first) : null;if (job) return Response.json({ job }, { headers: { "Cache-Control": "no-store" } });if (Date.now() >= end || request.signal.aborted) return new Response(null, { status: 204, headers: { "Cache-Control": "no-store" } });await new Promise((r) => setTimeout(r, HELPER_TIMES.pollMs));diff --git a/src/server/db.ts b/src/server/db.tsindex 3980bfe6..a2ec54c0 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -1204,6 +1204,13 @@ function open(): Database.Database {// Why a slot takes no jobs for now ("updating": its worker restarts on new code), and since when.["helper_slots", "away", "TEXT"],["helper_slots", "away_at", "INTEGER"],+ // Tool calling: the tools a chat offers and how to choose, the calls in its answer and why it stopped, the slots+ // that take tools.+ ["helper_jobs", "tools_json", "TEXT"],+ ["helper_jobs", "tool_choice_json", "TEXT"],+ ["helper_jobs", "tool_calls_json", "TEXT"],+ ["helper_jobs", "finish", "TEXT"],+ ["helper_slots", "tools", "INTEGER NOT NULL DEFAULT 0"],]) {if (!(db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[]).some((c) => c.name === column)) addColumn(db, `ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);}@@ -1412,7 +1419,11 @@ const HELPER_TABLES = `CREATE TABLE IF NOT EXISTS helper_jobs (sampling_json TEXT,stream INTEGER NOT NULL DEFAULT 0,partial TEXT,- partial_at INTEGER+ partial_at INTEGER,+ tools_json TEXT,+ tool_choice_json TEXT,+ tool_calls_json TEXT,+ finish TEXT);CREATE INDEX IF NOT EXISTS helper_jobs_line ON helper_jobs(state, created_at);CREATE TABLE IF NOT EXISTS helper_slots (@@ -1423,7 +1434,8 @@ const HELPER_TABLES = `CREATE TABLE IF NOT EXISTS helper_jobs (vision INTEGER NOT NULL DEFAULT 0,chat INTEGER NOT NULL DEFAULT 0,away TEXT,- away_at INTEGER+ away_at INTEGER,+ tools INTEGER NOT NULL DEFAULT 0);`;export function db(): Database.Database {diff --git a/src/server/text-helper.ts b/src/server/text-helper.tsindex a82e59b9..f30f3efc 100644--- a/src/server/text-helper.ts+++ b/src/server/text-helper.ts@@ -67,16 +67,52 @@ export const HELPER_LIMITS = {/** A chat's turns: how many, and their words together (the caller trims older turns itself). */chatTurns: 200,chatChars: 24_000,+ /** Tools a chat may offer: how many, and their definitions as JSON together. */+ tools: 64,+ toolsChars: 32_000,+ /** Tool calls in one answer or one assistant turn, and the arguments of one. */+ toolCalls: 16,+ toolArgsChars: 8000,/** Pictures a job may carry: how many, how big each may come in, and as the small JPEG it is sent as. */pictures: { count: 4, inputBytes: 20 * 2 ** 20, longEdge: 1024, outputBytes: 512 * 1024 },};-/** One turn of a chat. */-export interface HelperMessage {- role: "user" | "assistant";- content: string;+/** A tool call as a chat's assistant turn carries it (OpenAI's shape; `arguments` is JSON text). */+export interface HelperToolCall {+ id: string;+ type: "function";+ function: { name: string; arguments: string };+}++/**+ * One turn of a chat: the person's, the model's (its words, the tools it called, or both), or a tool's result for one+ * of those calls.+ */+export type HelperMessage =+ | { role: "user"; content: string }+ | { role: "assistant"; content?: string; tool_calls?: HelperToolCall[] }+ | { role: "tool"; tool_call_id: string; content: string };++/** A tool a chat offers the model (an OpenAI function definition). */+export interface HelperTool {+ type: "function";+ function: { name: string; description?: string; parameters: object };+}++export type HelperToolChoice = "auto" | "none" | { type: "function"; function: { name: string } };++/** A tool the model called in its answer. */+export interface HelperCall {+ id: string;+ name: string;+ /** JSON text, as the model wrote it (the caller parses and checks it). */+ arguments: string;}+/** A tool's name: what OpenAI's function names allow. */+const TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/;+const CALL_ID = /^[A-Za-z0-9_.:-]{1,100}$/;+/** The sampling a job may ask for, each inside these bounds. */export const HELPER_SAMPLING = { temperature: [0, 2], top_p: [0.05, 1] } as const;@@ -93,21 +129,103 @@ export function helperSampling(s: HelperSampling | undefined | null): HelperSampreturn Object.keys(out).length ? out : null;}-/** Why these chat turns can't be sent, or null: user and assistant turns, the newest the person's, within the limits. */+/** Why these tool calls can't be kept, or null. */+function toolCallsProblem(calls: unknown): string | null {+ if (!Array.isArray(calls) || !calls.length || calls.length > HELPER_LIMITS.toolCalls) return "a turn's tool calls aren't a short list";+ for (const c of calls as Partial<HelperToolCall>[]) {+ if (!c || typeof c !== "object" || c.type !== "function" || typeof c.id !== "string" || !CALL_ID.test(c.id)) return "a tool call has no id";+ const f = c.function;+ if (!f || typeof f.name !== "string" || !TOOL_NAME.test(f.name) || typeof f.arguments !== "string" || f.arguments.length > HELPER_LIMITS.toolArgsChars) return "a tool call isn't a name with its arguments";+ }+ return null;+}++/**+ * Why these chat turns can't be sent, or null: the person's turns, the model's (words, tool calls or both) and tools'+ * results for calls made before them; the newest the person's or a tool's; within the limits.+ */export function helperMessagesProblem(messages: unknown): string | null {if (!Array.isArray(messages) || !messages.length) return "no turns";if (messages.length > HELPER_LIMITS.chatTurns) return "too many turns";let chars = 0;- for (const m of messages as Partial<HelperMessage>[]) {- if (!m || typeof m !== "object" || (m.role !== "user" && m.role !== "assistant") || typeof m.content !== "string") return "a turn isn't a user or assistant turn with words";- chars += m.content.length;+ const called = new Set<string>();+ for (const m of messages as Record<string, unknown>[]) {+ if (!m || typeof m !== "object") return "a turn isn't a user, assistant or tool turn";+ if (m.role === "user") {+ if (typeof m.content !== "string") return "a person's turn has no words";+ chars += m.content.length;+ } else if (m.role === "assistant") {+ if (m.content !== undefined && typeof m.content !== "string") return "an assistant turn's words aren't text";+ if (m.tool_calls !== undefined) {+ const p = toolCallsProblem(m.tool_calls);+ if (p) return p;+ for (const c of m.tool_calls as HelperToolCall[]) {+ called.add(c.id);+ chars += c.function.name.length + c.function.arguments.length;+ }+ } else if (typeof m.content !== "string") return "an assistant turn has neither words nor tool calls";+ chars += typeof m.content === "string" ? m.content.length : 0;+ } else if (m.role === "tool") {+ if (typeof m.tool_call_id !== "string" || !called.has(m.tool_call_id)) return "a tool's result answers no call before it";+ if (typeof m.content !== "string") return "a tool's result isn't text";+ chars += m.content.length;+ } else return "a turn isn't a user, assistant or tool turn";}if (chars > HELPER_LIMITS.chatChars) return "too long";const last = messages[messages.length - 1] as HelperMessage;- if (last.role !== "user" || !last.content.trim()) return "the newest turn isn't the person's";+ if (last.role === "tool") return null;+ if (last.role !== "user" || !last.content.trim()) return "the newest turn isn't the person's or a tool's";return null;}+/** Why these tools (and the choice among them) can't be offered, or null. */+export function helperToolsProblem(tools: unknown, choice?: unknown): string | null {+ if (!Array.isArray(tools) || !tools.length) return "no tools";+ if (tools.length > HELPER_LIMITS.tools) return "too many tools";+ const names = new Set<string>();+ for (const t of tools as Partial<HelperTool>[]) {+ const f = t?.function;+ if (!t || t.type !== "function" || !f || typeof f.name !== "string" || !TOOL_NAME.test(f.name)) return "a tool has no name";+ if (names.has(f.name)) return "two tools have the same name";+ names.add(f.name);+ if (f.description !== undefined && typeof f.description !== "string") return "a tool's description isn't text";+ if (!f.parameters || typeof f.parameters !== "object" || Array.isArray(f.parameters)) return "a tool's parameters aren't a schema";+ }+ if (JSON.stringify(tools).length > HELPER_LIMITS.toolsChars) return "the tools are too long";+ if (choice === undefined || choice === "auto" || choice === "none") return null;+ const c = choice as { type?: unknown; function?: { name?: unknown } };+ if (c && typeof c === "object" && c.type === "function" && typeof c.function?.name === "string" && names.has(c.function.name)) return null;+ return "the tool choice names no tool";+}++/** The tool calls a slot sent, kept only in their shape and only for tools the job offered. */+function callsOf(raw: unknown, offered: Set<string>): HelperCall[] {+ if (!Array.isArray(raw)) return [];+ const out: HelperCall[] = [];+ for (const c of raw.slice(0, HELPER_LIMITS.toolCalls) as Partial<HelperCall>[]) {+ if (!c || typeof c.name !== "string" || !offered.has(c.name) || typeof c.arguments !== "string" || c.arguments.length > HELPER_LIMITS.toolArgsChars) continue;+ out.push({ id: typeof c.id === "string" && CALL_ID.test(c.id) ? c.id : `call_${out.length + 1}`, name: c.name, arguments: c.arguments });+ }+ return out;+}++const FINISH = new Set(["stop", "tool_calls", "length"]);++/** A checked turn with only its own fields. */+const turnOf = (m: HelperMessage): HelperMessage =>+ m.role === "user"+ ? { role: "user", content: m.content }+ : m.role === "tool"+ ? { role: "tool", tool_call_id: m.tool_call_id, content: m.content }+ : {+ role: "assistant",+ ...(m.content !== undefined && { content: m.content }),+ ...(m.tool_calls && { tool_calls: m.tool_calls.map((c) => ({ id: c.id, type: "function" as const, function: { name: c.function.name, arguments: c.function.arguments } })) }),+ };++/** A checked tool with only its own fields. */+const toolOf = (t: HelperTool): HelperTool => ({ type: "function", function: { name: t.function.name, ...(t.function.description !== undefined && { description: t.function.description }), parameters: t.function.parameters } });+/** Whose job: "owner", "acct:<id>", or "guest:<address key>". */export type HelperWho = string;@@ -140,6 +258,10 @@ interface JobRow {stream: number | null;partial: string | null;partial_at: number | null;+ tools_json: string | null;+ tool_choice_json: string | null;+ tool_calls_json: string | null;+ finish: string | null;}/** A job as a text slot gets it. */@@ -159,6 +281,9 @@ export interface HelperJob {sampling?: HelperSampling;/** The slot sends the words so far as they come (POST /api/gpu/computer/text/:id/partial). */stream?: true;+ /** Tools the model may call (only to a slot that takes tools), and how it may choose among them. */+ tools?: HelperTool[];+ toolChoice?: HelperToolChoice;}const json = <T,>(s: string | null, fallback: T): T => {@@ -187,9 +312,9 @@ export function textEligible(w: WorkerRow, now = Date.now()): boolean {* A text slot asked for a job in the last moments, from a worker that may take one (`vision`: one whose model sees* pictures; `chat`: one that takes chats).*/-export function helperLive(now = Date.now(), o: { vision?: boolean; chat?: boolean } = {}): boolean {+export function helperLive(now = Date.now(), o: { vision?: boolean; chat?: boolean; tools?: boolean } = {}): boolean {const rows = db()- .prepare(`SELECT w.* FROM helper_slots s JOIN relay_workers w ON w.id = s.worker_id WHERE s.seen_at >= ? AND s.away IS NULL${o.vision ? " AND s.vision = 1" : ""}${o.chat ? " AND s.chat = 1" : ""}`)+ .prepare(`SELECT w.* FROM helper_slots s JOIN relay_workers w ON w.id = s.worker_id WHERE s.seen_at >= ? AND s.away IS NULL${o.vision ? " AND s.vision = 1" : ""}${o.chat ? " AND s.chat = 1" : ""}${o.tools ? " AND s.tools = 1" : ""}`).all(now - HELPER_TIMES.liveMs) as WorkerRow[];return rows.some((w) => textEligible(w, now));}@@ -201,10 +326,10 @@ export function helperLive(now = Date.now(), o: { vision?: boolean; chat?: boole*/export type HelperState = "ready" | "busy" | "starting" | "absent";-export function helperState(now = Date.now(), o: { vision?: boolean; chat?: boolean } = {}): HelperState {+export function helperState(now = Date.now(), o: { vision?: boolean; chat?: boolean; tools?: boolean } = {}): HelperState {const d = db();const rows = d- .prepare(`SELECT w.*, s.seen_at AS slot_seen_at, s.away AS slot_away FROM helper_slots s JOIN relay_workers w ON w.id = s.worker_id WHERE s.seen_at >= ?${o.vision ? " AND s.vision = 1" : ""}${o.chat ? " AND s.chat = 1" : ""}`)+ .prepare(`SELECT w.*, s.seen_at AS slot_seen_at, s.away AS slot_away FROM helper_slots s JOIN relay_workers w ON w.id = s.worker_id WHERE s.seen_at >= ?${o.vision ? " AND s.vision = 1" : ""}${o.chat ? " AND s.chat = 1" : ""}${o.tools ? " AND s.tools = 1" : ""}`).all(now - HELPER_TIMES.startingMs) as (WorkerRow & { slot_seen_at: number; slot_away: string | null })[];const live = rows.filter((r) => r.slot_away === null && now - r.slot_seen_at <= HELPER_TIMES.liveMs && textEligible(r, now));if (live.length) {@@ -235,13 +360,13 @@ export function noteHelperAway(w: WorkerRow, state: unknown, now = Date.now()):* How the free helper stands for this call: helperState, and "absent" for a call that may not use it (a guest's, or an* account's while hosted runs are off). A chat may be asked unless "absent": it waits for a slot that is coming back.*/-export function freeHelperState(now = Date.now(), o: { vision?: boolean; chat?: boolean } = {}): HelperState {+export function freeHelperState(now = Date.now(), o: { vision?: boolean; chat?: boolean; tools?: boolean } = {}): HelperState {const t = tenant();return !t || (t.kind === "account" && hostedRunsOn()) ? helperState(now, o) : "absent";}/** May this call use the free helper now: it is live, and an account's call only while hosted runs are on (a guest's never: sign up first). */-export function freeHelperOn(now = Date.now(), o: { vision?: boolean; chat?: boolean } = {}): boolean {+export function freeHelperOn(now = Date.now(), o: { vision?: boolean; chat?: boolean; tools?: boolean } = {}): boolean {const t = tenant();return (!t || (t.kind === "account" && hostedRunsOn())) && helperLive(now, o);}@@ -287,7 +412,7 @@ export function sweepHelper(now = Date.now()): void {}/** The jobs a slot may take: one with pictures only where its model sees them, a chat only where the slot takes chats. */-const takes = (vision: boolean, chat: boolean) => `${vision ? "" : " AND images_json IS NULL"}${chat ? "" : " AND messages_json IS NULL"}`;+const takes = (vision: boolean, chat: boolean, tools = false) => `${vision ? "" : " AND images_json IS NULL"}${chat ? "" : " AND messages_json IS NULL"}${tools ? "" : " AND tools_json IS NULL"}`;/** The line's order: people's jobs first, then the owner's, oldest first. */const OWNER_LAST = "CASE WHEN who = 'owner' THEN 1 ELSE 0 END";@@ -297,27 +422,30 @@ const OWNER_LAST = "CASE WHEN who = 'owner' THEN 1 ELSE 0 END";* slot as live either way. `chat`: the slot takes chats (turns, and words sent as they come); an older worker never* says so, and gets the same jobs as before.*/-export function claimHelperJob(w: WorkerRow, slot: { model?: unknown; device?: unknown; vision?: unknown; chat?: unknown } = {}, now = Date.now(), note = true): HelperJob | null {+export function claimHelperJob(w: WorkerRow, slot: { model?: unknown; device?: unknown; vision?: unknown; chat?: unknown; tools?: unknown } = {}, now = Date.now(), note = true): HelperJob | null {const d = db();return d.transaction(() => {const model = typeof slot.model === "string" ? slot.model.slice(0, 120) : null;const device = slot.device === "gpu" || slot.device === "cpu" ? slot.device : null;const vision = slot.vision === true ? 1 : 0;const chat = slot.chat === true ? 1 : 0;+ const tools = chat && slot.tools === true ? 1 : 0;if (note) {d.prepare(- "INSERT INTO helper_slots (worker_id, seen_at, model, device, vision, chat, away, away_at) VALUES (?, ?, ?, ?, ?, ?, NULL, NULL) ON CONFLICT(worker_id) DO UPDATE SET seen_at = excluded.seen_at, model = excluded.model, device = excluded.device, vision = excluded.vision, chat = excluded.chat, away = NULL, away_at = NULL",- ).run(w.id, now, model, device, vision, chat);+ "INSERT INTO helper_slots (worker_id, seen_at, model, device, vision, chat, tools, away, away_at) VALUES (?, ?, ?, ?, ?, ?, ?, NULL, NULL) ON CONFLICT(worker_id) DO UPDATE SET seen_at = excluded.seen_at, model = excluded.model, device = excluded.device, vision = excluded.vision, chat = excluded.chat, tools = excluded.tools, away = NULL, away_at = NULL",+ ).run(w.id, now, model, device, vision, chat, tools);}const fresh = d.prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as WorkerRow | undefined;if (!fresh || !textEligible(fresh, now)) return null;- const row = d.prepare(`SELECT * FROM helper_jobs WHERE state = 'waiting'${takes(!!vision, !!chat)} ORDER BY ${OWNER_LAST}, created_at, id LIMIT 1`).get() as JobRow | undefined;+ const row = d.prepare(`SELECT * FROM helper_jobs WHERE state = 'waiting'${takes(!!vision, !!chat, !!tools)} ORDER BY ${OWNER_LAST}, created_at, id LIMIT 1`).get() as JobRow | undefined;if (!row || !isHelperTask(row.task)) return null;const lease = crypto.randomBytes(16).toString("base64url");d.prepare("UPDATE helper_jobs SET state = 'running', worker_id = ?, lease = ?, claimed_at = ? WHERE id = ? AND state = 'waiting'").run(w.id, lease, now, row.id);const images = json<string[] | null>(row.images_json, null);const messages = json<HelperMessage[] | null>(row.messages_json, null);const sampling = json<HelperSampling | null>(row.sampling_json, null);+ const offered = json<HelperTool[] | null>(row.tools_json, null);+ const toolChoice = json<HelperToolChoice | null>(row.tool_choice_json, null);return {id: row.id,lease,@@ -330,12 +458,13 @@ export function claimHelperJob(w: WorkerRow, slot: { model?: unknown; device?: u...(messages?.length && { messages }),...(sampling && { sampling }),...(row.stream ? { stream: true as const } : {}),+ ...(offered?.length && { tools: offered, ...(toolChoice && { toolChoice }) }),};}).immediate();}/** Is any text job waiting that this slot may take (a quick read before a claim)? */-export const helperWaiting = (vision = false, chat = false): boolean => !!db().prepare(`SELECT 1 FROM helper_jobs WHERE state = 'waiting'${takes(vision, chat)} LIMIT 1`).get();+export const helperWaiting = (vision = false, chat = false, tools = false): boolean => !!db().prepare(`SELECT 1 FROM helper_jobs WHERE state = 'waiting'${takes(vision, chat, tools)} LIMIT 1`).get();/** Where a waiting job stands in the line: 1 is next. Null once it isn't waiting. */export function helperPosition(id: string): number | null {@@ -367,20 +496,39 @@ export function partialHelperJob(w: WorkerRow, id: string, body: { lease?: unkno}/** A text slot's answer for its job (only with the lease its claim gave). False: not its job any more. */-export function finishHelperJob(w: WorkerRow, id: string, body: { lease?: unknown; text?: unknown; error?: unknown }, now = Date.now()): boolean {+export function finishHelperJob(w: WorkerRow, id: string, body: { lease?: unknown; text?: unknown; error?: unknown; toolCalls?: unknown; finish?: unknown }, now = Date.now()): boolean {if (typeof body.lease !== "string") return false;+ const d = db();let text: string | null = null;let error: string | null = null;if (typeof body.text === "string" && Buffer.byteLength(body.text) <= HELPER_LIMITS.textBytes) text = tidyHelperText(body.text);- if (!text) error = typeof body.error === "string" && body.error ? body.error.slice(0, 200) : "no-text";- const r = db()- .prepare("UPDATE helper_jobs SET state = ?, text = ?, error = ?, done_at = ? WHERE id = ? AND worker_id = ? AND lease = ? AND state = 'running'")- .run(text ? "done" : "failed", text, error, now, id, w.id, body.lease);+ // Tool calls count only for tools the job offered.+ let calls: HelperCall[] = [];+ if (body.toolCalls !== undefined) {+ const row = d.prepare("SELECT tools_json FROM helper_jobs WHERE id = ? AND worker_id = ? AND lease = ?").get(id, w.id, body.lease) as { tools_json: string | null } | undefined;+ const offered = new Set(json<HelperTool[]>(row?.tools_json ?? null, []).map((t) => t.function.name));+ calls = callsOf(body.toolCalls, offered);+ }+ const answered = !!text || calls.length > 0;+ if (!answered) error = typeof body.error === "string" && body.error ? body.error.slice(0, 200) : "no-text";+ const finish = typeof body.finish === "string" && FINISH.has(body.finish) ? (calls.length ? "tool_calls" : body.finish === "tool_calls" ? "stop" : body.finish) : calls.length ? "tool_calls" : null;+ const r = d+ .prepare("UPDATE helper_jobs SET state = ?, text = ?, error = ?, done_at = ?, tool_calls_json = ?, finish = ? WHERE id = ? AND worker_id = ? AND lease = ? AND state = 'running'")+ .run(answered ? "done" : "failed", answered ? (text ?? "") : null, error, now, calls.length ? JSON.stringify(calls) : null, answered ? finish : null, id, w.id, body.lease);return r.changes === 1;}/** "sign-in": a guest's call, refused before anything is checked or queued. */-export type HelperAnswer = { text: string } | { error: "busy" | "limit" | "blocked" | "failed" | "sign-in"; message?: string; retryAfterS?: number };+export type HelperAnswer =+ | {+ /** The model's words ("" when it only called tools). */+ text: string;+ /** The tools it called (a chat that offered tools), in order. */+ toolCalls?: HelperCall[];+ /** Why it stopped, from a worker that says: done, to call tools, or at its token limit. Missing: as "stop". */+ finish?: "stop" | "tool_calls" | "length";+ }+ | { error: "busy" | "limit" | "blocked" | "failed" | "sign-in"; message?: string; retryAfterS?: number };const rateOf = (who: HelperWho) => (who.startsWith("acct:") ? HELPER_LIMITS.account : who === "guest:shared" ? { perMinute: HELPER_LIMITS.guest.perMinute * 10, perHour: HELPER_LIMITS.guest.perHour * 10 } : HELPER_LIMITS.guest);@@ -396,6 +544,12 @@ export interface AskHelper {messages?: HelperMessage[];/** The job's own sampling, kept inside HELPER_SAMPLING; the model family's when unset. */sampling?: HelperSampling;+ /**+ * Tools the model may call (a chat only; only a slot that takes tools gets it): OpenAI function definitions, at most+ * HELPER_LIMITS.toolsChars of JSON in all. The answer's toolCalls are the calls it made.+ */+ tools?: HelperTool[];+ tool_choice?: HelperToolChoice;json?: boolean;/** Pictures for a model that sees them (only a slot that does takes the job). A chat takes one, with its newest turn. */images?: { data: Buffer; contentType: string }[];@@ -433,11 +587,16 @@ export async function askHelper(o: AskHelper): Promise<HelperAnswer> {if (problem) return { error: "failed", message: `The conversation can't be sent: ${problem}.` };if ((o.images?.length ?? 0) > 1) return { error: "failed", message: "A chat turn takes one picture." };}+ const tools = o.tools !== undefined;+ if (tools) {+ const problem = chat ? helperToolsProblem(o.tools, o.tool_choice) : "tools need a chat's turns";+ if (problem) return { error: "failed", message: `The tools can't be offered: ${problem}.` };+ }const d = db();sweepHelper(now());const vision = !!o.images?.length;// A chat waits for a slot that is coming back (its worker restarts on new code); another task needs one asking now.- if (chat ? helperState(now(), { vision, chat }) === "absent" : !helperLive(now(), { vision, chat })) return { error: "busy" };+ if (chat ? helperState(now(), { vision, chat, tools }) === "absent" : !helperLive(now(), { vision, chat })) return { error: "busy" };const pictures = vision ? await helperPictures(o.images!) : null;if (vision && !pictures) return { error: "failed" };if (who !== "owner" && o.counted !== false) {@@ -451,7 +610,9 @@ export async function askHelper(o: AskHelper): Promise<HelperAnswer> {const waiting = d.prepare("SELECT COUNT(*) AS n, SUM(CASE WHEN who = ? THEN 1 ELSE 0 END) AS mine FROM helper_jobs WHERE state IN ('waiting','running')").get(who) as { n: number; mine: number | null };if (waiting.n >= HELPER_LIMITS.waitingAll || (who !== "owner" && (waiting.mine ?? 0) >= HELPER_LIMITS.waitingEach)) return { error: "busy" };// A chat's newest turn is its words for moderation (the turns before it were checked when they were sent).- const user = (chat ? o.messages![o.messages!.length - 1].content : (o.user ?? "")).slice(0, HELPER_LIMITS.userChars);+ // A chat's newest turn of the person's is its words for moderation (the turns before it were checked when they were sent).+ const newest = chat ? o.messages!.findLast((m) => m.role === "user") : null;+ const user = (chat ? newest?.content || "Continue." : (o.user ?? "")).slice(0, HELPER_LIMITS.userChars);const sampling = helperSampling(o.sampling);const stream = chat || !!o.onText;const id = `hlp_${crypto.randomBytes(9).toString("base64url")}`;@@ -472,7 +633,7 @@ export async function askHelper(o: AskHelper): Promise<HelperAnswer> {}const created = now();d.prepare(- "INSERT INTO helper_jobs (id, who, task, system, user, max_tokens, json, state, created_at, images_json, messages_json, sampling_json, stream) VALUES (?, ?, ?, ?, ?, ?, ?, 'waiting', ?, ?, ?, ?, ?)",+ "INSERT INTO helper_jobs (id, who, task, system, user, max_tokens, json, state, created_at, images_json, messages_json, sampling_json, stream, tools_json, tool_choice_json) VALUES (?, ?, ?, ?, ?, ?, ?, 'waiting', ?, ?, ?, ?, ?, ?, ?)",).run(id,who,@@ -483,9 +644,11 @@ export async function askHelper(o: AskHelper): Promise<HelperAnswer> {o.json ? 1 : 0,created,pictures ? JSON.stringify(pictures) : null,- chat ? JSON.stringify(o.messages!.map((m) => ({ role: m.role, content: m.content }))) : null,+ chat ? JSON.stringify(o.messages!.map(turnOf)) : null,sampling ? JSON.stringify(sampling) : null,stream ? 1 : 0,+ tools ? JSON.stringify(o.tools!.map(toolOf)) : null,+ tools && o.tool_choice !== undefined ? JSON.stringify(o.tool_choice) : null,);const waitMs = o.waitMs ?? (chat ? HELPER_TIMES.chatWaitMs : 45_000);// A caller's hook never stops the wait.@@ -504,13 +667,15 @@ export async function askHelper(o: AskHelper): Promise<HelperAnswer> {const row = d.prepare("SELECT * FROM helper_jobs WHERE id = ?").get(id) as JobRow | undefined;const t = now();if (!row || row.state === "failed" || row.state === "canceled") return { error: row?.error === "busy" ? "busy" : "failed" };- if (row.state === "done" && row.text) {- if (checkOutputs) {+ if (row.state === "done" && (row.text || row.tool_calls_json)) {+ if (checkOutputs && row.text) {const bytes = Buffer.from(row.text);const c = await checkOutput({ bytes, contentType: "text/plain; charset=utf-8", generationId: id, account, assetId: id, kind: "text", sha256: crypto.createHash("sha256").update(bytes).digest("hex") });if (c.decision !== "show") return c.decision === "hide" && c.text ? { error: "blocked", message: c.text } : { error: "failed" };}- return { text: row.text };+ const calls = json<HelperCall[] | null>(row.tool_calls_json, null);+ const finish = row.finish && FINISH.has(row.finish) ? (row.finish as "stop" | "tool_calls" | "length") : null;+ return { text: row.text ?? "", ...(calls?.length && { toolCalls: calls }), ...(finish && { finish }) };}if (row.state === "waiting") {if (t - created >= waitMs) {diff --git a/tests/text-helper.test.ts b/tests/text-helper.test.tsindex b055622a..519526de 100644--- a/tests/text-helper.test.ts+++ b/tests/text-helper.test.ts@@ -404,8 +404,8 @@ describe("chat: turns, words as they come, ending early", () => {it("checks the turns: user and assistant only, the newest the person's, at most 24,000 characters; nothing is queued for a bad one", async () => {expect(helper.helperMessagesProblem(turns)).toBeNull();expect(helper.helperMessagesProblem([])).toBe("no turns");- expect(helper.helperMessagesProblem(turns.slice(0, 2))).toBe("the newest turn isn't the person's");- expect(helper.helperMessagesProblem([{ role: "system", content: "x" }, turns[2]])).toMatch(/user or assistant/);+ expect(helper.helperMessagesProblem(turns.slice(0, 2))).toBe("the newest turn isn't the person's or a tool's");+ expect(helper.helperMessagesProblem([{ role: "system", content: "x" }, turns[2]])).toMatch(/user, assistant or tool/);expect(helper.helperMessagesProblem([{ role: "user", content: "x".repeat(helper.HELPER_LIMITS.chatChars + 1) }])).toBe("too long");expect(helper.helperMessagesProblem([{ role: "user", content: "x".repeat(helper.HELPER_LIMITS.chatChars) }])).toBeNull();expect(helper.helperMessagesProblem(Array(helper.HELPER_LIMITS.chatTurns + 1).fill(turns[2]))).toBe("too many turns");@@ -696,3 +696,105 @@ describe("what a chat waits for: a slot ready, busy, coming back or gone", () =>expect(helper.helperState(Date.now(), { chat: true })).toBe("starting");});});++describe("chat with tools", () => {+ const tools: import("@/server/text-helper").HelperTool[] = [+ { type: "function", function: { name: "make_picture", description: "Make a picture from words", parameters: { type: "object", properties: { prompt: { type: "string" } }, required: ["prompt"] } } },+ { type: "function", function: { name: "remove_background", parameters: { type: "object", properties: {} } } },+ ];+ const asked = [{ role: "user" as const, content: "Make a picture of a cat" }];+ const called: import("@/server/text-helper").HelperMessage[] = [+ ...asked,+ { role: "assistant", tool_calls: [{ id: "call_a", type: "function", function: { name: "make_picture", arguments: '{"prompt":"a cat"}' } }] },+ { role: "tool", tool_call_id: "call_a", content: '{"made":"asset_1"}' },+ ];+ const toolWorker = (o: { tools?: boolean } = {}) => {+ const w = addWorker();+ helper.claimHelperJob(workerRow(w), { chat: true, tools: o.tools !== false });+ return w;+ };+ const claim = async (w: W, tools = true, ms = 5000) => {+ const end = Date.now() + ms;+ for (;;) {+ const job = helper.claimHelperJob(workerRow(w), { chat: true, tools });+ if (job || Date.now() > end) return job;+ await new Promise((r) => setTimeout(r, 25));+ }+ };++ it("checks tools, the choice, tool calls and tools' results; the newest turn may be a tool's", () => {+ expect(helper.helperToolsProblem(tools)).toBeNull();+ expect(helper.helperToolsProblem(tools, "none")).toBeNull();+ expect(helper.helperToolsProblem(tools, { type: "function", function: { name: "make_picture" } })).toBeNull();+ expect(helper.helperToolsProblem(tools, { type: "function", function: { name: "nope" } })).toBe("the tool choice names no tool");+ expect(helper.helperToolsProblem([])).toBe("no tools");+ expect(helper.helperToolsProblem([tools[0], tools[0]])).toBe("two tools have the same name");+ expect(helper.helperToolsProblem([{ type: "function", function: { name: "has space", parameters: {} } }])).toBe("a tool has no name");+ expect(helper.helperToolsProblem([{ type: "function", function: { name: "x", parameters: [] } }])).toBe("a tool's parameters aren't a schema");+ const big = { type: "function", function: { name: "big", description: "x".repeat(helper.HELPER_LIMITS.toolsChars), parameters: {} } };+ expect(helper.helperToolsProblem([big])).toBe("the tools are too long");+ expect(helper.helperMessagesProblem(called)).toBeNull();+ expect(helper.helperMessagesProblem([...asked, { role: "tool", tool_call_id: "call_z", content: "x" }])).toBe("a tool's result answers no call before it");+ expect(helper.helperMessagesProblem([{ role: "assistant" }, ...asked])).toBe("an assistant turn has neither words nor tool calls");+ expect(helper.helperMessagesProblem([...asked, { role: "assistant", tool_calls: [{ id: "c", type: "function", function: { name: "x", arguments: "y".repeat(8001) } }] }, ...asked])).toMatch(/name with its arguments/);+ expect(helper.helperMessagesProblem([...asked, { role: "assistant", tool_calls: [] }, ...asked])).toMatch(/short list/);+ });++ it("goes only to a slot that takes tools, with its tools, choice and turns as they are; tools need a chat", async () => {+ expect(await helper.askHelper({ task: "enhance", system: "s", user: "u", tools })).toMatchObject({ error: "failed", message: expect.stringContaining("need a chat") });+ const plain = toolWorker({ tools: false });+ // Only a chat slot without tools is here: nothing is coming that takes tools.+ expect(await helper.askHelper({ task: "chat", system: "s", messages: asked, tools })).toEqual({ error: "busy" });+ const w = toolWorker();+ const answer = helper.askHelper({ task: "chat", system: "s", messages: called, tools, tool_choice: "auto" });+ await new Promise((r) => setTimeout(r, 50));+ expect(helper.claimHelperJob(workerRow(plain), { chat: true })).toBeNull();+ const job = (await claim(w))!;+ expect(job).toMatchObject({ tools, toolChoice: "auto", messages: called, user: "Make a picture of a cat" });+ helper.finishHelperJob(workerRow(w), job.id, { lease: job.lease, text: "Here is your cat.", finish: "stop" });+ expect(await answer).toEqual({ text: "Here is your cat.", finish: "stop" });+ });++ it("an answer of tool calls: only offered tools, no words needed; why it stopped comes with it", async () => {+ const w = toolWorker();+ const answer = helper.askHelper({ task: "chat", system: "s", messages: asked, tools });+ const job = (await claim(w))!;+ expect(+ helper.finishHelperJob(workerRow(w), job.id, {+ lease: job.lease,+ text: "",+ finish: "tool_calls",+ toolCalls: [+ { id: "call_1", name: "make_picture", arguments: '{"prompt":"a cat"}' },+ { id: "call_2", name: "delete_everything", arguments: "{}" },+ { name: "remove_background", arguments: "{}" },+ ],+ }),+ ).toBe(true);+ expect(await answer).toEqual({+ text: "",+ finish: "tool_calls",+ toolCalls: [+ { id: "call_1", name: "make_picture", arguments: '{"prompt":"a cat"}' },+ { id: "call_2", name: "remove_background", arguments: "{}" },+ ],+ });+ // Cut at its token limit; and calls only to tools it wasn't offered: no answer.+ const cut = helper.askHelper({ task: "chat", system: "s", messages: asked, tools });+ const j2 = (await claim(w))!;+ helper.finishHelperJob(workerRow(w), j2.id, { lease: j2.lease, text: "A very long", finish: "length" });+ expect(await cut).toEqual({ text: "A very long", finish: "length" });+ const none = helper.askHelper({ task: "chat", system: "s", messages: asked, tools });+ const j3 = (await claim(w))!;+ helper.finishHelperJob(workerRow(w), j3.id, { lease: j3.lease, text: "", toolCalls: [{ id: "c", name: "delete_everything", arguments: "{}" }] });+ expect(await none).toEqual({ error: "failed" });+ });++ it("an older slot's answer (no finish, no calls) stays just its words", async () => {+ const w = toolWorker();+ const answer = helper.askHelper({ task: "chat", system: "s", messages: asked });+ const job = (await claim(w))!;+ helper.finishHelperJob(workerRow(w), job.id, { lease: job.lease, text: "Hi" });+ expect(await answer).toEqual({ text: "Hi" });+ });+});diff --git a/tests/worker-text-slot.test.ts b/tests/worker-text-slot.test.tsindex 2ffb4fbf..2e8fba90 100644--- a/tests/worker-text-slot.test.ts+++ b/tests/worker-text-slot.test.ts@@ -11,7 +11,7 @@ import path from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";import { othersOf } from "../bin/lib/worker/gpu.mjs";import { parseCounters, splitMemory } from "../bin/lib/worker/local-work.mjs";-import { chatBody, contextOf, cudaMbOf, familyOf, fileMatches, jobOf, modelName, serverArgs, streamedWords, TextSlot, textSlotOf, textTurn } from "../bin/lib/worker/text.mjs";+import { chatBody, contextOf, cudaMbOf, familyOf, fileMatches, jobOf, modelName, serverArgs, callsOf, joinCalls, streamedPart, streamedWords, TextSlot, textSlotOf, textTurn } from "../bin/lib/worker/text.mjs";import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 30_000 });@@ -45,6 +45,21 @@ http.createServer((req, res) => {const b = JSON.parse(body);const last = b.messages.at(-1).content;const parts = Array.isArray(last) ? last : [{ type: "text", text: last }];+ // Tools offered: it calls the chosen one (else the first) with the words and what it was sent, nothing else.+ if (b.tools) {+ const name = b.tool_choice?.function?.name ?? b.tools[0].function.name;+ const args = JSON.stringify({ prompt: parts.find((p) => p.type === "text")?.text ?? "", turns: b.messages.map((m) => m.role + (m.tool_calls ? "+calls" : "") + (m.tool_call_id ? ":" + m.tool_call_id : "")), tools: b.tools.length, choice: b.tool_choice ?? null });+ const ev = (o) => "data: " + JSON.stringify(o) + "\\n\\n";+ if (!b.stream) {+ res.writeHead(200, { "content-type": "application/json" });+ return res.end(JSON.stringify({ choices: [{ message: { content: null, tool_calls: [{ id: "call_x1", type: "function", function: { name, arguments: args } }] }, finish_reason: "tool_calls" }] }));+ }+ res.writeHead(200, { "content-type": "text/event-stream" });+ res.write(ev({ choices: [{ delta: { tool_calls: [{ index: 0, id: "call_x1", type: "function", function: { name, arguments: "" } }] } }] }));+ for (const piece of args.match(/[\\s\\S]{1,7}/g)) res.write(ev({ choices: [{ delta: { tool_calls: [{ index: 0, function: { arguments: piece } }] } }] }));+ res.write(ev({ choices: [{ delta: {}, finish_reason: "tool_calls" }] }));+ return res.end("data: [DONE]\\n\\n");+ }const content = JSON.stringify({ host: req.headers.host, ngl: arg("-ngl"), ctx: arg("-c"), mmproj: process.argv.includes("--mmproj"), cuda: process.env.CUDA_VISIBLE_DEVICES ?? null, token: process.env.FUOBE_WORKER_TOKEN ?? null, kwargs: b.chat_template_kwargs ?? null, temperature: b.temperature, top_p: b.top_p, user: parts.find((p) => p.type === "text").text, pictures: parts.filter((p) => p.type === "image_url").map((p) => p.image_url.url.slice(0, 23)), max: b.max_tokens, stream: b.stream, turns: b.messages.map((m) => m.role + ":" + (Array.isArray(m.content) ? m.content.map((p) => p.type).join("+") : m.content)) });if (!b.stream) {res.writeHead(200, { "content-type": "application/json" });@@ -468,3 +483,79 @@ describe("while its worker restarts or pauses", () => {expect(aways).toEqual(["updating", "paused", "updating"]);});});++describe("tool calling", () => {+ const tools = [+ { type: "function", function: { name: "make_picture", description: "Make a picture", parameters: { type: "object", properties: { prompt: { type: "string" } } } } },+ { type: "function", function: { name: "remove_background", parameters: { type: "object", properties: {} } } },+ ];+ const history = [+ { role: "user", content: "Make a cat" },+ { role: "assistant", tool_calls: [{ id: "call_a", type: "function", function: { name: "make_picture", arguments: '{"prompt":"a cat"}' } }] },+ { role: "tool", tool_call_id: "call_a", content: '{"ok":true}' },+ ];+ const base = { id: "j", lease: "l", system: "", user: "Make a cat", maxTokens: 900 };++ it("reads tools, the choice among them, tool calls and tools' results; anything else is dropped", () => {+ const job = jobOf({ job: { ...base, messages: history, tools, toolChoice: { type: "function", function: { name: "make_picture" } } } })!;+ expect(job.tools).toHaveLength(2);+ expect(job.toolChoice).toEqual({ type: "function", function: { name: "make_picture" } });+ expect(job.messages!.map((m: { role: string }) => m.role)).toEqual(["user", "assistant", "tool"]);+ expect(jobOf({ job: { ...base, messages: history, tools, toolChoice: { type: "function", function: { name: "nope" } } } })).toBeNull();+ expect(jobOf({ job: { ...base, tools } })).toBeNull();+ expect(jobOf({ job: { ...base, messages: history, tools: [{ type: "function", function: { name: "bad name!", parameters: {} } }] } })).toBeNull();+ expect(jobOf({ job: { ...base, messages: [...history, { role: "system", content: "x" }] } })).toBeNull();+ expect(jobOf({ job: { ...base, messages: [{ role: "assistant", tool_calls: [{ id: "c", type: "function", function: { name: "x", arguments: {} } }] }, history[2]] } })).toBeNull();+ // An older studio's job: no tools.+ expect(jobOf({ job: { ...base, messages: [history[0]] } })).toMatchObject({ tools: null, toolChoice: null });+ const body = chatBody(job, { model: "gemma-4-E2B-it-Q6_K.gguf" });+ expect(body).toMatchObject({ tools, tool_choice: { type: "function", function: { name: "make_picture" } } });+ expect(body.messages[1]).toMatchObject({ role: "assistant", tool_calls: history[1].tool_calls });+ expect(body.messages[2]).toEqual({ role: "tool", tool_call_id: "call_a", content: '{"ok":true}' });+ // A picture goes with the person's newest turn, even when a tool's result comes after it.+ const pic = chatBody({ ...job, images: [JPEG_B64] }, {});+ expect(Array.isArray(pic.messages[0].content)).toBe(true);+ expect(pic.messages[2].content).toBe('{"ok":true}');+ });++ it("puts streamed tool calls together from their pieces", () => {+ const lines = [+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"make_pic","arguments":""}}]}}]}',+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"name":"ture","arguments":"{\\"pro"}}]}}]}',+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"mpt\\":1}"}}]}}]}',+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":1,"id":"call_2","function":{"name":"remove_background","arguments":"{}"}}]}}]}',+ 'data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}]}',+ ].map(streamedPart);+ expect(lines.at(-1)!.finish).toBe("tool_calls");+ expect(callsOf(joinCalls(lines.flatMap((l) => l.calls)))).toEqual([+ { id: "call_1", name: "make_picture", arguments: '{"prompt":1}' },+ { id: "call_2", name: "remove_background", arguments: "{}" },+ ]);+ expect(callsOf([{ function: { name: "x", arguments: { a: 1 } } }])).toEqual([{ id: "call_1", name: "x", arguments: '{"a":1}' }]);+ });++ it("says it takes tools, and sends the calls it streamed with why it stopped (no words go as partials)", async () => {+ const site = studio([{ id: "hlp_t", lease: "Lt", user: "Make a cat", maxTokens: 900, messages: history, stream: true, tools } as never]);+ const { s } = makeSlot(site.call);+ await until(s, Date.now, { may: true, room: "cpu" }, () => site.answers.length === 1);+ expect(site.claims[0]).toMatchObject({ chat: true, tools: true });+ const a = site.answers[0].body as { text: string; toolCalls: { id: string; name: string; arguments: string }[]; finish: string };+ expect(a).toMatchObject({ lease: "Lt", text: "", finish: "tool_calls" });+ expect(a.toolCalls).toHaveLength(1);+ expect(a.toolCalls[0]).toMatchObject({ id: "call_x1", name: "make_picture" });+ expect(JSON.parse(a.toolCalls[0].arguments)).toMatchObject({ prompt: '{"ok":true}', turns: ["system", "user", "assistant+calls", "tool:call_a"], tools: 2 });+ expect(site.partials.every((p) => p.text === "")).toBe(true);+ });++ it("not streamed: the calls come back the same way, and a chat's answer says why it stopped", async () => {+ const site = studio([+ { id: "hlp_u", lease: "Lu", user: "Cut her out", maxTokens: 900, messages: [{ role: "user", content: "Cut her out" }], tools, toolChoice: { type: "function", function: { name: "remove_background" } } } as never,+ { id: "hlp_w", lease: "Lw", user: "Hi", maxTokens: 900, messages: [{ role: "user", content: "Hi" }] } as never,+ ]);+ const { s } = makeSlot(site.call);+ await until(s, Date.now, { may: true, room: "cpu" }, () => site.answers.length === 2);+ expect(site.answers[0].body).toMatchObject({ text: "", finish: "tool_calls", toolCalls: [{ id: "call_x1", name: "remove_background" }] });+ expect(site.answers[1].body).toMatchObject({ finish: "stop" });+ expect(site.answers[1].body).not.toHaveProperty("toolCalls");+ });+});