@fluidframework/tree-agent 2.70.0-360753 → 2.70.0-361248
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/api-report/tree-agent.alpha.api.md +2 -2
- package/dist/agent.d.ts +4 -4
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +25 -0
- package/dist/agent.js.map +1 -1
- package/dist/api.d.ts +66 -0
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js.map +1 -1
- package/dist/prompt.d.ts.map +1 -1
- package/dist/prompt.js +111 -17
- package/dist/prompt.js.map +1 -1
- package/lib/agent.d.ts +4 -4
- package/lib/agent.d.ts.map +1 -1
- package/lib/agent.js +26 -1
- package/lib/agent.js.map +1 -1
- package/lib/api.d.ts +66 -0
- package/lib/api.d.ts.map +1 -1
- package/lib/api.js.map +1 -1
- package/lib/prompt.d.ts.map +1 -1
- package/lib/prompt.js +110 -16
- package/lib/prompt.js.map +1 -1
- package/package.json +12 -12
- package/src/agent.ts +34 -8
- package/src/api.ts +73 -0
- package/src/prompt.ts +118 -18
|
@@ -20,10 +20,10 @@ export type BindableSchema = TreeNodeSchema<string, NodeKind.Object> | TreeNodeS
|
|
|
20
20
|
export const bindEditor: typeof bindEditorImpl;
|
|
21
21
|
|
|
22
22
|
// @alpha
|
|
23
|
-
export function bindEditorImpl<TSchema extends ImplicitFieldSchema>(tree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode), editor:
|
|
23
|
+
export function bindEditorImpl<TSchema extends ImplicitFieldSchema>(tree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode), editor: AsynchronousEditor): (code: string) => Promise<void>;
|
|
24
24
|
|
|
25
25
|
// @alpha
|
|
26
|
-
export function bindEditorImpl<TSchema extends ImplicitFieldSchema>(tree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode), editor:
|
|
26
|
+
export function bindEditorImpl<TSchema extends ImplicitFieldSchema>(tree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode), editor: SynchronousEditor): (code: string) => void;
|
|
27
27
|
|
|
28
28
|
// @alpha
|
|
29
29
|
export function buildFunc<const Return extends z.ZodTypeAny, const Args extends readonly Arg[], const Rest extends z.ZodTypeAny | null = null>(def: {
|
package/dist/agent.d.ts
CHANGED
|
@@ -37,19 +37,19 @@ export declare class SharedTreeSemanticAgent<TSchema extends ImplicitFieldSchema
|
|
|
37
37
|
*/
|
|
38
38
|
export declare const defaultEditor: AsynchronousEditor;
|
|
39
39
|
/**
|
|
40
|
-
* Binds the given {@link
|
|
40
|
+
* Binds the given {@link AsynchronousEditor | editor} to the given view or tree.
|
|
41
41
|
* @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor function.
|
|
42
42
|
* @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.
|
|
43
43
|
* @alpha
|
|
44
44
|
*/
|
|
45
|
-
export declare function bindEditorImpl<TSchema extends ImplicitFieldSchema>(tree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode), editor:
|
|
45
|
+
export declare function bindEditorImpl<TSchema extends ImplicitFieldSchema>(tree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode), editor: AsynchronousEditor): (code: string) => Promise<void>;
|
|
46
46
|
/**
|
|
47
|
-
* Binds the given {@link
|
|
47
|
+
* Binds the given {@link SynchronousEditor | editor} to the given view or tree.
|
|
48
48
|
* @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor function.
|
|
49
49
|
* @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.
|
|
50
50
|
* @alpha
|
|
51
51
|
*/
|
|
52
|
-
export declare function bindEditorImpl<TSchema extends ImplicitFieldSchema>(tree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode), editor:
|
|
52
|
+
export declare function bindEditorImpl<TSchema extends ImplicitFieldSchema>(tree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode), editor: SynchronousEditor): (code: string) => void;
|
|
53
53
|
/**
|
|
54
54
|
* Binds the given {@link SynchronousEditor | synchronous} or {@link AsynchronousEditor | asynchronous} editor to the given view or tree.
|
|
55
55
|
* @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor.
|
package/dist/agent.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EACX,mBAAmB,EAGnB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,
|
|
1
|
+
{"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EACX,mBAAmB,EAGnB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAY,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,KAAK,EACX,aAAa,EAIb,MAAM,4BAA4B,CAAC;AAGpC,OAAO,KAAK,EACX,mBAAmB,EAEnB,oBAAoB,EAEpB,iBAAiB,EACjB,kBAAkB,EAElB,MAAM,UAAU,CAAC;AAGlB,OAAO,EAIN,KAAK,QAAQ,EAGb,MAAM,YAAY,CAAC;AAQpB;;;;GAIG;AACH,qBAAa,uBAAuB,CAAC,OAAO,SAAS,mBAAmB;IAStE,OAAO,CAAC,QAAQ,CAAC,MAAM;IAEvB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC;IAT1B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAmB;IAC7C;;OAEG;IACH,OAAO,CAAC,gBAAgB,CAAS;gBAGf,MAAM,EAAE,mBAAmB,EAC5C,IAAI,EAAE,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,OAAO,CAAC,GAAG,QAAQ,CAAC,EAC5C,OAAO,CAAC,4CAAgC;IAiC1D;;;;;OAKG;IACU,KAAK,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;CAqEvD;AAqED;;;;;GAKG;AACH,eAAO,MAAM,aAAa,EAAE,kBAI3B,CAAC;AAEF;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,OAAO,SAAS,mBAAmB,EACjE,IAAI,EAAE,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,OAAO,CAAC,GAAG,QAAQ,CAAC,EAC7D,MAAM,EAAE,kBAAkB,GACxB,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AACnC;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,OAAO,SAAS,mBAAmB,EACjE,IAAI,EAAE,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,OAAO,CAAC,GAAG,QAAQ,CAAC,EAC7D,MAAM,EAAE,iBAAiB,GACvB,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;AAe1B;;;;;;GAMG;AACH,eAAO,MAAM,UAAU,uBAAiB,CAAC"}
|
package/dist/agent.js
CHANGED
|
@@ -211,9 +211,11 @@ exports.bindEditor = bindEditorImpl;
|
|
|
211
211
|
function bindEditorToSubtree(tree, executeEdit) {
|
|
212
212
|
// Stick the tree schema constructors on an object passed to the function so that the LLM can create new nodes.
|
|
213
213
|
const create = {};
|
|
214
|
+
const is = {};
|
|
214
215
|
for (const schema of (0, utils_js_1.findNamedSchemas)(tree.schema)) {
|
|
215
216
|
const name = (0, utils_js_1.getFriendlyName)(schema);
|
|
216
217
|
create[name] = (input) => constructTreeNode(schema, input);
|
|
218
|
+
is[name] = (input) => alpha_1.Tree.is(input, schema);
|
|
217
219
|
}
|
|
218
220
|
const context = {
|
|
219
221
|
get root() {
|
|
@@ -223,6 +225,29 @@ function bindEditorToSubtree(tree, executeEdit) {
|
|
|
223
225
|
tree.field = value;
|
|
224
226
|
},
|
|
225
227
|
create,
|
|
228
|
+
is,
|
|
229
|
+
isArray(node) {
|
|
230
|
+
if (Array.isArray(node)) {
|
|
231
|
+
return true;
|
|
232
|
+
}
|
|
233
|
+
if (node instanceof tree_1.TreeNode) {
|
|
234
|
+
const schema = alpha_1.Tree.schema(node);
|
|
235
|
+
return schema.kind === tree_1.NodeKind.Array;
|
|
236
|
+
}
|
|
237
|
+
return false;
|
|
238
|
+
},
|
|
239
|
+
isMap(node) {
|
|
240
|
+
if (node instanceof Map) {
|
|
241
|
+
return true;
|
|
242
|
+
}
|
|
243
|
+
if (node instanceof tree_1.TreeNode) {
|
|
244
|
+
const schema = alpha_1.Tree.schema(node);
|
|
245
|
+
return schema.kind === tree_1.NodeKind.Map;
|
|
246
|
+
}
|
|
247
|
+
return false;
|
|
248
|
+
},
|
|
249
|
+
parent: (child) => alpha_1.Tree.parent(child),
|
|
250
|
+
key: (child) => alpha_1.Tree.key(child),
|
|
226
251
|
};
|
|
227
252
|
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
228
253
|
return (code) => executeEdit(context, code);
|
package/dist/agent.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAOH,+CAAgD;AAOhD,sDAAoE;AAUpE,2CAAuD;AACvD,6CAAuC;AACvC,yCAOoB;AAEpB;;;GAGG;AACH,MAAM,yBAAyB,GAAG,EAAE,CAAC;AAErC;;;;GAIG;AACH,MAAa,uBAAuB;IAQnC,YACkB,MAA2B,EAC5C,IAA6D,EAC5C,OAAwC;QAFxC,WAAM,GAAN,MAAM,CAAqB;QAE3B,YAAO,GAAP,OAAO,CAAiC;QAR1D;;WAEG;QACK,qBAAgB,GAAG,KAAK,CAAC;QAOhC,IAAI,IAAI,YAAY,eAAQ,EAAE,CAAC;YAC9B,YAAI,CAAC,EAAE,CAAC,IAAI,EAAE,aAAa,EAAE,GAAG,EAAE,CAAC,CAAC,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC,CAAC,CAAC;QACpE,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B,EAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;QACpD,MAAM,IAAI,GAAG,IAAA,0BAAe,EAAC,MAAM,CAAC,CAAC;QACrC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,KAA2B,EAAE,EAAE,CAAC,iBAAiB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAClF,CAAC;IAED,MAAM,OAAO,GAAG;QACf,IAAI,IAAI;YACP,OAAO,IAAI,CAAC,KAAK,CAAC;QACnB,CAAC;QACD,IAAI,IAAI,CAAC,KAAsD;YAC9D,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACpB,CAAC;QACD,MAAM;KACN,CAAC;IAEF,qEAAqE;IACrE,OAAO,CAAC,IAAY,EAAE,EAAE,CAAC,WAAW,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;AACrD,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport type {\n\tImplicitFieldSchema,\n\tTreeFieldFromImplicitField,\n\tTreeNodeSchema,\n} from \"@fluidframework/tree\";\nimport { TreeNode } from \"@fluidframework/tree\";\nimport type {\n\tReadableField,\n\tFactoryContentObject,\n\tInsertableContent,\n\tReadSchema,\n} from \"@fluidframework/tree/alpha\";\nimport { ObjectNodeSchema, Tree } from \"@fluidframework/tree/alpha\";\n\nimport type {\n\tSharedTreeChatModel,\n\tEditResult,\n\tSemanticAgentOptions,\n\tLogger,\n\tSynchronousEditor,\n\tAsynchronousEditor,\n} from \"./api.js\";\nimport { getPrompt, stringifyTree } from \"./prompt.js\";\nimport { Subtree } from \"./subtree.js\";\nimport {\n\tconstructNode,\n\tgetFriendlyName,\n\tllmDefault,\n\ttype TreeView,\n\tfindNamedSchemas,\n\ttoErrorString,\n} from \"./utils.js\";\n\n/**\n * The default maximum number of sequential edits the LLM can make before we assume it's stuck in a loop.\n * @remarks This can be overridden by passing {@link SemanticAgentOptions.maximumSequentialEdits | maximumSequentialEdits} to {@link createSemanticAgent}.\n */\nconst defaultMaxSequentialEdits = 20;\n\n/**\n * An agent that uses a {@link SharedTreeChatModel} to interact with a SharedTree.\n * @remarks This class forwards user queries to the chat model, and handles the application of any edits to the tree that the model requests.\n * @alpha @sealed\n */\nexport class SharedTreeSemanticAgent<TSchema extends ImplicitFieldSchema> {\n\t// Converted from ECMAScript private fields (#name) to TypeScript private members for easier debugger inspection.\n\tprivate readonly outerTree: Subtree<TSchema>;\n\t/**\n\t * Whether or not the outer tree has changed since the last query finished.\n\t */\n\tprivate outerTreeIsDirty = false;\n\n\tpublic constructor(\n\t\tprivate readonly client: SharedTreeChatModel,\n\t\ttree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode),\n\t\tprivate readonly options?: Readonly<SemanticAgentOptions>,\n\t) {\n\t\tif (tree instanceof TreeNode) {\n\t\t\tTree.on(tree, \"treeChanged\", () => (this.outerTreeIsDirty = true));\n\t\t} else {\n\t\t\ttree.events.on(\"changed\", () => (this.outerTreeIsDirty = true));\n\t\t}\n\n\t\tthis.outerTree = new Subtree(tree);\n\t\tconst prompt = getPrompt({\n\t\t\tsubtree: this.outerTree,\n\t\t\teditToolName: this.client.editToolName,\n\t\t\tdomainHints: this.options?.domainHints,\n\t\t});\n\t\tthis.options?.logger?.log(`# Fluid Framework SharedTree AI Agent Log\\n\\n`);\n\t\tconst now = new Date();\n\t\tconst formattedDate = now.toLocaleString(undefined, {\n\t\t\tweekday: \"long\",\n\t\t\tyear: \"numeric\",\n\t\t\tmonth: \"long\",\n\t\t\tday: \"numeric\",\n\t\t\thour: \"numeric\",\n\t\t\tminute: \"2-digit\",\n\t\t\tsecond: \"2-digit\",\n\t\t});\n\t\tthis.options?.logger?.log(`Agent created: **${formattedDate}**\\n\\n`);\n\t\tif (this.client.name !== undefined) {\n\t\t\tthis.options?.logger?.log(`Model: **${this.client.name}**\\n\\n`);\n\t\t}\n\t\tthis.client.appendContext?.(prompt);\n\t\tthis.options?.logger?.log(`## System Prompt\\n\\n${prompt}\\n\\n`);\n\t}\n\n\t/**\n\t * Given a user prompt, return a response.\n\t *\n\t * @param userPrompt - The prompt to send to the agent.\n\t * @returns The agent's response.\n\t */\n\tpublic async query(userPrompt: string): Promise<string> {\n\t\tthis.options?.logger?.log(`## User Query\\n\\n${userPrompt}\\n\\n`);\n\n\t\t// Notify the llm if the tree has changed since the last query, and if so, provide the new state of the tree.\n\t\tif (this.outerTreeIsDirty) {\n\t\t\tconst stringified = stringifyTree(this.outerTree.field);\n\t\t\tthis.client.appendContext?.(\n\t\t\t\t`The tree has changed since the last query. The new state of the tree is: \\n\\n\\`\\`\\`JSON\\n${stringified}\\n\\`\\`\\``,\n\t\t\t);\n\t\t\tthis.options?.logger?.log(\n\t\t\t\t`### Latest Tree State\\n\\nThe Tree was edited by a local or remote user since the previous query. The latest state is:\\n\\n\\`\\`\\`JSON\\n${stringified}\\n\\`\\`\\`\\n\\n`,\n\t\t\t);\n\t\t}\n\n\t\t// Fork a branch that will live for the lifetime of this query (which can be multiple LLM calls if the there are errors or the LLM decides to take multiple steps to accomplish a task).\n\t\t// The branch will be merged back into the outer branch if and only if the query succeeds.\n\t\tconst queryTree = this.outerTree.fork();\n\t\tconst maxEditCount = this.options?.maximumSequentialEdits ?? defaultMaxSequentialEdits;\n\t\tlet active = true;\n\t\tlet editCount = 0;\n\t\tlet rollbackEdits = false;\n\t\tconst { editToolName } = this.client;\n\t\tconst edit = async (editCode: string): Promise<EditResult> => {\n\t\t\tif (editToolName === undefined) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"disabledError\",\n\t\t\t\t\tmessage: \"Editing is not enabled for this model.\",\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (!active) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"expiredError\",\n\t\t\t\t\tmessage: `The query has already completed. Further edits are not allowed.`,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (++editCount > maxEditCount) {\n\t\t\t\trollbackEdits = true;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"tooManyEditsError\",\n\t\t\t\t\tmessage: `The maximum number of edits (${maxEditCount}) for this query has been exceeded.`,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst editResult = await applyTreeFunction(\n\t\t\t\tqueryTree,\n\t\t\t\teditCode,\n\t\t\t\tthis.options?.editor ?? defaultEditor,\n\t\t\t\tthis.options?.logger,\n\t\t\t);\n\n\t\t\trollbackEdits = editResult.type !== \"success\";\n\t\t\treturn editResult;\n\t\t};\n\n\t\tconst responseMessage = await this.client.query({\n\t\t\ttext: userPrompt,\n\t\t\tedit,\n\t\t});\n\t\tactive = false;\n\n\t\tif (!rollbackEdits) {\n\t\t\tthis.outerTree.branch.merge(queryTree.branch);\n\t\t\tthis.outerTreeIsDirty = false;\n\t\t}\n\t\tthis.options?.logger?.log(`## Response\\n\\n`);\n\t\tthis.options?.logger?.log(`${responseMessage}\\n\\n`);\n\t\treturn responseMessage;\n\t}\n}\n\n/**\n * Creates an unhydrated node of the given schema with the given value.\n * @remarks If the schema is an object with {@link llmDefault | default values}, this function populates the node with those defaults.\n */\nfunction constructTreeNode(schema: TreeNodeSchema, value: FactoryContentObject): TreeNode {\n\tif (schema instanceof ObjectNodeSchema) {\n\t\tconst inputWithDefaults: Record<string, InsertableContent | undefined> = {};\n\t\tfor (const [key, field] of schema.fields) {\n\t\t\tif (value[key] === undefined) {\n\t\t\t\tif (\n\t\t\t\t\ttypeof field.metadata.custom === \"object\" &&\n\t\t\t\t\tfield.metadata.custom !== null &&\n\t\t\t\t\tllmDefault in field.metadata.custom\n\t\t\t\t) {\n\t\t\t\t\tconst defaulter = field.metadata.custom[llmDefault];\n\t\t\t\t\tif (typeof defaulter === \"function\") {\n\t\t\t\t\t\tconst defaultValue: unknown = defaulter();\n\t\t\t\t\t\tif (defaultValue !== undefined) {\n\t\t\t\t\t\t\tinputWithDefaults[key] = defaultValue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tinputWithDefaults[key] = value[key];\n\t\t\t}\n\t\t}\n\t\treturn constructNode(schema, inputWithDefaults);\n\t}\n\treturn constructNode(schema, value);\n}\n\n/**\n * Applies the given function (as a string of JavaScript code or an actual function) to the given tree.\n */\nasync function applyTreeFunction<TSchema extends ImplicitFieldSchema>(\n\ttree: Subtree<TSchema>,\n\teditCode: string,\n\teditor: Required<SemanticAgentOptions>[\"editor\"],\n\tlogger: Logger | undefined,\n): Promise<EditResult> {\n\tlogger?.log(`### Editing Tool Invoked\\n\\n`);\n\tlogger?.log(`#### Generated Code\\n\\n\\`\\`\\`javascript\\n${editCode}\\n\\`\\`\\`\\n\\n`);\n\n\t// Fork a branch to edit. If the edit fails or produces an error, we discard this branch, otherwise we merge it.\n\tconst editTree = tree.fork();\n\tconst boundEditor = bindEditorToSubtree(editTree, editor);\n\ttry {\n\t\tawait boundEditor(editCode);\n\t} catch (error: unknown) {\n\t\tlogger?.log(`#### Error\\n\\n`);\n\t\tlogger?.log(`\\`\\`\\`JSON\\n${toErrorString(error)}\\n\\`\\`\\`\\n\\n`);\n\t\teditTree.branch.dispose();\n\t\treturn {\n\t\t\ttype: \"editingError\",\n\t\t\tmessage: `Running the generated code produced an error. The state of the tree will be reset to its previous state as it was before the code ran. Please try again. Here is the error: ${toErrorString(error)}`,\n\t\t};\n\t}\n\n\ttree.branch.merge(editTree.branch);\n\tlogger?.log(`#### New Tree State\\n\\n`);\n\tlogger?.log(`${`\\`\\`\\`JSON\\n${stringifyTree(tree.field)}\\n\\`\\`\\``}\\n\\n`);\n\treturn {\n\t\ttype: \"success\",\n\t\tmessage: `After running the code, the new state of the tree is:\\n\\n\\`\\`\\`JSON\\n${stringifyTree(tree.field)}\\n\\`\\`\\``,\n\t};\n}\n\n/**\n * The default {@link AsynchronousEditor | editor} implementation that simply uses `new Function` to run the provided code.\n * @remarks This editor allows both synchronous and asynchronous code (i.e. the provided code may return a Promise).\n * @example `await new Function(\"context\", code)(context);`\n * @alpha\n */\nexport const defaultEditor: AsynchronousEditor = async (context, code) => {\n\t// eslint-disable-next-line no-new-func, @typescript-eslint/no-implied-eval\n\tconst fn = new Function(\"context\", code);\n\tawait fn(context);\n};\n\n/**\n * Binds the given {@link SynchronousEditor | editor} to the given view or tree.\n * @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor function.\n * @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.\n * @alpha\n */\nexport function bindEditorImpl<TSchema extends ImplicitFieldSchema>(\n\ttree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode),\n\teditor: SynchronousEditor,\n): (code: string) => void;\n/**\n * Binds the given {@link AsynchronousEditor | editor} to the given view or tree.\n * @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor function.\n * @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.\n * @alpha\n */\nexport function bindEditorImpl<TSchema extends ImplicitFieldSchema>(\n\ttree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode),\n\teditor: AsynchronousEditor,\n): (code: string) => Promise<void>;\n/**\n * Binds the given {@link SynchronousEditor | editor} or {@link AsynchronousEditor | editor} to the given view or tree.\n * @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor function.\n * @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.\n * @alpha\n */\nexport function bindEditorImpl<TSchema extends ImplicitFieldSchema>(\n\ttree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode),\n\teditor: SynchronousEditor | AsynchronousEditor,\n): ((code: string) => void) | ((code: string) => Promise<void>) {\n\tconst subtree = new Subtree(tree);\n\treturn bindEditorToSubtree(subtree, editor);\n}\n\n/**\n * Binds the given {@link SynchronousEditor | synchronous} or {@link AsynchronousEditor | asynchronous} editor to the given view or tree.\n * @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor.\n * @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.\n * @alpha\n * @privateRemarks This exists (as opposed to just exporting bindEditorImpl directly) so that API documentation links work correctly.\n */\nexport const bindEditor = bindEditorImpl;\n\nfunction bindEditorToSubtree<TSchema extends ImplicitFieldSchema>(\n\ttree: Subtree<TSchema>,\n\texecuteEdit: SynchronousEditor | AsynchronousEditor,\n): (code: string) => void | Promise<void> {\n\t// Stick the tree schema constructors on an object passed to the function so that the LLM can create new nodes.\n\tconst create: Record<string, (input: FactoryContentObject) => TreeNode> = {};\n\tfor (const schema of findNamedSchemas(tree.schema)) {\n\t\tconst name = getFriendlyName(schema);\n\t\tcreate[name] = (input: FactoryContentObject) => constructTreeNode(schema, input);\n\t}\n\n\tconst context = {\n\t\tget root(): ReadableField<TSchema> {\n\t\t\treturn tree.field;\n\t\t},\n\t\tset root(value: TreeFieldFromImplicitField<ReadSchema<TSchema>>) {\n\t\t\ttree.field = value;\n\t\t},\n\t\tcreate,\n\t};\n\n\t// eslint-disable-next-line @typescript-eslint/promise-function-async\n\treturn (code: string) => executeEdit(context, code);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAOH,+CAA0D;AAO1D,sDAAoE;AAWpE,2CAAuD;AACvD,6CAAuC;AACvC,yCAOoB;AAEpB;;;GAGG;AACH,MAAM,yBAAyB,GAAG,EAAE,CAAC;AAErC;;;;GAIG;AACH,MAAa,uBAAuB;IAQnC,YACkB,MAA2B,EAC5C,IAA6D,EAC5C,OAAwC;QAFxC,WAAM,GAAN,MAAM,CAAqB;QAE3B,YAAO,GAAP,OAAO,CAAiC;QAR1D;;WAEG;QACK,qBAAgB,GAAG,KAAK,CAAC;QAOhC,IAAI,IAAI,YAAY,eAAQ,EAAE,CAAC;YAC9B,YAAI,CAAC,EAAE,CAAC,IAAI,EAAE,aAAa,EAAE,GAAG,EAAE,CAAC,CAAC,IAAI,CAAC,gBAAgB,GAAG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AC;YACD,OAAO,KAAK,CAAC;QACd,CAAC;QACD,MAAM,EAAE,CAAC,KAAe,EAAwB,EAAE,CAAC,YAAI,CAAC,MAAM,CAAC,KAAK,CAAC;QACrE,GAAG,EAAE,CAAC,KAAe,EAAmB,EAAE,CAAC,YAAI,CAAC,GAAG,CAAC,KAAK,CAAC;KAC/B,CAAC;IAE7B,qEAAqE;IACrE,OAAO,CAAC,IAAY,EAAE,EAAE,CAAC,WAAW,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;AACrD,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport type {\n\tImplicitFieldSchema,\n\tTreeFieldFromImplicitField,\n\tTreeNodeSchema,\n} from \"@fluidframework/tree\";\nimport { NodeKind, TreeNode } from \"@fluidframework/tree\";\nimport type {\n\tReadableField,\n\tFactoryContentObject,\n\tInsertableContent,\n\tReadSchema,\n} from \"@fluidframework/tree/alpha\";\nimport { ObjectNodeSchema, Tree } from \"@fluidframework/tree/alpha\";\n\nimport type {\n\tSharedTreeChatModel,\n\tEditResult,\n\tSemanticAgentOptions,\n\tLogger,\n\tSynchronousEditor,\n\tAsynchronousEditor,\n\tContext,\n} from \"./api.js\";\nimport { getPrompt, stringifyTree } from \"./prompt.js\";\nimport { Subtree } from \"./subtree.js\";\nimport {\n\tconstructNode,\n\tgetFriendlyName,\n\tllmDefault,\n\ttype TreeView,\n\tfindNamedSchemas,\n\ttoErrorString,\n} from \"./utils.js\";\n\n/**\n * The default maximum number of sequential edits the LLM can make before we assume it's stuck in a loop.\n * @remarks This can be overridden by passing {@link SemanticAgentOptions.maximumSequentialEdits | maximumSequentialEdits} to {@link createSemanticAgent}.\n */\nconst defaultMaxSequentialEdits = 20;\n\n/**\n * An agent that uses a {@link SharedTreeChatModel} to interact with a SharedTree.\n * @remarks This class forwards user queries to the chat model, and handles the application of any edits to the tree that the model requests.\n * @alpha @sealed\n */\nexport class SharedTreeSemanticAgent<TSchema extends ImplicitFieldSchema> {\n\t// Converted from ECMAScript private fields (#name) to TypeScript private members for easier debugger inspection.\n\tprivate readonly outerTree: Subtree<TSchema>;\n\t/**\n\t * Whether or not the outer tree has changed since the last query finished.\n\t */\n\tprivate outerTreeIsDirty = false;\n\n\tpublic constructor(\n\t\tprivate readonly client: SharedTreeChatModel,\n\t\ttree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode),\n\t\tprivate readonly options?: Readonly<SemanticAgentOptions>,\n\t) {\n\t\tif (tree instanceof TreeNode) {\n\t\t\tTree.on(tree, \"treeChanged\", () => (this.outerTreeIsDirty = true));\n\t\t} else {\n\t\t\ttree.events.on(\"changed\", () => (this.outerTreeIsDirty = true));\n\t\t}\n\n\t\tthis.outerTree = new Subtree(tree);\n\t\tconst prompt = getPrompt({\n\t\t\tsubtree: this.outerTree,\n\t\t\teditToolName: this.client.editToolName,\n\t\t\tdomainHints: this.options?.domainHints,\n\t\t});\n\t\tthis.options?.logger?.log(`# Fluid Framework SharedTree AI Agent Log\\n\\n`);\n\t\tconst now = new Date();\n\t\tconst formattedDate = now.toLocaleString(undefined, {\n\t\t\tweekday: \"long\",\n\t\t\tyear: \"numeric\",\n\t\t\tmonth: \"long\",\n\t\t\tday: \"numeric\",\n\t\t\thour: \"numeric\",\n\t\t\tminute: \"2-digit\",\n\t\t\tsecond: \"2-digit\",\n\t\t});\n\t\tthis.options?.logger?.log(`Agent created: **${formattedDate}**\\n\\n`);\n\t\tif (this.client.name !== undefined) {\n\t\t\tthis.options?.logger?.log(`Model: **${this.client.name}**\\n\\n`);\n\t\t}\n\t\tthis.client.appendContext?.(prompt);\n\t\tthis.options?.logger?.log(`## System Prompt\\n\\n${prompt}\\n\\n`);\n\t}\n\n\t/**\n\t * Given a user prompt, return a response.\n\t *\n\t * @param userPrompt - The prompt to send to the agent.\n\t * @returns The agent's response.\n\t */\n\tpublic async query(userPrompt: string): Promise<string> {\n\t\tthis.options?.logger?.log(`## User Query\\n\\n${userPrompt}\\n\\n`);\n\n\t\t// Notify the llm if the tree has changed since the last query, and if so, provide the new state of the tree.\n\t\tif (this.outerTreeIsDirty) {\n\t\t\tconst stringified = stringifyTree(this.outerTree.field);\n\t\t\tthis.client.appendContext?.(\n\t\t\t\t`The tree has changed since the last query. The new state of the tree is: \\n\\n\\`\\`\\`JSON\\n${stringified}\\n\\`\\`\\``,\n\t\t\t);\n\t\t\tthis.options?.logger?.log(\n\t\t\t\t`### Latest Tree State\\n\\nThe Tree was edited by a local or remote user since the previous query. The latest state is:\\n\\n\\`\\`\\`JSON\\n${stringified}\\n\\`\\`\\`\\n\\n`,\n\t\t\t);\n\t\t}\n\n\t\t// Fork a branch that will live for the lifetime of this query (which can be multiple LLM calls if the there are errors or the LLM decides to take multiple steps to accomplish a task).\n\t\t// The branch will be merged back into the outer branch if and only if the query succeeds.\n\t\tconst queryTree = this.outerTree.fork();\n\t\tconst maxEditCount = this.options?.maximumSequentialEdits ?? defaultMaxSequentialEdits;\n\t\tlet active = true;\n\t\tlet editCount = 0;\n\t\tlet rollbackEdits = false;\n\t\tconst { editToolName } = this.client;\n\t\tconst edit = async (editCode: string): Promise<EditResult> => {\n\t\t\tif (editToolName === undefined) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"disabledError\",\n\t\t\t\t\tmessage: \"Editing is not enabled for this model.\",\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (!active) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"expiredError\",\n\t\t\t\t\tmessage: `The query has already completed. Further edits are not allowed.`,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (++editCount > maxEditCount) {\n\t\t\t\trollbackEdits = true;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"tooManyEditsError\",\n\t\t\t\t\tmessage: `The maximum number of edits (${maxEditCount}) for this query has been exceeded.`,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst editResult = await applyTreeFunction(\n\t\t\t\tqueryTree,\n\t\t\t\teditCode,\n\t\t\t\tthis.options?.editor ?? defaultEditor,\n\t\t\t\tthis.options?.logger,\n\t\t\t);\n\n\t\t\trollbackEdits = editResult.type !== \"success\";\n\t\t\treturn editResult;\n\t\t};\n\n\t\tconst responseMessage = await this.client.query({\n\t\t\ttext: userPrompt,\n\t\t\tedit,\n\t\t});\n\t\tactive = false;\n\n\t\tif (!rollbackEdits) {\n\t\t\tthis.outerTree.branch.merge(queryTree.branch);\n\t\t\tthis.outerTreeIsDirty = false;\n\t\t}\n\t\tthis.options?.logger?.log(`## Response\\n\\n`);\n\t\tthis.options?.logger?.log(`${responseMessage}\\n\\n`);\n\t\treturn responseMessage;\n\t}\n}\n\n/**\n * Creates an unhydrated node of the given schema with the given value.\n * @remarks If the schema is an object with {@link llmDefault | default values}, this function populates the node with those defaults.\n */\nfunction constructTreeNode(schema: TreeNodeSchema, value: FactoryContentObject): TreeNode {\n\tif (schema instanceof ObjectNodeSchema) {\n\t\tconst inputWithDefaults: Record<string, InsertableContent | undefined> = {};\n\t\tfor (const [key, field] of schema.fields) {\n\t\t\tif (value[key] === undefined) {\n\t\t\t\tif (\n\t\t\t\t\ttypeof field.metadata.custom === \"object\" &&\n\t\t\t\t\tfield.metadata.custom !== null &&\n\t\t\t\t\tllmDefault in field.metadata.custom\n\t\t\t\t) {\n\t\t\t\t\tconst defaulter = field.metadata.custom[llmDefault];\n\t\t\t\t\tif (typeof defaulter === \"function\") {\n\t\t\t\t\t\tconst defaultValue: unknown = defaulter();\n\t\t\t\t\t\tif (defaultValue !== undefined) {\n\t\t\t\t\t\t\tinputWithDefaults[key] = defaultValue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tinputWithDefaults[key] = value[key];\n\t\t\t}\n\t\t}\n\t\treturn constructNode(schema, inputWithDefaults);\n\t}\n\treturn constructNode(schema, value);\n}\n\n/**\n * Applies the given function (as a string of JavaScript code or an actual function) to the given tree.\n */\nasync function applyTreeFunction<TSchema extends ImplicitFieldSchema>(\n\ttree: Subtree<TSchema>,\n\teditCode: string,\n\teditor: Required<SemanticAgentOptions>[\"editor\"],\n\tlogger: Logger | undefined,\n): Promise<EditResult> {\n\tlogger?.log(`### Editing Tool Invoked\\n\\n`);\n\tlogger?.log(`#### Generated Code\\n\\n\\`\\`\\`javascript\\n${editCode}\\n\\`\\`\\`\\n\\n`);\n\n\t// Fork a branch to edit. If the edit fails or produces an error, we discard this branch, otherwise we merge it.\n\tconst editTree = tree.fork();\n\tconst boundEditor = bindEditorToSubtree(editTree, editor);\n\ttry {\n\t\tawait boundEditor(editCode);\n\t} catch (error: unknown) {\n\t\tlogger?.log(`#### Error\\n\\n`);\n\t\tlogger?.log(`\\`\\`\\`JSON\\n${toErrorString(error)}\\n\\`\\`\\`\\n\\n`);\n\t\teditTree.branch.dispose();\n\t\treturn {\n\t\t\ttype: \"editingError\",\n\t\t\tmessage: `Running the generated code produced an error. The state of the tree will be reset to its previous state as it was before the code ran. Please try again. Here is the error: ${toErrorString(error)}`,\n\t\t};\n\t}\n\n\ttree.branch.merge(editTree.branch);\n\tlogger?.log(`#### New Tree State\\n\\n`);\n\tlogger?.log(`${`\\`\\`\\`JSON\\n${stringifyTree(tree.field)}\\n\\`\\`\\``}\\n\\n`);\n\treturn {\n\t\ttype: \"success\",\n\t\tmessage: `After running the code, the new state of the tree is:\\n\\n\\`\\`\\`JSON\\n${stringifyTree(tree.field)}\\n\\`\\`\\``,\n\t};\n}\n\n/**\n * The default {@link AsynchronousEditor | editor} implementation that simply uses `new Function` to run the provided code.\n * @remarks This editor allows both synchronous and asynchronous code (i.e. the provided code may return a Promise).\n * @example `await new Function(\"context\", code)(context);`\n * @alpha\n */\nexport const defaultEditor: AsynchronousEditor = async (context, code) => {\n\t// eslint-disable-next-line no-new-func, @typescript-eslint/no-implied-eval\n\tconst fn = new Function(\"context\", code);\n\tawait fn(context);\n};\n\n/**\n * Binds the given {@link AsynchronousEditor | editor} to the given view or tree.\n * @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor function.\n * @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.\n * @alpha\n */\nexport function bindEditorImpl<TSchema extends ImplicitFieldSchema>(\n\ttree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode),\n\teditor: AsynchronousEditor,\n): (code: string) => Promise<void>;\n/**\n * Binds the given {@link SynchronousEditor | editor} to the given view or tree.\n * @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor function.\n * @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.\n * @alpha\n */\nexport function bindEditorImpl<TSchema extends ImplicitFieldSchema>(\n\ttree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode),\n\teditor: SynchronousEditor,\n): (code: string) => void;\n/**\n * Binds the given {@link SynchronousEditor | editor} or {@link AsynchronousEditor | editor} to the given view or tree.\n * @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor function.\n * @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.\n * @alpha\n */\nexport function bindEditorImpl<TSchema extends ImplicitFieldSchema>(\n\ttree: TreeView<TSchema> | (ReadableField<TSchema> & TreeNode),\n\teditor: SynchronousEditor | AsynchronousEditor,\n): ((code: string) => void) | ((code: string) => Promise<void>) {\n\tconst subtree = new Subtree(tree);\n\treturn bindEditorToSubtree(subtree, editor);\n}\n\n/**\n * Binds the given {@link SynchronousEditor | synchronous} or {@link AsynchronousEditor | asynchronous} editor to the given view or tree.\n * @returns A function that takes a string of JavaScript code and executes it on the given view or tree using the given editor.\n * @remarks This is useful for testing/debugging code execution without needing to set up a full {@link SharedTreeSemanticAgent | agent}.\n * @alpha\n * @privateRemarks This exists (as opposed to just exporting bindEditorImpl directly) so that API documentation links work correctly.\n */\nexport const bindEditor = bindEditorImpl;\n\nfunction bindEditorToSubtree<TSchema extends ImplicitFieldSchema>(\n\ttree: Subtree<TSchema>,\n\texecuteEdit: SynchronousEditor | AsynchronousEditor,\n): (code: string) => void | Promise<void> {\n\t// Stick the tree schema constructors on an object passed to the function so that the LLM can create new nodes.\n\tconst create: Record<string, (input: FactoryContentObject) => TreeNode> = {};\n\tconst is: Record<string, <T extends TreeNode>(input: unknown) => input is T> = {};\n\tfor (const schema of findNamedSchemas(tree.schema)) {\n\t\tconst name = getFriendlyName(schema);\n\t\tcreate[name] = (input: FactoryContentObject) => constructTreeNode(schema, input);\n\t\tis[name] = <T extends TreeNode>(input: unknown): input is T => Tree.is(input, schema);\n\t}\n\n\tconst context = {\n\t\tget root(): ReadableField<TSchema> {\n\t\t\treturn tree.field;\n\t\t},\n\t\tset root(value: TreeFieldFromImplicitField<ReadSchema<TSchema>>) {\n\t\t\ttree.field = value;\n\t\t},\n\t\tcreate,\n\t\tis,\n\t\tisArray(node) {\n\t\t\tif (Array.isArray(node)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (node instanceof TreeNode) {\n\t\t\t\tconst schema = Tree.schema(node);\n\t\t\t\treturn schema.kind === NodeKind.Array;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t\tisMap(node) {\n\t\t\tif (node instanceof Map) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (node instanceof TreeNode) {\n\t\t\t\tconst schema = Tree.schema(node);\n\t\t\t\treturn schema.kind === NodeKind.Map;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t\tparent: (child: TreeNode): TreeNode | undefined => Tree.parent(child),\n\t\tkey: (child: TreeNode): string | number => Tree.key(child),\n\t} satisfies Context<TSchema>;\n\n\t// eslint-disable-next-line @typescript-eslint/promise-function-async\n\treturn (code: string) => executeEdit(context, code);\n}\n"]}
|
package/dist/api.d.ts
CHANGED
|
@@ -14,6 +14,72 @@ export interface Logger {
|
|
|
14
14
|
*/
|
|
15
15
|
log(message: string): void;
|
|
16
16
|
}
|
|
17
|
+
/**
|
|
18
|
+
* The context object available to generated code when editing a tree.
|
|
19
|
+
* @remarks This object is provided to JavaScript code executed by the {@link SynchronousEditor | editor} as a variable named `context`.
|
|
20
|
+
* It contains the current state of the tree and utilities for creating and inspecting tree nodes.
|
|
21
|
+
* @alpha
|
|
22
|
+
*/
|
|
23
|
+
export interface Context<TSchema extends ImplicitFieldSchema> {
|
|
24
|
+
/**
|
|
25
|
+
* The root of the tree that can be read or modified.
|
|
26
|
+
* @remarks
|
|
27
|
+
* You can read properties and navigate through the tree starting from this root.
|
|
28
|
+
* You can also assign a new value to this property to replace the entire tree, as long as the new value is one of the types allowed at the root.
|
|
29
|
+
*
|
|
30
|
+
* Example: Read the current root with `const currentRoot = context.root;`
|
|
31
|
+
*
|
|
32
|
+
* Example: Replace the entire root with `context.root = context.create.MyRootType({ });`
|
|
33
|
+
*/
|
|
34
|
+
root: ReadableField<TSchema>;
|
|
35
|
+
/**
|
|
36
|
+
* A collection of builder functions for creating new tree nodes.
|
|
37
|
+
* @remarks
|
|
38
|
+
* Each property on this object is named after a type in the tree schema.
|
|
39
|
+
* Call the corresponding function to create a new node of that type.
|
|
40
|
+
* Always use these builder functions when creating new nodes rather than plain JavaScript objects.
|
|
41
|
+
*
|
|
42
|
+
* Example: Create a new Person node with `context.create.Person({ name: "Alice", age: 30 })`
|
|
43
|
+
*/
|
|
44
|
+
create: Record<string, (input: FactoryContentObject) => TreeNode>;
|
|
45
|
+
/**
|
|
46
|
+
* A collection of type-checking functions for tree nodes.
|
|
47
|
+
* @remarks
|
|
48
|
+
* Each property on this object is named after a type in the tree schema.
|
|
49
|
+
* Call the corresponding function to check if a node is of that specific type.
|
|
50
|
+
* This is useful when working with nodes that could be one of multiple types.
|
|
51
|
+
*
|
|
52
|
+
* Example: Check if a node is a Person with `if (context.is.Person(node)) { console.log(node.name); }`
|
|
53
|
+
*/
|
|
54
|
+
is: Record<string, <T extends TreeNode>(input: T) => input is T>;
|
|
55
|
+
/**
|
|
56
|
+
* Checks if the given node is an array.
|
|
57
|
+
*/
|
|
58
|
+
isArray(value: unknown): boolean;
|
|
59
|
+
/**
|
|
60
|
+
* Checks if the given node is a map.
|
|
61
|
+
*/
|
|
62
|
+
isMap(value: unknown): boolean;
|
|
63
|
+
/**
|
|
64
|
+
* Returns the parent node of the given child node.
|
|
65
|
+
* @param child - The node whose parent you want to find.
|
|
66
|
+
* @returns The parent node, or `undefined` if the node is the root or is not in the tree.
|
|
67
|
+
* @remarks
|
|
68
|
+
* Example: Get the parent with `const parent = context.parent(childNode);`
|
|
69
|
+
*/
|
|
70
|
+
parent(child: TreeNode): TreeNode | undefined;
|
|
71
|
+
/**
|
|
72
|
+
* Returns the key or index of the given node within its parent.
|
|
73
|
+
* @param child - The node whose key you want to find.
|
|
74
|
+
* @returns A string key if the node is in an object or map, or a numeric index if the node is in an array.
|
|
75
|
+
* @remarks
|
|
76
|
+
* For a node in an object, this might return a string like "firstName".
|
|
77
|
+
* For a node in an array, this might return a number like 0, 1, 2, etc.
|
|
78
|
+
*
|
|
79
|
+
* Example: `const key = context.key(childNode);`
|
|
80
|
+
*/
|
|
81
|
+
key(child: TreeNode): string | number;
|
|
82
|
+
}
|
|
17
83
|
/**
|
|
18
84
|
* A synchronous function that executes a string of JavaScript code to perform an edit within a {@link SharedTreeSemanticAgent}.
|
|
19
85
|
* @param context - An object that must be provided to the generated code as a variable named "context" in its top-level scope.
|
package/dist/api.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAE1E,OAAO,KAAK,EAAE,oBAAoB,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAMtF;;;GAGG;AACH,MAAM,WAAW,MAAM;IACtB;;OAEG;IACH,GAAG,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B;AAED;;;;;;GAMG;AACH,M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ED;;;;;GAKG;AACH,MAAM,WAAW,mBAAmB;IACnC;;;;OAIG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;;;;;;OAOG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;;;OAKG;IACH,aAAa,CAAC,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACnC;;;OAGG;IACH,KAAK,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CACrD;AAED;;GAEG;AACH,MAAM,MAAM,YAAY,CAAC,OAAO,SAAS,mBAAmB,IAAI,CAAC,EAChE,IAAI,EACJ,MAAM,GACN,EAAE;IACF,IAAI,EAAE,aAAa,CAAC,OAAO,CAAC,CAAC;IAC7B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,KAAK,EAAE,oBAAoB,KAAK,QAAQ,CAAC,CAAC;CAClE,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC"}
|
package/dist/api.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.js","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AA4FH;;GAEG;AACH,SAAgB,YAAY,CAAC,KAAc;IAC1C,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QACjD,OAAO,KAAK,CAAC;IACd,CAAC;IACD,OAAO,CACN,OAAQ,KAAoB,CAAC,IAAI,KAAK,QAAQ;QAC9C,OAAQ,KAAoB,CAAC,OAAO,KAAK,QAAQ,CACjD,CAAC;AACH,CAAC;AARD,oCAQC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport type { ImplicitFieldSchema, TreeNode } from \"@fluidframework/tree\";\n// These are used for doc links\nimport type { FactoryContentObject, ReadableField } from \"@fluidframework/tree/alpha\";\n\n// This is used for doc links\n// eslint-disable-next-line unused-imports/no-unused-imports\nimport type { bindEditor, defaultEditor } from \"./agent.js\";\n\n/**\n * Logger interface for logging events from a {@link SharedTreeSemanticAgent}.\n * @alpha\n */\nexport interface Logger {\n\t/**\n\t * Log a message.\n\t */\n\tlog(message: string): void;\n}\n\n/**\n * A synchronous function that executes a string of JavaScript code to perform an edit within a {@link SharedTreeSemanticAgent}.\n * @param context - An object that must be provided to the generated code as a variable named \"context\" in its top-level scope.\n * @param code - The JavaScript code that should be executed.\n * @remarks To simulate the execution of an editor outside of an {@link SharedTreeSemanticAgent | agent}, you can use {@link bindEditor | bindEditor} to bind an editor to a specific subtree.\n * @alpha\n */\nexport type SynchronousEditor = (context: Record<string, unknown>, code: string) => void;\n/**\n * An asynchronous function that executes a string of JavaScript code to perform an edit within a {@link SharedTreeSemanticAgent}.\n * @param context - An object that must be provided to the generated code as a variable named \"context\" in its top-level scope.\n * @param code - The JavaScript code that should be executed.\n * @remarks To simulate the execution of an editor outside of an {@link SharedTreeSemanticAgent | agent}, you can use {@link bindEditor | bindEditor} to bind an editor to a specific subtree.\n * @alpha\n */\nexport type AsynchronousEditor = (\n\tcontext: Record<string, unknown>,\n\tcode: string,\n) => Promise<void>;\n\n/**\n * Options used to parameterize the creation of a {@link SharedTreeSemanticAgent}.\n * @alpha\n */\nexport interface SemanticAgentOptions {\n\t/**\n\t * Additional information about the application domain that will be included in the context provided to the {@link SharedTreeChatModel | model}.\n\t */\n\tdomainHints?: string;\n\t/**\n\t * Executes any generated JavaScript created by the {@link SharedTreeChatModel.editToolName | model's editing tool}.\n\t * @remarks If an error is thrown while executing the code, it will be caught and the message will be forwarded to the {@link SharedTreeChatModel | model} for debugging.\n\t * @remarks If this function is not provided, the generated code will be executed using a {@link defaultEditor | simple default} which may not provide sufficient security guarantees for some environments.\n\t * Use a library such as SES to provide a more secure implementation - see `@fluidframework/tree-agent-ses` for a drop-in implementation.\n\t *\n\t * To simulate the execution of an editor outside of an {@link SharedTreeSemanticAgent | agent}, you can use {@link bindEditor | bindEditor} to bind an editor to a specific subtree.\n\t */\n\teditor?: SynchronousEditor | AsynchronousEditor;\n\t/**\n\t * The maximum number of sequential edits the LLM can make before we assume it's stuck in a loop.\n\t */\n\tmaximumSequentialEdits?: number;\n\t/**\n\t * If supplied, generates human-readable markdown text describing the actions taken by the {@link SharedTreeSemanticAgent | agent} as it performs queries.\n\t */\n\tlogger?: Logger;\n}\n\n/**\n * A result from an edit attempt via the {@link SharedTreeChatQuery.edit} function.\n * @alpha\n */\nexport interface EditResult {\n\t/**\n\t * The type of the edit result.\n\t * @remarks\n\t * - `success`: The edit was successfully applied.\n\t * - `disabledError`: The model is not allowed to edit the tree (i.e. {@link SharedTreeChatModel.editToolName} was not provided).\n\t * - `editingError`: An error was thrown while parsing or executing the provided JavaScript.\n\t * - `tooManyEditsError`: The {@link SharedTreeChatQuery.edit} function has been called more than the number of times specified by {@link SemanticAgentOptions.maximumSequentialEdits} for the same message.\n\t * - `expiredError`: The {@link SharedTreeChatQuery.edit} function was called after the issuing query has already completed.\n\t */\n\ttype: \"success\" | \"disabledError\" | \"editingError\" | \"tooManyEditsError\" | \"expiredError\";\n\n\t/**\n\t * A human-readable message describing the result of the edit attempt.\n\t * @remarks In the case of an error, this message is appropriate to include in a model's chat history.\n\t */\n\tmessage: string;\n}\n\n/**\n * Type guard for {@link EditResult}.\n */\nexport function isEditResult(value: unknown): value is EditResult {\n\tif (value === null || typeof value !== \"object\") {\n\t\treturn false;\n\t}\n\treturn (\n\t\ttypeof (value as EditResult).type === \"string\" &&\n\t\ttypeof (value as EditResult).message === \"string\"\n\t);\n}\n\n/**\n * A query from a user to a {@link SharedTreeSemanticAgent}.\n * @remarks Processing a query may involve editing the SharedTree via the provided {@link SharedTreeChatQuery.edit} function.\n * @alpha\n */\nexport interface SharedTreeChatQuery {\n\t/**\n\t * The user's query.\n\t */\n\ttext: string;\n\t/**\n\t * Edit the tree with the provided JavaScript function code.\n\t * @remarks Attempting an edit may fail for a variety of reasons which are captured in the {@link EditResult | returned object}.\n\t * If an edit fails, the tree will not be modified and the model may attempt another edit if desired.\n\t * When the query ends, if the last edit attempt was successful, all edits made during the query will be merged into the agent's SharedTree.\n\t * Otherwise, all edits made during the query will be discarded.\n\t */\n\tedit(js: string): Promise<EditResult>;\n}\n\n/**\n * A plugin interface that handles queries from a {@link SharedTreeSemanticAgent}.\n * @remarks This wraps an underlying communication with an LLM and receives all necessary {@link SharedTreeChatModel.appendContext | context} from the {@link SharedTreeSemanticAgent | agent} for the LLM to properly analyze and edit the tree.\n * See `@fluidframework/tree-agent-langchain` for a drop-in implementation based on the LangChain library.\n * @alpha\n */\nexport interface SharedTreeChatModel {\n\t/**\n\t * A optional name of this chat model.\n\t * @remarks If supplied, this may be used in logging or debugging information.\n\t * @example \"gpt-5\"\n\t */\n\tname?: string;\n\t/**\n\t * The name of the tool that the model should use to edit the tree.\n\t * @remarks If supplied, this will be mentioned in the context provided to the model so that the underlying LLM will be encouraged to use it when a user query requires an edit.\n\t * The model should \"implement\" the tool by registering it with the underlying LLM API.\n\t * The tool should take an LLM-generated JavaScript function as input and supply it to the {@link SharedTreeChatQuery.edit | edit} function.\n\t * Instructions for generating the proper function signature and implementation will be provided by the {@link SharedTreeSemanticAgent | agent} via {@link SharedTreeChatModel.appendContext | context}.\n\t * If not supplied, the model will not be able to edit the tree (running the {@link SharedTreeChatQuery.edit | edit} function will fail).\n\t */\n\teditToolName?: string;\n\t/**\n\t * Add contextual information to the model that may be relevant to future queries.\n\t * @remarks In practice, this may be implemented by e.g. appending a \"system\" message to an LLM's chat/message history.\n\t * This context must be present in the context window of every {@link SharedTreeChatModel.query | query} for e.g. {@link SharedTreeChatModel.editToolName | editing} to work.\n\t * @param text - The message or context to append.\n\t */\n\tappendContext?(text: string): void;\n\t/**\n\t * Queries the chat model with a request from the user.\n\t * @remarks This model may simply return a text response to the query, or it may first call the {@link SharedTreeChatQuery.edit} function (potentially multiple times) to modify the tree in response to the query.\n\t */\n\tquery(message: SharedTreeChatQuery): Promise<string>;\n}\n\n/**\n * A function that edits a SharedTree.\n */\nexport type EditFunction<TSchema extends ImplicitFieldSchema> = ({\n\troot,\n\tcreate,\n}: {\n\troot: ReadableField<TSchema>;\n\tcreate: Record<string, (input: FactoryContentObject) => TreeNode>;\n}) => void | Promise<void>;\n"]}
|
|
1
|
+
{"version":3,"file":"api.js","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAqKH;;GAEG;AACH,SAAgB,YAAY,CAAC,KAAc;IAC1C,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QACjD,OAAO,KAAK,CAAC;IACd,CAAC;IACD,OAAO,CACN,OAAQ,KAAoB,CAAC,IAAI,KAAK,QAAQ;QAC9C,OAAQ,KAAoB,CAAC,OAAO,KAAK,QAAQ,CACjD,CAAC;AACH,CAAC;AARD,oCAQC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport type { ImplicitFieldSchema, TreeNode } from \"@fluidframework/tree\";\n// These are used for doc links\nimport type { FactoryContentObject, ReadableField } from \"@fluidframework/tree/alpha\";\n\n// This is used for doc links\n// eslint-disable-next-line unused-imports/no-unused-imports\nimport type { bindEditor, defaultEditor } from \"./agent.js\";\n\n/**\n * Logger interface for logging events from a {@link SharedTreeSemanticAgent}.\n * @alpha\n */\nexport interface Logger {\n\t/**\n\t * Log a message.\n\t */\n\tlog(message: string): void;\n}\n\n/**\n * The context object available to generated code when editing a tree.\n * @remarks This object is provided to JavaScript code executed by the {@link SynchronousEditor | editor} as a variable named `context`.\n * It contains the current state of the tree and utilities for creating and inspecting tree nodes.\n * @alpha\n */\nexport interface Context<TSchema extends ImplicitFieldSchema> {\n\t/**\n\t * The root of the tree that can be read or modified.\n\t * @remarks\n\t * You can read properties and navigate through the tree starting from this root.\n\t * You can also assign a new value to this property to replace the entire tree, as long as the new value is one of the types allowed at the root.\n\t *\n\t * Example: Read the current root with `const currentRoot = context.root;`\n\t *\n\t * Example: Replace the entire root with `context.root = context.create.MyRootType({ });`\n\t */\n\troot: ReadableField<TSchema>;\n\n\t/**\n\t * A collection of builder functions for creating new tree nodes.\n\t * @remarks\n\t * Each property on this object is named after a type in the tree schema.\n\t * Call the corresponding function to create a new node of that type.\n\t * Always use these builder functions when creating new nodes rather than plain JavaScript objects.\n\t *\n\t * Example: Create a new Person node with `context.create.Person({ name: \"Alice\", age: 30 })`\n\t */\n\tcreate: Record<string, (input: FactoryContentObject) => TreeNode>;\n\n\t/**\n\t * A collection of type-checking functions for tree nodes.\n\t * @remarks\n\t * Each property on this object is named after a type in the tree schema.\n\t * Call the corresponding function to check if a node is of that specific type.\n\t * This is useful when working with nodes that could be one of multiple types.\n\t *\n\t * Example: Check if a node is a Person with `if (context.is.Person(node)) { console.log(node.name); }`\n\t */\n\tis: Record<string, <T extends TreeNode>(input: T) => input is T>;\n\n\t/**\n\t * Checks if the given node is an array.\n\t */\n\tisArray(value: unknown): boolean;\n\n\t/**\n\t * Checks if the given node is a map.\n\t */\n\tisMap(value: unknown): boolean;\n\n\t/**\n\t * Returns the parent node of the given child node.\n\t * @param child - The node whose parent you want to find.\n\t * @returns The parent node, or `undefined` if the node is the root or is not in the tree.\n\t * @remarks\n\t * Example: Get the parent with `const parent = context.parent(childNode);`\n\t */\n\tparent(child: TreeNode): TreeNode | undefined;\n\n\t/**\n\t * Returns the key or index of the given node within its parent.\n\t * @param child - The node whose key you want to find.\n\t * @returns A string key if the node is in an object or map, or a numeric index if the node is in an array.\n\t * @remarks\n\t * For a node in an object, this might return a string like \"firstName\".\n\t * For a node in an array, this might return a number like 0, 1, 2, etc.\n\t *\n\t * Example: `const key = context.key(childNode);`\n\t */\n\tkey(child: TreeNode): string | number;\n}\n\n/**\n * A synchronous function that executes a string of JavaScript code to perform an edit within a {@link SharedTreeSemanticAgent}.\n * @param context - An object that must be provided to the generated code as a variable named \"context\" in its top-level scope.\n * @param code - The JavaScript code that should be executed.\n * @remarks To simulate the execution of an editor outside of an {@link SharedTreeSemanticAgent | agent}, you can use {@link bindEditor | bindEditor} to bind an editor to a specific subtree.\n * @alpha\n */\nexport type SynchronousEditor = (context: Record<string, unknown>, code: string) => void;\n/**\n * An asynchronous function that executes a string of JavaScript code to perform an edit within a {@link SharedTreeSemanticAgent}.\n * @param context - An object that must be provided to the generated code as a variable named \"context\" in its top-level scope.\n * @param code - The JavaScript code that should be executed.\n * @remarks To simulate the execution of an editor outside of an {@link SharedTreeSemanticAgent | agent}, you can use {@link bindEditor | bindEditor} to bind an editor to a specific subtree.\n * @alpha\n */\nexport type AsynchronousEditor = (\n\tcontext: Record<string, unknown>,\n\tcode: string,\n) => Promise<void>;\n\n/**\n * Options used to parameterize the creation of a {@link SharedTreeSemanticAgent}.\n * @alpha\n */\nexport interface SemanticAgentOptions {\n\t/**\n\t * Additional information about the application domain that will be included in the context provided to the {@link SharedTreeChatModel | model}.\n\t */\n\tdomainHints?: string;\n\t/**\n\t * Executes any generated JavaScript created by the {@link SharedTreeChatModel.editToolName | model's editing tool}.\n\t * @remarks If an error is thrown while executing the code, it will be caught and the message will be forwarded to the {@link SharedTreeChatModel | model} for debugging.\n\t * @remarks If this function is not provided, the generated code will be executed using a {@link defaultEditor | simple default} which may not provide sufficient security guarantees for some environments.\n\t * Use a library such as SES to provide a more secure implementation - see `@fluidframework/tree-agent-ses` for a drop-in implementation.\n\t *\n\t * To simulate the execution of an editor outside of an {@link SharedTreeSemanticAgent | agent}, you can use {@link bindEditor | bindEditor} to bind an editor to a specific subtree.\n\t */\n\teditor?: SynchronousEditor | AsynchronousEditor;\n\t/**\n\t * The maximum number of sequential edits the LLM can make before we assume it's stuck in a loop.\n\t */\n\tmaximumSequentialEdits?: number;\n\t/**\n\t * If supplied, generates human-readable markdown text describing the actions taken by the {@link SharedTreeSemanticAgent | agent} as it performs queries.\n\t */\n\tlogger?: Logger;\n}\n\n/**\n * A result from an edit attempt via the {@link SharedTreeChatQuery.edit} function.\n * @alpha\n */\nexport interface EditResult {\n\t/**\n\t * The type of the edit result.\n\t * @remarks\n\t * - `success`: The edit was successfully applied.\n\t * - `disabledError`: The model is not allowed to edit the tree (i.e. {@link SharedTreeChatModel.editToolName} was not provided).\n\t * - `editingError`: An error was thrown while parsing or executing the provided JavaScript.\n\t * - `tooManyEditsError`: The {@link SharedTreeChatQuery.edit} function has been called more than the number of times specified by {@link SemanticAgentOptions.maximumSequentialEdits} for the same message.\n\t * - `expiredError`: The {@link SharedTreeChatQuery.edit} function was called after the issuing query has already completed.\n\t */\n\ttype: \"success\" | \"disabledError\" | \"editingError\" | \"tooManyEditsError\" | \"expiredError\";\n\n\t/**\n\t * A human-readable message describing the result of the edit attempt.\n\t * @remarks In the case of an error, this message is appropriate to include in a model's chat history.\n\t */\n\tmessage: string;\n}\n\n/**\n * Type guard for {@link EditResult}.\n */\nexport function isEditResult(value: unknown): value is EditResult {\n\tif (value === null || typeof value !== \"object\") {\n\t\treturn false;\n\t}\n\treturn (\n\t\ttypeof (value as EditResult).type === \"string\" &&\n\t\ttypeof (value as EditResult).message === \"string\"\n\t);\n}\n\n/**\n * A query from a user to a {@link SharedTreeSemanticAgent}.\n * @remarks Processing a query may involve editing the SharedTree via the provided {@link SharedTreeChatQuery.edit} function.\n * @alpha\n */\nexport interface SharedTreeChatQuery {\n\t/**\n\t * The user's query.\n\t */\n\ttext: string;\n\t/**\n\t * Edit the tree with the provided JavaScript function code.\n\t * @remarks Attempting an edit may fail for a variety of reasons which are captured in the {@link EditResult | returned object}.\n\t * If an edit fails, the tree will not be modified and the model may attempt another edit if desired.\n\t * When the query ends, if the last edit attempt was successful, all edits made during the query will be merged into the agent's SharedTree.\n\t * Otherwise, all edits made during the query will be discarded.\n\t */\n\tedit(js: string): Promise<EditResult>;\n}\n\n/**\n * A plugin interface that handles queries from a {@link SharedTreeSemanticAgent}.\n * @remarks This wraps an underlying communication with an LLM and receives all necessary {@link SharedTreeChatModel.appendContext | context} from the {@link SharedTreeSemanticAgent | agent} for the LLM to properly analyze and edit the tree.\n * See `@fluidframework/tree-agent-langchain` for a drop-in implementation based on the LangChain library.\n * @alpha\n */\nexport interface SharedTreeChatModel {\n\t/**\n\t * A optional name of this chat model.\n\t * @remarks If supplied, this may be used in logging or debugging information.\n\t * @example \"gpt-5\"\n\t */\n\tname?: string;\n\t/**\n\t * The name of the tool that the model should use to edit the tree.\n\t * @remarks If supplied, this will be mentioned in the context provided to the model so that the underlying LLM will be encouraged to use it when a user query requires an edit.\n\t * The model should \"implement\" the tool by registering it with the underlying LLM API.\n\t * The tool should take an LLM-generated JavaScript function as input and supply it to the {@link SharedTreeChatQuery.edit | edit} function.\n\t * Instructions for generating the proper function signature and implementation will be provided by the {@link SharedTreeSemanticAgent | agent} via {@link SharedTreeChatModel.appendContext | context}.\n\t * If not supplied, the model will not be able to edit the tree (running the {@link SharedTreeChatQuery.edit | edit} function will fail).\n\t */\n\teditToolName?: string;\n\t/**\n\t * Add contextual information to the model that may be relevant to future queries.\n\t * @remarks In practice, this may be implemented by e.g. appending a \"system\" message to an LLM's chat/message history.\n\t * This context must be present in the context window of every {@link SharedTreeChatModel.query | query} for e.g. {@link SharedTreeChatModel.editToolName | editing} to work.\n\t * @param text - The message or context to append.\n\t */\n\tappendContext?(text: string): void;\n\t/**\n\t * Queries the chat model with a request from the user.\n\t * @remarks This model may simply return a text response to the query, or it may first call the {@link SharedTreeChatQuery.edit} function (potentially multiple times) to modify the tree in response to the query.\n\t */\n\tquery(message: SharedTreeChatQuery): Promise<string>;\n}\n\n/**\n * A function that edits a SharedTree.\n */\nexport type EditFunction<TSchema extends ImplicitFieldSchema> = ({\n\troot,\n\tcreate,\n}: {\n\troot: ReadableField<TSchema>;\n\tcreate: Record<string, (input: FactoryContentObject) => TreeNode>;\n}) => void | Promise<void>;\n"]}
|
package/dist/prompt.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt.d.ts","sourceRoot":"","sources":["../src/prompt.ts"],"names":[],"mappings":"AAAA;;;GAGG;
|
|
1
|
+
{"version":3,"file":"prompt.d.ts","sourceRoot":"","sources":["../src/prompt.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,KAAK,EAAE,mBAAmB,EAAe,MAAM,sBAAsB,CAAC;AAC7E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAIhE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAW5C;;GAEG;AACH,wBAAgB,SAAS,CAAC,KAAK,SAAS,mBAAmB,EAAE,IAAI,EAAE;IAClE,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;IACxB,YAAY,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB,GAAG,MAAM,CAyRT;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,aAAa,CAAC,mBAAmB,CAAC,GAAG,MAAM,CA8C9E"}
|
package/dist/prompt.js
CHANGED
|
@@ -5,9 +5,10 @@
|
|
|
5
5
|
*/
|
|
6
6
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
7
|
exports.stringifyTree = exports.getPrompt = void 0;
|
|
8
|
+
const internal_1 = require("@fluidframework/core-utils/internal");
|
|
8
9
|
const tree_1 = require("@fluidframework/tree");
|
|
9
10
|
const alpha_1 = require("@fluidframework/tree/alpha");
|
|
10
|
-
const
|
|
11
|
+
const internal_2 = require("@fluidframework/tree/internal");
|
|
11
12
|
const typeGeneration_js_1 = require("./typeGeneration.js");
|
|
12
13
|
const utils_js_1 = require("./utils.js");
|
|
13
14
|
/**
|
|
@@ -20,10 +21,19 @@ function getPrompt(args) {
|
|
|
20
21
|
const mapInterfaceName = "TreeMap";
|
|
21
22
|
const simpleSchema = (0, alpha_1.getSimpleSchema)(schema);
|
|
22
23
|
// Inspect the schema to determine what kinds of nodes are possible - this will affect how much information we need to include in the prompt.
|
|
24
|
+
const rootTypes = [...(0, internal_2.normalizeFieldSchema)(schema).allowedTypeSet];
|
|
25
|
+
const rootTypeUnion = `${rootTypes.map((t) => (0, utils_js_1.getFriendlyName)(t)).join(" | ")}`;
|
|
26
|
+
let nodeTypeUnion;
|
|
23
27
|
let hasArrays = false;
|
|
24
28
|
let hasMaps = false;
|
|
25
29
|
let exampleObjectName;
|
|
26
30
|
for (const [definition, nodeSchema] of simpleSchema.definitions) {
|
|
31
|
+
if (nodeSchema.kind !== tree_1.NodeKind.Leaf) {
|
|
32
|
+
nodeTypeUnion =
|
|
33
|
+
nodeTypeUnion === undefined
|
|
34
|
+
? (0, utils_js_1.unqualifySchema)(definition)
|
|
35
|
+
: `${nodeTypeUnion} | ${(0, utils_js_1.unqualifySchema)(definition)}`;
|
|
36
|
+
}
|
|
27
37
|
switch (nodeSchema.kind) {
|
|
28
38
|
case tree_1.NodeKind.Array: {
|
|
29
39
|
hasArrays = true;
|
|
@@ -52,22 +62,103 @@ function getPrompt(args) {
|
|
|
52
62
|
const stringified = stringifyTree(field);
|
|
53
63
|
const details = { hasHelperMethods: false };
|
|
54
64
|
const typescriptSchemaTypes = (0, utils_js_1.getZodSchemaAsTypeScript)(domainTypes, details);
|
|
65
|
+
const exampleTypeName = nodeTypeUnion === undefined
|
|
66
|
+
? undefined
|
|
67
|
+
: nodeTypeUnion
|
|
68
|
+
.split("|")
|
|
69
|
+
.map((part) => part.trim())
|
|
70
|
+
.find((part) => part.length > 0);
|
|
71
|
+
const createDocs = exampleObjectName === undefined
|
|
72
|
+
? ""
|
|
73
|
+
: `\n /**
|
|
74
|
+
* A collection of builder functions for creating new tree nodes.
|
|
75
|
+
* @remarks
|
|
76
|
+
* Each property on this object is named after a type in the tree schema.
|
|
77
|
+
* Call the corresponding function to create a new node of that type.
|
|
78
|
+
* Always use these builder functions when creating new nodes rather than plain JavaScript objects.
|
|
79
|
+
*
|
|
80
|
+
* For example:
|
|
81
|
+
*
|
|
82
|
+
* \`\`\`javascript
|
|
83
|
+
* // This creates a new ${exampleObjectName} object:
|
|
84
|
+
* const ${(0, utils_js_1.communize)(exampleObjectName)} = context.create.${exampleObjectName}({ ...properties });
|
|
85
|
+
* // Don't do this:
|
|
86
|
+
* // const ${(0, utils_js_1.communize)(exampleObjectName)} = { ...properties };
|
|
87
|
+
* \`\`\`
|
|
88
|
+
*/
|
|
89
|
+
create: Record<string, <T extends TreeData>(input: T) => T>;\n`;
|
|
90
|
+
const isDocs = exampleTypeName === undefined
|
|
91
|
+
? ""
|
|
92
|
+
: `\n /**
|
|
93
|
+
* A collection of type-guard functions for data in the tree.
|
|
94
|
+
* @remarks
|
|
95
|
+
* Each property on this object is named after a type in the tree schema.
|
|
96
|
+
* Call the corresponding function to check if a node is of that specific type.
|
|
97
|
+
* This is useful when working with nodes that could be one of multiple types.
|
|
98
|
+
*
|
|
99
|
+
* ${`Example: Check if a node is a ${exampleTypeName} with \`if (context.is.${exampleTypeName}(node)) {}\``}
|
|
100
|
+
*/
|
|
101
|
+
is: Record<string, <T extends TreeData>(data: unknown) => data is T>;
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Checks if the provided data is an array.
|
|
105
|
+
* @remarks
|
|
106
|
+
* DO NOT use \`Array.isArray\` to check if tree data is an array - use this function instead.
|
|
107
|
+
*
|
|
108
|
+
* This function will also work for native JavaScript arrays.
|
|
109
|
+
*
|
|
110
|
+
* ${`Example: \`if (context.isArray(node)) {}\``}
|
|
111
|
+
*/
|
|
112
|
+
isArray(data: any): boolean;
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Checks if the provided data is a map.
|
|
116
|
+
* @remarks
|
|
117
|
+
* DO NOT use \`instanceof Map\` to check if tree data is a map - use this function instead.
|
|
118
|
+
*
|
|
119
|
+
* This function will also work for native JavaScript Map instances.
|
|
120
|
+
*
|
|
121
|
+
* ${`Example: \`if (context.isMap(node)) {}\``}
|
|
122
|
+
*/
|
|
123
|
+
isMap(data: any): boolean;\n`;
|
|
124
|
+
const context = `\`\`\`typescript
|
|
125
|
+
${nodeTypeUnion === undefined ? "" : `type TreeData = ${nodeTypeUnion};\n\n`} /**
|
|
126
|
+
* An object available to generated code which provides read and write access to the tree as well as utilities for creating and inspecting data in the tree.
|
|
127
|
+
* @remarks This object is available as a variable named \`context\` in the scope of the generated JavaScript snippet.
|
|
128
|
+
*/
|
|
129
|
+
interface Context<TSchema extends ImplicitFieldSchema> {
|
|
130
|
+
/**
|
|
131
|
+
* The root of the tree that can be read or mutated.
|
|
132
|
+
* @remarks
|
|
133
|
+
* You can read properties and navigate through the tree starting from this root.
|
|
134
|
+
* You can also assign a new value to this property to replace the entire tree, as long as the new value is one of the types allowed at the root.
|
|
135
|
+
*
|
|
136
|
+
* Example: Read the current root with \`const currentRoot = context.root;\`
|
|
137
|
+
*${rootTypes.length > 0 ? ` Example: Replace the entire root with \`context.root = context.create.${(0, utils_js_1.getFriendlyName)(rootTypes[0] ?? (0, internal_1.oob)())}({ });\`\n *` : ""}/
|
|
138
|
+
root: ReadableField<TSchema>;
|
|
139
|
+
${createDocs}
|
|
140
|
+
${isDocs}
|
|
141
|
+
/**
|
|
142
|
+
* Returns the parent object/array/map of the given object/array/map, if there is one.
|
|
143
|
+
* @returns The parent node, or \`undefined\` if the node is the root or is not in the tree.
|
|
144
|
+
* @remarks
|
|
145
|
+
* Example: Get the parent with \`const parent = context.parent(child);\`
|
|
146
|
+
*/
|
|
147
|
+
parent(child: TreeData): TreeData | undefined;
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Returns the property key or index of the given object/array/map within its parent.
|
|
151
|
+
* @returns A string key if the child is in an object or map, or a numeric index if the child is in an array.
|
|
152
|
+
*
|
|
153
|
+
* Example: \`const key = context.key(child);\`
|
|
154
|
+
*/
|
|
155
|
+
key(child: TreeData): string | number;
|
|
156
|
+
}
|
|
157
|
+
\`\`\``;
|
|
55
158
|
const helperMethodExplanation = details.hasHelperMethods
|
|
56
159
|
? `Manipulating the data using the APIs described below is allowed, but when possible ALWAYS prefer to use any application helper methods exposed on the schema TypeScript types if the goal can be accomplished that way.
|
|
57
160
|
It will often not be possible to fully accomplish the goal using those helpers. When this is the case, mutate the objects as normal, taking into account the following guidance.`
|
|
58
161
|
: "";
|
|
59
|
-
const builderExplanation = exampleObjectName === undefined
|
|
60
|
-
? ""
|
|
61
|
-
: `When constructing new objects, you should wrap them in the appropriate builder function rather than simply making a javascript object.
|
|
62
|
-
The builders are available on the \`create\` property on the context object and are named according to the type that they create.
|
|
63
|
-
For example:
|
|
64
|
-
|
|
65
|
-
\`\`\`javascript
|
|
66
|
-
// This creates a new ${exampleObjectName} object:
|
|
67
|
-
const ${(0, utils_js_1.communize)(exampleObjectName)} = context.create.${exampleObjectName}({ /* ...properties... */ });
|
|
68
|
-
// Don't do this:
|
|
69
|
-
// const ${(0, utils_js_1.communize)(exampleObjectName)} = { /* ...properties... */ };
|
|
70
|
-
\`\`\`\n\n`;
|
|
71
162
|
const reinsertionExplanation = `Once non-primitive data has been removed from the tree (e.g. replaced via assignment, or removed from an array), that data cannot be re-inserted into the tree.
|
|
72
163
|
Instead, it must be deep cloned and recreated.
|
|
73
164
|
${exampleObjectName === undefined
|
|
@@ -132,7 +223,6 @@ ${getTreeMapNodeDocumentation(mapInterfaceName)}
|
|
|
132
223
|
\`\`\`
|
|
133
224
|
|
|
134
225
|
`;
|
|
135
|
-
const rootTypes = (0, internal_1.normalizeFieldSchema)(schema).allowedTypeSet;
|
|
136
226
|
const editing = `If the user asks you to edit the tree, you should author a snippet of JavaScript code to accomplish the user-specified goal, following the instructions for editing detailed below.
|
|
137
227
|
You must use the "${editToolName}" tool to run the generated code.
|
|
138
228
|
After editing the tree, review the latest state of the tree to see if it satisfies the user's request.
|
|
@@ -145,14 +235,18 @@ If the user asks you to edit the document, you will write a snippet of JavaScrip
|
|
|
145
235
|
The snippet may be synchronous or asynchronous (i.e. it may \`await\` functions if necessary).
|
|
146
236
|
The snippet has a \`context\` variable in its scope.
|
|
147
237
|
This \`context\` variable holds the current state of the tree in the \`root\` property.
|
|
148
|
-
You may mutate any part of
|
|
149
|
-
You may also set the \`root\` property of the context to be an entirely new value as long as it is one of the types allowed at the root of the tree (\`${
|
|
238
|
+
You may mutate any part of this tree as necessary, taking into account the caveats around${hasArrays ? ` arrays${hasMaps ? " and" : ""}` : ""}${hasMaps ? " maps" : ""} detailed below.
|
|
239
|
+
You may also set the \`root\` property of the context to be an entirely new value as long as it is one of the types allowed at the root of the tree (\`${rootTypeUnion}\`).
|
|
240
|
+
You should also use the \`context\` object to create new data to insert into the tree, using the builder functions available on the \`create\` property.
|
|
241
|
+
There are other additional helper functions available on the \`context\` object to help you analyze the tree.
|
|
242
|
+
Here is the definition of the \`Context\` interface:
|
|
243
|
+
${context}
|
|
150
244
|
${helperMethodExplanation}
|
|
151
245
|
${hasArrays ? arrayEditing : ""}${hasMaps ? mapEditing : ""}#### Additional Notes
|
|
152
246
|
|
|
153
247
|
Before outputting the edit function, you should check that it is valid according to both the application tree's schema and any restrictions of the editing APIs described above.
|
|
154
248
|
|
|
155
|
-
${
|
|
249
|
+
${reinsertionExplanation}
|
|
156
250
|
|
|
157
251
|
Finally, double check that the edits would accomplish the user's request (if it is possible).
|
|
158
252
|
|