Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

refactor: Split AI commands detection and execution (#2444)

Giuseppedda50628a638
diff --git a/apps/builder/app/builder/features/ai/commands-bar.tsx b/apps/builder/app/builder/features/ai/commands-bar.tsx
index b7cfc4d09c..1d892515dd 100644
--- a/apps/builder/app/builder/features/ai/commands-bar.tsx
+++ b/apps/builder/app/builder/features/ai/commands-bar.tsx
@@ -1,5 +1,10 @@
import { z } from "zod";
-import { copywriter, type operations, handleAiRequest } from "@webstudio-is/ai";
+import {
+ copywriter,
+ type operations,
+ handleAiRequest,
+ commandDetect,
+} from "@webstudio-is/ai";
import { createCssEngine } from "@webstudio-is/css-engine";
import { Button, InputField, Label, Text } from "@webstudio-is/design-system";
import { SpinnerIcon } from "@webstudio-is/icons";
@@ -9,6 +14,7 @@ import {
getIndexesWithinAncestors,
getStyleRules,
idAttribute,
+ componentAttribute,
} from "@webstudio-is/react-sdk";
import { createScope, findTreeInstanceIds } from "@webstudio-is/sdk";
import { computed } from "nanostores";
@@ -35,7 +41,7 @@ import { traverseTemplate } from "@webstudio-is/jsx-utils";
const handleSubmit = async (
event: React.FormEvent<HTMLFormElement>,
abortSignal: AbortSignal
-) => {
+): Promise<string[]> => {
const requestParams = Object.fromEntries(new FormData(event.currentTarget));
requestParams.components =
@@ -43,51 +49,104 @@ const handleSubmit = async (
? JSON.parse(requestParams.components)
: undefined;
- if (RequestParamsSchema.safeParse(requestParams).success === false) {
- throw new Error("Invalid prompt data");
+ if (
+ RequestParamsSchema.omit({ command: true }).safeParse(requestParams)
+ .success === false
+ ) {
+ return ["Invalid prompt data"];
}
- const result = await handleAiRequest<operations.Response>(
- fetch(restAi(), {
+ const commandsResponse = await handleAiRequest<commandDetect.Response>(
+ fetch(restAi("detect"), {
method: "POST",
- body: JSON.stringify(requestParams),
+ body: JSON.stringify({ prompt: requestParams.prompt }),
signal: abortSignal,
}),
- {
- signal: abortSignal,
- onChunk: (operationId, { completion }) => {
- if (operationId === "copywriter") {
- try {
- const jsonResponse = z
- .array(copywriter.TextInstanceSchema)
- .parse(JSON.parse(untruncateJson(completion)));
+ { signal: abortSignal }
+ );
- const currenTextInstance = jsonResponse.pop();
+ if (
+ commandsResponse.success === false ||
+ commandsResponse.type === "stream"
+ ) {
+ // Commands detection is not using streaming
+ // therefore this should never be the case.
+ // The check is here just for type safety.
+ if (commandsResponse.type === "stream") {
+ return ["Something went wrong."];
+ }
- if (currenTextInstance === undefined) {
- return;
- }
+ if (abortSignal.aborted === false) {
+ return [commandsResponse.data.message];
+ }
- patchTextInstance(currenTextInstance);
- } catch {
- /**/
- }
+ return [];
+ }
+
+ const promises = await Promise.allSettled(
+ commandsResponse.data.map((command) =>
+ handleAiRequest<operations.Response>(
+ fetch(restAi(), {
+ method: "POST",
+ body: JSON.stringify({ ...requestParams, command }),
+ signal: abortSignal,
+ }),
+ {
+ signal: abortSignal,
+ onChunk: (operationId, { completion }) => {
+ if (operationId === "copywriter") {
+ try {
+ const jsonResponse = z
+ .array(copywriter.TextInstanceSchema)
+ .parse(JSON.parse(untruncateJson(completion)));
+
+ const currenTextInstance = jsonResponse.pop();
+
+ if (currenTextInstance === undefined) {
+ return;
+ }
+
+ patchTextInstance(currenTextInstance);
+ } catch {
+ /**/
+ }
+ }
+ },
}
- },
- }
+ )
+ )
);
- if (result.success === true) {
- if (result.type === "json" && result.id === "operations") {
- restoreComponentsNamespace(result.data);
- applyOperations(result.data);
+ const errors = [];
+
+ for (const promise of promises) {
+ if (promise.status === "fulfilled") {
+ const result = promise.value;
+
+ if (result.success === false) {
+ errors.push(result.data.message);
+ continue;
+ }
+
+ if (result.type !== "json") {
+ continue;
+ }
+
+ if (result.id === "operations") {
+ restoreComponentsNamespace(result.data);
+ applyOperations(result.data);
+ continue;
+ }
+
+ // Handle other commands responses below.
+ // ...
+ //
+ } else if (promise.status === "rejected") {
+ errors.push(promise.reason);
}
- return;
}
- if (abortSignal.aborted === false) {
- throw new Error(result.data.message);
- }
+ return errors;
};
export const CommandsBar = () => {
@@ -116,11 +175,12 @@ export const CommandsBar = () => {
setIsLoading(true);
try {
- await handleSubmit(event, abort.current.signal);
+ const errors = await handleSubmit(event, abort.current.signal);
+ if (errors.length > 0) {
+ setError(errors.join("\n"));
+ }
} catch (error) {
- setError(
- error instanceof Error ? error.message : "Something went wrong."
- );
+ setError("Something went wrong.");
}
abort.current = undefined;
@@ -143,6 +203,7 @@ export const CommandsBar = () => {
name="instanceId"
value={selectedInstanceSelector ? selectedInstanceSelector[0] : ""}
/>
+ <input type="hidden" name="command" value="" />
<Button
onClick={(event) => {
if (isLoading) {
@@ -263,7 +324,7 @@ const $jsx = computed(
}
return `<style>{\`${engine.cssText.replace(/\n/gm, " ")}\`}</style>${jsx
- .replace(new RegExp(`${idAttribute}="[^"]+"`, "g"), "")
+ .replace(new RegExp(`${componentAttribute}="[^"]+"`, "g"), "")
.replace(/\n(data-)/g, " $1")}`;
}
);
diff --git a/apps/builder/app/routes/rest.ai.copy.ts b/apps/builder/app/routes/rest.ai.detect.ts
similarity index 70%
rename from apps/builder/app/routes/rest.ai.copy.ts
rename to apps/builder/app/routes/rest.ai.detect.ts
index 9a5ea77aa5..c7c58ea9c4 100644
--- a/apps/builder/app/routes/rest.ai.copy.ts
+++ b/apps/builder/app/routes/rest.ai.detect.ts
@@ -1,20 +1,20 @@
+import { z } from "zod";
import type { ActionArgs } from "@remix-run/node";
import {
- copywriter,
- createErrorResponse,
+ commandDetect,
createGptModel,
type GptModelMessageFormat,
+ createErrorResponse,
+ copywriter,
+ operations,
} from "@webstudio-is/ai/index.server";
import { isFeatureEnabled } from "@webstudio-is/feature-flags";
-import { authorizeProject } from "@webstudio-is/trpc-interface/index.server";
-import { z } from "zod";
+
import env from "~/env/env.server";
import { createContext } from "~/shared/context.server";
-export const RequestSchema = z.object({
- projectId: z.string(),
+export const RequestParamsSchema = z.object({
prompt: z.string().max(1200),
- textInstances: z.array(copywriter.TextInstanceSchema),
});
export const action = async ({ request }: ActionArgs) => {
@@ -27,6 +27,7 @@ export const action = async ({ request }: ActionArgs) => {
message: "The feature is not available",
debug: "aiCopy feature disabled",
}),
+ llmMessages: [],
};
}
@@ -38,6 +39,7 @@ export const action = async ({ request }: ActionArgs) => {
status: 401,
debug: "Invalid OpenAI API key",
}),
+ llmMessages: [],
};
}
@@ -52,10 +54,11 @@ export const action = async ({ request }: ActionArgs) => {
status: 401,
debug: "Invalid OpenAI API organization",
}),
+ llmMessages: [],
};
}
- const parsed = RequestSchema.safeParse(await request.json());
+ const parsed = RequestParamsSchema.safeParse(await request.json());
if (parsed.success === false) {
return {
@@ -65,19 +68,13 @@ export const action = async ({ request }: ActionArgs) => {
status: 401,
debug: "Invalid request data",
}),
+ llmMessages: [],
};
}
- const { projectId, prompt, textInstances } = parsed.data;
-
- // Permissions check
const requestContext = await createContext(request);
- const canEdit = await authorizeProject.hasProjectPermit(
- { projectId: projectId, permit: "edit" },
- requestContext
- );
- if (canEdit === false) {
+ if (requestContext.authorization.userId === undefined) {
return {
id: "ai",
...createErrorResponse({
@@ -86,30 +83,31 @@ export const action = async ({ request }: ActionArgs) => {
message: "You don't have edit access to this project",
debug: "Unauthorized access attempt",
}),
+ llmMessages: [],
};
}
- // End of Permissions check
+
+ const { prompt } = parsed.data;
const model = createGptModel({
apiKey: env.OPENAI_KEY,
organization: env.OPENAI_ORG,
- temperature: 0.5,
+ temperature: 0,
model: "gpt-3.5-turbo",
});
- const chain = copywriter.createChain<GptModelMessageFormat>();
-
- const response = await chain({
+ const commandDetectChain = commandDetect.createChain<GptModelMessageFormat>();
+ return commandDetectChain({
model,
context: {
prompt,
- textInstances,
+ commands: {
+ [copywriter.name]: "writes, rewrites, rephrases or translates text",
+ [operations.editStyles.name]: "edits styles",
+ [operations.generateTemplatePrompt.name]:
+ "handles a user interface generation request",
+ [operations.deleteInstance.name]: "deletes elements",
+ },
},
});
-
- if (response.success) {
- return response.data;
- }
-
- return response;
};
diff --git a/apps/builder/app/routes/rest.ai.ts b/apps/builder/app/routes/rest.ai.ts
index 9001b9201a..e5f06dc100 100644
--- a/apps/builder/app/routes/rest.ai.ts
+++ b/apps/builder/app/routes/rest.ai.ts
@@ -2,7 +2,6 @@ import { z } from "zod";
import type { ActionArgs } from "@remix-run/node";
import {
copywriter,
- commandDetect,
operations,
templateGenerator,
createGptModel,
@@ -10,8 +9,11 @@ import {
createErrorResponse,
type ModelMessage,
} from "@webstudio-is/ai/index.server";
+import {
+ copywriter as clientCopywriter,
+ operations as clientOperations,
+} from "@webstudio-is/ai";
import { isFeatureEnabled } from "@webstudio-is/feature-flags";
-
import env from "~/env/env.server";
import { createContext } from "~/shared/context.server";
import { authorizeProject } from "@webstudio-is/trpc-interface/index.server";
@@ -23,13 +25,20 @@ export const RequestParamsSchema = z.object({
prompt: z.string().max(1200),
components: z.array(z.string()),
jsx: z.string(),
+ command: z.union([
+ // Using client* friendly imports because RequestParamsSchema
+ // is used to parse the form data on the client too.
+ z.literal(clientCopywriter.name),
+ z.literal(clientOperations.editStylesName),
+ z.literal(clientOperations.generateTemplatePromptName),
+ z.literal(clientOperations.deleteInstanceName),
+ ]),
});
-export const maxDuration = 120;
+// Override Vercel's default serverless functions timeout.
+export const maxDuration = 120; // seconds
export const action = async ({ request }: ActionArgs) => {
- const llmMessages: ModelMessage[] = [];
-
if (isFeatureEnabled("ai") === false) {
return {
id: "ai",
@@ -39,7 +48,7 @@ export const action = async ({ request }: ActionArgs) => {
message: "The feature is not available",
debug: "aiCopy feature disabled",
}),
- llmMessages,
+ llmMessages: [],
};
}
@@ -51,7 +60,7 @@ export const action = async ({ request }: ActionArgs) => {
status: 401,
debug: "Invalid OpenAI API key",
}),
- llmMessages,
+ llmMessages: [],
};
}
@@ -66,7 +75,7 @@ export const action = async ({ request }: ActionArgs) => {
status: 401,
debug: "Invalid OpenAI API organization",
}),
- llmMessages,
+ llmMessages: [],
};
}
@@ -80,12 +89,10 @@ export const action = async ({ request }: ActionArgs) => {
status: 401,
debug: "Invalid request data",
}),
- llmMessages,
+ llmMessages: [],
};
}
- const { prompt, components, jsx, projectId, instanceId } = parsed.data;
-
const requestContext = await createContext(request);
if (requestContext.authorization.userId === undefined) {
@@ -97,46 +104,14 @@ export const action = async ({ request }: ActionArgs) => {
message: "You don't have edit access to this project",
debug: "Unauthorized access attempt",
}),
- llmMessages,
+ llmMessages: [],
};
}
- let model = createGptModel({
- apiKey: env.OPENAI_KEY,
- organization: env.OPENAI_ORG,
- temperature: 0,
- model: "gpt-3.5-turbo",
- });
-
- // Given a prompt, categorize the user request.
- // Based on that we can then decide whether we should execute standalone chains
- // or the operations chain which needs full context about the instances tree as JSX and CSS.
- const commandDetectChain = commandDetect.createChain<GptModelMessageFormat>();
- const commandDetectResponse = await commandDetectChain({
- model,
- context: {
- prompt,
- commands: [
- // @todo Find a good way to pass only the features we want/need to detect
- // without passing them all. As a safety measure we are currently passing them all
- // so that the LLM won't miscategorize the task and for example handle an "edit-style" request as a "write-copy" one.
- // During testing the LLM misdetected a stylistic request like "make it bold" as a request to rewrite the text to sound more "bold".
- "write-copy",
- "generate-user-interface",
- "edit-styles",
- "delete-elements",
- "generate-images-only",
- ],
- },
- });
-
- llmMessages.push(...commandDetectResponse.llmMessages);
+ const { prompt, components, jsx, projectId, instanceId, command } =
+ parsed.data;
- // If this is indeed a copy request use the copywriter chain.
- if (
- commandDetectResponse.success &&
- commandDetectResponse.data.some((command) => command === "write-copy")
- ) {
+ if (command === copywriter.name) {
const canEdit = await authorizeProject.hasProjectPermit(
{ projectId: projectId, permit: "edit" },
requestContext
@@ -144,18 +119,26 @@ export const action = async ({ request }: ActionArgs) => {
if (canEdit === false) {
return {
- id: commandDetectResponse.id,
+ id: copywriter.name,
...createErrorResponse({
error: "unauthorized",
status: 401,
message: "You don't have edit access to this project",
debug: "Unauthorized access attempt",
}),
- llmMessages,
+ llmMessages: [],
};
}
const { instances } = await loadBuildByProjectId(projectId);
+
+ const model = createGptModel({
+ apiKey: env.OPENAI_KEY,
+ organization: env.OPENAI_ORG,
+ temperature: 0,
+ model: "gpt-3.5-turbo",
+ });
+
const copywriterChain = copywriter.createChain<GptModelMessageFormat>();
const copywriterResponse = await copywriterChain({
model,
@@ -168,20 +151,19 @@ export const action = async ({ request }: ActionArgs) => {
},
});
- if (copywriterResponse.success) {
- // Return the copywriter generation stream.
- return copywriterResponse.data;
+ if (copywriterResponse.success === false) {
+ return copywriterResponse;
}
- return {
- ...copywriterResponse,
- llmMessages,
- };
+ // Return the copywriter generation stream.
+ return copywriterResponse.data;
}
// If the request requires context about the instances tree use the Operations chain.
- model = createGptModel({
+ const llmMessages: ModelMessage[] = [];
+
+ const model = createGptModel({
apiKey: env.OPENAI_KEY,
organization: env.OPENAI_ORG,
temperature: 0,
diff --git a/apps/builder/app/shared/router-utils/path-utils.ts b/apps/builder/app/shared/router-utils/path-utils.ts
index db57a34da5..ecd2e48215 100644
--- a/apps/builder/app/shared/router-utils/path-utils.ts
+++ b/apps/builder/app/shared/router-utils/path-utils.ts
@@ -163,4 +163,5 @@ export const getPublishedUrl = (domain: string) => {
return `${protocol}//${domain}.${host}`;
};
-export const restAi = () => `/rest/ai`;
+export const restAi = (subEndpoint?: "detect" | "copy") =>
+ typeof subEndpoint === "string" ? `/rest/ai/${subEndpoint}` : "/rest/ai";
diff --git a/packages/ai/src/chains/command-detect/README.md b/packages/ai/src/chains/command-detect/README.md
index 883d8bd4f4..465195c293 100644
--- a/packages/ai/src/chains/command-detect/README.md
+++ b/packages/ai/src/chains/command-detect/README.md
@@ -19,7 +19,7 @@ export async function handler({ request }) {
const model = createGptModel({
apiKey: process.env.OPENAI_KEY,
organization: process.env.OPENAI_ORG,
- temperature: 0.5,
+ temperature: 0,
model: "gpt-3.5-turbo",
});
@@ -29,11 +29,11 @@ export async function handler({ request }) {
model,
context: {
prompt,
- commands: [
- "write-text",
- "generate-images",
- // ... a list of descriptive command names that you want to detect
- ]
+ commands: {
+ "copywriter": "writes, rewrites, translates text",
+ "edit-styles": "edits styles",
+ // ...
+ }
}
});
diff --git a/packages/ai/src/chains/command-detect/__generated__/command-detect.system.prompt.ts b/packages/ai/src/chains/command-detect/__generated__/command-detect.system.prompt.ts
index 74e54aca45..0dede8158f 100644
--- a/packages/ai/src/chains/command-detect/__generated__/command-detect.system.prompt.ts
+++ b/packages/ai/src/chains/command-detect/__generated__/command-detect.system.prompt.ts
@@ -1,12 +1,12 @@
-export const prompt = `Given a user prompt and a list of available operations, your task is to infer what is the user request about and return a list with one or multiple operation names that fit the prompt.
+export const prompt = `Given a prompt where a user requests you to perform a task, you should determine what's the task type.
-Available operations:
+Avaliable tasks are provided below as an object with task_name:task_description pairs:
-\`\`\`
+\`\`\`json
{commands}
\`\`\`
-For example if the user is asking to translate the operation should be a copywrite and you should respond with ["copywrite"]
+The task description can help you infer the task name to pick. For example if the user is asking to translate you should respond with ["copywrite"]
-Respond with a valid JSON array of operation names or an empty array if you think that none of the operations is relevant for the user request. Start with [
+Respond with a valid JSON array of task names that are relevant for the user request. Start with [
`;
diff --git a/packages/ai/src/chains/command-detect/chain.ts b/packages/ai/src/chains/command-detect/chain.ts
index f4b1ee7476..a71e918796 100644
--- a/packages/ai/src/chains/command-detect/chain.ts
+++ b/packages/ai/src/chains/command-detect/chain.ts
@@ -11,10 +11,13 @@ import { createErrorResponse } from "../../utils/create-error-response";
* Given a prompt and a list of possible commands and descriptions, it returns an array of operations matching the prompt request.
*/
+export const name = "command-detect";
+
export const ContextSchema = z.object({
// The prompt provides the original user request.
prompt: z.string(),
- commands: z.array(z.string()),
+ // Command name - description pairs.
+ commands: z.record(z.string(), z.string()),
});
export type Context = z.infer<typeof ContextSchema>;
@@ -27,8 +30,6 @@ export const createChain = <ModelMessageFormat>(): Chain<
Response
> =>
async function chain({ model, context }) {
- const id = "command-detect";
-
const { prompt, commands } = context;
const llmMessages: ModelMessage[] = [
@@ -47,7 +48,7 @@ export const createChain = <ModelMessageFormat>(): Chain<
const messages = model.generateMessages(llmMessages);
const completion = await model.completion({
- id,
+ id: name,
messages,
});
@@ -64,7 +65,7 @@ export const createChain = <ModelMessageFormat>(): Chain<
let detectedCommands = [];
try {
detectedCommands = ResponseSchema.parse(JSON.parse(completionText));
- const expectedCommands = new Set(commands);
+ const expectedCommands = new Set(Object.keys(commands));
for (const command of detectedCommands) {
if (expectedCommands.has(command) === false) {
throw new Error("Invalid command name detected " + command);
@@ -72,7 +73,7 @@ export const createChain = <ModelMessageFormat>(): Chain<
}
} catch (error) {
return {
- id,
+ id: name,
...createErrorResponse({
status: 500,
error: "ai.parseError",
diff --git a/packages/ai/src/chains/command-detect/command-detect.system.prompt.md b/packages/ai/src/chains/command-detect/command-detect.system.prompt.md
index c52ad388a9..b810268d23 100644
--- a/packages/ai/src/chains/command-detect/command-detect.system.prompt.md
+++ b/packages/ai/src/chains/command-detect/command-detect.system.prompt.md
@@ -1,11 +1,11 @@
-Given a user prompt and a list of available operations, your task is to infer what is the user request about and return a list with one or multiple operation names that fit the prompt.
+Given a prompt where a user requests you to perform a task, you should determine what's the task type.
-Available operations:
+Avaliable tasks are provided below as an object with task_name:task_description pairs:
-```
+```json
{commands}
```
-For example if the user is asking to translate the operation should be a copywrite and you should respond with ["copywrite"]
+The task description can help you infer the task name to pick. For example if the user is asking to translate you should respond with ["copywrite"]
-Respond with a valid JSON array of operation names or an empty array if you think that none of the operations is relevant for the user request. Start with [
+Respond with a valid JSON array of task names that are relevant for the user request. Start with [
diff --git a/packages/ai/src/chains/command-detect/index.ts b/packages/ai/src/chains/command-detect/index.ts
index 9c0952f12b..66fd813adf 100644
--- a/packages/ai/src/chains/command-detect/index.ts
+++ b/packages/ai/src/chains/command-detect/index.ts
@@ -1 +1 @@
-export { type Response, ResponseSchema } from "./chain";
+export { name, type Response, ResponseSchema } from "./chain";
diff --git a/packages/ai/src/chains/copywriter/README.md b/packages/ai/src/chains/copywriter/README.md
index 84a86a43ec..0a144f0cb6 100644
--- a/packages/ai/src/chains/copywriter/README.md
+++ b/packages/ai/src/chains/copywriter/README.md
@@ -27,21 +27,31 @@ export async function handler({ request }) {
const chain = copywriter.createChain<GptModelMessageFormat>();
- // Respond with a stream.
- return chain({
+ const response = await chain({
model,
context: {
prompt,
textInstances
}
- })
+ });
+
+ if (response.success === false) {
+ return response;
+ }
+
+ // Respond with the text generation stream.
+ return response.stream;
}
```
Client side:
```tsx
-import { copywriter, request, StreamingResponseTextType } from "@webstudio-is/ai";
+import {
+ copywriter,
+ handleAiRequest,
+ type RemixStreamingTextResponse
+} from "@webstudio-is/ai";
function UiComponent() {
const [error, setError] = useState();
@@ -68,8 +78,8 @@ function UiComponent() {
return;
}
- request<StreamingResponseTextType>(
- [
+ handleAiRequest<RemixStreamingTextResponse>(
+ fetch(
'/rest/ai/copy',
{
method: "POST",
@@ -80,8 +90,9 @@ function UiComponent() {
}),
signal: abort.current.signal,
},
- ],
+ ),
{
+ signal: abort.current.signal,
onChunk: (id, { completion, done }) => {
// Log the completion.
console.log(completion)
diff --git a/packages/ai/src/chains/copywriter/chain.ts b/packages/ai/src/chains/copywriter/chain.ts
index 74eefec2b8..9a144676f4 100644
--- a/packages/ai/src/chains/copywriter/chain.ts
+++ b/packages/ai/src/chains/copywriter/chain.ts
@@ -14,6 +14,8 @@ import type { RemixStreamingTextResponse } from "../../utils/remix-streaming-tex
* this chain generates copy for the instance and all its descendant text nodes.
*/
+export const name = "copywriter";
+
export const TextInstanceSchema = z.object({
instanceId: z.string(),
index: z.number(),
@@ -46,56 +48,54 @@ export const createChain = <ModelMessageFormat>(): Chain<
async function chain({ model, context }) {
const { prompt, textInstances } = context;
- const id = "copywriter";
-
- const llmMessages: ModelMessage[] = [
- ["system", promptSystemTemplate],
- [
- "user",
- formatPrompt(
- {
- prompt,
- text_nodes: JSON.stringify(textInstances),
- },
- promptUserTemplate
- ),
- ],
- ];
-
if (textInstances.length === 0) {
const message = "No text nodes found for the instance";
return {
- id,
+ id: name,
...createErrorResponse({
status: 404,
error: "ai.copywriter.textNodesNotFound",
message,
debug: message,
}),
- llmMessages,
+ llmMessages: [],
};
}
- try {
- z.array(TextInstanceSchema).parse(textInstances);
- } catch (error) {
+ if (
+ z.array(TextInstanceSchema).safeParse(textInstances).success === false
+ ) {
const message = "Invalid nodes list";
return {
- id,
+ id: name,
...createErrorResponse({
status: 404,
error: "ai.parseError",
message,
debug: message,
}),
- llmMessages,
+ llmMessages: [],
};
}
+ const llmMessages: ModelMessage[] = [
+ ["system", promptSystemTemplate],
+ [
+ "user",
+ formatPrompt(
+ {
+ prompt,
+ text_nodes: JSON.stringify(textInstances),
+ },
+ promptUserTemplate
+ ),
+ ],
+ ];
+
const messages = model.generateMessages(llmMessages);
const response = await model.completionStream({
- id,
+ id: name,
messages,
});
diff --git a/packages/ai/src/chains/copywriter/index.ts b/packages/ai/src/chains/copywriter/index.ts
index 2523eb8356..e469ad4ea5 100644
--- a/packages/ai/src/chains/copywriter/index.ts
+++ b/packages/ai/src/chains/copywriter/index.ts
@@ -1,4 +1,5 @@
export {
+ name,
type Response,
ResponseSchema,
type TextInstance,
diff --git a/packages/ai/src/chains/operations/README.md b/packages/ai/src/chains/operations/README.md
index b0011ded24..c05382d435 100644
--- a/packages/ai/src/chains/operations/README.md
+++ b/packages/ai/src/chains/operations/README.md
@@ -117,11 +117,16 @@ export async function handler({ request }) {
Client side:
```tsx
-import { operations, request, type ErrorResponse } from "@webstudio-is/ai";
+import {
+ operations,
+ handleAiRequest
+} from "@webstudio-is/ai";
import { applyOperations } from "./apply-operations";
-request<operations.Response>(
- [
+const abortController = new AbortController();
+
+handleAiRequest<operations.Response>(
+ fetch(
'/rest/ai/op',
{
method: 'POST',
@@ -129,11 +134,15 @@ request<operations.Response>(
prompt,
components: getAvailableComponentsFromWebstudioMetas(...),
jsx: getJsxAndCssForSelectedInstance(...),
- })
+ }),
+ signal: abortController.signal
}
- ]
+ ),
+ {
+ signal: abortController.signal
+ }
).then((result) => {
- if (result.success) {
+ if (result.success === true && result.id === operations.name) {
applyOperations(result.data);
}
});
diff --git a/packages/ai/src/chains/operations/__generated__/operations.system.prompt.ts b/packages/ai/src/chains/operations/__generated__/operations.system.prompt.ts
index 8504d4ce73..8d25ffc980 100644
--- a/packages/ai/src/chains/operations/__generated__/operations.system.prompt.ts
+++ b/packages/ai/src/chains/operations/__generated__/operations.system.prompt.ts
@@ -6,5 +6,7 @@ The available operations are defined by the following JSON schema which you shou
{operationsSchema}
\`\`\`
+Properties value might contain descriptions with instructions on how to fill them out. When they do please keep those in mind when generating a completion.
+
Respond with an array of operations as JSON and no other text. Start with [{"operation":
`;
diff --git a/packages/ai/src/chains/operations/chain.ts b/packages/ai/src/chains/operations/chain.ts
index f390a2afc6..50b0341be8 100644
--- a/packages/ai/src/chains/operations/chain.ts
+++ b/packages/ai/src/chains/operations/chain.ts
@@ -21,6 +21,8 @@ import { createErrorResponse } from "../../utils/create-error-response";
* it generates a series of edit operations to fulfill an edit request coming from the user.
*/
+export const name = "operations";
+
export const ContextSchema = z.object({
prompt: z.string().describe("Edit request from the user"),
components: z.array(z.string()).describe("Available Webstudio components"),
@@ -37,8 +39,6 @@ export const createChain = <ModelMessageFormat>(): Chain<
Response
> =>
async function chain({ model, context }) {
- const id = "operations";
-
const { prompt, components, jsx } = context;
const operationsSchema = zodToJsonSchema(
@@ -72,7 +72,7 @@ export const createChain = <ModelMessageFormat>(): Chain<
const messages = model.generateMessages(llmMessages);
const completion = await model.completion({
- id,
+ id: name,
messages,
});
@@ -91,7 +91,7 @@ export const createChain = <ModelMessageFormat>(): Chain<
);
if (parsedCompletion.success === false) {
return {
- id,
+ id: name,
...createErrorResponse({
status: 500,
error: "ai.parseError",
@@ -116,7 +116,7 @@ export const createChain = <ModelMessageFormat>(): Chain<
}
} catch (error) {
return {
- id,
+ id: name,
...createErrorResponse({
status: 500,
error: "ai.parseError",
diff --git a/packages/ai/src/chains/operations/delete-instance.ts b/packages/ai/src/chains/operations/delete-instance.ts
index b6c4d01632..416c3c4d81 100644
--- a/packages/ai/src/chains/operations/delete-instance.ts
+++ b/packages/ai/src/chains/operations/delete-instance.ts
@@ -1,6 +1,9 @@
import { z } from "zod";
+import { idAttribute } from "@webstudio-is/react-sdk";
-const wsId = z.string().describe("The element's ws-id to remove");
+export const name = "delete-instance";
+
+const wsId = z.string().describe(`The element's ${idAttribute} to remove`);
export const aiOperation = z.object({
operation: z.literal("deleteInstance"),
diff --git a/packages/ai/src/chains/operations/edit-styles.ts b/packages/ai/src/chains/operations/edit-styles.ts
index 6ab4d2d292..7ce077a5e9 100644
--- a/packages/ai/src/chains/operations/edit-styles.ts
+++ b/packages/ai/src/chains/operations/edit-styles.ts
@@ -1,10 +1,12 @@
import { z } from "zod";
-import { EmbedTemplateStyleDecl } from "@webstudio-is/react-sdk";
+import { EmbedTemplateStyleDecl, idAttribute } from "@webstudio-is/react-sdk";
import { parseTailwindToWebstudio } from "@webstudio-is/css-data";
+export const name = "edit-styles";
+
const wsId = z
.string()
- .describe("The element's ws-id that must get the new styles");
+ .describe(`The ${idAttribute} value of the element being edited.`);
export const aiOperation = z.object({
operation: z.literal("editStylesWithTailwindCSS"),
diff --git a/packages/ai/src/chains/operations/generate-insert-template.ts b/packages/ai/src/chains/operations/generate-insert-template.ts
index a27eb3948f..4e643507a9 100644
--- a/packages/ai/src/chains/operations/generate-insert-template.ts
+++ b/packages/ai/src/chains/operations/generate-insert-template.ts
@@ -1,15 +1,17 @@
import { z } from "zod";
-import { WsEmbedTemplate } from "@webstudio-is/react-sdk";
+import { WsEmbedTemplate, idAttribute } from "@webstudio-is/react-sdk";
import { jsxToTemplate } from "../../utils/jsx-to-template.server";
// Currently this operation is used is a separate LLM call after the main one has returned an insert-instance operation. This is to produce better results.
// Effectively the aiOperation from this module is not used. The separate chain will call the LLM and we use the resulting completion to construct an aiOperation by hand
// and pass it to this file's aiOperationToWs, replacing the initial insert-instance operation.
+export const name = "generate-insert-template";
+
const wsId = z
.string()
.describe(
- "Append the generated code to the element with this data-ws-id. Don't use element names for this value."
+ `The ${idAttribute} value of the host element. The result will be added to this element.`
);
export const aiOperation = z.object({
diff --git a/packages/ai/src/chains/operations/generate-template-prompt.ts b/packages/ai/src/chains/operations/generate-template-prompt.ts
index 322e15445d..7f91a68c84 100644
--- a/packages/ai/src/chains/operations/generate-template-prompt.ts
+++ b/packages/ai/src/chains/operations/generate-template-prompt.ts
@@ -1,12 +1,15 @@
import { z } from "zod";
+import { idAttribute } from "@webstudio-is/react-sdk";
// Currently this operation is used to prepare a context for the insert-template operations.
// insert-template is processed as a regular chain in a separate LLM call. This is to produce better results.
+export const name = "generate-template-prompt";
+
const wsId = z
.string()
.describe(
- "Add the generated code to the element with this data-ws-id. Don't use element names for this value."
+ `The ${idAttribute} value of the host element. The result will be added to this element.`
);
export const aiOperation = z.object({
diff --git a/packages/ai/src/chains/operations/index.ts b/packages/ai/src/chains/operations/index.ts
index e39fbb6892..4e69e61627 100644
--- a/packages/ai/src/chains/operations/index.ts
+++ b/packages/ai/src/chains/operations/index.ts
@@ -1,4 +1,4 @@
-export { type Response, ResponseSchema } from "./chain";
+export { name, type Response, ResponseSchema } from "./chain";
export {
AiOperationsSchema,
@@ -10,21 +10,25 @@ export {
// Operations.
export {
+ name as editStylesName,
aiOperation as editStylesAiOperation,
wsOperation as editStylesWsOperation,
} from "./edit-styles";
export {
+ name as generateTemplatePromptName,
aiOperation as generateTemplatePromptAiOperation,
wsOperation as generateTemplatePromptWsOperation,
} from "./generate-template-prompt";
export {
+ name as generateInsertTemplateName,
aiOperation as generateInsertTemplateAiOperation,
wsOperation as generateInsertTemplateWsOperation,
} from "./generate-insert-template";
export {
+ name as deleteInstanceName,
aiOperation as deleteInstanceAiOperation,
wsOperation as deleteInstanceWsOperation,
} from "./delete-instance";
diff --git a/packages/ai/src/chains/operations/operations.system.prompt.md b/packages/ai/src/chains/operations/operations.system.prompt.md
index 0737e8808b..f217c9bc75 100644
--- a/packages/ai/src/chains/operations/operations.system.prompt.md
+++ b/packages/ai/src/chains/operations/operations.system.prompt.md
@@ -6,4 +6,6 @@ The available operations are defined by the following JSON schema which you shou
{operationsSchema}
```
+Properties value might contain descriptions with instructions on how to fill them out. When they do please keep those in mind when generating a completion.
+
Respond with an array of operations as JSON and no other text. Start with [{"operation":
diff --git a/packages/ai/src/chains/template-generator/README.md b/packages/ai/src/chains/template-generator/README.md
index 1652760802..095c538de9 100644
--- a/packages/ai/src/chains/template-generator/README.md
+++ b/packages/ai/src/chains/template-generator/README.md
@@ -35,25 +35,16 @@ export async function handler({ request }) {
}
});
- if (response.success === false) {
- return response;
- }
-
- return {
- success: true,
- data: response.data,
- };
+ // response.data contains the template
+
+ return response;
}
```
Client side:
```tsx
-import {
- templateGenerator,
- request,
- type ErrorResponse,
-} from "@webstudio-is/ai";
+import { templateGenerator, handleAiRequest } from "@webstudio-is/ai";
function UiComponent() {
const [error, setError] = useState();
@@ -75,16 +66,15 @@ function UiComponent() {
return;
}
- request<templateGenerator.Response>([
- "/rest/ai/template-generator",
- {
+ handleAiRequest<templateGenerator.Response>(
+ fetch("/rest/ai/template-generator", {
method: "POST",
body: JSON.stringify({
prompt,
components: JSON.parse(components) || [],
}),
- },
- ]).then((response) => {
+ })
+ ).then((response) => {
if (response.success) {
// Log the template
console.log(response.data);
diff --git a/packages/ai/src/chains/template-generator/chain.ts b/packages/ai/src/chains/template-generator/chain.ts
index eb2529b552..0db54f82d9 100644
--- a/packages/ai/src/chains/template-generator/chain.ts
+++ b/packages/ai/src/chains/template-generator/chain.ts
@@ -17,6 +17,8 @@ import { getCode } from "../../utils/get-code";
* Given a UI section or widget description, this chain generates a Webstudio Embed Template representing the UI.
*/
+export const name = "template-generator";
+
export const ContextSchema = z.object({
// The prompt provides the original user request.
prompt: z.string(),
@@ -33,8 +35,6 @@ export const createChain = <ModelMessageFormat>(): Chain<
Response
> =>
async function chain({ model, context }) {
- const id = "template-generator";
-
const { prompt, components } = context;
const llmMessages: ModelMessage[] = [
@@ -53,7 +53,7 @@ export const createChain = <ModelMessageFormat>(): Chain<
const messages = model.generateMessages(llmMessages);
const completion = await model.completion({
- id,
+ id: name,
messages,
});
@@ -73,7 +73,7 @@ export const createChain = <ModelMessageFormat>(): Chain<
template = await jsxToTemplate(getCode(completionText, "jsx"));
} catch (error) {
return {
- id,
+ id: name,
...createErrorResponse({
status: 500,
debug: (
@@ -89,7 +89,7 @@ export const createChain = <ModelMessageFormat>(): Chain<
postProcessTemplate(template, components);
} catch (error) {
return {
- id,
+ id: name,
...createErrorResponse({
status: 500,
debug: (
diff --git a/packages/ai/src/chains/template-generator/index.ts b/packages/ai/src/chains/template-generator/index.ts
index 9c0952f12b..66fd813adf 100644
--- a/packages/ai/src/chains/template-generator/index.ts
+++ b/packages/ai/src/chains/template-generator/index.ts
@@ -1 +1 @@
-export { type Response, ResponseSchema } from "./chain";
+export { name, type Response, ResponseSchema } from "./chain";
diff --git a/packages/ai/src/utils/handle-ai-request.ts b/packages/ai/src/utils/handle-ai-request.ts
index 6e13e5d266..607d0c30a7 100644
--- a/packages/ai/src/utils/handle-ai-request.ts
+++ b/packages/ai/src/utils/handle-ai-request.ts
@@ -18,7 +18,7 @@ type RequestOptions = {
export const handleAiRequest = <ResponseData>(
request: Promise<Response>,
- options?: RequestOptions
+ options: RequestOptions
) => {
return request
.then(async (response) => {