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
Assist on a local LLM: Ollama tool calling
Claude69a8cf5c1441
diff --git a/src/app/api/assist/route.ts b/src/app/api/assist/route.tsindex 5520ae54..8b5bf8b1 100644--- a/src/app/api/assist/route.ts+++ b/src/app/api/assist/route.ts@@ -1,13 +1,13 @@import { after, connection } from "next/server";import { z } from "zod";-import { addMessage, agentKind, createThread, listThreads, run } from "@/server/assist/agent";+import { addMessage, createThread, listThreads, resolveAgent, run } from "@/server/assist/agent";import { AssistMessage } from "@/server/assist/schemas";const Create = AssistMessage.extend({ engine: z.enum(["cloud", "open"]), autoApprove: z.boolean().optional() });export async function GET() {await connection();- return Response.json({ threads: listThreads(), agent: agentKind() });+ return Response.json({ threads: listThreads(), agent: await resolveAgent() });}/** Start a chat with its first message; the agent replies in the background (poll the thread). */@@ -15,7 +15,7 @@ export async function POST(request: Request) {const parsed = Create.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Write a message" }, { status: 400 });const { text, attachments, engine, autoApprove } = parsed.data;- const thread = createThread({ engine, autoApprove });+ const thread = createThread({ engine, autoApprove, agent: await resolveAgent() });const updated = addMessage(thread.id, text, attachments);// Claimed now (not in after()) so a poll that lands first doesn't see a stale "running" thread.const reply = run(thread.id);diff --git a/src/components/assist-view.tsx b/src/components/assist-view.tsxindex f1667a2c..58dedb90 100644--- a/src/components/assist-view.tsx+++ b/src/components/assist-view.tsx@@ -29,6 +29,13 @@ const SUGGESTIONS = [const KIND_ICON: Record<MediaKind | "storyboard", typeof ImageIcon> = { image: ImageIcon, video: Video, audio: AudioLines, storyboard: Clapperboard };+const AGENT_LABEL: Record<AssistThread["agent"], string> = { claude: "Claude", ollama: "Local LLM", offline: "Offline planner" };+const AGENT_HINT: Record<AssistThread["agent"], string> = {+ claude: "Claude plans the shoot, picks models and runs them with your approval.",+ ollama: "Runs on your Ollama model (Settings → Prompt enhancement). Smaller local models follow instructions less reliably than Claude.",+ offline: "A simple rule-based planner. Add an Anthropic API key, or run Ollama, for the full assistant that picks models, chains steps and checks results.",+};+interface Attachment {id: string;preview: string;@@ -442,17 +449,16 @@ export function AssistView() {}, [count, status]);const agent = thread?.agent ?? threads.data?.agent;- const offline = agent === "offline";const agentBadge = agent && (<Tooltip><TooltipTrigger asChild><Link href="/settings" className="inline-flex h-7 items-center gap-1.5 rounded-full bg-muted px-2.5 text-[12px] font-medium whitespace-nowrap text-muted-foreground hover:text-foreground">- {offline ? <Cpu className="size-3" /> : <Bot className="size-3" />}- <span className={cn(id && "hidden sm:inline")}>{offline ? "Offline planner" : "Claude"}</span>+ {agent === "claude" ? <Bot className="size-3" /> : <Cpu className="size-3" />}+ <span className={cn(id && "hidden sm:inline")}>{AGENT_LABEL[agent]}</span></Link></TooltipTrigger><TooltipContent className="max-w-64">- {offline ? "A simple rule-based planner. Add an Anthropic API key in Settings for the full assistant that picks models, chains steps and checks results." : "Claude plans the shoot, picks models and runs them with your approval."}+ {AGENT_HINT[agent]}</TooltipContent></Tooltip>);diff --git a/src/lib/assist.ts b/src/lib/assist.tsindex 21983444..75eb6ea3 100644--- a/src/lib/assist.ts+++ b/src/lib/assist.ts@@ -35,8 +35,8 @@ export interface AssistThread {id: string;title: string;status: AssistStatus;- /** "claude" = the full agent; "offline" = a rule-based planner (no LLM configured). */- agent: "claude" | "offline";+ /** "claude" = Claude; "ollama" = a local model through Ollama; "offline" = a rule-based planner (no LLM). */+ agent: "claude" | "ollama" | "offline";engine: Engine;/** Run plans without the approval card. */autoApprove: boolean;diff --git a/src/server/assist/agent.ts b/src/server/assist/agent.tsindex f92cb525..af8856b7 100644--- a/src/server/assist/agent.ts+++ b/src/server/assist/agent.ts@@ -157,17 +157,35 @@ export function updateThread(id: string, patch: { autoApprove?: boolean; title?:return s.thread;}-/** Claude when a key is set (and the install allows it), else the offline planner. */-export function agentKind(): AssistThread["agent"] {+let ollamaProbe: { at: number; url: string; ok: boolean } | null = null;+async function ollamaReachable(): Promise<boolean> {+ const url = getSetting("ollamaUrl").replace(/\/+$/, "");+ if (ollamaProbe && ollamaProbe.url === url && Date.now() - ollamaProbe.at < 30_000) return ollamaProbe.ok;+ const ok = await fetch(`${url}/api/tags`, { signal: AbortSignal.timeout(800) })+ .then((r) => r.ok)+ .catch(() => false);+ ollamaProbe = { at: Date.now(), url, ok };+ return ok;+}++/**+ * Which LLM drives new chats: Claude when a key is set (on open-source-only installs only when+ * picked explicitly), else a reachable local Ollama, else the offline planner.+ */+export async function resolveAgent(): Promise<AssistThread["agent"]> {const choice = getSetting("enhanceProvider");- if (!getSetting("anthropicKey") || choice === "none" || choice === "ollama") return "offline";- return choice === "anthropic" || engineMode() !== "open" ? "claude" : "offline";+ const key = !!getSetting("anthropicKey");+ if (choice === "none") return "offline";+ if (choice === "anthropic") return key ? "claude" : "offline";+ if (choice === "ollama") return "ollama";+ if (key && engineMode() !== "open") return "claude";+ return (await ollamaReachable()) ? "ollama" : "offline";}-export function createThread(opts: { engine: Engine; autoApprove?: boolean; title?: string }): AssistThread {+export function createThread(opts: { engine: Engine; agent: AssistThread["agent"]; autoApprove?: boolean; title?: string }): AssistThread {const now = Date.now();const s: State = {- thread: { id: nanoid(12), title: opts.title ?? "New chat", status: "idle", agent: agentKind(), engine: opts.engine, autoApprove: !!opts.autoApprove, items: [], createdAt: now, updatedAt: now },+ thread: { id: nanoid(12), title: opts.title ?? "New chat", status: "idle", agent: opts.agent, engine: opts.engine, autoApprove: !!opts.autoApprove, items: [], createdAt: now, updatedAt: now },messages: [],pending: null,};@@ -290,6 +308,74 @@ export const claude: ModelCall = async ({ system, messages, tools }) => {});};+type OllamaMessage = { role: "system" | "user" | "assistant" | "tool"; content: string; tool_calls?: { function: { name: string; arguments: unknown } }[]; tool_name?: string };++const blockText = (c: ToolResult["content"]): string =>+ typeof c === "string" ? c : (c ?? []).map((b) => (b.type === "text" ? b.text : b.type === "image" ? "[image omitted]" : "")).join("\n");++/** The stored (Anthropic-shaped) history as Ollama chat messages. Images stay as their URLs in the text. */+export function toOllamaMessages(system: ModelRequest["system"], messages: MessageParam[]): OllamaMessage[] {+ const names = new Map<string, string>();+ const out: OllamaMessage[] = [{ role: "system", content: `${system.stable}\n\n${system.turn}` }];+ for (const m of messages) {+ if (typeof m.content === "string") {+ out.push({ role: m.role, content: m.content });+ continue;+ }+ if (m.role === "assistant") {+ const text = m.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("\n");+ const calls = m.content.flatMap((b) => {+ if (b.type !== "tool_use") return [];+ names.set(b.id, b.name);+ return [{ function: { name: b.name, arguments: b.input } }];+ });+ out.push({ role: "assistant", content: text, ...(calls.length && { tool_calls: calls }) });+ continue;+ }+ for (const b of m.content) if (b.type === "tool_result") out.push({ role: "tool", tool_name: names.get(b.tool_use_id), content: `${b.is_error ? "Error: " : ""}${blockText(b.content)}` });+ const text = m.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("\n");+ if (text) out.push({ role: "user", content: text });+ }+ return out;+}++/** A local model through Ollama's tool calling (qwen3, llama3.x, mistral…), answering in the same shape as Claude. */+export const ollama: ModelCall = async ({ system, messages, tools }) => {+ const res = await fetch(`${getSetting("ollamaUrl").replace(/\/+$/, "")}/api/chat`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ model: getSetting("ollamaModel"),+ stream: false,+ messages: toOllamaMessages(system, messages),+ tools: tools.map((t) => ({ type: "function", function: { name: t.name, description: t.description, parameters: t.input_schema } })),+ options: { num_ctx: 16384 },+ }),+ signal: AbortSignal.timeout(300_000),+ }).catch((e: Error) => {+ throw new Error(`Couldn't reach Ollama at ${getSetting("ollamaUrl")} (${e.message}). Is it running?`);+ });+ if (!res.ok) throw new Error(`Ollama returned ${res.status}: ${(await res.text()).slice(0, 300)}`);+ const j = (await res.json()) as { message?: { content?: string; tool_calls?: { function: { name: string; arguments: unknown } }[] }; done_reason?: string };+ const content: Anthropic.Beta.BetaContentBlock[] = [];+ const text = (j.message?.content ?? "").replace(/<think>[\s\S]*?<\/think>/g, "").trim();+ if (text) content.push({ type: "text", text, citations: null } as Anthropic.Beta.BetaTextBlock);+ for (const c of j.message?.tool_calls ?? []) {+ let input = c.function.arguments;+ if (typeof input === "string") {+ try {+ input = JSON.parse(input);+ } catch {+ input = { INVALID_JSON: input };+ }+ }+ content.push({ type: "tool_use", id: `toolu_ollama_${nanoid(10)}`, name: c.function.name, input } as unknown as Anthropic.Beta.BetaToolUseBlock);+ }+ const stop: Anthropic.Beta.BetaStopReason = j.message?.tool_calls?.length ? "tool_use" : j.done_reason === "length" ? "max_tokens" : "end_turn";+ if (!content.length) content.push({ type: "text", text: "…", citations: null } as Anthropic.Beta.BetaTextBlock);+ return { id: `msg_ollama_${nanoid(8)}`, type: "message", role: "assistant", model: getSetting("ollamaModel"), content, stop_reason: stop, stop_sequence: null, stop_details: null, usage: null } as unknown as Anthropic.Beta.BetaMessage;+};+/** A rule-based planner with the same shape as a model reply, for installs without an LLM. */export const offline: ModelCall = async ({ messages, ctx }) => {const last = messages.at(-1);@@ -430,7 +516,7 @@ async function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {return "continue";}-const MODELS: Record<AssistThread["agent"], ModelCall> = { claude, offline };+const MODELS: Record<AssistThread["agent"], ModelCall> = { claude, ollama, offline };/*** Run the agent until it ends its turn or waits for approval. Call it right after addMessage or@@ -468,6 +554,7 @@ function errorText(e: unknown): string {if (e instanceof Anthropic.AuthenticationError) return "Your Anthropic API key was rejected. Check it in Settings → API keys.";if (e instanceof Anthropic.RateLimitError) return "Claude is rate-limited right now. Try again in a minute.";if (e instanceof Anthropic.APIError) return `Claude returned an error (${e.status ?? "network"}): ${e.message}`;+ if (e instanceof DOMException && e.name === "TimeoutError") return "The model took too long to answer. Try again, or pick a smaller model.";return (e as Error).message || "Something went wrong";}diff --git a/tests/assist.test.ts b/tests/assist.test.tsindex aadbe6fa..48800a94 100644--- a/tests/assist.test.ts+++ b/tests/assist.test.ts@@ -61,7 +61,7 @@ describe("assist tools", () => {describe("assist loop", () => {it("pauses on a paid plan, then answers every call of that turn in one message", async () => {- const t = agent.createThread({ engine: "cloud" });+ const t = agent.createThread({ agent: "offline", engine: "cloud" });agent.addMessage(t.id, "Make a fox photo");const m = scripted(reply([text("Let me check models."), use("toolu_a", "search_models", { kind: "image" }), use("toolu_b", "generate", { summary: "A fox photo", jobs: [job] })], "tool_use"),@@ -90,7 +90,7 @@ describe("assist loop", () => {});it("treats a new message as declining the plan, with the results before the text", async () => {- const t = agent.createThread({ engine: "cloud" });+ const t = agent.createThread({ agent: "offline", engine: "cloud" });agent.addMessage(t.id, "Fox video");await agent.run(t.id, scripted(reply([use("toolu_c", "generate", { summary: "Fox", jobs: [job] })], "tool_use")).call);agent.addMessage(t.id, "Actually make it a wolf");@@ -103,7 +103,7 @@ describe("assist loop", () => {});it("runs gated tools straight away when auto-run is on", async () => {- const t = agent.createThread({ engine: "cloud", autoApprove: true });+ const t = agent.createThread({ agent: "offline", engine: "cloud", autoApprove: true });agent.addMessage(t.id, "Two foxes");await agent.run(t.id, scripted(reply([use("toolu_d", "generate", { summary: "Foxes", jobs: [{ ...job, outputs: 2 }] })], "tool_use"), reply([text("Done.")], "end_turn")).call);const v = agent.getThread(t.id)!;@@ -113,7 +113,7 @@ describe("assist loop", () => {});it("doesn't run a tool call cut off by max_tokens", async () => {- const t = agent.createThread({ engine: "cloud", autoApprove: true });+ const t = agent.createThread({ agent: "offline", engine: "cloud", autoApprove: true });agent.addMessage(t.id, "Fox");const m = scripted(reply([use("toolu_e", "generate", { summary: "Fo" })], "max_tokens"), reply([text("Retried.")], "end_turn"));await agent.run(t.id, m.call);@@ -123,7 +123,7 @@ describe("assist loop", () => {});it("returns invalid tool input to the model as an error", async () => {- const t = agent.createThread({ engine: "cloud", autoApprove: true });+ const t = agent.createThread({ agent: "offline", engine: "cloud", autoApprove: true });agent.addMessage(t.id, "Fox");const m = scripted(reply([use("toolu_f", "search_models", { kind: "smell" })], "tool_use"), reply([text("Oops.")], "end_turn"));await agent.run(t.id, m.call);@@ -131,7 +131,7 @@ describe("assist loop", () => {});it("keeps the history valid after a refusal", async () => {- const t = agent.createThread({ engine: "cloud" });+ const t = agent.createThread({ agent: "offline", engine: "cloud" });agent.addMessage(t.id, "something");await agent.run(t.id, scripted(reply([], "refusal", { stop_details: { type: "refusal", category: null, explanation: "Not this one." } as Msg["stop_details"] })).call);const v = agent.getThread(t.id)!;@@ -144,7 +144,7 @@ describe("assist loop", () => {});it("refuses a message while a reply is still running", async () => {- const t = agent.createThread({ engine: "cloud" });+ const t = agent.createThread({ agent: "offline", engine: "cloud" });agent.addMessage(t.id, "one");let release!: () => void;const slow: import("@/server/assist/agent").ModelCall = () => new Promise((r) => (release = () => r(reply([text("ok")], "end_turn"))));@@ -171,7 +171,7 @@ describe("offline planner", () => {});it("plans, waits for approval and starts demo generations end to end", async () => {- const t = agent.createThread({ engine: "cloud" });+ const t = agent.createThread({ agent: "offline", engine: "cloud" });agent.addMessage(t.id, "A cozy cabin in the snow, square");await agent.run(t.id, agent.offline);expect(agent.getThread(t.id)!.thread.status).toBe("waiting");@@ -191,7 +191,7 @@ describe("claude request", () => {const png = Buffer.from("89504e470d0a1a0a0000000d4948445200000001000000010806000000", "hex");const asset = saveFile({ data: png, contentType: "image/png", source: "upload" });setSetting("anthropicKey", "sk-ant-test");- const t = agent.createThread({ engine: "open" });+ const t = agent.createThread({ engine: "open", agent: await agent.resolveAgent() });expect(t.agent).toBe("claude");agent.addMessage(t.id, "Animate this", [asset.url]);const sent: { url: string; headers: Headers; body: Record<string, unknown> }[] = [];@@ -235,3 +235,49 @@ describe("claude request", () => {expect(agent.getThread(t.id)!.thread.items.at(-1)).toMatchObject({ role: "assistant", text: "Ready when you are." });});});++describe("ollama agent", () => {+ it("talks to Ollama's chat API with tools and maps its tool calls back", async () => {+ const http = await import("node:http");+ const seen: { messages: { role: string; content: string; tool_calls?: unknown[]; tool_name?: string }[]; tools: { function: { name: string } }[]; model: string }[] = [];+ const replies = [+ { message: { role: "assistant", content: "<think>hmm</think>Let me look.", tool_calls: [{ function: { name: "search_models", arguments: { kind: "image" } } }] }, done_reason: "stop" },+ { message: { role: "assistant", content: "Nano Banana Pro is a great pick." }, done_reason: "stop" },+ ];+ const server = http.createServer((req, res) => {+ if (req.url === "/api/tags") return res.end(JSON.stringify({ models: [] }));+ let body = "";+ req.on("data", (c) => (body += c));+ req.on("end", () => {+ seen.push(JSON.parse(body));+ res.setHeader("content-type", "application/json");+ res.end(JSON.stringify(replies.shift()));+ });+ });+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));+ const port = (server.address() as { port: number }).port;+ setSetting("ollamaUrl", `http://127.0.0.1:${port}`);+ setSetting("ollamaModel", "qwen3:8b");+ try {+ expect(await agent.resolveAgent()).toBe("ollama");+ const t = agent.createThread({ engine: "open", agent: "ollama" });+ agent.addMessage(t.id, "Which image model should I use?");+ await agent.run(t.id);+ expect(seen).toHaveLength(2);+ expect(seen[0].model).toBe("qwen3:8b");+ expect(seen[0].messages[0].role).toBe("system");+ expect(seen[0].tools.map((x) => x.function.name)).toContain("generate");+ const second = seen[1].messages;+ expect(second.map((m) => m.role)).toEqual(["system", "user", "assistant", "tool"]);+ expect(second[2].tool_calls).toHaveLength(1);+ expect(second[3].tool_name).toBe("search_models");+ expect(JSON.parse(second[3].content).models.length).toBeGreaterThan(0);+ const items = agent.getThread(t.id)!.thread.items;+ expect(items.find((i) => i.role === "assistant")).toMatchObject({ text: "Let me look." });+ expect(items.at(-1)).toMatchObject({ role: "assistant", text: "Nano Banana Pro is a great pick." });+ } finally {+ server.close();+ setSetting("ollamaUrl", "");+ }+ });+});