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
Chat: the free model can ask to make something, and its ask becomes a plan
Adarsh2257b807c6ca
diff --git a/src/app/api/chat/threads/[id]/reply/route.ts b/src/app/api/chat/threads/[id]/reply/route.tsindex 48c494de..7c8ce5bc 100644--- a/src/app/api/chat/threads/[id]/reply/route.ts+++ b/src/app/api/chat/threads/[id]/reply/route.ts@@ -114,6 +114,7 @@ export async function POST(request: Request, ctx: RouteContext<"/api/chat/threadreturn;}const answer = await answerThread(v.who, id, {+ from: request,signal: abort.signal,onText: (t) => {text = t;diff --git a/src/server/chat/answer.ts b/src/server/chat/answer.tsindex aa41d58f..2960738b 100644--- a/src/server/chat/answer.ts+++ b/src/server/chat/answer.ts@@ -1,8 +1,9 @@import "server-only";import { systemPrompt, type ChatTurn } from "@/lib/chat/prompt";import type { ChatErrorCode, ChatMessage } from "@/lib/chat/types";-import { chatReply, summarize } from "./backend";+import { chatReply, summarize, type MakeCall } from "./backend";import { readPicture } from "./files";+import { planMake } from "./make";import { addMessage, chatKey, getPrefs, getThread, setSummary, threadMemory, threadTurns } from "./store";/**@@ -30,8 +31,17 @@ export interface AnswerOptions {onText?: (soFar: string) => void;onQueue?: (position: number) => void;onStatus?: (status: "starting") => void;+ /**+ * The person's own request, when they are here: the model may then ask to make something, and the plan is priced+ * and later run as them (src/server/chat/make.ts). A retry that answers later has none: it answers in words.+ */+ from?: Request;}+/** The make tool's ask as words the planner reads for that kind. */+const askFor = (m: MakeCall): string =>+ m.kind === "video" ? `A video: ${m.what}` : m.kind === "music" ? `A music track: ${m.what}` : m.kind === "voice" ? `A voice-over: "${m.what}"` : m.what;+export async function answerThread(who: string, id: string, o: AnswerOptions = {}): Promise<AnswerResult> {const thread = getThread(who, id);if (!thread) return { error: "failed", message: "That chat is gone." };@@ -52,7 +62,20 @@ export async function answerThread(who: string, id: string, o: AnswerOptions = {const answer = await chatReply(prefs.engine,- { who, system, turns: visible, speaker, image: picture, temperature: TEMPERATURE[thread.kind], signal: o.signal, waitMs: o.waitMs, onText: o.onText, onQueue: o.onQueue, onStatus: o.onStatus },+ {+ who,+ system,+ turns: visible,+ speaker,+ image: picture,+ temperature: TEMPERATURE[thread.kind],+ signal: o.signal,+ waitMs: o.waitMs,+ onText: o.onText,+ onQueue: o.onQueue,+ onStatus: o.onStatus,+ makeTool: !!o.from && thread.kind !== "character",+ },key,);if ("pending" in answer) return { pending: true };@@ -60,6 +83,18 @@ export async function answerThread(who: string, id: string, o: AnswerOptions = {// Answered meanwhile (a retry and the person's own visit): keep the first answer only.const now = threadTurns(who, id).at(-1);if (!now || now.role !== "user") return { nothing: true };+ // The model asked to make something: a plan to approve, priced as the person (else its words, or a short ask).+ if (answer.make && o.from) {+ const made = await planMake(o.from, who, askFor(answer.make), last.image).catch(() => null);+ if (made) {+ const plan = addMessage(who, id, "assistant", made.say, null, made.plan);+ return { message: plan, title: getThread(who, id)?.title ?? thread.title };+ }+ if (!answer.text) {+ const ask = addMessage(who, id, "assistant", "I can make that. Tell me a little more about what you'd like to see, and I'll put the plan together.");+ return { message: ask, title: getThread(who, id)?.title ?? thread.title };+ }+ }const saved = addMessage(who, id, "assistant", answer.text);// Keep a long chat coherent: once enough turns have fallen out of view, fold them into the summary (after the replydiff --git a/src/server/chat/backend.ts b/src/server/chat/backend.tsindex efb9fe20..3bf8bb57 100644--- a/src/server/chat/backend.ts+++ b/src/server/chat/backend.ts@@ -3,7 +3,7 @@ import { alternate, fitHistory, summaryAsk, tidyReply, transcript, type ChatTurnimport type { ChatEngine, ChatErrorCode } from "@/lib/chat/types";import { readSse } from "../llm/sse";import { runAsTenant } from "../tenant";-import { askHelper, freeHelperOn, freeHelperState, helperKnown, HELPER_LIMITS, helperMessagesProblem, type HelperAnswer } from "../text-helper";+import { askHelper, freeHelperOn, freeHelperState, helperKnown, HELPER_LIMITS, helperMessagesProblem, type HelperAnswer, type HelperCall, type HelperTool } from "../text-helper";/*** Where Fuobe Chat's replies come from:@@ -32,10 +32,55 @@ export interface ReplyAsk {onStatus?: (status: "starting") => void;/** How long to wait for the free model before keeping the message for later (SITE_WAIT_MS). */waitMs?: number;+ /** Offer the model the make tool (a chat that can make things: not a character's story). */+ makeTool?: boolean;+}++/** What the model asked to make, in its own clean words. */+export interface MakeCall {+ what: string;+ kind: "image" | "video" | "music" | "voice";+}++/**+ * The one tool Chat offers the free model: one plain tool it picks reliably (pictures sent with a message are read+ * before the model, by src/lib/chat/make-intent.ts, where near-neighbour tools would confuse it).+ */+const MAKE_TOOL: HelperTool = {+ type: "function",+ function: {+ name: "make",+ description:+ "Make something for the person when they ask for it to be made: a picture, a video clip, a music track or a voice-over. The app shows them a plan with the price to approve. Only when they ask to make it now, never for questions or advice about making things.",+ parameters: {+ type: "object",+ properties: {+ what: { type: "string", description: "A rich, specific description of what to make, in the person's language: subject, setting, look, mood; for a voice-over, the exact words to say." },+ kind: { type: "string", enum: ["image", "video", "music", "voice"], description: "What it is: image (a picture), video (a clip), music (a track or song) or voice (a voice-over)." },+ },+ required: ["what", "kind"],+ },+ },+};++const MAKE_HINT = "When the person asks you to make a picture, a video, a music track or a voice-over now, call the make tool with what to make; don't describe it in words instead.";++function makeOf(calls: HelperCall[] | undefined): MakeCall | null {+ const c = calls?.find((x) => x.name === "make");+ if (!c) return null;+ try {+ const a = JSON.parse(c.arguments) as { what?: unknown; kind?: unknown };+ const what = typeof a.what === "string" ? a.what.trim().slice(0, 2000) : "";+ const kind = a.kind === "video" || a.kind === "music" || a.kind === "voice" ? a.kind : "image";+ return what.length >= 3 ? { what, kind } : null;+ } catch {+ return null;+ }}export type ReplyAnswer =- | { text: string; dropped: number }+ /** `make`: the model asked to make something (its words, if any, are in `text`). */+ | { text: string; dropped: number; make?: MakeCall }/** The free model didn't come up in time: the message is kept and answered later. */| { pending: true }| { error: ChatErrorCode; message: string; retryAfterS?: number };@@ -95,10 +140,13 @@ async function siteTry(ask: ReplyAsk, waitMs: number): Promise<ReplyAnswer | "buconst fit = fitHistory(ask.turns, CHAT_BUDGET);const messages = alternate(fit.turns);if (helperMessagesProblem(messages)) return { error: "failed", message: CHAT_WORDS.failed };+ // The make tool, on a slot that takes tool jobs (an older one answers in words, as before).+ const tools = ask.makeTool && freeHelperState(Date.now(), { chat: true, tools: true, vision }) !== "absent";const a = await askHelper({task: "chat",- system: ask.system,+ system: tools ? `${ask.system}\n\n${MAKE_HINT}` : ask.system,messages,+ ...(tools && { tools: [MAKE_TOOL], tool_choice: "auto" as const }),sampling: ask.temperature === undefined ? undefined : { temperature: ask.temperature },...(ask.image && { images: [ask.image] }),signal: ask.signal,@@ -114,6 +162,8 @@ async function siteTry(ask: ReplyAsk, waitMs: number): Promise<ReplyAnswer | "bu});if ("error" in a) return a.error === "busy" ? "busy" : fromHelper(a);const text = tidyReply(a.text, ask.speaker);+ const make = tools ? makeOf(a.toolCalls) : null;+ if (make) return { text, dropped: fit.dropped, make };return text ? { text, dropped: fit.dropped } : { error: "failed", message: CHAT_WORDS.failed };}if (!freeHelperOn(Date.now(), { vision })) return "busy";diff --git a/tests/chat.test.ts b/tests/chat.test.tsindex 52e48ec7..3f6f6ec1 100644--- a/tests/chat.test.ts+++ b/tests/chat.test.ts@@ -414,6 +414,49 @@ describe("making things in a chat", () => {for (const g of ran.ids) expect(db().prepare("SELECT json_extract(request_json, '$.account') AS a FROM generations WHERE id = ?").get(g)).toEqual({ a });});+ it("lets the free model ask to make something with its one tool, and turns that into a plan", async () => {+ let on = true;+ const seen: { tools?: { function: { name: string } }[]; system: string }[] = [];+ const slot = (async () => {+ while (on) {+ beat();+ const job = helper.claimHelperJob(workerRow(worker), { model: "test", device: "gpu", chat: true, tools: true });+ if (!job) {+ await new Promise((r) => setTimeout(r, 20));+ continue;+ }+ seen.push(job as never);+ const offered = (job as { tools?: unknown[] }).tools?.length;+ helper.finishHelperJob(+ workerRow(worker),+ job.id,+ offered+ ? { lease: job.lease, text: "", toolCalls: [{ id: "call_1", name: "make", arguments: JSON.stringify({ what: "A red fox in fresh snow at dusk, soft rim light", kind: "image" }) }], finish: "tool_calls" }+ : { lease: job.lease, text: "*smiles* A song? Let me hum you something." },+ );+ }+ })();+ try {+ // Words the careful check leaves to the model.+ const t = (await (await threadsRoute.POST(req(cookies.a, "/api/chat/threads", "POST", { kind: "chat" }))).json()) as { id: string };+ expect(wantsToMake("I'd love a picture of a red fox in the snow")).toBe(false);+ const ev = await events(await replyRoute.POST(req(cookies.a, `/api/chat/threads/${t.id}/reply`, "POST", { text: "I'd love a picture of a red fox in the snow" }), ctx({ id: t.id })));+ const done = ev.find((e) => e.type === "done")?.message as { plan?: { jobs: { kind: string }[]; requests: { prompt?: string }[] } } | undefined;+ expect(done?.plan?.jobs[0].kind).toBe("image");+ expect(done?.plan?.requests[0].prompt).toContain("red fox in fresh snow");+ const job = seen.at(-1)!;+ expect(job.tools?.map((x) => x.function.name)).toEqual(["make"]);+ expect(job.system).toContain("call the make tool");+ // A character's story is never offered the tool.+ const c = (await (await threadsRoute.POST(req(cookies.a, "/api/chat/threads", "POST", { kind: "character", characterId: "kai" }))).json()) as { id: string };+ await events(await replyRoute.POST(req(cookies.a, `/api/chat/threads/${c.id}/reply`, "POST", { text: "Could you sing me something?" }), ctx({ id: c.id })));+ expect(seen.at(-1)!.tools).toBeUndefined();+ } finally {+ on = false;+ await slot;+ }+ });+it("keeps talk as talk, and characters stay in their story", async () => {const slot = standIn(() => "Pick a dark wool coat.");try {