@browserbasehq/orca 3.2.0-middleware.1 → 3.2.0-middleware.2
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/dist/cjs/lib/inference.d.ts +3 -1
- package/dist/cjs/lib/inference.js +3 -3
- package/dist/cjs/lib/inference.js.map +1 -1
- package/dist/cjs/lib/prompt.d.ts +1 -1
- package/dist/cjs/lib/prompt.js +24 -18
- package/dist/cjs/lib/prompt.js.map +1 -1
- package/dist/cjs/lib/v3/agent/OpenAICUAClient.d.ts +6 -2
- package/dist/cjs/lib/v3/agent/OpenAICUAClient.js +40 -10
- package/dist/cjs/lib/v3/agent/OpenAICUAClient.js.map +1 -1
- package/dist/cjs/lib/v3/agent/prompts/agentSystemPrompt.js +4 -5
- package/dist/cjs/lib/v3/agent/prompts/agentSystemPrompt.js.map +1 -1
- package/dist/cjs/lib/v3/agent/tools/fillform.js +2 -2
- package/dist/cjs/lib/v3/agent/tools/fillform.js.map +1 -1
- package/dist/cjs/lib/v3/agent/utils/variables.d.ts +5 -0
- package/dist/cjs/lib/v3/agent/utils/variables.js +9 -0
- package/dist/cjs/lib/v3/agent/utils/variables.js.map +1 -1
- package/dist/cjs/lib/v3/handlers/observeHandler.js +2 -1
- package/dist/cjs/lib/v3/handlers/observeHandler.js.map +1 -1
- package/dist/cjs/lib/v3/llm/LLMProvider.js +1 -0
- package/dist/cjs/lib/v3/llm/LLMProvider.js.map +1 -1
- package/dist/cjs/lib/v3/llm/aisdk.d.ts +3 -1
- package/dist/cjs/lib/v3/llm/aisdk.js +13 -11
- package/dist/cjs/lib/v3/llm/aisdk.js.map +1 -1
- package/dist/cjs/lib/v3/types/private/handlers.d.ts +1 -0
- package/dist/cjs/lib/v3/types/private/handlers.js.map +1 -1
- package/dist/cjs/lib/v3/types/public/api.d.ts +20 -7
- package/dist/cjs/lib/v3/types/public/api.js +33 -14
- package/dist/cjs/lib/v3/types/public/api.js.map +1 -1
- package/dist/cjs/lib/v3/types/public/methods.d.ts +1 -0
- package/dist/cjs/lib/v3/types/public/methods.js.map +1 -1
- package/dist/cjs/lib/v3/types/public/model.d.ts +2 -0
- package/dist/cjs/lib/v3/types/public/model.js.map +1 -1
- package/dist/cjs/lib/v3/types/public/variables.d.ts +7 -0
- package/dist/cjs/lib/v3/types/public/variables.js +22 -0
- package/dist/cjs/lib/v3/types/public/variables.js.map +1 -0
- package/dist/cjs/lib/v3/understudy/context.js +6 -2
- package/dist/cjs/lib/v3/understudy/context.js.map +1 -1
- package/dist/cjs/lib/v3/understudy/page.js +1 -1
- package/dist/cjs/lib/v3/understudy/page.js.map +1 -1
- package/dist/cjs/lib/v3/v3.js +9 -1
- package/dist/cjs/lib/v3/v3.js.map +1 -1
- package/dist/cjs/lib/version.d.ts +1 -1
- package/dist/cjs/lib/version.js +1 -1
- package/dist/cjs/lib/version.js.map +1 -1
- package/dist/cjs/tests/integration/chrome-newtab-page-tracking.spec.d.ts +1 -0
- package/dist/cjs/tests/integration/chrome-newtab-page-tracking.spec.js +56 -0
- package/dist/cjs/tests/integration/chrome-newtab-page-tracking.spec.js.map +1 -0
- package/dist/cjs/tests/unit/agent-execution-model.test.js +24 -2
- package/dist/cjs/tests/unit/agent-execution-model.test.js.map +1 -1
- package/dist/cjs/tests/unit/agent-system-prompt-variables.test.d.ts +1 -0
- package/dist/cjs/tests/unit/agent-system-prompt-variables.test.js +23 -0
- package/dist/cjs/tests/unit/agent-system-prompt-variables.test.js.map +1 -0
- package/dist/cjs/tests/unit/aisdk-reasoning-effort.test.d.ts +1 -0
- package/dist/cjs/tests/unit/aisdk-reasoning-effort.test.js +153 -0
- package/dist/cjs/tests/unit/aisdk-reasoning-effort.test.js.map +1 -0
- package/dist/cjs/tests/unit/api-client-observe-variables.test.d.ts +1 -0
- package/dist/cjs/tests/unit/api-client-observe-variables.test.js +86 -0
- package/dist/cjs/tests/unit/api-client-observe-variables.test.js.map +1 -0
- package/dist/cjs/tests/unit/api-variables-schema.test.d.ts +1 -0
- package/dist/cjs/tests/unit/api-variables-schema.test.js +37 -0
- package/dist/cjs/tests/unit/api-variables-schema.test.js.map +1 -0
- package/dist/cjs/tests/unit/prompt-observe-variables.test.d.ts +1 -0
- package/dist/cjs/tests/unit/prompt-observe-variables.test.js +19 -0
- package/dist/cjs/tests/unit/prompt-observe-variables.test.js.map +1 -0
- package/dist/cjs/tests/unit/public-api/public-types.test.js.map +1 -1
- package/dist/cjs/tests/unit/timeout-handlers.test.js +50 -0
- package/dist/cjs/tests/unit/timeout-handlers.test.js.map +1 -1
- package/dist/esm/lib/inference.d.ts +3 -1
- package/dist/esm/lib/inference.js +3 -3
- package/dist/esm/lib/inference.js.map +1 -1
- package/dist/esm/lib/prompt.d.ts +1 -1
- package/dist/esm/lib/prompt.js +24 -18
- package/dist/esm/lib/prompt.js.map +1 -1
- package/dist/esm/lib/v3/agent/OpenAICUAClient.d.ts +6 -2
- package/dist/esm/lib/v3/agent/OpenAICUAClient.js +40 -10
- package/dist/esm/lib/v3/agent/OpenAICUAClient.js.map +1 -1
- package/dist/esm/lib/v3/agent/prompts/agentSystemPrompt.js +4 -5
- package/dist/esm/lib/v3/agent/prompts/agentSystemPrompt.js.map +1 -1
- package/dist/esm/lib/v3/agent/tools/fillform.js +2 -2
- package/dist/esm/lib/v3/agent/tools/fillform.js.map +1 -1
- package/dist/esm/lib/v3/agent/utils/variables.d.ts +5 -0
- package/dist/esm/lib/v3/agent/utils/variables.js +8 -0
- package/dist/esm/lib/v3/agent/utils/variables.js.map +1 -1
- package/dist/esm/lib/v3/handlers/observeHandler.js +2 -1
- package/dist/esm/lib/v3/handlers/observeHandler.js.map +1 -1
- package/dist/esm/lib/v3/llm/LLMProvider.js +1 -0
- package/dist/esm/lib/v3/llm/LLMProvider.js.map +1 -1
- package/dist/esm/lib/v3/llm/aisdk.d.ts +3 -1
- package/dist/esm/lib/v3/llm/aisdk.js +13 -11
- package/dist/esm/lib/v3/llm/aisdk.js.map +1 -1
- package/dist/esm/lib/v3/types/private/handlers.d.ts +1 -0
- package/dist/esm/lib/v3/types/private/handlers.js.map +1 -1
- package/dist/esm/lib/v3/types/public/api.d.ts +20 -7
- package/dist/esm/lib/v3/types/public/api.js +28 -12
- package/dist/esm/lib/v3/types/public/api.js.map +1 -1
- package/dist/esm/lib/v3/types/public/methods.d.ts +1 -0
- package/dist/esm/lib/v3/types/public/methods.js.map +1 -1
- package/dist/esm/lib/v3/types/public/model.d.ts +2 -0
- package/dist/esm/lib/v3/types/public/model.js.map +1 -1
- package/dist/esm/lib/v3/types/public/variables.d.ts +7 -0
- package/dist/esm/lib/v3/types/public/variables.js +19 -0
- package/dist/esm/lib/v3/types/public/variables.js.map +1 -0
- package/dist/esm/lib/v3/understudy/context.js +6 -2
- package/dist/esm/lib/v3/understudy/context.js.map +1 -1
- package/dist/esm/lib/v3/understudy/page.js +1 -1
- package/dist/esm/lib/v3/understudy/page.js.map +1 -1
- package/dist/esm/lib/v3/v3.js +9 -1
- package/dist/esm/lib/v3/v3.js.map +1 -1
- package/dist/esm/lib/version.d.ts +1 -1
- package/dist/esm/lib/version.js +1 -1
- package/dist/esm/lib/version.js.map +1 -1
- package/dist/esm/tests/integration/chrome-newtab-page-tracking.spec.d.ts +1 -0
- package/dist/esm/tests/integration/chrome-newtab-page-tracking.spec.js +54 -0
- package/dist/esm/tests/integration/chrome-newtab-page-tracking.spec.js.map +1 -0
- package/dist/esm/tests/unit/agent-execution-model.test.js +24 -2
- package/dist/esm/tests/unit/agent-execution-model.test.js.map +1 -1
- package/dist/esm/tests/unit/agent-system-prompt-variables.test.d.ts +1 -0
- package/dist/esm/tests/unit/agent-system-prompt-variables.test.js +21 -0
- package/dist/esm/tests/unit/agent-system-prompt-variables.test.js.map +1 -0
- package/dist/esm/tests/unit/aisdk-reasoning-effort.test.d.ts +1 -0
- package/dist/esm/tests/unit/aisdk-reasoning-effort.test.js +118 -0
- package/dist/esm/tests/unit/aisdk-reasoning-effort.test.js.map +1 -0
- package/dist/esm/tests/unit/api-client-observe-variables.test.d.ts +1 -0
- package/dist/esm/tests/unit/api-client-observe-variables.test.js +84 -0
- package/dist/esm/tests/unit/api-client-observe-variables.test.js.map +1 -0
- package/dist/esm/tests/unit/api-variables-schema.test.d.ts +1 -0
- package/dist/esm/tests/unit/api-variables-schema.test.js +35 -0
- package/dist/esm/tests/unit/api-variables-schema.test.js.map +1 -0
- package/dist/esm/tests/unit/prompt-observe-variables.test.d.ts +1 -0
- package/dist/esm/tests/unit/prompt-observe-variables.test.js +17 -0
- package/dist/esm/tests/unit/prompt-observe-variables.test.js.map +1 -0
- package/dist/esm/tests/unit/public-api/public-types.test.js.map +1 -1
- package/dist/esm/tests/unit/timeout-handlers.test.js +50 -0
- package/dist/esm/tests/unit/timeout-handlers.test.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inference.js","sourceRoot":"","sources":["../../../lib/inference.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EACL,oBAAoB,EACpB,wBAAwB,EACxB,sBAAsB,EACtB,mBAAmB,EACnB,yBAAyB,EACzB,wBAAwB,EACxB,uBAAuB,GACxB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,aAAa,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAKhF,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAK3E,SAAS,cAAc,CAAI,OAAmB,EAAE,SAAiB;IAC/D,OAAO,WAAW,CAChB,OAAO,EACP,eAAe,CAAC,YAAY,CAAC,EAC7B,OAAO,SAAS,EAAE,CACnB,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,OAAO,CAA+B,EAC1D,WAAW,EACX,WAAW,EACX,MAAM,EACN,SAAS,EACT,MAAM,EACN,wBAAwB,EAC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od\";\nimport { LogLine } from \"./v3/types/public/logs.js\";\nimport { ChatMessage, LLMClient } from \"./v3/llm/LLMClient.js\";\nimport { getEnvTimeoutMs, withTimeout } from \"./v3/timeoutConfig.js\";\nimport {\n buildActSystemPrompt,\n buildExtractSystemPrompt,\n buildExtractUserPrompt,\n buildMetadataPrompt,\n buildMetadataSystemPrompt,\n buildObserveSystemPrompt,\n buildObserveUserMessage,\n} from \"./prompt.js\";\nimport { appendSummary, writeTimestampedTxtFile } from \"./inferenceLogUtils.js\";\nimport type {\n InferStagehandSchema,\n StagehandZodObject,\n} from \"./v3/zodCompat.js\";\nimport { SupportedUnderstudyAction } from \"./v3/types/private/handlers.js\";\n\n// Re-export for backward compatibility\nexport type { LLMParsedResponse, LLMUsage } from \"./v3/llm/LLMClient.js\";\n\nfunction withLlmTimeout<T>(promise: Promise<T>, operation: string): Promise<T> {\n return withTimeout(\n promise,\n getEnvTimeoutMs(\"LLM_MAX_MS\"),\n `LLM ${operation}`,\n );\n}\n\nexport async function extract<T extends StagehandZodObject>({\n instruction,\n domElements,\n schema,\n llmClient,\n logger,\n userProvidedInstructions,\n logInferenceToFile = false,\n}: {\n instruction: string;\n domElements: string;\n schema: T;\n llmClient: LLMClient;\n userProvidedInstructions?: string;\n logger: (message: LogLine) => void;\n logInferenceToFile?: boolean;\n}) {\n const metadataSchema = z.object({\n progress: z\n .string()\n .describe(\n \"progress of what has been extracted so far, as concise as possible\",\n ),\n completed: z\n .boolean()\n .describe(\n \"true if the goal is now accomplished. Use this conservatively, only when sure that the goal has been completed.\",\n ),\n });\n\n type ExtractionResponse = InferStagehandSchema<T>;\n type MetadataResponse = z.infer<typeof metadataSchema>;\n\n const isUsingAnthropic = llmClient.type === \"anthropic\";\n const isGPT5 = llmClient.modelName.includes(\"gpt-5\"); // TODO: remove this as we update support for gpt-5 configuration options\n\n const extractCallMessages: ChatMessage[] = [\n buildExtractSystemPrompt(isUsingAnthropic, userProvidedInstructions),\n buildExtractUserPrompt(instruction, domElements, isUsingAnthropic),\n ];\n\n let extractCallFile = \"\";\n let extractCallTimestamp = \"\";\n if (logInferenceToFile) {\n const { fileName, timestamp } = writeTimestampedTxtFile(\n \"extract_summary\",\n \"extract_call\",\n {\n modelCall: \"extract\",\n messages: extractCallMessages,\n },\n );\n extractCallFile = fileName;\n extractCallTimestamp = timestamp;\n }\n\n const extractStartTime = Date.now();\n const extractionResponse = await withLlmTimeout(\n llmClient.createChatCompletion<ExtractionResponse>({\n options: {\n messages: extractCallMessages,\n response_model: {\n schema,\n name: \"Extraction\",\n },\n temperature: isGPT5 ? 1 : 0.1,\n top_p: 1,\n frequency_penalty: 0,\n presence_penalty: 0,\n },\n logger,\n }),\n \"extract\",\n );\n const extractEndTime = Date.now();\n\n const { data: extractedData, usage: extractUsage } = extractionResponse;\n\n let extractResponseFile: string;\n if (logInferenceToFile) {\n const { fileName } = writeTimestampedTxtFile(\n \"extract_summary\",\n \"extract_response\",\n {\n modelResponse: \"extract\",\n rawResponse: extractedData,\n },\n );\n extractResponseFile = fileName;\n\n appendSummary(\"extract\", {\n extract_inference_type: \"extract\",\n timestamp: extractCallTimestamp,\n LLM_input_file: extractCallFile,\n LLM_output_file: extractResponseFile,\n prompt_tokens: extractUsage?.prompt_tokens ?? 0,\n completion_tokens: extractUsage?.completion_tokens ?? 0,\n reasoning_tokens: extractUsage?.reasoning_tokens ?? 0,\n cached_input_tokens: extractUsage?.cached_input_tokens ?? 0,\n inference_time_ms: extractEndTime - extractStartTime,\n });\n }\n\n const metadataCallMessages: ChatMessage[] = [\n buildMetadataSystemPrompt(),\n buildMetadataPrompt(instruction, extractedData),\n ];\n\n let metadataCallFile = \"\";\n let metadataCallTimestamp = \"\";\n if (logInferenceToFile) {\n const { fileName, timestamp } = writeTimestampedTxtFile(\n \"extract_summary\",\n \"metadata_call\",\n {\n modelCall: \"metadata\",\n messages: metadataCallMessages,\n },\n );\n metadataCallFile = fileName;\n metadataCallTimestamp = timestamp;\n }\n\n const metadataStartTime = Date.now();\n const metadataResponse = await withLlmTimeout(\n llmClient.createChatCompletion<MetadataResponse>({\n options: {\n messages: metadataCallMessages,\n response_model: {\n name: \"Metadata\",\n schema: metadataSchema,\n },\n temperature: isGPT5 ? 1 : 0.1,\n top_p: 1,\n frequency_penalty: 0,\n presence_penalty: 0,\n },\n logger,\n }),\n \"extract metadata\",\n );\n const metadataEndTime = Date.now();\n\n const {\n data: {\n completed: metadataResponseCompleted,\n progress: metadataResponseProgress,\n },\n usage: metadataResponseUsage,\n } = metadataResponse;\n\n let metadataResponseFile: string;\n if (logInferenceToFile) {\n const { fileName } = writeTimestampedTxtFile(\n \"extract_summary\",\n \"metadata_response\",\n {\n modelResponse: \"metadata\",\n completed: metadataResponseCompleted,\n progress: metadataResponseProgress,\n },\n );\n metadataResponseFile = fileName;\n\n appendSummary(\"extract\", {\n extract_inference_type: \"metadata\",\n timestamp: metadataCallTimestamp,\n LLM_input_file: metadataCallFile,\n LLM_output_file: metadataResponseFile,\n prompt_tokens: metadataResponseUsage?.prompt_tokens ?? 0,\n completion_tokens: metadataResponseUsage?.completion_tokens ?? 0,\n reasoning_tokens: metadataResponseUsage?.reasoning_tokens ?? 0,\n cached_input_tokens: metadataResponseUsage?.cached_input_tokens ?? 0,\n inference_time_ms: metadataEndTime - metadataStartTime,\n });\n }\n\n const totalPromptTokens =\n (extractUsage?.prompt_tokens ?? 0) +\n (metadataResponseUsage?.prompt_tokens ?? 0);\n\n const totalCompletionTokens =\n (extractUsage?.completion_tokens ?? 0) +\n (metadataResponseUsage?.completion_tokens ?? 0);\n\n const totalInferenceTimeMs =\n extractEndTime - extractStartTime + (metadataEndTime - metadataStartTime);\n const totalReasoningTokens =\n (extractUsage?.reasoning_tokens ?? 0) +\n (metadataResponseUsage?.reasoning_tokens ?? 0);\n const totalCachedInputTokens =\n (extractUsage?.cached_input_tokens ?? 0) +\n (metadataResponseUsage?.cached_input_tokens ?? 0);\n\n return {\n ...extractedData,\n metadata: {\n completed: metadataResponseCompleted,\n progress: metadataResponseProgress,\n },\n prompt_tokens: totalPromptTokens,\n completion_tokens: totalCompletionTokens,\n reasoning_tokens: totalReasoningTokens,\n cached_input_tokens: totalCachedInputTokens,\n inference_time_ms: totalInferenceTimeMs,\n };\n}\n\nexport async function observe({\n instruction,\n domElements,\n llmClient,\n userProvidedInstructions,\n logger,\n logInferenceToFile = false,\n supportedActions,\n}: {\n instruction: string;\n domElements: string;\n llmClient: LLMClient;\n userProvidedInstructions?: string;\n logger: (message: LogLine) => void;\n logInferenceToFile?: boolean;\n supportedActions?: string[];\n}) {\n const isGPT5 = llmClient.modelName.includes(\"gpt-5\"); // TODO: remove this as we update support for gpt-5 configuration options\n\n const observeSchema = z.object({\n elements: z\n .array(\n z.object({\n elementId: z\n .string()\n .regex(/^\\d+-\\d+$/)\n .describe(\n \"the ID string associated with the element. Never include surrounding square brackets. This field must follow the format of 'number-number'.\",\n ),\n description: z\n .string()\n .describe(\n \"a description of the accessible element and its purpose\",\n ),\n method: z\n .enum(\n // Use Object.values() for Zod v3 compatibility - z.enum() in v3 doesn't accept TypeScript enums directly\n Object.values(SupportedUnderstudyAction) as unknown as readonly [\n string,\n ...string[],\n ],\n )\n .describe(\n `the candidate method/action to interact with the element. Select one of the available Understudy interaction methods.`,\n ),\n arguments: z.array(\n z\n .string()\n .describe(\n \"the arguments to pass to the method. For example, for a click, the arguments are empty, but for a fill, the arguments are the value to fill in.\",\n ),\n ),\n }),\n )\n .describe(\"an array of accessible elements that match the instruction\"),\n });\n\n type ObserveResponse = z.infer<typeof observeSchema>;\n\n const messages: ChatMessage[] = [\n buildObserveSystemPrompt(userProvidedInstructions, supportedActions),\n buildObserveUserMessage(instruction, domElements),\n ];\n\n let callTimestamp = \"\";\n let callFile = \"\";\n if (logInferenceToFile) {\n const { fileName, timestamp } = writeTimestampedTxtFile(\n `observe_summary`,\n `observe_call`,\n {\n modelCall: \"observe\",\n messages,\n },\n );\n callFile = fileName;\n callTimestamp = timestamp;\n }\n\n const start = Date.now();\n const rawResponse = await llmClient.createChatCompletion<ObserveResponse>({\n options: {\n messages,\n response_model: {\n schema: observeSchema,\n name: \"Observation\",\n },\n temperature: isGPT5 ? 1 : 0.1,\n top_p: 1,\n frequency_penalty: 0,\n presence_penalty: 0,\n },\n logger,\n });\n const end = Date.now();\n const usageTimeMs = end - start;\n\n const { data: observeData, usage: observeUsage } = rawResponse;\n const promptTokens = observeUsage?.prompt_tokens ?? 0;\n const completionTokens = observeUsage?.completion_tokens ?? 0;\n const reasoningTokens = observeUsage?.reasoning_tokens ?? 0;\n const cachedInputTokens = observeUsage?.cached_input_tokens ?? 0;\n\n let responseFile: string;\n if (logInferenceToFile) {\n const { fileName: responseFileName } = writeTimestampedTxtFile(\n `observe_summary`,\n `observe_response`,\n {\n modelResponse: \"observe\",\n rawResponse: observeData,\n },\n );\n responseFile = responseFileName;\n\n appendSummary(\"observe\", {\n [`observe_inference_type`]: \"observe\",\n timestamp: callTimestamp,\n LLM_input_file: callFile,\n LLM_output_file: responseFile,\n prompt_tokens: promptTokens,\n completion_tokens: completionTokens,\n reasoning_tokens: reasoningTokens,\n cached_input_tokens: cachedInputTokens,\n inference_time_ms: usageTimeMs,\n });\n }\n\n const parsedElements =\n observeData.elements?.map((el) => {\n const base = {\n elementId: el.elementId,\n description: String(el.description),\n method: String(el.method),\n arguments: el.arguments,\n };\n return base;\n }) ?? [];\n\n return {\n elements: parsedElements,\n prompt_tokens: promptTokens,\n completion_tokens: completionTokens,\n reasoning_tokens: reasoningTokens,\n cached_input_tokens: cachedInputTokens,\n inference_time_ms: usageTimeMs,\n };\n}\n\nexport async function act({\n instruction,\n domElements,\n llmClient,\n userProvidedInstructions,\n logger,\n logInferenceToFile = false,\n}: {\n instruction: string;\n domElements: string;\n llmClient: LLMClient;\n userProvidedInstructions?: string;\n logger: (message: LogLine) => void;\n logInferenceToFile?: boolean;\n}) {\n const isGPT5 = llmClient.modelName.includes(\"gpt-5\"); // TODO: remove this as we update support for gpt-5 configuration options\n\n const actSchema = z.object({\n elementId: z\n .string()\n .regex(/^\\d+-\\d+$/)\n .describe(\n \"the ID string associated with the element. Never include surrounding square brackets. This field must follow the format of 'number-number'.\",\n ),\n description: z\n .string()\n .describe(\"a description of the accessible element and its purpose\"),\n method: z\n .enum(\n // Use Object.values() for Zod v3 compatibility - z.enum() in v3 doesn't accept TypeScript enums directly\n Object.values(SupportedUnderstudyAction) as unknown as readonly [\n string,\n ...string[],\n ],\n )\n .describe(\n \"the candidate method/action to interact with the element. Select one of the available Understudy interaction methods.\",\n ),\n arguments: z.array(\n z\n .string()\n .describe(\n \"the arguments to pass to the method. For example, for a click, the arguments are empty, but for a fill, the arguments are the value to fill in.\",\n ),\n ),\n twoStep: z.boolean(),\n });\n\n type ActResponse = z.infer<typeof actSchema>;\n\n const messages: ChatMessage[] = [\n buildActSystemPrompt(userProvidedInstructions),\n buildObserveUserMessage(instruction, domElements),\n ];\n\n let callTimestamp = \"\";\n let callFile = \"\";\n if (logInferenceToFile) {\n const { fileName, timestamp } = writeTimestampedTxtFile(\n `act_summary`,\n `act_call`,\n {\n modelCall: \"act\",\n messages,\n },\n );\n callFile = fileName;\n callTimestamp = timestamp;\n }\n\n const start = Date.now();\n const rawResponse = await llmClient.createChatCompletion<ActResponse>({\n options: {\n messages,\n response_model: {\n schema: actSchema,\n name: \"act\",\n },\n temperature: isGPT5 ? 1 : 0.1,\n top_p: 1,\n frequency_penalty: 0,\n presence_penalty: 0,\n },\n logger,\n });\n const end = Date.now();\n const usageTimeMs = end - start;\n\n const { data: actData, usage: actUsage } = rawResponse;\n const promptTokens = actUsage?.prompt_tokens ?? 0;\n const completionTokens = actUsage?.completion_tokens ?? 0;\n const reasoningTokens = actUsage?.reasoning_tokens ?? 0;\n const cachedInputTokens = actUsage?.cached_input_tokens ?? 0;\n\n let responseFile: string;\n if (logInferenceToFile) {\n const { fileName: responseFileName } = writeTimestampedTxtFile(\n `act_summary`,\n `act_response`,\n {\n modelResponse: \"act\",\n rawResponse: actData,\n },\n );\n responseFile = responseFileName;\n\n appendSummary(\"act\", {\n [`act_inference_type`]: \"act\",\n timestamp: callTimestamp,\n LLM_input_file: callFile,\n LLM_output_file: responseFile,\n prompt_tokens: promptTokens,\n completion_tokens: completionTokens,\n reasoning_tokens: reasoningTokens,\n cached_input_tokens: cachedInputTokens,\n inference_time_ms: usageTimeMs,\n });\n }\n\n const parsedElement = {\n elementId: actData.elementId,\n description: String(actData.description),\n method: String(actData.method),\n arguments: actData.arguments,\n };\n\n return {\n element: parsedElement,\n prompt_tokens: promptTokens,\n completion_tokens: completionTokens,\n reasoning_tokens: reasoningTokens,\n cached_input_tokens: cachedInputTokens,\n inference_time_ms: usageTimeMs,\n twoStep: actData.twoStep,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"inference.js","sourceRoot":"","sources":["../../../lib/inference.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EACL,oBAAoB,EACpB,wBAAwB,EACxB,sBAAsB,EACtB,mBAAmB,EACnB,yBAAyB,EACzB,wBAAwB,EACxB,uBAAuB,GACxB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,aAAa,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAKhF,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAM3E,SAAS,cAAc,CAAI,OAAmB,EAAE,SAAiB;IAC/D,OAAO,WAAW,CAChB,OAAO,EACP,eAAe,CAAC,YAAY,CAAC,EAC7B,OAAO,SAAS,EAAE,CACnB,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,OAAO,CAA+B,EAC1D,WAAW,EACX,WAAW,EACX,MAAM,EACN,SAAS,EACT,MAAM,EACN,wBAAwB,EACxB,kBAAkB,GAAG,KAAK,GAS3B;IACC,MAAM,cAAc,GAAG,CAAC,CAAC,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atMessage, LLMClient } from \"./v3/llm/LLMClient.js\";\nimport { getEnvTimeoutMs, withTimeout } from \"./v3/timeoutConfig.js\";\nimport {\n buildActSystemPrompt,\n buildExtractSystemPrompt,\n buildExtractUserPrompt,\n buildMetadataPrompt,\n buildMetadataSystemPrompt,\n buildObserveSystemPrompt,\n buildObserveUserMessage,\n} from \"./prompt.js\";\nimport { appendSummary, writeTimestampedTxtFile } from \"./inferenceLogUtils.js\";\nimport type {\n InferStagehandSchema,\n StagehandZodObject,\n} from \"./v3/zodCompat.js\";\nimport { SupportedUnderstudyAction } from \"./v3/types/private/handlers.js\";\nimport type { Variables } from \"./v3/types/public/agent.js\";\n\n// Re-export for backward compatibility\nexport type { LLMParsedResponse, LLMUsage } from \"./v3/llm/LLMClient.js\";\n\nfunction withLlmTimeout<T>(promise: Promise<T>, operation: string): Promise<T> {\n return withTimeout(\n promise,\n getEnvTimeoutMs(\"LLM_MAX_MS\"),\n `LLM ${operation}`,\n );\n}\n\nexport async function extract<T extends StagehandZodObject>({\n instruction,\n domElements,\n schema,\n llmClient,\n logger,\n userProvidedInstructions,\n logInferenceToFile = false,\n}: {\n instruction: string;\n domElements: string;\n schema: T;\n llmClient: LLMClient;\n userProvidedInstructions?: string;\n logger: (message: LogLine) => void;\n logInferenceToFile?: boolean;\n}) {\n const metadataSchema = z.object({\n progress: z\n .string()\n .describe(\n \"progress of what has been extracted so far, as concise as possible\",\n ),\n completed: z\n .boolean()\n .describe(\n \"true if the goal is now accomplished. Use this conservatively, only when sure that the goal has been completed.\",\n ),\n });\n\n type ExtractionResponse = InferStagehandSchema<T>;\n type MetadataResponse = z.infer<typeof metadataSchema>;\n\n const isUsingAnthropic = llmClient.type === \"anthropic\";\n const isGPT5 = llmClient.modelName.includes(\"gpt-5\"); // TODO: remove this as we update support for gpt-5 configuration options\n\n const extractCallMessages: ChatMessage[] = [\n buildExtractSystemPrompt(isUsingAnthropic, userProvidedInstructions),\n buildExtractUserPrompt(instruction, domElements, isUsingAnthropic),\n ];\n\n let extractCallFile = \"\";\n let extractCallTimestamp = \"\";\n if (logInferenceToFile) {\n const { fileName, timestamp } = writeTimestampedTxtFile(\n \"extract_summary\",\n \"extract_call\",\n {\n modelCall: \"extract\",\n messages: extractCallMessages,\n },\n );\n extractCallFile = fileName;\n extractCallTimestamp = timestamp;\n }\n\n const extractStartTime = Date.now();\n const extractionResponse = await withLlmTimeout(\n llmClient.createChatCompletion<ExtractionResponse>({\n options: {\n messages: extractCallMessages,\n response_model: {\n schema,\n name: \"Extraction\",\n },\n temperature: isGPT5 ? 1 : 0.1,\n top_p: 1,\n frequency_penalty: 0,\n presence_penalty: 0,\n },\n logger,\n }),\n \"extract\",\n );\n const extractEndTime = Date.now();\n\n const { data: extractedData, usage: extractUsage } = extractionResponse;\n\n let extractResponseFile: string;\n if (logInferenceToFile) {\n const { fileName } = writeTimestampedTxtFile(\n \"extract_summary\",\n \"extract_response\",\n {\n modelResponse: \"extract\",\n rawResponse: extractedData,\n },\n );\n extractResponseFile = fileName;\n\n appendSummary(\"extract\", {\n extract_inference_type: \"extract\",\n timestamp: extractCallTimestamp,\n LLM_input_file: extractCallFile,\n LLM_output_file: extractResponseFile,\n prompt_tokens: extractUsage?.prompt_tokens ?? 0,\n completion_tokens: extractUsage?.completion_tokens ?? 0,\n reasoning_tokens: extractUsage?.reasoning_tokens ?? 0,\n cached_input_tokens: extractUsage?.cached_input_tokens ?? 0,\n inference_time_ms: extractEndTime - extractStartTime,\n });\n }\n\n const metadataCallMessages: ChatMessage[] = [\n buildMetadataSystemPrompt(),\n buildMetadataPrompt(instruction, extractedData),\n ];\n\n let metadataCallFile = \"\";\n let metadataCallTimestamp = \"\";\n if (logInferenceToFile) {\n const { fileName, timestamp } = writeTimestampedTxtFile(\n \"extract_summary\",\n \"metadata_call\",\n {\n modelCall: \"metadata\",\n messages: metadataCallMessages,\n },\n );\n metadataCallFile = fileName;\n metadataCallTimestamp = timestamp;\n }\n\n const metadataStartTime = Date.now();\n const metadataResponse = await withLlmTimeout(\n llmClient.createChatCompletion<MetadataResponse>({\n options: {\n messages: metadataCallMessages,\n response_model: {\n name: \"Metadata\",\n schema: metadataSchema,\n },\n temperature: isGPT5 ? 1 : 0.1,\n top_p: 1,\n frequency_penalty: 0,\n presence_penalty: 0,\n },\n logger,\n }),\n \"extract metadata\",\n );\n const metadataEndTime = Date.now();\n\n const {\n data: {\n completed: metadataResponseCompleted,\n progress: metadataResponseProgress,\n },\n usage: metadataResponseUsage,\n } = metadataResponse;\n\n let metadataResponseFile: string;\n if (logInferenceToFile) {\n const { fileName } = writeTimestampedTxtFile(\n \"extract_summary\",\n \"metadata_response\",\n {\n modelResponse: \"metadata\",\n completed: metadataResponseCompleted,\n progress: metadataResponseProgress,\n },\n );\n metadataResponseFile = fileName;\n\n appendSummary(\"extract\", {\n extract_inference_type: \"metadata\",\n timestamp: metadataCallTimestamp,\n LLM_input_file: metadataCallFile,\n LLM_output_file: metadataResponseFile,\n prompt_tokens: metadataResponseUsage?.prompt_tokens ?? 0,\n completion_tokens: metadataResponseUsage?.completion_tokens ?? 0,\n reasoning_tokens: metadataResponseUsage?.reasoning_tokens ?? 0,\n cached_input_tokens: metadataResponseUsage?.cached_input_tokens ?? 0,\n inference_time_ms: metadataEndTime - metadataStartTime,\n });\n }\n\n const totalPromptTokens =\n (extractUsage?.prompt_tokens ?? 0) +\n (metadataResponseUsage?.prompt_tokens ?? 0);\n\n const totalCompletionTokens =\n (extractUsage?.completion_tokens ?? 0) +\n (metadataResponseUsage?.completion_tokens ?? 0);\n\n const totalInferenceTimeMs =\n extractEndTime - extractStartTime + (metadataEndTime - metadataStartTime);\n const totalReasoningTokens =\n (extractUsage?.reasoning_tokens ?? 0) +\n (metadataResponseUsage?.reasoning_tokens ?? 0);\n const totalCachedInputTokens =\n (extractUsage?.cached_input_tokens ?? 0) +\n (metadataResponseUsage?.cached_input_tokens ?? 0);\n\n return {\n ...extractedData,\n metadata: {\n completed: metadataResponseCompleted,\n progress: metadataResponseProgress,\n },\n prompt_tokens: totalPromptTokens,\n completion_tokens: totalCompletionTokens,\n reasoning_tokens: totalReasoningTokens,\n cached_input_tokens: totalCachedInputTokens,\n inference_time_ms: totalInferenceTimeMs,\n };\n}\n\nexport async function observe({\n instruction,\n domElements,\n llmClient,\n userProvidedInstructions,\n logger,\n logInferenceToFile = false,\n supportedActions,\n variables,\n}: {\n instruction: string;\n domElements: string;\n llmClient: LLMClient;\n userProvidedInstructions?: string;\n logger: (message: LogLine) => void;\n logInferenceToFile?: boolean;\n supportedActions?: string[];\n variables?: Variables;\n}) {\n const isGPT5 = llmClient.modelName.includes(\"gpt-5\"); // TODO: remove this as we update support for gpt-5 configuration options\n\n const observeSchema = z.object({\n elements: z\n .array(\n z.object({\n elementId: z\n .string()\n .regex(/^\\d+-\\d+$/)\n .describe(\n \"the ID string associated with the element. Never include surrounding square brackets. This field must follow the format of 'number-number'.\",\n ),\n description: z\n .string()\n .describe(\n \"a description of the accessible element and its purpose\",\n ),\n method: z\n .enum(\n // Use Object.values() for Zod v3 compatibility - z.enum() in v3 doesn't accept TypeScript enums directly\n Object.values(SupportedUnderstudyAction) as unknown as readonly [\n string,\n ...string[],\n ],\n )\n .describe(\n `the candidate method/action to interact with the element. Select one of the available Understudy interaction methods.`,\n ),\n arguments: z.array(\n z\n .string()\n .describe(\n \"the arguments to pass to the method. For example, for a click, the arguments are empty, but for a fill, the arguments are the value to fill in.\",\n ),\n ),\n }),\n )\n .describe(\"an array of accessible elements that match the instruction\"),\n });\n\n type ObserveResponse = z.infer<typeof observeSchema>;\n\n const messages: ChatMessage[] = [\n buildObserveSystemPrompt(\n userProvidedInstructions,\n supportedActions,\n variables,\n ),\n buildObserveUserMessage(instruction, domElements),\n ];\n\n let callTimestamp = \"\";\n let callFile = \"\";\n if (logInferenceToFile) {\n const { fileName, timestamp } = writeTimestampedTxtFile(\n `observe_summary`,\n `observe_call`,\n {\n modelCall: \"observe\",\n messages,\n },\n );\n callFile = fileName;\n callTimestamp = timestamp;\n }\n\n const start = Date.now();\n const rawResponse = await llmClient.createChatCompletion<ObserveResponse>({\n options: {\n messages,\n response_model: {\n schema: observeSchema,\n name: \"Observation\",\n },\n temperature: isGPT5 ? 1 : 0.1,\n top_p: 1,\n frequency_penalty: 0,\n presence_penalty: 0,\n },\n logger,\n });\n const end = Date.now();\n const usageTimeMs = end - start;\n\n const { data: observeData, usage: observeUsage } = rawResponse;\n const promptTokens = observeUsage?.prompt_tokens ?? 0;\n const completionTokens = observeUsage?.completion_tokens ?? 0;\n const reasoningTokens = observeUsage?.reasoning_tokens ?? 0;\n const cachedInputTokens = observeUsage?.cached_input_tokens ?? 0;\n\n let responseFile: string;\n if (logInferenceToFile) {\n const { fileName: responseFileName } = writeTimestampedTxtFile(\n `observe_summary`,\n `observe_response`,\n {\n modelResponse: \"observe\",\n rawResponse: observeData,\n },\n );\n responseFile = responseFileName;\n\n appendSummary(\"observe\", {\n [`observe_inference_type`]: \"observe\",\n timestamp: callTimestamp,\n LLM_input_file: callFile,\n LLM_output_file: responseFile,\n prompt_tokens: promptTokens,\n completion_tokens: completionTokens,\n reasoning_tokens: reasoningTokens,\n cached_input_tokens: cachedInputTokens,\n inference_time_ms: usageTimeMs,\n });\n }\n\n const parsedElements =\n observeData.elements?.map((el) => {\n const base = {\n elementId: el.elementId,\n description: String(el.description),\n method: String(el.method),\n arguments: el.arguments,\n };\n return base;\n }) ?? [];\n\n return {\n elements: parsedElements,\n prompt_tokens: promptTokens,\n completion_tokens: completionTokens,\n reasoning_tokens: reasoningTokens,\n cached_input_tokens: cachedInputTokens,\n inference_time_ms: usageTimeMs,\n };\n}\n\nexport async function act({\n instruction,\n domElements,\n llmClient,\n userProvidedInstructions,\n logger,\n logInferenceToFile = false,\n}: {\n instruction: string;\n domElements: string;\n llmClient: LLMClient;\n userProvidedInstructions?: string;\n logger: (message: LogLine) => void;\n logInferenceToFile?: boolean;\n}) {\n const isGPT5 = llmClient.modelName.includes(\"gpt-5\"); // TODO: remove this as we update support for gpt-5 configuration options\n\n const actSchema = z.object({\n elementId: z\n .string()\n .regex(/^\\d+-\\d+$/)\n .describe(\n \"the ID string associated with the element. Never include surrounding square brackets. This field must follow the format of 'number-number'. for example, '0-76' or '16-21'\",\n ),\n description: z\n .string()\n .describe(\"a description of the accessible element and its purpose\"),\n method: z\n .enum(\n // Use Object.values() for Zod v3 compatibility - z.enum() in v3 doesn't accept TypeScript enums directly\n Object.values(SupportedUnderstudyAction) as unknown as readonly [\n string,\n ...string[],\n ],\n )\n .describe(\n \"the candidate method/action to interact with the element. Select one of the available Understudy interaction methods.\",\n ),\n arguments: z.array(\n z\n .string()\n .describe(\n \"the arguments to pass to the method. For example, for a click, the arguments are empty, but for a fill, the arguments are the value to fill in.\",\n ),\n ),\n twoStep: z.boolean(),\n });\n\n type ActResponse = z.infer<typeof actSchema>;\n\n const messages: ChatMessage[] = [\n buildActSystemPrompt(userProvidedInstructions),\n buildObserveUserMessage(instruction, domElements),\n ];\n\n let callTimestamp = \"\";\n let callFile = \"\";\n if (logInferenceToFile) {\n const { fileName, timestamp } = writeTimestampedTxtFile(\n `act_summary`,\n `act_call`,\n {\n modelCall: \"act\",\n messages,\n },\n );\n callFile = fileName;\n callTimestamp = timestamp;\n }\n\n const start = Date.now();\n const rawResponse = await llmClient.createChatCompletion<ActResponse>({\n options: {\n messages,\n response_model: {\n schema: actSchema,\n name: \"act\",\n },\n temperature: isGPT5 ? 1 : 0.1,\n top_p: 1,\n frequency_penalty: 0,\n presence_penalty: 0,\n },\n logger,\n });\n const end = Date.now();\n const usageTimeMs = end - start;\n\n const { data: actData, usage: actUsage } = rawResponse;\n const promptTokens = actUsage?.prompt_tokens ?? 0;\n const completionTokens = actUsage?.completion_tokens ?? 0;\n const reasoningTokens = actUsage?.reasoning_tokens ?? 0;\n const cachedInputTokens = actUsage?.cached_input_tokens ?? 0;\n\n let responseFile: string;\n if (logInferenceToFile) {\n const { fileName: responseFileName } = writeTimestampedTxtFile(\n `act_summary`,\n `act_response`,\n {\n modelResponse: \"act\",\n rawResponse: actData,\n },\n );\n responseFile = responseFileName;\n\n appendSummary(\"act\", {\n [`act_inference_type`]: \"act\",\n timestamp: callTimestamp,\n LLM_input_file: callFile,\n LLM_output_file: responseFile,\n prompt_tokens: promptTokens,\n completion_tokens: completionTokens,\n reasoning_tokens: reasoningTokens,\n cached_input_tokens: cachedInputTokens,\n inference_time_ms: usageTimeMs,\n });\n }\n\n const parsedElement = {\n elementId: actData.elementId,\n description: String(actData.description),\n method: String(actData.method),\n arguments: actData.arguments,\n };\n\n return {\n element: parsedElement,\n prompt_tokens: promptTokens,\n completion_tokens: completionTokens,\n reasoning_tokens: reasoningTokens,\n cached_input_tokens: cachedInputTokens,\n inference_time_ms: usageTimeMs,\n twoStep: actData.twoStep,\n };\n}\n"]}
|
package/dist/esm/lib/prompt.d.ts
CHANGED
|
@@ -5,7 +5,7 @@ export declare function buildExtractSystemPrompt(isUsingPrintExtractedDataTool?:
|
|
|
5
5
|
export declare function buildExtractUserPrompt(instruction: string, domElements: string, isUsingPrintExtractedDataTool?: boolean): ChatMessage;
|
|
6
6
|
export declare function buildMetadataSystemPrompt(): ChatMessage;
|
|
7
7
|
export declare function buildMetadataPrompt(instruction: string, extractionResponse: object): ChatMessage;
|
|
8
|
-
export declare function buildObserveSystemPrompt(userProvidedInstructions?: string, supportedActions?: string[]): ChatMessage;
|
|
8
|
+
export declare function buildObserveSystemPrompt(userProvidedInstructions?: string, supportedActions?: string[], variables?: Variables): ChatMessage;
|
|
9
9
|
export declare function buildObserveUserMessage(instruction: string, domElements: string): ChatMessage;
|
|
10
10
|
export declare function buildActSystemPrompt(userProvidedInstructions?: string): ChatMessage;
|
|
11
11
|
export declare function buildActPrompt(action: string, supportedActions: string[], variables?: Variables): string;
|
package/dist/esm/lib/prompt.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { getVariablePromptEntries } from "./v3/agent/utils/variables.js";
|
|
1
2
|
export function buildUserInstructionsString(userProvidedInstructions) {
|
|
2
3
|
if (!userProvidedInstructions) {
|
|
3
4
|
return "";
|
|
@@ -72,10 +73,18 @@ Extracted content: ${JSON.stringify(extractionResponse, null, 2)}`,
|
|
|
72
73
|
};
|
|
73
74
|
}
|
|
74
75
|
// observe
|
|
75
|
-
export function buildObserveSystemPrompt(userProvidedInstructions, supportedActions) {
|
|
76
|
+
export function buildObserveSystemPrompt(userProvidedInstructions, supportedActions, variables) {
|
|
76
77
|
const actionsString = supportedActions?.length
|
|
77
78
|
? `\n\nSupported actions: ${supportedActions.join(", ")}`
|
|
78
79
|
: "";
|
|
80
|
+
const variableEntries = getVariablePromptEntries(variables);
|
|
81
|
+
const variablesString = variableEntries.length
|
|
82
|
+
? `\n\nAvailable variables: ${variableEntries
|
|
83
|
+
.map(({ name, description }) => {
|
|
84
|
+
return description ? `%${name}% (${description})` : `%${name}%`;
|
|
85
|
+
})
|
|
86
|
+
.join(", ")}. When an action needs a dynamic or sensitive value, return the matching %variableName% placeholder in the action arguments instead of a literal value`
|
|
87
|
+
: "";
|
|
79
88
|
const observeSystemPrompt = `
|
|
80
89
|
You are helping the user automate the browser by finding elements based on what the user wants to observe in the page.
|
|
81
90
|
|
|
@@ -84,7 +93,7 @@ You will be given:
|
|
|
84
93
|
2. a hierarchical accessibility tree showing the semantic structure of the page. The tree is a hybrid of the DOM and the accessibility tree.
|
|
85
94
|
|
|
86
95
|
Return an array of elements that match the instruction if they exist, otherwise return an empty array.
|
|
87
|
-
When returning elements, include the appropriate method from the supported actions list.${actionsString}. When choosing non-left click actions, provide right or middle as the argument.`;
|
|
96
|
+
When returning elements, include the appropriate method from the supported actions list.${actionsString}${variablesString}. When choosing non-left click actions, provide right or middle as the argument.`;
|
|
88
97
|
const content = observeSystemPrompt.replace(/\s+/g, " ");
|
|
89
98
|
return {
|
|
90
99
|
role: "system",
|
|
@@ -117,6 +126,17 @@ Return the element that matches the instruction if it exists. Otherwise, return
|
|
|
117
126
|
.join("\n\n"),
|
|
118
127
|
};
|
|
119
128
|
}
|
|
129
|
+
function buildActVariablesPrompt(variables) {
|
|
130
|
+
if (!variables || Object.keys(variables).length === 0) {
|
|
131
|
+
return "";
|
|
132
|
+
}
|
|
133
|
+
const variableNames = Object.keys(variables)
|
|
134
|
+
.map((key) => `%${key}%`)
|
|
135
|
+
.join(", ");
|
|
136
|
+
return ` The user has provided the following variables to be used in the action: ${variableNames} \n
|
|
137
|
+
Note that these are the variable names/keys, and not the actual variable values. \n
|
|
138
|
+
To use the variables in the action, you must respond with the variable name inside the 'arguments' array. The variable name must be wrapped in percentage signs (eg, %variableNameHere%) so that it can be replaced with the actual variable value before the action is taken. \n`;
|
|
139
|
+
}
|
|
120
140
|
export function buildActPrompt(action, supportedActions, variables) {
|
|
121
141
|
// Base instruction
|
|
122
142
|
let instruction = `Find the most relevant element to perform an action on given the following action: ${action}.
|
|
@@ -144,14 +164,7 @@ export function buildActPrompt(action, supportedActions, variables) {
|
|
|
144
164
|
- choose the 'click' method
|
|
145
165
|
- set twoStep to true.
|
|
146
166
|
`;
|
|
147
|
-
|
|
148
|
-
if (variables && Object.keys(variables).length > 0) {
|
|
149
|
-
const variableNames = Object.keys(variables)
|
|
150
|
-
.map((key) => `%${key}%`)
|
|
151
|
-
.join(", ");
|
|
152
|
-
const variablesPrompt = `The following variables are available to use in the action: ${variableNames}. Fill the argument variables with the variable name.`;
|
|
153
|
-
instruction += ` ${variablesPrompt}`;
|
|
154
|
-
}
|
|
167
|
+
instruction += buildActVariablesPrompt(variables);
|
|
155
168
|
return instruction;
|
|
156
169
|
}
|
|
157
170
|
export function buildStepTwoPrompt(originalUserAction, previousAction, supportedActions, variables) {
|
|
@@ -170,14 +183,7 @@ export function buildStepTwoPrompt(originalUserAction, previousAction, supported
|
|
|
170
183
|
If the user is asking to scroll to the next chunk/previous chunk, choose the nextChunk/prevChunk method. No arguments are required here.
|
|
171
184
|
If the action implies a key press, e.g., 'press enter', 'press a', 'press space', etc., always choose the press method with the appropriate key as argument — e.g. 'a', 'Enter', 'Space'. Do not choose a click action on an on-screen keyboard. Capitalize the first character like 'Enter', 'Tab', 'Escape' only for special keys.
|
|
172
185
|
`;
|
|
173
|
-
|
|
174
|
-
if (variables && Object.keys(variables).length > 0) {
|
|
175
|
-
const variableNames = Object.keys(variables)
|
|
176
|
-
.map((key) => `%${key}%`)
|
|
177
|
-
.join(", ");
|
|
178
|
-
const variablesPrompt = `The following variables are available to use in the action: ${variableNames}. Fill the argument variables with the variable name.`;
|
|
179
|
-
instruction += ` ${variablesPrompt}`;
|
|
180
|
-
}
|
|
186
|
+
instruction += buildActVariablesPrompt(variables);
|
|
181
187
|
return instruction;
|
|
182
188
|
}
|
|
183
189
|
export function buildOperatorSystemPrompt(goal) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt.js","sourceRoot":"","sources":["../../../lib/prompt.ts"],"names":[],"mappings":"AAGA,MAAM,UAAU,2BAA2B,CACzC,wBAAiC;IAEjC,IAAI,CAAC,wBAAwB,EAAE,CAAC;QAC9B,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,OAAO;;;;;EAKP,wBAAwB,EAAE,CAAC;AAC7B,CAAC;AAED,UAAU;AACV,MAAM,UAAU,wBAAwB,CACtC,gCAAyC,KAAK,EAC9C,wBAAiC;IAEjC,MAAM,WAAW,GAAG;;;;;;IAMlB,CAAC;IAEH,MAAM,aAAa,GAAG,yCAAyC,CAAC;IAEhE,MAAM,YAAY,GAAG;;;GAGpB,CAAC,IAAI,EAAE,CAAC;IAET,MAAM,gBAAgB,GAAG,6BAA6B;QACpD,CAAC,CAAC;;;GAGH,CAAC,IAAI,EAAE;QACN,CAAC,CAAC,EAAE,CAAC;IAEP,MAAM,sBAAsB,GAC1B,+GAA+G;QAC/G,sFAAsF,CAAC;IAEzF,MAAM,gBAAgB,GAAG,2BAA2B,CAClD,wBAAwB,CACzB,CAAC;IAEF,MAAM,OAAO,GACX,GAAG,WAAW,GAAG,aAAa,OAAO,YAAY,KAAK,gBAAg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IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;;;CAGvD;KACE,CAAC;AACJ,CAAC","sourcesContent":["import { ChatMessage } from \"./v3/llm/LLMClient.js\";\nimport type { Variables } from \"./v3/types/public/agent.js\";\n\nexport function buildUserInstructionsString(\n userProvidedInstructions?: string,\n): string {\n if (!userProvidedInstructions) {\n return \"\";\n }\n\n return `\\n\\n# Custom Instructions Provided by the User\n \nPlease keep the user's instructions in mind when performing actions. If the user's instructions are not relevant to the current task, ignore them.\n\nUser Instructions:\n${userProvidedInstructions}`;\n}\n\n// extract\nexport function buildExtractSystemPrompt(\n isUsingPrintExtractedDataTool: boolean = false,\n userProvidedInstructions?: string,\n): ChatMessage {\n const baseContent = `You are extracting content on behalf of a user.\n If a user asks you to extract a 'list' of information, or 'all' information, \n YOU MUST EXTRACT ALL OF THE INFORMATION THAT THE USER REQUESTS.\n \n You will be given:\n1. An instruction\n2. `;\n\n const contentDetail = `A list of DOM elements to extract from.`;\n\n const instructions = `\nPrint the exact text from the DOM elements with all symbols, characters, and endlines as is.\nPrint null or an empty string if no new information is found.\n `.trim();\n\n const toolInstructions = isUsingPrintExtractedDataTool\n ? `\nONLY print the content using the print_extracted_data tool provided.\nONLY print the content using the print_extracted_data tool provided.\n `.trim()\n : \"\";\n\n const additionalInstructions =\n \"If a user is attempting to extract links or URLs, you MUST respond with ONLY the IDs of the link elements. \\n\" +\n \"Do not attempt to extract links directly from the text unless absolutely necessary. \";\n\n const userInstructions = buildUserInstructionsString(\n userProvidedInstructions,\n );\n\n const content =\n `${baseContent}${contentDetail}\\n\\n${instructions}\\n${toolInstructions}${\n additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\"\n }${userInstructions ? `\\n\\n${userInstructions}` : \"\"}`.replace(/\\s+/g, \" \");\n\n return {\n role: \"system\",\n content,\n };\n}\n\nexport function buildExtractUserPrompt(\n instruction: string,\n domElements: string,\n isUsingPrintExtractedDataTool: boolean = false,\n): ChatMessage {\n let content = `Instruction: ${instruction}\nDOM: ${domElements}`;\n\n if (isUsingPrintExtractedDataTool) {\n content += `\nONLY print the content using the print_extracted_data tool provided.\nONLY print the content using the print_extracted_data tool provided.`;\n }\n\n return {\n role: \"user\",\n content,\n };\n}\n\nconst metadataSystemPrompt = `You are an AI assistant tasked with evaluating the progress and completion status of an extraction task.\nAnalyze the extraction response and determine if the task is completed or if more information is needed.\nStrictly abide by the following criteria:\n1. Once the instruction has been satisfied by the current extraction response, ALWAYS set completion status to true and stop processing, regardless of remaining chunks.\n2. Only set completion status to false if BOTH of these conditions are true:\n - The instruction has not been satisfied yet\n - There are still chunks left to process (chunksTotal > chunksSeen)`;\n\nexport function buildMetadataSystemPrompt(): ChatMessage {\n return {\n role: \"system\",\n content: metadataSystemPrompt,\n };\n}\n\nexport function buildMetadataPrompt(\n instruction: string,\n extractionResponse: object,\n): ChatMessage {\n return {\n role: \"user\",\n content: `Instruction: ${instruction}\nExtracted content: ${JSON.stringify(extractionResponse, null, 2)}`,\n };\n}\n\n// observe\nexport function buildObserveSystemPrompt(\n userProvidedInstructions?: string,\n supportedActions?: string[],\n): ChatMessage {\n const actionsString = supportedActions?.length\n ? `\\n\\nSupported actions: ${supportedActions.join(\", \")}`\n : \"\";\n\n const observeSystemPrompt = `\nYou are helping the user automate the browser by finding elements based on what the user wants to observe in the page.\n\nYou will be given:\n1. a instruction of elements to observe\n2. a hierarchical accessibility tree showing the semantic structure of the page. The tree is a hybrid of the DOM and the accessibility tree.\n\nReturn an array of elements that match the instruction if they exist, otherwise return an empty array.\nWhen returning elements, include the appropriate method from the supported actions list.${actionsString}. When choosing non-left click actions, provide right or middle as the argument.`;\n const content = observeSystemPrompt.replace(/\\s+/g, \" \");\n\n return {\n role: \"system\",\n content: [content, buildUserInstructionsString(userProvidedInstructions)]\n .filter(Boolean)\n .join(\"\\n\\n\"),\n };\n}\n\nexport function buildObserveUserMessage(\n instruction: string,\n domElements: string,\n): ChatMessage {\n return {\n role: \"user\",\n content: `instruction: ${instruction}\nAccessibility Tree: \\n${domElements}\\n`,\n };\n}\n\nexport function buildActSystemPrompt(\n userProvidedInstructions?: string,\n): ChatMessage {\n const actSystemPrompt = `\nYou are helping the user automate the browser by finding elements based on what action the user wants to take on the page\n\nYou will be given:\n1. a user defined instruction about what action to take\n2. a hierarchical accessibility tree showing the semantic structure of the page. The tree is a hybrid of the DOM and the accessibility tree.\n\nReturn the element that matches the instruction if it exists. Otherwise, return an empty object.`;\n const content = actSystemPrompt.replace(/\\s+/g, \" \");\n\n return {\n role: \"system\",\n content: [content, buildUserInstructionsString(userProvidedInstructions)]\n .filter(Boolean)\n .join(\"\\n\\n\"),\n };\n}\n\nexport function buildActPrompt(\n action: string,\n supportedActions: string[],\n variables?: Variables,\n): string {\n // Base instruction\n let instruction = `Find the most relevant element to perform an action on given the following action: ${action}. \n IF AND ONLY IF the action EXPLICITLY includes the word 'dropdown' and implies choosing/selecting an option from a dropdown, ignore the 'General Instructions' section, and follow the 'Dropdown Specific Instructions' section carefully.\n \n General Instructions: \n Provide an action for this element such as ${supportedActions.join(\", \")}. Remember that to users, buttons and links look the same in most cases.\n When choosing non-left click actions, provide right or middle as the argument\n If the action is completely unrelated to a potential action to be taken on the page, return an empty object. \n ONLY return one action. If multiple actions are relevant, return the most relevant one. \n If the user is asking to scroll to a position on the page, e.g., 'halfway' or 0.75, etc, you must return the argument formatted as the correct percentage, e.g., '50%' or '75%', etc.\n If the user is asking to scroll to the next chunk/previous chunk, choose the nextChunk/prevChunk method. No arguments are required here.\n If the action implies a key press, e.g., 'press enter', 'press a', 'press space', etc., always choose the press method with the appropriate key as argument — e.g. 'a', 'Enter', 'Space'. Do not choose a click action on an on-screen keyboard. Capitalize the first character like 'Enter', 'Tab', 'Escape' only for special keys. \n \n Dropdown Specific Instructions:\n For interacting with dropdowns, there are two specific cases that you need to handle. \n \n CASE 1: the element is a 'select' element. \n - choose the selectOptionFromDropdown method,\n - set the argument to the exact text of the option that should be selected,\n - set twoStep to false.\n CASE 2: the element is NOT a 'select' element:\n - do not attempt to directly choose the element from the dropdown. You will need to click to expand the dropdown first. You will achieve this by following these instructions:\n - choose the node that most closely corresponds to the given instruction EVEN if it is a 'StaticText' element, or otherwise does not appear to be interactable. \n - choose the 'click' method\n - set twoStep to true.\n `;\n\n // Add variable names (not values) to the instruction if any\n if (variables && Object.keys(variables).length > 0) {\n const variableNames = Object.keys(variables)\n .map((key) => `%${key}%`)\n .join(\", \");\n const variablesPrompt = `The following variables are available to use in the action: ${variableNames}. Fill the argument variables with the variable name.`;\n instruction += ` ${variablesPrompt}`;\n }\n\n return instruction;\n}\n\nexport function buildStepTwoPrompt(\n originalUserAction: string,\n previousAction: string,\n supportedActions: string[],\n variables?: Variables,\n): string {\n // Base instruction\n let instruction = `\n The original user action was: ${originalUserAction}.\n You have just taken the following action which completed step 1 of 2: ${previousAction}.\n \n Now, you must find the most relevant element to perform an action on in order to complete step 2 of 2. \n \n General Instructions: \n Provide an action for this element such as ${supportedActions.join(\", \")}. Remember that to users, buttons and links look the same in most cases.\n If the action is completely unrelated to a potential action to be taken on the page, return an empty object. \n ONLY return one action. If multiple actions are relevant, return the most relevant one. \n If the user is asking to scroll to a position on the page, e.g., 'halfway' or 0.75, etc, you must return the argument formatted as the correct percentage, e.g., '50%' or '75%', etc.\n If the user is asking to scroll to the next chunk/previous chunk, choose the nextChunk/prevChunk method. No arguments are required here.\n If the action implies a key press, e.g., 'press enter', 'press a', 'press space', etc., always choose the press method with the appropriate key as argument — e.g. 'a', 'Enter', 'Space'. Do not choose a click action on an on-screen keyboard. Capitalize the first character like 'Enter', 'Tab', 'Escape' only for special keys. \n `;\n\n // Add variable names (not values) to the instruction if any\n if (variables && Object.keys(variables).length > 0) {\n const variableNames = Object.keys(variables)\n .map((key) => `%${key}%`)\n .join(\", \");\n const variablesPrompt = `The following variables are available to use in the action: ${variableNames}. Fill the argument variables with the variable name.`;\n instruction += ` ${variablesPrompt}`;\n }\n\n return instruction;\n}\n\nexport function buildOperatorSystemPrompt(goal: string): ChatMessage {\n return {\n role: \"system\",\n content: `You are a general-purpose agent whose job is to accomplish the user's goal across multiple model calls by running actions on the page.\n\nYou will be given a goal and a list of steps that have been taken so far. Your job is to determine if either the user's goal has been completed or if there are still steps that need to be taken.\n\n# Your current goal\n${goal}\n\n# CRITICAL: You MUST use the provided tools to take actions. Do not just describe what you want to do - actually call the appropriate tools.\n\n# Available tools and when to use them:\n- \\`act\\`: Use this to interact with the page (click, type, navigate, etc.)\n- \\`extract\\`: Use this to get information from the page\n- \\`goto\\`: Use this to navigate to a specific URL\n- \\`wait\\`: Use this to wait for a period of time\n- \\`navback\\`: Use this to go back to the previous page\n- \\`refresh\\`: Use this to refresh the current page\n- \\`close\\`: Use this ONLY when the task is complete or cannot be achieved\n- External tools: Use any additional tools (like search tools) as needed for your goal\n\n# Important guidelines\n1. ALWAYS use tools - never just provide text responses about what you plan to do\n2. Break down complex actions into individual atomic steps\n3. For \\`act\\` commands, use only one action at a time, such as:\n - Single click on a specific element\n - Type into a single input field\n - Select a single option\n4. Avoid combining multiple actions in one instruction\n5. If multiple actions are needed, they should be separate steps\n6. Only use \\`close\\` when the task is genuinely complete or impossible to achieve`,\n };\n}\n\nexport function buildCuaDefaultSystemPrompt(): string {\n return `You are a helpful assistant that can use a web browser.\\nDo not ask follow up questions, the user will trust your judgement. Today's date is ${new Date().toISOString().split(\"T\")[0]}.`;\n}\n\nexport function buildGoogleCUASystemPrompt(): ChatMessage {\n return {\n role: \"system\",\n content: `You are a general-purpose browser agent whose job is to accomplish the user's goal.\nToday's date is ${new Date().toISOString().split(\"T\")[0]}.\nYou have access to a search tool; however, in most cases you should operate within the page/url the user has provided. ONLY use the search tool if you're stuck or the task is impossible to complete within the current page.\nYou will be given a goal and a list of steps that have been taken so far. Avoid requesting the user for input as much as possible. Good luck!\n`,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"prompt.js","sourceRoot":"","sources":["../../../lib/prompt.ts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M;;;;iDAI/D,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC;;;;;;;;;;;;;;;;;;;;GAoBzE,CAAC;IAEF,WAAW,IAAI,uBAAuB,CAAC,SAAS,CAAC,CAAC;IAElD,OAAO,WAAW,CAAC;AACrB,CAAC;AAED,MAAM,UAAU,kBAAkB,CAChC,kBAA0B,EAC1B,cAAsB,EACtB,gBAA0B,EAC1B,SAAqB;IAErB,mBAAmB;IACnB,IAAI,WAAW,GAAG;kCACc,kBAAkB;0EACsB,cAAc;;;;;+CAKzC,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC;;;;;;GAMvE,CAAC;IAEF,WAAW,IAAI,uBAAuB,CAAC,SAAS,CAAC,CAAC;IAElD,OAAO,WAAW,CAAC;AACrB,CAAC;AAED,MAAM,UAAU,yBAAyB,CAAC,IAAY;IACpD,OAAO;QACL,IAAI,EAAE,QAAQ;QACd,OAAO,EAAE;;;;;EAKX,IAAI;;;;;;;;;;;;;;;;;;;;;;;mFAuB6E;KAChF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,2BAA2B;IACzC,OAAO,gJAAgJ,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;AACnM,CAAC;AAED,MAAM,UAAU,0BAA0B;IACxC,OAAO;QACL,IAAI,EAAE,QAAQ;QACd,OAAO,EAAE;kBACK,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;;;CAGvD;KACE,CAAC;AACJ,CAAC","sourcesContent":["import { ChatMessage } from \"./v3/llm/LLMClient.js\";\nimport type { Variables } from \"./v3/types/public/agent.js\";\nimport { getVariablePromptEntries } from \"./v3/agent/utils/variables.js\";\n\nexport function buildUserInstructionsString(\n userProvidedInstructions?: string,\n): string {\n if (!userProvidedInstructions) {\n return \"\";\n }\n\n return `\\n\\n# Custom Instructions Provided by the User\n \nPlease keep the user's instructions in mind when performing actions. If the user's instructions are not relevant to the current task, ignore them.\n\nUser Instructions:\n${userProvidedInstructions}`;\n}\n\n// extract\nexport function buildExtractSystemPrompt(\n isUsingPrintExtractedDataTool: boolean = false,\n userProvidedInstructions?: string,\n): ChatMessage {\n const baseContent = `You are extracting content on behalf of a user.\n If a user asks you to extract a 'list' of information, or 'all' information, \n YOU MUST EXTRACT ALL OF THE INFORMATION THAT THE USER REQUESTS.\n \n You will be given:\n1. An instruction\n2. `;\n\n const contentDetail = `A list of DOM elements to extract from.`;\n\n const instructions = `\nPrint the exact text from the DOM elements with all symbols, characters, and endlines as is.\nPrint null or an empty string if no new information is found.\n `.trim();\n\n const toolInstructions = isUsingPrintExtractedDataTool\n ? `\nONLY print the content using the print_extracted_data tool provided.\nONLY print the content using the print_extracted_data tool provided.\n `.trim()\n : \"\";\n\n const additionalInstructions =\n \"If a user is attempting to extract links or URLs, you MUST respond with ONLY the IDs of the link elements. \\n\" +\n \"Do not attempt to extract links directly from the text unless absolutely necessary. \";\n\n const userInstructions = buildUserInstructionsString(\n userProvidedInstructions,\n );\n\n const content =\n `${baseContent}${contentDetail}\\n\\n${instructions}\\n${toolInstructions}${\n additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\"\n }${userInstructions ? `\\n\\n${userInstructions}` : \"\"}`.replace(/\\s+/g, \" \");\n\n return {\n role: \"system\",\n content,\n };\n}\n\nexport function buildExtractUserPrompt(\n instruction: string,\n domElements: string,\n isUsingPrintExtractedDataTool: boolean = false,\n): ChatMessage {\n let content = `Instruction: ${instruction}\nDOM: ${domElements}`;\n\n if (isUsingPrintExtractedDataTool) {\n content += `\nONLY print the content using the print_extracted_data tool provided.\nONLY print the content using the print_extracted_data tool provided.`;\n }\n\n return {\n role: \"user\",\n content,\n };\n}\n\nconst metadataSystemPrompt = `You are an AI assistant tasked with evaluating the progress and completion status of an extraction task.\nAnalyze the extraction response and determine if the task is completed or if more information is needed.\nStrictly abide by the following criteria:\n1. Once the instruction has been satisfied by the current extraction response, ALWAYS set completion status to true and stop processing, regardless of remaining chunks.\n2. Only set completion status to false if BOTH of these conditions are true:\n - The instruction has not been satisfied yet\n - There are still chunks left to process (chunksTotal > chunksSeen)`;\n\nexport function buildMetadataSystemPrompt(): ChatMessage {\n return {\n role: \"system\",\n content: metadataSystemPrompt,\n };\n}\n\nexport function buildMetadataPrompt(\n instruction: string,\n extractionResponse: object,\n): ChatMessage {\n return {\n role: \"user\",\n content: `Instruction: ${instruction}\nExtracted content: ${JSON.stringify(extractionResponse, null, 2)}`,\n };\n}\n\n// observe\nexport function buildObserveSystemPrompt(\n userProvidedInstructions?: string,\n supportedActions?: string[],\n variables?: Variables,\n): ChatMessage {\n const actionsString = supportedActions?.length\n ? `\\n\\nSupported actions: ${supportedActions.join(\", \")}`\n : \"\";\n const variableEntries = getVariablePromptEntries(variables);\n const variablesString = variableEntries.length\n ? `\\n\\nAvailable variables: ${variableEntries\n .map(({ name, description }) => {\n return description ? `%${name}% (${description})` : `%${name}%`;\n })\n .join(\n \", \",\n )}. When an action needs a dynamic or sensitive value, return the matching %variableName% placeholder in the action arguments instead of a literal value`\n : \"\";\n\n const observeSystemPrompt = `\nYou are helping the user automate the browser by finding elements based on what the user wants to observe in the page.\n\nYou will be given:\n1. a instruction of elements to observe\n2. a hierarchical accessibility tree showing the semantic structure of the page. The tree is a hybrid of the DOM and the accessibility tree.\n\nReturn an array of elements that match the instruction if they exist, otherwise return an empty array.\nWhen returning elements, include the appropriate method from the supported actions list.${actionsString}${variablesString}. When choosing non-left click actions, provide right or middle as the argument.`;\n const content = observeSystemPrompt.replace(/\\s+/g, \" \");\n\n return {\n role: \"system\",\n content: [content, buildUserInstructionsString(userProvidedInstructions)]\n .filter(Boolean)\n .join(\"\\n\\n\"),\n };\n}\n\nexport function buildObserveUserMessage(\n instruction: string,\n domElements: string,\n): ChatMessage {\n return {\n role: \"user\",\n content: `instruction: ${instruction}\nAccessibility Tree: \\n${domElements}\\n`,\n };\n}\n\nexport function buildActSystemPrompt(\n userProvidedInstructions?: string,\n): ChatMessage {\n const actSystemPrompt = `\nYou are helping the user automate the browser by finding elements based on what action the user wants to take on the page\n\nYou will be given:\n1. a user defined instruction about what action to take\n2. a hierarchical accessibility tree showing the semantic structure of the page. The tree is a hybrid of the DOM and the accessibility tree.\n\nReturn the element that matches the instruction if it exists. Otherwise, return an empty object.`;\n const content = actSystemPrompt.replace(/\\s+/g, \" \");\n\n return {\n role: \"system\",\n content: [content, buildUserInstructionsString(userProvidedInstructions)]\n .filter(Boolean)\n .join(\"\\n\\n\"),\n };\n}\n\nfunction buildActVariablesPrompt(variables?: Variables): string {\n if (!variables || Object.keys(variables).length === 0) {\n return \"\";\n }\n\n const variableNames = Object.keys(variables)\n .map((key) => `%${key}%`)\n .join(\", \");\n\n return ` The user has provided the following variables to be used in the action: ${variableNames} \\n\n Note that these are the variable names/keys, and not the actual variable values. \\n\n To use the variables in the action, you must respond with the variable name inside the 'arguments' array. The variable name must be wrapped in percentage signs (eg, %variableNameHere%) so that it can be replaced with the actual variable value before the action is taken. \\n`;\n}\n\nexport function buildActPrompt(\n action: string,\n supportedActions: string[],\n variables?: Variables,\n): string {\n // Base instruction\n let instruction = `Find the most relevant element to perform an action on given the following action: ${action}. \n IF AND ONLY IF the action EXPLICITLY includes the word 'dropdown' and implies choosing/selecting an option from a dropdown, ignore the 'General Instructions' section, and follow the 'Dropdown Specific Instructions' section carefully.\n \n General Instructions: \n Provide an action for this element such as ${supportedActions.join(\", \")}. Remember that to users, buttons and links look the same in most cases.\n When choosing non-left click actions, provide right or middle as the argument\n If the action is completely unrelated to a potential action to be taken on the page, return an empty object. \n ONLY return one action. If multiple actions are relevant, return the most relevant one. \n If the user is asking to scroll to a position on the page, e.g., 'halfway' or 0.75, etc, you must return the argument formatted as the correct percentage, e.g., '50%' or '75%', etc.\n If the user is asking to scroll to the next chunk/previous chunk, choose the nextChunk/prevChunk method. No arguments are required here.\n If the action implies a key press, e.g., 'press enter', 'press a', 'press space', etc., always choose the press method with the appropriate key as argument — e.g. 'a', 'Enter', 'Space'. Do not choose a click action on an on-screen keyboard. Capitalize the first character like 'Enter', 'Tab', 'Escape' only for special keys. \n \n Dropdown Specific Instructions:\n For interacting with dropdowns, there are two specific cases that you need to handle. \n \n CASE 1: the element is a 'select' element. \n - choose the selectOptionFromDropdown method,\n - set the argument to the exact text of the option that should be selected,\n - set twoStep to false.\n CASE 2: the element is NOT a 'select' element:\n - do not attempt to directly choose the element from the dropdown. You will need to click to expand the dropdown first. You will achieve this by following these instructions:\n - choose the node that most closely corresponds to the given instruction EVEN if it is a 'StaticText' element, or otherwise does not appear to be interactable. \n - choose the 'click' method\n - set twoStep to true.\n `;\n\n instruction += buildActVariablesPrompt(variables);\n\n return instruction;\n}\n\nexport function buildStepTwoPrompt(\n originalUserAction: string,\n previousAction: string,\n supportedActions: string[],\n variables?: Variables,\n): string {\n // Base instruction\n let instruction = `\n The original user action was: ${originalUserAction}.\n You have just taken the following action which completed step 1 of 2: ${previousAction}.\n \n Now, you must find the most relevant element to perform an action on in order to complete step 2 of 2. \n \n General Instructions: \n Provide an action for this element such as ${supportedActions.join(\", \")}. Remember that to users, buttons and links look the same in most cases.\n If the action is completely unrelated to a potential action to be taken on the page, return an empty object. \n ONLY return one action. If multiple actions are relevant, return the most relevant one. \n If the user is asking to scroll to a position on the page, e.g., 'halfway' or 0.75, etc, you must return the argument formatted as the correct percentage, e.g., '50%' or '75%', etc.\n If the user is asking to scroll to the next chunk/previous chunk, choose the nextChunk/prevChunk method. No arguments are required here.\n If the action implies a key press, e.g., 'press enter', 'press a', 'press space', etc., always choose the press method with the appropriate key as argument — e.g. 'a', 'Enter', 'Space'. Do not choose a click action on an on-screen keyboard. Capitalize the first character like 'Enter', 'Tab', 'Escape' only for special keys. \n `;\n\n instruction += buildActVariablesPrompt(variables);\n\n return instruction;\n}\n\nexport function buildOperatorSystemPrompt(goal: string): ChatMessage {\n return {\n role: \"system\",\n content: `You are a general-purpose agent whose job is to accomplish the user's goal across multiple model calls by running actions on the page.\n\nYou will be given a goal and a list of steps that have been taken so far. Your job is to determine if either the user's goal has been completed or if there are still steps that need to be taken.\n\n# Your current goal\n${goal}\n\n# CRITICAL: You MUST use the provided tools to take actions. Do not just describe what you want to do - actually call the appropriate tools.\n\n# Available tools and when to use them:\n- \\`act\\`: Use this to interact with the page (click, type, navigate, etc.)\n- \\`extract\\`: Use this to get information from the page\n- \\`goto\\`: Use this to navigate to a specific URL\n- \\`wait\\`: Use this to wait for a period of time\n- \\`navback\\`: Use this to go back to the previous page\n- \\`refresh\\`: Use this to refresh the current page\n- \\`close\\`: Use this ONLY when the task is complete or cannot be achieved\n- External tools: Use any additional tools (like search tools) as needed for your goal\n\n# Important guidelines\n1. ALWAYS use tools - never just provide text responses about what you plan to do\n2. Break down complex actions into individual atomic steps\n3. For \\`act\\` commands, use only one action at a time, such as:\n - Single click on a specific element\n - Type into a single input field\n - Select a single option\n4. Avoid combining multiple actions in one instruction\n5. If multiple actions are needed, they should be separate steps\n6. Only use \\`close\\` when the task is genuinely complete or impossible to achieve`,\n };\n}\n\nexport function buildCuaDefaultSystemPrompt(): string {\n return `You are a helpful assistant that can use a web browser.\\nDo not ask follow up questions, the user will trust your judgement. Today's date is ${new Date().toISOString().split(\"T\")[0]}.`;\n}\n\nexport function buildGoogleCUASystemPrompt(): ChatMessage {\n return {\n role: \"system\",\n content: `You are a general-purpose browser agent whose job is to accomplish the user's goal.\nToday's date is ${new Date().toISOString().split(\"T\")[0]}.\nYou have access to a search tool; however, in most cases you should operate within the page/url the user has provided. ONLY use the search tool if you're stuck or the task is impossible to complete within the current page.\nYou will be given a goal and a list of steps that have been taken so far. Avoid requesting the user for input as much as possible. Good luck!\n`,\n };\n}\n"]}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import type { EasyInputMessage } from "openai/resources/responses/responses";
|
|
1
2
|
import { LogLine } from "../types/public/logs.js";
|
|
2
3
|
import { AgentAction, AgentResult, AgentType, AgentExecutionOptions, ResponseInputItem, ResponseItem, SafetyConfirmationHandler } from "../types/public/agent.js";
|
|
3
4
|
import { ClientOptions } from "../types/public/model.js";
|
|
4
5
|
import { AgentClient } from "./AgentClient.js";
|
|
5
6
|
import { ToolSet } from "ai";
|
|
7
|
+
type OpenAIRequestInputItem = ResponseInputItem | EasyInputMessage;
|
|
6
8
|
export declare class OpenAICUAClient extends AgentClient {
|
|
7
9
|
private pendingContextNotes;
|
|
8
10
|
private captchaSolvedToolActive;
|
|
@@ -37,7 +39,7 @@ export declare class OpenAICUAClient extends AgentClient {
|
|
|
37
39
|
* Execute a single step of the agent
|
|
38
40
|
* This coordinates the flow: Request → Get Action → Execute Action
|
|
39
41
|
*/
|
|
40
|
-
executeStep(inputItems:
|
|
42
|
+
executeStep(inputItems: OpenAIRequestInputItem[], previousResponseId: string | undefined, logger: (message: LogLine) => void): Promise<{
|
|
41
43
|
actions: AgentAction[];
|
|
42
44
|
message: string;
|
|
43
45
|
completed: boolean;
|
|
@@ -53,7 +55,7 @@ export declare class OpenAICUAClient extends AgentClient {
|
|
|
53
55
|
private handleSafetyConfirmation;
|
|
54
56
|
private isFunctionCallItem;
|
|
55
57
|
private createInitialInputItems;
|
|
56
|
-
getAction(inputItems:
|
|
58
|
+
getAction(inputItems: OpenAIRequestInputItem[], previousResponseId?: string): Promise<{
|
|
57
59
|
output: ResponseItem[];
|
|
58
60
|
responseId: string;
|
|
59
61
|
usage: Record<string, number>;
|
|
@@ -61,9 +63,11 @@ export declare class OpenAICUAClient extends AgentClient {
|
|
|
61
63
|
takeAction(output: ResponseItem[], logger: (message: LogLine) => void): Promise<ResponseInputItem[]>;
|
|
62
64
|
private convertComputerCallToAction;
|
|
63
65
|
private drainContextNotes;
|
|
66
|
+
private captureInitialScreenshot;
|
|
64
67
|
private convertFunctionCallToAction;
|
|
65
68
|
captureScreenshot(options?: {
|
|
66
69
|
base64Image?: string;
|
|
67
70
|
currentUrl?: string;
|
|
68
71
|
}): Promise<string>;
|
|
69
72
|
}
|
|
73
|
+
export {};
|
|
@@ -91,7 +91,7 @@ export class OpenAICUAClient extends AgentClient {
|
|
|
91
91
|
let finalMessage = "";
|
|
92
92
|
this.reasoningItems.clear(); // Clear any previous reasoning items
|
|
93
93
|
// Start with the initial instruction
|
|
94
|
-
let inputItems = this.createInitialInputItems(instruction);
|
|
94
|
+
let inputItems = await this.createInitialInputItems(instruction);
|
|
95
95
|
let previousResponseId = undefined;
|
|
96
96
|
let totalInputTokens = 0;
|
|
97
97
|
let totalOutputTokens = 0;
|
|
@@ -324,18 +324,37 @@ export class OpenAICUAClient extends AgentClient {
|
|
|
324
324
|
"name" in item &&
|
|
325
325
|
"arguments" in item);
|
|
326
326
|
}
|
|
327
|
-
createInitialInputItems(instruction) {
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
{
|
|
327
|
+
async createInitialInputItems(instruction) {
|
|
328
|
+
const inputItems = [];
|
|
329
|
+
if (this.userProvidedInstructions) {
|
|
330
|
+
const systemMessage = {
|
|
331
331
|
role: "system",
|
|
332
332
|
content: this.userProvidedInstructions,
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
333
|
+
};
|
|
334
|
+
inputItems.push(systemMessage);
|
|
335
|
+
}
|
|
336
|
+
const textInput = {
|
|
337
|
+
type: "input_text",
|
|
338
|
+
text: instruction,
|
|
339
|
+
};
|
|
340
|
+
const userContent = [
|
|
341
|
+
textInput,
|
|
338
342
|
];
|
|
343
|
+
const initialScreenshot = await this.captureInitialScreenshot();
|
|
344
|
+
if (initialScreenshot) {
|
|
345
|
+
const screenshotInput = {
|
|
346
|
+
type: "input_image",
|
|
347
|
+
image_url: initialScreenshot,
|
|
348
|
+
detail: "high",
|
|
349
|
+
};
|
|
350
|
+
userContent.push(screenshotInput);
|
|
351
|
+
}
|
|
352
|
+
const userMessage = {
|
|
353
|
+
role: "user",
|
|
354
|
+
content: userContent,
|
|
355
|
+
};
|
|
356
|
+
inputItems.push(userMessage);
|
|
357
|
+
return inputItems;
|
|
339
358
|
}
|
|
340
359
|
async getAction(inputItems, previousResponseId) {
|
|
341
360
|
try {
|
|
@@ -638,6 +657,17 @@ export class OpenAICUAClient extends AgentClient {
|
|
|
638
657
|
this.pendingContextNotes = [];
|
|
639
658
|
return notes;
|
|
640
659
|
}
|
|
660
|
+
async captureInitialScreenshot() {
|
|
661
|
+
if (!this.screenshotProvider) {
|
|
662
|
+
return undefined;
|
|
663
|
+
}
|
|
664
|
+
try {
|
|
665
|
+
return await this.captureScreenshot();
|
|
666
|
+
}
|
|
667
|
+
catch {
|
|
668
|
+
return undefined;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
641
671
|
convertFunctionCallToAction(call) {
|
|
642
672
|
try {
|
|
643
673
|
const args = JSON.parse(call.arguments);
|