Repository navigation
Introduce generic tool calling explainer - #375
domfarolino wants to merge 21 commits into
Conversation
martinthomson
left a comment
There was a problem hiding this comment.
This looks directionally good from my recollection of the discussion.
| - the exact representation files, images, and other binary values; | ||
| - payload-size limits and whether browsers may transform large values; | ||
| - the initial allowlist of supported types; and | ||
| - versioning of standardized lowerings. |
There was a problem hiding this comment.
Rather than say "versioning", I'd prefer that this was about how it might be possible to evolve how things are transformed into a model-compatible form.
We discussed versioning at some length when we met and it seems like there was a bit of a disconnect about expectations. None of that made it into this document, which is good, but I'd like to keep that solid.
One way to manage changes in serialization is the same way you would manage a new, incompatible version of a tool: define a new tool. If the tool takes a different type of object, then that different type can have different transforms to and from JSON.
There was a problem hiding this comment.
@martinthomson Do you think you could clarify this for me:
Rather than say "versioning", I'd prefer that this was about how it might be possible to evolve how things are transformed into a model-compatible form.
I removed this line from the explainer, but I want to make sure we're aligned on expectations here. I think this line was originally referencing how we might want to change the BiDi-exposed JSON serialization of the subset of web-serializable objects that we're supporting in naturalLanguageProperties tools, although I'm not sure that's even necessary. Maybe we're good to resolve this as-is, but if you have any outstanding concerns I'd love to hear them.
There was a problem hiding this comment.
how we might want to change the BiDi-exposed JSON serialization of the subset of web-serializable objects
It should be backwards compatible? So either additions to the existing data structure or the consumer needs to opt-in to ImageDataV2 serialization.
There was a problem hiding this comment.
There are always three ways I'm aware of to introduce new features. The first is as @khushalsagar suggests, which is to ensure that your addition is seamlessly compatible (adding dictionary members, for example). The second is to break everything, guaranteeing that a new capability is not consumed by an entity that does not understand the new thing, which is what you generally get with "versioning". The third is to negotiate their use, though this is generally only available in two-party scenarios.
Now, it's possible that new types can be added to JSON schema without major compatibility issues, which would then follow the first option. That might work. That said, you might need consumers of tools that use extended types to indicate their willingness to receive them before you expose them to an entity that can only produce JSON.
bvandersloot-mozilla
left a comment
There was a problem hiding this comment.
Also directionally correct from where I sit!
jakearchibald
left a comment
There was a problem hiding this comment.
I haven't done a full review yet, but figured I'd submit what I've got so far.
|
|
||
| ### Alternatives considered | ||
|
|
||
| #### EventTarget instead of Observer |
There was a problem hiding this comment.
I'm really undecided on this one haha. I'll have a think.
There was a problem hiding this comment.
@markafoltz also likes the EventTarget version more. :)
There was a problem hiding this comment.
Repolling for the Tool here seems fine to me, and probably better than the observer above to my eye.
Reworking this direction to reduce polling is possible: put stuff in the change event and adding filter options to getTools. Heck, have one of these pop out of a call to frame.getToolList(options)!
But I defer to Jake on how one would want to spell this.
There was a problem hiding this comment.
https://w3ctag.github.io/design-principles/#state-and-subclassing is probably relevant if you get into events.
There was a problem hiding this comment.
I think EventTarget is more natural, but the funky lifetime issues we summon (elaborated on in #375) are really weird if we hang EventTarget off of WindowProxy. It seems like a serious footgun to me, and I have to imagine that's why we avoid adding more things to WindowProxy / cross-origin event listeners, etc.
It'd be great to understand what the best alternative pattern to this would be. Putting a FooObserver in your own window that consumes a foreign WindowProxy helps us avoid touching the cross-realm state that gets us into the lifetime issues above, which is why I'm fine with it, but I'm not sure it's the most natural pattern.
There was a problem hiding this comment.
@domfarolino the lifetime issue of an object off the proxy is separate from using an EventTarget pattern. The EventTarget instead of Observer option below requires the caller to create and cache the object but uses an EventTarget to dispatch change notifications. Both can work.
@jakearchibald for lifetime issues see the Tool object on Window section.
There was a problem hiding this comment.
So, the lifetime issues aren't a problem in terms of EventTarget vs observer?
There was a problem hiding this comment.
Yes. Its only a problem if you want to cache the EventTarget. We originally wanted to put it on the window reference the caller has to the target browsing context but that got pretty complicated.
I'm fine with both ToolObserver and ToolList options here. What do you like more?
There was a problem hiding this comment.
Can't we just have windowProxy.addEventListener('toolschange'), or does that hit the lifecycle issue?
There was a problem hiding this comment.
It does. WindowProxy is not a stateful object, where would you cache the event listeners?
|
Note for me to think more about: Tools returning tools (for grouping and continuation) |
| primitives needed for model-exposed tools. If present, the tool opts-into the following: | ||
|
|
||
| - Constrained JSON input/output types. | ||
| - Exposure to the user-agent, and any powerful agent it delegates to. |
There was a problem hiding this comment.
Is this kinda weird if your goal was to expose a tool to webbidi?
Also, could the inverse be true, where you want these props, but not expose it outside the browser - for cases where the agent is web-based. But… eh if this isn't a realistic case, we could ignore it and deal with the consequences later if we're wrong. It might be worth checking with the Shopify folks here, since web-based agents was one of their use cases.
If we really want to avoid an extra boolean option for exposing externally, we could have a prop that takes a boolean or NaturalLanguageProperties, where true would be exposing externally but not to agents.
There was a problem hiding this comment.
Is this kinda weird if your goal was to expose a tool to webbidi? If we really want to avoid an extra boolean option for exposing externally, we could have a prop that takes a boolean or NaturalLanguageProperties, where true would be exposing externally but not to agents.
expose a tool with no naturalLanguageProperties to webbidi? what's the use-case and does it need to be in v1?
If we want to add it later, we can do a property like exposedToUserAgent: auto | always instead of a boolean. auto means tool is only exposed if it has nLP and always means its only exposed irrespective of nLP being there.
But… eh if this isn't a realistic case, we could ignore it and deal with the consequences later if we're wrong.
That's it, there's no case where a site should make tools available to web-based agents but not the UA. We can consider it if one shows up but has to be a good reason. I also don't see any harm in adding it later because it should be an opt-out.
There was a problem hiding this comment.
expose a tool with no naturalLanguageProperties to webbidi? what's the use-case
For testing - you can use a tool call to get a page into a particular state as a starting point for integrations tests.
and does it need to be in v1?
I think we need to make sure we're not designing ourselves into a corner on this.
There was a problem hiding this comment.
I think we need to make sure we're not designing ourselves into a corner on this.
Does the exposedToUserAgent: auto | always idea suffice to ensure that?
| Each tool also carries a reference to its source `WindowProxy`. That reference isn't always cross-origin, so for a same-origin frame it gives direct access to the DOM the shadow root was hiding. The closest existing pattern is `postMessage`: a frame inside a shadow tree can already pass its window reference out, but only on purpose. We should likely follow the same principle: by default, subtree discovery doesn't cross shadow boundaries but content inside the shadow tree can opt in to exposing its frames' tools upward. | ||
|
|
||
| ## Tool Serialization | ||
| A Document often runs functionality in a worker that it also wants to offer to other Documents. Today, every such call has to hop through the Document that brokers it. A Tool is a handle in the consumer's realm to a function in the executor's realm. So the broker could pass its handle to another consumer with postMessage(). This would create a new Tool handle in the receiving realm, bound to the same function. Calls would go directly to the executor. |
There was a problem hiding this comment.
Curious about the reference to postMessage() here. Wouldn't it simply get the tools via getTools?
There was a problem hiding this comment.
Once its serializable, you could send it to any consumer via postMessage. Like this example if you have a couple of iframes:
const tools = await app.contentWindow.getTools();
agent.contentWindow.postMessage(tools, "*");
the embedder is brokering between an app and an agent which don't know about each other directly. It pulls tools from the relevant app and sends them to the agent over postMessage.
|
|
||
| Each tool also carries a reference to its source `WindowProxy`. That reference isn't always cross-origin, so for a same-origin frame it gives direct access to the DOM the shadow root was hiding. The closest existing pattern is `postMessage`: a frame inside a shadow tree can already pass its window reference out, but only on purpose. We should likely follow the same principle: by default, subtree discovery doesn't cross shadow boundaries but content inside the shadow tree can opt in to exposing its frames' tools upward. | ||
|
|
||
| ## Tool Serialization |
There was a problem hiding this comment.
Similarly, it feels like tool serialization would allow for tool responses to contain other tools. This allows for tool grouping, but also continuation of an operation.
For example, a flight booking response could return a tool for booking an airport transfer.
However, this would require tools to be created & used without being registered.
There was a problem hiding this comment.
If we allowed tools to be created, and passed around without being registered, this would make the 'global' tool events even weirder.
There was a problem hiding this comment.
it feels like tool serialization would allow for tool responses to contain other tools.
Agreed, once a Tool is serializable i could see this working.
await toolManager.registerTool({ name: "a", execute: () => {} });
const [a] = await getTools();
await toolManager.registerTool({ name: "b", execute: () => a });
this would require tools to be created & used without being registered.
This makes the lifetime of tools on the provider side hard to reason about. Right now the contract is this:
- The provider registers tools with the ToolManager which is bound to a Document.
- The browser creates Tool instances and internally ties them to a registration above.
- When a caller calls execute, the browser routes the call to the registered tool in the ToolManager. If the tool has since been unregistered, execution fails.
There was a problem hiding this comment.
That's fair, although the current model doesn't work well for grouping & continuation.
That said, I'm happy to discuss it in further issues.
There was a problem hiding this comment.
That's fair, although the current model doesn't work well for grouping & continuation.
Why? I'm not seeing the problem. We'll always need a way for the browser to maintain a map of tool identifier -> executing function. Right now the lifetime of a tool in that map is explicitly controlled by the author. The browser could manage it implicitly by keeping entries alive in the map if another execution context has a reference to that Tool (or its in flight via postMessage). But that's complicated and weird if the provider's application state changes in a way that the execution function really shouldn't be called. So I want to know why the current model doesn't work before solving it.
Feel free to file an issue with more details, happy to discuss it there more. And I'm assuming we aren't designing ourselves into a corner such that this can't be added easily later. :)
There was a problem hiding this comment.
Unless I'm misunderstanding the proposal, here's how you'd do a simple continuation:
await toolManager.registerTool({
name: "start-game",
naturalLanguageProperties: {
description: "Start an adventure game!",
inputSchema: { /* … */ },
outputSchema: { /* … */ },
},
async execute(input, { signal }) {
const gameId = crypto.randomUUID();
const doorsController = new AbortController();
const doorToolName = (door) => `open-door-${door}-${gameId}`;
signal.addEventListener("abort", () => doorsController.abort(), {
once: true,
});
const registerDoor = (door) =>
toolManager.registerTool(
{
name: doorToolName(door),
naturalLanguageProperties: {
description: `Open door ${door}. You can only open one door.`,
inputSchema: { /* … */ },
outputSchema: { /* … */ },
},
async execute() {
// Unregister both doors - the choice has been made.
doorsController.abort();
return { /* … */ };
},
},
{ signal: doorsController.signal },
);
await Promise.all([registerDoor(1), registerDoor(2)]);
const tools = await self.getTools();
const doors = [1, 2].map((door) =>
tools.find((tool) => tool.name === doorToolName(door)),
);
return {
message: "You see two doors before you. Pick one.",
doors,
};
},
});Problems I see with this:
- Having to register the tool and then get it seems bad. I guess we could fix this by having
registerToolresolve with the tool. - Having to expose these continuation tools at the top level seems really broken. This means another agent would see the tool for "opening door two" in part of a flow that it isn't part of.
- It seems really easy to leak tools. I'm not sure if there's a way around that.
If registering the tool is what defines the lifecycle here, I think this is another example where naturalLanguageProperties controlling visibility is bad. In this case, you want to provide naturalLanguageProperties, but you do not want it to be visible to any agent - we're sharing it with the one session we want to be able to see it.
Maybe we need a specific way to handle continuation where the lifecycle of the tool is handled some other way.
There was a problem hiding this comment.
Ok. I see the problems now. Right now a Tool is like a public function, once its registered any caller can see (based on exposedTo) and invoke it. You want a callback like primitive: the provider creates a reference and sends it to a specific consumer. That needs a better model for both visibility and lifetime.
Could something like this work?
dictionary ToolManagerTool {
required DOMString name;
required ToolExecuteCallback execute;
AbortSignal signal;
};
dictionary ToolManagerRegisterToolOptions {
sequence<USVString> exposedTo;
};
optional ToolManagerCreateToolOptions {
boolean once = false;
};
interface ToolManager : EventTarget {
Promise<undefined> registerTool(ToolManagerTool tool, optional ToolManagerRegisterToolOptions options = {});
Promise<Tool> createTool(ToolManagerTool tool, ToolManagerCreateToolOptions options = {});
...
};
-
registerToolputs it in the list that tool discovery pulls from. -
createTooladds it to the browser's internal map but only for bookkeeping, these don't show up in tool discovery. The author sends them via any API that takes serializable objects.exposedTodoesn't make sense for these since you're explicitly deciding that when you send the tool.
To begin with, the author manages the lifetime in the internal map manually. We can add convenience options likeonceif a tool should only be invoked once. Kinda like your example.
There was a problem hiding this comment.
If we start to separate tool creation from tool discovery, we should just make Tool constructible, so you can do new Tool() and immediately be able to pass it anywhere, just like we do for MessageChannel and related primitives—construction is sync, and cross-realm bookkeeping happens async at serialization time. I think this is a reasonable proposal, and the only reason I stayed away from it in the past is that there wasn't a need for it. But if there is, seems OK to proceed with it.
Registration would then continue to be async, but I guess there's a question about what naturalLanguageProperties would do, given:
I think this is another example where naturalLanguageProperties controlling visibility is bad. In this case, you want to provide naturalLanguageProperties, but you do not want it to be visible to any agent - we're sharing it with the one session we want to be able to see it.
Maybe only tool creation would take naturalLanguageProperties, and then separately, registration of a natural language tool would imply UA exposure, whereas registration of a non-natural language tool would only buy you cross-origin getTools() exposure so you don't manually have to pass your tool around to other origins and WindowProxies that know about you? (I can't think of a use case where I'd really want global proxy exposure of a non-natural language tool, when I could just manually pass around the Tool object over postMessage() which is a perfectly fine discovery mechanism...)
Regardless, I might caution against this being the end-all solution for tool grouping and progressive disclosure though. If Tool becomes serializable, we could of course pass it across message ports and postMessage(), etc., but we need to think through how this would be exposed as a return value to tools. If a natural language tool with augmented serializable outputs returns a Tool object, how should that get exposed to agents outside the browser, communicating with the page over BiDi? So far we've envisioned:
- Platform-serializable objects being exposed over BiDi as pure JSON
- A BiDi-equivalent of
getTools()being the only way to actually retrieve tools for a page
If we want "Tool object return values" to be the way to progressively disclose tools, then we have to figure out what the JSON representation of Tool ends up being, and if it returns some magic UUID in JSON that gives agents another way of obtaining the tool's UUID separately from their getTools()-like API. Actually that's probably fine—Tool already has a UUID that we're planning to expose via BiDi (along with name/description, etc.) so that works well.
Still, I think we should also consider aligning on what MCP is doing as they try and solve the same exact problem on their side, and I hear they have a concrete proposal. Maybe @liady can point us to it?
| it. | ||
| - Consumer (`getTools()`, `executeTool()`, `toolchange`): both same-origin and cross-origin | ||
| contexts can use it. `exposedTo` further controls which origins can see each tool. | ||
| - Expose these APIs to Documents through `WindowProxy`. This means only Documents in the same |
There was a problem hiding this comment.
We may want to check with TAG as well that they agree on the windowProxy move given they're the ones who suggested moving from window.navigator to window.document in #173 (comment)
jakearchibald
left a comment
There was a problem hiding this comment.
As long as the shape and details here continue to be up for discussion, I'm happy for this to land.
|
|
||
| Each tool also carries a reference to its source `WindowProxy`. That reference isn't always cross-origin, so for a same-origin frame it gives direct access to the DOM the shadow root was hiding. The closest existing pattern is `postMessage`: a frame inside a shadow tree can already pass its window reference out, but only on purpose. We should likely follow the same principle: by default, subtree discovery doesn't cross shadow boundaries but content inside the shadow tree can opt in to exposing its frames' tools upward. | ||
|
|
||
| ## Tool Serialization |
There was a problem hiding this comment.
That's fair, although the current model doesn't work well for grouping & continuation.
That said, I'm happy to discuss it in further issues.
| Since DOMException and the native JavaScript \`Error\` types are both [serializable](https://html.spec.whatwg.org/C#serializable-objects), the error thrown from ToolManager’s `ToolExecuteCallback` is propagated to the tool.execute() caller. The serialization will exclude any internal details (like stack traces). | ||
|
|
||
| \[\!WARNING\] It's an open question as to whether we want to simply return userland errors exactly as they are to callers, or wrap all of them in a new error interface that's not constructible from JavaScript, like `ToolError` or `ToolRuntimeError`. The only benefit of this would be to make it impossible for a userland tool error from spoofing one of the errors generated by the browser when a tool fails for reasons outside of the tool implementation's control. | ||
| Since DOMException and the native JavaScript \`Error\` types are both [serializable](https://html.spec.whatwg.org/C#serializable-objects), the error thrown from ToolManager’s `ToolExecuteCallback` is propagated to the tool.execute() caller. See #tool-error-outputs for details. |
There was a problem hiding this comment.
@khushalsagar this link you added doesn't really work. Can you link to the right section properly?
This proposal includes three concrete API changes to satisfy great feedback from Mozilla, largely captured in #236 and #237.
Please take a look @jakearchibald, @martinthomson, @bvandersloot-mozilla.