xlerobot-sim / src /agent /agent.js
VectorW's picture
Update the web simulation
8ff66cf verified
Raw History Blame Contribute Delete
5.25 kB
// The agent loop: the user's instruction, the model's tool calls run in the simulation, their results
// back to the model, until it answers without calling a tool (or the step limit). The model is one on an
// OpenAI-compatible endpoint (llm.js: Hugging Face's router, a local server), Gemini (gemini.js) or Claude
// (claude.js); each keeps the conversation in its own API's form.
import { complete } from "./llm.js";
import { geminiTurn } from "./gemini.js";
import { ROBOT_INTRO, TOOL_GUIDE } from "./specs.js";
/** Claude's models for the agent (claude.js talks to them, loaded when one is chosen). */
export const CLAUDE_MODELS = [
{ id: "claude-opus-5-5", label: "Claude Opus 5.5" },
{ id: "claude-sonnet-5-5", label: "Claude Sonnet 5.5" },
{ id: "claude-haiku-5-5", label: "Claude Haiku 5.5" },
{ id: "claude-fable-5-2", label: "Claude Fable 5.2" },
];
export const CLAUDE_DEFAULT = "claude-opus-5-5";
export const SYSTEM_PROMPT = `${ROBOT_INTRO}
${TOOL_GUIDE}
Keep replies short. Answer in the language the user writes in.`;
export class Agent {
constructor(tools, settings) {
this.tools = tools;
this.settings = settings; // () => {provider, baseUrl, apiKey, model, vision, effort}
this.messages = [{ role: "system", content: SYSTEM_PROMPT }];
this.history = []; // Claude's or Gemini's conversation
this.talkingTo = null; // provider and model of the conversation so far
this.controller = null;
this.maxSteps = 40; // a household task takes a few calls per object
}
get busy() {
return this.controller !== null;
}
clear() {
this.messages = [{ role: "system", content: SYSTEM_PROMPT }];
this.history = [];
this.talkingTo = null;
}
stop() {
this.controller?.abort();
}
/**
* Run one user turn. `on` receives events: {type: "assistant", text}, {type: "tool", name, args},
* {type: "result", name, result}, {type: "error", message}, {type: "image", url}.
*/
async send(text, on = () => {}) {
if (this.busy) throw new Error("the agent is still working");
const settings = this.settings();
// A conversation belongs to its model (Claude's and Gemini's thinking is bound to it): another starts afresh.
const who = `${settings.provider ?? "openai"} ${settings.model}`;
if (this.talkingTo && this.talkingTo !== who) this.clear();
this.talkingTo = who;
this.controller = new AbortController();
const signal = this.controller.signal;
try {
if (settings.provider === "claude" || settings.provider === "gemini") {
const turn = settings.provider === "claude" ? (await import("./claude.js")).claudeTurn : geminiTurn;
await turn({
apiKey: settings.apiKey,
model: settings.model,
effort: settings.effort,
thinking: settings.effort,
system: SYSTEM_PROMPT,
specs: this.tools.specs(true),
history: this.history,
text,
call: (name, args) => this.tools.call(name, args),
on,
signal,
maxSteps: this.maxSteps,
});
} else await this.#openaiTurn(text, settings, on, signal);
} catch (error) {
if (error.name === "AbortError" || signal.aborted) on({ type: "error", message: "stopped" });
else on({ type: "error", message: error.message });
} finally {
this.controller = null;
}
}
async #openaiTurn(text, settings, on, signal) {
this.messages.push({ role: "user", content: text });
for (let step = 0; step < this.maxSteps; step++) {
const message = await complete({ ...settings, messages: this.messages, tools: this.tools.specs(settings.vision), signal });
const calls = message.tool_calls ?? [];
this.messages.push({ role: "assistant", content: message.content ?? "", ...(calls.length ? { tool_calls: calls } : {}) });
const said = (message.content ?? "").replace(/<think>[\s\S]*?<\/think>/g, "").trim();
if (said) on({ type: "assistant", text: said });
if (!calls.length) return;
const images = [];
for (const call of calls) {
if (signal.aborted) throw new DOMException("stopped", "AbortError");
let args = {};
try {
args = call.function.arguments ? JSON.parse(call.function.arguments) : {};
} catch {
args = {};
}
on({ type: "tool", name: call.function.name, args });
const result = await this.tools.call(call.function.name, args);
const { image, ...rest } = result ?? {};
if (image) {
images.push(image);
on({ type: "image", url: image });
}
on({ type: "result", name: call.function.name, result: rest });
this.messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(rest) });
}
// Tool messages carry text only; pictures go to the model as a user message.
if (images.length) {
this.messages.push({ role: "user", content: [{ type: "text", text: images.length > 1 ? "Camera images, in the order of the calls:" : "Camera image:" }, ...images.map((url) => ({ type: "image_url", image_url: { url } }))] });
}
}
on({ type: "assistant", text: `(stopped after ${this.maxSteps} steps)` });
}
}